Archive for the ‘C/C++’ Category

In this post, we will explore how to set different TAB settings while editing C/C++ and Python code. For C/C++, we want 2 spaces for indendation, while for Python, we will stick to PEP 8 recommendations (4 spaces for indendation, 8 spaces for TAB, 4 spaces for expandtab). Vim being such a powerful and versatile editor, there are many ways to achieve this. We will explore the most portable way – with changes just to the .vimrc.

" Python options
let python_highlight_all = 1
function! s:set_python_settings()
  set tabstop=8
  set softtabstop=4
  set shiftwidth=4
endfunction
function! s:unset_python_settings()
  set tabstop=2
  set softtabstop=2
  set shiftwidth=2
endfunction
autocmd BufNewFile,BufEnter *.{py} call set_python_settings()
autocmd BufLeave *.{py} call unset_python_settings()

What we are doing here is define two functions, set_python_settings() which will change tab settings as per PEP 8 recommendations and unset_python_settings() which will default to our C/C++ settings. Autocmd upon entering a new buffer (BufEnter) or a new file is opened (BufNewFile) of type *py, we call set_python_settings() to set tab settings for Python. When we leave a buffer (BufLeave) of type *.py, we get back to original settings by calling unset_python_settings().

Exuberant ctags is a pretty nifty utility for source code browsing. Especially since it integrates so well with vim. Also exuberant ctags can understand many languages (41 as per the official website). So this is relevant not only for C/C++ or Python but for all 41 languages supported (and future ones too). In this post, we explore yet another popular plugin using exuberant ctags – TagList.

TagList is capable of showing a list of functions/global variables/class/struct towards one side of the vim. This is similar to some IDEs or event editors like Notepad++. This makes browsing and navigation pretty easy. Our aim will be to be able to navigate current file using TagList window and to always display current function name in the status line.

Screenshot of TagList plugin showing current function name in status line

For this, we will need:

TagList will work only with exuberant ctags and not with any other ctags (specifically GNU ctags). Install exuberant ctags if required. Also ensure that ctags command should actually invoke exuberant ctags.

Install TagList plugin (see elaborate steps in the link). Typically vim plugins are installed by simply copying to $HOME/.vim/plugin directory. If any documentation is there, copy that to $HOME/.vim/doc and re-index vim help by giving “:helptags $HOME/.vim/doc” command in vim.

Now we need to customize the TagList plugin options to get what we want.

" TagList options
let Tlist_Close_On_Select = 1 "close taglist window once we selected something
let Tlist_Exit_OnlyWindow = 1 "if taglist window is the only window left, exit vim
let Tlist_Show_Menu = 1 "show Tags menu in gvim
let Tlist_Show_One_File = 1 "show tags of only one file
let Tlist_GainFocus_On_ToggleOpen = 1 "automatically switch to taglist window
let Tlist_Highlight_Tag_On_BufEnter = 1 "highlight current tag in taglist window
let Tlist_Process_File_Always = 1 "even without taglist window, create tags file, required for displaying tag in statusline
let Tlist_Use_Right_Window = 1 "display taglist window on the right
let Tlist_Display_Prototype = 1 "display full prototype instead of just function name
"let Tlist_Ctags_Cmd = /path/to/exuberant/ctags

nnoremap <F5> :TlistToggle
nnoremap <F6> :TlistShowPrototype

set statusline=[%n]\ %<%f\ %([%1*%M%*%R%Y]%)\ \ \ [%{Tlist_Get_Tagname_By_Line()}]\ %=%-19(\LINE\ [%l/%L]\ COL\ [%02c%03V]%)\ %P

Notice the call to Tlist_Get_Tagname_By_Line() within the statuline. This is what displays the current function name (actually tag which can be class name or struct name or any tag) in the status line. With the above settings, pressing F6 will show the prototype of current function at the bottom.

Pressing F5 will open up the TagList window which will show the list of functions/classes/structs/define etc. The focus is automatically switched to the list window and we can quickly jump to the function/class/struct definition we want to. Upon selecting an entry, the list window is automatically closed.shrink the window back to default size.

Screenshot of TagList window

