Por qué amo a Vim: son las características menos conocidas las que lo hacen tan asombroso

Desde que comencé a usar Vim en 2016, descubrí varias características menos conocidas que Vim ofrece de fábrica sin ningún complemento.

¿Puede cubrir algunos conceptos básicos antes de comenzar a divagar sobre estas cosas nuevas?

¡Oh, por supuesto! Antes de copiar y pegar algunos comandos de una hoja de trucos, voy a hacer una suposición audaz: no estarías leyendo esto si quisieras una hoja de trucos y ya conocieras los conceptos básicos de Vim.

Es posible que haya escuchado que las distribuciones de Linux se envían con un editor de texto de línea de comandos predeterminado llamado Vim,y es posible que desee probarlo.

Por lo tanto, supongamos que eres completamente nuevo en todo este juego y empiezas con lo que necesitamos como conceptos básicos (sin historia / teoría aburrida).

NOTA: Si conoce los conceptos básicos, haga clic aquí para desplazarse más allá de ellos

¿Cuál es su oferta aquí en comparación con toneladas de otros artículos sobre Vim?

La mayoría de los artículos de introducción sobre Vim comienzan con los modos de Vim, insertando, guardando y saliendo. Si realmente te apetece el modo de aprendizaje de perfección teórica, siéntete libre de leer lo que sea de ayuda en los wikilibros.

También hay algunos libros y artículos geniales que le dicen que hay una filosofía detrás de la forma en que funciona Vim y que los comandos en VI / Vim deben combinarse. Absolutamente cierto y estoy seguro de que lo apreciará una vez que se acostumbre al editor y al poder que proporciona.

He escuchado historias divertidas y he visto imágenes divertidas sobre la curva de aprendizaje de Vim. ¿Es eso cierto? ¿Es realmente tan malo?

Bueno, los que odian van a odiar? Sin embargo, según yo, la imagen que de alguna manera da una representación adecuada de Vim es:

La mayoría de los artículos en Vim se refieren a la * curva de aprendizaje * como un * muro * de aprendizaje, pero bueno, hay algo de positividad: ¡mira el otro lado del muro!

Para los principiantes, es literalmente un muro, ya que nunca antes habían hecho algo como esto para usar un editor en la línea de comandos. Lo que más me atrajo cuando comencé como principiante fue la ubicuidad de Vim.

Inicie sesión en cualquier máquina (que no sea de Windows) desde cualquier terminal y, literalmente, puede obtener un editor escribiendo * vi * con los ojos cerrados. ¡El editor aparecerá frente a ti!

Otra cosa que me atrajo es la capacidad de trabajar sin un mouse y sin perder tiempo productivo en el touchpad o en conseguir un mouse para laptop.

Lo sé, lo sé, puedo escuchar a algunos de ustedes gritando “¡Emacs! ¡Emacs! " Lo entiendo. Pero una vez que me enganché a Vim, nunca tuve ningún interés en emacs (puede ser debido a la instalación requerida). Entonces, sí, emacs también es genial, supongo. Siéntase libre de saltar del barco antes de comenzar a navegar en este hermoso viaje con VI (m).

Abrí mi terminal, escribí vi y presioné la tecla de retorno. Todo lo que veo es una pantalla de bienvenida. No puedo escribir a máquina y no sé cómo salir de eso. ¿Estás seguro de que es un editor poderoso con capacidades?

100% seguro. El comportamiento que acaba de presenciar es el * muro * que vimos antes. Créame, VI (m) puede hacer muchas otras cosas. Simplemente tiene sus propias formas de usarlo. Puede editar archivos, abrir pestañas, dividir la pantalla horizontal o verticalmente, navegar por el sistema de archivos, ejecutar comandos de Linux sin salir de su archivo, activar compilaciones de su código fuente sin salir del archivo, marcar directorios, incluso mejor: marcar líneas de un archivo, buscar y reemplazar palabras, por supuesto copiar y pegar y mucho más.

¡Si! Como si fuera un gran problema para un editor apoyarlos. ¡Meh! Todo el mundo hace eso. ¿Cual es el problema?

No hay gran problema, el único problema que veo es la capacidad de concentrarse en su archivo / código sin salir del teclado. Realmente, si no te importa usar un mouse, entonces abre tu editor de MS word / GUI y haz toda la edición que desees.

