Using gtags for code navigation

2 minute read

Introduction

GNU Global, also known as gtags is a source code tagging system that works the same way across diverse environments. It can be used in shell, vim, emacs and more.

Why `gtags`?

  • Independent of any editor.
  • Has capability to treat definition and reference.
  • Substantially faster than cscope and ctags.

Installation

Ubuntu

sudo apt install global

MacOS

Using homebrew.

brew install global

Build from source

  • Get source code from global server and extract it.
wget https://ftp.gnu.org/pub/gnu/global/global-6.6.tar.gz
tar -xvzf global-6.6.tar.gz
cd global-6.6
  • Compile and Install
./configure
make -j4
sudo make install

Using `gtags` in `neovim`

There are lots of ways to use gtags. I prefer to use it in neovim. Same instructions can be used for vim.

We’ll be using plugins to set-up auto tag generation for a project. These plugins re-generate DB when files in project are changed. Thanks to the incremental update support by gatgs re-generation takes only few seconds.

  • My setup for this tutorial:

Plugin installation

We’ll use vim-gutentags and gutentags_plus.

Add these lines to init.lua and run :PackerSync

local use = require('packer').use
require('packer').startup(function()
  -- snip --
  use 'ludovicchabant/vim-gutentags' -- Automatic tags management
  use 'skywind3000/gutentags_plus'   -- Cscope support
  -- snip --
end)

Few more configurations

Use following settings for better experience.

-- Gutentags
-- generate cscope compatible DB
vim.g.gutentags_modules = {'gtags_cscope'}
-- add folders you want to exclude from index e.g. {'tests', 'doc'}
vim.g.gutentags_ctags_exclude = {}
 -- project root detection other that default ones e.g {'.projectile'}
vim.g.gutentags_project_root = {}
-- store DB in different dir so project doesn't get cluttered
vim.g.gutentags_cache_dir= '~/.gutentags'
-- change focus to quickfix window after search
vim.g.gutentags_plus_switch = 1
-- Debugging
vim.g.gutentags_define_advanced_commands = 1

Keymaps

KeymapDescription
<leader>csFind symbol (reference) under cursor
<leader>cgFind symbol definition under cursor
<leader>cdFunctions called by this function
<leader>ccFunctions calling this function
<leader>ctFind text string under cursor
<leader>ceFind egrep pattern under cursor
<leader>cfFind file name under cursor
<leader>ciFind files #including the file name under cursor
<leader>caFind places where current symbol is assigned
<leader>czFind current word in ctags database

Example

Code navigation in cURL source code.

Pressing <leader>cg on Curl_convert_to_network symbol opens a quickfix window with links to defination.

Figure 1: cURL source code navigation

Figure 1: cURL source code navigation