1

I have a function that changes the 6th caracter of a line to a dollar symbol ($).

I want it to be performed on several lines, so I naively did a "while" loop using a counter (as shown under).

But I have the feeling that there must be a much simpler, more "vim-esque" way to do that -- my function seems a bit complicated for such a simple task. Maybe I'm wrong, but I would appreciate any simplification/comments.

My current function is :

function! DollarSplit(nlines)
   let current_pos = getpos(".")
   let a:count = 0
   while a:count < a:nlines 
      normal! 6|r$j
      a:count += 1
   endwhile
   call setpos(".", current_pos)
endfunction
3
function! DollarSplit() range
   let current_pos = getpos(".")
   execute a:firstline . "," . a:lastline . "normal! 6|r$"
   call setpos(".", current_pos)
endfunction

See :help function-range-example.

  • Thanks for your answer, it is more in the spirit of what I was looking for, though @Nobe4's regexp was perfect too (and his explanations as well) – Feffe May 17 '16 at 12:10
2

You can use the following replace:

function! DollarSplit(nlines)
   let current_pos = getpos(".")

   execute ',+'.a:nlines.'s/^\(.\{5}\).\(.*\)/\1$\2/g'

   call setpos(".", current_pos)
endfunction

Decomposing:

execute '      " prepare a command
,+             " the command will operate on lines from current to
'.a:nlines.'   " current+a:nlines
s/^            " the command is a substitution, starting at start of line
\(.\{5}\)      " capture the first 5 characters into a group (1)
.              " match any 6th character
\(.*\)         " capture the remaining of the line into a group (2)
/\1$\2         " replace by group 1 $ group 2
/g'            " end the substitution

This will basically create two matching group, surrounding the char you want to replace, and then restore the two groups with a $ inside.

References:

  • :h ranges
  • :h substitute
  • ... I was trying to explain the parts I understood and the part I did not in your regexp, thank you very much haha – Feffe May 17 '16 at 10:56
  • do you understand everything now ? :) – nobe4 May 17 '16 at 10:57
  • I think so yes, thank you very much ! I did not know about the "groups" usage, it seems very useful. Two last little questions if you have time : 1. * means "all that remains in the line" ? 2. One can not add spaces inside the regexp I suppose (to make it more readable for a newbie like me) as they would be interpretated as litteral white spaces ? – Feffe May 17 '16 at 11:07
  • 1
    * means any number of so .* means any number of anything. I'm not sure about the regex formatting, but once you grasp the concept it shouldn't be too hard to read ;) – nobe4 May 17 '16 at 11:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.