Vi, Vim, Vscode editors
VI or VIM
This section describes both editors however these days vi command is an alias to vim. Therefore bear in mind although all have been tested the test itself was made on VIM.
- transpose 2 chars
xp :- current char with next one xP :- current char with previous one
- delete till space
d, t, space - d(elete) t(ill) space, but you can replace space with any printable character
- drop to bash
:!bash or :!sh
- edit other file
:e file.txt # autocomplite works
- redirect command STDOUT to the new line below the cursor
:r !ls
- show line number
:set number or :set nu
- Substitite find and replace in VI called substitute (ref. sed)
:%s/wily/trusty/g # substitute all ''wily'' with ''trusty'' in all document :s/wily/trusty/g # substitute only in the current line :%s/,/\r/g # CSV substitite ',' to '\r' carage return (aka newline)
- display only lines matching pattern :global command
:g/string-pattern-search/p # :g -global search, /p -print out on a screen :g/ERROR # display only lines with ERROR :g!/ERROR # don't display matching lines :v/ERROR # don't display matching lines
- Undo and redo
u -undo last change Ctrl-R -redo changes which were undone (undo the undos). '.' to repeat a previous change, at the current cursor position
- Visual mode
v -visual selection using arrows and navigation keys ^v -visual block selection, y-yank, d-delete, i-insert still work
- Multi-line insert in visual block selection
Press I to start a special form of insert mode, then type the wanted text (s:). When you press Esc to exit from insert mode, the text will be inserted in the same position on each of the lines affected by the visual block selection.
- Insert comments sign # at the begging each line between 10 and 12th line
:set number :10,12s/^/#
Set - configure current session
:set wrap or :set nowrap :- wrap text :set ruler :- enable ruler :set paste :- enable paste mode
Show current file name
Ctrl+g -shows the current file name 1, Ctrl+g -shows relative to vim full path. Press '1' then Ctrl+g
Delete all after : - Kubernetes manifest cleanup
# substitute, delete everything after ':' :3,21s/:.*/:/ # :normal solutions, these examples are for '.' :%norm )Dx :%norm $T.D :%norm f.C. :%norm 0/\. /e<C-v><CR>D
VIM only
Sort
- Sort IPv4 addresses
:%sort n /.*\./ | %sort n /\.\d\+\./ | %sort n /\./ | %sort n
Split screens, multiple windows (aka viewports)
vim -O|o file1 file2 file2 # open multiple files in the split window '-o' horizontal or '-O' vertical layout vim -O2 file* # open maximum 2 files in vsplit c^w,<nhjkl> :new # create a split window into a cursor direction C^w,s :split # horizontal split window C^w,v :vsplit # vertically split window C^w,c :close # close current window C^w,o :only # close all except current C^w,w # jump to next windows C^w,<n-lines>,- or +# shrink/large window by n lines (default: 1 line) C^w,<n-colum>,< or ># shrink/large window by n columns (default: 1 char-column) C^w,| # zoom horizontal C^w,<n-colum>,| # set current window width to N (default: widest possible) C^w,_ # zoom vertical C^w,<n-lines>,_ # set current window height to N (default: highest possible) C^w,= # same size for all windows # Unverified :wincmd j :- move to window below :wincmd k :- move to window above # All splits actions :qa # close all splits (viewports) - 'quit all' :wa # write all
convert tabs to spaces
# The expandtab property will ensure that when you hit tab it will actually use spaces set tabstop=2 shiftwidth=2 expandtab # Convert existing tabs to spaces :retab
Tabs (windows)
vim -p file1 file2 # -p[N] :- open a [N]umber of tabs, if omitted opens each file in own tab #Once Vim has been launched, there are many commands that directly create or close tabs: :tabnew/:tabc new tab open / close :tabedit {file} edit specified file in a new tab :tabfind {file} open a new tab with filename given, searching the 'path' to find it :tabclose close current tab :tabclose {i} close i-th tab :tabonly close all other tabs (show only the current tab) :tabn :tabp go to next/previous, the same as C^PgUp and C^PgDn
Lower or uppercase
Visual select the text, then U
for uppercase or u
for lowercase. To swap all casing in a visual selection, press ~
.
Without using a visual selection, gU<motion>
will make the characters in motion uppercase, or use gu<motion>
for lowercase. So: g~w
will change case of a word.
Spell chacking
Comma delimited, it means a sequence of keystrokes.
:set spell # enable spell checking :set spell spelllang=en # choose language z,= # show suggestions ],s / [,s # go to next (spelling) previous (spelling) mistype
Change colour of dark blue comments
You can do it manually with the command below, where ABCDEF is an appropriate colour hex code.
:hi Comment guifg=#ABCDEF
To make it permanent, add these lines to your ~/.vimrc file (using green as an example):
syntax on :highlight Comment ctermfg=green
Oneliner
echo "syntax on" >> ~/.vimrc && echo ":highlight Comment ctermfg=green" >> ~/.vimrc
Show special characters
:set list #and to unset -> :set nolist
Vimdiff - diff compare
Show differences of multiple files (up to 4) using vim
vimdiff file1 file2 vimdiff -O file1 file2 file3 # -o|O split horizontal|vertical
Comparison tools
user@server1:/etc/cups# sdiff cupsd.conf -RE cupsd.conf #side-by-side merge of file differences LogLevel debug LogLevel debug MaxLogSize 0 MaxLogSize 0 # Allow remote access # Allow remote access Port 631 Port 631 Listen /var/run/cups/cups.sock Listen /var/run/cups/cups.sock
Another tools:
- colourdiff - this takes the standard diff options like -y for side-by-side compare
Disable bell
- Turn off bell for bash
vi ~/.inputrc set bell-style none
- Turn off bell for vi
vi ~/.vimrc set visualbell set t_vb=
Remote edit
Vim allows edit a remote server files using scp://
protocol. This techics actually copies a file locally and when you save sends the edited file to the server.
vim scp://user@server//path/to/file.conf # Inside vim :e scp://user@server//path/to/file.conf
Vim plugins
- VimAwesome
- FUGITIVE.VIM - Git integration
- Syntastic - syntax and style checker that uses other plugins
- flake8 - Python syntax checker
- jedi-vim - Python autocompletion, use ctr+space
Vundle - plugin manager
Follow these steps to installe it Vundle Vim bundle/plugins manager. Just remember to comment out plugin examples otherwise it will not work. As an alternative you can use my .vimrc configuration file.
git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim
Use following commands inside Vim
:PluginList
- lists configured plugins:PluginInstall
- installs plugins; append `!` to update or just :PluginUpdate:PluginSearch foo
- searches for foo; append `!` to refresh local cache:PluginClean
- confirms removal of unused plugins; append `!` to auto-approve removal
Read more how to use Vim as Python IDE integrated development environment
my .vimrc
This is my Vim configuration file that uses Vundle as a package manager and has Python syntax autocomplete, checker and style
vim ~/.vimrc cat << 'EOF' > ~/.vimrc set nocompatible " be iMproved, required filetype off " required " set the runtime path to include Vundle and initialise set rtp+=~/.vim/bundle/Vundle.vim " set indent and pasting text set expandtab "affects what happens when you press TAB key, If 'expandtab' is set, "pressing the <TAB> key will always insert 'softtabstop' amount of "space characters. Otherwise, the amount of spaces inserted is minimized "by using TAB characters. set tabstop=2 "changes the width of the TAB character set shiftwidth=2 "affects what happens when you press >>, << or ==. "It also affects how automatic indentation works. set softtabstop=2 "affects what happens when you press the <TAB> or <BS> keys set noautoindent "copy the indentation from the previous line, when starting a new line set nosmartindent "automatically inserts one extra level of indentation in some cases set bg=dark set paste "set nowrap " Syntastic setting - basic settings for beginners set statusline+=%#warningmsg# set statusline+=%{SyntasticStatuslineFlag()} set statusline+=%* let g:syntastic_always_populate_loc_list = 1 let g:syntastic_auto_loc_list = 1 let g:syntastic_check_on_open = 1 let g:syntastic_check_on_wq = 0 "disable automatic syntax checking for Python, to allow flake8 do it via F7 or :call Flake8() let g:syntastic_mode_map = { 'passive_filetypes': ['python'] } call vundle#begin() " alternatively, pass a path where Vundle should install plugins " call vundle#begin('~/some/path/here') " let Vundle manage Vundle, required Plugin 'VundleVim/Vundle.vim' " Keep Plugin commands between vundle#begin/end. Plugin 'tpope/vim-fugitive' Plugin 'davidhalter/jedi-vim' "Plugin 'scrooloose/syntastic' Plugin 'vim-syntastic/syntastic' Plugin 'nvie/vim-flake8' " Python lintel Plugin 'glench/vim-jinja2-syntax' Plugin 'scrooloose/nerdtree' " usage :NERDTree then :? Plugin 'hashivim/vim-terraform' " All of your Plugins must be added before the following line call vundle#end() " required filetype plugin indent on " required " To ignore plugin indent changes, instead use: "filetype plugin on " see :h vundle for more details or wiki for FAQ " Put your non-Plugin stuff after this line EOF
Vim as IDE
XML Lintel - pretty
This solution is based on external tool called xmllint
that you can call from vim
using command :%!xmllint --format -
or ! xmllint --format -
in normal mode.
%
-scope full file-
-at the end of the command is for receiving standard input - which, in this case, is the selected text that vim sends toxmllint
sudo apt-get install libxml2-utils
Python
Python is going through transformation from ~2.7 to 3.6+ therefore over time starting around 2012 multiple transitional solutions have been used by Distro vendors to support both versions. Therefore something like syntax checking and highlighting configuration in Vim was also affected and fixes differs over time.
Ubuntu 18.04
- Syntastic is lintel for Python 2.x
- Flake8 is lintel for python 3.x
Install falke8
It is very important to install Flake8 on the correct version of Python for your needs. If you want Flake8 to properly parse new language features in Python 3.5 (for example), you need it to be installed on 3.5 for Flake8 to understand those features. In many ways, Flake8 is tied to the version of Python on which it runs.
python<version> -m pip install flake8
Make sure you have lines like below in your .vimrc
let g:syntastic_mode_map = { 'passive_filetypes': ['python'] } "disable automatic syntax checking for Python Plugin 'nvie/vim-flake8' "lintel, PEP8 indenting standard PEP8, syntax highlighter
Ubuntu before 16.04
Ubuntu comes with vim-tiny package that has most of things disabled, so get it uninstalled
sudo apt-get purge vim-tiny sudo apt-get install vim-nox-py2 #py2 support sudo apt-get install vim #py3 support vim --version | grep python #verify you should see eg: +python -python3
Optionally you may want to set alternatives
sudo update-alternatives --set vim /usr/bin/vim.nox-py2
Now, open vim and check :python import sys; print(sys.version)
you should see similar output
2.7.12 (default, Nov 19 2016, 06:48:10) [GCC 5.4.0 20160609]
Vscode
window management hotkeys:
Ctrl
+1
Focus into Left Editor GroupCtrl
+2
Focus into Side Editor GroupCtrl
+3
Focus into Right Editor GroupCtrl
+K
Ctrl+Left Focus into Editor Group on the LeftCtrl
+K
Ctrl+Right Focus into Editor Group on the Right
References
- Vim Cheat Sheet broken down into editor functionality
- PacVim – A Game That Teaches You Vim Commands & flake8 Python tool for style guide enforcement
- minimal-vim