Create a new mode in Emacs

2019-04-11 06:31发布

问题:

I know nothing about Emacs Lisp (or any Lisp, for that matter). I want to do something that seems very simple, yet I have had no luck with online guides. I want to create "packet-mode.el" for .packet files. I want to do the following:

  • Enable C++ mode
  • Make packet a keyword, while leaving the rest of C++ mode unchanged
(define-derived-mode packet-mode fundamental-mode
  (font-lock-add-keywords 'c++-mode `(("packet" . font-lock-keyword-face)))
  (c++-mode))

  (add-to-list 'auto-mode-alist '("\\.packet\\'" . packet-mode)
  (provide 'packet-mode)

I've also tried switching the order of the statements in packet mode, but then the C++ highlighting breaks.

I would like packet to behave like struct in the sense that

packet foo {
  int bar;
}

is highlighted the same way it would be if struct were used in place of packet.

回答1:

Here is what you need to put into packet-mode.el:

(defvar packet-mode-font-lock-keywords
  '(("\\<packet\\>" . font-lock-keyword-face)))
(define-derived-mode packet-mode c++-mode "Packet"
  "A major mode to edit GNU ld script files."
  (font-lock-add-keywords nil packet-mode-font-lock-keywords))
(add-to-list 'auto-mode-alist '("\\.packet\\'" . packet-mode))
(provide 'packet-mode)

Place packet-mode.el into a directory in your load-path and (optionally) byte compile it.

Now, add (require 'packet-mode) into your .emacs.el.



标签: emacs elisp