Outils pour utilisateurs

Outils du site


issue56:c_c

Due to the large interest presented in this topic by a reader, I've decided to write another one or two articles on Vim (including this one). This month I'll be focusing on a tangible example (file can be found here: http://pastebin.com/EqrfBFhF). I'll cover using visual block mode, some tricks for commenting large numbers of lines, a couple of tricks for using the mouse, and copying/pasting to/from external programs from/to Vim. If you're familiar with all of these topics, you can safely skip this article. Before we begin, I will briefly explain what an abundant number is, so that everyone can roughly follow the script. An abundant number is a number for which the sum of all factors (a factor is a number which divides a value without a remainder) is greater than the number itself. Example: The factors of 12 are: 1,2,3,4,6; the sum of the factors: 1+2+3+4+6=16; 16>12. What the script does is simply calculate which numbers (from a supplied range of numbers) are abundant, and which are not. The function is part of my solution to an Euler Project problem. In order to follow the article, I'd highly recommend opening a copy of the file from Pastebin in Vim (or GVim) so you can work along.

Vu le grand intérêt suscité par ce sujet chez un lecteur, j'ai décidé d'écrire un ou deux autres articles sur Vim (y compris celui-ci). Ce mois-ci je vais m'appuyer sur un exemple concret (dont le fichier peut être trouvé ici : http://pastebin.com/PkNqrqJt). Je vais parler de l'utilisation du mode visuel par bloc, de quelques astuces pour commenter un grand nombre de lignes, de deux ou trois trucs sur l'utilisation de la souris et du copier/coller depuis/vers des programmes externes à partir de/vers Vim. Si vous connaissez déjà tout ceci, vous pouvez ignorer cet article.

Avant de commencer, je vais vous expliquer brièvement ce qu'est un nombre abondant, afin que chacun puisse à peu près suivre le script. Un nombre abondant est un nombre qui est plus grand que la somme de tous ses diviseurs (un diviseur est un nombre qui divise une valeur sans un reste). Exemple : les facteurs de 12 sont 1,2,3,4,6 ; la somme des diviseurs vaut : 1+2+3+4+6 = 16, et 16>12. Le script calcule simplement quels nombres (compris entre deux valeurs données) sont abondants et lesquels ne le sont pas. La fonction fait partie de ma solution à un problème du Projet Euler.

Afin de suivre l'article, je vous recommande vivement l'ouverture d'une copie du fichier à partir de Pastebin dans Vim (ou GVim) pour que vous puissiez travailler avec moi.

Area 1 (Commenting) For those of you who are programmers, you'll be familiar with the concept of commenting out all code besides a small segment you want to test, when things aren't working. My approach to doing this is to use Visual Block Mode. The steps are as follows (from the beginning of the first line you want to comment): <ctrl>+[v]; [j]; <shift>+[i], [#]; [Esc] The first step enters Visual Block mode, the j key acts as a down arrow key, and <shift>+[i] enters insert mode for all selected lines. After these steps, you then hit the key for the comment symbol (in Python's case it's the octothorpe, a.k.a. hash symbol). For uncommenting, check Area 2 for Deleting in Visual Block Mode. The reader who contacted me offered the following script to do the same: “ COMMENTING OUT A # CHARACTER IN BASH SCRIPTS function! AddDelBashComment() let char=getline('.')[0] if char == ”#“ s/^#//g else s/^/#/g endif endfunction vmap <silent> # :call AddDelBashComment()<CR>

Section 1 (Commenter)

Les programmeurs parmi vous seront familiers avec le concept de commenter tout le code sauf un petit bout que vous voulez tester ; c'est utile quand les choses ne fonctionnent pas. Pour ce faire, j'utilise le mode Visuel par bloc. Les étapes sont les suivantes (à partir du début de la première ligne que vous voulez commenter) :

<ctrl>+[v]; [j]; <shift>+[i], [#]; [Echap]

La première étape passe en mode visuel par bloc, la touche j agit comme la flèche vers le bas et <shift>+[i] passe en mode insertion pour toutes les lignes sélectionnées. Après ces étapes, vous devez ensuite appuyer sur la touche pour le symbole de commentaire (dans le cas de Python, c'est le dièse). Pour décommenter, consultez la section 2 pour comment supprimer en mode Visuel par bloc.

Le lecteur qui m'a contacté a proposé le script suivant pour faire la même chose:

" COMMENTER AVEC UN # DANS LES SCRIPTS BASH
function! AjouterSupprimerCommentaireBash()
  let char=getline('.')[0]
  if char == "#"
     s/^#//g
  else
     s/^/#/g
  endif
endfunction
vmap <silent> # :call AjouterSupprimerCommentaireBash()<CR>**

This script has to be added to your .vimrc. Once it has been added, you can call it in the following way (same process for commenting and uncommenting): <ctrl>+[v]//[v]//[V]; [j]; [#] As you can see, the only thing you save by doing this is entering and exiting insert mode (and possibly having to press the control key). I've included this script for the sake of those for whom every keystroke counts. You will need to adjust the substitute lines for each comment character you frequently use. For SQL you would replace if char == “#” with if char == “-” and s/^#//g with s/^--//g (same for the other substitution command). You must also replace the octothorpe in the vmap line, otherwise you'll be using the same key for multiple functions.

Ce script doit être ajouté à votre .vimrc. Une fois qu'il a été ajouté, vous pouvez l'appeler de la manière suivante (même processus pour commenter et décommenter) :

<ctrl>+[v]//[v]//[V]; [j]; [#]

Comme vous pouvez le voir, la seule chose que vous économisez en faisant cela est d'entrer dans le mode insertion et d'en sortir (et peut-être d'avoir à appuyer sur la touche Ctrl). J'ai inclus ce script pour ceux pour qui toutes les touches comptent. Vous aurez besoin d'ajuster les lignes de substitution pour chaque caractère de commentaire que vous utilisez fréquemment. Pour SQL, vous devriez remplacer if char == ”#“ par if char == ”-“ et s/^#//g par s/^-// g (de même pour l'autre commande de substitution). Vous devez également remplacer le dièse dans la ligne vmap, sinon vous allez utiliser le même raccourci pour plusieurs fonctions.

Area 2 (Visual Block Mode) Since we covered inserting in Visual Block Mode in Area 1, I will not repeat it in this area. Deleting in Visual Block Mode: <ctrl>+[v]; [j]//[h]//[l]//[k]; [d]//[x]//[X] Which key you use in the second step is entirely dependent upon which direction you want to go (down, left, right, up, respectively). The key in the last step is entirely up to you, they all do the same. Yanking (copying) text in Visual Block mode: Section of a line: [v]; [h]//[j]//[k]//[l]; [y]; [h]//[j]//[k]//[l]; <ctrl>+[v]; [h]//[j]//[k]//[l]; <shift>+[i]//<shift>+[a]; <ctrl>+[r]+[“]; [Esc] <shift>+[i] inserts at the start of the line/selection, and <shift>+[a] appends to the end of the line/selection. Copying and pasting an entire line in multiple lines doesn't work with this method (at least not for me). As such, we won't cover it. As a side-note: <ctrl>+[r]+[“] works in any insert mode and pastes the contents of the Vim register (the local clipboard).

Section 2 (mode Visuel par bloc)

Puisque nous avons parlé de l'insertion dans le mode Visuel par bloc à l'étape 1, je ne vais pas en reparler ici.

Suppression en mode Visuel par bloc :

<ctrl>+[v]; [j]//[h]//[l]//[k]; [d]//[x]//[X]

La touche à utiliser dans la deuxième étape est entièrement dépendante de la direction dans laquelle vous voulez aller (respectivement vers le bas, la gauche, la droite, le haut). La touche dans la dernière étape est à votre choix, elles font toutes la même chose.

Emporter (copier) du texte en mode Visuel par bloc :

Section d'une ligne : [v]; [h]//[j]//[k]//[l]; [y]; [h]//[j]//[k]//[l]; <ctrl>+[v]; [h]//[j]//[k]//[l]; <shift>+[i]//<shift>+[a]; <ctrl>+[r]+[“]; [Echap]

<shift>+[i] insère au début de la ligne ou de la sélection, et <Shift>+[a] ajoute à la fin de la ligne ou de la sélection.

Copier et coller une ligne entière sur plusieurs lignes ne fonctionne pas avec cette méthode (du moins pas pour moi). Donc je n'en parlerai pas. Une petite remarque : <ctrl>+[r]+[”] fonctionne dans n'importe quel mode d'insertion et colle le contenu du registre Vim (le presse-papier local).

Area 3 (Mouse usage) Just a brief tip: If you want to highlight something in Vim using Visual Block Mode, hold <shift>+<alt> as you select. Area 4 (Copying and Pasting to/from external programs) You may have noticed that the yank and paste methods work only within Vim. To copy text from Vim to another program (firefox, for example), you can select the text with the mouse and use the middle-mouse button paste. If, however, you are at another computer that runs a different operating system (or lacks that function), you can copy text to the system clipboard with: [v]//[V]; [y]; [h]//[j]//[k]//[l]; [“][+][y] A quick explanation: you select the text you want (first two steps) and then you hit the quotation marks key (on German keyboards it's <shift>+[2]), and then the plus key, and then the y key. Do this one after the other, not all at once. Then to paste in the external program, just use <ctrl>+[v], as per usual. Pasting: [“][+][p] That's it. Press those 3 keys and it will paste the clipboard onto the line you have selected (so you may need to start a new line if that's what you want). You can also set the clipboard to autoselect, which should automatically copy to the system clipboard when you highlight something, and automatically paste from the clipboard when you press the middle-mouse button.

Section 3 (utilisation de la souris)

Juste un conseil rapide : si vous voulez mettre en évidence quelque chose dans Vim en étant dans le mode Visuel par bloc, appuyez sur <shift>+<alt> pendant que vous sélectionnez.

Section 4 (copier et coller depuis/vers des programmes externes)

Vous avez sans doute remarqué que les méthodes copier et coller fonctionnent uniquement à l'intérieur de Vim. Pour copier du texte depuis Vim vers un autre programme (Firefox, par exemple), vous pouvez sélectionner le texte avec la souris et coller avec le bouton central de la souris. Si, toutefois, vous êtes sur un autre ordinateur qui exécute un système d'exploitation différent (ou n'a pas cette fonction), vous pouvez copier du texte dans le presse-papiers du système avec :

[v]//[V]; [y]; [h]//[j]//[k]//[l]; [“][+][y]

Une explication rapide : vous sélectionnez le texte que vous voulez (deux premières étapes), puis vous appuyez sur la touche guillemets (sur les claviers allemands c'est <shift>+[2]), puis sur la touche plus et puis sur la touche y. Faites cela touche après touche, pas tout à la fois. Puis, pour coller dans le programme externe, il suffit d'utiliser <ctrl>+[v], comme d'habitude.

Coller:

[“][+][p]

C'est tout. Appuyez sur ces 3 touches et cela va coller le presse-papier sur la ligne que vous avez sélectionnée (vous devrez peut-être commencer une nouvelle ligne si c'est ce que vous voulez).

Vous pouvez également régler le presse-papiers sur autoselect, ce qui devrait automatiquement copier dans le presse-papiers système lorsque vous surlignez quelque chose et coller à partir du presse-papier automatiquement lorsque vous appuyez sur le bouton du milieu de la souris.

Area 5 (Extra tips) Syntax Highlighting: You can enable syntax highlighting in Vim by using: :set syntax=on (in Vim itself) or syntax enable (in your .vimrc) Hide Vim in the terminal: <ctrl>+[z] will suspend a task into the background (tested in Zsh and Bash). Once you've suspended a task, you can re-open it using the command fg in the terminal. In keypresses: <ctrl>+[z]; [f][g][Enter] Encrypt files with Vim: vim -x <file name> This command will prompt you for an encryption key before you view the file (if the file is empty/new, it will then store the password you enter).

Section 5 (astuces supplémentaires)

La coloration syntaxique : Vous pouvez activer la coloration syntaxique dans Vim en utilisant :

:set syntax=on (dans Vim lui-même)

ou

syntax enable (in votre .vimrc)

Masquer Vim dans le terminal : <ctrl>+[z] suspendra une tâche en arrière-plan (testé dans Zsh et Bash). Une fois que vous avez suspendu une tâche, vous pouvez la ré-ouvrir à l'aide de la commande fg dans le terminal.

En frappes, cela donne :

<ctrl>+[z], [f][g][Entrée]

Crypter les fichiers avec Vim :

vim -x <nomFichier>

Cette commande vous demandera une clé de chiffrement avant de voir le fichier (si le fichier est vide/nouveau, elle stockera le mot de passe que vous entrerez).

Viewing History: [q][:] This will pull up a list of past commands. You can enter the number from the list in order to pull up the command, or enter [:][q] to quit the list. Execute system commands from within Vim: [!](command) An example: :w !sudo tee % This will save the file with sudo rights (in case you open a system file and made changes before realizing you had no rights to save the file). Vim will ask you afterwards if it ought to re-load the file, which you'll want to do. Vimdiff: Vimdiff is an extended version of Vim where you can open multiple files to compare them. Usage: vimdiff file1 file2

Affichage de l'historique :

[q][:]

Cela affichera une liste des commandes passées. Vous pouvez entrer le numéro de la liste afin de faire revenir la commande ou entrer [:][q] pour quitter la liste.

Exécuter les commandes système à partir de Vim :

[!](commande)

Un exemple :

:w !sudo tee %

Cela sauvegardera le fichier avec les droits sudo (pour le cas où vous ouvrez un fichier système et le modifiez avant de réaliser que vous n'aviez pas les droits pour enregistrer le fichier). Vim vous demandera ensuite s'il doit recharger le fichier, ce que vous devrez faire.

Vimdiff : Vimdiff est une version étendue de Vim où vous pouvez ouvrir plusieurs fichiers pour les comparer.

Utilisation :

vimdiff fichier1 fichier2

For horizontal split: vimdiff -o file1 file2 For more information: http://vimdoc.sourceforge.net/htmldoc/diff.html Specify that a Tab is 4 spaces (useful for Python users): set tabstop=4 Write this into your .vimrc, and any time you press the tab key, it will actually insert up to 4 spaces. This should be more than enough to keep everyone busy until next month. If you have any questions, comments, or requests, feel free to email me at lswest34@gmail.com. If you do email me, please be sure to include “C&C” or “FCM” in the subject, so that I don't overlook it. My .vimrc file: http://pastebin.com/wv260CJk I hope you've found this article to be interesting. I plan to continue along this path next month. If you have any questions, comments, or suggestions, feel free to email me at lswest34@gmail.com. If you do email me, please include “FCM” or “C&C” (or, as a regular expression: [fFcC][cC&][mMcC]) in the subject header.

Pour une scission horizontale :

vimdiff -o fichier1 fichier2

Pour plus d'informations : http://vimdoc.sourceforge.net/htmldoc/diff.html

Spécifier qu'une tabulation vaut 4 espaces (utile pour les utilisateurs de Python) :

set tabstop=4

Ecrivez ceci dans votre .vimrc, et à chaque fois que vous appuierez sur la touche de tabulation, il insérera en fait jusqu'à 4 espaces.

Cela devrait être plus que suffisant pour garder tout le monde occupé jusqu'au mois prochain. Si vous avez des questions, commentaires ou demandes, n'hésitez pas à m'envoyer un courriel à lswest34@gmail.com. Si vous m'écrivez un courriel, n'oubliez pas d'inclure « C&C » ou « FCM » dans la case Objet, de sorte que je ne passe pas à côté.

Mon fichier .vimrc : http://pastebin.com/wv260CJk

J'espère que vous avez trouvé cet article intéressant. J'ai l'intention de poursuivre dans cette voie le mois prochain. Si vous avez des questions, commentaires ou suggestions, n'hésitez pas à m'envoyer un email à lswest34@gmail.com. Si vous m'envoyez un courriel, prière d'inclure « FCM » ou « C&C » (ou, comme expression régulière : [fFcC][cC&][mMcC]) dans le sujet.

issue56/c_c.txt · Dernière modification : 2012/02/07 13:16 de andre_domenech