vim - text manipulation

Lower case Upper case

How to change lower case letters words to upper case words? How to change upper case words to lower case words?

You can change the case of text:

Toggle case "HellO" to "hELLo" with g~ then a movement (word or end of line).
Uppercase "HellO" to "HELLO" with gU then a movement (word or end of line).
Lowercase "HellO" to "hello" with gu then a movement (word or end of line).

Alternatively(easier to remember), you can visually select text then press ~ to toggle case, or U to convert to uppercase, or u to convert to lowercase.

Word and text manipulation

https://vim.fandom.com/wiki/Search_and_replace*substitute_last_search

WORD MANIPULATION:

Quickly change word or line : To quickly change a word you can use cw,caw (change a word) or ciw (change in word). Use c$ or just C to quickly change from the cursor to the end of a line, cc to change an entire line, or cis (change in sentense) for a sentence

command description
ea To append something to a word (at the end of the word)
dw (vw to select in visual mode) To delete a word along with the whitespace after the word
de (ve to select in visual mode) To delete a word but not the the whitespace after the word

TEXT SELECTION :

If you want to do the same thing to a collection of lines, like cut, copy, sort, or format, you first need to select the text. Get out of insert mode, hit one of the options below, and then move up or down a few lines. You should see the selected text highlighted.

command description
V selects entire lines
v selects range of text
ctrl-v selects columns
gv reselect block

After selecting the text, try d to cut/delete, or y to copy, or :s/match/replace/, or :center, or !sort, or… Move to cursor where you would like to paste. Press P to paste before the cursor, or p to paste after.

SEARCH AND REPLACE :


:1,$s/ABC/XYZ/g   and then press [Enter].

This vi command replaces every occurrence of ABC with XYZ on every line, and even when there are multiple occurrences on a line. Note that in this example, the “g” character at the end of the command means “global”. If you don’t use this “g” the tab character will only be replaced the first time it is seen on a line, but if you add the “g” at the end of the command every tab character in each line will be replaced.


How to select a word within Vim and replace it with something else?

(a quick search on the internet shows many ways to do this. but here is a simple way to do it)

:%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’.

Refer to this page for more examples


