Configuring Vim

Vim is a text editor that is difficult to get comfortable with, but once you have a set configuration that works for you it is very portable and powerful to use when editing files on remote hosts. Configuring vim requires taking a look at your local user's ~/.vimrc, and depending on the features you require, you may need to install and manage vim plugins.

For some context, vim users are classified as 'Light' and 'Dark' users. Dark vim users prefer heavy customization within the .vimrc and usually include multiple plugins often times carrying their own custom settings also stored in the ~/.vimrc. There is no right or wrong way to be here, it is just a matter of preference. As you will see below, I tend to enjoy modding out my vim sessions.

There are many forked versions of Vim created by dark users. I have personally not experimented with these, but they would be worth taking a look at should your needs surpass the configurations below.

Default Vim Unicode Input

To enter Vim's default Unicode input mode, ensure you are in <INSERT> mode and press <Ctrl>+V. Then proceed to enter your character code following the guidelines below -

# Vim character sequence prefix codes
a decimal number (0-255)
o then an octal number (o0-o377, i.e., 255 is the maximum value)
x then a hex number (x00-xFF, i.e., 255 is the maximum value)
u then a 4-hexchar Unicode sequence
U then an 8-hexchar Unicode sequence

So, if we wanted the stopwatch - f2f2 symbol from Font Awesome's Cheatsheet, we would enter <INSERT> mode within Vim and press <Ctrl>+V, followed by the character keypresses respective to our (4-char) unicode symbol - u+f+2+f+2.

Note that Vim will not change appearance or indicate that it is pending input for a character sequence, once pressing <Ctrl>+V within <INSERT> mode we are not prompted further. This is expected and if the sequence is done correctly Vim will input the Character specified by the sequence input, whether its decimal, octal, hex, or unicode, just be sure to use the appropriate prefix listed above

Custom .vimrc

Comments in .vimrc is as follows -

" Comments to describe what the line of code below does
"" Actual working code for the .vimrc file - could be uncommented and ran

If ~/.vimrc does not exist in your home directory, create it, and customize it to suit your needs. For example, the following .vimrc will set your tab size to 2 from the default 4, and convert your tabs to spaces automatically. This is useful when sharing code, as things are more compact and using spaces is less ambiguous than tab sizes across platforms.

set tabstop=2 shiftwidth=2 expandtab autoindent mouse=a

Here, tabstop is the tab size setting, measured in spaces. shiftwidth allows vim to compensate according to our tab settings when automatically indenting, etc. expandtab converts our tab size setting into actual spaces. set autoindent will set vim to automatically indent to our current depth when in insert mode and moving to a new line by pressing enter. This will not insert spaces unless text is input. mouse=a enables mouse interaction with split windows, when supported.

The ~/.vimrc can also include vim plugin settings, these are specific to the plugin they modify and are usually documented well within the plugin's repository.

Plugin Management

Vim stores plugins within ~/.vim/bundles/ and managing them is made simple using various vim plugin managers. See some of the repositories below for different options. Currently, I am using Pathogen, but there are many options that provide great solutions to vim plugin management.

I prefer Pathogen since it pairs well with Git submodules, but again, to each their own. Other plugin managers may pair well with git in their own ways as well. Consider the options below.

Pathogen plugin manager for Vim, allows for easy installation of useful plugins via git clone into a specified directory..
Don't like it? To uninstall Pathogen -

  • delete ~/.vim/autoload/pathogen.vim,

  • delete the lines you have added to ~/.vimrc.

Check out these alternatives

Plug
Vundle
Dein
And I'm sure there are more out there..

Plugins

The section below contains my notes on plugins that I use within Vim. Much like the other pages on knoats, these are just a collection of findings on the related plugins.

Unicode.vim Plugin

The plugin created by https://github.com/chrisbra/unicode.vim on GitHub adds easy support for Unicode characters, some of the useful commands can be seen below (Mostly taken from the official README.md within the plugin repository linked above)

Commands

These commands will be ran within Vim.

If you just installed the plugin, run the below to update your unicode tables, just to be sure you have the full list -

:DownloadUnicode - Download (or update) Unicode data
Searching Unicode Characters
:Digraphs        - Search for specific digraph char
:UnicodeSearch   - Search for specific unicode char
:UnicodeSearch!  - Search for specific unicode char (and add at current cursor position)
:UnicodeName     - Identify character under cursor (like ga command)
:UnicodeTable    - Print Unicode Table in new window
:DownloadUnicode - Download (or update) Unicode data
:UnicodeCache    - Create cache file
Digraphs / Tables
:Digraphs        - Search for specific digraph char

    :Digraphs

