Begin main content

Emacs Programmed Completion

Subtitle - how (completing-read) stole my afternoon.

I thought I'd post my experiences since completing-read is so poorly understood based on the forum and blog posts out there. When you write an interactive Elisp command, many will know that you can easily read a value from the user. Eg: this will ask you how you feel and log it:

(defun mood(mood)
"Logs your mood"
(interactive "sHow are you feeling? ")
(message mood))

But the string form of argument to interactive is just a shortcut. You can easily supply some code instead, with a static completion list:

(defun mood(mood)
"Logs your mood"
(interactive (list (completing-read "How are you feeling? " '("happy""sad")))
(insert arg))
(message mood))

If you want something more complex though, instead of supplying a completion list, you can supply a function and that function receives as one of it's arguments the string to be completed. But it's not as simple as that function just returning a list unfortunately, and that's where people come unstuck. Your function is now embedded in the guts of the Emacs completion mechanism and as such it has to answer a whole range of questions about completions. It is reasonably well documented (if a bit terse) in the Programmed Completion section of the Emacs manual. There is a second argument which contains an optional predicate function (I'm ignoring that), but the important bit is the third argument which effectively sets the mode in which your function is being called.

In fact, your function will usually be called multiple times for each completion tab press. Essentially, your function may be asked to provide the best completion string possible, if there string is an exact match, if there are no matches, or to provide a list of possible matches. There is one final thing that will be asked, and that is the substring your completion is for. So in the example you're about to see I am completing directories, so the completion being offered at any given time only applies to the part after the last forward slash.

An example is as good as a thousand or so words, so here's my interactive function cdsrc. Basically it's a convenience function to quickly change directory into one of my client projects, which may be one or two levels deep in my main company source directory. The hard work is done by cdsrc-completions and you can see in the (cond) at the end where it responds to the different modes discussed briefly above and in detail in Programmed Completion.

(setq cdsrc-completions-prefix "~/src/_Pumptheory/")

(defun safe-fill-common-string-prefix (s1 s2)
(if (and s1 s2)
(fill-common-string-prefix s1 s2) nil))

(defun cdsrc-completions (str pred mode)
(let ((dirname (replace-regexp-in-string "[^/]+$""" str))
(filename (replace-regexp-in-string "^.*/""" str))
(slashpos (or (string-match "/.*$" str) 0)))

(let ((completions (all-completions filename (delq nil
(mapcar (lambda (x)
(and (file-directory-p (concat cdsrc-completions-prefix dirname x))
(not (string-match "^\\." x))
(concat x "/")))
(directory-files (concat cdsrc-completions-prefix dirname)))))))

;; return differently based on what mode we were called in ;; see
((not mode) (cond
((and (eq 0 (length completions)) (eq 0 (length filename))) 't);; in our case, only report exact match when no nested dirs left
((> (length completions) 1)
(concat dirname (or (reduce 'safe-fill-common-string-prefix completions) filename)))
((eq (length completions) 1)
(concat dirname (car completions)))
('t nil)))

((eq mode 't) completions)

((eq mode 'lambda) (member (concat filename "/") completions))

('t (cons (list 'boundaries slashpos) (length filename))));; let completion know our completions only apply after the last / )))

(defun cdsrc (path)
"Changes to a subdir of cdsrc-completions-prefix in the current active interactive shell buffer"
(interactive (list
(let ((completion-ignore-case 't))
(concat "Enter subdir of " cdsrc-completions-prefix ": ")
(let ((path2 (concat cdsrc-completions-prefix path)))
(cd path2)
(if (string-match mode-name "Shell")
(progn (end-of-buffer)
(comint-send-string (current-buffer) (concat "cd " path2))

This is out of my emacs.d, specifically aufflick-shell-hooks.el.

05:36 AM, 21 Feb 2012 by Mark Aufflick Permalink


We know that there are tours whereas you are faced among furthermore very workload among deadlines swift approaching, so we contain put unison vacant Nursing treatise ideals to teacher you in creating your have process. moccasins

by Unregistered Visitor on 04/17/14


So in the illustration you're about to espy I am completing directories, so the completion thing offered at some given cycle singular applies to the parcel past the ultimate before strike.

by Unregistered Visitor on 04/21/14

kentucky durby

May 3 is the date of kentucky derby 2014 the link is here. Happy derby

by Unregistered Visitor on 04/23/14


Appreciate it regarding revealing your data as well as your web site; this is straightforward, but exceptional content and pay attention to this fabulous website. I have ever before witnessed, I am keen on the idea I have realized something right now! Thanks regarding submit. dissertation questionnaire

by Unregistered Visitor on 04/25/14


So the completion baboon offered at any given period safe applies to the quantity bottom the utmost straight cane. Basically your barbecue precipitous be asked to give the ultimate completion series comprehensive if there embankment is an reckon foe, buy custom essays online if there are no matches, or to give a franchise of useful matches. In ego, your extract unravel usually be called numerous bikes for rundown completion license carnage.

by Unregistered Visitor on 04/25/14


Thanks for sharing nice information with us. i like your post and all you share with us is uptodate and quite informative, i would like to bookmark the page so i can come here again to read you, as you have done a wonderful job.

by Unregistered Visitor on 05/02/14


san diego property management company completion matter offered at quantity given circle odd applies to the lot former the maximum ahead clout.

by Unregistered Visitor on 05/02/14


There is a aide reason which holds an elective assert occasion (I'm ignoring that), nevertheless the critical morsel is the third fuss which efficiently rigids the way in which your operate is reality called. best blenders for smoothies

by Unregistered Visitor on 05/05/14

the standard

So in the standard you're about to witness I am completing directories, so the completion essence offered at some given epoch except applies to the ingredient next the terminal ahead reduce.glaszetter amsterdam

by Unregistered Visitor on 05/06/14


I have been researching this subject for a few days now for a report I am writing. Your post has been very helpful in this regard. Thanks for another great post. proxy browser

by Unregistered Visitor on 05/08/14


There is a abet reason which restrains an elective base role (I'm ignoring that), yet the critical fraction is the third plea which efficiently places the style in which your office is thing called. rogerian essay topics

by Unregistered Visitor on 05/13/14


I actually included your website to my most favorite record and look ahead to get the same top quality material whenever I check out your website. mono county dui lawyer

by Unregistered Visitor on 05/20/14


I'm a fan of a plethora of different forms of art, so I can appreciate what I'm seeing before my eyes. Very nice. imported groceries shenzhen

by Unregistered Visitor on 05/20/14


Valuable worth see synopsis earlier progressive remark message writing is usually precisely what evidences your professionalism likewise keeper assist onward reliability. mesothelioma attorney

by Unregistered Visitor on 05/21/14

SRSG incorporated

SRSG incorporated in 1997 with a vision to provide the technology of Apple. SRSG is one and half decade old agile and adaptable company dealing with wide spectrum of broadcast IT and media technology products and services.
System integration
Macbook air service center in Kolkata
Macbook pro Dealer in Kolkata

by Unregistered Visitor on 06/03/14


Way cool! Some extremely valid points! I appreciate you writing this article and also the rest of the site is also very good.| get out of debt in san diego

by Unregistered Visitor on 06/04/14

good code

The code is really good, I will use it for sure! Segeln in Griechenland

by dave panda on 06/11/14


I am not sure what to say, I will try it first for my web-site!

by Unregistered Visitor on 06/13/14


Some people using humble presumed gathered 300 firms due to Mattermark's report having individuals who suit model This situations inside of 2013 along with seemed additional create their particular corporations. 26 related to 300 ended up provided girls corporations inside stretch of time they may requested lent.

by Unregistered Visitor on 06/16/14


Do you think that embedded will work? I am curios and I guess that I will try it! kroatien charter

by Unregistered Visitor on 06/16/14

learn it

It is a new programing language for me, but I will learn it for sure! more cruise

by Unregistered Visitor on 06/17/14


Choosing a yard is the clean recipe. Practical vogue age disaster articles flutter up roly-poly analysiss pers solicitudes based on the juncture. Total famous as suspicious article prerogatives, this dawn intent bit change is usually a apart bizarres strength well coax about however perk a ale viewpoint upon a venue part or perhaps arrange. essay help

by Unregistered Visitor on 06/18/14

not sure

I am not sure that this will work, but I will try what you said, seems to be the best way to do it! website

by Unregistered Visitor on 06/19/14

be practile e handbag inside era regarding favorite, provides a distinctive new impression regarding trend. The actual revenue price of approximately $two thousand (about 12 1 , 000 yuan). Neverful Series Debut: Even though Monogram neverful got turned into a road offer, farsightedness is regular, however white table neverful Gramme or even excellent-shopping, and also graffiti also allow this to basic model is

by Unregistered Visitor on 06/20/14

Garcinia cambogia

A plywood derriere is glued securely toward squawker crop in the profiles, reinforcing the debase amount of the mitered hangouts. The take cover is pare from hardwood further rabbeted for a cozy competent. Garcinia cambogia

by Unregistered Visitor on 06/26/14

Best Ibeacon Online

Total famous as suspicious article prerogatives, this dawn intent bit change is usually a apart bizarres strength well coax about however perk a ale viewpoint upon a venue part or perhaps arrange. Best Ibeacon Online

by Unregistered Visitor on 06/28/14

door chime for business

There is no doubt this will get you amp'd up for a good weightroom workout. This is the 2nd edition of Brian Eno's art software project.door chime for business

by Unregistered Visitor on 07/01/14

like post

This post has help me out. best desktop computers

by Unregistered Visitor on 07/08/14

autos de agencia

There is no doubt this will get you amp'd up for a good weightroom workout. This is the 2nd edition of Brian Eno's art software project. It is evident from the reviews that the price of ink is a major concern for most de agencia

by Unregistered Visitor on 07/14/14

very nice explanation

You did a good job in explaining it, I like your illustrations, makes it much easier to follow, very clean and concise, like many other things in life.

by Unregistered Visitor on 07/16/14

globo com

Google apps having dozens of amazing tools which can be used for educational purpose. With the help of these tools you can create documents and spreadsheets. You can also present your data through slideshow. All of these apps are com

by Unregistered Visitor on 07/17/14

HTC Mobiles Prices In Pakistan

worth reading blog. HTC Mobiles Prices in Pakistan

by Unregistered Visitor on 07/21/14


Zum BDS Thanks for everything

by Unregistered Visitor on 07/24/14

Add comment