On Sun, 7 May 2006, Meino Christian Cramer wrote:

Hi,
[snip]

OK, if you're just starting out, before writing scripts, you would need
to jump through a few hoops first. Please pardon me if you are already
familiar with what I'm about to write. I'm just taking it from the top.

First, get familiar with the :help system of Vim. You will be using it a
lot, so make sure you understand

  :help help-context

It consists of foru lines:

:normal gg
:normal %s/^[ ]*//g
:normal gg
:normal %s/[ ]*$//g

Other versions I tried were:

:normal gg
:normal %s/^[ ]*//g<CR>
:normal gg
:normal %s/[ ]*$//g<CR>

and

:normal gg
:normal :%s/^[ ]*//g<CR>
:normal gg
:normal :%s/[ ]*$//g<CR>

Then as Eric mentioned, you would need to get familiar with all the
modes of Vim to really make it fly. For this, read this and commit to
memory if possible:

  :help mode-switching

Commiting it to memory is as easy as trying it out to switch between
modes. Don't bother memorizing, just try to use it daily.

One thing to remember when scripting in Vim is that you can always
___manually___ go through every script line. In the case of your 4
lines, you would find that

  :normal gg

does its job. That is, start Vim, type ":normal gg" and hit Enter.

But when you try all of these

  :normal %s/^[ ]*//g
  :normal %s/^[ ]*//g<CR>
  :normal :%s/^[ ]*//g<CR>

and press Enter,

it just won't work. You'll know that the second line has problems. What
would you do if you wanted to do a :substitute command while you were in
Vim? I think you would do

  :%s/^[ ]*//g

and press Enter, just as you illustrated in your script (with the
unnecessary <CR>). See how the :s command above matches the ":normal gg"
command that worked? Place the :s command into your script then:

  :normal gg
  :%s/^[ ]*//g

and now you have 2 working lines of script code.

(Intention is to strip off all leading and trailing white space from
a file. It is an experiment, so I choose this basic task. May be
there is one command to achieve this, but as said...I used this as an
exercise.
[snip]

To be really productive in Vim, you could learn more about Vim's regular
expressions. Regexes allow you to do the "one command to achieve this"
deal.

So, in your case of removing leading and trailing white space, this
would do it:

  :%s/^\s\+\|\s\+$//g

Info on the regex elements I used can be found at

  :help /\s
  :help /\+
  :help /\|

Now I noticed that you did a couple of

  :normal gg

It's good that you're thinking in terms of the cursor position. It'll
become useful later (in search ranges, see ":help :range"), but in your
case, you are applying the :substitute command to all lines by
specifying "%" in ":%s".

Hopefully, that's enough to get you started :)

HTH.
--
Gerald

Reply via email to