At @Drew's suggestion, here's a short example of combining YASnippet and auto-insert
to achieve dynamic or interactive boilerplate.
From my ~/.emacs.d/init.el
:
;;{{{ yasnippet & auto-insert
(use-package yasnippet
:config
(add-to-list 'yas-snippet-dirs "~/.emacs.d/snippets")
(yas-global-mode 1))
(defun nega/yas-cmake-bp ()
(interactive)
(yas-expand-snippet (yas-lookup-snippet "cmake_minimum_required" 'cmake-mode)))
(use-package autoinsert
:config
(setq auto-insert-query nil)
(auto-insert-mode 1)
(add-hook 'find-file-hook 'auto-insert)
(setq auto-insert-alist nil) ;; remove this like to restore defaults
(add-to-list 'auto-insert-alist '("CMakeLists\\.txt$" . [nega/yas-cmake-bp])))
;;}}}
Block-by-block, we:
- Load
yasnippet
, set the user-defined snippet location to ~/.emacs.d/snippets
, and enable yasnippet
globally
- Define a callable function that "executes" the snippet named "cmake_minimum_required" from the "cmake-mode" snippet table
- Load
autoinsert
and configure it to
- Do not ask when inserting
- Enable
auto-insert-mode
globally
- Run auto-insert when a new file is opened
- Delete any default "auto inserts"
- Add a filespec + function pair to the list of "auto inserts"
With these three blocks of elisp, every time I open a new file named "CMakeLists.txt", the following YASnippet snippet will be "executed" and the corresponding text will be inserted in to the new buffer.
# name: cmake_minimum_required
# key: cmr
# --
cmake_minimum_required(VERSION ${1:`cmake-mode-cmake-version`}${2: FATAL_ERROR})
$0
The buffer for my new "CMakeLists.txt" looks like:
cmake_minimum_required(VERSION 3.11.1 FATAL_ERROR)
^
The cursor is at the location of the carrot, ie: before the "3". My snippet has found the current version of CMake on my system, and inserted it at that point. This is an editable field, so I change it if I wish. If I edit it, or not, I hit TAB to move to the next field, which is " FATAL_ERROR". (Yes, in this case it contains the space.)
FATAL_ERROR
is an optional argument to cmake_minimum_required()
. If I want to keep it, I can press TAB again or Ctrl+d to delete it. Either way the cursor moves to first column of the second line, and we're ready to continue typing.
Note that you can have "traditional auto inserts" and "YASnippet auto inserts" in auto-insert-alist
. But, you will run into trouble if your filespecs overlap.