Monday, February 20, 2012

Re: script to insert lines

Christian Brabandt <cblists@256bit.org> a écrit:
>
> Hi eda!
>
> On Mo, 20 Feb 2012, eda wizard wrote:
>
> > Greetings all,
> >
> > I've got lots of Java classes whose fields need Xml attributes - sounds like a perfect job for a Vim script!
> >
> > Given some lines like:
> >
> > private String lName;
> > private String fName;
> > private String eAddr;
> > private int age;
> >
> > I need the script to produce
> >
> > @XmlElement(name = "LName")
> > private String lName;
> > @XmlElement(name = "FName")
> > private String fName;
> > @XmlElement(name = "EAddr")
> > private String eAddr;
> > @XmlElement(name = "Age")
> > private int age;
> >
> > so within the for-loop of my function I need to read each line, extract the field name, tweak it a bit, add the fieldname to a new string and insert that string on a newline before the line in the buffer.
>
> You can probably also loop over the buffer contents, but for your
> example a "simple" :g command would suffice. Let's see:
> 1) for each line, that starts with "private" followed by a word:
> :g/^\s*private \w\+/
> 2) substitute the current line:
> :s/\%(\w\+\s\+\)\{2}\(\w\)\(\w\+\);$/
> 3) by modifying the contents and putting it in front of it:
> @xmlElement(name = "\u\1\2")\r&/
>
> Together, this makes:
> :g/^\s*private \w\+/s/\%(\w\+\s\+\)\{2}\(\w\)\(\w\+\);$/@xmlElement(name = "\u\1\2")\r&/

Perhaps less concise but a little bit easier to follow:

function! XmlElement() range
let n = a:firstline
let max = a:lastline
while n <= max
let name = matchlist(getline(n), '^\s*private\s\+\w\+\s\+\(\w\)\(\w\+\);$')
if empty(name)
let n += 1
else
call append(n-1, '@XmlElement(name = "' . toupper(name[1]) . name[2] . '")')
let n += 2
let max += 1
endif
endwhile
endfunction

Then you can call XmlElement() with a range or in Visual mode.

As for Vim's :for, if I'm not mistaken (and I might be, since I've
always found that surprising), it can't be used as in C by incrementing
a variable; instead, it operates on lists only.

Best,
Paul

--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

No comments: