difference between two ways of specifying emacs lisp macro indent style - emacs

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.

Related

How is the defun macro implemented in lisp?

I'd like to learn more about lisp macros and I want to create a simple implementation of the defun macro.
I'm also interested in lisp's source code in all the implementations.
This is a tricky question, because of bootstrapping: defun does a lot of things (iow, calls a lot of functions), but to define those functions one needs a working defun. Thus there are three(3!) definitions of defun in clisp/src/init.lisp: at lines
228
1789
1946
The very basic definition of defun could be this:
(defmacro defun (fname lambda-list &rest body)
`(setf (fdefinition ',fname)
(lambda ,lambda-list
(block ,fname ,#body))))
In fact, this is the first definition of defun in CLISP (line 228), except that there is no defmacro and no backquote at that moment yet, so the actual code looks a lot uglier.
See also Is defun or setf preferred for creating function definitions in common lisp and why? where I discuss macroexpansions of defuns.
You can easily check how your particular CL implementation, implemented defun by running
(macroexpand '(defun add2 (x) (+ x 2)))
On SBCL it expands to:
(PROGN
(EVAL-WHEN (:COMPILE-TOPLEVEL) (SB-C:%COMPILER-DEFUN 'ADD2 NIL T))
(SB-IMPL::%DEFUN 'ADD2
(SB-INT:NAMED-LAMBDA ADD2
(X)
(BLOCK ADD2 (+ X 2)))
(SB-C:SOURCE-LOCATION)))
T
To see the particular source code that implemented the I would use (on Emacs) the M-. key binding and then I will write defun and hit enter. Then Emacs will get to the source code:
(sb!xc:defmacro defun (&environment env name lambda-list &body body)
#!+sb-doc
"Define a function at top level."
[...]
I am not going to paste the whole macro as it is rather long. If you are not on Emacs, you can try searching in the repos as most implementations are open source.
BTW defun is not so special. You can implement much of it with setf-inf a symbol-function to a lambda. E.g.:
(setf (symbol-function 'ADD3) #'(lambda (x) (+ x 3)))
; => #<FUNCTION (LAMBDA (X)) {1006E94EBB}>
(add3 4)
; => 7

Emacs-lisp: prettify-symbols-mode for LaTeX

I was trying to port over the "pretty entities" behaviour from org-mode to latex-mode using the Emacs builtin prettify-symbols-mode. This mode uses font-lock-mode to display character sequences in a buffer as a single (unicode) character. By default for instance emacs-lisp code
(lambda () t)
becomes
(λ () t)
It does however seem to require the character sequences to be separated by some characters, e.g. white-spaces. For instance in my setup, the replacement
\alpha \beta -> α β`
will work, but it will fail when the strings are not separated, e.g.
\alpha\beta -> \alphaβ
This is an issue specifically, because I wanted to use this prettification to make quantum mechanical equations more readable, where I e.g. the replacement like
|\psi\rangle -> |ψ⟩
Is it possible to avoid this delimiter-issue using prettify-symbols-mode? And if it is not, is it possible by using font-lock-mode on a lower level?
Here's the code that should do what you want:
(defvar pretty-alist
(cl-pairlis '("alpha" "beta" "gamma" "delta" "epsilon" "zeta" "eta"
"theta" "iota" "kappa" "lambda" "mu" "nu" "xi"
"omicron" "pi" "rho" "sigma_final" "sigma" "tau"
"upsilon" "phi" "chi" "psi" "omega")
(mapcar
(lambda (x) (make-char 'greek-iso8859-7 x))
(number-sequence 97 121))))
(add-to-list 'pretty-alist '("rangle" . ?\⟩))
(defun pretty-things ()
(mapc
(lambda (x)
(let ((word (car x))
(char (cdr x)))
(font-lock-add-keywords
nil
`((,(concat "\\(^\\|[^a-zA-Z0-9]\\)\\(" word "\\)[a-zA-Z]")
(0 (progn
(decompose-region (match-beginning 2) (match-end 2))
nil)))))
(font-lock-add-keywords
nil
`((,(concat "\\(^\\|[^a-zA-Z0-9]\\)\\(" word "\\)[^a-zA-Z]")
(0 (progn
(compose-region (1- (match-beginning 2)) (match-end 2)
,char)
nil)))))))
pretty-alist))
As you can see above, pretty-alist starts out with greek chars. Then I add
\rangle just to demonstrate how to add new things.
To enable it automatically, add it to the hook:
(add-hook 'LaTeX-mode-hook 'pretty-things)
I used the code from here as a starting
point, you can look there for a reference.
The code of prettify-symbols-mode derives from code developped for languages like Haskell and a few others, which don't use something like TeX's \. So you may indeed be in trouble. I suggest you M-x report-emacs-bug requesting prettify-symbol-mode be improved to support TeX-style syntax.
In the mean time, you'll have to "do it by hand" along the lines of what abo-abo suggests.
One note, tho: back in the days of Emacs-21, I ported X-Symbol to work on Emacs, specifically because I wanted to see such pretty things in LaTeX. Yet, I discovered that it was mostly useless to me. And I think it's even more the case now. Here's why:
You can just use an actual ψ character in your LaTeX code instead of \psi nowadays. So you don't need display tricks for it to look "right".
Rather than repeating |\psi\rangle I much prefer defining macros and then use \Qr{\Vangle} (where \Vangle turns into \psi ("V" stands for "metaVariable"), and \Qr wraps it in a braket) so I can easily tweak those macros and know that the document will stay consistent. At that point, pretty-display of \psi and \rangle is of no importance.

Elisp destructuring-bind for cons cell?

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)))
...)

Elisp rename macro

How can I rename elisp macro? To be more accurate, I want make defun to be synonym to cl-defun.
I do not care about time or memory overhead.
Summary
I don't think you can do that - at least not easily.
Since cl-defun expands to defun, you will get an infinite macroexpand loop when using defun if you do the obvious (defalias 'defun 'cl-defun).
The is a way...
So what you need to do is
save the original defun: (fset 'defun-original (symbol-function 'defun)).
copy the definition of cl-defun in cl-macs.el, replacing defun with defun-original.
replace defun with cl-defun using defalias: (defalias 'defun 'cl-defun).
Now, at least, if things go sour, you can restore the original behavior with (fset 'defun (symbol-function 'defun-original)).
...but you don't want it
However, I think you don't really want to do that.
If you want to use a Common Lisp, use it. Trying to pretend that you can turn Elisp into CL will cause you nothing but grief. I tried to travel that road 15 years ago - there is no fun there. It should be easier now, at least there is lexical binding, but I still don't think it is worth the effort.
If you want to extend Emacs, then using cl-defun makes even less sense: your extensions will be useless for others and you won't even be able to ask for help because few people will bother with such a radical change in such a basic functionality for such a tiny gain.
In general, you can make a synonym very simply with (defalias 'foo 'cl-defun).
But the expansion of a call to cl-defun uses defun, so if you do (defalias 'defun 'cl-defun) you'll get into infinite loops.
You can probably get what you want by replacing defun with a macro which either does what defun does or what cl-defun does, depending on whether the cal uses cl-defun features or not. E.g. using advice-add (which is in Emacs's trunk; you can use defadvice in older Emacsen to get simlar results) it could look something like the untested code below:
(defun my-defun-dispatch (doit name args &rest body)
(let ((needs-cl nil))
(dolist (arg args)
(unless (and (symbolp arg)
(or (not (eq ?& (aref (symbol-name arg) 0)))
(memq arg '(&optional &rest))))
(setq needs-cl t)))
(if needs-cl
`(cl-defun ,name ,args ,#body)
(funcall doit name args body))))
(advice-add :around 'defun 'my-defun-dispatch)
Any particular reason?
Maybe it's safe to do, and I'm sure it's possible, but I'm very dubious that you should be attempting it in the first place if you can't figure out how to go about it. I don't mean that as any kind of insult; I just suspect that a fundamental change like this could easily cause problems, so you ought to have a solid handle on elisp first before trying it.
I realise that's a bit of a non-answer, but I thought it was worth saying.
FYI cl-defun is defined in terms of defun.

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)