Vim provides the :s
(substitute) command for search and replace; this tip shows examples of how to substitute. On some systems, gvim has Find and Replace on the Edit menu (:help :promptrepl), however it is easier to use the :s
command due to its command line history and ability to insert text (for example, the word under the cursor) into the search or replace fields.
The :substitute
command searches for a text pattern, and replaces it with a text string. There are many options, but these are what you probably want:
:s/foo/bar/g
- Find each occurrence of ‘foo’ (in the current line only), and replace it with ‘bar’.
:%s/foo/bar/g
- Find each occurrence of ‘foo’ (in all lines), and replace it with ‘bar’.
:%s/foo/bar/gc
- Change each ‘foo’ to ‘bar’, but ask for confirmation first.
:%s/<foo>/bar/gc
- Change only whole words exactly matching ‘foo’ to ‘bar’; ask for confirmation.
:%s/foo/bar/gci
- Change each ‘foo’ (case insensitive due to the
i
flag) to ‘bar’; ask for confirmation. :%s/fooc/bar/gc
is the same becausec
makes the search case insensitive.- This may be wanted after using
:set noignorecase
to make searches case sensitive (the default).
:%s/foo/bar/gcI
- Change each ‘foo’ (case sensitive due to the
I
flag) to ‘bar’; ask for confirmation. :%s/fooC/bar/gc
is the same becauseC
makes the search case sensitive.- This may be wanted after using
:set ignorecase
to make searches case insensitive.
The g
flag means global – each occurrence in the line is changed, rather than just the first. This tip assumes the default setting for the 'gdefault'
and 'edcompatible'
option (off), which requires that the g
flag be included in %s///g
to perform a global substitute. Using :set gdefault
creates confusion because then %s///
is global, whereas %s///g
is not (that is, g
reverses its meaning).
When using the c
flag, you need to confirm for each match what to do. Vim will output something like:
replace with foobar (y/n/a/q/l/^E/^Y)?
(where foobar is the replacement part of the :s/.../.../
command). You can type y
which means to substitute this match, n
to skip this match, a
to substitute this and all remaining matches («all» remaining matches), q
to quit the command, l
to substitute this match and quit (think of «last»), ^E
to scroll the screen up by holding the Ctrl key and pressing E and ^Y
to scroll the screen down by holding the Ctrl key and pressing Y. However, the last two choices are only available, if your Vim is a normal, big or huge built or the insert_expand feature was enabled at compile time (look for +insert_expand
in the output of :version
).
Also when using the c
flag, Vim will jump to the first match it finds starting from the top of the buffer and prompt you for confirmation to perform replacement on that match. Vim applies the IncSearch
highlight group to the matched text to give you a visual cue as to which match it is operating on (set to reverse
by default for all three term types as of Vim 7.3). Additionally, if more than one match is found and you have search highlighting enabled with :set hlsearch
, Vim highlights the remaining matches with the Search
highlight group. If you do use search highlighting, you should make sure that these two highlight groups are visually distinct or you won’t be able to easily tell which match Vim is prompting you to substitute.
Details[]
Search range:
:s/foo/bar/g |
Change each ‘foo’ to ‘bar’ in the current line. |
:%s/foo/bar/g |
Change each ‘foo’ to ‘bar’ in all the lines. |
:5,12s/foo/bar/g |
Change each ‘foo’ to ‘bar’ for all lines from line 5 to line 12 (inclusive). |
:'a,'bs/foo/bar/g |
Change each ‘foo’ to ‘bar’ for all lines from mark a to mark b inclusive (see Note below). |
:'<,'>s/foo/bar/g |
When compiled with +visual , change each ‘foo’ to ‘bar’ for all lines within a visual selection. Vim automatically appends the visual selection range (‘<,’>) for any ex command when you select an area and enter : . Also, see Note below.
|
:.,$s/foo/bar/g |
Change each ‘foo’ to ‘bar’ for all lines from the current line (.) to the last line ($) inclusive. |
:.,+2s/foo/bar/g |
Change each ‘foo’ to ‘bar’ for the current line (.) and the two next lines (+2). |
:g/^baz/s/foo/bar/g |
Change each ‘foo’ to ‘bar’ in each line starting with ‘baz’. |
- Note: As of Vim 7.3, substitutions applied to a range defined by marks or a visual selection (which uses a special type of marks ‘< and ‘>) are not bounded by the column position of the marks by default. Instead, Vim applies the substitution to the entire line on which each mark appears unless the
%V
atom is used in the pattern like::'<,'>s/%Vfoo/bar/g
.
When searching:
.
,*
,,
[
,^
, and$
are metacharacters.+
,?
,|
,&
,{
,(
, and)
must be escaped to use their special function./
is / (use backslash + forward slash to search for forward slash)t
is tab,s
is whitespace (space or tab)n
is newline,r
is CR (carriage return = Ctrl-M = ^M)- After an opening
[
, everything until the next closing]
specifies a /collection. Character ranges can be represented with a-
; for example a letter a, b, c, or the number 1 can be matched with[1a-c]
. Negate the collection with[^
instead of[
; for example[^1a-c]
matches any character except a, b, c, or 1. {#}
is used for repetition./foo.{2}
will match foo and the two following characters. Theis not required on the closing
}
so/foo.{2}
will do the same thing.(foo)
makes a backreference to foo. Parenthesis without escapes are literally matched. Here theis required for the closing
)
.
When replacing:
r
is newline,n
is a null byte (0x00).&
is ampersand (& is the text that matches the search pattern).inserts the text matched by the entire pattern
1
inserts the text of the first backreference.2
inserts the second backreference, and so on.
You can use other delimiters with substitute:
:s#http://www.example.com/index.html#http://example.com/#
Save typing by using zs
and ze
to set the start and end of a pattern. For example, instead of:
:s/Copyright 2007 All Rights Reserved/Copyright 2008 All Rights Reserved/
Use:
:s/Copyright zs2007ze All Rights Reserved/2008/
Using the current word or registers[]
:%s//bar/g
- Replace each match of the last search pattern with ‘bar’.
- For example, you might first place the cursor on the word
foo
then press*
to search for that word. - The above substitute would then change all words exactly matching ‘foo’ to ‘bar’.
:%s/foo/<c-r><c-w>/g
- Replace each occurrence of ‘foo’ with the word under the cursor.
<c-r><c-w>
means that you press Ctrl-R then Ctrl-W.- The word under the cursor will be inserted as though you typed it.
:%s/foo/<c-r><c-a>/g
- Replace each occurrence of ‘foo’ with the WORD under the cursor (delimited by whitespace).
<c-r><c-a>
means that you press Ctrl-R then Ctrl-A.- The WORD under the cursor will be inserted as though you typed it.
:%s/foo/<c-r>a/g
- Replace each occurrence of ‘foo’ with the contents of register ‘a’.
<c-r>a
means that you press Ctrl-R thena
.- The contents of register ‘a’ will be inserted as though you typed it.
:%s/foo/<c-r>0/g
- Same as above, using register 0 which contains the text from the most recent yank command. Examples of yank (copy) commands are
yi(
which copies the text inside parentheses around the cursor, andy$
which copies the text from the cursor to the end of the line. After a yank command which did not specify a destination register, the copied text can be entered by pressing Ctrl-R then0
.
:%s/foo/=@a/g
- Replace each occurrence of ‘foo’ with the contents of register ‘a’.
=@a
is a reference to register ‘a’.- The contents of register ‘a’ is not shown in the command. This is useful if the register contains many lines of text.
:%s//<c-r>//g
- Replace each match of the last search pattern with the
/
register (the last search pattern). - After pressing Ctrl-R then
/
to insert the last search pattern (and before pressing Enter to perform the command), you could edit the text to make any required change.
:%s/<c-r>*/bar/g
- Replace all occurrences of the text in the system clipboard (in the
*
register) with ‘bar’ (see next example if multiline). - On some systems, selecting text (in Vim or another application) is all that is required to place that text in the
*
register.
:%s/<c-r>a/bar/g
- Replace all occurrences of the text in register ‘a’ with ‘bar’.
<c-r>a
means that you press Ctrl-R thena
. The contents of register ‘a’ will be inserted as though you typed it.- Any newlines in register ‘a’ are inserted as
^M
and are not found. - The search works if each
^M
is manually replaced with ‘n’ (two characters: backslash, ‘n’). - This replacement can be performed while you type the command:
:%s/<c-r>=substitute(@a,"n",'\n','g')<CR>/bar/g
- The
"n"
(double quotes) represents the single character newline; the'\n'
(single quotes) represents two backslashes followed by ‘n
‘. - The
substitute()
function is evaluated by the<c-r>=
(Ctrl-R=
) expression register; it replaces each newline with a single backslash followed by ‘n
‘. - The
<CR>
indicates that you press Enter to finish the=
expression.
:%s/<c-r>0/bar/g
- Same as above, using register 0 which contains the text from the most recent yank command.
See Paste registers in search or colon commands instead of using the clipboard.
Additional examples[]
:%s/foo/bar/
- On each line, replace the first occurrence of «foo» with «bar».
:%s/.*zsfoo/bar/
- On each line, replace the last occurrence of «foo» with «bar».
:%s/<foo>//g
- On each line, delete all occurrences of the whole word «foo».
:%s/<foo>.*//
- On each line, delete the whole word «foo» and all following text (to end of line).
:%s/<foo>.{5}//
- On each line, delete the first occurrence of the whole word «foo» and the following five characters.
:%s/<foo>zs.*//
- On each line, delete all text following the whole word «foo» (to end of line).
:%s/.*<foo>//
- On each line, delete the whole word «foo» and all preceding text (from beginning of line).
:%s/.*ze<foo>//
- On each line, delete all the text preceding the whole word «foo» (from beginning of line).
:%s/.*(<foo>).*/1/
- On each line, delete all the text preceding and following the whole word «foo».
:%s/<foo(bar)@!/toto/g
- On each line, replace each occurrence of «foo» (which starts a word and is not followed by «bar») by «toto».
:s/^(w)/u1/
- If the first character at the beginning of the current line only is lowercase, switch it to uppercase using
u
(see switching case of characters).
:%s/(.*n){5}/&r/
- Insert a blank line every 5 lines.
- The pattern searches for
(.*n)
(any line including its line ending) repeated five times ({5}
). - The replacement is
&
(the text that was found), followed byr
(newline).
:%s/<foo(a*)>/=len(add(list, submatch(1)))?submatch(0):submatch(0)/g
- Get a list of search results. (the list must exist)
- Sets the
modified
flag, because of the replacement, but the content is unchanged. - Note: With a recent enough Vim (version 7.3.627 or higher), you can simplify this to:
:%s/<foo(a*)>/=add(list, submatch(1))/gn
- This has the advantage, that the buffer won’t be marked modified and no extra undo state is created. The expression in the replacement part is executed in the sandbox and not allowed to modify the buffer.
Special cases[]
For substituting patterns with corresponding case-sensitive text, Michael Geddes’s keepcase plugin can be used, e.g.:
:%SubstituteCase/cHello/goodBye/g
- Substitute ‘Hello hello helLo HELLO’ by ‘Goodbye goodbye goodBye GOODBYE’
For changing the offsets in a patch file (line number of a block), this little snippet can be used:
s/^@@ -(d+),(d+) +(d+),(d+) @@$/="@@ -".eval(submatch(1)+offsetdiff).",".submatch(2)." +".eval(submatch(3)+offsetdiff).",".submatch(4)." @@"/g
Useful when we want to strip some blocks from a patch, without patch having to complain about offset differences.
- Note Should try to make the expression more compact, but don’t know how without having the possibility of modifying unwanted lines.
Change and repeat[]
- Search for text using
/
or for a word using*
. - In normal mode, type
cgn
(change the next search hit) then immediately type the replacement. Press Esc to finish. - From normal mode, search for the next occurrence that you want to replace (
n
) and press.
to repeat the last change.
See also: using substitute[]
- 63 Applying substitutes to a visual block
- 81 Substitute characters and lines easily
- 159 Keystroke Saving Substituting and Searching
- 406 Alternate delimiters for the replace command
- 438 Search and replace in a visual selection
- 464 Search and replace the word under the cursor
- 479 Replace with no typing
- 573 Repeating a substitute from current cursor position
- 605 Replace a word with the yanked text
- 654 Special characters in the substitute command
- 755 Using an expression in substitute command
- 808 Replace a visual-block of text with another such block
- 915 Using g instead of substitute
- 971 Substitute with incrementing numbers
- 1114 Step increment and replace
- 1501 Substitute last search
See also: substitute in buffers/files[]
- 382 Search and replace in multiple buffers
References[]
- :help :substitute
- :help cmdline-ranges
- :help pattern
- :help ‘gdefault’
- :help registers
- :help :s_flags
[]
TO DO
The large «see also» section may be useful to readers. We need to merge some of the related tips (but don’t make the result too complex). I included the tip numbers to help editors keep track.
Want a short section mentioning that simple substitutes are often best handled by searching then manually changing (and pressing .
to repeat the last change). Additionally, you can decide how to change each instance. See Copy or change search hit for a technique where you can press n
to find the next instance, then type cs
to change the search hit to whatever.
Has there been a change recently with how %s works? Somehow i can use both <c-r> and =@ as replacers, but I can’t use them as searches and replacements.
- If you describe exactly what you do and what happens I might be able to help although see asking questions. JohnBeckett (talk) 02:15, June 1, 2019 (UTC)
You might be interested in this answer I gave on how to use registers, but here are four methods to do that:
Method 1
While editing a command, hit CTRLR then CTRLW to insert word under the cursor.
Also see :help c_CTRL-R
Method 2
Go to your word, hit *, and do :%s//replacement/g
. When no search pattern is used, last search pattern, taken from register @/
, is used.
Method 3 (you will probably like that one)
Do a :nnoremap <f12> :%s/<c-r><c-w>/<c-r><c-w>/gc<c-f>$F/i
(ctrl-f is determined by the ‘cedit’ option)
You can put this mapping into your .vimrc.
This will map the F12 key to what you want, and your cursor will be left where you want.
Method 4
Go to your word, hit *, and do :%s//
CTRLR,//gc
CTRL-R then / inserts contents of your search register.
Introduction
Manipulating text and making multiple edits at once is crucial when working in Vim or its older version Vi.
As a popular Linux text editor, Vim offers several practical ways to find and replace terms quickly and efficiently.
This tutorial shows how to use the find and replace function in Vim/Vi and keep track of all the changes.
Note: If you don’t have Vim, check out these tutorials and learn how to install the text editor on CentOS or Ubuntu.
Find and Replace Methods
Finding and replacing text patterns in Vim simplifies navigation and changes in large files.
Hence, Vim offers two ways to search and replace text, depending on whether a single change or multiple edits are necessary.
Warning: Vim must be in normal mode to execute commands. Go back to normal mode with the Esc key.
Slash and Dot Command
Use the slash and dot command to find and replace a single occurrence of a word in Vim.
Open a file in Vim and follow these steps:
- Press the slash key (/).
- Type the search term to highlight it in the text and hit Enter.
- Use the Esc key to return to normal mode.
- Type
cgn
and enter the replacement term.
- Go back to normal mode.
- Hit n to move to the next search term occurrence.
- Press the dot (.) key to replace the next occurrence with the same replacement term.
Substitute Command
The substitute command :s
is more versatile than the slash and dot command.
The basic :s
command syntax is:
:s/search_term/replacement_term/
The command searches for the search_term
in the current line, the line where the cursor is. Next, :s
changes the search_term
to the replacement_term
.
For example, to find the term vi in the current line and replace it with Vim, use the following command:
:s/vi/Vim/
Hit Enter and the terminal shows that the string vi changed to Vim:
However, :s
offers much more than the basic search and replace function. For instance, the command accepts different options and flags. The complete syntax for the substitute command looks like this:
:[range]s/search_term/replace_term/[flags] [count]
These options and flags help specify the search. For example, to find all occurrences of vi in the current line, add the g
flag.
:s/vi/Vim/g
Hit Enter to replace both instances with Vim:
Moreover, confirm each substitution with the c
flag:
:s/vi/Vim/gc
Output is the following:
Vim prompts users to choose between several options:
- Substitute selected match with Y.
- Skip selected match with n.
- Replace all matches with a.
- Quit the command with q.
- Replace the selected match and quit with I.
However, the ^E and ^Y options are available in some Vim installations. Use them to scroll the screen:
- Scroll the screen up with Ctrl + E.
- Scroll the screen down with Ctrl + Y.
Find and Replace Important Considerations
The find and replace tools in Vim, especially the substitute command, offer additional possibilities for a more specific and effective search. Check out how to customize the search and replace operation in the following text.
Search Range
Specifying a range when running the :s
command helps users search and replace patterns beyond the current line.
To determine the range:
- Add line numbers separated by a comma to find and replace a pattern in specific lines.
For example, substitute all occurrences of vi to Vim from line 1 to line 3:
:1,3s/vi/Vim/g
The output shows that only the first two instances of vi, in the first three lines, were changed to Vim:
- Choose the
%
symbol and add theg
flag to find and replace a pattern in the entire file.
:%s/vi/Vim/g
- Use a dot (
.
) and a dollar sign ($
) separated by a comma to substitute everything from the current line to the last line.
:.,$s/vi/Vim/g
Since the current line is also the last line, the output shows that the instances of vi in the last line were changed.
- Combine
+
/-
symbols with numbers to add or subtract lines from the current one.
For example, to substitute each vi with Vim starting from the current line and the next two lines, type:
:.,+2s/vi/Vim/g
Case Sensitivity
The find and replace process in Vim is case-sensitive by default. For example, using the :s
command to substitute vim (in lowercase) with vi does not work. This is because Vim is always in capitalized in this text. Therefore, use Vim instead of vi as the search term.
To make the find and replace operation case insensitive, use one of the two methods:
- Add the
i
flag.
:%s/vim/vi/gi
The output shows that both instances of Vim have been found and replaced with vi.
Use the I
flag to turn the case-sensitive search back on.
- Append
c
after the search pattern.
:%s/vimc /vi/g
The output shows that even though the search term is lower case, the command finds the uppercase Vim in the text.
Adding the /C
after a search pattern turns on case-sensitive search.
Word Substitution
The :s
command, by default, searches for patterns, not unique words. For example, using vi as the search pattern results in matches where vi is part of a larger word, such as visible.
Executing the command in the entire text changes patterns included in other words as well.
Search and replace a whole word with:
:%s/<search_term>/replace_term/
The <
symbol marks the beginning and the >
symbol the end of a word. For example, to search for the word vi, but not when part of a bigger word, and replace the word with Vim, use:
:%s/<vi>/Vim/g
Find and Replace History
Running the :s
command without any options shows previous substitute operations. In addition, run the :s
command and use the up/down arrow keys to move across the document.
More importantly, use the :s
command to apply previous substitutes to new text. For example, the history shows that the command replaced all instances of vi with Vim.
Running :s
finds any already made substitutes, but also all instances of vi not changed yet.
Find and Replace Examples
The find and replace function in Vim has extensive practical use. Thus, outlined below are common substitute command examples.
Find and Replace Entire Lines
Use :s
to substitute entire lines in Vim based on a single parameter. For example, substitute every line starting with Do you with Learn more about Vim! using this command:
:%s/^Do you .*/ Learn more about Vim!/g
The ^
(caret) symbol matches the beginning of a line, and *
matches the rest of the line.
The output shows the change:
Change Number in Numbered List
Adding an item in the middle of a numbered list in Vim means that the user has to change numbers in all the subsequent lines.
The substitute command changes the numbers of all other articles accordingly. Use this command:
:5,$s/d+/=submatch(0) + 1/
The command consists of:
:5,$
— The range from the fifth line to the last line.d+
— The digits sequence as the search term.=submatch(0) + 1
— The replacement term adding 1 to each match.
After executing the substitute command, the output looks like this:
Eliminate Double Spaces
Double spaces are common typing errors, but :s
takes care of this quite quickly with:
:%s/[double space]/[single space]/g
All spaces in the last line are doubled. After executing the command, the sentence is single-spaced:
Replace Different Words with One
Use the substitute command to substitute different search terms with one replacement term. For example, replace every instance of vi and Vim with This text editor.
:%s/(vi|Vim)/This text editor/g
The changed text looks like this:
Delete All Pattern Occurrences
Instead of substituting the search term, delete the pattern by omitting the replacement term. For example, delete all instances of Vim with:
:%s/Vim/
Conclusion
After reading this tutorial, you know how to find and replace text in Vim.
Next, check out and download this useful Vim Commands Cheat Sheet to learn other common Vim commands.
-
First install Vim.
-
To install the packages, first install ‘vundle’ using following command. Use ‘git-shell’ to run this command in Windows.
git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim (in Windows : use 'git-shell' to run below command) git clone https://github.com/VundleVim/Vundle.vim.git C:/Users/<Username>/.vim/bundle/Vundle.vim
-
Copy and paste the .vimrc file in the home directory.
-
In Windows, paste in the .vimrc file at C:/Users/<Username>/; and change the line “set rtp+= …” in .vimrc with correct location of “Vundle.vim” i.e. “set rtp+=C:/Users/<Username>/.vim/bundle/Vundle.vim”.
-
Use double quote to comment/uncomment the packages in .vimrc file e.g. ” Plugin ‘mattn/emmet-vim’ will not install the package “emmet-vim”. Or add some more packages in .vimrc file as required.
-
After selecting the packages, open vim and run the command -> :PluginInstall and it will install the all the plugins.
-
Use :help <plugin name> to see the list of operations.
1.1. Starting Vim¶
Commands | Descriptions |
---|---|
:w | save file |
:w <filename> | save file as <filename> and keep the current file open |
:sav <filename> | save file as <filename> and open <filename> |
:q | quit (if already saved) |
:q! | quit without saving |
:e <filename> | open new/existing <filename> in new buffer |
:wq | save and quit |
:bn | go to next buffer i.e. file |
:b <filename> | go to buffer with <filename> |
:bd | close current file without exiting vim |
:bd! | close current file without exiting vim and ‘no modification’ |
:vim * | open all files in the directory (all in same buffer) |
:vim file1 file2 file3 | open file1, file2 and file3 in vim |
:n | go to next file |
:n <filename> | go to file name |
:prev | go to previous file |
ctrl-Z | suspend vim |
fg | bring forground vim |
1.2. Undo/Redo¶
Commands | Descriptions |
---|---|
u | undo |
crtl-r | redo |
1.3. Insert¶
Commands | Descriptions |
---|---|
i | insert mode at cursor |
I | insert mode at beginning of the line (i.e. first character of line) |
s | delete character under the cursor and enter into insert mode |
S | delete the line and go to insert mode from the beginning of same line |
a | insert mode after the cursor |
A | insert mode at the end of line |
o | insert mode on below line |
O | insert mode at bottom line |
C | delete from cursor to end of line and go to insert mode |
r | replace current character |
R | replace characters until Esc is pressed (i.e. same as insert button in keyboard) |
1.4. Copy/Paste/Delete¶
Commands | Descriptions |
---|---|
y | yank (copy) |
yiw | copy the word |
yw | copy the word after the cursor |
yy or Y | copy the line |
y$ | copy till end of the line from current location of cursor |
“+y | copy to clipboard e.g. “+yiw will copy the word in clipboard |
<F3>y | same as above (use <F3> for clipboard, remapped in .vimrc) |
<F3>p | paste from clipboard (see above line as well) |
p | paste after cursor (remapped as ]p in .vimrc ) |
]p | paste with indentation |
P | paste before cursor |
ctrl-P | paste from clipboard (remapped in .vimrc) |
shift insert | paste from clipboard (remapped in .vimrc) |
d<command> | delete<command> |
diw | delete word (and stay at normal mode) |
ciw | delete word (and go to insert mode) |
dw or cw | delete word after the cursor |
dd or cc | delete line |
D or C | delete till end of line |
x | delete character (delete) |
X | delete character (backspace) |
. | repeat previous operation |
1.5. Paste in search or colon commands¶
- Following commands can be used at command mode during search or color commands e.g. :w ctrl r ctrl w etc.
Commands | Descriptions |
---|---|
ctrl r “ | paste the last copied data |
ctrl r ctrl w | paste the word under cursor |
ctrl r % | print the naem of current file |
shift insert | paste the data from clipboard |
1.6. Search¶
Commands | Descriptions |
---|---|
/ | forward then use n/N for next/previous match |
? | backward |
* (asterisk) | word under cursor forward (exact match) |
g* | word under the cursor (partial match) |
# | word under cursor backward (exact match) |
g# | word under cursor backward (partial match) |
/<word1> | search for exact match for “word1” |
:set ignorecase | use this option for avoiding case-matches |
:set noignorecase | use this option for case-matches |
1.7. Replace¶
- Use ‘c’, ‘g’, ‘gc’ and other combination to perform the desired replacement.
Commands | Descriptions |
---|---|
:s /word1/word2 | substitute word1 with word2 in current line (only first occurrence) |
:s /word1/word2/c | substitute word1 with word2 in current line after confirmation (only first occurrence) |
:s /word1/word2/g | substitute word1 with word2 in current line (all occurrence) |
:s /word1/word2/gc | substitute word1 with word2 in current line ater confirmation (all occurrence) |
:1,4 s /word1/word2 | substitute word1 with word2 in lines 1 to 4 (only first occurrence in each line) |
:%s /word1/word2/g | replace all occurrences |
:%s /word1/word2/gc | replace all occurrence after confirmation |
:%s /ctrl-r ctrl-w/word2/gc | replace all occurance of the word under cursor after confirmation (exact match) |
:s /<word1>/word2 | substitute exactly matched “word1” with word2 in current line |
1.8. Indentation¶
Commands | Descriptions |
---|---|
>> | Right indent the current line |
5>> | Right indent 5 lines |
<< | De-indent line |
5== | Re-indent 5 lines |
>% | Increase indent of a braced or bracketed block (place cursor on brace first) |
=% | Reindent a braced or bracketed block (cursor on brace) |
<% | Decrease indent of a braced or bracketed block (cursor on brace) |
]p | Paste text, aligning indentation with surroundings |
=i{ | Re-indent the ‘inner block’, i.e. the contents of the block |
=a{ | Re-indent ‘a block’, i.e. block and containing braces |
>i{ | Increase inner block indent |
<i{ | Decrease inner block indent |
Commands | Descriptions |
---|---|
:retab | convert existing tabs to spaces |
1.9. Mouse settings¶
Commands | Descriptions |
---|---|
:behave mswin | mouse functionality will work as windows |
:behave xterm | mouse functionality will word as x-windows |
1.10. Command/Visual Mode¶
Commands | Descriptions |
---|---|
Esc or crtl-[ | command mode |
v | visual mode |
crtl-v | visual block mode |
1.11. Cursor movement¶
Note
To run the ‘ctrl-]’ and ‘ctrl-T’ command, we need to create the tags first. In the below command, the ‘tags’ will be created for all the python files in the directory, which will be stored in a file ‘tags’,
(run the following command in shell) ctags -R *.py
Commands | Descriptions |
---|---|
h | left |
j | down |
k | up |
l | down |
w | forward to the beginning of next word |
3w | forward 3 words |
W | forward to the beginning of next word (only spaces are the end of word) |
b | backward to the beginning of next word |
B | backward to the beginning of next word (only spaces are the end of word) |
e | forward to end of next word |
E | forward to end of next word (only spaces are the end of the word) |
gg | go to first line of page |
G | go to end line of page |
10G | go to 10th line |
10gg | go to 10th line |
0 | go to first character of line |
$ | go to end character of line |
^ | go to first non-black character of line |
M | go to middle of the screen |
fa | go to next a in current line |
Fa | go to previous a in current line |
ta | go to end of next a in current line |
Ta | to to end of previous a in current line |
ctrl-o | go to previous location e.g. we went to line 10 from line 18, ctrl-o will go to line 18 again |
ctrl-i or Tab | go to next location i.e. go to line 10 again from line 18. |
gd | go to the local declaration of the word under cursor |
gD | go to the global declaration of the word under cursor |
g* | search for the word under the cursor |
g# | same as g* but in backward direction. |
gf | go to the filename under the cursor, use ctrl-o to go back |
ctrl-] | go to tag definition (a tag can be a function or variable name etc.); use ctrl-o to go back |
ctrl-T | go back to previous loation from where ctrl-] was exectued |
1.12. Screen movements¶
Commands | Descriptions |
---|---|
ctrl-d | move half screen down |
ctrl-f | page down |
ctrl-e | move one line down |
ctrl-u | move half screen up |
ctrl-b | page up |
ctrl-y | move one line up |
z<Enter> | move current line to the top of screen (with cursor at the beginning) |
zt | move current line to the top with without changing the location of cursor |
|
move current line to the center of screen (with cursor at the beginning) |
zz | move current line to the center of screen (without moving cursor) |
z- | move current line to the center of screen (with cursor at the beginning) |
zb | move current line to the center of screen (without moving cursor) |
1.13. Unix Shell¶
Commands | Descriptions |
---|---|
:shell | go to unix shell |
exit | type exit in unix shell to come back in Vim |
1.14. Registers¶
Commands | Descriptions |
---|---|
“ayy | copy line in register ‘a’ |
“ap | paste content of register ‘a’ |
Capital letters append the new value to previously stored values | |
“Ayy | copy line and append to previous value in register “a” Then use “a to paste the value in register ‘a’ |
“=3*2<Enter>p | paste the result i.e. 6 at the current cursor location |
:registers | display the values in all the registers |
:registers abc | display the values of registers a, b and c |
1.15. Multiple Files¶
Commands | Descriptions |
---|---|
:arg grep -l ‘import’ *.py | open all files in current folder which contains word ‘import’ |
1.16. Mark¶
Commands | Descriptions |
---|---|
ma | mark the line with name ‘a’ (use a-z or 0-9) |
Next go to some other line and excute following command | |
d’a | delete till line which is marked as ‘a’ |
:marks | show the list of marks |
‘a | go to mark a |
1.17. Sorting¶
Commands | Descriptions |
---|---|
!10G (press enter) sort (press enter) | it will sort first ten lines according to name |
!G (press enter) sort (press enter) | it will sort all the lines according to names |
!!ls | go to terminal, run ls command and print the output on the file (i.e. print list of file in current directory) |
!!dates | go to terminal, run date command and print the output on the file |
1.18. Printing the code¶
Commands | Descriptions |
---|---|
:hardcopy <filename.pdf> | open the printing-instructions-window |
:TOhtml and then save the file | Save in html format, use :colorscheme default for white background |
1.19. Mapping¶
- Please read the comments in .vimrc file for more commands and details
- comment/uncomment the command using double quote as per requirement.
Commands | Descriptions |
---|---|
:map | display the key-mappings, |
1.19.1. Copy/paste from clip board¶
Use <F3> and then normal copy/paste command from clipboard.
Copy/paste to clip board | |
---|---|
<F3> is remapped | nnoremap <F3> “+ |
<ctrl-P> is remapped | nnoremap <C-P> “+]p (paste with indentation) |
<F3>yiw or <F3>yy etc. | copy the word or line etc. in clipboard |
<F3>p | paste the data from clipboard |
1.19.2. Disable arraow keys¶
Below code can be used in .vimrc file
“Key mappings : disable arrow keys |
---|
no <left> <Nop> |
no <down> <Nop> |
no <up> <Nop> |
no <right> <Nop> |
ino <down> <Nop> |
ino <left> <Nop> |
ino <right> <Nop> |
ino <up> <Nop> |
1.19.3. Code execution¶
“python commands |
---|
” Execute : F9 (Below code is used in .vimrc file) |
:autocmd FileType python :nmap <F9> :! clear <CR> :! python % <Enter> |
“C/C++ commands |
---|
“Compile : F9 (Below code is used in .vimrc file) |
:autocmd FileType c,cpp :nmap <F9> :! rm -r out <CR> :! clear <CR> :! g++ % -o out <Enter> |
“Run : Ctrl+F9 (Below code is used in .vimrc file) |
:autocmd FileType c,cpp :nmap <C-F9> :! clear <CR> :! ./out <CR> |
1.20. Buffer¶
Commands | Descriptions |
---|---|
:bn | go to next buffer i.e. file |
:b <filename> | go to buffer with <filename> |
:bd | close current file without exiting vim |
:bd! | close current file without exiting vim and ‘no modification’ |
1.21. Split windows¶
Commands | Descriptions |
---|---|
:split | split window in two part and display current file in both window |
:split <filename> | open <filename> in split window |
:5 split <filename> | open <filename> in new split window with width of 5 line |
:new | split window in two part with second window as blank |
crtl-w j | go to below split window |
crtl-w k | go to above split window |
crtl-ww, crtl-w w | go to next split window |
crtl-w + | increase the width of split window by one line |
5 crtl-w — | decrease the width of split window by 5 line |
crtl-w = | make all split window of equal size |
crtl-w _ | maximize the current split window |
1.22. Auto completion¶
Commands | Descriptions |
---|---|
ctrl-p,ctrl-n | auto complete by looking previous/next words (use ctrl-p or ctrl-n to change the words from list) |
1.23. Text files¶
Commands | Descriptions |
---|---|
:set textwidth=50 | change the line after 50 character |
:1,5 center 50 | textwidth = 50 and center the lines 1 to 5 |
:1,5 right 50 | textwidth = 50 and right justify the text on lines 1 to 5 |
:1,5 left 4 | left margin = 4 for lines 1 to 5 |
Use $ for end of the line as shown below, | |
:1,$ center 50 | textwidth=50 and cneter all the line |
or use % sign for the file (results is same as above, | |
:% center 50 | |
:set wrap | turn the wrap words on |
:set nowrap | turn off the wrap words |
1.24. Macros¶
Commands | Descriptions |
---|---|
qa | start recording and store in reg ‘a’. Then perform certain operations. press ‘q’ again to stop recording. |
@a | execute macro |
3@a | repeat macro 3 times |
1.25. More commands¶
Commands | Descriptions |
---|---|
ctrl + g | name of current file |
ctrl + u | move half screen up |
ctrl + d | move half screen down |
J | join line below with current line |
3J | join below two line with this line (not 3) |
z= | spell suggestion |
~ | change case of letter |
:digraphs | to see the list of symbols e.g. copyright etc. |
1.26. Block Visual Mode¶
Add same items in the beginning/end/middle of all the lines
Commands | Descriptions |
---|---|
crtl-v | select the block with cursor movement |
press I (insert before) or A (insert after) or c (replace) |
type the text -> press Esc -> block will be replaces by text |
1.27. Zoom Screen¶
Commands | Descriptions |
---|---|
Zoom in | crtl-+ |
Zoom out | ctrl– |
1.28. Save session¶
Commands | Descriptions |
---|---|
:mksession name.vim | save session |
:mksession! name.vim | override session |
:source name.vim | load session |
1.29. Folding¶
Use space (remapped in .vimrc) at the line below the function definition for folding/unfolding the code.
1.30. Plugins¶
First install ‘vundle’ using following command. Use ‘git-shell’ to run this command in Windows.
- git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim
- After that copy and paste the .vimrc file in the home directory (in Windows paste in the director C:/Users/<Username>/)
- Use double quote to comment/uncomment” the packages in .vimrc file e.g. ” Plugin ‘mattn/emmet-vim’ will not install the package “emmet-vim”. Or add some more packages in .vimrc file as required.
- After selecting the packages, open vim and run the command -> :PluginInstall and it will install the all the plugins.
- Use :help <plugin name> to see the list of operations.
1.30.1. NERDTree¶
Commands | Descriptions |
---|---|
NERDTree | turn on the directory structure |
NERDTree! | disable the directory structure |
m | then use various operations for delete, and create files. |
e.g | |
m-a meher | create a file with name meher |
m-a meher/ | create a folder with name meher |
1.30.2. Surround¶
Commands | Descriptions | Results |
---|---|---|
ysiw” | add “” to the word | Meher -> “Meher” |
ds” | delete surround quotes | “Meher” -> Meher |
cs[( or cs]) | change surround [] by () | [2+3]/2 -> (2+3)/2 |
cst<h1> | change <p> tag to <h1> | <p>Meher Krishna</p> -> <h1>Meher Krishna</h1> |
1.30.4. vim-table-mode¶
Follow the below steps to create the ‘rst-table’ in Vim,
- Enable/Disable table mode using ‘:TableModeEnable/TableModeDisable’ or using ‘:TableModeToggle’,
- Type column-names e.g. |Col1 | Col2| and press enter
- Then press | twice to create the table. Do the same to add more lines in the table.
- Also, go above the |Col1 | Col2| and press | twice (required for correct rst-table-format)
1.30.5. vim-extline¶
This is used to underline the text, which is required for making Headings in .rst document.
- Type the symbols (in insert mode) e.g. = and then press ctrl-l ctrl-l to complete it.
- Or press ctrl-l and then press the symbol,
- Or press ctrl-l and then press a number e.g. 1, 2 etc. This is autocomplete the underline base on heading levels.
- Some more commands are listed below,
Commands | Descriptions |
---|---|
ctrl-l ctrl-l | Auto-line update |
ctrl-l ctrl-h | Horizontal line update |
ctrl-l ctrl-u | Change to underlined title |
ctrl-l ctrl-o | Change to overlined title |
ctrl-l ctrl-i | Change to underlined and overlined title |
ctrl-l = or = ctrl-l | Force Section heading (with = as underline) |
ctrl-l 2 | Force Section heading (level 2) |
1.30.6. ConqureShell¶
Use :ConqueTermSplit to start the terminal in the Vim.
1.30.7. Airline¶
Airline theme plugin for better view e.g. display name of file, line number, column number etc.
The Vim way is to learn how to intentionally use the yank, delete and other registers. Once you know these, you will easily find your own key sequences to do this.
Register "0
is the yank register. Anything you yank will be put here, but neither deletes or change removals will ever touch register "0
.
So, in your example, you had just yanked a word. To replace a word with what you just yanked, you take advantage of deletions never touching the yank register. Move to the target word, delete it with dw
, then paste from your yank register with "0p
or better yet, cw
then ^R0
(which is repeatable).
The flip side to the yank register is the small deletions register "-
. Any small delete or change removal is put here, but yanks never touch "-
. A deletion counts as small if it is less than a full line.
Registers "1
—"9
are the large delete history registers. With "1
containing the latest large deletion or change removal, and "9
containing the oldest large deletion or change removal. Only deletes that aren’t small, i.e. deletes of one full line or more, get pushed onto "1
—"9
.
For any operation that changes a register, a copy is also always placed in the default, a.k.a. unnamed register ""
. This is the register used when you don’t explicitly name a register.
Register "_
is the black hole register, and it is always empty. If you delete to it, nothing in any register is changed at all, not even the default ""
register or the black hole register itself. The removed text is fully gone, apart from your undo history. Yanking to or pasting from the black hole register does essentially nothing.
The black hole register "_
lets you do things like first one small deletion, then a number of other deletions into "_
without changing your small deletions register "-
, then paste your first small deletion.
You are probably already familiar with the normal named registers, they are simply registers "a
—"z
, and you can use them as scratch space at will. If you refer to a named register by its capital form, "A
—"Z
, you will append to it rather than replace its contents.
Other registers are the last inserted register ".
, the filename registers "%
and "#
, the command register ":
, search register "/
and expression register "=
.
You can get a list of all these registers as well as their contents with the command :register
. Because it shows the current contents of the registers, the command is very useful to experiment with and learn what ends up where.