Elisp destructuring-bind for cons cell? - emacs

I'd like to do
(destructuring-bind (start end) (bounds-of-thing-at-point 'symbol))
But bounds-of-thing-at-point returns a cons cell and not a list, so
destructuring-bind doesn't work.
What could work for this case?

Since destructuring-bind is a macro from cl package, it may be worthwhile to look into Common Lisp documentation for more examples.
This page shows the syntax of the macro. Note the (wholevar reqvars optvars . var). Though I'm not sure cl version of destructuring-bind actually supports all of the less common cases (many keywords only make sense when used with Common Lisp macros / functions, but don't have that meaning in Emacs Lisp).
Thus:
(destructuring-bind (start . end) (bounds-of-thing-at-point 'symbol) ;...)
should work.

I'd use
(pcase-let ((`(,start . ,end) (bounds-of-thing-at-point 'symbol)))
...)

I cannot think on anything as elegant as destructuring-bind, but this would work:
(let* ((b (bounds-of-thing-at-point 'symbol))
(start (car b))
(end (cdr b)))
...)

Nowadays we can use -let in dash.el. It is like pcase-let, just a bit cleaner:
(-let (((start . end) (bounds-of-thing-at-point 'symbol)))
...)

Related

registering a function in a list as it is being defined

I am trying to make a list of callback functions, which could look like this:
(("command1" . 'callback1)
("command2" . 'callback2)
etc)
I'd like it if I could could do something like:
(define-callback callback1 "command1" args
(whatever the function does))
Rather than
(defun callback1 (args)
(whatever the function does))
(add-to-list 'callback-info ("command1" . 'callback1))
Is there a convenient way of doing this, e.g., with macros?
This is a good example of a place where it's nice to use a two-layered approach, with an explicit function-based layer, and then a prettier macro layer on top of that.
Note the following assumes Common Lisp: it looks just possible from your question that you are asking about elisp, in which case something like this can be made to work but it's all much more painful.
First of all, we'll keep callbacks in an alist called *callbacks*:
(defvar *callbacks* '())
Here's a function which clears the alist of callbacks
(defun initialize-callbacks ()
(setf *callbacks* '())
(values)
Here is the function that installs a callback. It does this by searching the list to see if there is a callback with the given name, and if there is then replacing it, and otherwise installing a new one. Like all the functions in the functional layer lets us specify the test function which will let us know if two callback names are the same: by default this is #'eql which will work for symbols and numbers, but not for strings. Symbols are probably a better choice for the names of callbacks than strings, but we'll cope with that below.
(defun install-callback (name function &key (test #'eql))
(let ((found (assoc name *callbacks* :test test)))
(if found
(setf (cdr found) function)
(push (cons name function) *callbacks*)))
name)
Here is a function to find a callback, returning the function object, or nil if there is no callback with that name.
(defun find-callback (name &key (test #'eql))
(cdr (assoc name *callbacks* :test test)))
And a function to remove a named callback. This doesn't tell you if it did anything: perhaps it should.
(defun remove-callback (name &key (test #'eql))
(setf *callbacks* (delete name *callbacks* :key #'car :test test))
name)
Now comes the macro layer. The syntax of this is going to be (define-callback name arguments ...), so it looks a bit like a function definition.
There are three things to know about this macro.
It is a bit clever: because you can know at macro-expansion time what sort of thing the name of the callback is, you can decide then and there what test to use when installing the callback, and it does this. If the name is a symbol it also wraps a block named by the symbol around the body of the function definition, so it smells a bit more like a function defined by defun: in particular you can use return-from in the body. It does not do this if the name is not a symbol.
It is not quite clever enough: in particular it does not deal with docstrings in any useful way (it ought to pull them out of the block I think). I am not sure this matters.
The switch to decide the test uses expressions like '#'eql which reads as (quote (function eql)): that is to avoid wiring in functions into the expansion because functions are not externalisable objects in CL. However I am not sure I have got this right: I think what is there is safe but it may not be needed.
So, here it is
(defmacro define-callback (name arguments &body body)
`(install-callback ',name
,(if (symbolp name)
`(lambda ,arguments
(block ,name
,#body))
`(lambda ,arguments
,#body))
:test ,(typecase name
(string '#'string=)
(symbol '#'eql)
(number '#'=)
(t '#'equal))))
And finally here are two different callbacks being defined:
(define-callback "foo" (x)
(+ x 3))
(define-callback foo (x)
(return-from foo (+ x 1)))
These lists are called assoc lists in Lisp.
CL-USER 120 > (defvar *foo* '(("c1" . c1) ("c2" . c2)))
*FOO*
CL-USER 121 > (setf *foo* (acons "c0" `c1 *foo*))
(("c0" . C1) ("c1" . C1) ("c2" . C2))
CL-USER 122 > (assoc "c1" *foo* :test #'equal)
("c1" . C1)
You can write macros for that, but why? Macros are advanced Lisp and you might want to get the basics right, first.
Some issues with you example you might want to check out:
what are assoc lists?
what are useful key types in assoc lists?
why you don't need to quote symbols in data lists
variables are not quoted
data lists need to be quoted
You can just as easy create such lists for callbacks without macros. We can imagine a function create-callback, which would be used like this:
(create-callback 'callback1 "command1"
(lambda (arg)
(whatever the function does)))
Now, why would you use a macro instead of a plain function?
In the end, assisted by the responders above, I got it down to something like:
(defmacro mk-make-command (name &rest body)
(let ((func-sym (intern (format "mk-cmd-%s" name))))
(mk-register-command name func-sym)
`(defun ,func-sym (args &rest rest)
(progn
,#body))))

Translating this to Common Lisp

I've been reading an article by Olin Shivers titled Stylish Lisp programming techniques and found the second example there (labeled "Technique n-1") a bit puzzling. It describes a self-modifying macro that looks like this:
(defun gen-counter macro (x)
(let ((ans (cadr x)))
(rplaca (cdr x)
(+ 1 ans))
ans))
It's supposed to get its calling form as argument x (i.e. (gen-counter <some-number>)). The purpose of this is to be able to do something like this:
> ;this prints out the numbers from 0 to 9.
(do ((n 0 (gen-counter 1)))
((= n 10) t)
(princ n))
0.1.2.3.4.5.6.7.8.9.T
>
The problem is that this syntax with the macro symbol after the function name is not valid in Common Lisp. I've been unsuccessfully trying to obtain similar behavior in Common Lisp. Can someone please provide a working example of analogous macro in CL?
Why the code works
First, it's useful to consider the first example in the paper:
> (defun element-generator ()
(let ((state '(() . (list of elements to be generated)))) ;() sentinel.
(let ((ans (cadr state))) ;pick off the first element
(rplacd state (cddr state)) ;smash the cons
ans)))
ELEMENT-GENERATOR
> (element-generator)
LIST
> (element-generator)
OF
> (element-generator)
This works because there's one literal list
(() . (list of elements to be generated)
and it's being modified. Note that this is actually undefined behavior in Common Lisp, but you'll get the same behavior in some Common Lisp implementations. See Unexpected persistence of data and some of the other linked questions for a discussion of what's happening here.
Approximating it in Common Lisp
Now, the paper and code you're citing actually has some useful comments about what this code is doing:
(defun gen-counter macro (x) ;X is the entire form (GEN-COUNTER n)
(let ((ans (cadr x))) ;pick the ans out of (gen-counter ans)
(rplaca (cdr x) ;increment the (gen-counter ans) form
(+ 1 ans))
ans)) ;return the answer
The way that this is working is not quite like an &rest argument, as in Rainer Joswig's answer, but actually a &whole argument, where the the entire form can be bound to a variable. This is using the source of the program as the literal value that gets destructively modified! Now, in the paper, this is used in this example:
> ;this prints out the numbers from 0 to 9.
(do ((n 0 (gen-counter 1)))
((= n 10) t)
(princ n))
0.1.2.3.4.5.6.7.8.9.T
However, in Common Lisp, we'd expect the macro to be expanded just once. That is, we expect (gen-counter 1) to be replaced by some piece of code. We can still generate a piece of code like this, though:
(defmacro make-counter (&whole form initial-value)
(declare (ignore initial-value))
(let ((text (gensym (string 'text-))))
`(let ((,text ',form))
(incf (second ,text)))))
CL-USER> (macroexpand '(make-counter 3))
(LET ((#:TEXT-1002 '(MAKE-COUNTER 3)))
(INCF (SECOND #:TEXT-1002)))
Then we can recreate the example with do
CL-USER> (do ((n 0 (make-counter 1)))
((= n 10) t)
(princ n))
023456789
Of course, this is undefined behavior, since it's modifying literal data. It won't work in all Lisps (the run above is from CCL; it didn't work in SBCL).
But don't miss the point
The whole article is sort of interesting, but recognize that it's sort of a joke, too. It's pointing out that you can do some funny things in an evaluator that doesn't compile code. It's mostly satire that's pointing out the inconsistencies of Lisp systems that have different behaviors under evaluation and compilation. Note the last paragraph:
Some short-sighted individuals will point out that these programming
techniques, while certainly laudable for their increased clarity and
efficiency, would fail on compiled code. Sadly, this is true. At least
two of the above techniques will send most compilers into an infinite
loop. But it is already known that most lisp compilers do not
implement full lisp semantics -- dynamic scoping, for instance. This
is but another case of the compiler failing to preserve semantic
correctness. It remains the task of the compiler implementor to
adjust his system to correctly implement the source language, rather
than the user to resort to ugly, dangerous, non-portable, non-robust
``hacks'' in order to program around a buggy compiler.
I hope this provides some insight into the nature of clean, elegant
Lisp programming techniques.
—Olin Shivers
Common Lisp:
(defmacro gen-counter (&rest x)
(let ((ans (car x)))
(rplaca x (+ 1 ans))
ans))
But above only works in the Interpreter, not with a compiler.
With compiled code, the macro call is gone - it is expanded away - and there is nothing to modify.
Note to unsuspecting readers: you might want to read the paper by Olin Shivers very careful and try to find out what he actually means...

difference between two ways of specifying emacs lisp macro indent style

What is the difference or pros/cons between the two popular ways of specifying an indentation style for an Emacs Lisp macro I define?
The declare way:
(defmacro my-dotimes-1 (num &rest body)
(declare (indent 1)) ; <---
`(let ((it 0))
(while (< it ,num)
,#body
(setq it (1+ it)))))
The put way:
(defmacro my-dotimes-2 (num &rest body)
`(let ((it 0))
(while (< it ,num)
,#body
(setq it (1+ it)))))
(put 'my-dotimes-2 'lisp-indent-function 1) ; <---
(The name it is not a gensym because the example is copied from the --dotimes macro of dash.el which is intended as an anaphoric macro.)
The only difference I know of is that declare only works for Emacs Lisp, whereas the put method works for other languages as well (that is, if they use a similar technique for managing their indentation).
For instance, you can do things like
(put 'match 'clojure-indent-function 2)
To control how clojure-mode indents particular forms.
It's also worth noting that while indentation levels are most often specified for macros it also works with functions.
In addition to what jbm said, declare is not part of Emacs Lisp before version 22 (or it might be 21). So if you want your code to be usable also with older Emacs versions then do not use declare.
The first expands to the second, so there is no technical difference. Nowadays, the first is the recommended one, while the second is the underlying implementation.

Emacs, namespaces and defuns

The only thing I don't like about Emacs is the lack of namespaces, so I'm wondering if I can implement them on my own.
This is my first attempt, and it's obvious that I can't just replace every match of a name with its prefixed version, but what should I check? I can check for bindings with (let) then mark the entire subtree, but what if somebody creates a (my-let) function that uses let? Is my effort destined to fail? :(
Also, why are my defuns failing to define the function? Do I have to run something similar to intern-symbol on every new token?
Thanks!
Since this is the first google result for elisp namespaces...
There's a minimalist implementation of namespaces called fakespace which you can get on elpa, which does basic encapsulation. I'm working on something ambitious myself, which you can check out here.
To handle things like my-let or my-defun, you need to macroexpand those definitions, e.g. with macroexpand-all.
For the failure to define the functions, you need to use intern instead of make-symbol (because make-symbol always creates a new distinct fresh uninterned symbol).
Adding namespaces will take more than prefixing the identifiers with the namespace names. The interpreter has to be able to tell the namespaces. Some tinkering must go into the interpreter as well. That might need to go through a thorough discussion at gnu.emacs.sources and/or #emacs at irc.freenode.org.
This is a fixed version of the code from #vpit3833 to provide namespace support (using the hint from #Stefan). It’s too good to leave around half-fixed :)
;; Simple namespace definitions for easier elisp writing and clean
;; access from outside. Pythonesque elisp :)
;;
;; thanks to vpit3833 → http://6e5e5ae9206fa093.paste.se/
(defmacro namespace (prefix &rest sexps)
(let* ((naive-dfs-map
(lambda (fun tree)
(mapcar (lambda (n) (if (listp n) (funcall naive-dfs-map fun n)
(funcall fun n))) tree)))
(to-rewrite (loop for sexp in sexps
when (member (car sexp)
'(defvar defmacro defun))
collect (cadr sexp)))
(fixed-sexps (funcall naive-dfs-map
(lambda (n) (if (member n to-rewrite)
(intern
(format "%s-%s" prefix n)) n))
sexps)))
`(progn ,#fixed-sexps)))
;; (namespace test
;; (defun three () 3)
;; (defun four () (let ((three 4)) three))
;; (defun + (&rest args) (apply #'- args)))
;; (test-+ 1 2 3)
(provide 'namespace)

Is it possible to have an alias for the function name in Lisp?

...just like packages do.
I use Emacs (maybe, it can offer some kind of solution).
For example (defun the-very-very-long-but-good-name () ...) is not to useful later in code. But the name like Fn-15 or the first letters abbreviation is not useful too.
Is it possible either to have an alias like for packages or to access the documentation string while trying to recall the function's name?
In other words, is it possible for functions to mix somehow self-documenting and short names?
You want defalias. (defalias 'newname 'oldname) will preserve documentation and even show "newname is an alias for `oldname'" when its documentation is requested.
You could use setf to assign the function to the function cell of another, for example:
(defmacro alias (new-name prev-name)
`(setf (symbol-function ,new-name) (symbol-function ,prev-name)))
from 《On Lisp》?Here is the code:
(defmacro alias (new-name prev-name)
`(defmacro ,new-name (&rest args)
`(,',prev-name ,#args)))
; use: (alias df defun)
(defun group (source n)
(if (zerop n) (error "zero length"))
(labels ((rec (source acc)
(let ((rest (nthcdr n source)))
(if (consp rest)
(rec rest (cons (subseq source 0 n) acc))
(nreverse (cons source acc))))))
(if source (rec source nil) nil)))
(defmacro aliasx (&rest names)
`(alias
,#(mapcar #'(lambda (pair)
`(alias ,#pair))
(group names 2))))
; use: (aliasx df1 defun
; df2 defun
; df3 defun)
If it's all the typing which makes continual use of long names undesirable, then yes, emacs can help. Check out abbrev-mode. Also well thought-of in this context is hippie-expand.
If it's a question of readability, that's harder.
If your problem is that you can't remember a very long function name, but you remember PART of the name, that's what "apropos" is for. In my Emacs, I have "C-h a" bound to "hyper-apropos". You enter a substring of the symbol you're looking for, and it lists all the matches.
I dont know Emacs, but wouldn't (define shortname longnamefunctionblahblah) work?
You could simply have a function that just calls another function.
you can use (defmacro ...) to alias a function