7 Reasons Why Developers Prefer NeoVim Over Vim

7 Reasons Why Developers Prefer NeoVim Over Vim

The Vim editor is a successor to the vi editor found on the original UNIX. As a fork of Vim, Neovim is an editor that aims to improve the quality of life for all developers, better than Vim.

Vim is an excellent choice for experienced sysadmins. However, NeoVim has gathered a significant following among developers.

Wondering why more developers are choosing NeoVim over Vim? As an ardent NeoVim user, I can think of the following reasons.

1: Project maintenance and feature improvements

You might be wondering “With Vim so popular, especially because of the ‘I can’t quit Vim’ memes, Vim would be the go-to choice for users. Why would someone fork Vim and risk wasting development time just so a dozen people use it?”

And that is a valid question. Vim is really popular! But that doesn’t mean that the community developing Vim is pleased with the state of the project itself.

There are two existing problems with Vim’s current codebase:

  • The lead developer of Vim has not been fostering the development of Vim as a community-friendly project. This argument is backed by features initially added to Neovim like async support, a built-in terminal emulator, and pop-up windows (for showing debug messages and auto-completion suggestions) which were later adopted into Vim due to community “pressure”.
  • The Vim codebase is less maintainable compared to Neovim.

2: Code auto-completion (LSP)

LSP or Language Server Protocol is a protocol that defines how an editor communicates with a “language server” to enable options like code highlighting, syntax checking, code completion, inlay hints, type hints, and much more.

No matter how good of a developer you are, getting type hints, error highlighting and more in the editor itself may not make you a better developer. Still, it will undoubtedly reduce your development and/or debugging time.

Neovim ships with out-of-box support for LSP and uses Lua for further configuration. Vim, however, needs an external plugin to achieve this functionality.

3: Support for better plugins

A plugin is something that plugs into an existing thing and adds a new feature to it. In this case, an editor plugin is something that plugs into the editor and provides more functionality.

Vim already has rich plugin support and also an ecosystem, so much so that there are plugin managers just for Vim!

How to Install and Use Vim Plugins
Vim’s functionality can be extended with plugins. Here is how you can install and use plugins in Vim. Also learn about updating and removing the plugins.
7 Reasons Why Developers Prefer NeoVim Over Vim

But Neovim one-ups Vim by allowing plugins to use a “more versatile language” to write plugins in Lua. Not that Vim’s built-in language was bad, but if you want IDE-like functionality, the setup will get complicated. And, with an actual programming language, this configuration is comparatively easier than Vim.

This means that you can extend or modify even core Neovim functionality.

Here is a list of plugins that are exclusively for Neovim because Vim does not offer a similar level of extensibility.

4: Parallel start up

I discussed above that Neovim uses Lua as an optional but additional language for plugin configuration. But did you know that Neovim starts each plugin in parallel?

This ought to make you feel even faster with Neovim, especially if you have plugins that take a few seconds to initialize!

5: Ability to embed the editor

Due to the codebase of the Neovim editor being comparatively easier to maintain than Vim, the possibility to embed the core editor into something else becomes a real possibility.

You can finally have a good editor in VS Code now 😎

6: Location of config file(s)

Having used Vim, when I needed to distro hop migrate to a new different Linux distribution, I would usually forget to take the backup of the ~/.vimrc file because it was not in my ~/.config directory.

Most of the modern Linux applications adhere to a standard called XDG (Cross Desktop Group). This standard defines various things but one of the most important things, in this case, is the location from where the application loads its config file(s).

This standard dictates that user-specific config files should be stored inside the ~/.config directory. Neovim adheres to this and the primary config file (init.nvim) is stored inside the ~/.config/nvim/ directory.

This is a minor nitpick but it weighs in highly when taking a backup of the important files on your computer.

7: Optimizations made in Neovim

Before I talk about optimizations, please note that both editors are fast enough that neither may feel faster than the other in day-to-day tasks. But I feel obliged to share this.

