How to write helm extensions

From WikEmacs
Revision as of 14:21, 4 February 2015 by Elvince (talk | contribs) (helm and prefix functions)
Jump to navigation Jump to search

This documentation was initiated thanks to John Kitchin's articles on his blog.

So you have been integrating helm into your emacs work flows almost anywhere and you need to make interactive selections and do something with them ? In this post, we will go through the simplest helm examples we can think of that get you to writing your own example.

Basic call

To run a helm selection process you basically just call a function that calls this minimal function:

(helm :sources '(some-helm-source))

In that code, the symbol some-helm-source will provide the input for the helm buffer.

A list of candidates and an action

Let us look at the simplest example here. Each source should have

  • a name,
  • a list of candidates,
  • and an action that works on the selected candidate.

We construct a source as a list of cons cells. Here, we make a source with the name "HELM at the Emacs", a static list of candidates, which are simply a list of numbers, and a single action that will operate on the selected candidate.

If you run this block, you will get a helm buffer, you can select an entry, press enter, and you should see a message box pop up telling you what entry you selected. I like to separate the source definition from the helm call like this, but only for readability.

(setq some-helm-source
      '((name . "HELM at the Emacs")
        (candidates . (1 2 3 4))
        (action . (lambda (candidate)
                    (message-box "%s" candidate)))))

(helm :sources '(some-helm-source))
   3

Dynamic candidates

Not bad, but what if we want some dynamic candidates? The usual way we will do that is to define a function that calculates the candidates for us. Let us work out an example that just shows us random numbers between 0 and 10 to select from. In a real example, you would use this function to generate a list of candidates like bibtex keys, email-addresses, etc…

(defun random-candidates ()
  "Return a list of 4 random numbers from 0 to 10"
  (loop for i below 4 collect (random 10)))

(setq some-helm-source
      '((name . "HELM at the Emacs")
        (candidates . random-candidates)
        (action . (lambda (candidate)
                    (message "%s" candidate)))))

