-
LINUX > vi et vim
- \[1-9] Le contenu du Nième groupe \( \).
- \u Le caractère suivant passe en majuscule.
- \U Tous les caractères jusqu’à \e ou \E passent en majuscule.
- \l Le caractère suivant passe en minuscule.
- \L Tous les caractères jusqu’à \e ou \E passent en minuscule.
- \[eE] Termine la zone de passage en majuscule ou en minuscule.
CONFIGURATION
QUELQUES TRUCS A METTRE PAR DÉFAUT
Pour que vi soit l’éditeur par défaut :
export EDITOR=vimalias vi='vim'Dans le fichier ~/.exrc, mettre :
:set autoindentCrée une indentation si la ligne précédente en a une
:set ts=4Avoir une tabulation de 4 caractères
:set ignorecaseIgnore la casse lors d’un recherche
:set listAffiche les caractères spéciaux
:set numberAffiche le numéro des lignes
:set shiftwidth=2Valeur de l’indentation (2 caractères)
:set showmodeAffiche si on est en mode Insert, Append, ou Replace
:set wrapmargin=nCrée une marge de 80-n pour un autowrapping lines (inserting newlines). 0 pour mettre en off:set hlsearchsurligne les termes trouvés:set smartindentmodifie l’indentation suivant le contenuLA COLORISATION
Modifier les thèmes de couleurs
En faisant
ls /usr/share/vim/vim82(si version 8.2) et à l’intérieur de ce dossier, le dossier colors avec tous les thèmes de couleurs.Pour en sélectionner un, dans vi, taper :
:colorscheme darkbluePour faire défiler la liste, dans vi taper:
:colorschemepuisESPACEpuisTABPour changer de thème de façon permanente : ajouter
colorscheme nom_du_themedans/etc/vim/vimrcCréer un thème de couleurs
set t_Co=256(pour un jeu de 256 couleurs. A déclarer en premier)cterm=NONE(normal)cterm=bold(gras)Statement=boucles for, while, if, les pipesConstant=ce qu’il y a entre guillemetsIndentifier=déclaration de variablesComment=commentairesPreProc=variablesType=…Special=les options (-i -u etc.) et tout entre parenthèsesListe des couleurs
:hipour voir la couleur apparentéeexemple :
:hi Comment→ctermfg=008etctermbg=001rouge foncé -002vert -003jaune -004bleu -005magenta -006cyan -007blanc -008gris -009rouge210rose pâle -111bleu pâle -209orange -207magenta vif -206mauve -150kaki pâle -154vert pommeCOPIER / COLLER
Copier / coller dans un autre fichier
- on ouvre le 1er fichier
- on va au début de ce que l’on veut copier
- on tape [
V] pour passer en mode visuel- on sélectionne ce qu’on veut copier avec les touches [
↑] et [↓]- on appuie sur [
Y] pour copier ou [ ] pour couper- on ouvre l’autre fichier "
:e autrefichier"- on va là où on veut coller
- on appuie sur [
P]Recopier l’intégralité d’un fichier A dans un fichier B : On ouvre B dans vi et on tape la commande
:r ACopier / coller entre vi et un autre processus
Pour copier/coller entre vi et un aute processus (qui peut être une autre vi) il faut utiliser le tampon système ‘
+‘Copier :
+yyColler :
+pPour faire des sélections : [
v] ou [V]
——————————————-
Copier 1 ligne :
YCopier 2 lignes :
2YCopier 10 lignes:
10YCopier toutes les lignes jusqu’à la fin du fichier:
yGCopier du curseur à la fin du mot :
ywCopier du curseur à la fin de la ligne :
y$Coller après le curseur :
pColler avant le curseur :
PCopier / Coller
Mettre le curseur là où il faut couper.
Touche [
v] pour sélectionner les caractères / [V] pour sélectionner des lignes.Déplacer le curseur à la fin de ce que l’on veut couper.
Touche [
d] pour couper / [y] pour copier.Déplacer le curseur là où l’on veut copier.
Touche [
P] pour coller avant le curseur / [p] pour coller après le curseur.Copies multiples
Exemple : On sélectionne le texte
hellothen type"ayto copy "hello" to thearegister.Then you could select the text
worldand type"byto copy "world" to thebregister.After moving the cursor to another location, the text could be pasted: type
"apto paste "hello" or"bpto paste "world". These commands paste the text after the cursor.Alternatively, type
"aPor"bPto paste before the cursor.COMMANDES DE BASE
iPasser en mode insertionAAjouter en fin de ligne:xEnregistrer (seulement en cas de modification) et quitter:set pastePasser en mode "collage"Commandes d’édition:
uAnnuler la dernière opération<CTRL>-rRétablir la dernière opération annulée.Répéter la dernière opération d’éditionyyCopier la ligne (4yy = 4 lignes)ddCouper la ligne (4dd = 4 lignes)pColler après (P= insérer avant)xEffacer le caractèredwEffacer le texte jusqu’à la fin du motdiwEffacer le mot sous le curseurRecherche / remplacement:
/Rechercher du textenRechercher l’occurence suivanteNRechercher l’occurence précédentecwRemplacer le texte jusqu’à la fin du motciwRemplacer le motCRemplacer jusqu’en fin de ligne.Répéter la dernière opération d’édition:%s/A/B/gRemplacer tous (g) les A par des BFenêtrage:
<CTRL-w>-sDiviser horizontalement<CTRL-w>-vDiviser verticalement<CTRL-w>-wPasser à la fenêtre suivante<CTRL-w>-nOuvrir un fichier vierge dans une nouvelle fenêtre<CTRL-w>-qFermer la fenêtre
set nocompatibleDésactive la compatibilité avec viset background=darkadapte les couleurs pour un fond noirsyntax onActive la coloration syntaxiqueset numberAffiche les numéros de lignesset tabstop=4Indentation toutes les quatre colonnesset expandtabConversion des tabulations en espacesset shiftwidth=4Indentation de quatre colonnesset smartindentIndentation "intelligents"set autoindentConserve l’indentation courante sur les nouvelles lignesset backspace=indent,eol,startretours arrières intelligentsset shiftroundIndentation à la marque de Tab la plus procheset ignorecaseIgnore la casse lors de rechercheset showmodeaffiche le mode d’éditionset ruleraffiche la position du curseurset showcmdaffiche les commandes incomplètemap <C-m> :resize<CR>Ctrl-m maximize la fenetre courrante (:help map)map <C-b> :bNext<CR>Ctrl-b aller au tampon suivant (:help map)Vim ET LA SOURIS
sudo apt-get install gpmPuis insérer dans ~/.vimrc :
set mouse=aCHANGER LE CHARSET
Pour changer le charset du fichier en utf-8, dans vi, taper :
: se encoding=utf-8Et bien sûr, enregistrer ensuite le fichier :
:qRACCOURCIS CLAVIER
Quitter
:qQuit Vim. This fails when changes have been made.
:q!Quit without writing.
:cqQuit always, without writing.
:wqWrite the current file and exit.
:wq!Write the current file and exit always.
:wq {file}Write to {file}. Exit if not editing the last
:wq! {file}Write to {file} and exit always.
:[range]wq[!] [file]Same as above, but only write the lines in [range].
ZZWrite current file, if modified, and exit.
ZQQuit current file and exit (same as ":q!").Éditer
:eEdit the current file. This is useful to re-edit the current file, when it has been changed outside of Vim.
:e!Edit the current file always. Discard any changes to the current buffer. This is useful if you want to start all over again.
:e fileEdit file.
:e! fileEdit file always. Discard any changes to the current buffer.
gfEdit the file whose name is under or after the cursor. Mnemonic: "goto file".Remplacer du texte
:g/chaine/S//remp/gremplace chaine par rempr{char}replace the character under the cursor with {char}.
REnter Insert mode, replacing characters rather than inserting
~Switch case of the character under the cursor and move the cursor to the right. If a [count] is given, do that many characters.
~{motion}switch case of {motion} text.
{Visual}~Switch case of highlighted textInsérer du texte
aAppend text after the cursor [count] times.
AAppend text at the end of the line [count] times.
iInsert text before the cursor [count] times.
IInsert text before the first non-blank in the line [count] times.
gIInsert text in column 1 [count] times.
oBegin a new line below the cursor and insert text, repeat [count] times.
OBegin a new line above the cursor and insert text, repeat [count] times.Insérer un fichier
:r fichInsert le fichierfichsous le curseur.
:r !cmdExécutecmdet insert son résultat sous le curseur.Effacer du texte
delavec
xDelete [count] characters under and after the cursor
XDelete [count] characters before the cursor
d{motion} Delete text that {motion} moves over
ddDelete [count] lines
DDelete the characters under the cursor until the end of the lineen mode Visuel [
v] ou [V] :xoudDelete the highlighted text
XouDDelete the highlighted lines
:[range]dDelete [range] lines (default: current line)
:[range]d {count}Delete {count} lines, starting with [range]Substitution
:[range]s[ubstitute]/{pattern}/{string}/[c][e][g][p][r][i][I] [count]For each line in [range] replace a match of {pattern} with {string}.
:[range]s[ubstitute] [c][e][g][r][i][I] [count] :[range]&[c][e][g][r][i][I] [count]Repeat last :substitute with same search pattern and substitute string, but without the same flags. You may add extra flagsThe arguments that you can use for the substitute commands:
[c] Confirm each substitution. Vim positions the cursor on the matching
string. You can type:
‘y‘ to substitute this match
‘n‘ to skip this match
‘a‘ to substitute this and all remaining matches {not in Vi}
‘q‘ to quit substituting {not in Vi}
[CTRL] + [E] scroll d’une ligne de l’écran vers le haut
[CTRL] + [Y] scroll d’une ligne de l’écran vers le bas
[e] When the search pattern fails, do not issue an error message and, in
particular, continue in maps as if no error occurred.
[g] Replace all occurrences in the line. Without this argument,
replacement occurs only for the first occurrence in each line.
[i] Ignore case for the pattern.
[I] Don’t ignore case for the pattern.
[p] Print the line containing the last substitute.Copying and Moving Text
"{a-zA-Z0-9.%#:-"} Use register {a-zA-Z0-9.%#:-"} for next delete, yank or put (use uppercase character to append with delete and yank) ({.%#:} only work with put).
:reg[isters] Display the contents of all numbered and named registers.
:reg[isters] {arg} Display the contents of the numbered and named registers that are mentioned in {arg}.
:di[splay] [arg] Same as :registers.
["x]y{motion} Yank {motion} text [into register x].
["x]yy Yank [count] lines [into register x]
["x]Y yank [count] lines [into register x] (synonym for yy).
{Visual}["x]y Yank the highlighted text [into register x] (for {Visual} see Selecting Text).
{Visual}["x]Y Yank the highlighted lines [into register x]
:[range]y[ank] [x] Yank [range] lines [into register x].
:[range]y[ank] [x] {count} Yank {count} lines, starting with last line number in [range] (default: current line), [into register x].
["x]p Put the text [from register x] after the cursor [count] times.
["x]P Put the text [from register x] before the cursor [count] times.
["x]gp Just like "p", but leave the cursor just after the new text.
["x]gP Just like "P", but leave the cursor just after the new text.
:[line]pu[t] [x] Put the text [from register x] after [line] (default current line).
:[line]pu[t]! [x] Put the text [from register x] before [line] (default current line).Undo/Redo/Repeat
CTRL-R Redo [count] changes which were undone.
:red[o] Redo one change which was undone.
U Undo all latest changes on one line. {Vi: while not moved off of it}
. Repeat last change, with count replaced with [count].SE DEPLACER
0 To the first character of the line (exclusive).
^To the first non-blank character of the line
$To the end of the linegWhen lines wrap (‘wrap on): To the first character of the screen line (exclusive). Differs from "0″ when a line is wider than the screen. When lines don’t wrap (‘wrap’ off): To the leftmost character of the current line that is on the screen. Differs from "0″ when the first character of the line is not on the screen.
g^When lines wrap (‘wrap’ on): To the first non-blank character of the screen line (exclusive). Differs from "^" when a line is wider than the screen. When lines don’t wrap (‘wrap’ off): To the leftmost non-blank character of the current line that is on the screen. Differs from "^" when the first non-blank character of the line is not on the screen.
g$or
g f{char} To [count]‘th occurrence of {char} to the right. The cursor is placed on {char} (inclusive).
F{char} To the [count]‘th occurrence of {char} to the left. The cursor is placed on {char} (inclusive).
t{char} Till before [count]‘th occurrence of {char} to the right. The cursor is placed on the character left of {char} (inclusive).
T{char} Till after [count]‘th occurrence of {char} to the left. The cursor is placed on the character right of {char} (inclusive).
; Repeat latest f, t, F or T [count] times.
, Repeat latest f, t, F or T in opposite direction [count] times.
- [count] lines upward, on the first non-blank character (linewise).
+ or CTRL-M or [count] lines downward, on the first non-blank character (linewise).
_ [count] - 1 lines downward, on the first non-blank character (linewise).
Galler à la fin du fichierHaller en haut de la pageggaller au début du fichier
geBackward to the end of word [count]
gEBackward to the end of WORD [count]
These commands move over words or WORDS.( [count] sentences backward
) [count] sentences forward
{ [count] paragraphs backward
} [count] paragraphs forward
]] [count] sections forward or to the next ‘{‘ in the first column. When used after an operator, then the ‘}’ in the first column.
][ [count] sections forward or to the next ‘}’ in the first column
[[ [count] sections backward or to the previous ‘{‘ in the first column
[] [count] sections backward or to the previous ‘}’ in the first columnMarks
m{a-zA-Z}Set mark {a-zA-Z} at cursor position (does not move the cursor, this is not a motion command).
m’Set the previous context mark. This can be jumped to with the "‘’" or "``" command (does not move the cursor, this is not a motion command).
:[range]ma[rk] {a-zA-Z}Set mark {a-zA-Z} at last line number in [range], column 0. Default is cursor line.
:[range]k{a-zA-Z}Same as :mark, but the space before the mark name can be omitted.
‘{a-z}To the first non-blank character on the line with mark {a-z} (linewise).
‘{A-Z0-9}To the first non-blank character on the line with mark {A-Z0-9} in the correct file
`{a-z}To the mark {a-z}
`{A-Z0-9}To the mark {A-Z0-9} in the correct file
:marksList all the current marks (not a motion command).
:marks {arg}List the marks that are mentioned in {arg} (not a motion command).w Move to next word
W Move to next blank delimited word
b Move to the beginning of the word
B Move to the beginning of blank delimted word
e Move to the end of the word
E Move to the end of Blank delimited word
( Move a sentence back
) Move a sentence forward
{ Move a paragraph back
} Move a paragraph forward
$ Move to the end of the line
1G Move to the first line of the file
G Move to the last line of the file
nG Move to nth line of the file
:n Move to nth line of the file
fc Move forward to c
Fc Move back to c
H Move to top of screen
M Move to middle of screen
L Move to botton of screen
% Move to associated ( ), { }, [ ]
^ Moves to the first non-blank character in the current line
+ or Moves to the first character in the next line
- Moves to the first non-blank character in the previous line
[[ Move a section back
]] Move a section forward
0 or | Move to the begining of the line
n| Moves to the column n in the current line
nH Moves to nth line from the top of the screen
nL Moves to nth line from the bottom of the screen
Control-d Move forward ½ screen
Control-f Move forward one full screen
Control-u Move backward ½ screen
Control-b Move backward one full screen
CTRL-e Moves screen up one line
CTRL-y Moves screen down one line
CTRL-u Moves screen up ½ page
CTRL-d Moves screen down ½ page
CTRL-b Moves screen up one page
CTRL-f Moves screen down one page
CTRL-I Redraws screen
z z-carriage return makes the current line the top line on the page
nz Makes the line n the top line on the page
z. Makes the current line the middle line on the page
nz. Makes the line n the middle line on the page
z- Makes the current line the bottom line on the page
nz- Makes the line n the bottom line on the page
Chercher
/{pattern}[/]Search forward for the [count]‘th occurrence of {pattern}
/{pattern}/{offset}Search forward for the [count]‘th occurrence of {pattern} and go {offset} lines up or down.
/Search forward for the [count]‘th latest used pattern
//{offset}Search forward for the [count]‘th latest used pattern with new. If {offset} is empty no offset is used.
?{pattern}[?]Search backward for the [count]‘th previous occurrence of {pattern}
?{pattern}?{offset}Search backward for the [count]‘th previous occurrence of {pattern} and go {offset} lines up or down
?Search backward for the [count]‘th latest used pattern
??{offset}Search backward for the [count]‘th latest used pattern with new {offset}. If {offset} is empty no offset is used.
nRepeat the latest "/" or "?" [count] times.
NRepeat the latest "/" or "?" [count] times in opposite direction.mode Visuel
vcommencer le mode Visuel par caractère
Vcommencer le mode Visuel par ligneéchapQuitter le mode VisuelAprès avoir sélectionné le texte, utiliser les commandes suivantes :
~switch case
ddelete
cchange
yyank
>shift right
<shift left
!filter through external command
=filter through ‘equalprg’ option command
gqformat lines to ‘textwidth’ lengthComment rechercher du texte et le remplacer ?
Pour faire une modification sur la ligne du curseur, il faut taper :
:s/texte_à_trouver/nouveau_texte/gPour agir sur l’ensemble du document :
:%s/texte_à_trouver/nouveau_texte/gEt pour limiter la recherche à un intervalle défini :
:[zone]s/texte_à_trouver/nouveau_texte/[cgi]La zone peut être délimitée de plusieurs façon : de la forme n,m avec n et m les numéros de lignes bornant la zone, comme on l’a vu plus haut, avec des opérateurs comme $ (fin du fichier), . (ligne du curseur), ou % (le fichier actuel). On peut ainsi écrire .,+5 pour désigner la ligne du curseur et les 5 suivantes. Si la commande est suivie de c , vi demandera confirmation avant chaque substitution. g permet de ne pas s’arrêter après la première substitution, et i demande à vi de ne pas tenir compte de la casse (minuscule ou majuscule) des caractères dans sa recherche.
On peut aussi utiliser la syntaxe suivante : :g/rototo/s/toto/titi/g , pour remplacer rototo par rotiti. L’avantage de cette méthode, qui cherche une ligne avec le mot rototo et qui remplace alors toto par titi, c’est qu’elle laisse intacte les lignes ne contenant que toto, alors que la méthode précédente les aurait modifiées aussi. Toutefois, s’il y a une ligne où se trouvent à la fois toto et rototo, alors ce toto sera modifié aussi.
On peut utiliser des RegEx dans les fonctions de recherche et de substitution. Exemple: permuter le premier et le deuxième mot des lignes contenant le mot toto, on peut utiliser ceci :
:g/toto/s/^\([^ ]*\) \([^ ]*\)/\2 \1/Quelques fonctionnalités spécifiques à vi :
&Représente tout ce qui a été trouvé lors de la recherche.Comment exécuter un programme depuis vi ?
:!nom_du_programmelancera le programme correspondant. :sh démarrera un shell interactif. Depuis lequel on peut, si on le souhaite, lancer vi. C’est utile lorsqu’on édite des Makefiles et des fichiers de configuration afin de réussir à compiler un programme, c’est plus rapide que de sauvegarder, de quitter et de relancer vi.Aaargh ! j’étais en train d’écrire, et mon ordinateur a planté.
En tapant vi -r nom_de_fichier , on peut récupérer le fichier que l’on éditait au moment du plantage. vi -r tout court fait la liste des fichiers récupérables.
Comment rendre vi plus convivial pour le programmeur ?
:set aipermet de faire automatiquement les indentations.:set sw=Npermet de régler à N le nombre d’espace d’une indentation. On peut déplacer une ligne d’un niveau d’indentation avec<<et>>vers la gauche et vers la droite respectivement. En se positionnant sur le premier élément d’une paire de crochets, de parenthèses ou d’accolades, et en tapant>%ou<%on peut déplacer d’un niveau vers la droite ou vers la gauche la paire et son contenu.:set smdéplace brièvement le curseur sur le {, ( ou [ ouvrant lorsqu'on tape le }, ), ou ] qui le ferme.:set lispmodifie le comportement de vi pour faciliter la programmation en lisp.Les Macros - comment les écrire ?
:map <abréviation> <commande> .L’abréviation doit être de 10 caractères maxi, et la commande, de 100. Les macros se lancent depuis le mode commande, mais on peut finir dans n’importe quel mode. Pour inclure un caractère de contrôle, il faut qu’il soit précédé de <C-V>. De même pour les commande ex, comme|: il faut taper:map co <C-V> <C-V>|unmap <abréviation>permet de supprimer une macro.map! <abréviation> <texte>permet d’insérer le <texte> dans le document.Comment associer une macro à une touche de fonction ?
Si l’on crée une macro dont l’abréviation est un chiffre entre 0 et 9, elle sera associée à la touche de Fn correspondante.
Comment abréger du texte ?
:ab mél votre.nom@fai.frpermet de remplacer automatiquement, à la saisie, mél par votre adresse. Pour arrêter cette substitution, tapez:una mél———
ZZ Exit and save changes if any have been made
i Insert before cursor
I Insert before line
a Append after cursor
A Append after line
o Open a new line after current line
O Open a new line before current line
r Replace one character
R Replace many characters
DEPLACEMENT
SUPPRESSION
x Delete character to the right of cursor
X Delete character to the left of cursor
D Delete to the end of the line
dd Delete current line
Backspace While inserting, deletes previous character
CTRL-w While inserting, deletes previous word
CTRL-x While inserting, deletes to start of inserted text
CTRL-v Take the next character literally. (i.e. To insert a Control-H, type Control-v Control-h)
nx Deletes n characters starting with current; omitting n deletes current character only
nX Deletes previous n characters; omitting n deletes previous character only
d$ Deletes from the cursor to the end of the line
ndw Deletes the next n words starting with current
ndb Deletes the previous n words starting with current
ndd Deletes n lines beginning with the current line
:n,md Deletes lines n through m
dMotion_cmd Deletes everything included in the Motion Command (e.g., dG would delete from current position to the end of the file, and d4 would delete to the end of the fourth sentence).
"np Retrieves the last nth delete (last 9 deletes are kept in a buffer)
"1pu.u. Scrolls through the delete buffer until the desired delete is retrieved (repeat u.)
COPIER
yy copier la ligne
MARQUEURS
mc Set marker c on this line
`c Go to beginning of marker c line.
‘c Go to first non-blank character of marker c line.
RECHERCHES
/string Search forward for string
?string Search back for string
n Search for next instance of string
N Search for previous instance of string
REMPLACER
:s/pattern/string/flags Replace pattern with string according to flags.
g Flag - Replace all occurences of pattern
c Flag - Confirm replaces.
& Repeat last :s command
EXPRESSIONS REGULIERES
. (dot) Any single character except newline
* zero or more occurances of any character
[...] Any single character specified in the set
[^...] Any single character not specified in the set
^ Anchor - beginning of the line
$ Anchor - end of line
\< Anchor - begining of word
\> Anchor - end of word
\(…\) Grouping - usually used to group conditions
\n Contents of nth grouping
[A-Z] The SET from Capital A to Capital Z
[a-z] The SET from lowercase a to lowercase z
[0-9] The SET from 0 to 9 (All numerals)
[./=+] The SET containing . (dot), / (slash), =, and +
[-A-F] The SET from Capital A to Capital F and the dash (dashes must be specified first)
[0-9 A-Z] The SET containing all capital letters and digits and a space
[A-Z][a-zA-Z] In the first position, the SET from Capital A to Capital Z
In the second character position, the SET containing all letters
/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
LIMITES
:n,m Range - Lines n-m
:. Range - Current line
:$ Range - Last line
:’c Range - Marker c
:% Range - All lines in file
:g/pattern/ Range - All lines that contain pattern
Starting and Ending VI
Starting VI
vi + nfilename Edits filename and places curser at line n
vi + filename Edits filename and places curser on last line
vi +/stringfilename Edits filename and places curser on first occurance of string
vi filenamefile2 … Edits filename, then edits file2 … After the save, use :n
Ending VI
:n,mw file Saves lines n through m to file
:n,mw >>file Saves lines n through m to the end of file
:q Quits VI and may prompt if you need to save
:q! Quits VI and without saving
:e! Edits file discarding any unsaved changes (starts over)
:we! Saves and continues to edit current file
Status
:.= Shows current line number
:= Shows number of lines in file
Control-G Shows filename, current line number, total lines in file, and % of file location
l Displays tab (^l) backslash (\) backspace (^H) newline ($) bell (^G) formfeed (^L^) of current line
Yanking Text
yy Yank the current line
:y Yank the current line
nyy or nY Places n lines in the buffer-copies
yMotion_cmd Copies everything from the curser to the Motion Command (e.g., yG would copy from current position to the end of the file, and y4 would copy to the end of the fourth sentence)
"(a-z)nyy or "(a-z)ndd Copies or cuts (deletes) n lines into a named buffer a through z; omitting n works on current line
Changing text
C Change to the end of the line
cc or S Change the whole line until ESC is pressed
xp Switches character at cursor with following character
stext Substitutes text for the current character until ESC is used
cwtext Changes current word to text until ESC is used
Ctext Changes rest of the current line to text until ESC is used
cMotion_cmd Changes to text from current position to Motion Command until ESC is used
<< or >> Shifts the line left or right (respectively) by one shift width (a tab)
n<< or n>> Shifts n lines left or right (respectively) by one shift width (a tab)
<Motion_cmd or >Motion_cmd Use with Motion Command to shift multiple lines left or right
Search for strings
/string Search forward for string
?string Search back for string
n Search for next instance of string
N Search for previous instance of string
% Searches to beginning of balancing ( ) [ ] or { }
fc Searches forward in current line to char
Fc Searches backward in current line to char
tc Searches forward in current line to character before char
Tchar Searches backward in current line to character before char
?str Finds in reverse for str
:set ic Ignores case when searching
:set noic Pays attention to case when searching
:n,ms/str1/str2/opt Searches from n to m for str1; replaces str1 to str2; using opt-opt can be g for global change, c to confirm change (y to acknowledge, to suppress), and p to print changed lines
& Repeats last :s command
:g/str/cmd Runs cmd on all lines that contain str
:g/str1/s/str2/str3/ Finds the line containing str1, replaces str2 with str3
:v/str/cmd Executes cmd on all lines that do not match str
, Repeats, in reverse direction, last / or ? search command
Replace
:s/pattern/string/flags Replace pattern with string according to flags.
g Flag - Replace all occurences of pattern
c Flag - Confirm replaces.
& Repeat last :s command
Shell Functions
:! cmd Executes shell command cmd; you can add these special characters to indicate:% name of current file# name of last file edited
!! cmd Executes shell command cmd, places output in file starting at current line
:!! Executes last shell command
:r! cmd Reads and inserts output from cmd
:f file Renames current file to file
:w !cmd Sends currently edited file to cmd as standard input and execute cmd
:cd dir Changes current working directory to dir
:sh Starts a sub-shell (CTRL-d returns to editor)
:so file Reads and executes commands in file (file is a shell script)
!Motion_cmd Sends text from current position to Motion Command to shell command cmd
!}sort Sorts from current position to end of paragraph and replaces text with sorted text
Settings
To change option, enter type :set option to turn them on or :set nooptioni to turn them off.To make them execute every time you open VI, create a file in your HOME directory called .exrc and type the options without the colon (:) preceding the option Set Default Description
:set ai noai Turns on auto indentation
:set all -- Prints all options to the screen
:set ap aw Prints line after d c J m :s t u commands
:set aw noaw Automatic write on :n ! e# ^^ :rew ^} :tag
:set bf nobf Discards control characters from input
:set dir=tmp dir = /tmp Sets tmp to directory or buffer file
:set eb noed Precedes error messages with a bell
:set ed noed Precedes error messages with a bell
:set ht= ht = 8 Sets terminal hardware tabs
:set ic noic Ignores case when searching
:set lisp nolisp Modifies brackets for Lisp compatibility.
:set list nolist Shows tabs (^l) and end of line ($)
:set magic magic Allows pattern matching with special characters
:set mesg mesg Allows others to send messages
:set nooption Turns off option
:set nu nonu Shows line numbers
:set opt opt Speeds output; eliminates automatic RETURN
:set para= para = LIlPLPPPQPbpP macro names that start paragraphs for { and } operators
:set prompt prompt Prompts for command input with :
:set re nore Simulates smart terminal on dumb terminal
:set remap remap Accept macros within macros
:set report noreport Indicates largest size of changes reported on status line
:set ro noro Changes file type to "read only"
:set scroll=n scroll = 11 set n lines for CTRL-d and z
:set sh=shell_path sh = /bin/sh set shell escape (default is /bin/sh) to shell_path
:set showmode nosm Indicates input or replace mode at bottom
:set slow slow Pospone display updates during inserts
:set sm nosm Show matching { or ( as ) or } is typed
:set sw=n sw = 8 Sets shift width to n characters
:set tags=x tags = /usr/lib/tags Path for files checked for tags (current directory included in default)
:set term $TERM Prints terminal type
:set terse noterse Shorten messages with terse
:set timeout Eliminates one-second time limit for macros
:set tl=n tl = 0 Sets significance of tags beyond n characters (0 means all)
:set ts=n ts = 8 Sets tab stops to n for text input
:set wa nowa Inhibits normal checks before write commands
:set warn warn Warns "no write since last change"
:set window=n window = n Sets number of lines in a text window to n
:set wm=n wm = 0 Sets automatic wraparound n spaces from right margin.
:set ws ws Sets automatic wraparound n spaces from right margin.
Key Mapping
NOTE: Map allows you to define strings of VI commands. If you create a file called ".exrc" in your home directory, any map or set command you place inside this file will be executed every time you run VI. To imbed control characters like ESC in the macro, you need to precede them with CTRL-v. If you need to include quotes ("), precede them with a \ (backslash). Unused keys in vi are: K V g q v * = and the function keys.
Example (The actual VI commands are in blue): :map v /I CTRL-v ESCdwiYou CTRL-v ESC ESC
Description: When v is pressed, search for "I" (/I ESC), delete word (dw), and insert "You" (iYou ESC). CTRL-v allows ESC to be inserted
:map keycmd_seq Defines key to run cmd_seq when pressed
:map Displays all created macros on status line
:unmap key Removes macro definition for key
:ab strstring When str is input, replaces it with string
:ab Displays all abbreviations
:una str Unabbreviates str
UNDO / REDO
Undo le dernier changement: u
Undo les 4 derniers changements : 4u
Undo tous les changements : U (u pour annuler le U)
Redo: CTRL + R
Redo les 4 derniers changements: 4Ctrl-R.