• LINUX > vi et vim

      CONFIGURATION

      QUELQUES TRUCS A METTRE PAR DÉFAUT

      Pour que vi soit l’éditeur par défaut :

      export EDITOR=vim
      alias vi='vim'

       

       

      Dans le fichier ~/.exrc, mettre :

       

      :set autoindent Crée une indentation si la ligne précédente en a une
      :set ts=4 Avoir une tabulation de 4 caractères
      :set ignorecase Ignore la casse lors d’un recherche
      :set list Affiche les caractères spéciaux
      :set number Affiche le numéro des lignes
      :set shiftwidth=2 Valeur de l’indentation (2 caractères)
      :set showmode Affiche si on est en mode Insert, Append, ou Replace
      :set wrapmargin=n Crée une marge de 80-n pour un autowrapping lines (inserting newlines). 0 pour mettre en off

      :set hlsearch surligne les termes trouvés

      :set smartindent modifie l’indentation suivant le contenu

      LA 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 darkblue

      Pour faire défiler la liste, dans vi taper: :colorscheme puis ESPACE puis TAB

      Pour changer de thème de façon permanente : ajouter colorscheme nom_du_theme dans /etc/vim/vimrc

      Cré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 pipes

      Constant= ce qu’il y a entre guillemets

      Indentifier= déclaration de variables

      Comment= commentaires

      PreProc= variables

      Type=

      Special= les options (-i -u etc.) et tout entre parenthèses

      Liste des couleurs

      :hi pour voir la couleur apparentée

      exemple : :hi Commentctermfg=008 et ctermbg=

       

      001 rouge foncé    -    002 vert    -   003 jaune   -   004 bleu   -   005 magenta   -   006 cyan   -   007 blanc   -   008 gris   -   009 rouge

      210 rose pâle        -    111 bleu pâle   -   209 orange   -   207 magenta vif   -   206 mauve   -   150 kaki pâle    -     154 vert pomme

      COPIER / 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 A

      Copier / 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 : +yy

      Coller : +p

      Pour faire des sélections :  [v] ou [V]

       

      ——————————————-

       

      Copier 1 ligne : Y

      Copier 2 lignes : 2Y

      Copier 10 lignes: 10Y

      Copier toutes les lignes jusqu’à la fin du fichier: yG

      Copier du curseur à la fin du mot : yw

      Copier du curseur à la fin de la ligne : y$

      Coller après le curseur : p

      Coller avant le curseur : P

       

      Copier / 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 hello then type "ay to copy "hello" to the a register.

      Then you could select the text world and type "by to copy "world" to the b register.

      After moving the cursor to another location, the text could be pasted: type "ap to paste "hello" or "bp to paste "world". These commands paste the text after the cursor.

      Alternatively, type "aP or "bP to paste before the cursor.

      COMMANDES DE BASE

      i Passer en mode insertion

      A Ajouter en fin de ligne

      :x Enregistrer (seulement en cas de modification) et quitter

      :set paste Passer en mode "collage"

      Commandes d’édition:

      u Annuler la dernière opération

      <CTRL>-r Rétablir la dernière opération annulée

      . Répéter la dernière opération d’édition

      yy Copier la ligne (4yy = 4 lignes)

      dd Couper la ligne (4dd = 4 lignes)

      p Coller après (P = insérer avant)

      x Effacer le caractère

      dw Effacer le texte jusqu’à la fin du mot

      diw Effacer le mot sous le curseur

      Recherche / remplacement:

      / Rechercher du texte

      n Rechercher l’occurence suivante

      N Rechercher l’occurence précédente

      cw Remplacer le texte jusqu’à la fin du mot

      ciw Remplacer le mot

      C Remplacer jusqu’en fin de ligne

      . Répéter la dernière opération d’édition

      :%s/A/B/g Remplacer tous (g) les A par des B

      Fenêtrage:

      <CTRL-w>-s Diviser horizontalement

      <CTRL-w>-v Diviser verticalement

      <CTRL-w>-w Passer à la fenêtre suivante

      <CTRL-w>-n Ouvrir un fichier vierge dans une nouvelle fenêtre

      <CTRL-w>-q Fermer la fenêtre
      set nocompatible Désactive la compatibilité avec vi

      set background=dark adapte les couleurs pour un fond noir

      syntax on Active la coloration syntaxique

      set number Affiche les numéros de lignes

      set tabstop=4 Indentation toutes les quatre colonnes

      set expandtab Conversion des tabulations en espaces

      set shiftwidth=4 Indentation de quatre colonnes

      set smartindent Indentation "intelligents"

      set autoindent Conserve l’indentation courante sur les nouvelles lignes

      set backspace=indent,eol,start retours arrières intelligents

      set shiftround Indentation à la marque de Tab la plus proche

      set ignorecase Ignore la casse lors de recherche

      set showmode affiche le mode d’édition

      set ruler affiche la position du curseur

      set showcmd affiche les commandes incomplète

      map <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 gpm

      Puis insérer dans ~/.vimrc : set mouse=a

      CHANGER LE CHARSET

      Pour changer le charset du fichier en utf-8, dans vi, taper :: se encoding=utf-8

      Et bien sûr, enregistrer ensuite le fichier : :q

      RACCOURCIS CLAVIER

      Quitter

      :q Quit Vim. This fails when changes have been made.
      :q! Quit without writing.
      :cq Quit always, without writing.
      :wq Write 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].
      ZZ Write current file, if modified, and exit.
      ZQ Quit current file and exit (same as ":q!").

      Éditer

      :e Edit 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 file Edit file.
      :e! file Edit file always. Discard any changes to the current buffer.
      gf Edit the file whose name is under or after the cursor. Mnemonic: "goto file".

      Remplacer du texte

      :g/chaine/S//remp/g remplace chaine par remp

       

      r{char} replace the character under the cursor with {char}.
      R Enter 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 text

      Insérer du texte

      a Append text after the cursor [count] times.
      A Append text at the end of the line [count] times.
      i Insert text before the cursor [count] times.
      I Insert text before the first non-blank in the line [count] times.
      gI Insert text in column 1 [count] times.
      o Begin a new line below the cursor and insert text, repeat [count] times.
      O Begin a new line above the cursor and insert text, repeat [count] times.

      Insérer un fichier

      :r fich Insert le fichier fich sous le curseur.
      :r !cmd Exécute cmd et insert son résultat sous le curseur.

      Effacer du texte

      del avec
      x Delete [count] characters under and after the cursor
      X Delete [count] characters before the cursor
      d{motion} Delete text that {motion} moves over
      dd Delete [count] lines
      D Delete the characters under the cursor until the end of the line

       

      en mode Visuel [v] ou [V] :

      x ou d Delete the highlighted text
      X ou D Delete the highlighted lines
      :[range]d Delete [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 flags

       

      The 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 line

      g When 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).
      G aller à la fin du fichier

      H aller en haut de la page

      gg aller au début du fichier
      ge Backward to the end of word [count]
      gE Backward 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 column

      Marks

      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
      :marks List 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.
      n Repeat the latest "/" or "?" [count] times.
      N Repeat the latest "/" or "?" [count] times in opposite direction.

      mode Visuel

      v commencer le mode Visuel par caractère
      V commencer le mode Visuel par ligne

      échap Quitter le mode Visuel

       

      Après avoir sélectionné le texte, utiliser les commandes suivantes :
      ~ switch case
      d delete
      c change
      y yank
      > shift right
      < shift left
      ! filter through external command
      = filter through ‘equalprg’ option command
      gq format lines to ‘textwidth’ length

      Comment rechercher du texte et le remplacer ?

      Pour faire une modification sur la ligne du curseur, il faut taper : :s/texte_à_trouver/nouveau_texte/g

      Pour agir sur l’ensemble du document : :%s/texte_à_trouver/nouveau_texte/g

      Et 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.

      • \[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.

      Comment exécuter un programme depuis vi ?

      :!nom_du_programme lancera 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 ai permet de faire automatiquement les indentations.

      :set sw=N permet 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 sm déplace brièvement le curseur sur le {, ( ou [ ouvrant lorsqu'on tape le }, ), ou ] qui le ferme.

      :set lisp modifie 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.fr permet 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.

       

 

Aucun commentaire

 

Laissez un commentaire