Outputs the digraph list in an easier way to read with coloring of the
digraphs. If a character has several digraphs, all will be shown, separated by
space.

If you want to display a list with a line break after each digraph, use the
bang attribute (Note, this output also contains the name in parentheses). >

    :Digraphs!

And if you want to display all digraphs matching a certain value, you can add
an argument to the command: >

    :Digraphs! A

displays all digraphs, that match 'A' (e.g. all that can be created with the
letter A or whose digraph matches the letter 'A'.)
Note: This is a silly example, that can take some time. You should always be
able to abort that by pressing |CTRL-C|. To output progress information, call
the command with the |:verbose| command modifier.

If you know the name, you can also search for the unicode name: >

    :Digraphs copy

will display all Digraphs, where their unicode name contains the word "copy"
(e.g. copyright symbol). Case is ignored. Note, you need at least to enter 2
characters.

:UnicodeTable    - Print Unicode Table in new window

See the unicode.vim official GitHub docs for more info

Code Completion in Vim

Check out https://github.com/xavierd/clang_complete/ for code completion. Instructions are within the README there.
This is dependent on the clang package / library. Install it using your package manager if you receive errors.
Be sure to edit your .vimrc to use clang_complete - instructions on the GitHub

If you use code-completion, you'll probably miss the tab function that usually brought up a context menu with code snippets. To use something similar, check out https://github.com/ervandew/supertab
This requires Pathogen.

A .vimrc running all of these modifications might look like the below -

" Set tabwidth=2, adjust Vim shiftwidth to the same
set tabstop=2 shiftwidth=2 

" expandtab inserts spaces instead of tabs
set expandtab 

" autindent inserts the next line at your current depth
set autoindent 

" mouse=a allows for mouse interaction with vim when supported
set mouse=a

" Enable Syntax Highlighting in Vim
syntax on

" Enable Pathogen plugin manager
execute pathogen#infect()
filetype plugin indent on

" Enable clang_complete plugin for vim
" https://github.com/xavierd/clang_complete
" Requires clang to be installed
" Path to library may change
let g:clang_library_path='/usr/lib64/libclang.so.8'

Backup Vim Configurations

To use vim to its full potential, its useful to stay organized when testing out different vim configurations, and providing yourself with a git repository to track your changes is a good way to do so. This way, should problems arise or should your system be lost for any reason, returning to your preferred setup is not a case a deja vu, but instead a planned restoration of your already backed up settings. This enables you to quickly establish your settings on a new host without over complicating the process or repeating steps across multiple hosts.

To create a git repository storing dotfiles, see information on stow. For an example on using stow with vim, see below. This same concept can generally be applied to any application that stores local user configurations, but it is very imporant to know exactly what changes will be applied when using stow as it will replace system files - stow(8)

At the very least, run a cp -r ~/.vim* ~/backup/vim/ from time to time.

Stow Backups

To backup vim configurations using stow, create the file structure like the below tree by copying your vim settings with cp -r ~/.vim* ~/backup/vim/

vim/
├── .vim
│   ├── autoload/
│   ├── bundle/
│   ├── colors/
│   ├── doc/
│   ├── .netrwhist
│   ├── plugin/
│   └── .VimballRecord
└── .vimrc

If the ~/backup/vim/ directories don't exist, create them. Once this has been created, from the ~/backup/ directory, run stow --adopt vim/. this will create a symbolic link to the configuration files and directories on your system, which enables you to edit the files within ~/backup/vim/ and the changes will reflect in the configurations stored within the parent ~/ directory. If these files or configurations already exist in the parent directory, stow will overwrite them. If they do not exist, they will be created / linked to the files in ~/backup/vim/.

This is a powerful tool when storing configurations in remote repositories, sometimes for various users or configurations based on distributions or window managers.

Personally, I prefer this method over writing a script to handle this manually, but since I did the work at writing the manual backup script, take a look below if you're interested in such a solution. I haven't revised it in quite a while, but it may at the very least provide some ideas.

Backup Scripts

I created a script that configures vim according to my preferred settings.

Feel free to tweak it to suit your needs, create your own, or find a better one somewhere else. If nothing else, you might get some ideas by reading through the script below -

Depending on your system, the script below attempts to globally configure vim's default settings