Neovim has several optimizations to how it reacts to user commands. For an example, take the following command:

:g/<pattern>/d

If you execute the above command in Vim, it will find all the lines with your specified regex pattern and delete those lines. That is not all that Vim will do. The d key also copies the deleted text to the register (clipboard).

This means, Vim will do the following:

  1. Find the line with the pattern
  2. Copy it to the register
  3. Delete the line
  4. Go to step 1 if there are other lines with matching pattern

If you do not want Step 2, you can use the following command in Vim:

:g/<pattern>/d _

The above command will do everything but copy the line to the register, speeding up the operation. Suppose you run the previous command (without the underscore) in Neovim. In that case, it will notice that you are trying to delete multiple lines and will use automatically “optimize” it by including the underscore.

Bonus: Better out-of-the-box configuration

This is somewhat of a personal opinion but if you are new to either Vim or Neovim, I would advise you to start your journey with Neovim. Both editors can be configured, but Neovim has better defaults.

For example, Neovim has the following knobs twisted by default:

  • autoindent is enabled by default
  • background defaults to “dark” unless explicitly set by the terminal
  • hlsearch (highlight all matches) is enabled by default

Though with newer releases of Vim, this may be subject to change as both editors are constantly evolving.

11 Pro Vim Tips to Get Better Editing Experience
You can learn plenty of Vim tips on your own, or you can learn it from others’ experiences.
7 Reasons Why Developers Prefer NeoVim Over Vim

Conclusion

Vim was created to improve the existing Vi editor. It stands for V Improved. Similarly, NeoVim was created to improve the existing Vim editor. It stands for New Vim.

I have been a Vim user for two years since I gave it a try and have happily migrated all of my Vim configurations to Neovim. This article outlines why someone might choose Neovim over traditional Vim.

Are you still using Vim? Do comment and let me know why! 🙂

🐧LHB Linux Digest #22.11: Concept of Links, Podman, Vim and More

🐧LHB Linux Digest #22.11: Concept of Links, Podman, Vim and More

Do you like the LHB Linux Digest newsletter? If yes, would you like to provide a 100-200 characters testimonial along with your name, country and job title (student, home user, self hoster, retired teacher, sysadmin with x years of experience etc)? You can concisely share what you like about the newsletter by replying to this email.

I plan to showcase some testimonials on the newsletter page (in works). It’s your chance to be famous! Just kidding 😉

💬 Let’s see what you have in this month’s issue:

  • All about links in Linux
  • Selected new articles on Linux Handbook
  • And the usual newsletter elements like memes, deals and nifty tool to discover

Navigating Up or Down a Page in Vim

Navigating Up or Down a Page in Vim

When you want to have an overview of a file, you can get a good overview just moving down a few pages.

To move a page down in Vim, press the Ctrl + f key combination, and to move a page up, press the Ctrl + b key combination.

  • Ctrl+f: Page down
  • Ctrl+b: Page up

If you want a more granular control, read along!

Moving Page Down

There are several ways you can move the cursor downwards in Vim.

You can move the cursor down one full screen or you can move it down only half the screen.

Page forward one screen

Page down is a common action to perform that moves down one full screen.

To move down one full screen, make sure you are in Normal mode and then press Ctrl + f key combination.

You can remember this thinking that the ‘f’ in “Ctrl + f” stands for forwards.

Alternatively,  you can also press the Page Down key on your keyboard (that is above the arrow keys).

This operation is also called a page forward operation.

Scroll forward half a screen

Sometimes it makes more sense to scroll down just a little bit.

In those cases, you can use the Ctrl + d key combination. Make sure you are in Normal mode before you press this key combination.

If you have trouble remembering this key combination, you can think of the ‘d’ in “Ctrl + d” as downwards.

This operation is also referred as a scroll forward operation.

Moving Page Up

Just like Page Down, there are several ways you can move the cursor in the upwards direction in Vim.

