0% found this document useful (0 votes)
46 views19 pages

General Terminal Commands::cd:pwd

A cheat sheet of useful vim commands for beginners

Uploaded by

infinity9151
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views19 pages

General Terminal Commands::cd:pwd

A cheat sheet of useful vim commands for beginners

Uploaded by

infinity9151
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

In this note we will see all the cool features within vanilla Vim and Neovim.

These can be achieved using plugins but for now we are using native vim/ nvim
features for the simple reason being they have negligible overhead and need no
custom configuration.

General Terminal Commands


We can :cd to change directory, :pwd to print present working directory or any
other command we wish.
• :e <filename> would open a new file and :tabe <filename> would open
a new file in a new tab. We may use C^ + 6 to toggle through our files
(with 2 files open).
• gt would switch between the files in forward direction and gTwould toggle
in backwards direction.
• In Vim, :messages is a command that displays all of the messages that
have been printed during the current session. This includes information,
warnings, errors, and other output that Vim has shown us as we’ve been
working.

Vim Grep
Vim-grep is a grep feature built into Vim and Neovim. It is blazingly fast
and uses minimal system resources. Extremely useful while working on large
projects.

Using vimgrep
• vimgrep <query> **/*.<fileextension> will search all files recursively
and for the <query> get us the files ending with the specified extension.
We can obviously grep for other patterns as well to suit our needs.
• We will be sent to the first result of our search after doing the above
process at a blazingly fast speed. Now, we press :clist to make a list of
all the results in a register in nvim.
• To toggle through the list we press :cn for next, and :cp for previous
search results :cfirst jumps to the very first search result and :clast
jumps to the very last one. Now we can successfully toggle throughout
the vim-grep searches at our own pace and liking.
[!tip] For larger and more complex patterns we delimit using
forward slashes. E.g. :vimgrep /crazy complex pattern/
**/*.<extension>

1
Vim Native Autocomplete
Vim and Neovim have built in autocomplete which suggests code based off of
existing code from current file and files within the directory while in Insert Mode
. To enable it type the first few letters of whatever we want to do followed by
C-N (Ctrl + N) or C-P (Ctrl + P) to do it in reverse order.

String Search within Nvim


• To search for patterns or strings within vim, use /<word> followed by
return and this will take us to the first occurrence of the word. we can
press n to jump to the next occurrence of the word and N to jump to the
previous occurrence.
• ? <word> would also do the same but in reverse order (bottom to top
search). n will take us back (towards the top) and Nwould take us towards
the bottom of our search results.
• We can also hover the cursor over a word and press * asterisk to search for
all occurrences of that word in our file and toggle thorough using n and N.
[!note] Use :noh to remove the highlights after a search until the
next search.
• The following command will match all lines containing either foo or bar
and execute whatever follows:
[!danger] :g/foo\|bar/
• :g – This is the global command, which means ”execute the following
command on all lines that match the given pattern.”
• \| – This is the ”or” operator in Vim’s regular expression syntax. It
matches either the pattern on the left or the pattern on the right.
Typically, this command would be followed by another operation, such as delet-
ing lines, replacing text, or performing an action on the matched lines, like
so:
• :g/foo\|bar/d – Deletes lines containing ”foo” or ”bar”.
• :g/our_word|the_other_word/s/foo/bar/ – Replaces ”foo” with ”bar” in
all lines containing ”our_word” or ”the_other_word”.

More Specific Searching


At times we might be interested in searching for more than one word, let’s say

2
two words one after the another. We can run the following command for that:
:/foo\+ another_word
• \+ – This is a special pattern in Vim that means ”one or more occurrences”
of the preceding character or group. In this case, it means ”one or more
occurrences of the letter ’o’ in ’foo’”. So, foo\+ would match not just ”foo”
but also ”fooo”, ”foooo”, etc. The \+ modifies the previous character, so
it allows for one or more repetitions of ”o” after ”f”.

If we’re searching in a text file, the following lines would match:

• "foo another_word"
• "fooo another_word"
• "foooo another_word"
But this would not match:

• "foo bar another_word"


• "f another_word"

Deleting All Empty Lines


We can get rid of all blank lines in Vim using the following command:

:^\s*$/d

• ^: This anchors the pattern to the beginning of the line. It matches the
start of a line.
• \s*:

