sponsor Vim development Vim logo Vim Book Ad

intermediate Tip #1434: as you type (or paste) in Makefile, autoconvert leading eight spaces to tab

 tip karma   Rating 1/3, Viewed by 375 

created:   December 7, 2006 16:54      complexity:   intermediate
author:   Yakov Lerner      as of Vim:   6.0

[ this tip is only for those who edit Makefiles by hand]
Makefiles punish you if instead of single tab somebody puts eight spaces in your makefile (happens  when pasting between Makeiles). But those treacherous Makefiles did not suspect that we have now  this little vimscript piece.  It guards against this annoying pitfall (but you must have ':set nopaste' set for this helper to work.)

The following piece auto-converts 8 spaces at the beginning of line (only in Makefiles, and only at the beginning of line) into tab, as you type or paste. It is suggested to have ':set list' in Makefiles, too.  This piece will only work if 'set nopaste' is set.

"****************
" In Makefile, automatically convert eight spaces at the beginning
" of line to tab, as you type (or paste)
"*****************
au FileType make :inoremap <buffer><silent><space> <space><c-o>:call MapSpaceInMakefile()<cr>
function! MapSpaceInMakefile()
    " if this space is 8th space from the beginning of line, replace 8 spaces with
    " one tab (only at the beginning of file)
    let line = getline('.')
    let col = col('.')

    if strpart(line, 0, 8) == '        '
        let new = "\t" . strpart(line,8)
        call setline('.', new )
    endif

    return ""
endfunction

 rate this tip  Life Changing Helpful Unfulfilling 

<<Use of vim to convert files mangled by Palm OS memo conduit | use recording to easily add function skeletons from prototypes >>

Additional Notes

MJ, December 8, 2006 0:55
You really don't need a script for this! Use the subsitution command (:help :s):
       :s/^ \{8}/^V<tab>/
(^V<tab> means pressing CTRL-V and the press the <tab>-key)
or s/^ \{8}/^Q<tab>/ on windowz.
Yakov Lerner, December 8, 2006 6:19
Your command above does not fix as you type.
Wu Yongwei, December 11, 2006 17:18
A competent programmer should not err when typing. It is more likely to occur on paste, when one generally will `:set paste'. Alas....
If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to [email protected] after searching the archive. Help Bram help Uganda.
    stats
Sponsored by Web Concept Group Inc. SourceForge.net Logo