Emacs Mode for Protobuf editing

I like using Google’s Protocol Buffers (aka protobuf). It is faster and more bandwidth/disk efficient than JSON, but perhaps not quite as simple or flexible.

In protobuf you have messages. In messages, everything is a key/value pair. Keys are tagged to show the type of the value (int, float, string, sub-message), then followed by the value. Keys can be used repeatedly to create something like arrays. The big difference between a protobuf message and a JSON associative array is that in JSON the keys are strings, while in protobuf, the key is a number. Protobuf uses .proto files to describe the messages, primarily to map a text name for keys to a number, and also to describe the type of the field, specify a default value, and to flag it as required/optional/repeated. The messages in the files look something like this:

message Person {
        required int32 id = 1;
        required string name = 2;
        optional string email = 3;

I also like Emacs a lot, and so obviously, I will use Emacs to edit these .proto files. Here is the start of a major mode for editing proto files. Just paste it into a file named protobuf.el, then (require ‘protobuf) in you .emacs file.

(define-derived-mode protobuf-mode c-mode
  "Protocol Buffer" "Major mode for editing Google Protocol Buffer files."
  (setq fill-column 80
          tab-width 4))

(add-to-list 'auto-mode-alist '("\\.proto$" . protobuf-mode))
(provide 'protobuf)

This is my first major mode. It is derived from C mode, and I still haven’t figured out how to add syntax rules for the =1 type stuff required by every line. I hope to get back and flesh this out further eventually.

Leave a Reply