Either you move it one full screen up or move it half a screen up.

Page backwards one screen

Vim allows you to go up a full screen.

To scroll up a full screen, enter Normal mode and press the Ctrl + b key combination.

You can remember this by thinking that the ‘b’ in “Ctrl + b” stands for back[wards].

If present on your keyboard (usually above the arrow keys), you can make use of the Page Up keys to perform the same action as “Ctrl + b”.

This operation is also called a backwards scroll.

Scroll backwards half a screen

You can move half a screen in the upwards direction in Vim.

Scrolling up half a screen can be done by pressing the Ctrl + u key combination. Make sure you are in Normal mode before you press it, though.

If you have any trouble remembering this, think of the ‘u’ in “Ctrl + u” as up[wards].

This operation is referred as a backwards scroll operation.

Suggested reads 📖

This article mentions how you can scroll up or scroll down in Vim. Here are a few more related articles you should read:

If you are interested in learning more than just the Vim Basics, I highly recommend using this program by Jovica Ilic.

Mastering Vim Quickly – Jovica Ilic
Exiting Mastering Vim Quickly From WTF to OMG in no time
Navigating Up or Down a Page in Vim

11 Pro Vim Tips to Get Better Editing Experience

11 Pro Vim Tips to Get Better Editing Experience

The Vim editor is like an ocean – wonderful and joyful to be in, but there will always be things you don’t know.

While you cannot discover the ocean alone, you can always learn from others’ experiences.

I am sharing a few tips in this article that will help you use Vim like a pro.

I use them regularly and I have seen expert Vim users sharing them in various communities.

You should add them to your vimrc file, wherever applicable. You’ll have a better and smoother experience using the ever-versatile Vim editor. Trust me on this.

1: Always use the built-in help

I can not stress this enough. The biggest and least used tip is “RTFM” (Read the f**king manual).

Obviously, there is the Internet, humanity’s biggest collective resource for untapped knowledge, but what happens when Stack Overflow goes down?

Getting yourself habituated to Vim’s built-in help is the biggest favour you can do for yourself.

The syntax for looking at Vim’s internal help is as follows:

Prefix Example Context
: :help :w Help regarding the ‘:w’ command
none :help j Help regarding ‘j’ key in context to Normal mode
v_ :help v_J Help about using ‘J’ key in context to Visual mode
i_ :help i_<Esc> Help about using ‘Esc’ key in context to Insert mode
/ :help /n Help about search pattern ‘n’

2: Open as normal user, save as root user

In my memory of editing system files, you can easily forget adding sudo before editing a file in Vim. This opens a file in the ‘readonly’ mode. Meaning you can not write anything to it.

But you might have made some significant changes. And there might be no way of remembering every single edit you made. Hence, exiting with unsaved work is not an option.

11 Pro Vim Tips to Get Better Editing Experience

In those scenarios, type the following command in Vim:

:w !sudo tee %

Once you type this command, you will be asked for the password for sudo command. Enter that, and your changes will be saved.

💡
You should use the sudoedit command instead of sudo vim for editing files that require superuser privilages.

Let us break this down and understand what is happening here…

  • :w – This is the write command. Since no argument is given, Vim will write the whole file to standard output.
  • !sudo – Run the ‘sudo’ command as a shell command, not as a Vim command
  • tee – The ‘tee’ command is used to read from standard input and write it either to standard output or to a file
  • % – Vim substitutes this by the name of the current file that you are editing.

The :w command writes the whole file to STDOUT (standard output). Then, we use the sudo command (since what we are editing is a system file after all) to obtain temporary privilege.

The percent sign (%) represents our filename and the tee command takes Vim’s output from STDOUT and writes it to the % file.

This essentially works out to <Vim's STDOUT> | sudo tee /etc/ssh/sshd_config. A bit complex initially, but so is Vim 😉

3: Convert all spaces to tabs and vice-a-versa

We all have a preference for using either tabs or spaces over the other.