(helm :sources '(some-helm-source))

Separate candidates' sets for searching and for actions

So far, we have looked at the simplest list of candidates: a simple list. It may be that this is not the most convenient way to see the candidates. We might like to have one set of candidates that we use for searching, but another set of equivalent candidates used for the action. For example, we might want a list of names for selecting, but then have the action work on the corresponding email address. Let us consider a case where we have a list of cons cells of names and email addresses.

We use the `, way to create the source variable to make sure our list of candidates is constructed. Then, in our function we take the selection and get the corresponding entry in the data a-list.

(setq data '(("John" . "john@email.com")
             ("Jim" . "jim@email.com")
             ("Jane" . "jane@email.com")
             ("Jill" . "jill@email.com")))

(setq some-helm-source
      `((name . "HELM at the Emacs")
        (candidates . ,(mapcar 'car data))
        (action . (lambda (candidate)
                    (message "%s" (cdr (assoc candidate data)))))))

(helm :sources '(some-helm-source))
   jim@email.com

That is not too bad, and might be a general way to get to the data you want. But, helm can integrate this directly by using the a-list directly as the list of candidates. Helm will show you the car of each cell, but return the cdr of the selected entry.

Let us try this to make a function that will give us a helm buffer to select some names from, and then insert a comma separated list of emails from our selection at the point. We make our action function just return the list of marked candidates. Then we create a function that calls helm, and inserts a concatenated string.

(setq data '(("John" . "john@email.com")
             ("Jim" . "jim@email.com")
             ("Jane" . "jane@email.com")
             ("Jill" . "jill@email.com")))

(setq some-helm-source
      `((name . "HELM at the Emacs")
        (candidates . ,data)
        (action . (lambda (candidate)
                    (helm-marked-candidates)))))

(defun helm-select-and-insert-emails ()
  (interactive)
  (insert
   (mapconcat 'identity
              (helm :sources '(some-helm-source))
              ",")))
   helm-select-and-insert-emails

Here is what I get when we run the command, select John and Jill, and press enter: john@email.com,jill@email.com

More than one action

We now consider how to have more than one action for a selection. When you press enter, helm runs the default action defined, but you can define more than one action, and choose which one to run. How do you know if there are multiple actions? Press C-z in helm and you will get a new helm buffer showing the actions. The first action is the default, and you can select the the actions with function keys, e.g. f1 is the first action, f2 is the second action, or you can select the action and press enter.

The main difference in setting up multiple actions is that instead of a single function for action in the source definition, we provide a list of cons cells for the action element of the helm source. Each action cons cell should have a descriptive string as the car that identifies the action. This will be shown in the helm buffer. The cdr should be the function to run on the candidate. The function will be called with the selection, so the function must take one argument.

Here is an example where we have two actions. The default action will just show us the email address of the selected candidates in a message box. It will show as a list. The second action opens an email window and inserts the selected candidates in the To: field as a comma separated list. I use helm-selected-candidates in these functions instead of the just the current selected candidate so we can have multiple selections. I define the first function as a lambda function, and the second one as a defun to illustrate how to use both approaches. You can have as many actions as you want, so you could consider functions that open notes about the person, or open your contacts to look up a phone number, or functions with template emails you send often, etc…

Now, you have these options to run those actions.

  • Make a selection and press enter. That runs the first (and default) action to show you a message box.
  • Make a selection and press C-z to see what actions are available. Select the action you want, and press enter.
  • Make a selection and press F1 to run the default action, or F2 to run the second action.

Here is our code:

(setq data '(("John" . "john@email.com")
             ("Jim" . "jim@email.com")
             ("Jane" . "jane@email.com")
             ("Jill" . "jill@email.com")))


(defun open-email (candidates)
  "Compose an email to the candidates. Fill in the addresses and
move point to the subject."
  (compose-mail)
  (message-goto-to)
  (insert
   (mapconcat
    'identity
    (helm-marked-candidates)
    ","))
  (message-goto-subject))

(setq some-helm-source
      `((name . "HELM at the Emacs")
        (candidates . ,data)
        (action . (("show email address" . (lambda (candidate)
                                             (message-box
                                              "selected: %s"
                                              (helm-marked-candidates))))
                   ("send email" . open-email)))))

(helm :sources '(some-helm-source))
   t

Now, you can define multiple actions for your selection in helm!

Handling multiple selections

The basic usage pattern of helm is you run a command which opens a buffer of choices. You enter some text in the minibuffer which eliminates choices that do not match what you type in. You can select multiple choices by using C-spc, or M-a to mark them all. When you press enter, the current selection is sent to the default action defined. The action is a function that does something, usually on the selected item(s). Here, we explore writing the action function to do what we want. The reason this is somewhat tricky is that when you mark an item in helm, the "cursor" moves to the next item, which means when you press enter it may be possible that the current highlighted item is not part of the items you have marked. If your action will perform a delete action, for example, you may have wanted to delete the marked items, and not the current selection! So, what we need is a way to get what we want.

An action function in helm should normally take one argument, which is going to be the currently selected item from helm. However, we can use two different functions to access either the selected item (helm-get-selection) or the marked items (helm-marked-candidates). So, we can write our function to do "do what we mean". Note, even if you do not mark any candidates, (helm-marked-candidates) will return a list that has the current selection in it. So we can write our action function to act on this list so it works on what is marked or what is selected if nothing is marked. That is probably "what we mean".

Here is one way to work on a selection or marked list of selections. We define an action function that takes an arg, but inside we operate on each element of the marked candidates.

(defun some-action (candidate)
  (loop for cand in (helm-marked-candidates)
        do
        (message-box "working on %s" cand)))

(helm :sources '(((name . "HELM")
                  (candidates . (1 2 3 4))
                  (action . (("open" . some-action))))))

Here is an alternative approach. Here we define the action function to work on one candidate. That might be helpful for testing, for example. Then, we use mapc to apply the function to each marked candidate.

(defun some-action (candidate)
  (message-box "single working on %s" candidate))

(helm :sources '(((name . "HELM")
                  (candidates . (1 2 3 4))
                  (action . (("open" . (lambda (candidate)
                                         (mapc
                                          'some-action
                                          (helm-marked-candidates)))))))))

