What does the `#` mean in elisp? [duplicate] - emacs

This question already has answers here:
What is the role of the # character in Emacs Lisp?
(2 answers)
Closed 7 years ago.
Quite likely this is a dumb question, but I haven't come across the # symbol in the bits of elisp I have read, and was wondering what it means (preceded by a , as well) in this code? I have had some difficulty providing the proper search phrase I think.
In case of link rot:
(defmacro zenburn-with-color-variables (&rest body)
"`let' bind all colors defined in `zenburn-colors-alist' around BODY.
Also bind `class' to ((class color) (min-colors 89))."
(declare (indent 0))
`(let ((class '((class color) (min-colors 89)))
,#(mapcar (lambda (cons)
(list (intern (car cons)) (cdr cons)))
zenburn-colors-alist))
,#body))

This is an elisp macro definition, it defines a template for code to be substituted by other code at compile time. A decent intro is chapter 7 of Paul Graham's On Lisp
http://www.paulgraham.com/onlisptext.html

Ask Emacs, by checking the index of the elisp manual:
C-hig (elisp) RET
I # RET
Follow result: * ,# (with backquote) [Index]: Backquote. (line 29)
You can also "splice" an evaluated value into the resulting list,
using the special marker ‘,#’. The elements of the spliced list become
elements at the same level as the other elements of the resulting list.
The equivalent code without using ‘`’ is often unreadable. Here are
some examples:
[...]

Related

Emacs: What does the "#" before function symbol imply? [duplicate]

This question already has answers here:
When should Emacs #'function syntax be used?
(3 answers)
Closed 6 years ago.
For example: (add-hook 'after-init-hook #'global-flycheck-mode)
Why # needs to be prepended to 'global-flycheck-mode?
#' is just a short-hand for using function. From the elisp manual:
-- Special Form: function function-object
This special form returns FUNCTION-OBJECT without evaluating it.
In this, it is similar to ‘quote’ (see Quoting). But unlike
‘quote’, it also serves as a note to the Emacs evaluator and
byte-compiler that FUNCTION-OBJECT is intended to be used as a
function. Assuming FUNCTION-OBJECT is a valid lambda expression,
this has two effects:
• When the code is byte-compiled, FUNCTION-OBJECT is compiled
into a byte-code function object (see Byte Compilation).
• When lexical binding is enabled, FUNCTION-OBJECT is converted
into a closure. See Closures.
You can see the difference when byte-compiling/loading this
(setq f1 '(lambda (x) (* x x)))
(setq f2 #'(lambda (x) (* x x)))
Only the the correctly quoted form is byte-compiled:
(byte-code-function-p f1)
nil
(byte-code-function-p f2)
t

How to convert kbd-macro to real command in Emacs? [duplicate]

This question already has answers here:
Convert Emacs macro into Elisp
(2 answers)
Closed 8 years ago.
It seems kbd-macro only records keys I pushed. But I want to record real commands(that is tied with key I pushed) and save these as function.
So my question is something like following.
How to record commands I used as executable format?
How to convert key sequence to command sequence?
How to convert my-kbd-macro to command sequence function?
Example:
F3(M-x kmacro-start-macro)
C-f
F4(M-x kmacro-end-or-call-macro)
M-x name-last-kbd-macro my-kbd-macro
M-x insert-kbd-macro my-kbd-macro
Output:
(fset 'my-kbd-macro
"\C-f")
My desired output is like following:
(defun my-kbd-macro ()
(interactive)
(forward-char)
)
Thanks.
Here's a simplistic implementation of what you want.
It will work only for simple commands that don't want input, like forward-char.
To do any more in a fully automated way seems hard / not feasible. That's why this functionality
isn't in place already, I guess.
I've added these functions to
my macro package that allows multiple anonymous macros
You can get it from github or from MELPA as centimacro.
To use it, just do your F3 ... F4 thing, and
M-x last-macro-to-defun from e.g. *scratch*.
(defun macro->defun (str)
"Convert macro representation STR to an Elisp string."
(let ((i 0)
(j 1)
(n (length str))
forms s f)
(while (< i n)
(setq s (substring str i j))
(setq f (key-binding s))
(if (keymapp f)
(incf j)
(push (list f) forms)
(setq i j)
(setq j (1+ i))))
(with-temp-buffer
(emacs-lisp-mode)
(insert
"(defun foo ()\n (interactive)")
(mapc (lambda (f)
(newline-and-indent)
(insert (prin1-to-string f)))
(nreverse forms))
(insert ")")
(buffer-string))))
(defun last-macro-to-defun ()
"Insert last macro as defun at point."
(interactive)
(insert (macro->defun last-kbd-macro)))
Do bear in mind that when writing a function there are frequently better ways to do things than to exactly mimic the interactive bindings, so while not necessary, some refactoring is likely going to be beneficial if you start out with just the commands used when the macro runs.
Anyhow, I can think of a couple of useful tools to assist with working this out manually:
Firstly, if you edit a keyboard macro, the macro editor comments each key with the function it is bound to (n.b. for the buffer in which you invoke the editor! -- if you are switching buffers while your macro executes, I would suggest checking the editor for each buffer).
Obviously you can obtain the same information in other ways, but the macro editor gives you the whole list, which could be convenient.
The other helper is repeat-complex-command bound to C-xM-:, which gives you the resulting elisp form from certain types of interactive function call ("a complex command is one which used the minibuffer"). My favourite example of this is align-regexp, as it's a case where the user's interactive arguments are further manipulated, which isn't necessarily obvious. e.g.:
M-x align-regexp RET = RET C-xM-: might tell you:
(align-regexp 1 191 "\\(\\s-*\\)=" 1 1 nil)

How to exchange words in emacs(by replace them with each other one) [duplicate]

This question already has answers here:
How can I swap or replace multiple strings in code at the same time?
(5 answers)
Closed 8 years ago.
Say I have some text like:
First one is good, so I used first one.Second one is bad, so I drop it.
I want to switch the 'first' and 'second',and like replace-string,leave the capital to the same case as original word.
Is there any built-in functions to handle this situations?
Edit:
Let me explain the problem further.If I use usual replace-string twice,will some times cause unwanted results.In the example above, If using replace-string first RET second RET, then replace-string second RET first RET,it will out put: First one is good. so I used first one.First one is bad, so I drop it. It also a problem in some case like "clientFolder=>serverFolder and server=> client"
#huaiyuan answered the same question here:
How can I swap or replace multiple strings in code at the same time?
His code allows you to enter arbitrary list of pairs to do parallel replacement.
Incidently, if you want to read some cool lisp code, click on #huaiyuan and read his answers.
Here's a great trick courtesy of Mickey's Mastering Emacs blog (see http://www.masteringemacs.org/articles/2013/01/25/evaluating-lisp-forms-regular-expressions/ under the heading "Swapping Elements")
C-M-% \(first\)\|second RET \,(if \1 "second" "first") RET
Edit: and here's an elisp version of that:
(defun my-swap-text (a b)
"Swap two pieces of text wherever they appear, using `query-replace-regexp'."
(interactive "sSwap: \nswith: ")
(let ((use-region (and transient-mark-mode mark-active)))
(query-replace-regexp
(rx (or (group (eval a)) (eval b)))
(quote (replace-eval-replacement replace-quote (if (match-string 1) b a)))
nil
(when use-region (region-beginning))
(when use-region (region-end)))))
did you google search this at all?
http://kb.iu.edu/data/abdp.html

