2 Comments

Vim Setup for Arduino: Syntax & Tags

I just started working on a new rev of some Arduino code originally written by someone else, consisting of half a dozen PDE files plus two contributed libraries.  The Arduino environment supplies a nice little editor/IDE tool, but my favorite way to explore and author code is in Vim.

In addition to a nice base set of general configuration files and Vim plugins, it’s nice to have two major components in place for a language I’ll be spending time with:

  1. Syntax highlighting
  2. ctags

There’s a regularly-updated Vim syntax file on vim.org, which you may save to your system as ~/.vim/syntax/arduino.vim, then add a file ~/.vim/ftdetect/arduino.vim to help Vim know you’re editing Arduino source files:

au! BufRead,BufNewFile *.pde setfiletype arduino

The Arduino highlighting rules are largely based on C++, and additionally apply special coloriing to Arduino-specific built-ins like loop(), shiftOut(), analogRead() etc.

Generating a tags file require’s a little extra work with your ctags command, as Arduino’s PDE files are not directly supported. But since PDE is really just C++, if we tell ctags to invoke C++ rules to generate its output. The following commands are easily baked into a local shell script or Rakefile for repeat use:

ctags -f tags.cpp `find . -name "*.cpp" -o -name "*.h"`
ctags -f tags.pde --langmap=c++:.pde `find . -name "*.pde"`
cat tags.cpp tags.pde > tags
sort tags -o tags
rm -f tags.*

(Thanks to niva’s forum post that clued me in to the –-langmap argument to ctags.)

Vim uses tags to make your life easier in a number of ways:

  • Navigate directly to a function, variable definition or class, eg. :tag setup
  • Navigate to the tag for the word currently under the cursor via Ctrl=]
  • Auto-complete variable and function names via Ctrl-n in insert mode.
  • Convenient file navigation using the vim-fuzzyfinder plugin

Since I’ve decided to include my contributed libraries’ source code in the same Sketchbook location as my project PDE files, my tag generation commands will also create tags for all the functions, constants and variables designed in those third party libraries, keeping the underlying implementations just one Ctrl-] away from my prying eyes.

I’m still using the Arduino IDE to compile and upload my code, but having Vim configured for rapid navigation and editing has been a great way to dive into an existing Arduino code base, trace its logic and become productive quickly.