But what if you are editing an indented text file contradicting your preference?

3.1: Covert all spaces to tabs

When the current file is intended to use spaces, and you wish to convert them to tabs, there are two Vim commands that you need to run.

These two commands are as follows:

:set noexpandtab
:retab!

Doing so will convert all spaces to their equivalent of tabs. If the document uses two spaces as indentation width, they will be converted to 1 tab. If four spaces are used as a single indentation width, those four tabs will be replaced with one tab character.

3.2: Convert all tabs to spaces

If the file you are editing is intended with tabs and you want to convert the tabs to spaces, there are four Vim commands you must run.

:set expandtab
:set tabstop=4
:set shiftwidth=4
:retab

The first command (expandtab) tells Vim to expand tabs with spaces. The second command (tabstop) command how many spaces are used as one ‘indentation block’.

In our case, we are defining “1 tab = 4 spaces”. The shiftwidth command is used to control indentation when using >> operator, this too, is set to 4 spaces.

Finally, the retab command converts all tabs (that are used for indentation) to spaces.

4: Indent all lines

Wrongly indented lines can create havoc for Python and YAML programs.

To indent all lines, press the gg key to reach the top. Then press the = key to denote ‘indent’ and finally press the G key to denote ‘last line’.

Repeat with me; it is gg=G key combination to indent all lines.

This will automatically indent (to the best of Vim’s ability) all lines from the first line to the last line.

Below is a demonstration where I indent Rust code using the :gg=G command.

11 Pro Vim Tips to Get Better Editing Experience

As you can see (from this limited preview), all the lines are correctly indented.

The icing is that lines do not have to be wrongly indented to use Vim’s indentation.

5: Preserve indentation when you paste code

Admit it; we all have copy pasted code from the internet at least once. But what to do when the indentation gets messed up when you paste it?

To avoid that, add the following line to your .vimrc file:

set pastetoggle=<F2>

With this change to your vimrc file, press the F2 key before you paste code. Doing so will ensure that your code gets pasted with the correct indentation.

6: Start writing with the correct indent depth

This is a handy trick that I learned only recently. Suppose you are on the first column of a line, but what you write needs to be indented.

How do you do that in a smart way? Without pressing tabs/spaces?

The answer is to use the S key in Normal mode.

When you are on the first column of a line, enter the Normal mode by pressing Esc key. Then press the S (uppercase) key. This will move your cursor to the appropriate indent depth and automatically enter into Insert mode so that you can start typing.

11 Pro Vim Tips to Get Better Editing Experience

You can see, in this demonstration, my cursor was on the first column, and by pressing the S key, the cursor moved to the correct indent depth and Vim switched from Normal mode to Insert mode.

Pretty neat!

7: Show diff before saving the file

We have all been there. “I modified this file, but don’t know what I changed and now I am afraid the change will cause unexpected issues down the road.”

The remedy to this problem is to view the difference between the buffer and the file.

To do so, execute the following command in Vim itself:

:w !diff % -

Let’s break this down so you understand what is happening…

  • :w is the Vim command to save/write. In this particular scenario, where no file name is specified in the command, the output is written to the STDIN (standard input) file.
  • :!<command> is the syntax for executing a shell command. In our case, we are running the diff command in our shell.
  • % represents the name of the current file that is unmodified. Try this with :!echo %.
  • - is the STDIN file for the diff command.

So, this command first writes all the [unsaved] content to the STDIN file. Then the diff command reads the current file (%) and comparing it against the STDIN (-) file.

This command roughly equates to this shell command -> diff <original-file> <Vim's STDOUT>.

8: Show spelling mistakes

If you have been using only Vim ever since the beginning, good for you! But some people are also introduced to word processing software like Microsoft Word.

It has a feature (or a curse, for people with non-English names), where the spell-checker of MS Word places a red squiggly line under a misspelled word.

That feature might appear to be “missing” from Vim. Well, not exactly.

