Loading ...
Sorry, an error occurred while loading the content.
 

Re: Adding numbers to lines

Expand Messages
  • Colin Keith
    ... The way to think (well the way that I thought about this) was to use a global substitution to insert the number at the beginning of the line. As you re not
    Message 1 of 4 , Jun 30, 2002
      On Sun, Jun 30, 2002 at 11:13:59AM +0200, Wouter Brok wrote:
      > Is there any way this can be accomplished (there must be of course ;) a
      > better question would be: how is this accomplished)?

      The way to think (well the way that I thought about this) was to use a
      global substitution to insert the number at the beginning of the line.
      As you're not just incrementing the line number by 1 each time, but
      reseting it after each paragraph it made it a little more complex, so
      I used a function to perform the calculations for the count value (g:x)


      Anyway:

      :%s/^\(.\?\)/\= Test(submatch(1))/

      Which says look for the first character at the start of the line and store
      it away. The \? says it can be 0 or 1 characters. We have to allow this as
      you want to match the empty lines so you can reset the counter to 0. As the
      regexp is greedy it will match 1 character if it can and store an empty
      string if it can't. This is retreived using submatch(1) (the first match)
      and passed through to Test() (you can always rename the function :)
      The 0 or 1 means that a:match can be empty in the function - and we test
      that to see if the counter should be reset.

      The line('.') tests save you having to let g:x = 0 before you run it, and
      unlet g:x afterwards (I'm lazy like that :)


      function! Test(match)
      if(line('.') == 1)
      let g:x = 0
      endif

      if a:match == ''
      let g:x = 0
      return ''
      endif

      let g:x = g:x + 1
      let out = g:x .' '. a:match
      if(line('.') == line('$'))
      unlet g:x
      endif
      return out
      endfunction


      --
      Then graphics games came along and the computer using portion of the human race
      forgot all about 500,000 years of language evolution and went straight back to
      the electronic equivalent of banging rocks together - the point'n'click game
      - http://www.douglasadams.com/creations/infocomjava.html
    Your message has been successfully submitted and would be delivered to recipients shortly.