Vim gets string between visual selection range using Python

Here is some text here is line two of text 

I visually select from is to is in Vim: (brackets represent visual selection [ ] )

 Here [is some text here is] line two of text 

Using Python, I can get a series of selection sets:

 function! GetRange() python << EOF import vim buf = vim.current.buffer # the buffer start = buf.mark('<') # start selection tuple: (1,5) end = buf.mark('>') # end selection tuple: (2,7) EOF endfunction 

I use this file:: :so % , visually select the text, run :<,'>call GetRange() and

now that i have (1,5) and (2,7) . In Python, how can I compile a string that is as follows:

is some text\nhere is

It would be nice:

  • Get this string for future manipulations
  • then replace this selected range with an updated / managed line
+6
source share
3 answers

Try the following:

 fun! GetRange() python << EOF import vim buf = vim.current.buffer (lnum1, col1) = buf.mark('<') (lnum2, col2) = buf.mark('>') lines = vim.eval('getline({}, {})'.format(lnum1, lnum2)) lines[0] = lines[0][col1:] lines[-1] = lines[-1][:col2] print "\n".join(lines) EOF endfun 

You can use vim.eval to get the values โ€‹โ€‹of python functions and vim variables.

+7
source

This will probably work if you used pure vimscript

 function! GetRange() let @" = substitute(@", '\n', '\\n', 'g') endfunction vnoremap ,ry:call GetRange()<CR>gvp 

This will convert all newlines to \n in the visual selection and replace the selection with that string.

This mapping maps the selection to case. " Calls a function (not really necessary, as its only command). Then it uses gv to reselect the visual selection, and then reinserts the quotation register into the selected area.

Note: in vimscript, all user-defined functions must begin with a top-level letter.

+4
source

Here's another version based on Conner's answer. I accepted the qed suggestion and also added a fix when the selection is completely within the same row.

 import vim def GetRange(): buf = vim.current.buffer (lnum1, col1) = buf.mark('<') (lnum2, col2) = buf.mark('>') lines = vim.eval('getline({}, {})'.format(lnum1, lnum2)) if len(lines) == 1: lines[0] = lines[0][col1:col2 + 1] else: lines[0] = lines[0][col1:] lines[-1] = lines[-1][:col2 + 1] return "\n".join(lines) 
+1
source

Source: https://habr.com/ru/post/951466/


All Articles