A little more verbose method might be like this. Here we just pull out the lambda function to another function, to make the helm source definition a little shorter. I cannot tell if this is easier to follow, it is just another option.

(defun some-action (candidate)
  (message-box "single2 working on %s" candidate))

(defun some-actions (candidate)
  (mapc 'some-action (helm-marked-candidates)))

(helm :sources '(((name . "HELM")
                  (candidates . (1 2 3 4))
                  (action . some-actions))))

So there you have it. You can select multiple things in helm, and then operate on them with your action function!

Actions when there is no match

Sometimes you run out of matches in a helm selection buffer, and all that is left is the pattern you have typed in. It turns out you can perform some action on that pattern! Why would you do that? Suppose you are searching your bibliography, and you do not find what you are looking for. Then, you may want to send the pattern to Google, or some other search engine to see what comes up.

The key to handling this situation is to use two sources in your helm session. One that works on the candidates and deals with actions on them, and one that has no candidates, and works on the pattern. The variable helm-pattern contains what you typed in. We call the second source the Fallback option. The second source has no candidates, and we use (dummy) in place of the candidates.

It easy to add two sources. Here we define the sources as variables, and use the variables in the :sources list to the helm command.

(defun some-action (arg)
  (message-box "%s\n%s"
    (helm-get-selection)
    (helm-marked-candidates)))

(defun default-action (candidate)
  (browse-url
   (format
    "http://www.google.com/search?q=%s" (url-hexify-string helm-pattern))))

(defvar source1 '((name . "HELM")
                  (candidates . (1 2 3 4))
                  (action . (("open" . some-action)))))

(defvar fallback-source '((name . "fallback")
                          (dummy)
                          (action . (("Google" . default-action)))))

(helm :sources '(source1 fallback-source))
   #<process open http://www.google.com/search?q=addtion%20pul>

When you run this, if you run out of search candidates, all that will be left is the fallback option, and when you press enter, it will launch a browser pointing to the google search for your pattern.

Last words

Helm and prefix functions

Helm modifies how you use prefix arguments in Emacs. A prefix argument is when you type C-u before a command to modify its behavior. There are a few variations of prefix arguments. Basically, pressing C-u once sets a prefix variable to '(4), pressing twice sets it to '(16). Alternatively, C-u 7 sets the prefix to 7. In regular emacs commands, you type the prefix keys before the command. In helm, you type the after you enter the helm selection buffer, and before you press enter or select your action. In helm, you access the prefix arg in the variable helm-current-prefix-arg. Let us look at how you might use it.

We make an action function that does something conditionally depending on the prefix arg. Yes, you could write several functions to accomplish that too, but maybe there is just a little difference that you can use the prefix arg to handle. What you cannot remember 4 prefix options? You do write good doc strings on your functions right ;) If not, you probably ought to write four functions with meaningful names, and meaningful helm descriptions!

(defun action (candidate)
  "Our action function.
with no prefix message no prefix arg
with one prefix arg message C-u
with two prefix args message C-u C-u
with a numeric prefix arg, message the number."
  (interactive "p")
  (cond
   ((eq nil helm-current-prefix-arg)
    (message-box "no prefix arg"))
   ((equal helm-current-prefix-arg '(4))
    (message-box "C-u"))
   ((equal helm-current-prefix-arg '(16))
    (message-box "C-u C-u"))
   (t
    (message-box (format "C-u %s" helm-current-prefix-arg)))))

(setq some-helm-source
      '((name . "HELM at the Emacs")
        (candidates . (1 2 3 4))
        (action . action)))

(helm :sources '(some-helm-source))
   C-u (64)