function - vim keep cursor position when counting matches -
i have function count , homecoming number of matches of text:
function! count_matches() redir => matches_cnt silent! %s/\[\d*\]//gn redir end homecoming split(matches_cnt)[0] endfunction
i created map insert homecoming value of count_matches() @ current position:
noremap <c-a> go[foo<c-r>=count_matches()<cr>]
however cursor jumps origin of line after executing silent %s/[\d*]//gn command. when press control+a vim inserts "[foo", function beingness executed, search command resets cursor position , homecoming value inserted @ origin of line resulting in "1][foo" instead of "[foo1]".
can somehow prevent count changing cursor position, or reset cursor position after counting matches?
the script leads error, if pattern not found. how can function homecoming 1 without error 0 matches?
even improve save cursor position, save finish viewport. (but works, if not alter window layout)
see :help winsaveview()
let wsv = winsaveview() movethecursoraround phone call winrestview(wsv)
in particular case, take approach:
inoremap <expr> <f3> len(split(join(getline(1,'$'),"\n"), '\[\d\+\]',1))
which takes whole text, , splits on pattern \[\d\+\]
, counts how many elements there are. or if add together text:
inoremap <expr> <f3> '['.len(split(join(getline(1,'$'),"\n"), '\[\d\+\]',1)).']'
this add together [
in front end , ]
after number. adjust mapping key , text personal taste. (note, not need winsaveview()
function, cause cursor won't move).
it perhaps not such thought utilize function on multi mb text size. ;)
function vim
No comments:
Post a Comment