I have a function to count and return the number of matches of some text:
function! count_matches()
redir => matches_cnt
silent! %s/\[\d*\]//gn
redir END
return split(matches_cnt)[0]
endfunction
I created a map to insert the return value of count_matches() at the current position:
noremap <C-A> Go[foo<C-R>=count_matches()<CR>]
However the cursor jumps to the beginning of the line after executing the silent %s/[\d*]//gn command. So when I press control+a vim inserts "[foo", then the function is being executed, the search command resets the cursor position and the return value is inserted at the beginning of the line resulting in "1][foo" instead of "[foo1]".
Can I somehow prevent count from changing the cursor position, or reset the cursor position after counting the matches?
The script also leads to an error, if the pattern is not found. How can I get the function to return 1 without an error for zero matches?
Even better then just to save the cursor position, is to save the complete viewport. (But that only works, if you do not change the window layout)
See :help winsaveview()
let wsv = winsaveview()
MoveTheCursorAround
call winrestview(wsv)
In your particular case, I would take another approach:
inoremap <expr> <f3> len(split(join(getline(1,'$'),"\n"), '\[\d\+\]',1))
Which takes the whole text, and splits it on the pattern \[\d\+\] and then counts how many elements there are. Or if you like to add some text:
inoremap <expr> <f3> '['.len(split(join(getline(1,'$'),"\n"), '\[\d\+\]',1)).']'
This will add the [ in front and ] after the number. Adjust the mapping key and text to your personal taste. (Note, you do not need the winsaveview() function, cause the cursor won't move).
It is perhaps not such a good idea to use that function on a multi MB text size. ;)
This is the same function, reworked to return 1 when there's no match:
function! count_matches()
redir => matches_cnt
try
silent! %s/\[\d*\]//gn
catch
echo 1
endtry
redir END
return split(matches_cnt)[0]
endfunction
See :help getpos()
let save_cursor = getpos(".")
MoveTheCursorAround
call setpos('.', save_cursor)
My solution:
function! CountWithCursorKeep(...)
let currentCursor = getcurpos()
let pattern = expand('<cword>')
if a:0 > 0 | let pattern = a:1 | endif
execute(':%s#' . pattern . '##gn')
call setpos('.', currentCursor)
endfunction
nmap ,ns :call CountWithCursorKeep(<C-R>/)<cr>
nmap ,nw :call CountWithCursorKeep(expand('<cword>'))<cr>
nmap ,nW :call CountWithCursorKeep(expand('<cWORD>'))<cr>
command! -nargs=? -bar -complete=tag CountMatch call CountWithCursorKeep(<f-args>)
You can use :CountMatch pattern to get how many times pattern occurs in current file.
Related
I am trying to make a function in vimscript that will activate on every cursor movement in visual mode, i.e. it will automatically highlight all the matches of the current visual selection.
The mapping from https://vi.stackexchange.com/questions/20077/automatically-highlight-all-occurrences-of-the-selected-text-in-visual-mode:
xnoremap <silent> <cr> "*y:silent! let searchTerm = '\V'.substitute(escape(#*, '\/'), "\n", '\\n', "g") <bar> let #/ = searchTerm <bar> echo '/'.#/ <bar> call histadd("search", searchTerm) <bar> set hls<cr>
works perfectly for me but I am failing to implement it into function. This is what I tried:
function! HighlightVisual(mode)
if mode()=~#"^[vV\<C-v>]"
call feedkeys('"*y')
let searchTerm = '\V'.substitute(escape(#*, '\/'), "\n", '\\n', "g")
let #/ = searchTerm
echo '/'.#/
call histadd("search", searchTerm)
set hls
endif
endfunction
autocmd CursorMoved * call HighlightVisual(mode())
However, it is not working.
What am I doing wrong? I think the function is terminated each time a call is invoked but have no idea how to workaround that.
I have made it work. Firstly, I found from https://vi.stackexchange.com/questions/28404/vim-does-not-call-functions-correctly-when-wrapped-in-another-function that "Vim doesn't like updating Screen too often" so redraw was necessary after set hls. And secondly, y was forcing normal mode and gv was moving cursor triggering the autocmd CursorMoved inside the function thus making an infinite loop. I made a workaround by set eventignore=CursorMoved and resetting it back at the end of function. I am saving selected word to register h (as in highlight) but you can choose any by changing "hy and #h. Moreover, I added highlight toggle when not needed. So, if somebody wants to use the feature of automatically highlighting visual matches, here is the code:
function! HighlightVisual(mode)
if mode()=~#"^[vV\<C-v>]"
set eventignore=CursorMoved
normal "hy
normal gv
let searchTerm = '\V'.substitute(escape(#h, '\/'), "\n", '\\n', "g")
let #/ = searchTerm
call histadd("search", searchTerm)
set hls
redraw
set eventignore=""
endif
endfunction
autocmd CursorMoved * :call HighlightVisual(mode())
vnoremap <silent> <ESC> :<C-u>set nohlsearch<CR>
; just copy-paste it in your .vimrc/init.vim.
Big thanks to trusktr as I used his answer in https://vi.stackexchange.com/questions/20077/automatically-highlight-all-occurrences-of-the-selected-text-in-visual-mode to build my function I wanted for sooo long.
Happy coding!
I am using a VIM plugin called Goyo (for writing markdown files). It is similar to Distraction Free mode in SublimeText. I want to create a write-mode in my .vimrc that I can toggle. This toggle will set various options on in write-mode, such as set spell, set wrap etc.
I have everything working here, except calling the Goyo function. How can I execute the Goyo plugin from within my ToggleWrite() function?
Here is my code:
" Write toggle switch
let b:write = "no"
function! ToggleWrite()
if exists("b:write") && b:write == "yes"
let b:write = "no"
set nowrap
set nolinebreak
set textwidth=100
set wrapmargin=0
set nospell
" ↓↓↓ I want to call this ↓↓↓
":Goyo
else
let b:write = "yes"
set wrap
set linebreak
set textwidth=100
set wrapmargin=0
set spell
" ↓↓↓ I want to call this ↓↓↓
":Goyo 60x100%
endif
endfunction
" Set up the toggle sequence
nmap <expr> ,w ToggleWrite()
I put my comment as an answer:
Your mapping uses <expr>, which is not right in your case. You should try this mapping instead:
nmap ,w :call ToggleWrite()<cr>
or
nmap <silent> ,w :call ToggleWrite()<cr>
<expr> lets you make "custom" mappings, depending on the return of a function. It's rarely used in common cases.
I want to execute the command "yiw:s/\<<C-r>"\>/<C-r>"/g<Left><Left>" by key sequence.
So I make a mapping
nnoremap <F7> yiw:s/\<<C-r>"\>/<C-r>"/g<Left><Left>
This mapping copy the word under cursor, then the string :s/\<">/"/g" (where " are substituted by the copied word) appears in the command line and the cursor in the command line is at the end of replacement statement.
I also want to save cursor position before this command and restore after.
function! SafeCommand(cmd)
let line = line('.')
let col = col('.')
// execute cmd here
call cursor( line, col )
endfunction
How to do that?
Normally, you'd just put the entire (complex) command in a function, and invoke that function from the :nnoremap. But that doesn't work for incomplete commands, like the template :substitute that your mapping represents. For that, you need to include the save / restore parts into the command-line (though that's ugly):
:fun! Save()
let s:line = line('.')
let s:col = col('.')
:endfun
:fun! Restore()
call cursor( s:line, s:col )
:endfun
:nnoremap <F7> yiw:call Save()<Bar>s/\<<C-r>"\>/<C-r>"/g<Bar>call Restore()<Left><Left><Left><Left><Left><Left><Left><Left><Left><Left><Left><Left><Left><Left><Left><Left>
I've been trying to write a bit of Vimscript to call a function when I insert the same character twice, in my particular case I wanted that if you inserted semi colon twice for it to actually move the semi colon to the end of the line.
command! Semi call Semi()
inoremap ; <C-O>:Semi2<CR>
function! Semi()
let x = getpos(".")
" If we are in the last column..
if col(".")+1 == col("$")
let insert_semi = getline(".") . ";"
call setline(".", insert_semi)
let x[2] += 1
call setpos(".", x)
return
endif
let char = getline(".")[x[2] - 2]
if char == ";"
" if prev char was a semicolon also, remove and append to the end
else
" insert semicolon normally...
endif
endfunction
The problem I am having is when calling this function on the last column, you have to exit insert mode to call this function the cursor will go into normal mode and move the cursor to the last column. Is there any way to tell whether the cursor was appending to the end of the line or inserting before the last column and when function call is finished return it to the same position?
I am well aware that I could use an insert mapping on ;; however I dislike this behaviour, where Vim goes into a waiting for next key mode and does not display what you have written. This issue is not only to do with my problem listed but a more general problem which also occurs in the first column.
If your function does not use insert mode to append the ';' -- e.g. by pasting from a buffer -- you can use the gicommand to return to the place, where you exited insert mode.
I would advise against using i_CTRL-O, it triggers InsertLeave and InsertEnter events, which may affect other plugins. I would use :inoremap <expr> ; here. See :help :map-expr. Inside that expression (i.e. your function), record the current cursor position and compare it with the last recorded one. If it's next to it, return the keys to undo the inserts and redo at the end (<BS><BS><End>;), else just return ;.
You don't need a function for that:
inoremap ;; ;;<Esc>h"_xxm`$p``a
or cleaner:
inoremap ;; <Esc>m`A;<Esc>``a
I am trying to modify this terrific VIM script however both the original and my modified version have a maddening bug in which sometimes the cursor is shown in the wrong place. The simplest example that I could make is the 71 line text file below. Note that whitespace is important when copying the file.
<?php
/**
* Some silly method
*
* #param string Some silly string
*/
function someFunction()
{
global $class, $cv, $go, $pae;
global $messages, $counters, $ltn;
global $sh, $sub, $temp;
$charsets = array(
'us',
'si',
'pr',
'op',
'co',
'pa',
'av',
'pr',
'al',
'pc',
'pe',
'pi',
'pp',
'su',
'qu',
'de',
'ze',
'xo',
'mo',
'wo',
'de',
'mo',
'de',
'mo',
'dr',
'mo',
'de',
'mo',
'ev',
'pa',
'so',
'ms',
'bu',
'at',
'cu',
'pr',
'de',
'mo',
'nv',
'nl',
'nf',
'ne',
'nq',
'nt'
);
}
This is the relevant .vimrc file with the function:
set cul
hi CursorLine term=none cterm=none ctermbg=20
set nu
set statusline+=%{WhatFunctionAreWeIn()}
set laststatus=2
fun WhatFunctionAreWeIn()
let strList = ["while", "foreach", "ifelse", "if else", "for", "if", "else", "try", "catch", "case"]
let foundcontrol = 1
let position = ""
normal mz
while (foundcontrol)
let foundcontrol = 0
" The idea here is to go back to non-whitespace character before
" the last hanging open { and to check if it is a close paran.
" If so, then go to the matching open paren and search for the
" preceding it.
" If not, then go ahead and check the keyword right there.
normal [{
?\S
let tempchar = getline(".")[col(".") - 1]
if (match(tempchar, ")") >=0 )
normal %
?\S
endif
let tempstring = getline(".")
for item in strList
if( match(tempstring,item) >= 0 )
let position = item . " - " . position
let foundcontrol = 1
break
endif
endfor
if(foundcontrol == 0)
normal `z
return tempstring.position
endif
endwhile
normal `z
return tempstring.position
endfun
Starting from the beginning of the file, press j repeatedly until you get to line 63. Note that the highlighted cursorline stays on the correct line (63) but the cursor is shown on line 55. Jumping directly to line 63 won't trigger the bug, only pressing j repeatedly until you get to that line will.
Why does that happen, and how can I fix it? Note that when the cursor appears to be in the wrong place, pressing ``z` does in fact snap the cursor to the correct location. This is on VIM 7.3.154 on Kubuntu 11.10.
EDIT:
I notice by testing in other installs (Debian, CentOS) that the bug is not determinate, it happens occasionally but not in the same place on every system! You can test this code by pressing j and paying attention to the cursor location in whatever PHP files that you might have strung about. I would say that about one line out of every hundred lines triggers the bug in which the cursor appears to be in the wrong place.
I'm slightly confused by the logic of this function, but I suspect it is the ?\S which is causing the problems. It is searching backwards for a non-whitespace character, and wrapping around to the bottom of the file once it has reached the top.
Try replacing both occurrences of ?\S with
call search('\S','bW')
(Here the b flag searches backwards, and W prevents wrapping around the file.)
EDIT (2nd attempt)
The function also causes lots of jumping around of the view. The root of this is continually setting the mark mz and jumping to and fro. A better approach in vimscripts is to use the following commands to save the current view (instead of normal mz):
let pos=getpos(".") " This saves the cursor position
let view=winsaveview() " This saves the window view
You can then use these to restore the view:
call cursor(pos) " This restores the cursor position to that of "pos"
call winrestview(view) " This restores the window view to that of "view"
So I would use call cursor(pos) instead of `z and call winrestview(view) just before the return commands. This ensures that the function doesn't modify the appearance of the window, and makes for more pleasant usage.
Hope this helps!