On Sat, 6 Aug 2010, Jim Green wrote:
> I used to count one by one which field I am on in order to use awk to
> print this field. do we have a quick way to do this in vim?
The functions I just wrote in the attached script might be helpful.
To install, place it in your ~/.vim/autoload/ directory as
AwkFields.vim. Then these functions are available:
AwkFields#Get() -- returns the current field number: e.g. '4'
-- if on the separator, returns prior-next: e.g. '4-5'
AwkFields#GetVar() -- returns the variable-style field number: e.g. '$4'
-- if on the separator, returns empty string: e.g. ''
AwkFields#StatusLine() -- sets up the status line to display the awk
field variable, 'ruler'-style. (See :help 'stl' for what I used as the
basis.)
Get() and GetVar() can accept an optional parameter listing the field
separator. Default is to use the global variable 'g:awksplit'. If
neither of those exists, default is ' ', which uses the same semantics
as awk (AFAIK -- I'm a perler) i.e. leading spaces are trimmed, and
multiple spaces only count as one separator. If the field separator is
'', it splits on characters.
Example statusline that shows it in use:
set stl=%f\ %-5.(%{AwkFields#GetVar()}%)
Use:
:call AwkFields#StatusLine()
for a much better version.
--
Best,
Ben
--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php
fun! AwkFields#Get(...)
let linesofar = strpart(getline('.'), 0, col('.'))
let fieldsep = a:0 ? a:1 : exists('g:awksplit') ? g:awksplit : ' '
if fieldsep == ' '
let fieldsep = '\s\+'
let keep = 0
let partial = 1
elseif len(fieldsep)
let fieldsep = '\V'.escape(fieldsep, '\')
let keep = 1
let partial = 1
else
let fieldsep = '\zs'
let keep = 0
let partial = 0
endif
let parts = split(linesofar, fieldsep, keep)
let field = len(parts)
if partial && match(strpart(getline('.'), col('.')-1, 1), fieldsep) == 0
if keep | let field -= 1 | endif
let field .= '-'.(field+1)
endif
return field
endfun
fun! AwkFields#GetVar(...)
let f = a:0 ? AwkFields#Get(a:1) : AwkFields#Get()
if match(f, '-') != -1 || !f
return ''
endif
return '$'.f
endfun
fun! AwkFields#StatusLine()
let &stl='%<%f %h%m%r%=%-5.(%{AwkFields#GetVar()}%)'.(&ruler ?
'%-14.(%l,%c%V%) %P' : '')
endfun