Herramientas de usuario

Herramientas del sitio


otros:otros:howto:vi

Diferencias

Muestra las diferencias entre dos versiones de la página.

Enlace a la vista de comparación

Ambos lados, revisión anterior Revisión previa
Próxima revisión
Revisión previa
otros:otros:howto:vi [2010/03/30 12:38]
alfred
otros:otros:howto:vi [2020/05/09 09:25] (actual)
Línea 3: Línea 3:
  
 Para entrar en modo de comandos apretaremos //Esc// en modo de inserción. Para entrar en modo de comandos apretaremos //Esc// en modo de inserción.
 +
 +
 ===== Comandos ===== ===== Comandos =====
 | :q! | Salir sin guardar. | | :q! | Salir sin guardar. |
 | :wq | Salir y guardar. |  | :wq | Salir y guardar. | 
 | :w fichero.txt ​ | Guardar en el fichero llamado '​fichero.txt'​ |  | :w fichero.txt ​ | Guardar en el fichero llamado '​fichero.txt'​ | 
-| :w  |  Guardar. | +| :w  | Guardar. | 
 | i | Entrar en modo de inserción. |  | i | Entrar en modo de inserción. | 
-| :77 |  Ir a la línia 77. |  +| :77 | Ir a la línia 77. |  
-| G |  Ir a la última línia. |  +| G | Ir a la última línia. |  
-| dd |  Corta\Elimina la línia actual. | +| dd | Corta\Elimina la línia actual. | 
 | 5dd | Corta\Elimina 5 línias a partir de la línia actual. |  | 5dd | Corta\Elimina 5 línias a partir de la línia actual. | 