Vim has a spell checker built into it. You can enable it using the following command:

:set spell

Upon doing this, you might see misspelled words get highlighted. The way they are highlighted depends on your Vim color scheme. I get a white underline under misspelled words here.

11 Pro Vim Tips to Get Better Editing Experience

Your mileage may vary with the method of highlighting a word.

To make this the default Vim behaviour, you can add the following line to your .vimrc file:

set spell

9: Show line numbers

Like many Vim users, you might have tried to enable line numbers in Vim.

There are two methods to indicate the line numbers. One is Absolute line numbering. In this, you get the absolute number for each line, just like any other code editor or IDE.

The second is Relative line numbering. In this, the current line gets the number ‘0’ and every other line gets a relative number in context to the line on which the cursor is.

If you liked both, but had to make a tough choice of choosing one over the other, you are not alone. But you also don’t have to choose one over the other. You can have both!

You can enable “Hybrid line numbering” in Vim by adding the following line to your .vimrc:

set number relativenumber

This will show the absolute line number on the line with your cursor and relative line numbers for other lines.

Below is a screenshot demonstrating how it Hybrid line numbering works:

11 Pro Vim Tips to Get Better Editing Experience

Currently, my cursor is at the 44th line, so that line has the absolute line number. But the lines above and below my cursor have a relative number with respect to the line which has the cursor.

10: Open Vim with the cursor on a particular line

There might have been times in your past when you wanted to open Vim with the cursor set to a particular line instead of the first line.

This can be done by making use of the +linenum option. Below is the syntax to do so:

vim +linenum FILE

Replace the word linenum with an actual number.

11 Pro Vim Tips to Get Better Editing Experience

Here you can see that I open the /etc/ssh/sshd_config file with my cursor on the lines 20 and 50. That was done using the +linenum option.

11: Use readable color schemes

When it comes to using color schemes, people often choose the ones that they find most attractive or aethetically pleasing. But when you Vim as a code editor cum IDE, it is nice to give up some eye candy in favour of getting colorschemes with better visual guides.

A good colorscheme only looks good, but an excellent colorscheme helps you easily identify keywords, variables and other identifiers with the help of colors.

A few of my personal favorite colorschemes are as follows:

If you are not sure about how to use colorschemes in Vim, we have it covered on Linux Handbook 🙂

Bonus Tip: Delete text even when you are in Insert mode

We all know that you can use the d and x keys to delete text when you are in Normal mode. But what if you want something akin to dd in Insert mode?

In that case, below are a few key bindings that you can use:

  • Ctrl + w: Delete previous word (equivalent to db in Normal mode)
  • Ctrl + h: Delete previous character
  • Ctrl + u: Delete all the previous characters until the start of line (equivalent to d0 in Normal mode)
  • Ctrl + k: Delete all the leading characters until the end of line (equivalent to d$ in Normal mode)

Conclusion

I shared some of my favorite Vim tips. It involves things like indenting the whole file, getting a file diff before saving, opening a file with cursor at a particular line, and more…

Some are minor productivity pushes, while others – saving as root user – can be critical productivity boosters.

Comment and let me know which tip(s) you will be using. Is there any other cool Vim trick you are proud of? Share it with the rest of us.

Vim 9.0 Released with New Script Syntax, Popup Menu Command Completion

The popular Vim text editor released new major 9.0 version few days ago with many new features and large number of new features.

The new release introduced Vim9 script with drastic performance improvements. The execution speed can be increased via 10 to 100 times faster. However, function must be defined with def, and the argument and return types must be specified to benefit from the speed-up.

Legacy scripts will keep working as before. The new script syntax now looks a lot more like most programming languages. Line continuation does not require using a backslash; Function calls do not require call, assignments are done without let and expressions are evaluated without eval. And, comments now start with #.

Instead of the ‘wildmenu’ option, now a popup menu can be used in Vim 9 by setting “wildoptions’ to “pum”. Which, allows for showing many more command line completion matches. The updated colorschemes are also included in the release.

