Table of Contents
#NAVIGATION
@SEE:
8 Essential Vim Editor Navigation Fundamentals
- k – navigate upwards
- j – navigate downwards
- l – navigate right side
- h – navigate left side
- 0 – go to the starting of the current line.
- ^ – go to the first non blank character of the line.
- $ – go to the end of the current line.
- g_ – go to the last non blank character of the line.
- H – Go to the first line of current screen.
- M – Go to the middle line of current screen.
- L – Go to the last line of current screen.
- ctrl+f – Jump forward one full screen.
- ctrl+b – Jump backwards one full screen
- ctrl+d – Jump forward (down) a half screen
- ctrl+u – Jump back (up) one half screen
- e – go to the end of the current word.
- E – go to the end of the current WORD.
- b – go to the previous (before) word.
- B – go to the previous (before) WORD.
- w – go to the next word.
- W – go to the next WORD.
- { – Go to the beginning of the current paragraph. By pressing { again and again move to the previous paragraph beginnings.
- } – Go to the end of the current paragraph. By pressing } again and again move to the next paragraph end, and again.
- N% – Go to the Nth percentage line of the file.
- NG – Go to the Nth line of the file.
- G – Go to the end of the file.
- `” – Go to the position where you were in NORMAL MODE while last closing the file.
- `^ – Go to the position where you were in INSERT MODE while last closing the file.
- g – Go to the beginning of the file.
- % – Go to the matching braces, or parenthesis inside code.
- Use ‘.’ to repeat the last command.
The command will be repeated considering the current caret position.
#CMDS – COMPLEMENTARY
Vu Lowercase line
VU Uppercase line
g~~ Invert case
vEU Switch word to uppercase
vE~ Modify word case
ggguG Set all text to lowercase
:set ignorecase Ignore case in searches
:set smartcase Ignore case in searches excepted if an uppercase letter is used
:%s/\<./\u&/g Sets first letter of each word to uppercase
:%s/\<./\l&/g Sets first letter of each word to lowercase
:%s/.*/\u& Sets first letter of each line to uppercase
:%s/.*/\l& Sets first letter of each line to lowercase
:1,10 w outfile Saves lines 1 to 10 in outfile
:1,10 w >> outfile Appends lines 1 to 10 to outfile
:r infile Insert the content of infile
:23r infile Insert the content of infile under line 23
Vim +N filename: Go to the Nth line of the file after opening it.
vim +10 /etc/passwd
Vim +/pattern filename: Go to the particular pattern’s line inside the file, first occurrence from first. In the following example, it will open the README file and jump to the first occurrence of the word “install”.
vim +/install README
Vim +?patten filename: Go to the particular pattern’s line inside the file, first occurrence from last. In the following example, it will open the README file and jump to the last occurrence of the word “bug”.
vim +?bug README
#validating the punctuation matching
Type ‘%’ over the char to find its matcher: ( [ {
The vim lights a caret to its respective closing matcher character.
#WINDOWS SPLITTING
:split to split window
:q close the current window
:^Wj move to the botton window
:^Wk move to the upper window
:q! close the window that contains the cursor
:e filename Edit filename in current window
:split filename Split the window and open filename
ctrl-w up arrow Puts cursor in top window
ctrl-w ctrl-w Puts cursor in next window
ctrl-w_ Maximise current window
ctrl-w= Gives the same size to all windows
10 ctrl-w+ Add 10 lines to current window
:vsplit file Split window vertically
:sview file Same as :split in readonly mode
:hide Close current window
nly Close all windows, excepted current
:b 2 Open #2 in this window
#AUTO-COMPLETION
Ctrl+n Ctrl+p (in insert mode) Complete word
Ctrl+x Ctrl+l Complete line
:set dictionary=dict Define dict as a dictionnary
Ctrl+x Ctrl+k Complete with dictionnary
#SEARCH
- /i – Search for a pattern which will you take you to the next occurrence of it.
- ?i – Search for a pattern which will you take you to the previous occurrence of it.
- * – Go to the next occurrence of the current word under the cursor.
- # – Go to the previous occurrence of the current word under the cursor.
set hls = (hlsearch) highligh search
set is = (incsearch) incremental search – show result while you’re typing.
set magic/nomagic =
the first is the default option, the second generates expressions with too much scapes
characters not useful to other programs. Use the default.
:/ or 😕 = search
n = next ocurrence
shift + n = prior ocurrence
:s/// = replacement
. = present line
$ = last line
% = all file.
:s/a/b/g = change all ‘a’ by ‘b’ in the line.
:1,5s/^/#/ = comment the first 5 lines.
:.,$s/^/#/ = comment up to the end of the line.
:1,$s/^/#/ comment up to the end of the file
:%s/^.//g deletes the first letter of each line
:%s/^./\u&/c turns to uppercase the first char.
:%s/^./\l&/c turns to lowercase the first char.
Notes:
The ‘c’ at the end of the command, produces a prompt to confirm the operation.
The ‘p’ prints line after switching.
The ‘g’ switches all occurrences.
Check other modifiers typing: :help :s_flags
#IGNORE – NON SENSITIVE CASE
%s/foo/fooo/gi = set ignore case
Dynamic search: under ESC mode type: /string_to_search (not using ” : mode”). Then press enter to go the found string.
#cw
Searching and switching with next and cw:
1. Set caret on the word to be searched and switched.
2. Esc, cw, type the replacement.
3. On Esc mode, type ‘n’ (next)
4. Found the word, type ‘.’ (dot).
5. Go to step 3 until no more occurrences.
#Commands and regex examples:
slash: / the scape is: \/ (it’s not a ‘v’ letter, but a slash plus a backslash)
backslash \ : the scape is: \\
SHIFT * over the word (note the expression generated and copy to do it manually if necessary)
:# searches all matches to the string pointed by caret
:/word Search ?word? from top to bottom
:?word Search ?word? from bottom to top
n repeat the last command
:t(char) searches char on the line ahead caret pos
:T(char) searches char on the line behind caret pos
:; repeats the last command to t or T forward caret pos
:, repeats the last command to t or T forward caret pos
:s/a/b/ searches the first occurrence on line and switches a by b.
:s/a/b/g searches the all occurrences on line and switches a by b.
:%s/a/b/g searches the all occurrances on text and switches a by b.
/jo[ha]n Search ?john? or ?joan?
/\< the Search ?the?, ?theatre? or ?then?
/the\> Search ?the? or ?breathe?
/\< the\> Search ?the?
/\< ?.\> Search all words of 4 letters
/\/ Search ?fred? but not ?alfred? or ?frederick?
/fred\|joe Search ?fred? or ?joe?
/\<\d\d\d\d\> Search exactly 4 digits
/^\n\{3} Find 3 empty lines
:bufdo /searchstr/ Search in all open files
Ctrl+a Increment number under the cursor
Ctrl+x Decrement number under cursor
ggVGg? Change text to Rot13
#MARKS
To mark initial position – set the cursor on the position out of Insert mode and type ‘m’ and the mark name(mMARK).
Example: mq (makes a mark identified by ‘q’).
To mark final position: command’mark_letter
to move use d’mark_letter (or c)
to copy use y’mark_letter
to paste use just p.
Example:
#copying a block
select the 1st position and type: m’a
go to the last position and type: a’y
go to the new position where the block is supposed to be copied to and type: p
d’q (deletes from the mark ‘q’ to the end position (current caret pos)).
y’q (copies from the mark ‘q’ to the end position (current caret pos)).
Navigating using marks:
‘mark_letter
Example:
‘r (goes to mark r)
mk Marks current position as k
‘k Moves cursor to mark k
d’k Delete all until mark k
#REPLACING
Switches the first double hashes (‘##’) by one.
Notice that the slashes (‘/’) were substituted by colons.
158 # enable this line if using txt2html pre-parsing, and disable the line above it
159 #done < “$TEMP”
160
~
:158,159s:^##:#:
The search and replace function is accomplished with the :s command.
It is commonly used in combination with ranges or the :g command (below).
:s/pattern/string/flags Replace pattern with string according to flags.
g Flag – Replace all occurrences of pattern
c Flag – Confirm replaces.
& Repeat last :s command
%s/replaced/replacement/g (%..g – replaces across full text)
Suppose you want to change the last slash on this command switching to backslash: | sed “s/ù/ù” /.
Issue the following command:
:%s/[/]$/\\/g
Replacing Examples:
:%s/old/new/g Replace all occurences of ?old? by ?new? in file
:%s/old/new/gw Replace all occurences with confirmation
:2,35s/old/new/g Replace all occurences between lines 2 and 35
:5,$s/old/new/g Replace all occurences from line 5 to EOF
:%s/^/hello/g Replace the begining of each line by ?hello?
:%s/$/Harry/g Replace the end of each line by ?Harry?
:%s/onward/forward/gi Replace ?onward? by ?forward? , case unsensitive
:%s/ *$//g Delete all white spaces
:g/string/d Delete all lines containing ?string?
:v/string/d Delete all lines containing which didn’t contain ?string?
:s/Bill/Steve/ Replace the first occurence of ?Bill? by ?Steve? in current line
:s/Bill/Steve/g Replace ?Bill? by ?Steve? in current line
:%s/Bill/Steve/g Replace ?Bill? by ?Steve? in all the file
:%s/\r//g Delete DOS carriage returns (^M)
:%s/\r/\r/g Transform DOS carriage returns in returns
:%s#<[^>]\+>##g Delete HTML tags but keeps text
:%s/^\(.*\)\n\1$/\1/ Delete lines which appears twice
@SEE:
vim.wikia.com/wiki/Search_patterns
vimregex.com/
vim.wikia.com/wiki/Search_patterns
#syntax
:range s[ubstitute]/pattern/string/cgiI
For each line in the range replace a match of the pattern with the string where:
c Confirm each substitution
g Replace all occurrences in the line (without g – only first).
i Ignore case for the pattern.
I Don’t ignore case for the pattern.
#replace str or substring
:s/vi/VIM/g
:1,5 s/^/#/ = comment the first 5 lines.
***WRONG :1,5s/^/#/ = comment the first 5 lines.
:%s/a/b/g searchs the all occurrances on text and switches a by b.
:2,35 s/old/new/g Replace all occurences between lines 2 and 35
:199,$ s/local/replace/g
***WRONG :199,$ %s/local/replace/g
#replace just words
:s/\<vi\>/VIM/g
#replace initial words
:s/^vi\>/VIMg
#replace lines that contain just the word
s/^vi$/VIMg
#”Escaped” characters or metacharacters
. any character except new line
\s whitespace character
\S non-whitespace character
\d digit
\D non-digit
\x hex digit
\X non-hex digit
\o octal digit
\O non-octal digit
\h head of word character (a,b,c…z,A,B,C…Z and _)
\H non-head of word character
\p printable character
\P like \p, but excluding digits
\w word character
\W non-word character
\a alphabetic character
\A non-alphabetic character
\l lowercase character
\L non-lowercase character
\u uppercase character
\U non-uppercase character
Examples
– So, to match a date like 09/01/2000
\d\d/\d\d/\d\d\d\d
– To match 6 letter word starting with a capital letter
\u\w\w\w\w\w
#Quantifiers, Greedy and Non-Greedy
* matches 0 or more of the preceding characters, ranges or metacharacters .* matches everything including empty line
\+ matches 1 or more of the preceding characters…
\= matches 0 or 1 more of the preceding characters…
\{n,m} matches from n to m of the preceding characters…
\{n} matches exactly n times of the preceding characters…
\{,m} matches at most m (from 0 to m) of the preceding characters…
\{n,} matches at least n of of the preceding characters…
where n and m are positive integers (>0)
#Finding duplicate wordsEdit
\(\<\w\+\>\)\_s*\1
#Finding this or that string
/red\|green\|blue/
– To replace all instances of “red” or “green” or “blue” with “purple”, enter:
:%s/red\|green\|blue/purple/g
#Finding this or that word
\<\(red\|green\|blue\)\>
s:\<\(red\|green\|blue\)\>:g
@FAIL: vi/aix
In a pattern, \< and \> respectively specify the beginning and end of a word, while \( and \) respectively specify the
beginning and end of a group (the pattern \<red\|green\|blue\>,
#Replacement using the last search
After searching with the command /\<\(red\|green\|blue\)\> you could change the whole words “red” or “green” or “blue” to “purple” by
entering the following (the search pattern is empty in this command, so it uses the last search):
:%s//purple/g
In a substitute, you can use & in the replacement to mean the “whole matched pattern” (everything that was found).
For example, the following will insert quotes around all occurrences of the whole words “red” and “green” and “blue”:
:%s/\<\(red\|green\|blue\)\>/”&”/g
#TEXT EDITION/#fmt/#TABS
***NOTE: alternatively try: Fn + dd
#out insert mode
dd = delete
dw = delete word
#ESC MODE
:10 del 15 (deletes from 10th line up to 15th)
:10,12 co 17 (copies line 10 to 12 and pastes them under 17)
:10,12 mo 17 (copies line 10 to 12 and moves them under 17)
:d$ (deletes up to the end of the line)
:d# (deletes the lines between two matches to the string pointed by the caret)
:d3 (deletes 3 chars)
:d(Arrow right/left) (delete char on right/left)
yy copies the current line to memory
3yy copies the next 3 lines to memory
[n]p pastes after cursor position repeating n times
[n]P pastes before cursor position repeating n times
#Using buffer – marks
set initial: mMark_letter
set final: command’mark_letter Example: d’q (delete from mark q up to the current caret position)
“rdd: deletes line and save to buffer r
“x5yy: copies 5 lines to buffer x
“bdw: cuts the word and saves to buffer w
#Using visual mode
ESC mode. Type V and select the area.
y or x to yield or cut, respectively.
To past, use p.
#KEYBOARD TIPS
If using notebooks without numeric section, try:
Fn + shortcut.
Example: Fn + k
#CONFIGURATION
#TEMPLATE #0 (simplest)
syntax on
set nu “enable enumeration
“set nonu “disable enumeration
set autoindent
set cmdheight=2 “command bar is 2 high
set backspace=indent,eol,start “set backspace function
set hlsearch “highlight searched things
set incsearch “incremental search
“set ignorecase “ignore case
set textwidth=0
set autoread “auto read when file is changed from outside
set ruler “show current position
set showmatch “show maching braces
set shiftwidth=2
set tabstop=2
set t_Co=256
set vb
“set gfn=Courier/7
“set spell
” Toggle spell checking on and off with `,s`
let mapleader = “,”
nmap <silent> <leader>s :set spell!<CR>
” Set region to English USA
set spelllang=en_us
#TEMPLATE #1
*** IMPORTANT NOTES:
1. Edit .vimrc and switch “^M” to Ctrl+V ENTER. This cmd means “\n”.
2. Switch the similar matches below as follow, by example:
^O = Ctrl+V Ctrl+O
^U = Ctrl+V Ctrl+U
so on… The “^” denotes the “Ctrl+V” cmd, a vim’s special caracter for .vimrc configuration.
“last update: 05/07/10 13:45
syntax on
set nu title
set autoindent
set cmdheight=2 “command bar is 2 high
set backspace=indent,eol,start “set backspace function
set hlsearch “highlight searched things
set incsearch “incremental search
“set ignorecase “ignore case
set textwidth=0
set autoread “auto read when file is changed from outside
set ruler “show the current position
“set nu “show line number
set showmatch “show matching braces
set shiftwidth=2
set tabstop=2
set t_Co=256
set vb
“set gfn=Courier/7
map ^O :set nu
map ^U :set nonu
map ^E :set spell
map ^N :set nospell
” converts windows eol to unix
map ^K :set ff=unix
map! tthsh #!/bin/sh^M# last update:^M# script name:^M# target:^M# syntax:^M#^M# alsdias – ^M# History:
map! @@@ alsdias@yahoo.com.br
“set spell
” Toggle spell checking on and off with `,s`
let mapleader = “,”
nmap <silent> <leader>s :set spell!<CR>
” Set region to English USA
set spelllang=en_us
#TEMPLATE #2
standard
@SEE:
– methods of configuring:
@@bb#sslinux1;<vim.htm<configuration – methods
@SYNC: if compatible with vi:
.vim
@@vi;;;
.exrc (example of vi’s config file for IBM’s AIX servers, using SSH terminal)
” avoid using override (!) for each command that changes the file, otherwise to save you have to do w! or x!
syntax on
“line number on/off
set nu
set autoindent
set tabstop=2
set history=32
set window=42
set shiftwidth=2
set hardtabs=2
set scroll=21
“set directory=/var/tmp
” do not uncomment – @FAIL
“set directory=/cygdrive/f/portables/shell/tmp
“mapping section – make sure that the customized shortcut does not conflict with the standard and :set commands keep a space before ENTER.
map ^A :set nu ^M
map ^C :set nonu ^M
“show EOL
map ^M :set list ^M
map ^R :set nolist ^M
map ^T ^[!^M/cygdrive/f/portables/shell/sys -lu ^M
map ^H ^[!^M/cygdrive/f/portables/shell/sys -hsh ^M
map ^O ^[!^M/cygdrive/f/portables/shell/sys -ts ^M
” converts windows eol to unix
map ^K :set ff=unix
map ^X :syntax off ^M
ab @@@ Andre Luiz da Silva Dias/Brazil/Contr/IBM, alsdias@br.ibm.com
ab my@ aluizsilvadias@gmail.com
*** NOTE: use space before the final ENTER command, otherwise it interprets as a Ctrl+M command.
#howto
1- create a file with this content:
vi ~/.vimrc
2- fix the mapping chars under mapping section
For instance, replace ^N by: Ctrl+V N
3- overwrite vi’s config:
cat exrc > .exrc
4- if vi fails to start:
This procedure helps just in case a configuration fails.
If vi doesn’t start, do:
echo “” > .exrc
Edit the template:
vi exrc
Comment the line that it is probably causing the malfunction.
Repeat step 3.
***NOTE:
Before creating a shortcut, check if it doesn’t conflict with the standard ones.
@GOTO:__control
#COMMANDS (ESC MODE)
#MOST USED
“line number
set nu (turn no)
set nonu (turn off)
syntax on
set nu ru vb title
set autoread
set tabstop=2
set incsearch
set hlsearch
set autoindent
set ic
set noic
NOTE:
To be used with ESC + : mode or into .vimrc file.
#EXTENDED LIST
The commands below may be used in configuration file .vimrc (or .exrc for vi) without the colon (:). Example: set nu
:set wm=10 Set Wrap Margin 10 spaces from right edge of screen
:set wm=0 Turn off Wrap Margin
:set all Display all options
:set Display current settings of options
:set nooption Unset option
:set ai Set Auto Indentation during text entry
:set ic Set Ignore Case during searches
:set nu Show line Numbers
:set sm Show Matching ( or { when ) or } is entered
:set wm=10 Set Wrap Margin 10 spaces from right edge of screen
autoindent noai Supply indentation automatically
autowrite noaw Automatically write to file while editing
ignorecase noic Ignore case when searching
lisp nolisp (, {, ), and } commands deal with S-expressions
list nolist Tabs print as ^I; end of lines marked with $
magic nomagic The characters ., [, and * are special (“magical”) in scans
number nonu Lines are displayed prefixed with their line numbers
paragraphs para=IPLPPPQPbpP LI Macro names which start paragraphs
redraw nore Simulate a smart terminal on a dumb terminal
sections sect=NHSHH HU Macro names which start new sections
shiftwidth sw=8 Shift distance for <, >, and other “shift” commands
showmatch nosm Show matching ( or { locations as ) or } is typed, for example
showmode nosmd Show input mode description
slowopen slow Postpone display updates during inserts
term dumb The kind of terminal you are using
/ on just esc mode = dynamic search (like opera’s search)
DD = d$
^ww = deletes char
SHIFT i = insert a char and return to esc mode
// = repeats last search
> = indents
CRTL + r = redo
Put the caret on a string and type ‘#’
#forcing syntax
:set syntax=sh
:set syntax=perl
:set syntax=php
– enable/desable syntax
:set syntax on
:set syntax off
:syntax on
:syntax off
:set readonly!
:set autoindent
:set tabstop=2
:set history=32
:set window=42
:set shiftwidth=2
:set hardtabs=2
:set scroll=21
:set directory=/var/tmp
:set directory=/cygdrive/f/portables/shell/tmp-
– line number on/off
:map ^A :set nu ^M
:map ^C :set nonu ^M
– show EOL
:map ^M :set list ^M
:map ^R :set nolist ^M
:help for help
:e# returns to the original text
:e %.sp opens a file whith the same name plus .sp extension. (% = file name)
:.= show caret’s line number
:ab abbreviation string_to_abbreviate (typing abbreviation in Insert mode restore string)
:una delete abbreviation
:set nu, ou set number
:set noCOMMAND to unset. For instance: set nonu to unset set nu.
:set cmdheight=2 “command bar is 2 high
:set backspace=indent,eol,start “set backspace function
:set hlsearch “highlight searched things
:set incsearch “incremental search
:set ignorecase “ignore case (or set ic)
:set noic = unset ignorecase
:set textwidth=0
:set autoread “auto read when file is changed from outside
:set ruler “show current position
:set showmatch “show maching braces
:set nu, ou set number
:set noCOMMAND to unset. For instance: set nonu to unset set nu.
:set autoread (auto read when file is changed from outside)
:set tabstop=2
:set autoindent
:.= show the current line number
:r arq reads the arq file and inserts its content from current caret position
:syntax on|off color syntax
:e filename Edit filename in current window
:e! path edits withot saving the prior
:vb visual bip (turn off audio bip)
:eb turn on error bip
:sol column navigation
:ru shows status line
:title shows file’s title
#VAGRANT CONSOLE
Use Fn + shortcut on notebooks without the numeric right section keyboard.
Navigation: go to _navigation.
#out insert mode
#delete
Fn+dd = delete full line
Shift+dd = delete line content
Fn + D , S+$ = delete from current position up to the end of the line
#.VIM RC/#CONFIG/#SETUP
set nu
syntax on
set autoindent
set tabstop=2
set history=32
set window=42
set shiftwidth=2
set hardtabs=2
set scroll=21
#TEXT INDENT
#In insert mode, to tab:
^D de-indent current line
^T indent current line
# ‘:’ mode – summary
:set autoindent Turn on auto-indent
:set smartindent Turn on intelligent auto-indent
:set shiftwidth=4 Defines 4 spaces as indent size
ctrl-t, ctrl-d Indent/un-indent in insert mode
:set sw=3 # setting number of spaces to indent
:2,3>> # indenting the block from 2nd to 3rd line.
:2,3<< # returning the indentation to 2nd up to 3rd line.
# ‘:’ mode – detailed:
:tabnew Creates a new tab
gt Show next tab
:tabfirst Show first tab
:tablast Show last tab
:tabm n(position) Rearrange tabs
:tabdo %s/foo/bar/g Execute a command in all tabs
:tab ball Puts all open files in tabs
>> Indent line by shiftwidth spaces
<< De-indent line by shiftwidth spaces
5>> Indent 5 lines
5== Re-indent 5 lines
>% Increase indent of a braced or bracketed block (place cursor on brace first)
=% Reindent a braced or bracketed block (cursor on brace)
<% Decrease indent of a braced or bracketed block (cursor on brace)
]p Paste text, aligning indentation with surroundings
=i{ Re-indent the ‘inner block’, i.e. the contents of the block
=a{ Re-indent ‘a block’, i.e. block and containing braces
=2a{ Re-indent ‘2 blocks’, i.e. this block and containing block
>i{ Increase inner block indent
<i{ Decrease inner block indent
:%!fmt Align all lines
5!fmt Align the next 5 lines
Notes:
= is an operator that formats/indents text.
i{ is a text object that specifies the surrounding code block. It should be used together with v, =, etc.
==
formats the current line.
gg=G
whole text
Enter visual mode (V) , select the text and type ‘=’
or initial_line,final_line=
For instance: 1,10=
i{
Inner block, which means everything between { and } excluding the brackets. This can also be selected with i} and iB.
a{
A block, which means all the code between { and } including the brackets. This can also be selected with a} and aB.
i(
Inner parenthesis, meaning everything between ( and ) excluding the parentheses. Can also be selected with i) and ib.
a(
Parentheses, meaning everything between ( and ) including the parenthesis. Can also be selected with a) and ab.
i<
Inner < > block, meaning everything between < and > excluding the brackets. Can also be selected with i>.
a<
A < > block, meaning everything between < and > including the brackets. Can also be selected with a>.
i[
Inner [ ] block, meaning everything between [ and ] excluding the square brackets. Can also be selected with i].
a[
A [ ] block, meaning everything between [ and ], including the square brackets. This can also be selected with a].
whole text
gg=G
indenting 1st level of a block
=i{
indenting 2nd level
=2i{
These are useful to reformat text paragraphs or chunks of code (NOTE: this does not work for python code…):
V= – select text, then reformat with =
= – will correct alignment of code
== – one line;
gq – reformat a paragraph
Options to change how automatic formatting is done:
:set formatoptions (default “tcq”)
t – textwidth
c – comments (plus leader — see :help comments)
q – allogw ‘gq’ to work
n – numbered lists
2 – keep second line indent
1 – single letter words on next line
r – (in mail) comment leader after
Other related options:
:set wrapmargin
:set textwidth
@See:
stuff/shifting blocks visually vim tips wiki.mht
http://vim.wikia.com/wiki/Shifting_blocks_visually
stuff/vim how do i indent multiple lines quickly in vi stack overflow.mht
http://stackoverflow.com/questions/235839/how-do-i-indent-multiple-lines-quickly-in-vi
#REGEX
#SYMBOLS:
* zero or more occurrences.
. just one character
^ at the beginning means that the match must be at the beginning.
$ at
the end means that the match must be at the end.
ignores itself.
[] returns true if the pattern inside it is found.
The unique char to be ignored with ‘\’, if just in the case, are: -]\
<font color=”red” size=”2″>’^’ inside [],
means negative.</font>
For instance: [^0-9] no number occurence. Compare the ‘^’ outside the square
brackets.
( \) saves the found pattern in a buffer (total of 9 buffers).
< the pattern must be at the beginning of
a word.
> the pattern must be at the end of a word.
~ repeats the last RE used.
. (dot) Any single character except newline
* zero or more occurrences of any character
[…] Any single character specified in the set
[^…] Any single character not specified in the set
^ Anchor – the beginning of the line
$ Anchor – end of line
\< Anchor – beginning of the word
\> Anchor – end of the word
\(…\) Grouping – usually used to group conditions
\n Contents of nth grouping
/Hello/ Matches if the line contains the value Hello
/^TEST$/ Matches if the line contains TEST by itself
/^[a-zA-Z]/ Matches if the line starts with any letter
/^[a-z].*/ Matches if the first character of the line is a-z and there is at least one more of any character following it
/2134$/ Matches if line ends with 2134
/\(21|35\)/ Matches is the line contains 21 or 35
Note the use of ( ) with the pipe symbol to specify the ‘or’ condition
/[0-9]*/ Matches if there are zero or more numbers in the line
/^[^#]/ Matches if the first character is not a # in the line
Notes:
1. Regular expressions are case sensitive
2. Regular expressions are to be used where pattern is specified
#POSIX
[:upper:] [A-Z][:lower:][a-z][:alpha:] [A-Za-z] (try: [A-z])[:space:] [ \t\n\v\f\r]. For instance: :%/s/^[[:space:]]/#/g
(switches
initial spaces by ‘#’)
[:graph:] [^ \t\n\v\f\r] printable characters.
[:alnum:] [A-Za-z0-9] chars and
numbers
[:digit:] [0-9] decimal numbers
[:xdigit:] [0-9A-Fa-f] hexadecimals
[:punct:] [.,!?:…] punctuation
chars
[:blank:] [ \t] blank space and TAB
[:cntrl:] – control chars.
[:print:] printable chars
(see graph – I have doubt here – the doc made this = graph???)
#Ctrl commands (^)
#standard
^B page backward
^D scroll down
^E expose a line at the bottom of the screen
^F page forward
^G Positional status check
^I conflicts…
^J conflicts…
^L cleans messed text
^N next line, same column
^P previous line, same column
^U scroll up
^V return char (^M)
^Y expose a line at the top of the screen
^W erase a word during insert
^[ ESC char
#VISUAL MODE
#SELECTING UP TO THE FIRST PATTERN
1. Enter visual mode at the starting point
2. type / to enter in search mode
3. type the pattern. When found, use enter to return.
All area from the starting point up to the search is selected.
#OPENING MANY DOCS
vim doc1 doc2
To navigate, use:
:n (go forward)
:rew (or :rewind – go backward)
#swap file
To stop sending messages, delete it:
rm path/.file.swp
#UTILS
>windows CR to nix conversion
%s/^M//g (where ^M is obtained by: Ctrl+V M).
>backslash to forward slash
%s/\\/\//g
#abbreviations
to set:
:ab abbreviation string_to_abbreviate
to invoke:
typing abbreviation in Insert mode restore string
to delete – use the reverse command ‘una’:
:una delete abbreviation
#recovering failures
If just in the case, reboot system.
Type:
vim -r (it shows the files that can be recovered)
vim -r file (the specific file to be recovered)
#tt” (buffer operations)
Copy/Cut/Past from 26 available buffers.
To access the buffers, use quotes (“) plus a letter,
not on Insert or ‘:’ modes:
“cdd (cuts the line where the cursor is on to buffer c)
“p (pastes the a’s content to the line where the cursor is on)
Syntax: BUFFER_LETTERcommand
Examples:
“rdd: deletes line and save to buffer r
“x5yy: copies 5 lines to buffer x
“bdw: cuts the word and saves to buffer w
#macro to key shortcuts
On VIM, macros as key mappings.
Syntax:
:map key action
To unmap (mapping delete):
:unmap key
For instance:
:map ^x :set nu
means that each time its typed CRTL X, it’s gonna be the same as manually typing’:’command.
NOTE:
In order to get CRTL X, it’s necessary to indicates a special character set typing
before the command.
Example: CRTL V CRTL X (means CRTL X)
Notation: ^X means CRTL X on the documentation.
#Summary
:map ^V^LETTER COMMAND
Example: :map ^V^X :set nu^V ENTER
To unset: unmap, unm
SPECIAL KEYS MATCHINGS (notice the format title in blue)
CRTL V CRTL letter = CRTL letter = ^letter
CRTL V ESC = ESC = ^[
CRTL V ENTER = ENTER = ^M
#F1…#F12 (FUNCTION-KEY) = #1…#12 = #1…#12
to enter into the include mode = CRTL V i (after this you type the text to be included)
To check this notation, edit for instance a VIM’s configuration file (.vimrc) and type:
map CRTL V ENTER
The result is:
map ^[
Example of a /root/.vimrc configuration file:
vim_vimrc_config.png
The same content on a text file – notice that the special characters are gone: vim_vimrc_config.txt
#macro to inserting mode
A macro allow to type an alias that returns a string.
For instance, add this line to ~/.vimrc:
map! @@@ alsdias@yahoo.com.br
when you type fast 3time ‘@’ (the cursor remains in the same place when it finds a macro alias), at the end it’s returned the email: “alsdias@yahoo.com.br” .
Note:
The vim’s configuration file (~/.vimrc) did not accept any command.
For instance, the mapping below didn’t work:
map! ttbshReadFile while read line; do^M [ “$(echo $line | cut -c1)” = ‘#’ ] && continue^M [ “$line” ] || continue^M echo $line done < “$file”^M
but this another one was successful:
map! ttbshImport import=”/home/alsdias/dev/scripts” ^M . “$import”/toolBox.sh^M
The <em>^M</em> character set means return of line, obtained typing <em>^V</em> plus <em>ENTER</em>.
The prior macro mentioned before (without !) is used out of insert mode.
This kind of macro works into insert mode.
Same as MACRO TO KEY SHORTCUTS, but add a final ‘!’ .
Example:
:map! @ alsdias@yahoo.com.br
To unset:
unmap!, unm!
Example #2:
:map! @@@ alsdias@yahoo.com.br
On the insert mode, type fast twice ‘@’ to be returned
To unmap (mapping delete):
:unmap! key
Brazilian system analyst graduated by UNESA (University Estácio de Sá – Rio de Janeiro). Geek by heart.