vimtricks.wiki Concise Vim tricks, one at a time.

How do I run a Lua expression on every line of a buffer in Neovim?

Answer

:[range]luado {lua-expr}

Explanation

Neovim's :luado command runs a Lua expression on each line of a range, allowing you to transform text using the full power of Lua's string library. The expression receives two variables: line (the current line as a string) and linenr (the 1-based line number). If the expression returns a string, that string replaces the line; returning nil leaves the line unchanged.

How it works

  • :[range]luado {expr} — execute {expr} for each line in [range]
  • line — the current line content (string)
  • linenr — the current line number (integer)
  • Return a string to replace the line; return nil to leave it unchanged

Example

Convert every line in the buffer to uppercase:

:luado return line:upper()

Prefix each line with its line number:

:luado return string.format('%3d: %s', linenr, line)

Apply a Lua pattern substitution to lines 10–20:

:10,20luado return line:gsub('camelCase', 'camel_case')

Tips

  • For Vimscript-based per-line processing, use the older :pydo (Python) for Python users
  • Combine with a visual range: :'<,'>luado return line:lower()
  • Lua's string.format, string.gsub, string.match, and string.gmatch are all available
  • For simple substitutions, :s is usually faster; :luado shines for complex logic or math-based transformations

Next

How do I incrementally expand or shrink a selection based on syntax tree nodes using nvim-treesitter?