Wikia

Vim Tips Wiki

Macro expansion C/C++

Talk0
1,613pages on
this wiki

Proposed tip Please edit this page to improve it, or add your comments below (do not use the discussion page).

Please use new tips to discuss whether this page should be a permanent tip, or whether it should be merged to an existing tip.
created April 10, 2014 · complexity basic · author TTRh · version 7.0

This tip shows a function to expand a C/C++ macro using the gcc compiler.

The function expands a specific line in a preview window as the gcc compiler sees it. Normally this function deals with severals tab/buffer/windows.

Macro expansion with gccEdit

Here is the function :

function! ExpandCMacro()
  "get current info
  let l:macro_file_name = "__macroexpand__" . tabpagenr()
  let l:file_row = line(".")
  let l:file_name = expand("%")
  let l:file_window = winnr()
  "create mark
  execute "normal! Oint " . l:macro_file_name . ";"
  execute "w"
  "open tiny window ... check if we have already an open buffer for macro
  if bufwinnr( l:macro_file_name ) != -1
    execute bufwinnr( l:macro_file_name) . "wincmd w"
    setlocal modifiable
    execute "normal! ggdG"
  else
    execute "bot 10split " . l:macro_file_name
    execute "setlocal filetype=cpp"
    execute "setlocal buftype=nofile"
    nnoremap <buffer> q :q!<CR>
  endif
  "read file with gcc
  silent! execute "r!gcc -E " . l:file_name
  "keep specific macro line
  execute "normal! ggV/int " . l:macro_file_name . ";$\<CR>d"
  execute "normal! jdG"
  "indent
  execute "%!indent -st -kr"
  execute "normal! gg=G"
  "resize window
  execute "normal! G"
  let l:macro_end_row = line(".")
  execute "resize " . l:macro_end_row
  execute "normal! gg"
  "no modifiable
  setlocal nomodifiable
  "return to origin place
  execute l:file_window . "wincmd w"
  execute l:file_row
  execute "normal!u"
  execute "w"
  "highlight origin line
  let @/ = getline('.')
endfunction

A useful mapping to call the function is:

autocmd FileType cpp nnoremap <leader>m :call ExpandCMacro()<CR>

The function depends on the gnu program indent which could be replaced by some tricky search/replace operations.

PreviewEdit

CommentsEdit

Any ideas about the preview? It shows nothing for me, presumably because I don't have all scripts enabled. JohnBeckett (talk) 06:17, April 11, 2014 (UTC)

Around Wikia's network

Random Wiki