Get the current line in visual mode from a function - vim

I have a simple vim script that takes a visual block of text and stores it as a list. The problem with the function VtoList() is that it executes after the cursor returns to the start of the visual block, not before it. Because of this, I have no way of getting the line where the visual block ends.
nn <F2> :call VtoList()<CR>
func! VtoList()
firstline = line('v') " Gets the line where the visual block begins
lastline = line('.') " Gets the current line, but not the one I want.
mylist = getline(firstline, lastline)
echo mylist
endfunc
The problem is with line('.'). It should return the current line of the cursor, but before the function is called, the cursor has already returned to the start of the visual block. Thus, I'm only getting a single line instead of a range of lines.
I put together a solution that sets a mark everytime the user hits V and sets another mark before the function is called.
nnoremap V mV
nnoremap <F2> mZ:call VtoList()<CR>
The function works fine if I substitute line('v') and line('.') with line("'V") and line("'Z"), but I want to avoid this solution if I can because it could conflict with a user's mappings.
Is there a way I can get current line of a visual block within a function before the cursor has returned to the start of the visual block?

Don't use :, use <expr>:
function! s:NumSort(a, b)
return a:a>a:b ? 1 : a:a==a:b ? 0 : -1
endfunction
func! VtoList()
let [firstline, lastline]=sort([line('v'), line('.')], 's:NumSort')
let mylist = getline(firstline, lastline)
echo mylist
return ""
endfunc
vnoremap <expr> <F2> VtoList()
Note other changes: let (you forgot it), sort (line where selection starts may be after the line where selection ends), vnoremap (line("v") works only in visual mode), return (expr mappings return value is executed, but you don't need it, you need only side effects). You can replace the second line with
if mode()=~#"^[vV\<C-v>]"
let [firstline, lastline]=sort([line('v'), line('.')], 's:NumSort')
else
let [firstline, lastline]=sort([line("'<"), line("'>")], 's:NumSort')
endif
The reason why your solution is not working is that when : occurs in the mapping, you immediately exit visual mode and enter command mode. line("v") works only in visual mode.
Other note: vnoremap {lhs} : will produce command line already filled with '<,'>. You may have added range to the function definition and use let [firstline, lastline]=sort([a:firstline, a:lastline], 's:NumSort'). But you nevertheless will exit visual mode with :.

Related

Check if a selection exists in vimscript

I want to write a function in vimscript that echoes the selected text or, if no text is selected, the entire buffer.
How can I distinguish between these two cases?
Define two mappings, an :nmap using the entire buffer, and a :vmap for the selected text. Both can invoke the same function, passing an isVisual boolean flag or a mode argument.
Anything else (custom commands, direct function :call) would require an explicit hint, because in order to invoke them, visual mode as already been left (for command-line mode). You also cannot use the '<,'> marks for the detection, because they will keep the last selection even after it has been removed.
I write a function to get visually selected text.
I hope it can help you.
function! GetSelected()
" save reg
let reg = '"'
let reg_save = getreg(reg)
let reg_type = getregtype(reg)
" yank visually selected text
silent exe 'norm! gv"'.reg.'y'
let value = getreg(reg)
" restore reg
call setreg(reg,reg_save,reg_type)
return value
endfun
" viusal map
vnoremap gs :<C-U>echo GetSelected()<CR>
" normal map
nnoremap gs :<C-U>echo join(getline(1, '$'), "\n")<CR>

Vim copy and paste line with a search and replace

Say I've written code that references the x dimension. What is the best way to get vim to duplicate a line of code replacing all references to x to y and to z (best being the most clear method).
Input:
length_x = X_vec.dot(X_vec)**.5
Desired Output:
length_x = X_vec.dot(X_vec)**.5
length_y = Y_vec.dot(Y_vec)**.5
length_z = Z_vec.dot(Z_vec)**.5
Here's my best so far.
function SwitchXtoYZ()
:normal yy
:normal p
:normal! V
:s/X/Y/ge
:normal! V
:s/x/y/ge
:normal p
:normal! V
:s/X/Z/ge
:normal! V
:s/x/z/ge
endfunction
command XtoYZ exec SwitchXtoYZ() | :normal `.
It works, but I feel this is not very vim-y. Bonus points if the cursor returns to where it was before the command XtoYZ was issued (it currently goes the beginning of the second inserted line).
You don't need a function to do that, a macro would be fine for your requirement. Also you can define a macro in your vimrc too, if you like, so that you can have it everytime you open vim.
here is the macro:
qqv<Esc>Y2p:s/x/y/gi<Enter>n:s//z/gi<Enter>`<q
so it was recorded and saved in register q, you can #q to replay it.
explain it a little:
qq " start recording into q
v<esc> " enter visual mode and exit. to let `< work
Y2p " yank current line and paste twice below
:s/x/y/gi<Enter> " x->y sub, case insensitive
n " go to next x (here we could use j too)
:s//z/gi<Enter> " do another sub x->z
`< " back to the old cursor position
q " end recording
if you want to X->Y and x->y, just remove the i flag and add two more :s
The : at the beginning of each line is optional, as are the :normal! V lines.
You are leveraging the Normal commands that you know, which is a good way to start, but IMHO you get cleaner code if you use more Command-mode (ex) commands and functions. I would do something like this:
function! SwitchXtoYZ()
let save_cursor = getpos(".")
copy .
s/X/Y/ge
s/x/y/ge
-copy .
s/X/Z/ge
s/x/z/ge
call setpos('.', save_cursor)
endfun
command! XtoYZ call SwitchXtoYZ()
:help function-list
:help getpos()
:help :call
:help :exec

Improve TwiddleCase function to work in visual block mode

The following snippet can be found on the vim wiki:
function! TwiddleCase(str)
if a:str ==# toupper(a:str)
let result = tolower(a:str)
elseif a:str ==# tolower(a:str)
let result = substitute(a:str,'\(\<\w\+\>\)', '\u\1', 'g')
else
let result = toupper(a:str)
endif
return result
endfunction
vnoremap ~ ygv"=TwiddleCase(#")<CR>Pgv
This, however, fails in visual block mode. Given the following
input:
foo alpha
bar beta
Having the cursor positioned on the f of foo and pressing
ctrl-v je~ yields the following result.
Foo
Bar alpha
beta
instead of the expected
Foo alpha
Bar beta
How can this function be improved to properly work in visual block mode?
The problem is that the use of the expression register ("=) forces a characterwise operation.
To fix that, manipulate the default register (that contains the original yanked text, anyway), and keep the original register type via getregtype():
vnoremap ~ y:call setreg('', TwiddleCase(#"), getregtype(''))<CR>gv""Pgv

Can you do interactive macros or recordings in vim?

I would like to define a vim macro that breaks for user input at certain times, is this possible?
EDIT: Turns out I ment recordings (q), not macros
It is possible to use the input command in a recording, but it's more trouble than it's worth.
I first mapped insert input escape to a key
:map <F2> a<C-R>=input('input: ')<CR>
then I made this recording in the q register
name:
and pasted it into a new tab
iname: ^[
And after the final escape I pressed <C-V><F2> making the line:
iname ^[^[OQ
That I yanked back to the q buffer then used the macro, letting me use the input function.
It works, but terribly.
Yes. See the function input({prompt}, [, {text} [, {completion}] ]). There is even
inputdialog({prompt} [, {text} [, {cancelreturn}]]), for a dialog popup.
If you use input() inside a mapping or macro, the remaining characters will be taken as input, which is not what you want. Vim offers the inputsave() and inputrestore() functions to temporarily suspend reading from the mapping character stream.
Based on mogelbrod's answer, this doesn't work; the itest is read in as input:
oBEFORE ^R=input('prompt> ')^Mitest
But this does:
function! Input()
call inputsave()
let text = input('prompt> ')
call inputrestore()
return text
endfunction
oBEFORE ^R=Input()^Mitest
Unfortunately, because <C-R> takes an expression, we cannot put the commands inline, but have to define a separate Input() function.
Unfortunately it doesn't seem to be possible. You can trigger input() inside a macro, but continuing on afterwards doesn't seem to be possible as any additional input recorded is inserted into the input prompt.
Yank the line into a named register ("qY) and run it (#q) to try it out.
Note: replace ^R and ^M with Ctrl-V Ctrl-R/M (see :help i_CTRL-V).
oBEFORE ^R=input('prompt> ') - works
oBEFORE ^R=input('prompt> ')^Mitest - works, but inserts itest into the prompt
oBEFORE ^R=input('prompt> ')<CR>test - fails
I have collected information from this and other threads and written this script:
function! MacroInterrupt()
"call inputsave()
if strlen(reg_recording()) == 0
if mode() == 'n'
call inputsave()
let tmp_col = col('.')
let tmp_line = line('.')
let text = input('input:')
let line = getline('.')
call setline('.', strpart(line, 0, col('.') - 1) . text . strpart(line, col('.') - 1))
call cursor(tmp_line, tmp_col + strlen(text))
call inputrestore()
return text
else
call inputsave()
let text = input('input:')
call inputrestore()
return text
endif
else
echo "Interrupt added to macro"
call setreg(reg_recording(), getreg(reg_recording()) . "\<F2>")
"echo getreg("q")
endif
"call inputrestore()
endfunction
map <F2> :call MacroInterrupt() <CR>
inoremap <buffer><expr> <F2> MacroInterrupt()
I hope this can help especially people attempting the same.

Mark a block of characters in VI/M ex command

It's quite straitforward for VI/M to mark a block of lines from Mth line to Nth line ready to delete, cut & past, or copy & paste.
:M,N d
:M,N m p
:M,N t p
If it's further required for VI/M to mark a block of characters from Ith character of Mth line to Jth character of Nth line, is it possible to accomplish similarly to the above?
#EDIT
Except the next answer asked for visual block mode, how about the option on typing a succinct ex command?
#EDIT 2
To clarify the meaning of a block of characters:
a square block of characters, addressed by visual block mode, directly called upon by pressing Ctrl-v in normal mode
a zipzag area of successive characters, addressed by visual character mode, directly called upon by pressing v in normal mode
a rows region of successive lines, addressed by visual line mode, directly called upon by pressing V in normal mode. In this case, the handy solution in ex mode has been illustrated above when this topic was originally raised.
#SOLUTION
Selecting abitrary zipzag area of successive characters from line M, column I to line N, column J in ex mode exactly like in visual character mode :
mark:
:normal! MggI|vNggJ|
delete:
:normal! MggI|vNggJ|d
yank:
:normal! MggI|vNggJ|y
move to line X column Y
:normal! MggI|vNggJ|dXggY|p
copy to line X column Y
:normal! MggI|vNggJ|yXggY|p
#SOLUTION 2
Selecting abitrary square block of characters from line M, column I to line N, column J in ex mode exactly like in visual block mode :
mark:
:execute "normal! MggI|\<C-v>NggJ|"
delete:
:execute "normal! MggI|\<C-v>NggJ|d"
yank:
:execute "normal! MggI|\<C-v>NggJ|y"
move to line X column Y
:execute "normal! MggI|\<C-v>NggJ|dXggY|p"
copy to line X column Y
:execute "normal! MggI|\<C-v>NggJ|yXggY|p"
You can use visual block mode from an ex command mode using normal!: for example, to select a block (line, column) from (42, 10) to (54, 20) and yank it (both lines must have at least 20 characters or virtualedit=block should be set):
execute "normal! 42gg10|\<C-v>54gg20|y"
. It is very straightforward way to do this, useful only in scripts.
Note that this command has at least following side-effects:
Setting marks '<, '>, '[, '], ''.
Moving a cursor.
Changing registers #", #0.
Adding one item to the jumplist.
Overwriting previous visual selection.
Altering v:count and v:count1 variables.
Ctrl+V enables visual block mode, then you can use the arrow keys to select the block.

Resources