– \s is a regular expression (regex) symbol that matches any white-


space character (spaces, tabs, etc.).
– * is a quantifier that means ”zero or more occurrences.” So, \s*
matches any line that contains only white-space characters or is com-
pletely empty.
• $: This anchors the pattern to the end of the line. Together with ^ and
\s*, it ensures that the entire line consists only of white-space or is empty.

3
• /d: This is the action part of the command. The d stands for ”delete,”
meaning that all lines matching the pattern will be deleted.
• dE — Delete up to the end of the current word (not including the word’s
last character).
• dW — Delete to the end of the current word, including punctuation (similar
to the above, but for more general ”word” boundaries).
• dF<char> — Delete up to (and including) the first occurrence of <char>
to the left of the cursor.
• dT<char> — Delete up to (but not including) the first occurrence of
<char> to the left of the cursor.
• d/<char> — Delete up to the next occurrence of <char> forward in the
document. (Press n to repeat the search.)
• d? — Delete up to the previous occurrence of a character backward (press
N to repeat the search).

Repeating the Last Change


After making an edit, we can redo the entire action by pressing . (dot) while
in Normal Mode.

Interchanging two letters with two key strokes:

• Let’s say we did a /<> instead of </>, we can switch the two characters
by :

– Pressing x-p both in lowercase, one after another. Make sure the
cursor is at the beginning of the first letter for this however.
• x in Nvim and vim is used to delete a single character, whereas d is used in
motions to delete single character or entire document or just the selected
parts.

4
Vertical Visual Mode
• Vim also can use multiple cursors. It is achieved through a vertical visual
mode or what is properly referred to as Visual-Block Mode. Simply
press C-v (Control + v) in Normal Mode to enter the mode.
• Vim can also do arithmetic. Let’s say we have to increment or decrement a
variable parameter across a larger portion. We could select the parameter
using the visual block mode and increment (using C-a ) or decrement it
(using C-x).
Example:

a = 0
b = 1
c = 2
d = 3

Inserting and Appending using Visual Block Select

• We can add things before and after a block of text using visual block select.
Let’s say we want to add some markdown tag before and after a block.
To add let’s say bold, before the block we can visual select the first line of
the entire block using C-v, and then go to the bottom, then go into insert
mode using I (uppercase - i), type the_tag and press esc.
• To add after the block, select the whole text block in visual block mode
or just press gv to highlight the last selected text, press $ to go to the end
of the line and then press A to append towards the end, I to go to insert
mode, type closing_tag and hit esc. It will insert the closing tag into
every selected line.

[!warning] Make sure to proceed from left to right while adding the
tags, else it may mess up sequence of the tag in the latter lines.

• Pressing g-C-a would increment them serially. and g-C-x would decre-
ment them incresingly. So 0, 0, 0 would become 1,2,3 upon using g-C-a.

5
Changing the Direction for Selection in Visual Mode
It greatly helps to select or deselect when the direction change in visual mode.
To do this we just need to press - o while using visual mode.

[!tip] Moreover, if we want to retrace our steps, maybe because we


made a mistake or maybe we want to change something, we could
hit C-o (control + o), and it would go back to the lines we made
changes to, C-i to move forward.

Navigation Using ’g’.


Often times in Vim while navigating through text we’d see after pressing j a
couple of lines the cursor would move to the end of paragraph. It is intended
that way but if we want to traverse line by line, we could use:

• gj instead of just j. Same for k, use gk.


• _underscore (and ^ too ) moves the cursor to the beginning of a line and
$ towards the end. We could use g0, g^ and g$ for the same. 0 moves
the cursor to the beginning character of the line (0th one) which could be
a white space.
• If we press gv the cursor jumps to the previously selected text in visual
mode and it gets highlighted again.
• ~ will switch capitalization of whatever letter the cursor is on. g~ would
do it for only one line.

[!note] When we’re in Normal Mode and place the cursor over a
keyword (like a function or variable), gd will take us to the definition
of that symbol in the current file. It’s useful for quickly jumping to
the place where a symbol is defined.

• We can return to the previous location in the file by using the Ctrl-o.
This will take we back to where we were before jumping to the definition

6
Opening a File in the Documents
If we have a filename in a document opened in vim or nvim or even a path
leading to a file, we can open it as a buffer in nvim using :gf.