New options in the release including:

  • 'autoshelldir' change directory to the shell’s current directory
  • 'cdhome' change directory to the home directory by “:cd”
  • 'cinscopedecls' words that are recognized by ‘cino-g’
  • 'guiligatures' GTK GUI: ASCII characters that can form shapes
  • 'mousemoveevent' report mouse moves with
  • 'quickfixtextfunc' function for the text in the quickfix window
  • 'spelloptions' options for spell checking
  • 'thesaurusfunc' function to be used for thesaurus completion
  • 'xtermcodes' request terminal codes from an xterm

There are as well new ex commands, functions, variables and operators. See more about Vim 9 via its news page.

How to Get Vim 9 in Ubuntu Linux

Vim offers official AppImage package, along with the source tarball they are available to download at the link below:

There’s another universal Flatpak package available, though not updated at the moment of writing. For Windows, MacOS and other sources, go to vim.org/download.php

Split Vim Workspace Vertically or Horizontally

Split Vim Workspace Vertically or Horizontally

As you get comfortable with the basics of Vim and start exploring it even more deeply, you discover new things.

New things like splitting the screen while using Vim in a terminal. No need of tmux or screen. Just do it under Vim, natively.

Yes, Vim allows you to have multiple horizontal or vertical splits in your active workspace.

Let me show you how to split Vim and all the necessary keyboard shortcuts to navigate between the split windows.  

Create split window

Suppose you opened a file in Vim. Now you want to split the workspace into multiple windows for better productivity. Let’s go over how to create a split window in Vim.

There are two ways you can split a Vim workspace – horizontally and/or vertically.

You can know which window is active based on which window has your cursor.

Split window vertically

Assume that you have opened a file in Vim, and you want to split the screen vertically.

To make a vertical split, enter Normal mode, and run the following command:

:vsplit [file_path]
Split Vim Workspace Vertically or Horizontally

If you specify a file path, it will open the file in the newly split window, otherwise, the newly split window will open the same file.

A shorter command to vsplit is vs (you can specify a file path with vs as well).

As an alternative way to create a vertical split, you can press the Ctrl + w key combination, and lastly, press the letter “v” (v for vertical split).

Split window horizontally

Vim allows you to split the window horizontally as well.

To make a horizontal split, enter Normal mode, and run the following command:

:split [file_path]
Split Vim Workspace Vertically or Horizontally

If you specify a file path, it will open the file in the newly split window, otherwise the newly split window will open the same file.

A shorter command to perform a horizontal split is to use the sp command. It also accepts a file path.

If you are wondering if any key combination exists for creating a horizontal split window, yes. It is “Ctrl + w” and then press the letter “s“.

Close split windows

There are several ways you can close/quit an active split window.

  • :q[uit] – close the current window and the buffer as well
  • :bd[elete] – unload the current buffer and then close the current window
  • :on[ly] – close all other windows but leave all buffers open
Split Vim Workspace Vertically or Horizontally

Consider the following scenario, I have the Vim workspace divided into four quadrants.

Below are the four operations you can perform and the key combinations.

  • Move to the split window on the left: press Ctrl + w and press h
  • Move to the split window on the down: press Ctrl + w and press j
  • Move to the split window on the up: press Ctrl + w and press k
  • Move to the split window on the right: press Ctrl + w and press l

Resizing split windows

By default, Vim creates splits with a similar width/height. It is good for my OCD, but not really productive when I have a file that I edit most of the time and another file that I rarely edit.

So, let’s go over how you can resize the split windows in Vim.

Resize window

To resize a window, use either of the following methods:

  • Press Ctrl + w key combination [optionally specify a number] and then press the “+” (plus) symbol to increase the height of the current window
  • Press Ctrl + w key combination [optionally specify a number] and then press the “” (minus) symbol to reduce the height of current window
  • Press Ctrl + w key combination [optionally specify a number] and then press the “<” (greater than) symbol to reduce the width of the current window
  • Press Ctrl + w key combination [optionally specify a number] and then press the “>” (less than) symbol to increase the width of the current window
