I copy-pasted this example from the emacs wiki: https://www.emacswiki.org/emacs/DynamicBindingVsLexicalBinding#toc2
The wiki says that the printed thing should be 1, but for me it prints 2, indicating that lexical binding doesn't work. Does anyone have a clue why that might be?
I'm on Emacs v26. Debian.
Here is what is literally in my buffer. I am evaluating it with M-x eval-buffer.
;; -*- lexical-binding: t;-*-
(let ((a 1)) ; binding (1)
(let ((f (lambda () (print a))))
(let ((a 2)) ; binding (2)
(funcall f))))
I would appreciate your help.
You set lexical-binding as a file variable. That gets set when the file is opened, so if you just add the text to the file without closing it and reopening it, the value of lexical-binding will still be nil (do C-h v lexical-binding RET and see for yourself). So you are using dynamic binding and you get 2 for the value.
If you close and reopen the file, the file variable will be set (check it!) and when you evaluate the form, you will get 1.
Related
So I'm trying to add something into some elisp mode hooks — specifically, I'd like to define a hook's prettify-symbols-alist and then specifically activate it by calling prettify-symbols-mode.
In any case, I'm getting org-babel to export the values into a pair of lists from a table, using pairlis to tie them together as an alist, and add-hook it into the desired mode using a anonymous function.
So, the thing is, right now if I use a global variable, like the following, it works:
(let ((token (quote ("not" "*" "/" "->" "map" "/=" "<=" ">=" "lambda")))
(code (quote (172 215 247 8594 8614 8800 8804 8805 955)))) ; Generated automatically using org-babel
(require 'cl)
(setq *globalvar (pairlis token code))
(add-hook 'emacs-lisp-mode-hook
(lambda ()
(setq prettify-symbols-alist *globalvar)
(prettify-symbols-mode 1))))
But if I try to not use a global variable, by doing it this way, it doesn't work:
(let ((token (quote ("not" "*" "/" "->" "map" "/=" "<=" ">=" "lambda")))
(code (quote (172 215 247 8594 8614 8800 8804 8805 955)))) ; Generated automatically using org-babel
(let (localv)
(require 'cl)
(setq localv (pairlis token code))
(add-hook 'emacs-lisp-mode-hook
(lambda ()
(setq prettify-symbols-alist localv)
(prettify-symbols-mode 1))))
I kind of know why: if I C-h v emacs-lisp-mode-hook, I'll see that it refers to whatever variable I used in the let form, which works when the variable exists, as in *globalvar, but not when I use localvar, which no longer exists outside of its let form. But I'm not sure how to force evaluation of the local variable itself, as I'm still struggling with a lot of concepts in elisp that aren't immediately clear to me.
What am I missing? Where am I going wrong here?
Okay, here's what I did in the end:
(let ((token (quote ("not" "*" "/" "->" "map" "/=" "<=" ">=" "lambda")))
(code (quote (172 215 247 8594 8614 8800 8804 8805 955))))
(require 'cl)
(lexical-let (localv)
(setq localv (pairlis token code))
(add-hook 'emacs-lisp-mode-hook
(lambda ()
(setq prettify-symbols-alist localv)
(prettify-symbols-mode 1)))))
I ended up using phils' suggestion to use lexical-let rather than Drew's suggestion mostly because I'm currently using org-babel to tangle code blocks into my source code (basically I'm using org-mode to organize my setting files), and there doesn't appear to be a way to set the lexical-binding file-local variable — according to this page, you need to set it as the first line (using ;; -*- lexical-binding: t -*-), and I can't find a way to do that yet.
In any case, thank you to everyone who helped me out on this question!
Start by setting lexical-binding to non-nil, or else localv will be a free variable in your hook function. Preferably, set lexical-binding as a file-local variable.
In addition, there is nothing in your code that makes localv buffer-local. Presumably you want to give it a value that is local to the buffer that is in that mode. The code that binds it should be evaluated in the mode (i.e., in the buffer) in question.
I like this solution. With lexical-let, the call to lambda (inside add-hook) generates a closure, as you can see if you type M-x ielm RET and emacs-lisp-mode-hook RET to examine its value.
You could also use old-school style backtick like this:
(add-hook 'emacs-lisp-mode-hook
`(lambda ()
(setq prettify-symbols-alist ',localv)
(prettify-symbols-mode 1)))
(EDIT)
Note the backtick before the lambda and (as tarikq mentioned) the quote-comma before localv.
I think you got the meaning!
Actually, instead of "expand this then quote it", I would say "insert its value (from the lexical environment), then quote it".
If you try something like:
(macroexpand '`(lambda ()
(setq prettify-symbols-alist ',localv)
(prettify-symbols-mode 1)))
then you will get what lisp will actually do at run time:
(cons 'lambda
(cons nil
(cons
(list 'setq 'prettify-symbols-alist (list 'quote localv))
'((prettify-symbols-mode 1)))))
and you will see how the whole list is constructed, and how localv is normally evaluated, i.e. not quoted (compare with the symbols 'setq and 'prettify-symbols-alist and the list '((prettify-symbols-mode 1)))
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)
I am using zenburn.el color-scheme in emacs 23. The function name that starts with "do-" gets highlighted, as given in the figure below --
How do I fix it? Any idea?
I do not observe this with Emacs 24.3 (the current development version).
The code which would have resulted in this highlighting is commented out in lisp-mode.el:
;; This is too general -- rms.
;; A user complained that he has functions whose names start with `do'
;; and that they get the wrong color.
;; ;; CL `with-' and `do-' constructs
;;("(\\(\\(do-\\|with-\\)\\(\\s_\\|\\w\\)*\\)" 1 font-lock-keyword-face)
So, what you need to do is:
(dolist (s (apropos-internal "lisp.*-font-lock" #'boundp))
(set s (cl-remove-if (lambda (l)
(let ((re (car l)))
(and (stringp re)
(string-match re "do-something"))))
(symbol-value s))))
or just edit lisp-mode.el, comment out the appropriate regexp, and rebuild.
Update 2013 May: As of GNU Emacs 24.3.1, (let .. (defun..)) bytecompiles just fine without warning and the bytecompiled code works the same as not-compiled code. Just don't forget to add the file variable lexical-binding: t to the file to be bytecompiled. Workarounds at the end of this question is now not necessary.
Lexical Binding - Emacs Lisp Manual has this paragraph:
Note that functions like symbol-value, boundp, and set only retrieve or modify a variable's dynamic binding (i.e. the contents of its symbol's value cell). Also, the code in the body of a defun or defmacro cannot refer to surrounding lexical variables.
I am not sure if I am getting the meaning of the second sentence right. In the following code which should be run in lexical binding mode, the code in the body of a defun is successfully referring to the lexical binding value of the name n.
(let ((n 0))
(defun my-counter ()
(incf n)))
(my-counter) ;; 1
(my-counter) ;; 2
Is the sentence simply saying that (let .. (defun ..)) is a bad practice?
Workarounds:
;; -*- lexical-binding: t -*-
;; a way to define the counter function without byte-compile error or warning
(defvar my--counter-func
(let ((n 0))
(lambda ()
(setq n (1+ n)))))
(defun my-counter ()
(funcall my--counter-func))
;; another way to define the counter function, again without byte-compile error or warning
(fset 'my-another-counter
(let ((n 0))
(lambda ()
(setq n (1+ n)))))
And here's the code for testing the above code:
;; run:
;; emacs -q --load path-to-the-el-file-of-this-code.el
(load "path-to-file-defining-my-counter.elc") ;; loading the ELC file to test if byte-compiled code runs as expected.
(print (my-counter)) ;; 1
(print (my-counter)) ;; 2
(print (my-another-counter)) ;; 1
(print (my-another-counter)) ;; 2
The code does not byte-compile well at least in Emacs 24.1.1. I saved the following code in the foo.el file, which uses setq in place of incf in order to avoid any possible effects by the cl library:
;; -*- lexical-binding: t -*-
(let ((n 0))
(defun my-counter ()
(setq n (1+ n))))
When I tried to byte-compile it (M-x byte-compile-filefoo.el), I got the following warning messages:
foo.el:3:1:Warning: Function my-counter will ignore its context (n)
foo.el:3:1:Warning: Unused lexical variable `n'
foo.el:5:11:Warning: reference to free variable `n'
foo.el:5:17:Warning: assignment to free variable `n'
All of the messages are indicating that the code in the body of the defun construct cannot refer to the surrounding lexical variable n as the manual claims.
Actually, when I loaded the byte-compiled code (M-x load-filefoo.elc) and evaluted the (my-counter) form, I got the following erorr:
Debugger entered--Lisp error: (void-variable n)
...
Unfortunately, I'm not sure why the code appears to work when evaluated in the form of source code.
As I replied on gnu.emacs.help, you can use (defalias 'foo (lambda ...)) to work around that limitation.
And that limitation is lifted in Emacs's development code.
It's perfectly fine to refer to variables in lexical scope(*) from within a defun, just as you are doing above, and just as the "my-ticker" example on that manual page does as well.
Either I am missing something the line in the manual that says:
the code in the body of a defun or defmacro cannot refer to
surrounding lexical variables.
should say something more like:
code in the body of a defun can only access lexical variables if they are defined within the same lexical scope.
NOTE: There are comments in the other answers about problems byte-compiling this kind of code. Those should be fixed in the latest emacs. I've verified in v24.2.50.1 that this byte compiles and loads correctly.
Is it possible to configure Emacs, so that it saves all files when the emacs window loses
focus?
I added focus hooks to Gnu Emacs 24.4.
They are called focus-in-hook and focus-out-hook.
You can add
(defun save-all ()
(interactive)
(save-some-buffers t))
(add-hook 'focus-out-hook 'save-all)
to your .emacs file and it should save all files on loss of focus.
I use this, it will only work if emacs is running under X (like it probably would in something like ubuntu).
(when
(and (featurep 'x) window-system)
(defvar on-blur--saved-window-id 0 "Last known focused window.")
(defvar on-blur--timer nil "Timer refreshing known focused window.")
(defun on-blur--refresh ()
"Runs on-blur-hook if emacs has lost focus."
(let* ((active-window (x-window-property
"_NET_ACTIVE_WINDOW" nil "WINDOW" 0 nil t))
(active-window-id (if (numberp active-window)
active-window
(string-to-number
(format "%x00%x"
(car active-window)
(cdr active-window)) 16)))
(emacs-window-id (string-to-number
(frame-parameter nil 'outer-window-id))))
(when (and
(= emacs-window-id on-blur--saved-window-id)
(not (= active-window-id on-blur--saved-window-id)))
(run-hooks 'on-blur-hook))
(setq on-blur--saved-window-id active-window-id)
(run-with-timer 1 nil 'on-blur--refresh)))
(add-hook 'on-blur-hook #'(lambda () (save-some-buffers t)))
(on-blur--refresh))
Not sure if this is what you want.
(defun dld-deselect-frame-hook ()
(save-some-buffers 1))
(add-hook 'deselect-frame-hook 'dld-deselect-frame-hook)
From: http://www.dribin.org/dave/blog/archives/2003/09/10/emacs/
EDIT: It only seems to work in XEmacs
[…] the feature I am talking about is from
Scribes. It is very convient when
editing html and the like, you don't
have to press C-x C-s anymore, you
just change the window and check your
browser.
In that case, instead of switching to the browser application, order Emacs to load the browser application (C-c C-v or M-x browse-url-of-buffer). With this method, you can write your own function that saves the buffer and then brings the browser up, like:
(defun my-browse-url-of-buffer ()
"Save current buffer and view its content in browser."
(interactive)
(save-buffer)
(browse-url-of-buffer))
And hook it to a convenient binding.
Or you can still use the html-autoview-mode that each time you saves the buffer, automatically loads the file into your favorite browser.
You can use `auto-save-interval' to save every n characters you type. Mine is set to 100. So about every 2-3 lines of code, maybe?
auto-save-interval is a variable
defined in `C source code'. Its value
is 100
Documentation:
*Number of input events between auto-saves. Zero means disable
autosaving due to number of characters
typed.
You can customize this variable.
This doesn't answer your original question; it's just a way to achieve something similar.