Now with the full prototype display, it is not very easy to read the actual function name. TagList has a zoom feature to overcome this. Press “x” and the TagList window will enlarge, occupying almost the complete vim screen. Selection of an entry or pressing F5 again will close the window. Pressing x again will shrink the window back to default size.

Screenshot of TagList window zoomed using "x" key

TagList generates its own tags file and does not require the user to provide a tags file. This file is generated every time we switch to a buffer. The tags file is created somewhere in /tmp/ folder. TagList cannot work with a user generated tags file.

Omni Completion in Vim

Posted: August 26, 2010 in C/C++, Programming, Vim
Tags: , , ,

Vim 7 onwards, we have Omni Complete feature. This feature is similar to IntelliSense in Visual Studio or other IDEs. It can show a pop up menu displaying the structure, class or scope context. Here is a screenshot of Omni Complete displaying the class scope in CCCC code base .

OmniCppComplete screen shot in CCCC code.

As you can see, it can show all methods and variables including its original context like type, prototype (in case of method), documentation (if documented), private/protected/public, file defined in etc.

For getting Vim to work like this, you will need

Install all 4 by whatever means (apt-get, yum, build from source). OmniCppComplete and SuperTab are Vim scripts, detailed installation steps are given in the respective links. GNU has a version of ctags. But what we need is exuberant ctags which is different from GNU ctags. Most popular Linux distros bundle GNU ctags, but exuberant ctags should be available from the repository.

Vim is an excellent editor, but does not understand C/C++ natively. This is where ctags comes in to the picture. Ctags will generate a “tags” file which is like an index of the project source code. This tags file is used by Vim and OmniCppComplete script to provide contextual data in a pop-up menu.

To build a ctags tags file, give the command from the top directory of the project. This can be done from any subdirectory too (for even more focused tags file).

ctags -R --languages=C,C++ --c++-kinds=+p --fields=+iaS --extra=+q ./

Run vim from the same directory. By default, Vim will search for tags file beginning from current directory to all parent directories. First tags file found will be used. For better usability of OmniCppComplete, put these in your .vimrc file.

if v:version >= 600
  filetype plugin on
  filetype indent on
else
  filetype on
endif

if v:version >= 700
  set omnifunc=syntaxcomplete#Complete " override built-in C omnicomplete with C++ OmniCppComplete plugin
  let OmniCpp_GlobalScopeSearch   = 1
  let OmniCpp_DisplayMode         = 1
  let OmniCpp_ShowScopeInAbbr     = 0 "do not show namespace in pop-up
  let OmniCpp_ShowPrototypeInAbbr = 1 "show prototype in pop-up
  let OmniCpp_ShowAccess          = 1 "show access in pop-up
  let OmniCpp_SelectFirstItem     = 1 "select first item in pop-up
  set completeopt=menuone,menu,longest
endif

The default key mapping for invoking Omni Completion is C-X C-O. SuperTab plugin can help us invoke Omni Complete when we press TAB key. Also in the default color scheme, vim pop-up menu is in pink. Let’s change that to green.

if version >= 700
  let g:SuperTabDefaultCompletionType = "<C-X><C-O>"
  highlight   clear
  highlight   Pmenu         ctermfg=0 ctermbg=2
  highlight   PmenuSel      ctermfg=0 ctermbg=7
  highlight   PmenuSbar     ctermfg=7 ctermbg=0
  highlight   PmenuThumb    ctermfg=0 ctermbg=7
endif

As we edit code, newer types get defined, but vim continues to use the same tags file. So we need to regularly update our tags file. We can add a shortcut map (say pressing F4) in our .vimrc for the same.

function! UpdateTags()
  execute ":!ctags -R --languages=C++ --c++-kinds=+p --fields=+iaS --extra=+q ./"
  echohl StatusLine | echo "C/C++ tag updated" | echohl None
endfunction
nnoremap <F4> :call UpdateTags()

Vim is all about customizing it to your tastes. You can never get the perfect .vimrc file or plugin collection and settings from anywhere. The trick is to collect cool stuff for your .vimrc and plugins. Vim tips wiki in wikia is a good place for a lot of info. Play around with them. Find what suits best for you. And never forget to share. Happy coding 🙂