6

Is there a way to select a text block (e.g. a first word "TODO:") programmatically (with some commands or functions from a script)? Not simply highlight, like with a search, but visually select like with mouse?

  • Are you asking how to enter visual mode and select a search pattern? – jecxjo Apr 14 '15 at 19:16
  • Yes. Only not manually, but from a script. – Al Berger Apr 14 '15 at 19:51
6

If you are looking to visually select a search pattern you can do it using two commands. For example searching for "TODO...." lines:

/^TODO.*$/s
v//e

This will search your your pattern and then visually select to the end of it.

If you want to move this to a function and then be able to call it in a single action:

function! VisualSelectSearch (query)
  execute "normal /".a:query."/s\<CR>v//e\<CR>"
endfunction

command! -nargs=+ VSS call VisualSelectSearch(<q-args>)

Now you can type :VSS ^TODO.*$ and visually select the next instance. If you want to call the function directly in a script use VisualSelectSearch("^TODO.*$").

  • I needed to select text in autocommand, and this code works. Thanks! – Al Berger Apr 14 '15 at 20:13
2

Any sequence of key presses can be represented in vimscript with the :normal command. For instance, to visually select the next occurrence of "TODO:" you might normally hit the following keys:

/TODO:<CR>        jump to the next occurence of TODO:
v                 start a visual selection (on the T)
f:                jump to the next ':'

To simulate these key presses in vimscript, you'd want to write something like:

normal! /TODO:<CR>vf:

However, typing <CR> will literally type < C R > instead of enter. To get around this, we have to wrap this in an execute command:

execute "normal! /TODO:\<CR>vf:"

I recommend reading :help normal and Learn Vimscript the Hard Way for more information.

  • Unfortunately this code doesn't work from autocommand. But the variant from the previous answer does. Can't tell for sure why. – Al Berger Apr 14 '15 at 20:11
  • Whoops, forgot to escape <CR>. My solution is now virtually the same as jecxjo 's, except the function/command and slightly different interpretation of the problem. I'll leave it here as we described things slightly differently. – Matt Boehm Apr 14 '15 at 20:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.