/ : Search
*/* : Search forward/back for word under cursor
command description
:%s/search for this/replace with this/ search whole file and replace
:%s/search for this/replace with this/c confirm each replace
1,$s/\t/ /g To convert each tab in the file to four spaces
:%s/\t/ /g How to replace all tabs with spaces

General tips for searching :

command description
/pattern search forward for pattern
?pattern search backward
n repeat forward search
N repeat backward
:set ignorecase case insensitive
:set smartcase use case if any caps used
:set incsearch show match as search proceeds
:set hlsearch search highlighting

More cool searching tricks:

command description
* search for word currently under cursor
g* search for partial word under cursor (repeat with n)
ctrl-o, ctrl-i go through jump locations
[I show lines with matching word under cursor

command description
:g/<pattern>/j To join lines within a pattern
:g/.*(underscore)(underscore)text.*/j To join the subsequent line with a line containing a certain text
:%s/{\(underscore)s.*(underscore)(underscore)text/{(underscore)(underscore)text/g Join two lines with a pattern ending on one line and a pattern beginning on the subsequent line. This looks for lines ending with “{” and a next line starting with the text (a wildcard) “(underscore)(underscore)text” and joins them into a single line.
:%s/’ ,/’,\r/g Replace each “’ },” in the current file by a new line
:{\(underscore)$\(underscore)s*(underscore)(underscore)prefix This searches for lines ending with `{` and a subsequent line starting with `(underscore)(underscore)prefix`.
:’,\(underscore)$\(underscore)s*(underscore)(underscore)text This searches for lines ending with `’,` and a subsequent line starting with `(underscore)(underscore)text`.
:%s/’,\(underscore)$\(underscore)s*(underscore)(underscore)text/’,(underscore)(underscore)text/g This searches for lines ending with `’,` and a subsequent line starting with `(underscore)(underscore)text` and joins the two lines together.
:%s/{\(underscore)$\(underscore)s*(underscore)(underscore)prefix/{(underscore)(underscore)prefix\g This searches for lines ending with `{` and a subsequent line starting with `(underscore)(underscore)prefix` and joins the two lines together.
:g/.*(underscore)(underscore)prefix.*(underscore)(underscore)text.* },\(underscore)$/normal! @a Record a macro in register a and play it on a pattern match.
:g/pattern to match/ s/text to search/text to replace/gc How to mix global command and replace command? Using the above command or variants of it, we can search for patterns in the entire file and do replace operations on those specific lines.

COUNTING WORDS OR PATTERNS

  • Count the number of occurrences of a word or pattern in the current file :

    (first use * on the word)

    after that, use the following command to get a count : %s///gn
    

    We are actually calling the :substitute command, but the n flag suppresses the usual behaviour. Instead of replacing each match witht the target, it simply counts the number of matches and then echoes the result below the command line. Do not omit any of the forward slashes. g stands for global (in the curent file).

    * Find all occurrences of a word in the current file and populate the quickfix list window:

    `:vim /pattern/ % | cw`
    

    ~ & -
    

    Repeat last substitution on current line


    Insert mode tips :

    gi - (incredibly handy) - goes to Insert mode where you left it last time
    

    e.g. scenario: edit something, exit Insert, go look at something else, then gi back to restart editing

    CTRL-T and CTRL-D (tab and de-tab)
    

    inserts or deletes one shiftwidth of indent at the start of the line


Insertion and replace

insert mode

command description
i a insert before, after cursor
I A insert at beginning, end of line
gI insert text in first column
o O open a new line below, above the current line
rc replace character under cursor with c
grc like r, but without affecting layout
R replace characters starting at the cursor
gR like R, but without affecting layout
cm change text of movement command m
cc or S change current line
C change to the end of line
s change one character and insert
~ switch case and advance cursor
g~m switch case of movement command m
gum gUm lowercase, uppercase text of movement m
<m >m shift left, right text of movement m
n<< n>> shift n lines left, right

Insert Mode

command description
^Vc ^Vn insert char c literally, decimal value n
^A insert previously inserted text
^@ same as ^A and stop insert → command mode
^Rx ^R^Rx insert content of register x, literally
^N ^P text completion before, after cursor
^W delete word before cursor
^U delete all inserted character in current line
^D ^T shift left, right one shift width
^Kc1c2 or c1←c2 enter digraph \c1,c2\
^Oc execute c in temporary command mode
^X^E ^X^Y scroll up, down
<esc> or ^[ abandon edition → command mode

Advanced Insertion

command description
g?m perform rot13 encoding on movement m
n^A n^X +n, -n to number under cursor
gqm format lines of movement m to fixed width
:rce w↵ center lines in range r to width w
:rle i↵ left align lines in range r with indent i
:rri w↵ right align lines in range r to width w
!mc↵ filter lines of movement m through command c
n!!c↵ filter n lines through command c
:r!c↵ filter range r lines through command c

Search and Substitution

command description
What to Type What it does
[i show first line containing word under the cursor
[I or ]I show every line containing word under the cursor
:g/pattern/ show every line matching the regular expression pattern

SEARCH & SUBSTITUTION

command description
/s↵ ?s↵ search forward, backward for s
/s/o↵ ?s?o↵ search fwd, bwd for s with offset o
n or /↵ repeat forward last search
N or ?↵ repeat backward last search
* * search backward, forward for word under cursor
g* g* same, but also find partial matches
gd gD local, global definition of symbol under cursor
:rs/f/t/x↵ substitute f by t in range r x: g-all occurrences, c-confirm changes
:rs x↵ repeat substitution with new r & x

SPECIAL CHARACTERS IN SEARCH PATTERNS

command description
. ^ $ any single character, start, end of line
\< \> start, end of word
[c1-c2] a single character in range c1..c2
[^c1-c2] a single character not in range
\i \k \I \K an identifier, keyword; excl. digits
\f \p \F \P a file name, printable char.; excl. digits
\s § a white space, a non-white space
\e \t \r \b <esc>, <tab>, <↵>, <←>
\= * \+ match 0..1, 0..∞, 1..∞ of preceding atoms
\(pipe) separate two branches ( ≡ or)
\( \) group patterns into an atom
\& \n the whole matched pattern, nth () group
\u \l next character made upper, lowercase
\c \C ignore, match case on next pattern

OFFSETS IN SEARCH COMMANDS

command description
n or +n n line downward in column 1
(minus)n n line upward in column 1
e+n e-n n characters right, left to end of match
s+n s-n n characters right, left to start of match
;sc execute search command sc next

Registers and copy and paste

COPY AND PASTE:

How to copy a line in vim and paste it in a different program (a browser or word document or email): shift v (to select the line) (") quotation mark to select a register (+) we want to select the + register y - to yank

Now, go to the other program and press Cntrol v to paste it.

In the same way, if we want to copy something from a broser, copy it there and go to vim: " (to select a register) + (to select the + register) p (to paste it)

When you copy something using the key ‘y’, go to a different location and delete a word in this location using the key ’d’, and try to paste the text that was yanked before using either ‘p’ or ‘P’, the deleted word gets inserted instead of the word that was yanked earlier. This is very annoying. The reason for this is that when a word is deleted using the key ’d’, it is also saved into the unnamed register, replacing the word that was originally yanked. When pasting text in the new location, paste it form the 0 (zero) register because, when a word is yanked, it is saved into the unnamed register and also the 0 register. But when a word is deleted using the key ’d’, it is only put into the unnamed register but not into the 0 register. Another way to paste the text without using registers at all is to visually select the text that you want to replace and use the key ‘p’ (to paste).


Issue with copying/pasting to/from system clipboard?

Be aware that copying/pasting from the system clipboard will not work if :echo has(‘clipboard’) returns 0. In this case, vim is not compiled with the +clipboard feature and you’ll have to install a different version or recompile it. Some linux distros supply a minimal vim installation by default, but generally if you install the vim-gtk or vim-gtk3 package you can get the extra features.


“Hello” is in the “a” register “world” is in the “b” register

How can I quickly type “Hello world”?


command description
“x use register x for next delete, yank, put
:reg↵ show the content of all registers
:reg x↵ show the content of registers x
ym yank the text of movement command m
yy or Y yank current line into register
p P put register after, before cursor position
]p [p like p, P with indent adjusted
gp gP like p, P leaving cursor after new text

UNDOING, REPEATING & REGISTERS

command description
u U undo last command, restore last changed line
. ^R repeat last changes, redo last undo
n. repeat last changes with count replaced by n
qc qC record, append typed characters in register c
q stop recording
@c execute the content of register c
@@ repeat previous @ command
:@c↵ execute register c as an Ex command
:rg/p/c↵ execute Ex command c on range r where pattern p matches

Copying and Moving Text

command description
“{a-zA-Z0-9.%*:-”} Use register {a-zA-Z0-9.%*:-”} for next delete, yank or put (use uppercase character to append with delete and yank) ({.%*:} only work with put).
:reg[isters] Display the contents of all numbered and named registers.
:reg[isters] {arg} Display the contents of the numbered and named registers that are mentioned in {arg}.
:di[splay] [arg] Same as :registers.
[“x]y{motion} Yank {motion} text [into register x].
[“x]yy Yank [count] lines [into register x]
[“x]Y yank [count] lines [into register x] (synonym for yy).
{Visual}[“x]y Yank the highlighted text [into register x] (for {Visual} see Selecting Text).
{Visual}[“x]Y Yank the highlighted lines [into register x]
:[range]y[ank] [x] Yank [range] lines [into register x].
:[range]y[ank] [x] {count} Yank {count} lines, starting with last line number in [range] (default: current line), [into register x].
[“x]p Put the text [from register x] after the cursor [count] times.
[“x]P Put the text [from register x] before the cursor [count] times.
[“x]gp Just like “p”, but leave the cursor just after the new text.
[“x]gP Just like “P”, but leave the cursor just after the new text.
:[line]pu[t] [x] Put the text [from register x] after [line] (default current line).
:[line]pu[t]! [x] Put the text [from register x] before [line] (default current line).

Non empty lines

To do something only to non-empty lines, use `:g/./` before the command. `:g/./ s/$/;/`

To do something only to the visually selected non-empty lines, use the same approach.

Reverse selected lines order in Vim

To reverse all the lines in a file

:global/^/move 0

Abbreviated:

:g/^/m0

Sorting lines alphabetically

Imagine you’re working in vim. You come across this code:

gem 'clearance', '1.0.0.rc4'
gem 'neat'
gem 'stripe'
gem 'pg'
gem 'thin'
gem 'rails', '3.2.11'
gem 'bourbon'
gem 'simple_form'
gem 'strong_parameters'

If you want to sort the list alphabetically, select the lines visually and run the command: `:sort`

That will result in this:

gem 'bourbon'
gem 'clearance', '1.0.0.rc4'
gem 'neat'
gem 'pg'
gem 'rails', '3.2.11'
gem 'simple_form'
gem 'stripe'
gem 'strong_parameters'
gem 'thin'

If you want to dig deeper into the sort functionality: :help sort

Vim Golf challenges

Add semicolons at the end of each non blank line

Add semicolons.

Simply add a semicolon at the end of each non-blank (non-empty) line;

Before

super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
Intent intent = getIntent()
String text = intent.getStringExtra("text")

TextView view = findViewById(R.id.textView2)
view.setText(text)

After

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent intent = getIntent();
String text = intent.getStringExtra("text");

TextView view = findViewById(R.id.textView2);
view.setText(text);

Answer

:g/./ s/$/;/

Prepend an asterisk to every non-blank line in the input file

Prepend an asterisk to every non-blank line in the input file.

Before

This is a
very short

file, but it is
still
full

of

surpises.
i

After

*This is a
*very short

*file, but it is
*still
*full

*of

*surpises.
*i

Answer

:g/./ s/^/*/

Breaking the command down:

  1. g - globally
  2. . - on all lines that are not blank (dot represents a non-blank character)
  3. s - replace command
  4. ^ - the beginning of the line

Indentation - Remove all spaces in front of these lines

Before

Example line
    This is part of the parsed line
    Thats goes one
End of line

After

Example line
This is part of the parsed line
Thats goes one
End of line

Answer

To format a line to the left I use :left. Use this format an entire file :%le

Insert white spaces before a line

Here’s one way to move selected text over a few spaces:

Before

- select a chunk of code using capital V and the arrow keys (or j, k)
- type colon
- then type s/^/   /
- hit return

After

- select a chunk of code using capital V and the arrow keys (or j, k)
- type colon
- then type s/^/   /
- hit return

What you’ve done is replace the beginning of each selected line (the ^ symbol means “the beginning of the line”) with spaces.

Insert a Column of Numbers

http://xahlee.info/emacs/emacs/emacs_string-rectangle_ascii-art.html

Insert sequence of numbers in a vertical column.

try change this

cat
dog
bird

to this

1 cat
2 dog
3 bird

TODO: This is pending

Insert A to Z Using rectangle-number-lines

try change this

cat
dog
bird

to this

A. cat
B. dog
C. bird

Solution:

TODO: This is pending

Tags

  1. vim - completion