home about
blog 2017 2018 2019
tech android linux vim

vim tips

Some various vim tips I've found helpful over the years.

Contents

Count instances of string

To count the instances of a string in a buffer:

:%s/pattern to match//gn 34 matches on 13 lines.

To match in just a visual block of the buffer, select the text desired, then

:s/pattern to match//gn

Counting number of words

To count the number of words in the current buffer:

g ctl+g

To count the number of words in a block, select the block (for example, type V5j to select 6 lines) and then press the same combination.

The output looks like this:

Selected 6 of 358 Lines; 37 of 2281 Words; 186 of 13426 Bytes

Delete to character

If you want to delete all characters/words on a line up until a specific character, you can use

dtX

where X is the character you want to delete.

Example: A list of email addresses, where I want to delete the names before the "@domain" portion:

"Meredith Parker" <meredith.parker@companyname.com>,
"Randy Barrette" <randy.barrette@companyname.com>,

To delete, place the cursor at row 0 on the first line, and type: dt< Move down a line, and type: dt<

This removes all the names, quotes, etc, but leaves the rest of the lines. (The gt/lt signs and commas can be removed with regex: :%s/^<//g & :%s/>\,//g )

Find and replace a newline in vim

On Linux, this doesn't really make sense, since \n is considered a "null" character by vim. It does consider "\r" to be a return, but you can't use that instead, or you get even stranger results.

What you can do, is use the "magic" control sequence, which is ctrl+v by default.

So, to replace a space with newlines, you would do something like this:

:s/\ /

:s/\ /^M

This sequence is confusing, and tough to remember, so here it is again, all on one line:

:s/\ /ctrl+v<CR>/g<CR>

Happy replacements!

Force specific file text format

If you have a file with ^M spaces at the end from macOS it can be annoying (and break diff-ing capability).

Try this to solve the issue:

vim file.txt

:set ff=unix

:wq

This sets the fileformat (ff) to the unix type, and strips non-conforming control characters.

You can reverse this or change to any encoding you wish. The common ones are (self explanatory):

Format text or comments to fixed width paragraphs

To do this, use the gq shortcut (no colon or leader is required).

Explanation

A paragraph of text that is over the 79-character length will be reduced in length to a shorter 79-character limit, allowing you to automatically format comments, or other pieces of text that are too long.

To do this, select the paragraph(s) you wish to format with the visual selection (V), then type gq.

If the above is run on the above two paragraphs, the following is created:

New Text

A paragraph of text that is over the 79-character length will be reduced in
length to a shorter 79-character limit, allowing you to automatically format
comments, or other pieces of text that are too long.

To do this, select the paragraph(s) you wish to format with the visual
selection (V), then type "gq".

To do this, select the paragraph(s) you wish to format with the visual selection (V), then type "gq".

It should also work with comments like the ones below by setting this:

:set comments=:##  
                   \ 
                     Note trailing spaces!!

And then using V to select the below...:

Old Text

##  Script by Lunix409 <lunix409@gmail.com>

##  Written with the intention of providing a brief synopsis of current system stats for a unix-type system without having to leave the CLI or string a series of unrelated commands together.

##  It should work in OS X, Linux and probably Cygwin.  Other systems will probably not work without modification to the script.  I know for a fact FreeBSD will NOT work without a total-rewrite!  I know because I tried and gave up after a few hours.

##  Note that not all features are supported on all OS types.  In particular, the Cygwin version is missing a lot of functionality because it's just plain slow when using the full feature-set.  (Not sure if that's because of Perl or the fact that Cygwin is basically a hack.  Cygwin is also "broken" in a lot of other ways that make full implementation difficult at best.)

we can then type gq to produce the following:

New Text

##  Script by Lunix409 <lunix409@gmail.com>

##  Written with the intention of providing a brief synopsis of current system
##  stats for a unix-type system without having to leave the CLI or string a
##  series of unrelated commands together.

##  It should work in OS X, Linux and probably Cygwin.  Other systems will
##  probably not work without modification to the script.  I know for a fact
##  FreeBSD will NOT work without a total-rewrite!  I know because I tried and
##  gave up after a few hours.

##  Note that not all features are supported on all OS types.  In particular,
##  the Cygwin version is missing a lot of functionality because it's just
##  plain slow when using the full feature-set.  (Not sure if that's because of
##  Perl or the fact that Cygwin is basically a hack.  Cygwin is also "broken"
##  in a lot of other ways that make full implementation difficult at best.)

Increment or decrement numbers

All numbers in buffer

This should increment all number words by +1:

:s/\d\+/\=submatch(0)+1/g

Obviously you can do the reverse with -1.

Single numbers

If you only wish to increment or decrement the number under your cursor in the buffer, it's simpler to use ctrl+a and crtl+x. (Note that if you are using GNU Screen, you'll need to use ctrl+a a instead (that's "control+a", then release, and "a" a second time).

Indent or un-indent

You can indent or reverse-indent a line without exiting insert mode with ctrl+t or ctrl+d, respectively.

Jump to position relative to buffer viewport

Sometimes you want to move your cursor relative to the view of your buffer without moving the contents.

You may do that with these single capital letters:

Reverse all lines in buffer

To reverse all lines in the open buffer:

:g/^/m0

Sort all lines selected

To sort all lines currently selected (via visual block selection, typically):

:%sort

Spell check in vim

Some distros require aspell or similar to be installed. If you have a decent vim environment the following will enable spell check highlighting:

:set spell

Obviously :set nospell turns it back off again.

Here are some other things you can do.

Go directly to the next misspelled word:

]s

Previous:

[s

Show suggestions (on a highlighted word):

z=

Add a word you don't want highlighted:

zg

Splits

Open a few files in splits with one command:

$ vim -o file1.txt file2.txt [etc]

In vim, open a second file in current buffer using vertical split:

:vs file2.txt

In vim, change from horizontal splits to vertical:

C-W t C-W H

In vim, change from vertical splits to horizontal:

C-W t C-W K

Change to the next split in the session:

ctrl+w then a direction letter or arrow key motion

Strip trailing white space

There's nothing more annoying that trailing white-space in a file causing diffs to fail or other frustrations.

Strip them out with:

:%s/\s\+$//e

Undo and redo

Undo: u

Redo: ctrl+r

Simple find/replace for entire buffer

:%s/find/replace/g

Add command output to buffer

Write the contents of ~ (home directory) to your vim buffer:

:r ! ls -l /home/lunix

Print only the filenames of the above output:

:r!find $HOME -maxdepth 1 -type f | sed s/\.\\///

Use the pipe (|) as you would from bash to do redirection, etc.

Write buffer if you opened the file without correct permissions

We've all done it: opened a file and edited it quite drastically and gotten it perfect, only to realise we should have used sudo first.

Here's how to get around that, assuming you're in the sudoers file already:

:w !sudo tee %





© 1995-2019 clover