Lo suficientemente justo. Pero, en serio, ¿por qué no un IDE para algún trabajo?

Bien, entonces eres un desarrollador y te ha gustado un IDE. No, VI (m) no reemplaza su brillante IDE. VI (m) no tiene las increíbles capacidades listas para usar de su IDE. VI (m) es de tamaño pequeño (paquete e instalación) en comparación con los IDE voluminosos y está disponible para su uso sin ninguna configuración e instalación. En serio, VI (m) no es rival para algunas de las grandes cosas que ofrece su IDE.

Suficiente charla, enséñame lo básico

Claro, antes de comenzar, solo tenga en cuenta que cualquier usuario de Vim tiene que lidiar básicamente con el modo de comando y el modo de inserción. No hay escape (literalmente, no la tecla Esc).

Supongamos que está utilizando algún editor y desea eliminar una función larga en lenguaje C. Los pasos simples que debe seguir son: Coloque el cursor al principio de la línea, luego presione Mayús + flecha hacia abajo hasta el final o use el mouse. Esta acción que tuvo que hacer para seleccionar esas líneas requería que * dejara * de escribir y presione las teclas. ¿No es así? No me digas que estabas escribiendo algo y simultáneamente presionaste teclas para seleccionar mágicamente el cuerpo de tu función.

Sé razonable. Detuvo la escritura e hizo el trabajo de selección para decirle a su editor que desea hacer algo con este texto (copiar / cortar / Negrita / cursiva / cualquier cosa).

Esta pausa que tomó es equivalente a estar en modo comando en VI (m). Este es el momento en que le dice a VI (m) que desea realizar algunas acciones en algunas líneas / palabra / cualquier cosa y no va a escribir. Ahora, VI (m) lo saca del modo de inserción y no puede escribir texto en su archivo. Obviamente, el otro modo en el que realmente puede escribir su archivo es el modo de inserción.

Por cierto, si se preguntaba cómo selecciona el cuerpo de la función sin seleccionar texto o usar el mouse, lo logro colocando el cursor en las llaves de apertura y presionando las teclas: d%

Sí, eso elimina el contenido del cuerpo de su función. ¡No, esa no es una combinación espeluznante de teclas para recordar! dindica que desea eliminar algo. %va a mover el cursor al final de la llave correspondiente.

Ahora que hemos establecido los modos básicos, profundicemos en VI básico (m).

Si conoce el nombre del archivo que está escribiendo:

$ vi myfile.c

Si no está seguro del nombre del archivo y desea comenzar a escribir:

$ vi

Tan pronto como abra vi, estará en el modo de comando. Para introducir i modo de nsert, pulse i. Escriba lo que desee. Presione Escpara regresar al modo de comando. Ahora tiene algunas opciones para salir dependiendo de cómo haya abierto vi.

Si usted dio un nombre de archivo: :wvoluntad w rite esos cambios de forma segura en el disco. :qvoluntad q uit el editor. Puede combinar estas acciones con: :wqy Returnclave

If you did not give a filename: :wq filename.c will write the contents to the file filename.c and quit the editor. If you are not interested in the text you wrote and wish to exit without saving anything: :q! and you are out! The ! is required at the end to say : “Yes, I am sure I don’t want to save the contents and I want to get out urgently”

[DEMO] Basic vim usage

To start the vim editor: Use vim command on shell To start editing a file using vim, use : vim filenameasciinema.org

There you go! You just created, edited and saved(or may be not) your first vi file. Congratulations ?

Como mencioné anteriormente, esta no es una introducción para principiantes a VI (m). Hay muchos otros artículos (proporcionaré una referencia al final del artículo) para comenzar. Acabo de insertar esa introducción para que no se sienta decepcionado después de aterrizar en esta página y no encontrar nada que aprender.

Esta es la línea donde los principiantes se despiden de los usuarios intermedios y se dirigen a la sección de referencia para obtener artículos de introducción más brillantes.

Bienvenidos a los usuarios intermedios. Estas son algunas de las capacidades interesantes de VI (m) que no conocía. Pero ahora los uso a diario para ser más productivo.

Para aquellos de ustedes que prefieren TL; DR:

  • páginas de pestañas
  • sesiones
  • números de línea (+ marcas) y copiar / pegar
  • pliegues
  • sangría con =
  • insertar-completar
  • netrw
  • divisiones / ventanas
  • :! y un poco sobre :make

Páginas de pestañas de Vim

¿Mencionaste pestañas en Vim? ¡No sabía que existía!

I know, right! A tab page is a page with one or more windows with a label (aka tab) at the top.

If you are interested in knowing more about windows, buffers, tab pages: technical details

Have a look:

Steps:

  • Open Vim with any file or just Vim: $ vim file1
  • Type the contents of file and get into command mode (Press Esc )
  • :tabedit file2 , will open a new tab and take you to edit file2
  • :tabedit file3 , will open a new tab and take you to edit file3
  • To navigate between these tabs, you can be in normal mode and type : gt or gT to go to next tab or previous tab respectively. You can also navigate to a particular index tab (indexed from 1) using {i}gt where, i is the index of your tab. Example: 2gt takes you to 2nd tab
  • To directly move to first tab or last tab, you can enter the following in command mode: :tabfirst or :tablast for first or last tab respectively. To move back and forth : :tabn for next tab and :tabp for previous tab
  • You can list all the open tabs using : :tabs
  • To open multiple files in tabs: $ vim -p source.c source.h
  • To close a single tab: :tabclose and to close all other tabs except the current one: :tabonly . Use the suffix! to override changes of unsaved files

[DEMO] Tabs in VIM

VIM supports tabs to open multiple files and work with themasciinema.org

I think this feature enables us to effectively save time by sharing the buffer between tabs and enabling us to copy paste between tabs and keep multiple sessions of different tab set for category of work. Example: You can have a terminal tab with all Vim tabs of source code C files only and you can have another terminal tab with all Vim tabs of header files (.h).

Tabs provide so much convenience to keep all my files open and access them when I want. However, isn’t it a pain to open all tabs every time I reboot or close and open the terminal?

Right! We all like to have our own sessions of work in which we work with a set of files and would like Vim to restore that session of tabs the way we left it.

Vim allows us to save and restore those tab sessions! ✋

Steps:

  • Open any number of tabs you wish to work with
  • From any tab, press Esc and enter the command mode
  • Type :mksession header-files-work.vim and hit enter
  • Your current session of open tabs will be stored in a file header-files-work.vim
  • To see restore in action, close all tabs and Vim
  • Either start vim with your session using : $ vim -S header-files-work.vim or open vim with any other file and enter command mode to type: :source header-files-work.vim and BOOM! All your tabs are opened for you just the way you saved it!
  • If you change any session tabs (close/open new), you can save that back using : :mks! while you are in the session

[DEMO] Sessions in VIM

VIM allows users to store their work sessions separately based on the projects they are working on. Users can easily…asciinema.org

Can I copy/cut paste without having to know line numbers?

¡Oh si! Antes solía ver los números de línea ( :set nu) de las funciones que quería copiar / cortar. Digamos que quiero copiar / líneas de corte 34 y 65 años que he usado :34,65y(Copia / Y ANK) o :34,65d(Cortar / D elete).

Por supuesto, contar las líneas y usar {n}yyo {n}dd(¿dónde nestá el número de líneas) no es una opción para cientos de líneas?

Puede haber algunas funciones que abarcan varias páginas y no desea bajar solo para olvidar cuál fue el número de la primera línea. ¡Hay una forma sencilla de lograr esto sin preocuparse por los números de línea!

Pasos:

  • Ingrese al modo normal, vaya a la línea de inicio
  • Escriba mk(marque el punto con el alfabeto 'k' o use cualquier otro alfabeto)
  • Bajar (página abajo o lo que sea) y moverse a la línea final
  • y'k will yank/copy all the lines from start to end
  • d'k will cut/delete all the lines from start to end

I have some annoying long functions at the top of my file and I don’t want to waste my time scrolling or jumping to lines. This may be a lot to ask because this is not an IDE but, by any chance can we fold the code blocks?

Absolutely! Let’s say you want to skip remembering those line numbers and walk around with your new found love *the markers*. Go to the beginning of the function body and type mb . Now, just go to the end of the function body using % (brace matching) or any other convenient technique and press zf'b and you’re done!

Before and after:

If you are comfortable using the line numbers, the command is even easier to remember: :5,16fo (fo stands for code fold). Once you have folded your code, it’s easy to toggle between open and closed views using zo (Open the code fold) and zc (Close the code fold). Don’t stress it so much. Just use za to toggle between open and closed folds ?

Let’s say you spent considerable time folding your functions in a large file, you would obviously want to retain those folds every time you open that file right? (If not, why did you waste your energy folding them!?), so there’s a solution right in your ~/.vimrc . Insert the following lines in ~/.vimrcand your code folds are saved and restored:

autocmd BufWinLeave *.* mkview autocmd BufWinEnter *.* silent loadview

I’m usually careful with my indentation but sometimes, I have to edit some other idiot’s source code and it bugs me to edit his/her code without indentation. Are there any magical keystrokes to make that happen?

Sure! It’s as simple as: =i{ . Really that’s all ! ( i is inner object)

[DEMO] Indentation in VIM

VIM allows blocks of code to be indented with a few keystrokes. All you have to do is place the cursor in a block of…asciinema.org

Before-after:

All you have to do is place the cursor anywhere within a block you want to indent, press Esc to enter normal mode and then: =i{ . Boom! Your entire function body (including inner blocks) is indented.

NOTA: ¿No espera sangría en sus archivos de Python? Solo funciona cuando Vim puede identificar el inicio y el final usando paréntesis de apertura y cierre)

También puede aumentar / disminuir la sangría dentro de un bloque usando >:; i {para aumentar unnd

Puede que esté soñando, pero (* voz temblorosa *), quiero decir, solo quiero intentarlo, Uhmm, puede que esté yendo muy lejos con este, pero (* pausa de 5 segundos *) .. no importa, sigamos a mi siguiente pregunta

Vim tiene la mente bastante abierta para aceptar las críticas o enfrentar el hecho de que no es un IDE, adelante, veamos qué tienes.

Uhmmm, lo siento, pero por casualidad (* jadeo *) con cualquier complemento o algo, ¿vim tiene autocompletado como un IDE?

? Puede que te sorprendas, ¡pero sí! ? y adivina qué…

* redobles de tambor *

* redobles de tambor *

* redobles de tambor *

* redobles de tambor *

¡Sin plugin!

¡Me escuchaste bien! La única condición para que Vim le muestre opciones es "Vim debe saber de lo que está hablando". Podría ser a través de un archivo fuente incluido o funciones o variables definidas.

Todo lo que tiene que hacer es comenzar a escribir y luego presionar Ctrl+nen el modo de inserción.

¡Imagínense los usos! Especialmente si está escribiendo código C y no puede recordar la llamada exacta a la biblioteca OpenSSL, ¡todo lo que tiene que hacer es incluir el encabezado!

[DEMO] Función de autocompletar en VIM

VIM tiene sugerencias de autocompletar para palabras clave, nombres de funciones si se incluyen los archivos de encabezado apropiados o si… asciinema.org

Permítame recordarle nuevamente: ¿No se requieren complementos?

NOTA: Los archivos de encabezado pueden estar en otras ubicaciones de Mac y es posible que Vim no pueda encontrarlos. Solo uso una Mac para iniciar sesión en una máquina Linux. Entonces, si está usando Mac, lo siento.

I understand Vim is just a text editor but if you want me to work without losing focus and without exiting Vim every now and then, what options do I have if I can’t remember all the file names?

Simple, use the file explorer provided by VIM ? Yes, Vim provides a simple file explorer (*without any plugins*). Just type : :Explore from any Vim window and you will see an easy to navigate file explorer which can be navigated using ⬆️ and ⬇️ arrow keys. Press Enter/Return key to open a file/directory. Use :q to exit the explorer and vim. If you do not wish to quit vim and continue working with an open file, you have 3 options:

  1. Open the explorer in a horizontal ( :Sexplore ) or vertical ( :Vexplore ) split and exit the explorer using :q
  2. Abra el explorador en otra pestaña usando :Texplorey salga usando:q
  3. Abra el explorador de archivos en su ventana actual y luego descargue el búfer actual y elimínelo de la lista de búfer usando :bdel(eliminar búfer).
NOTA: también puede usar el comando corto :Expara abrir el explorador de archivos

A veces tengo que repetir los mismos pasos en algunas líneas para editar algo. Estoy bastante seguro de que Vim tendrá alguna característica que me permita hacer esto. Estoy en lo cierto?

100% correcto! Estás hablando de macros y Vim admite macros. Repetir el último comando ejecutado es simple y puede realizar tareas repetitivas simples. Sin embargo, si el procesamiento del texto consta de varios pasos para lograr un resultado, las macros son útiles.

Considere un ejemplo de archivo de encabezado C:

void encrypt_text(char *text, int bytes) void decrypt_text(char *text, int bytes) void process_text(char *text, int bytes) void another_important_function(int bytes, double precision)

Oops! You forgot to put a semicolon at the end of each line and also you just realized that all these functions return an integer error code instead of void.

The steps you need to perform for making change in one line are:

  • Place the cursor at the beginning of the word void
  • Press cw in normal mode to delete the word void and type int
  • Press Esc , move to the end of line using Shift+a to insert ;
  • Press Esc and press ^ to return to the beginning of the edited line

Resulting in:

int encrypt_text(char *text, int bytes); void decrypt_text(char *text, int bytes) void process_text(char *text, int bytes) void another_important_function(int bytes, double precision)

You can just record this sequence of steps and replay it on all 4 lines.

All you have to do is, before you start the sequence, start recording the macro in any alphabet (let’s say a) by pressing qa in normal mode. Now your steps are being recorded in a . Once you are done with all your steps, just press q in normal mode. This will end the recording. To replay these steps, just keep the cursor at the same place where it was placed during macro. Press @a and we’re done! BOOM! Vim will repeat the same steps for you on that line! To repeat it on multiple lines, you can also use @@ after using @a command once

I know Vim is nowhere close to an IDE and I may be having some unreasonable hopes but just a quick question: Remote editing of files possible with Vim?

If you think of it considering the available resources:

[1] Vim

[2] openssh-client (Comes installed with most Linux flavors)

You are in luck my friend! Yes, Vim supports remote editing of files ?

Vim just utilizes the secure connection established by scp (secure copy) provided by openssh-client. There are times when you are working with files on multiple remote machines and it’s a waste of time to log into a machine just to edit one single file! You can relax in your current machine if you just know your remote machine credentials and path.

vim scp://remoteuser@remote_IP_or_hostname/relative/path/of/file

For example: I need to edit a file on 10.0.18.12 stored in /home/dev-john/project/src/main.c and I have login credentials for dev-john, I can access the main.c using:

$ vim scp://[email protected]/project/src/main.c

I can use the relative path because, I can start looking for the file from the home directory of dev-john

TIP: If you access a remote machine frequently, you can create an ssh config file to create a shortcut for the connection. Create a file ~/.ssh/config with

Host remote-dev-machine Hostname 10.0.18.12 User dev-john IdentityFile ~/.ssh/id_rsa

Now you can access your file using:

$ vim scp://remote-dev-machine/project/src/main.c

If it’s confusing to remember the relative path and not intuitive, you can also specify it with an alternative:

$ vim scp://remote-dev-machine/~dev-john/project/src/main.c

Awesome! I’m already thrilled at the out-of-the-box capabilities of Vim. Looks like you’ve a solution to a lot of common editing problems. Let’s see. I have a file with over 2000 lines and the functions of my interest are located at line 9, line 768 and line 1898. I know I can jump to a line using line number but I’m not so good at remembering those numbers. Got anything for me?

Hell yeah! What you’re looking for is a local bookmark solution in Vim using letters. All you have to do is :

  • Place your cursor on any line at any position
  • Press Esc to make sure you’re in normal mode
  • Press m{lowercaseletter} where {lowercaseletter} is any letter from a-z
  • You just created a local bookmark to navigate in your file

To view all your bookmarks: Press Esc and enter command mode, type :marks and hit Enter/Return . You’ll see a list of your bookmarks. To visit any bookmark at any time, just press Esc and type `{lowercaseletter} . Kaboom! You’ll arrive at the exact same location with cursor where you bookmarked. Example:

I have created a local bookmark to line 21, column 18 using a . If I’m editing something on line 1783, I would just press Esc and type `a :

To solve your problem, all you’ve to do is create 3 local bookmarks and quickly jump to them by looking at :marks .

Problem solved ?

What if I told you that you can create global bookmarks too?! ? Yes, it is possible to create global bookmarks too! These are equivalent to your windows or GUI shortcuts (or linux soft/hardlinks) except you don’t need to create an actual link. You heard me right! You can literally jump from editing a file in /dir1 to another file and line in /project/src/ from your Vim without exiting ! ?

Fret not, it’s not a big new thing to remember. All you have to do is:

Use an uppercase letter instead of lower case letter to create a global bookmark. That’s all! Really! You navigate to the global bookmark using the same process. Example: If you’ve created a bookmark using mP , all you’ve to do is press Esc and type `P and BAM! You jump to your global bookmark (Vim remembers the path, so you don’t have to type anything about the path)

You can access the global bookmarks in the same way as local : :marks

:marks mark line col file/text P 53 4 ~/project/src/large-file.c A 11 0 ~/project/README.md

NOTE: If you are not interested in the cursor position and just want to be there at the beginning of you bookmarked line, use 'P instead of `P (Use a single quote instead of back tick to be positioned at the beginning of the line)

I’ve heard that Vim supports window splitting along with tabs! I understand tabs are great and you get to work with multiple open files at once. But, what about splitting? Why would I want that?

Scenarios:

  • You may want to edit a file by looking at another file simultaneously (May be you are defining a C function by looking at it’s declaration in a header file)
  • You may want to edit some portion of a file by looking at the top/bottom portion of the same file simultaneously
  • Your work may require you to edit a file by looking at different portions of different files simultaneously

Vim supports splitting of screen both horizontally and vertically. Even better, you can even browse file system to open a file when you split your screen.

Here are the available options:

:split filename - split window horizontally and load filename :vsplit file - vertical split and open file ctrl-w up arrow - move cursor up a window ctrl-w ctrl-w - move cursor to another window (cycle) ctrl-w _ - maximize current window vertically ctrl-w | - maximize current window horizontally ctrl-w = - make all equal size :sview file - same as split, but readonly :close - close current window

Maximizing a window for work:

Resizing:

CTRL-W [N] - Decrease current window height by N (default 1) CTRL-W [N] + Increase current window height by N (default 1) CTRL-W [N]  Increase current window width by N (default 1)

Is there a way to use file explorer while I split panes? (I can’t remember and type the file names always!)

Of course, all you have to do is type : :Sexplore for horizontal file explorer and :Vexplore for vertical file explorer. You can also use :Vexplore! to open the file explorer on right side (instead of default left)

Again, all this works *without any extra plugins* ?

I am in the middle of editing some code and I quickly need to run a shell command. Should I save my work, exit Vim and run my commands? I bet there is a better way out with Vim

You bet! Vim just doesn’t want you to leave Vim and wants you to continue focussing on your work. Hence the option to execute shell commands from within your Vim. Don’t worry, all your unsaved work is not discarded, you just execute your command and BAM! you are back in your unsaved/saved file safely!

Let’s say you are in the middle of a coding session and you quickly need to head out to take a look at man page of file operations because you forgot the signature! You don’t have to save your work, exit Vim and then check man pages or you don’t have to open another tab just for the man page. You can issue the command from right within the Vim editor.

[DEMO] Unix commands from VIM

VIM allows users to execute shell commands from within VIM without exiting. All you have to do is enter the command…asciinema.org

Guess what! Prepare to be amazed. Vim also supports make command from within your file! All you have to do is navigate to a directory with Makefile . Open any file (Could be your source code) and make all the changes and save it. Wait, there’s no need to exit to see the compilation result. You can trigger your make build from right within Vim:

[DEMO] Trigger make builds from vim

VIM allows users to trigger make builds without exiting VIM. All we have to do is enter the command mode and type :makeasciinema.org

Similarly you can build other targets in your Makefile!

Example: Build directory clean up

I hope these cool features will help you to use Vim more productively.

Your feedback is always welcome.

Feel free to comment, criticize or applaud ?

References:

  • //www.openvim.com/tutorial.html
  • //linuxconfig.org/vim-tutorial
  • ftp://ftp.vim.org/pub/vim/doc/book/vimbook-OPL.pdf
  • //vim.wikia.com/wiki/Tutorial
  • //www.viemu.com/a-why-vi-vim.html
  • //robertames.com/files/vim-editing.html
  • //www.youtube.com/watch?v=wlR5gYd6um0