rejillas ordenar filas espacio entre elementos desplazar derecha columnas columna centrar bootstrap alinear vim

vim - filas - ordenar columnas bootstrap 4



¿Cómo insertar espacios hasta la columna X para alinear cosas en columnas? (7)

Tengo mi código fuente para operadores de copia escrito de la siguiente manera.

foo = rhs.foo; foobar = rhs.foobar; bar = rhs.bar; toto = rhs.toto;

Me gustaría alinear las cosas de la siguiente manera (más humana legible, ¿no?).

foo = rhs.foo; foobar = rhs.foobar; bar = rhs.bar; toto = rhs.toto;

¿Hay una inserción mágica VIM-hasta-columna-N, o algo así que me permita alinear cosas usando un par de teclas por línea?


Hay un buen complemento que hace exactamente eso y más, llamado Align.vim

Para su caso, necesitaría seleccionar su expresión y luego escribir :Align = . Alineará todo, usando = como separador y referencia.

(Hay muchas opciones para alinear, izquierda, derecha, cíclicamente, etc.)

También puede marcar Tabular.vim que proporciona características similares. Vea el screencast there para una demostración.


Las otras respuestas aquí son geniales, especialmente el comentario de @nelstrom para Tabular.vim y su excelente screencast.

Pero si me sintiera demasiado flojo para instalar plugins de Vim, pero de alguna manera dispuesto a usar macros de Vim, usaría macros.

El algoritmo:

For each line, Add tons of spaces before the symbol = Go to the column you want to align to Delete all text up to =, thereby shifting the = into the spot you want.

Para tu ejemplo,

foo = rhs.foo; foobar = rhs.foobar; bar = rhs.bar; toto = rhs.toto;

Coloque el cursor en cualquier lugar de la primera línea y grabe la macro para esa línea escribiendo, en modo normal:

qa0f=100i <Esc>8|dwjq

Que se traduce a:

  1. qa - Grabe una macro en la tecla de acceso rápido a
  2. 0 - Ir al comienzo de la línea
  3. f= - Ir al primer signo igual
  4. 100i <Esc> - (Hay un solo espacio después del i , y el <Esc> significa presionar escape, no escriba "<Esc>".) Inserte 100 espacios
  5. 8| - Vaya a la octava columna (lo siento, tendrá que averiguar manualmente a qué columna se debe alinear)
  6. dw - Eliminar hasta el próximo personaje que no sea de espacio
  7. j - Ir a la siguiente línea
  8. q - Detener la grabación.

A continuación, ejecute la macro almacenada en la tecla de acceso rápido a , 3 veces (para las 3 líneas restantes), colocando el cursor en la segunda línea y presionando:

3@a


Podemos usar estas dos funciones que describí en la ruta siguiente para el mismo escenario: https://.com/a/32478708/3146151

simplemente ponga esas dos funciones en su .vimrc o .gvimrc y llame a las funciones como función normal en su editor siempre que lo desee.

Las funciones que he publicado aquí: https://github.com/imbichie/vim-vimrc-/blob/master/MCCB_MCCE.vim

Necesitamos llamar a esta función en el editor vim e indicar el Número de Ocurrencia del Personaje o Espacio que desea mover y el carácter dentro del número '''' y de la columna.

El número de ocurrencias puede ser desde el comienzo de cada línea (función MCCB) o puede estar al final de cada línea (función MCCE).

para el ejemplo anterior mencionado en la pregunta podemos usar la función MCCB y el carácter podemos usar ''='', por lo que el uso será así en el editor vim.

:1,4call MCCB(1,''='',8)

Así que esto moverá el primer signo = a la 8va columna de la línea número 1 a 4.

Estas son las funciones:

" MCCB - Move the Character to the Column from the Begin of line " This is a function for Moving the specified Character " in a given range of lines to a the specified Column from the Begin of the line " NOTE 1 :- If the specified character and the first character of the line are same " then the number of Occurance (num_occr) will be one less than the actual " NOTE 2 :- Maximum space between the specified character with in the range " of lines should be less than or equal to 80, if we need more than 80 " then we need to insert more spaces by increasing the value 80 in the " "nmap s 80i <ESC>" line inside the function " Usage :- in command mode do it like below " Eg 1:- :5,11call MCCB(1, ''='', 8) " The above command will move the 1st Occurance from the begin of Character = " to the 8th Column of the lines from 5 to 11 " Eg 2 :- :7,10call MCCB(2, ''+'', 12) " The above command will move the 2nd Occurance of Character = to the 12th " Column of the lines from 7 to 10 function! MCCB (num_occr, mv_char, col_num) range if (a:firstline <= a:lastline) nmap s 80i <ESC> let line_num = a:firstline while line_num <= a:lastline execute "normal " . line_num . "G0" . a:num_occr . "f" . a:mv_char . "s" . a:col_num . "|dw" let line_num = line_num + 1 endwhile nunmap s else execute printf(''ERROR : Start line %d is higher thatn End line %d, a:firstline, a:lastline) endif endfunction " MCCE - Move the Character to the Column from the End of line " This is a function for Moving the specified Character " in a given range of lines to a the specified Column from the End of the line " NOTE 1 :- If the specified character and the last character of the line are same " then the number of Occurance (num_occr) will be one less than the actual " NOTE 2 :- Maximum space between the specified character with in the range " of lines should be less than or equal to 80, if we need more than 80 " then we need to insert more spaces by increasing the value 80 in the " "nmap s 80i <ESC>" line inside the function " Usage :- in command mode do it like below " Eg 1:- :5,11call MCCE(1, '';'', 20) " The above command will move the 1st Occurance from the End of Character ; " to the 20th Column of the lines from 5 to 11 " Eg 2 :- :7,10call MCCE(5, ''i'', 26) " The above command will move the 5th Occurance from the End of Character i " to the 26th Column of the lines from 7 to 10 function! MCCE (num_occr, mv_char, col_num) range if (a:firstline <= a:lastline) nmap s 80i <ESC> let line_num = a:firstline while line_num <= a:lastline execute "normal " . line_num . "G$" . a:num_occr . "F" . a:mv_char . "s" . a:col_num . "|dw" let line_num = line_num + 1 endwhile nunmap s else execute printf(''ERROR : Start line %d is higher thatn End line %d, a:firstline, a:lastline) endif endfunction


Sé que esto es viejo, pero pensé que @talklittle tenía la idea correcta, la respuesta acaba de ser prolija. Una forma más rápida es insertar espacios después de = y luego eliminar todos los espacios después de la décima columna como esta:

:1,4 s/^/(.*=/) */(.*/)$//1 /2/ :1,4 s/^/(./{10/}/) */(.*/)$//1/2/


Si está utilizando un entorno tipo Unix, puede usar la column herramienta de línea de comandos. Marque sus líneas usando el modo visual, luego:

:''<,''>!column -t

¡Esto pega el texto seleccionado en el stdin del comando después de ''<,''>! . Tenga en cuenta que ''<,''>! se inserta automáticamente cuando presionas : en modo visual.


Una manera rápida y sencilla de proceder es agregar X espacios y luego eliminar de nuevo a la columna X. Por ejemplo, si X = 40, escriba

40a<Space><Esc>d40|


Una solución alternativa es realizar dos sustituciones consecutivas:

%s/=/ =/ %s//%>7c *//

El truco es el patrón de columna /%>7c que coincide con los espacios en blanco * solo después de la 7ma columna. Aquí foobar es el nombre de la variable más larga con 6 caracteres, por lo que necesitamos 7 en la expresión regular.