Split Vim Workspace Vertically or Horizontally

Expand the window as much as possible

Below are the key combinations that you can press to expand a vertically split window vertically or a horizontally split window horizontally.

  • Expand vertically – press Ctrl + w and then press the pipe “|” character (the character which gets typed when you press the backslash key while holding down Shift)
  • Expand horizontally – press Ctrl + w and then press “_
Split Vim Workspace Vertically or Horizontally

Reset the size of all resized windows

To reset the size of all split windows, press Ctrl + w and then “=“. This will resize all the windows and make them equal.

Split Vim Workspace Vertically or Horizontally

More tips to improve your workflow

Let’s go over some tips that I think you might find useful with a workflow that includes creating multiple split windows in a Vim workspace.

Open a new file/buffer

This will open the same file in newly split window. To open another file in new window, use either :e or :open command followed by the file name to make the window split actually usable.

Copy and paste

This is not actually a tip, but when you copy or cut something from a split window and move to another window and try to paste, it will work. No additional configuration is necessary.

Remap keys

If you look closely at navigating between active windows, it is similar to moving your cursor’s direction. Except, there is a need to press “Ctrl + w” every time and then press either h,j,k,l keys.

Below is what I personally use. Instead of pressing “Ctrl + w” and then pressing h,j,k,l keys, you can simply press “Ctrl + [h,j,k,l]”.

If you want to use these key combinations, add the following keys to your ‘vimrc’:

nnoremap <C-J> <C-W><C-J>
nnoremap <C-K> <C-W><C-K>
nnoremap <C-L> <C-W><C-L>
nnoremap <C-H> <C-W><C-H>

Splitting tweaks

By default, when you create a vertically split window, it will open to the left. To change this default behavior, add the following line to your ‘vimrc’.

set splitright

Similarly, if you create a new horizontally split window, it will open on the topmost portion of the Vim workspace. To make a new horizontally split window open on the bottom of current window, add the following line to your ‘vimrc’.

set splitbelow

Conclusion

This article covers how you can create one or more horizontal or vertical splits in an active Vim workspace. We also go over how you can resize split windows, close an active split window and how to navigate between open windows.

Interested in more advanced Vim topics? Go for this highly recommended Vim course.

Mastering Vim Quickly – Jovica Ilic
Exiting Mastering Vim Quickly From WTF to OMG in no time
Split Vim Workspace Vertically or Horizontally

Set Indentation Width to 2 or 4 Spaces (or Tab) in Vim

Set Indentation Width to 2 or 4 Spaces (or Tab) in Vim

Vim is one of the most popular terminal-based text editors for decades.

But no matter how long you have been using Vim, there are always more tips and tricks that you did not know about.

This one is about setting up indentation width in Vim to 2 spaces or 4 spaces. This is particularly helpful if you are a programmer, a Python one especially.

In your vimrc file (located at ~/.vimrc), add the following line to automatically use 2 spaces instead of tab in Vim.

set autoindent expandtab tabstop=2 shiftwidth=2

Don’t worry. I’ll go through it in detail.

Set automatic indentation

Imagine you are writing a line of code and the next line of code needs to be indented, you press the Enter key to go to the next line but the indentation is not applied automatically.

This can be very annoying. To automatically indent lines, add the following line to your ‘vimrc’.

set autoindent

Once you have this saved in your ‘vimrc’, it will enable automatic indentation in your vim session no matter the programming or scripting language that you use.

Use spaces for indenting

If you want to use spaces for indenting your code, add the following lines to your ‘.vimrc’ file.

set expandtab
set tabstop=<NUM OF SPACES>
set shiftwidth=<NUM OF SPACES>
  • The first line enables expandtab option in Vim. This option makes sure that spaces are used for indenting lines, even when you press the ‘Tab’ key.
  • The second option tabstop takes a numerical value. Let’s say I typed set tabstop=2, this will insert 2 spaces for a line indent.
  • Finally, the third option, shiftwidth manages the indentation when you use the ‘>>’ or ‘<<‘ operators to add or remove indentation to an already existing line/block of code.

I would suggest using 2 or 4 for tabstop and shiftwidth values.

I also recommend that you use the same values for tabstop and shiftwidth. Using different values might mess up your indentation.

Here is what indented code looks like in Vim:

Set Indentation Width to 2 or 4 Spaces (or Tab) in Vim
💡
In rare cases, if you need to use the tab character, pressing the ‘Tab’ key will not work with expandtab enabled. To use the tab character, use the ‘Ctrl + V’ key combination and then type the tab character.

Vice versa: Use tabs for indentation

Serving to people standing on both sides of ‘tabs vs spaces’, let’s now look at how you can use a tab character for indenting instead of spaces.

Add the following lines to your ‘vimrc’:

set noexpandtab
set tabstop=4
set shiftwidth=4

The only difference in these 3 lines for your vimrc to use tabs instead of spaces is the usage of noexpandtab instead of expandtab. The noexpandtab option prevents the conversion of tabs to spaces.

Conclusion

All the above works for new files. To convert tabs to spaces in the currently opened file in Vim, enter the Normal mode by pressing Esc key. Now use the retab command by pressing the ‘:’ (colon) character and Vim will convert the existing tabs to spaces.

The war of tabs vs spaces aside, this tutorial aims at helping you set the indentation to whatever your preference might be.

If you are interested in learning more than just the Vim Basics, use this program by Jovica Ilic.

Mastering Vim Quickly – Jovica Ilic
Exiting Mastering Vim Quickly From WTF to OMG in no time
Set Indentation Width to 2 or 4 Spaces (or Tab) in Vim

Move Cursor to Beginning or End of Line in Vim

Move Cursor to Beginning or End of Line in Vim

Vim is one of the most glorified text editors, and for a reason.

Every task that you can think of (except for typing the text) can be done with just a few keystrokes – without ever touching the mouse or trackpad.

Moving your cursor from the beginning or the end of the line is not a crucial task, but something you might be doing often enough for the repeated mashing of h or l keys to feel irritating, or worse, unproductive.

Thankfully, it can be easily done in Vim. Here’s how.

  • Press the Esc key to be in the normal mode.
  • Press the 0 key to move the cursor to the beginning of the line (column 0)
  • Press $ key to move the cursor to the end of the line (last column).

Let’s take a deeper look at how we can move the cursor from anywhere on the line to the beginning of the line or to the end of the line.

Move the cursor to the beginning of the line in Vim

In Vim, there are two ways you can move your cursor at the beginning of a line.

First, make sure that you are in Normal mode. Press the Esc key to make sure.

Then press either 0 (zero) key and it will move the cursor at the beginning of the line.

You can move the cursor to the beginning by pressing the ^ key as well.

Move the cursor to the end of the line in Vim

Vim has a straightforward way to move the cursor to the end of the line.

Again, you need to be in Normal mode to do this.

It does not matter in which column your cursor, only which line it is on. Then, press the $ key and it will move the cursor to the end of the line.

If the lines are wrapped, the cursor will go to the end of the wrapped line, not to the end of the column.

Conclusion

This article delves into the basics of cursor movement in Vim. Even trivial things like moving to the start or end of a line in Vim could be tiresome if you don’t know the correct key combinations. But that’s how Vim is.

On a related topic, you may like reading about moving to the beginning or end of a file in Vim.

If you are interested in learning more than just the Vim Basics, I highly recommend using this program by Jovica Ilic.

Mastering Vim Quickly – Jovica Ilic
Exiting Mastering Vim Quickly From WTF to OMG in no time
Move Cursor to Beginning or End of Line in Vim