Why do some use #'(lambda instead of just (lanbda in Common Lisp? [duplicate]

This question already has answers here:
Why use #' with lambda?
(2 answers)
Closed 9 years ago.
Why do some use #'(lambda instead of just (lambda in Common Lisp? Are there performance benefits or something?
Because, as Peter Siebel and others explain, in CL, "the following LAMBDA expression: (lambda () 42) expands into the following when it occurs in a context where it evaluated: (function (lambda () 42))".
There is not performance benefits except few milliseconds of compile time vs few millisecods of read time :)
I think real reason is consistency. If one writes (mapcar #'myfunc ...) (not just (mapcar myfunc ...)), it is natural to write (mapcar #'(lambda ...) ...) too.

emacs: how do I use edebug on code that is defined in a macro?

I don't even know the proper terminology for this lisp syntax, so I don't know if the words I'm using to ask the question, make sense. But the question makes sense, I'm sure.
So let me just show you. cc-mode (cc-fonts.el) has things called "matchers" which are bits of code that run to decide how to fontify a region of code. That sounds simple enough, but the matcher code is in a form I don't completely understand, with backticks and comma-atsign and just comma and so on, and furthermore it is embedded in a c-lang-defcost, which itself is a macro. I don't know what to call all that, but I want to run edebug on that code.
Look:
(c-lang-defconst c-basic-matchers-after
"Font lock matchers for various things that should be fontified after
generic casts and declarations are fontified. Used on level 2 and
higher."
t `(;; Fontify the identifiers inside enum lists. (The enum type
;; name is handled by `c-simple-decl-matchers' or
;; `c-complex-decl-matchers' below.
,#(when (c-lang-const c-brace-id-list-kwds)
`((,(c-make-font-lock-search-function
(concat
"\\<\\("
(c-make-keywords-re nil (c-lang-const c-brace-id-list-kwds))
"\\)\\>"
;; Disallow various common punctuation chars that can't come
;; before the '{' of the enum list, to avoid searching too far.
"[^\]\[{}();,/#=]*"
"{")
'((c-font-lock-declarators limit t nil)
(save-match-data
(goto-char (match-end 0))
(c-put-char-property (1- (point)) 'c-type
'c-decl-id-start)
(c-forward-syntactic-ws))
(goto-char (match-end 0)))))))
I am reading up on lisp syntax to figure out what those things are and what to call them, but aside from that, how can I run edebug on the code that follows the comment that reads ;; Fontify the identifiers inside enum lists. ?
I know how to run edebug on a defun - just invoke edebug-defun within the function's definition, and off I go. Is there a corresponding thing I need to do to edebug the cc-mode matcher code forms?
What does def-edebug-spec do, and would I use it here? If so, how?
According to (elisp)Top > Debugging > Edebug > Edebug and Macros you have to tell Edebug how to debug a macro by defining it with debug statements or by using def-edebug-spec. This tells it what parameters should be evaluated and which shouldn't. So it can be done. In fact it looks as if c-lang-defconst already been fitted for edebug. Here is the definition in case you were interested:
(def-edebug-spec c-lang-defconst
(&define name [&optional stringp] [&rest sexp def-form]))
However, if you just want to see what the body evaluates to, then the way to do that is to use something like macro-expand-last-sexp below to see the result. Position your cursor after the sexp you want expanded (as you would for C-x C-e) and run M-x macro-expand-last-sexp RET. This will show you what it gets expanded to. You may run into troubles if you try to expand something like ,(....) so you may have to copy that sexp somewhere else and delete the , or ,#.
(defun macro-expand-last-sexp (p)
"Macro expand the previous sexp. With a prefix argument
insert the result into the current buffer and pretty print it."
(interactive "P")
(let*
((sexp (preceding-sexp))
(expanded (macroexpand sexp)))
(cond ((eq sexp expanded)
(message "No changes were found when macro expanding"))
(p
(insert (format "%S" expanded))
(save-excursion
(backward-sexp)
(indent-pp-sexp 1)
(indent-pp-sexp)))
(t
(message "%S" expanded)))))
I guess it depends on exactly what you are trying to do.
Use macroexpand or macroexpand-all to turn it into macro-free code and debug as usual?
Backticks &co may be best illustrated by an example:
(let ((a 1)
(b (list 2 3)))
`(a ,a ,b ,#b))
-> (a 1 (2 3) 2 3)
A backtick (or backquote`) is similar to a quote(') in that it prevents evaluation, except its effect can be selectively undone with a comma(,); and ,# is like ,, except that its argument, which must be a list, is spliced into the resulting list.