## Using yasnippet to get completion in ref links

| categories: org-mode | tags: | View Comments

This post illustrates an alternative approach to completion in creating ref links compared to the approach shown here . In this approach we use a dynamic yasnippet to do the completion. We start with similar code that I used before to get a list of labels from the buffer. I used a slightly different regexp to recognize links in this version.

label:code-example

(defun get-labels ()
(interactive)
(save-excursion
(goto-char (point-min))
(let ((matches '()))
(while (re-search-forward "label:\$$[a-zA-z0-9:-]*\$$" (point-max) t)
(add-to-list 'matches (match-string-no-properties 1) t))
matches)))

get-labels


Let us see that in action:

(get-labels)

 code-example \\ code:ref-snippet load-snippets

I think the \\ link is an artifact of the regexp in my get-labels code, and it would not appear in other examples.

Now, we are going to create a yasnippet that uses the list returned from get-labels to provide your choices. See http://capitaomorte.github.io/yasnippet/snippet-development.html#sec-3-8 for some details. We will tangle this code block into a local snippets directory.

label:code:ref-snippet

# -*- mode: snippet -*-
# --
ref:${1:$$(yas-choose-value (get-labels))}$0


Now we load the snippets directory.

label:load-snippets

(yas-load-directory "./snippets")


Finally, we can type ref, press tab to complete it, and then select the label you want from a list. Here are some examples:

ref:code-example

ref:code:ref-snippet

That also works! I cannot decide if I like this better than the Emacs completion. yasnippet gives a popup menu, which is not as easy to navigate as the Emacs completion mechanism. It also requires a working yasnippet, which has not made it into my regular work flows too often. I think I like the Emacs completion better (which actually goes through Icicles since I have that installed). I like it better because I do not have to leave the keyboard or use the arrow buttons to choose a label. However, I do need to bind that function to some key to use it, or type in the command name. It turns out I do not use ref links too often, so it is not too burdensome.

Copyright (C) 2014 by John Kitchin. See the License for information about copying.

org-mode source

Org-mode version = 8.2.5h