#!/bin/bash
## Author: Shaun Reed | Contact: shaunrd0@gmail.com | URL: www.shaunreed.com ##
## A custom bash script to configure vim with my preferred settings          ##
## Run as user with sudo within directory to store / stash .vimrc configs    ##
###############################################################################

# For easy colorization of printf
GREEN=$(tput setaf 2)
RED=$(tput setaf 1)
UNDERLINE=$(tput smul)
NORMAL=$(tput sgr0)


welcome=( "\nEnter 1 to configure vim with the Klips repository, any other value to exit." \
  "The up-to-date .vimrc config can be found here: https://github.com/shaunrd0/klips/tree/master/configs" \
  "${RED}Configuring Vim with this tool will update / upgrade your packages${NORMAL}\n\n")

printf '%b\n' "${welcome[@]}"
read cChoice

if [ $cChoice -eq 1 ] ; then
  
  printf "\nUpdating, upgrading required packages...\n"
  sudo apt -y update && sudo apt -y upgrade
  sudo apt install vim git 

  # Clone klips repository in a temp directory
  git clone https://github.com/shaunrd0/klips temp/
  # Relocate the files we need and remove the temp directory
  sudo mkdir -pv /etc/config-vim
  sudo cp -fruv temp/README.md /etc/config-vim/
  
  sudo cp -fruv temp/configs/ /etc/config-vim/
  
  rm -Rf temp/
  printf "\n${GREEN}Klips config files updated"
  printf "\nSee /etc/config-vim/README.md for more information.${NORMAL}\n\n"

  # Create backup dir for .vimrc
  sudo mkdir -pv /etc/config-vim/backup/
  printf "\n${GREEN}Backup directory created - /etc/config-vim/backup/${NORMAL}\n"

  # Set global vimrc defaults to klips settings
  sudo cp /etc/config-vim/configs/.vimrc /usr/share/vim/vimfiles/vimrc

  # Stash the current .vimrc
  sudo mv -bv ~/.vimrc /etc/config-vim/backup/
  printf "${RED}Your local .vimrc has been stashed in /etc/config-vim/backup/${NORMAL}\n\n"

  # Copy our cloned config into the user home directory
  sudo cp /etc/config-vim/configs/.vimrc ~/
  printf "${GREEN}New /usr/share/vim/vimfiles/rc configuration installed.${NORMAL}\n"

  # Reinstall Pathogen plugin manager for vim
  # https://github.com/tpope/vim-pathogen
  printf "\n${RED}Removing any previous installations of Pathogen...${NORMAL}\n"
  sudo rm -f /usr/share/vim/vimfiles/autoload/pathogen.vim
  
  # Install Pathogen
  printf "\n${GREEN}Installing Pathogen plugin manager for Vim....\n"
	printf "\nIf they don't exist, we will create the following directories:\n"
	printf  "/usr/share/vim/vimfiles//autoload/    ~/.vim/bundle/${NORMAL}"
  mkdir -pv /usr/share/vim/vimfiles/autoload /usr/share/vim/vimfiles/bundle && \
  sudo curl -LSso /usr/share/vim/vimfiles/autoload/pathogen.vim https://tpo.pe/pathogen.vim
  printf "\n${GREEN}Pathogen has been installed! Plugins plugins can now be easily installed.\n"\
         "Clone any plugin repositories into /usr/share/vim/vimfiles/bundles${NORMAL}\n"

  # Remove any plugins managed by this config tool (Klips)
  printf "\n${RED}Removing plugins installed by this tool...${NORMAL}\n"
  sudo rm -R /usr/share/vim/vimfiles/bundle/*

  # Clone plugin repos into pathogen plugin directory 
  printf "\n${GREEN}Installing updated plugins...${NORMAL}\n"
  git clone https://github.com/ervandew/supertab /usr/share/vim/vimfiles/bundle/supertab && \
  printf "\n${GREEN}Supertab plugin has been installed${NORMAL}\n\n" && \
  git clone https://github.com/xavierd/clang_complete /usr/share/vim/vimfiles/bundle/clang_complete && \
  printf "\n${GREEN}Clang Completion plugin has been installed${NORMAL}\n\n"
  vimConf=( "\n${UNDERLINE}Vim has been configured with the Klips repository.${NORMAL}" \
    "\nConfiguration Changes: " )
  printf '%b\n' "${vimConf[@]}"


else
printf "\nExiting..\n"
fi

sudo cat /etc/config-vim/configs/.vimrc-README