Saturday, May 18, 2013

vim: format each long lines and insert just one break afterward

tested long time no good results...

so the goal here sounds simple: say I have

* a long text file (over 50K lines), and
* each line by itself is a nature paragraph, so sometime is very long
(over 1000 charactors).
* there are sometimes one of more empty line in between, sometimes not

I wanted to format it into:

1. if 2 lines are adjoining, add an empty line to as a break
2. if 2 lines already have more than 1 empty lines in between, remove
the extra and make sure only one empty line left.
3. trunk the long lines to multiple lines with each of 80 charactors

initially I though its simple, just a ranged :g can do:

:'<, '>global/.*/exec "normal! gqq"

but this can only do task 3 above. for the task 1 and 2.
I don't know of how to pass the lines found by :g to a function and some
more magic there.

so I turned to a normal function, with which I can read each line and do
some adjustment there:

func! GQeachline(...) range "ping: comments
let lnum=a:firstline

while lnum <= a:lastline

let line = getline(lnum)
let l1len = len(line)
echom "linenum: " . lnum . "length " . l1len

if l1len >= 80
echom "gq this line (" . l1len . " > tw!"
exec "normal! gqqj"
elseif line =~ '^\s*$' "if it's an empty line
echom "this line is empty"
else
echom "this line is short " . l1len
endif

let lnum=lnum+1

endwhile

endfunc

""line number all changed
" let lnum=a:firstline
" while lnum <= a:lastline
"
" let line = getline(lnum)
" let l1len = len(line)
"
" let nlinenum=lnum+1
" let nline=getline(nlinenum)
"
" if nline =~ '^\s*$'
" else
" exec "normal! o\<esc>"
" endif
"
" let lnum=lnum+1
"
" endwhile


command! -range=% -nargs=* GQeachline :<line1>,<line2>call
GQeachline(<q-args>)

map ,gQ :GQeachline<CR>


these doesn't work well either --- once I did a gqq whenver got a
longline, I changed the "current" text lines and so the next iteration
might not work well.
this is especially hard when I tried to insert empty lines based on what
are the current lines
I did some research and didn't find an existing solution on this.

I feel this is a very generic task --- think about you got a ure text
book (bible) and you just want to format it better...

are there a good way to do it?



thanks!

regards
ping

--
--
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

---
You received this message because you are subscribed to the Google Groups "vim_use" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vim_use+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment