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 http://www.gnu.org/software/emacs/manual/html_node/elisp/Programmed-Completion.html
(cond
((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))
(completing-read
(concat "Enter subdir of " cdsrc-completions-prefix ": ")
'cdsrc-completions))))
(let ((path2 (concat cdsrc-completions-prefix path)))
(cd path2)
(if (string-match mode-name "Shell")
(progn (end-of-buffer)
(comint-kill-input)
(comint-send-string (current-buffer) (concat "cd " path2))
(comint-send-input)))))

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

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

jack13

"While the industry is working on adding different fungicides, and crop breeders are getting better at incorporating different types of resistance, they attempt to save yield, not increase it, and there is usually a cost of some sort."panvoya

by Unregistered Visitor on 10/28/14

jack13

“You can look like a cop and we’ll call you a cop, but you don’t really have any way of being a cop,” Wardwell said. “Because we’re not going to train you, we won’t provide safety equipment. The salary will be so bad that we won’t be able to recruit anybody of talent.”Ingreso Cybernetico

by Unregistered Visitor on 10/30/14

Exceptional writing help online

Wow! I really appreciate the thought that you put into this article. This topic has been something I have been looking into for a few hours and your post is one of the best I have read. college essays help

by Unregistered Visitor on 10/31/14

jogar

this wa very helpful indeed i am very happy to say thsi also jogos de moto de topo

by Unregistered Visitor on 10/31/14

Professional writers available here

This was an excellent post. It has some valuable info on this topic. Thank you for compiling it into an easy to read and well written post. college essays help

by Unregistered Visitor on 10/31/14

great info realy

hmm guys your posts are very helpful indeed low calorie recipes

by Unregistered Visitor on 11/02/14

Passbook

Very nice coding and now i am found Passbook this website . It is really informative . It gives a all type of necessary instructions.

by Unregistered Visitor on 11/02/14

jackson

casino gambling sportsbook I was very pleased to find this site.I wanted to thank you for this great read!! I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you post

by Unregistered Visitor on 11/04/14

jackson

I thought it was going to be several wearisome experienced courier, however it truly compensated for my tour. I mind dispatch a join to this messenger on my blog. I am unfailing my tourists desire discover that truly helpful. www.rebelmouse.com

by Unregistered Visitor on 11/04/14

Essay Writing Help

I am an essay writer at special-essays.com, and if you have troubles with your writing assignments, please let me or another expert help you =)

by Unregistered Visitor on 11/05/14

Autos Nuevos

This too clarifies why hemorrhoids are common while pregnant, when the increasing the size of womb presses around the veins. Autos Nuevos

by Unregistered Visitor on 11/06/14

Autos Nuevos

Thank you very much for posting and sharing this great article. It is so interesting. I want to know some other information about this site. So please give me this news quickly. I always will be aware of you. Autos Nuevos

by Unregistered Visitor on 11/06/14

about

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.E-mail Hosting

by Unregistered Visitor on 11/06/14

Essay

Hi! My name is Nina! I want to recommend you a website called www.best-essays-writers.com. If you visit it you will not have academic problems.

by Unregistered Visitor on 11/06/14

software

Thanks so much for my favorite session of Drupalcon :) It was awesome meeting you, and troubleshooting SmartCVS. Haha. case management software

by Unregistered Visitor on 11/08/14

spy

I love you so much céline!!!!! you're amazing...Brazil loves you.. how to spy on mobile

by Unregistered Visitor on 11/08/14

my site

Absolutely fantastic posting! Lots of useful information and inspiration, both of which we all need!Relay appreciate your work. my site

by Unregistered Visitor on 11/08/14

Review

I just couldn't leave your website before telling you that I truly enjoyed the top quality info you present to your visitors? Will be back again frequently to check up on new posts. DubLi Network Review

by Unregistered Visitor on 11/08/14

boyfriend

Hi there, I found your website via Google whilst looking for a comparable matter, your web site came up, it seems to be good. I’ve bookmarked it in my google bookmarks. how to get ex boyfriend back

by Unregistered Visitor on 11/08/14

comment

Very awesome blog post. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. I was exactly searching for. his comment is here

by Unregistered Visitor on 11/08/14

click

Very awesome blog post. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. I was exactly searching for. click here now

by Unregistered Visitor on 11/08/14

tips

Absolutely fantastic posting! Lots of useful information and inspiration, both of which we all need!Relay appreciate your work. tips for juicing

by Unregistered Visitor on 11/08/14

turn

I am happy to find this post very useful for me, as it contains lot of information. I always prefer to read the quality content and this thing I found in you post. Thanks for sharing. turn fat into muscle

by Unregistered Visitor on 11/08/14

jackson

Very informative post! There is a lot of information here that can help any business get started with a successful social networking campaign! Church Financial Software

by Unregistered Visitor on 11/09/14

zeeshan1

I agree with your blog and i will be back to check it more in the future so please keep up your work. michael kors outleti love your content & the way that you write. http://www.youtube.com/watch?v=SR_VEWqAAd8

by ahmed raza on 11/09/14

jack13

le sauve en successeur son cœur problématique par une horloge mécanique. Il restera en vie avec ce bricolage merveilleux sous réserve de tenir en estime 3 loisblog comments Availble in here

by Unregistered Visitor on 11/10/14

Information for students

Thanks for sharing this information. By the way, students can buy custom essays online and get excellent grades for them.

by Unregistered Visitor on 11/10/14

Great site.

Everyone can buy custom essays online andforget about academic problems.

by Unregistered Visitor on 11/10/14

jackson

This is my initial epoch i stopover here. I discovered so numerous entertaining pad in your blog, essentially its conversation. From the tons of observations on your doctrines, I speculate I am nay the entirely alone holding many the ease here! Retain up the amazing process. https://rebelmouse.com/pregnancymiraclelisaolson/

by Unregistered Visitor on 11/10/14

jack

Looking for Tow Bars Melbourne? Tow Bar Pro have been supplying, and fitting towbars and related towing products dentist boynton beach for Victorians for over 25 year

by Unregistered Visitor on 11/11/14

davidjohn

Artesanía de conceptos relacionados al reciclaje y utilización de materiales recuperados del medio ambiente Definition of Endometriosis

by Unregistered Visitor on 11/12/14

water damage restoration dallas

Profiting is positively an intense assignment. On the other hand, in the event that you've brains and energy to address the engineering in the right way; then proceed, the world is yours and cash will naturally achieve you. water damage restoration dallas

by Unregistered Visitor on 11/12/14

great post

And that's a generous present! and I usually have enjoyment making use of your recommendations in what we need to do in the near future. Our checklist is a distance long and tips will certainly be put to excellent use. blog

by Unregistered Visitor on 11/12/14

davidjohn

Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work. Video adds

by Unregistered Visitor on 11/13/14

Ashar

site visiting....http://www.inbaogao.com

by Unregistered Visitor on 11/13/14

τραπεζια σαλονιου

Thank you for making this article on natural health solutions . I have read many articles with same topic but here you have collected information from all those sites and made the best one possible for the readers to enjoy. τραπεζια σαλονιου

by Unregistered Visitor on 11/13/14

jack13

without mentioning here or those that have yet to be identified in the immediate wake of Secretary Wetzel’s shocking announcement.one time check this site must

by Unregistered Visitor on 11/15/14

jackson

Thanks for a very interesting blog. What else may I get that kind of info written in such a perfect approach? I’ve a undertaking that I am simply now operating on, and I have been at the look out for such info. rebelmouse.com

by Unregistered Visitor on 11/16/14

Ashar

site visiting...Free PDF Ebooks

by Unregistered Visitor on 11/18/14

Service That Provides the Best Custom Essays

A lot of students cannot deal with their academic tasks without professional assistance. Fortunately, using this site http://super-essays-service.com, it is much easier to earn high grades!

by Unregistered Visitor on 11/18/14

Ashar

Training three to five days a week at 65 to 70 percent of max heart rate is ideal. ..Amelia Ellison

by Unregistered Visitor on 11/19/14

hostgator coupon

It is the best experience to be there at the wildest part of Africa and Australia It surely gives a very good feeling to be in the wild and to know about such places I think you must enjoy the place rather than feeling pissed up. hostgator coupon

by Unregistered Visitor on 11/20/14

Essay Writing

www.primewritings.net is one of those essay writing companies, which do their very best to make the customers 100% satisfied with their services.

by Unregistered Visitor on 11/21/14

