Wednesday, July 5, 2017

The basics of VIM find and replace

The basics of VIM find and replace work like this (for one line) —

:s/searchable/replaceable/optional_commands

The slashes separate the searchable and replaceable and the optional commands.

To search/replace for all occurences of searchable in the same line, use the /g option —

:s/searchable/replaceable/g

To search/replace through all the lines in the entire file, use the percentage sign before s

:%s/searchable/replaceable/g

To append (add after text) or prepend (add before text) instead of replacing, use the ampersand, and pay attention to its location relative to replaceable text:

:%s/searchable/&add_after

:%s/searchable/add_before&

If something goes wrong, press the <u> key to undo. Ctrl+R to redo.

Vim uses regular expressions for advanced searches. To test if a match works, use the simple / (slash) command in the Vim command line to find out if the searchable matches what you need to look for:

/searchable\/

looks for the word searchable that has a forward slash appended to it. Because the forward slash / is used in the search and replace syntax with subst, then it has to be escaped with a backslash \, like this: \/

If the searchable is highlighted, type :noh to turn it off for the time being.

Delete empty lines:
%s/^$\n/
^ = start of line
$ = end of line
\n = newline

Quitting Vim

Unlike strictly text-mode versions of Vim, Vim Touch has a more accessible quit command in the app's Android-native menu.

Some other basics of operating Vim:

Vim uses two modes: editing mode and command mode. The former is used to write text, the latter to manipulate text and files by way of entering commands outside editing mode.

The command mode uses two types of commands —
* those that begin with a colon, followed by additional commands and options :
* those that don't.

Quitting Vim with the virtual keyboard:

:q — simple quit. Uses confirmation.

:q! — quit without confirmation or saving files.

:qa! — quit all open files without confirmation or saving files.

Insert text:
i — before cursor
a — after cursor

I — at beginning of line
A — at end of line

Shift+R — insert text in INS mode (overwrite)

Press Esc to switch away from text insert mode.

Undo/redo:
u — undo
Ctrl+R — redo

:q

No comments: