11

I've the following sample code which modifies the current line using Python statement:

:py import vim; vim.current.line="["+vim.current.line+"]"

How I can execute this statement for each line in the current file?

Related: How can you use Python in Vim? at stackoverflow

kenorb
  • 18,433
  • 18
  • 72
  • 134

2 Answers2

10

You can use the pydo command available since Vim 7.4, the manual describe how it works better than I could:

:[range]pydo {body}

Execute Python function "def _vim_pydo(line, linenr): {body}" for each line in the [range], with the function arguments being set to the text of each line in turn, without a trailing <EOL>, and the current line number. The function should return a string or None. If a string is returned, it becomes the text of the line in the current turn. The default for [range] is the whole file: "1,$".

For your example you can use a command like:

:python import vim
:pydo vim.current.buffer[linenr - 1] = '[%s]' % line

The linenr - 1 bit is there because lines in vim.current.buffer are 0-indexed but Vim start to count lines from 1.

The nice thing is that you can easily define a custom command to execute your Python code on a range of lines:

command! -range=% BracketLines 
    \ <line1>,<line2>pydo vim.current.buffer[linenr - 1] = '[%s]' % line
toro2k
  • 4,882
  • 1
  • 31
  • 35
7

You can get the current buffer with vim.current.buffer, which is an iterable; you can use use a for loop to get each line.

You can change the lines by assigning to them; so putting that together, we get:

:py from vim import *
:py for i, line in enumerate(current.buffer): current.buffer[i] = '[%s]' % line

Also see :help python-buffer.

Martin Tournoij
  • 62,054
  • 25
  • 192
  • 271