Introducción para calcular-lisp-indent
Una mejor solución es anular la función calculate-lisp-indent
. En resumen, calculate-lisp-indent
es una función que devuelve la columna a la que se debe sangrar una línea en el punto. Esta función es la que informa lisp-indent-function
cuánto debe sangrarse cada línea. (vea también mi publicación en reddit para más información).
Comparación con otras respuestas
La ventaja que tiene esta respuesta sobre el uso de la función modificada de Fuco1 es que (1) corrige la raíz del problema que se encuentra en calculate-lisp-indent
lugar de simplemente limpiar después de la sangría incorrecta devuelta por calculate-lisp-indent
(2) se generaliza a las listas citadas y citadas (y funciona si se citan / retrocomponen explícitamente o con el '
y `). También funciona con comillas y comillas invertidas arbitrariamente anidadas.
La ventaja que tiene esta respuesta sobre el reemplazo lisp-indent-function
con la common-lisp-indent-function
función es que no tiene el efecto secundario de estropear otra sangría de elisp. Elisp y common-lisp tienen sangría diferente.
Cómo funciona
Este condicional (in calculate-lisp-indent
) es lo que decide si un sexp está sangrado como una función o no. Lo que cae en su cláusula else está sangrado como una función. Lo que cae dentro de la cláusula if es sangrado normalmente (debajo del elemento actual). Para sangrar las listas citadas como datos en lugar de como funciones, necesitamos agregar más verificación para los casos en los que la lista se cita en el predicado condicional.
(if (= (point) calculate-lisp-indent-last-sexp)
;; Containing sexp has nothing before this line
;; except the first element. Indent under that element.
nil
;; Skip the first element, find start of second (the first
;; argument of the function call) and indent under.
(progn (forward-sexp 1)
(parse-partial-sexp (point)
calculate-lisp-indent-last-sexp
0 t)))
Este código verifica los paréntesis abiertos del sexp que se sangra. Si es sexp con múltiples sexp, los verifica a todos. Devuelve t si encuentra algún sexps citado o retrocomillado.
(let* ((positions (elt state 9))
(last (car (last positions)))
(rest (nreverse (butlast positions)))
(any-quoted-p nil)
(point nil))
(or
(when-let (char last)
(or (char-equal char ?')
(char-equal char ?`)))
(while (and rest (not any-quoted-p))
(setq point (pop rest))
(setq any-quoted-p
(or
(when-let (char point)
(or (char-equal char ?')
(char-equal char ?`)))
(save-excursion
(goto-char (1+ point))
(looking-at-p "\\(?:back\\)?quote[\t\n\f\s]+(")))))))
Prima
Si desea que una lista que comienza con una palabra clave se sangra como datos, incluso si no está entre comillas, agregue esto como otra verificación al predicado condicional. Esto puede ser útil para macros en las que las listas no se citan por conveniencia, como en defhydra .
(when-let (char-after (char-after (1+ containing-sexp)))
(char-equal char-after ?:))
Ejemplos
El fragmento de código completo que he publicado a continuación funciona con el caso que ha mencionado y más. Por favor pruébalo!
;; Your example
`(:token ,token
:token-quality ,quality)
;; Other cool examples
(quote (hi im gosu
the best vayne player))
'(i am the phantom of
the opera)
'((angel of music
hide no longer))
(backquote (past the point
no return
... the final chapter))
`(fee fi fo
fum)
;; should indent it like a function.
(iamafunction arg1
arg2
arg3)
Para una explicación más detallada de cómo funciona esto, vea mi publicación en reddit .
Fragmento de código completo
Aquí está el fragmento de código completo.
(advice-add #'calculate-lisp-indent :override #'void~calculate-lisp-indent)
(defun void~calculate-lisp-indent (&optional parse-start)
"Add better indentation for quoted and backquoted lists."
;; This line because `calculate-lisp-indent-last-sexp` was defined with `defvar`
;; with it's value ommited, marking it special and only defining it locally. So
;; if you don't have this, you'll get a void variable error.
(defvar calculate-lisp-indent-last-sexp)
(save-excursion
(beginning-of-line)
(let ((indent-point (point))
state
;; setting this to a number inhibits calling hook
(desired-indent nil)
(retry t)
calculate-lisp-indent-last-sexp containing-sexp)
(cond ((or (markerp parse-start) (integerp parse-start))
(goto-char parse-start))
((null parse-start) (beginning-of-defun))
(t (setq state parse-start)))
(unless state
;; Find outermost containing sexp
(while (< (point) indent-point)
(setq state (parse-partial-sexp (point) indent-point 0))))
;; Find innermost containing sexp
(while (and retry
state
(> (elt state 0) 0))
(setq retry nil)
(setq calculate-lisp-indent-last-sexp (elt state 2))
(setq containing-sexp (elt state 1))
;; Position following last unclosed open.
(goto-char (1+ containing-sexp))
;; Is there a complete sexp since then?
(if (and calculate-lisp-indent-last-sexp
(> calculate-lisp-indent-last-sexp (point)))
;; Yes, but is there a containing sexp after that?
(let ((peek (parse-partial-sexp calculate-lisp-indent-last-sexp
indent-point 0)))
(if (setq retry (car (cdr peek))) (setq state peek)))))
(if retry
nil
;; Innermost containing sexp found
(goto-char (1+ containing-sexp))
(if (not calculate-lisp-indent-last-sexp)
;; indent-point immediately follows open paren.
;; Don't call hook.
(setq desired-indent (current-column))
;; Find the start of first element of containing sexp.
(parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
(cond ((looking-at "\\s(")
;; First element of containing sexp is a list.
;; Indent under that list.
)
((> (save-excursion (forward-line 1) (point))
calculate-lisp-indent-last-sexp)
;; This is the first line to start within the containing sexp.
;; It's almost certainly a function call.
(if (or
;; Containing sexp has nothing before this line
;; except the first element. Indent under that element.
(= (point) calculate-lisp-indent-last-sexp)
;; First sexp after `containing-sexp' is a keyword. This
;; condition is more debatable. It's so that I can have
;; unquoted plists in macros. It assumes that you won't
;; make a function whose name is a keyword.
;; (when-let (char-after (char-after (1+ containing-sexp)))
;; (char-equal char-after ?:))
;; Check for quotes or backquotes around.
(let* ((positions (elt state 9))
(last (car (last positions)))
(rest (reverse (butlast positions)))
(any-quoted-p nil)
(point nil))
(or
(when-let (char (char-before last))
(or (char-equal char ?')
(char-equal char ?`)))
(progn
(while (and rest (not any-quoted-p))
(setq point (pop rest))
(setq any-quoted-p
(or
(when-let (char (char-before point))
(or (char-equal char ?')
(char-equal char ?`)))
(save-excursion
(goto-char (1+ point))
(looking-at-p
"\\(?:back\\)?quote[\t\n\f\s]+(")))))
any-quoted-p))))
;; Containing sexp has nothing before this line
;; except the first element. Indent under that element.
nil
;; Skip the first element, find start of second (the first
;; argument of the function call) and indent under.
(progn (forward-sexp 1)
(parse-partial-sexp (point)
calculate-lisp-indent-last-sexp
0 t)))
(backward-prefix-chars))
(t
;; Indent beneath first sexp on same line as
;; `calculate-lisp-indent-last-sexp'. Again, it's
;; almost certainly a function call.
(goto-char calculate-lisp-indent-last-sexp)
(beginning-of-line)
(parse-partial-sexp (point) calculate-lisp-indent-last-sexp
0 t)
(backward-prefix-chars)))))
;; Point is at the point to indent under unless we are inside a string.
;; Call indentation hook except when overridden by lisp-indent-offset
;; or if the desired indentation has already been computed.
(let ((normal-indent (current-column)))
(cond ((elt state 3)
;; Inside a string, don't change indentation.
nil)
((and (integerp lisp-indent-offset) containing-sexp)
;; Indent by constant offset
(goto-char containing-sexp)
(+ (current-column) lisp-indent-offset))
;; in this case calculate-lisp-indent-last-sexp is not nil
(calculate-lisp-indent-last-sexp
(or
;; try to align the parameters of a known function
(and lisp-indent-function
(not retry)
(funcall lisp-indent-function indent-point state))
;; If the function has no special alignment
;; or it does not apply to this argument,
;; try to align a constant-symbol under the last
;; preceding constant symbol, if there is such one of
;; the last 2 preceding symbols, in the previous
;; uncommented line.
(and (save-excursion
(goto-char indent-point)
(skip-chars-forward " \t")
(looking-at ":"))
;; The last sexp may not be at the indentation
;; where it begins, so find that one, instead.
(save-excursion
(goto-char calculate-lisp-indent-last-sexp)
;; Handle prefix characters and whitespace
;; following an open paren. (Bug#1012)
(backward-prefix-chars)
(while (not (or (looking-back "^[ \t]*\\|([ \t]+"
(line-beginning-position))
(and containing-sexp
(>= (1+ containing-sexp) (point)))))
(forward-sexp -1)
(backward-prefix-chars))
(setq calculate-lisp-indent-last-sexp (point)))
(> calculate-lisp-indent-last-sexp
(save-excursion
(goto-char (1+ containing-sexp))
(parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
(point)))
(let ((parse-sexp-ignore-comments t)
indent)
(goto-char calculate-lisp-indent-last-sexp)
(or (and (looking-at ":")
(setq indent (current-column)))
(and (< (line-beginning-position)
(prog2 (backward-sexp) (point)))
(looking-at ":")
(setq indent (current-column))))
indent))
;; another symbols or constants not preceded by a constant
;; as defined above.
normal-indent))
;; in this case calculate-lisp-indent-last-sexp is nil
(desired-indent)
(t
normal-indent))))))
Notas finales
Vale la pena señalar que esta pregunta se generalizaría mejor sobre cómo evitar que emacs sangre las listas citadas y no citadas como funciones .