hotel bourg saint maurice

On the part of rich countries there is excessive zeal for protecting knowledge through an unduly rigid assertion of the right to intellectual property, especially in the field of health care. At the same time, in some poor countries, cultural models and social norms of behaviour persist which hinder the process of development."hotel bourg saint maurice

by Unregistered Visitor on 11/22/14

remedio para queda de cabelo

Typically it truly is worn for a belt. Hypertension cuff over the monitor will be worn within your clothes without anyone seeing it.This machine lets your physician determine what your bp was every Twenty to thirty minutes from a day.remedio para queda de cabelo

by Unregistered Visitor on 11/22/14

link building in facebook

Get a list of top 8 Licensed, Insured, Pre-screened & Reliable Packers and Movers, and Movers and Packers. Request free quotes to compare and select the best one. link building in facebook

by Unregistered Visitor on 11/22/14

franklin7

it won’t be a taboo topic however generally people are not enough to talk on such topics. To the next. Cheers seo backlinks service

by Unregistered Visitor on 11/23/14

jack13

The larger your assets the greater fame will come the right path. Plastic doctors once experienced a mind but right now it is about the cash. If you get access to cash, you will get just regarding any surgical treatment your center imagines. If you cannot find the surgeon to complete it in the usa, well almost always there is another country where one can probably obtain the procedure in a discount. Best forex broker in united states

by Unregistered Visitor on 11/23/14

jack13

This type of message always inspiring and I prefer to read quality content, so happy to find good place to many here in the post, the writing is just great, thanks for the post. seo marketing

by Unregistered Visitor on 11/24/14

franklin7

I have read this post and if I could I wish to suggest you few interesting things or advice. Chatroulette

by Unregistered Visitor on 11/24/14

Service That Provides the Best Custom Essays

I don’t suppose I have read anything like this before. Extremely impressed with the excellence of the knowledge offered. I sincerely hope that you keep up with the good job conducted. helpful resources

by Unregistered Visitor on 11/24/14

Service That Provides the Best Custom Essays

Nice post. Very helpful and full of information. This is very good. I appreciate this very much! paper writing

by Unregistered Visitor on 11/24/14

franklin7

I was seeking this particular information for a very long time. Thank you and good luck. parfum murah

by Unregistered Visitor on 11/26/14

Nice article

I am always searching online for articles that can help me. There is obviously a lot to know about this. In my experience, you do the truly amazing.Fifa 15 Coins

by Unregistered Visitor on 11/27/14

jack13

I was very pleased to find this site.I wanted to thank you for this great read!! I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you post.voyance la voyance ma voyance

by Unregistered Visitor on 11/27/14

rozi

The worst part of it was that the software only worked intermittantly and the data wasn’t accurate. You obviously can’t confront anyone about what you have discovered if the information isn’t right.pre approved for a car loan

by Unregistered Visitor on 11/27/14

rozi

What a really awesome post this is. Truly, one of the best posts I've ever witnessed to see in my whole life. Wow, just keep it up.jeep sahara used

by Unregistered Visitor on 11/27/14

rozi

This post is very simple to read and appreciate without leaving any details out. Great work! You completed certain reliable points there. I did a search on the subject and found nearly all persons will agree with your blog.lease or buy a car

by Unregistered Visitor on 11/27/14

rozi

Nice information, valuable and excellent design, as share good stuff with good ideas and concepts, lots of great information and inspiration, both of which I need, thanks to offer such a helpful information here.in house financing auto dealers

by Unregistered Visitor on 11/27/14

rozi

Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. I wanted to thank you for this websites! Thanks for sharing. Great websites! abaya sale online

by Unregistered Visitor on 11/27/14

rozi

Good to become visiting your weblog again, it has been months for me. Nicely this article that i've been waited for so long. I will need this post to total my assignment in the college, and it has exact same topic together with your write-up. Thanks, good share.vintage jewelry online

by Unregistered Visitor on 11/27/14

rozi

I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own BlogEngine blog now. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it.pet insurance

by Unregistered Visitor on 11/27/14

write a good essay

Great post. You know, that writing an essay is not easy, especially if you don't have good writing skills. That's why many students are looking for professional writing help online, so buy college essays online is what you are looking for.

by Unregistered Visitor on 11/27/14

Add comment