Indent with conditions
I would like to indent every line with 5 spaces when all the next conditions are matched:
1) after an empty line
2) when line starts with a Uppercase letter 3) when the line has more then 80 characters when the file has开发者_JS百科 no textwidth set 4) when the line has more then (textwidth-10) characters when the file has a textwidth set and the next line must not start with a Uppercase letter.Can anyone help me?
This is completely untested, and I'm sure there are more elegant methods, but this should give you a rough idea. I scan every line in the file one at a time, and indent it if one of your conditions is met.
function! Indenter()
let winview=winsaveview()
try
let this_line_num=1
let tw = &textwidth
while this_line_num <= line("$")
let thisline=getline(this_line_num)
let lastline=getline(this_line_num-1)
let firstchar=substitute(matchstr(thisline,"^ *.")," ","","g")
if ( matchstr(lastline,"^.") == "" && this_line_num > 1 )
\ || firstchar =~# "[A-Z]"
\ || ( tw == 0 && strlen(thisline) > 80 )
\ || ( tw != 0 && strlen(thisline) > tw-10
\ && firstchar !~# "[A-Z]" )
sil exe this_line_num . "s#^# #"
endif
let this_line_num+=1
endwhile
finally
call winrestview(winview)
endtry
endfunction
I am assuming that "empty lines" means no whitespace (hence matchstr(lastline,"^.")
) and that lines containing text can have leading whitespace (hence the substitute(matchstr())
command to get the first non-whitespace character.
Hope this helps. Let me know if it falls flat on its face.
精彩评论