file_name

~/.config/file_name

• If we hover the cursor over the filename and press gf it will open the said
file on a new buffer and jump to it.
• Press the carat ^ to return to the previous file.
• Note that g here represents more of go and not global like its usual usage
in substitutions and capitalization. gf is more like go file.

Conjoining Lines
If we have text as a list and we want to conjoin them into a single line, we could
do it by:

• Pressing J (uppercase J) in Normal Mode. This will join the current and
the next lines into a single line with a space between every joined element.
• To do the above action but without spaces, we could use gJ and it would
achieve the same.

Substitutions and Changes


We already know how to substitute throughout the document using :

7
• :%s/<word_to_replace>/<word_replacing>/gc to choose where to
change.
• However if we run the same command without the % it would just
replace the text on the selected (or the line where the cursor is
on).:s/<word_to_be_replaced>/<word_repacing_it>/g. We don’t
need the c as we want it to be replaced. s here stands for substitute.
• g& would run the previously substitution command we ran on a single line
on the entire document.
• To change a word inside parenthesis or braces or apostrophes use ci" to
change inside apostrophe, ci{ for braces. ca" will change things around
the apostrophe (that is inside the apostrophe and including the apostro-
phe). c here stands for change.

Important Distinction Between ’c’, ’s’ and ’r’ in Vim.

Usage of ’c’
• The c command in Vim is used for changing (or substituting) a text
object, such as a word, line, or selection.
• It deletes the specified text and puts we in insert mode to type a new
replacement.
– cw (change word): Deletes the word under the cursor and lets we
type a replacement.
– c$ (change to end of line): Deletes from the cursor position to the
end of the line and lets we insert new text.
– cc (change line): Deletes the entire line and puts we in insert mode.

• The s command is used for substituting the character under the


cursor with new text.
• After pressing s, it deletes the character under the cursor and places we
in insert mode to type a replacement.

• The r command in Vim allows we to replace a single character under


the cursor with another character. It does not put us in insert mode
however.
• It does not work for words or patterns.

8
Standard Text Object Commands:

1. Select inside parentheses ():

• vib (Visual mode inside parentheses)


• vi( (Visual mode inside parentheses)
2. Select inside braces {}:

• viB (Visual mode inside braces)


• vib works with regular braces as well
3. Select inside square brackets []:

• vib (Visual mode inside square brackets)


• vi[ (Visual mode inside square brackets)
4. Select inside angle brackets <>:

• vi< (Visual mode inside angle brackets)


5. Select inside quotes (single/double):

• vi' (Visual mode inside single quotes)


• vi" (Visual mode inside double quotes)

Motion-based Commands (for navigating around objects):

• To jump to the next matching parenthesis, brace, bracket, or


quote:

– % (Move between matching pairs)

Other Useful Commands:

• Select a complete block:

– vab (Visual mode around braces)


– vaB (Visual mode around braces, including braces themselves)
• Select a word inside parentheses:

– viw (Visual mode inside word)

9
Native Spell Check for English
Vim has a native spell checker for English. We can activate it in command
mode using :set spell and it would spell check the document and underline
the errors. This is more for traditional writing than coding.
To deactivate this or any command in vim, use set no<command_name>. So for
spell check it would be, :set nospell. :set spell! would also work.

Vim motions as Commands


We could use vim motions as commands. Select the text we want the command
to alter. Then do :norm <vim_motion> or :normal <vim_motion>. Example.

sample
sample
sample
sample

:norm Ivar= <press CR (enter) to execute>


# result

var=sample
var=sample
var=sample
var=sample

Auto and Manual Indentation


• In Neovim, when we select text in Visual Mode and press ’=’ (the in-
dent command), it will indent the selected text automatically to preset
standards withing Neovim.

10
• To manually indent, in normal mode press > to indent and < to unindent.

Navigation using w vs W.
We know pressing w takes us to the next word being separated by some delimiter.
However W would ignore all the delimiters except white-space and then jump
to the next word.

Jumping to Open-Close Pairs of Parenthesis


• % when pressed in Normal Mode with cursor over a parenthesis (),
bracket [] or brace {} jumps to its matching pair.

Invoking Commands/ Scripts

Running Shell Commands Inside Our Document


To invoke a command within our document, we can use a method similar to how
commands are executed in a terminal, by prefixing them with a ! symbol. This
syntax allows us to run shell commands directly from our document, which
is particularly useful for interacting with the filesystem, running scripts, or
performing other system-level operations.
For example, if we type :!ls in command mode, it will execute the ls command
(a common command for listing directories and files) in our current working
directory. The output will appear in a buffer, allowing us to interact with it
further.
Here’s how we can make use of the output:

11
1. Viewing the Output:
When we run a command like :!ls, the output (the list of files and direc-
tories) will be displayed in a separate buffer. We can scroll through this
buffer to inspect the results.
2. Yanking the Output:
If we want to copy the result of the command (for example, the list of
files), we can yank it into our clipboard or Vim’s internal registers.
In Vim, we can use the y command (yank) to copy the content into our
register. For example, after executing :!ls, we can visually select the
output and press y to yank it.
3. Dismissing the Output:
If we no longer need the output and wish to discard it, we can simply close
the buffer where the command’s output was shown.
We can use :q to quit the buffer or :bd (buffer delete) to remove it from
the buffer list.
4. Redirecting Output to a File:
We can also redirect the output of our command to a file directly from
within our document. For example, :!ls > file_list.txt would save
the list of files into a file named file_list.txt in our current directory.
5. Combining Commands:
We can chain multiple commands together. For instance, :!ls && echo
"Done" will first list the files and then print ”Done” to the output.
6. Custom Commands:
We can create our own custom shell commands and use them in this way.
For example, :!python3 script.py can run a Python script and show
the output directly within the editor.
By using :!, we can integrate our document more fluidly with system commands
and scripts, enabling powerful workflows directly from our editing environment.

Creating Dynamic Snippets

1. LuaSnip Nodes
LuaSnip snippets are composed of various nodes, each serving a specific purpose:

• Text Node (t): Inserts static text.

12
• Insert Node (i): Represents a placeholder for user input.
• Choice Node (c): Provides multiple options for the user to choose from.
• Dynamic Node (d): Generates content dynamically based on context
or functions.
• Function Node (f): Executes a Lua function to produce content.

2. Creating a Basic Dynamic Snippet


Here’s how to create a dynamic snippet that inserts a function definition with
placeholders:

local ls = require'luasnip'

ls.snippets = {
all = {
ls.parser.parse_snippet("func", "function ${1:name}(${2:args})\n ${3:body}\nend"),
},
}

3. Using Dynamic Nodes


Dynamic nodes allow for more complex behaviors, such as generating content
based on the current file type or other conditions.

local ls = require'luasnip'

ls.snippets = {
all = {
ls.snippet("date", {
ls.text_node("Today's date is "),
ls.function_node(function()
return os.date("%Y-%m-%d")
end, {}),
}),
},
}

13
4. Additional Resources
For more examples and advanced configurations, refer to the official LuaSnip
documentation and community resources:

• LuaSnip GitHub Repository


• LuaSnip Examples
• From UltiSnips to LuaSnip: A Comprehensive Guide

Using the Native Vim File Explorer


• Vim natively has a file explorer Netrw which is not very fancy but does
the job.
• It can be invoked using Nvim <directory name> Or :e <filename> from
inside Vim.
• :e filename – Opens the file named filename for editing. If the file
already exists, it will open it; if it doesn’t exist, Vim will create a new file
with that name.
• If we run :e without specifying a filename, Vim will try to open the current
file again, which can be useful to reload the file if it has been modified
outside of Vim.
• Also use :e! to forcefully reload a file, discarding any unsaved changes in
the current buffer.

Output of a Command in Vim


• We can directly get the output of a terminal command in vim. Go into
command mode and type: :r!<terminal_command>.
• E.g. : :r! ls, :r!cat filename.txt etc.
• Note that we would get the output in text form directly into our document.
• Another similar feature is using !! from Normal Mode. This will put us in
command mode with :.! already as input. We can then use a command

14
such as :.!date and it would print the current date. Time could also be
obtained.
• Let’s say we have a shell command in a document (ls ~/.config/nvim
for example). We can directly execute it inside Vim. For that we need to:

– Hover the cursor over the line the command is on.


– Use !!sh and press enter. We’d get the output instead of the com-
mand now.

Sorting in Vim
To sort a list of numbers or things in vim, we can select the list using Visual
Select and then use: !sort.

• Note that this will sort them in ascending order by default.


• To perform, this in descending order use: !sort -r and press enter. The
-r flag here represents reverse. This will automatically insert '<,'> to
indicate the range of the selected text.

Splitting Window in Vim

Horizontal Split

• To split screen and open two documents in Vim simultaneously, use: :sp
<name of other document to open> if we want the current document
and one other document open in split view.
• To quit the split view press ZQ in Normal Mode. or :q! works too if we
want to quit without saving.

15
Vertical Split
• For vertical split, use: :vs <file_name> to open the current and other
file in vertical split mode.

Additional Info
• We can move between split windows using Ctrl-w followed by h, j, k, or
l to move left, down, up, or right respectively.
• To close a split window, use :q (in Normal Mode).

Moving the Current File to a New Directory

• To move the current file to a new directory, use: :w path/to/new/directory

Putting Vim into Background and Bringing it


Back to Foreground
A lot of the times, we may want to use the terminal, but not close Vim. We
can suspend Vim by pressing - C-z while in Normal Mode.
Do whatever we want to on the terminal and then press fg and press enter to
get back to Vim right where we left.

Creating a Persistent Vim Session


We may want to create a persistent session of our Vim session. It can be done
as follows: + Enter command mode and type :mksession <filename>.vim
and then exit out of vim. We’d see a file being created with our filename with
extension .vim. That is our session saved. + We can reopen Vim later on and
reattach to our session using :source <filename>.vim and enter to reattach
to the session.

16
Opening a URL
We can open a URL under our cursor in our document on our browser
straight from Vim without copy-pasting the link.

• Just hover the cursor over the URL in Normal Mode and press gx.
• gf does the same but for file paths.

Marking a Location and Jumping to and Fro in Vim

1. Marking a Location To mark a specific location in a file, use the m


command followed by a lowercase or uppercase letter. Lowercase letters mark
temporary locations, while uppercase letters mark more permanent locations.
• Example: To mark a location with the letter a, position the cursor where
we want to mark, then type:
ma
This will create a mark named a at the current cursor position.

2. Jumping to a Mark To jump to a specific mark, use the backtick (`) or


apostrophe (') followed by the mark letter.
• Backtick (‘): Jumps to the exact position of the mark, including the
exact column.
– Example: To jump to mark a:
`a
• Apostrophe (’): Jumps to the beginning of the line where the mark is
placed.
– Example: To jump to mark a:
'a

3. Listing Marks We can also list all marks in the current file with the
command:
:marks
This will show all the marks set within the file and their corresponding positions.

17
4. Deleting Marks To remove a specific mark, use the command:
:delmarks a
This will delete the mark a. We can also delete multiple marks by listing them,
e.g., :delmarks a b c.

5. Jumping Back and Forth We can quickly jump back to the previous
mark we visited using the following:
• (backtick-backtick): This takes us to the exact position of the last
mark.
• '' (apostrophe-apostrophe): This takes us to the beginning of the line
of the last mark.
This makes navigating between marked locations in the file quite easy.

A Basic Built-In Cipher in Vim


• Vim has a basic built in cipher that shifts the selected text by 13 alphabets.
• To do it, select the text we want to shift in Visual Mode. Then press g?.
This shift them 13 alphabetical places.

Generating Random Bytes Inside Vim


• We can read data from any buffer when in Vim using the :read command;
here we’ll read from the random byte generator present in all Unix based
systems.
• Use :read !head -c 100 /dev/urandom This will read the first 100 bytes
from /dev/urandom file.

Vim and HTML


Vim’s built in File Explorer Netrw can browse through and download basic
HTML sites using libcurl. It’ll open the HTML source in Vim.
• Simply use :e <url for the HTTP site>. :e is used to open a new file
in Netrw.
We can also convert any file into and HTML file in Vim.
• Simply open the file and type :TOhtml and press enter.
• Now we can open the file in our browser and it will have the same format-
ting and syntax highlighting as it did in our editor.

18
Converting a File to a Hex
• We can convert an entire file into a hex dump using :%!xxd . To revert it
back, use :%!xxd -r.

Ex mode
Reminiscent of the old school Vi, there is a way to emulate it in Vim. Simply
press Q in Normal Mode*. + To exit Ex mode type visual.

19

You might also like