rnso
rnso

Reputation: 24555

How to apply substitution to text in a function in Vim

I know that I can get all the text of the buffer in a function using following code:

let alltext = getline(1,'$')

I also know that following command adds line numbers to all lines in the buffer:

:%!cat -n

However, I am trying to get all text in a function and then add line numbers to this text for further processing.

Following do not work:

let alltext = %!cat -n

or:

let alltext = %s!cat -n

I do not think following is the right approach (I did not try it since it is system command and my seriously misfire):

function Myfn()
   let alltext = getline(1,'$')  
   echo alltext | !cat -n
endfunction

How can I add line numbers to alltext in above function so that subsequent echo alltext will show all lines with numbers prefixed? Thanks for your help.

Upvotes: 1

Views: 55

Answers (1)

romainl
romainl

Reputation: 196606

[range]!cat -n is only "useful" (if ever) in normal mode.

In a scripting context you will need to think differently. The method below uses :help map() and will work in Vim 7.4 and up:

function! Myfn()
   let alltext = getline(1,'$')
   echo alltext
   call map(alltext, 'v:key + 1 . " " . v:val')
   echo alltext
endfunction

Assuming the following content:

foo
bar
baz

the function above will output:

['foo', 'bar', 'baz']
['1 foo', '2 bar', '3 baz']

See :help map() and :help lambda.

If you only care about Vim 8 and up, you can use the new lambda syntax:

function! Myfn()
   let alltext = getline(1,'$')
   echo alltext
   call map(alltext, {key, val -> key + 1 . ' ' . val})
   echo alltext
endfunction

Upvotes: 2

Related Questions