On Tue 5-Dec-06 10:29pm -0600, Sibin P. Thomas wrote: > While we are at the subject of tips for budding Vim > scripters - I had created this mapping --> > > nmap com ^:if search('\/\*.*\*\/','c',line("."))!=0<CR> > :.s/\/\*\(.*\)\*\//\1/g<CR> :else<CR> > :.s/\(\s*\)\(.*\)\(\s*\)/\1\/\*\2\*\/\3/g<CR> :endif<CR> :noh<CR> > > this command basically toggles C-style commenting on a > line i.e. if the line wasn't commented it comments out the > entire line and vice-versa. I spent an intense hour of > exploring the help pages and plenty of effort in trial and > error before I could reach the 'Eureka' moment.
The first thing I would do is ask myself whether the approach is adequate. For example, how does it handle common lines of code such as: /**/ a = b; /* comment */ /**/ a = b; a = b; /* comment */ It converts them to: */ a = b; /* comment a = b; a = b; comment Is that intended? Also, will the user only want to work with one line at a time or will a typical use be for a block of code? Two other solutions would be to use (1) the preprocessor '#if 0' start and '#endif' end, or (2) use the c99 '//' (perhaps with a following character to identify code your map has commented out. > What I wanted to know is could the same functionality have > been achieved by a better sequence of commands? Can an > experienced 'vimmer' do better? Without changing functionality of the provided code, you could preserve both the command line (with <silent> and :silent) and the '/' register (which also prevents the visible flashing). You don't need to escape '/' in the first arg of search() and can avoid escaping them in the :substitute commands if you use another separator. The 'g' flag doesn't appear to do anything in this context (for both :substitute commands). Finally, you code is apparently intended to be on one long line. Using continuation allows you to keep lines no longer than 80 characters. Here's a quick rewrite: nmap <silent> com ^:let com_hold=@/ \\|if search('/\*.*\*/','c',line("."))!=0 \\|silent s#/\*\(.*\)\*/#\1# \\|else \\|silent s#\v(\s*)(.*)(\s*)#\1/\*\2\*/\3# \\|endif \\|let @/=com_hold\|unlet com_hold<CR> -- Best regards, Bill