Skip to content

Instantly share code, notes, and snippets.

@koron
Created March 27, 2013 00:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koron/5250637 to your computer and use it in GitHub Desktop.
Save koron/5250637 to your computer and use it in GitHub Desktop.
Script to correct indentations of pragma with considering ifdef/endif nests. Vimのソースコード内のpragmaをifdefのネストを考慮したindentに修正するスクリプト。対象のソースを開いた状態で `source fix-ifdef-indent.vim` すると、インデントを修正しかつ修正した行番号一覧を表示する。
" vim:set ts=8 sts=2 sw=2 tw=0 et:
function! s:FixIfdefIndent()
let lnum = 1
let lend = line('$')
let wrong_lnums = []
let base_level = 0
while lnum <= lend
let str = getline(lnum)
let parsed = matchlist(getline(lnum), '^\(\s*\)#\(\s*\)\(\S\+\)\(.*\)$')
if len(parsed) > 0
let indent1 = parsed[1]
let indent2 = parsed[2]
let pragma = parsed[3]
let remain = parsed[4]
if pragma =~# '^endif'
if base_level == 0
echoerr "Too match #endif at " . lnum
break
end
let base_level -= 1
endif
let expected_level = base_level
if pragma =~# '^\(else\|elif\)'
if expected_level == 0
echoerr "Too match #else/elif at " . lnum
break
end
let expected_level -= 1
endif
let actual_level = len(indent1) + len(indent2)
if actual_level != expected_level
call add(wrong_lnums, lnum)
let indent = repeat(' ', expected_level)
call setline(lnum, printf('#%s%s%s', indent, pragma, remain))
endif
if pragma =~# '^if'
let base_level += 1
endif
endif
let lnum += 1
endwhile
return wrong_lnums
endfunction
echo s:FixIfdefIndent()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment