LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   vimscript: how delete a variable number of lines (https://www.linuxquestions.org/questions/programming-9/vimscript-how-delete-a-variable-number-of-lines-4175476528/)

porphyry5 09-09-2013 05:31 PM

vimscript: how delete a variable number of lines
 
In a vimscript I need to repeatedly delete lines from the buffer, but the number of lines to delete will vary with each iteration of the loop.
:d is the only command I know of that will remove entire lines, but how can I use it with a variable specifying the number of lines to be deleted?

TobiSGD 09-09-2013 06:31 PM

You can do it with a loop, like this:
Code:

:let linesToRemove =3
:while linesToRemove > 0
:  d
:  let linesToRemove -=1
:endwhile


porphyry5 09-09-2013 06:48 PM

Quote:

Originally Posted by TobiSGD (Post 5024902)
You can do it with a loop, like this:
Code:

:let linesToRemove =3
:while linesToRemove > 0
:  d
:  let linesToRemove -=1
:endwhile


Many thanks. I also did it by setting marks and deleting between the marks, i.e
Code:

    :normal ma 
    :call cursor(lno, 1) 
    :normal mb 
    :'a,'bd

where lno is the line number of the last line of the group to be deleted

TobiSGD 09-09-2013 07:53 PM

Looks more elegant than a loop, definitely, but it may be not a good idea to change marks, especially when you deploy your script to other users. I thought about that and with a little reading in the Vim documentation I found this way to do it:
Code:

"Get the line number of the current cursor position
"for info on that look at http://vimdoc.sourceforge.net/htmldoc/eval.html#line()
:let cLine = line(".")

"Since in your case lno already contains the number of the last line
"in the block more math is not necessary, of course any kind of arithmetic
"to determine the last line can be done here

"Okay, now we need to create the command to delete the block and execute it
"More info: http://www.cs.csubak.edu/docs/vim/eval.html#:execute
:execute cLine . "," . lno . "d"

"For some reason you can't execute the command directly like
":cLine,lnod
"This will throw an error E488

This solution looks more complicated, but will not touch marks (that are possibly already set by the user).


All times are GMT -5. The time now is 12:13 AM.