-| p |  Pega en la línia anterior a la actual. |  +| p | Pega en la línia anterior a la actual. |  
-| P |  Pega en la línia posterior a la actual. |  +| P | Pega en la línia posterior a la actual. |  
-| u |  Deshace un cambio. |  +| u | Deshace un cambio. |  
-| /perro |  Busca '​perro'​ posteriormente. |  +| /perro | Busca '​perro'​ posteriormente. |  
-| ?perro |  Busca '​perro'​ anteriormente. |  +| ?perro | Busca '​perro'​ anteriormente. |  
-| n |  Sigue la búsqueda. |  +| n | Sigue la búsqueda. |  
-| N |  Da un paso atrás en la búsqueda. |  ​+| N | Da un paso atrás en la búsqueda. |  ​ 
 +===== Otros ===== 
 + 
 + 
 +==== Respuesta en StackOverflow ==== 
 +  * [[http://​stackoverflow.com/​questions/​1218390/​what-is-your-most-productive-shortcut-with-vim/​1220118#​1220118]] 
 +Mencionas cortar con **yy** y te quejas de que casi nunca quieres cortar líneas completas. En realidad los programadores,​ editando del código fuente, a menudo trabajan con líneas completas, rangos de líneas y bloques de código. Aún así, **yy** es una de las muchas formas de trasladar texto al buffer de copia anónimo (o, tal y como se llama en vi, registro). 
 + 
 +La esencia de vi es que es un lenguaje. La primera **y** es un verbo. La sentencia **yy** es una sentencia simple la cual es una abreviación para **0y$**. 
 +  - **0** ir al inicio de línea. 
 +  - **y** recoge el texto desde aquí hasta... 
 +  - **$** hasta el final de esta línea. 
 + 
 +Esto puede ser expresado como **ddP** (elimina la lína actual y copiala en un lugar nuevo, dejando una copia en el registro. La **y** y la **d** son vebos que realizan la acción indicada por el sujeto. Entonces **yW** significa "​recoge de aquí (posición del cursor) hasta el final de la palabra actual"​ y **y'​a** es "​recoge desde aquí hasta la línia marcada como '​a"​. 
 + 
 +Si sólo entiendes lo básico, los movimientos arriba, abajo, derecha e izquierda entondes vi no será más que una copia del notepad. Vale, aún tienes el fortao de sintaxis y la abilidad de manejar ficheros de más de 45kb. 
 + 
 +vi tiene 26 marcas y 26 registros. Una marca se asigna a cualquier posición del cursor con **m**. Cada marca está definida por una letra minuscula. Por lo que **ma** asigna la marca '​a'​ a la posición actual del cursor y **mz** asigna la marca '​z'​. Puedes moverte entre las líneas marcadas usando **'**. Por lo que **'a** se mueve al principio de la línia que contenga la marca '​a'​. Y moverte a la localización concreta de la marca utilizando** `**. Por lo que **`z** irá a la posición concreta de la marca '​z'​. Puedes utilizar estos movimientos como sujetos para sentencias. 
 + 
 +Por lo que una forma de seleccionar texto para copiar es utilizando marcas. Podemos agregar una marca mediante **ma** y luego posicionarnos al final del texto que queremos copiar (o al principio) y utilizar **d`a** (para cortar) o **y`a** (para copiar). Una vez lo tengamos copiado\cortado sólo tendremos que pegarlo con **p**. 
 + 
 +Pero esta sólo es una forma de muchas de copiar\pegar. Por ejemplo **{** y **}** mueve el cursor al inicio y final de un párrafo, por lo que podemos copiar un parráfo con **{d}**, o desde la posición actual con **d}**. 
 + 
 +La búsqueda también puede ser utilizada como sujetos en nuestras sentencias en vi. Puedo utilizar **d/foo** para cortar desde la línea actual hasta la siguiente línea que contenga "​foo",​ y **y?bar** para copiar desde la línea actual hasta la línia anterior más reciente que contenga "​bar"​.  
 + 
 +Además de verbos y sujetos vi también tiene objetos gramaticales,​ serían los registros. vi tiene 26 registros a los cuales accedemos con **"**. Si utilizo **"​add** estoy cortando la línea actual y colocándola en el registro "​a",​ y si utilizo **"​by/​foo** entonces estoy colocando en el registro "​b"​ una copia del texto desde aquí hasta la siguiente línea que contenga foo. Para pegar dsde un registro detrás del cursor utilizaremos **"​bP**. 
 + 
 +<​code>​ 
 +A sampling of more advanced tricks: 
 + 
 +There are a number of : commands, most notably the :% s/foo/bar/g global substitution technique. (That'​s not advanced but other : commands can be). The whole : set of commands was historically inherited by vi's previous incarnations as the ed (line editor) and later the ex (extended line editor) utilities. In fact vi is so named because it's the visual interface to ex. 
 + 
 +: commands normally operate over lines of text. ed and ex were written in an era when terminal screens were uncommon and many terminals were "​teletype"​ (TTY) devices. So it was common to work from printed copies of the text, using commands through an extremely terse interface (common connection speeds were 110 baud, or, roughly, characters per second -- which is slower than a fast typist; lags were common on multi-user interactive sessions; additionally there was often some motivation to conserve paper). 
 + 
 +So the syntax of most : commands includes an address or range of addresses (line number) followed by a command. Naturally one could use literal line numbers: :127,215 s/foo/bar to change the first occurrence of "​foo"​ into "​bar"​ on each line between 127 and 215. One could also use some abbreviations such as . or $ for current and last lines respectively. One could also use relative prefixes + and - to refer to offsets after or before the curent line, respectively. Thus: :.,$j meaning "from the current line to the last line, join them all into one line". :% is synonymous with :1,$ (all the lines). 
 + 
 +The :... g and :... v commands bear some explanation as they are incredibly powerful. :... g is a prefix for "​globally"​ applying a subsequent command to all lines which match a pattern (regular expression) while :... v applies such a command too all lines which do NOT match the given pattern. As with other ex commands these can be prefixed by addressing/​range references. Thus :​.,​+21g/​foo/​d means "​delete any lines containing the string "​foo"​ from the current one through the next 21 lines" while :.,$v/bar/d means "from here to the end of the file, delete any lines which DON'T contain the string "​bar."​ 
 + 
 +It's interesting that the common Unix command grep was actually inspired by this ex command (and is named after the way in which it was documented). The ex command :g/re/p (grep) was the way they documented how to "​globally"​ "​print"​ lines containing a "​regular expression"​ (re). When ed and ex were used, the :p command was one of the first that anyone learned and often the first one used when editing any file. It was how you printed the current contents (usually just one page full at a time using :.,+25p or some such). 
 + 
 +The : addresses can also refer to marks. Thus you can use: :'​a,'​bg/​foo/​j to join any line containing the string foo to its subsequent line, if it lies between the lines between the '​a'​ and '​b'​ marks. 
 + 
 +That's pretty obscure (I've only used something like that a few times in the last 15 years). However, I'll freely admit that I've often done things iteratively and interactively that could probably have been done more efficiently if I'd taken the time to think out the correct incantation. 
 + 
 +Another very useful vi or ex command is :r to read in the contents of another file. Thus: :rfoo inserts the contents of the file named "​foo"​ at the current line. 
 + 
 +More powerful is the :r! command. This reads the results of a command. It's the same as suspending the vi session, running a command, redirecting its output to a temporary file, resuming your vi session, and reading in the contents from the temp. file. 
 + 
 +Even more powerful are the ! (bang) and :... ! (ex bang) commands. These also execute external commands and read the results into the current text. However, they also filter selections of our text through the command! This we can sort all the lines in our file using 1G!Gsort (G is the vi "​goto"​ command; it defaults to going to the last line of the file, but can be prefixed by a line number, such as 1, the first line). This is equivalent to the ex variant :1,$!sort. Writers often use ! with the Unix fmt or fold utilities for reformating or "word wrapping"​ selections of text. A very common macro is {!}fmt (reformat the current paragraph). Programmers sometimes use it to run their code, or just portions of it, through indent or other code reformatting tools. 
 + 
 +Using the :r! and ! commands means that any external utility or filter can be treated as an extension of our editor. I have occasionally used these with scripts that pulled data from a database, or with wget or lynx commands that pulled data off a website, or ssh commands that pulled data from remote systems. 
 + 
 +Another useful ex command is :so (short for :source). This reads the contents of a file as a series of commands. When you start vi it normally, implicitly, performs a :source on ~/.exinitrc file (and Vim usually does this on ~/.vimrc, naturally enough). The use of this is that you can change your editor profile on the fly by simply sourcing in a new set of macros, abbreviations,​ and editor settings. If you're sneaky you can even use this as a trick for storing sequences of ex editing commands to apply to files on demand. 
 + 
 +For example I have a seven line file (36 characters) which runs a file through wc, and inserts a C-style comment at the top of the file containing that word count data. I can apply that "​macro"​ to a file by using a command like: vim +'so mymacro.ex'​ ./​mytarget 
 + 
 +(The + command line option to vi and Vim is normally used to start the editing session at a given line number. However it's a little known fact that one can follow the + by any valid ex command/​expression,​ such as a "​source"​ command as I've done here). 
 + 
 +Usually it's far easier to write such "​macros"​ using Perl, AWK, sed (which is, in fact, like grep a utility inspired by the ed command). 
 + 
 +The @ command is probably the most obscure vi command. In occasionally teaching advanced systems administration courses for close to a decade I've met very few people who've ever used it. @ executes the contents of a register as if it were a vi or ex command. 
 +Example: I often use: :r!locate ... to find some file on my system and read its name into my document. From there I delete any extraneous hits, leaving only the full path to the file I'm interested in. Rather than laboriously Tab-ing through each component of the path (or worse, if I happen to be stuck on a machine without Tab completion support in its copy of vi) I just use: 
 + 
 +   1. 0i:r (to turn the current line into a valid :r command), 
 +   2. "cdd (to delete the line into the "​c"​ register) and 
 +   3. @c execute that command. 
 + 
 +That's only 10 keystrokes (and the expression "cdd @c is effectively a finger macro for me, so I can type it almost as quickly as any common six letter word). 
 +</​code>​
otros/otros/howto/vi.1269952701.txt.gz · Última modificación: 2020/05/09 09:25 (editor externo)