How to break out of an infinite loop in emacs lisp ? (environment: emacs) - emacs

I tried using ctrl-c then :a
But It doesn't work here.
My code is like:
(defun game-repl()
(loop (print (eval (read)))))
then I run
(game-repl())
look()

(require 'cl)
(loop (setq x (read))
(if (eq x 'exit)
(return)
(print (eval x))))

Emacs modes often send an interruption signal to the inferior program only when you hit Ctrl-C twice in a row (i.e., the key sequence you are looking for is C-c C-c). In particular, this is true for SLIME.
This is because C-c is a prefix key that is usually combined with other keys to access a whole bunch of mode-specific features.

This question can refer to:
how to programmatically break out of a loop that would otherwise be infinite or
how to manually stop an infinite loop that's already raging.
The 1st has satisfactorily been answered by #fred-foo (and it seems it was OP's actual question). The 2nd has been tackled by #matthias-benkard but his answer is not working for emacs lisp.
The actual answer to manually stop a running infinite emacs-lisp loop is Ctrl+g (C-g in emacs-speak).
There is a documentation page in the emacs lisp manual on this very topic.
Sorry, I don't have the reputation to just amend #matthias-benkard's answer and the question ranks high on search engines...

[Reference http://www.psg.com/~dlamkins/sl/chapter05.html]
Most of the time you write a LOOP form, you'd like to have a way out. Fortunately, a RETURN form anywhere inside will cause control to leave the LOOP; any value you specify becomes the value of the LOOP form:
? (loop
(print "Here I am.")
(return 17)
(print "I never got here."))
"Here I am."
17
RETURN is normally used in a conditional form, like this:
? (let ((n 0))
(loop
(when (> n 10) (return))
(print n) (print (* n n))
(incf n)))
0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
NIL
?

This Stack Exchange answer is the first hit on google for "break a never ending loop slime"
C-c C-b
What is missing, is that different lisps handle this break differently. I found this answer because GNU Clisp just doesn't intercept SLIME's C-c C-b. Nor does it do what SBCL does which is intercept both C-c C-b and C-c C-c.

Related

loop keyword immediately after finally

When I had asked how to Get numbers for the lottery I was given the hint to create a function that shuffles a list. So I tried to do so, and I even got it working.
My current implementation looks like this:
(defun shuffle (list)
(let ((len (length list)))
(loop repeat len
do
(rotatef
(nth (random len) list)
(nth (random len) list))
finally
return list)))
Good news is that it works:
(shuffle '(1 2 3 4 5 6))
;; => (3 1 4 2 6 5)
Bad news is that I get an error message:
WARNING: LOOP: loop keyword immediately after FINALLY: permitted by CLtL2, forbidden by ANSI CL.
Unfortunately I don't understand it. Why does it tell me that loop immediately appears after finally? And, what's wrong with the code that actually causes this?
Is there a better way to formulate this?
WARNING: LOOP: loop keyword immediately after FINALLY: permitted by CLtL2, forbidden by ANSI CL.
This means that RETURN is a loop keyword, which is not allowed after finally, according to the ANSI CL standard.
If we want to return from the LOOP, we need to use the return macro:
(loop ...
finally (return list))
It's actually a common mistake. finally return <expr> is no longer allowed since the ANSI CL standard. That's also a reason not to use CLtL2 (Common Lisp the Language, 2nd Edition) as a reference. The CL Hyperspec is the better reference.

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 update evaluation result comments of Emacs Lisp forms easilly

Say I have this code which shows usage examples of mapcar
(mapcar #'1+ (list 10 20 30)) ; ⇒ (11 21 31)
(mapcar (lambda (it)
(* 2 it))
(list 0 1 2 3))
;; ⇒ (0 2 4 6)
(require cl-lib)
(cl-mapcar #'+
'(1 2 3)
'(10 20 30))
;; ⇒ (11 22 33)
I may be keeping that code somewhere written so that I can use it on a tutorial or so that whenever I forget how mapcar works, I can quickly read the code.
Now suppose I want to update some of the examples in the code. For example, I may change (list 0 1 2 3) in the second example to some other list. Right after I change the example, the corresponding result comment is then outdated. The result comment need to be updated as well. So I evaluate the form, copy the result, and replace the old result in the comment with new result. Is there a package I can use to help me do that all easily and less tediously? This is a different problem than problems that the litable or ielm package solve because this is simply about updating existing example code.
Right now what I use is:
(defun my-insert-eval-last-sexp ()
(interactive)
(let ((beg (point)))
(let ((current-prefix-arg '(4)))
(call-interactively 'eval-last-sexp))
(goto-char beg)
(if (looking-back ")")
(insert " ; "))
(insert "⇒ ")
(move-end-of-line 1)))
which still isn't enough because it simply adds the result comment rather than updating an old one, and has a bug of odd stuff getting inserted when the form evaluates to a number:
(+ 1 2)
;; ⇒ 3 (#o3, #x3)
Well, I'm not sure I want to encourage this kind of thing ;-), but this will get you a little closer to what you are trying to do, IIUC:
(defun my-insert-eval-last-sexp ()
(interactive)
(let ((this-command 'eval-print-last-sexp))
(save-excursion (eval-last-sexp-1 t)))
(when (looking-back ")") (insert " ; "))
(insert "⇒ ")
(move-end-of-line 1))
You don't need to save point and then explicitly go back to it --- use save-excursion.
You don't need to bind the prefix arg and call the command interactively. Just call it (or its helper function) directly, passing the arg you want.
You need to tweak the behavior to prevent it from thinking this is the second occurrence of the command, which is what causes it to print the octal etc. number info. The let binding does that (but is an ugly little hack).
Respective thing your function does is implemented in org-mode, i.e. org-babel.
See in Info, Org Mode, 14 Working with source code

Emacs: adding 1 to every number made of 2 digits inside a marked region

Imagine I've got the following in a text file opened under Emacs:
some 34
word 30
another 38
thing 59
to 39
say 10
here 47
and I want to turn into this, adding 1 to every number made of 2 digits:
some 35
word 31
another 39
thing 60
to 40
say 11
here 48
(this is a short example, my actual need is on a much bigger list, not my call)
How can I do this from Emacs?
I don't mind calling some external Perl/sed/whatever magic as long as the call is made directly from Emacs and operates only on the marked region I want.
How would you automate this from Emacs?
I think the answer I'm thinking of consist in calling shell-command-on-region and replace the region by the output... But I'm not sure as to how to concretely do this.
This can be solved by using the command query-replace-regexp (bound to C-M-%):
C-M-%
\b[0-9][0-9]\b
return
\,(1+ \#&)
The expression that follows \, would be evaluated as a Lisp expression, the result of which used as the replacement string. In the Lisp expression, \#& would be replaced by the matched string, interpreted as a number.
By default, this works on the whole document, starting from the cursor. To have this work on the region, there are several posibilities:
If transient-mark-mode is turned on, you just need to select the region normally (using point and mark);
If for some reason you don't like transient-mark-mode, you may use narrow-to-region to restrict the changes to a specific region: select a region using point and mark, C-x n n to narrow, perform query-replace-regexp as described above, and finally C-x n w to widen. (Thanks to Justin Smith for this hint.)
Use the mouse to select the region.
See section Regexp Replacement of the Emacs Manual for more details.
Emacs' column editing mode is what you need.
Activate it typing M-x cua-mode.
Go to the beginning of the rectangle (leave cursor on character 3) and press C-RET.
Go to the end of the rectangle (leave cursor on character 7). You will be operating on the highlighted region.
Now press M-i which increments all values in the region.
You're done.! remove dead ImageShack links
It doesn't protect against 99->100.
(defun add-1-to-2-digits (b e)
"add 1 to every 2 digit number in the region"
(interactive "r")
(goto-char b)
(while (re-search-forward "\\b[0-9][0-9]\\b" e t)
(replace-match (number-to-string (+ 1 (string-to-int (match-string 0)))))))
Oh, and it operates on the region. If you want the entire file, then you replace b and e with (point-min) and nil.
Moderately tested; use M-: and issue the following command:
(while (re-search-forward "\\<[0-9][0-9]\\>" nil t) (let ((x (match-string 0))) (delete-backward-char 2) (insert (format "%d" (1+ (string-to-int x))))))
I managed to get it working in a different way using the following (my awk-fu ain't strong so it probably can be done in a simpler way):
C-u M-x shell-command-on-region RET awk '$2>=0&&$2<=99 {$2++} {print}' RET
but I lost my indentation in the process : )
Seeing all these answers, I can't help but have a lot of respect for Emacs...

Emacs: how to evaluate the smallest s-expression the cursor is in, or the following s-expression

What is a good way to evaluate the (+ 100 (+ 100 100)) part in
(+ (+ 1 2) (+ 100 (+ 100 100)))
?
For now, I do it by C-x C-e, which means I need to locate the ending parenthesis, which is difficult in most cases. Options > Paren Matching Highlighting helps, but still I need to move the cursor toward the ending parenthesis until the highlighted match is the starting parenthesis.
One way would be to have the reverse version of C-x C-e, so that I can place the cursor at the starting parenthesis like this:
(+ (+ 1 2) |(+ 100 (+ 100 100)))
and then press the appropriate keybinding.
Or I could place the cursor inside the expression, but not inside smaller expressions,:
(+ (+ 1 2) (+ | 100 (+ 100 100)))
and press a keybinding. Because aiming at a target is easier if the target is big.
How can I make such a command? Or is there one already provided?
Sidenote: bar cursor and box cursor
Emacsers who use box cursor (default) might wonder where I'm putting the cursor with the bar notation above. In emacs, you can choose box cursor or bar cursor, (bar-cursor-mode t). When the bar cursor is between the letters A and B, the box cursor is on B. So the bar is the left wall of the box.
BTW, the concept of bar cursor is useful in some unusual way:
The practice of iterating from index1 to index2-1 in programming surprises beginners. It helps to imagine index1 and index2 as indicating bars (left walls) rather than boxes.
Bind a key to one or both of these:
(defun eval-next-sexp ()
(interactive)
(save-excursion
(forward-sexp)
(eval-last-sexp nil)))
(defun eval-surrounding-sexp (levels)
(interactive "p")
(save-excursion
(up-list (abs levels))
(eval-last-sexp nil)))
Tangentially related, I highly recommend paredit for working with s-expressions. The structure editing commands and bindings make editing s-expressions a breeze. It binds C-down to up-list, so that eval-surrounding-sexp above is almost exactly the same as C-down C-x C-e (the only difference is that the function uses save-excursion to prevent movement).
You could write such a command like so:
(require 'thingatpt)
(defun eval-sexp-at-or-surrounding-pt ()
"evaluate the sexp following the point, or surrounding the point"
(interactive)
(save-excursion
(forward-char 1)
(if (search-backward "(" nil t)
(message "%s" (eval (read-from-whole-string (thing-at-point 'sexp)))))))
In Icicles there is a general way to do what you want.
By default, in the minibuffer M-. is bound to a command that inserts text at (or near) point into the minibuffer (doesn't enter it or doing else with it; just inserts it).
You can, for example, use M-: to evaluate a Lisp sexp, and then you use M-. to grab a sexp at/near point.
If you repeat M-. then it drops what it just grabbed and grabs some other kind of THING (text) at/near point and inserts that. By default, it runs through these kinds of THING, in order:
a. A Lisp symbol or file name.
b. The active region (selected text) or a word.
c. The most immediate list.
d. The next largest list.
e. The next largest list.
f. Whichever file or URL the function ffap-guesser guesses.
g. Whatever URL the function thing-at-point-url-at-point guesses.
What does this mean for your example of (+ (+ 1 2) (+ 100 (+ 100 100)))?
If point is before the 1 of the second-to-last 100, for example, these are the sexps that are consecutively inserted in the minibuffer when you hit M-. repeatedly, in order:
a. +
b. 100
c. (+ 100 100)
d. (+ 100 (+ 100 100))
e. (+ (+ 1 2) (+ 100 (+ 100 100)))?
So to insert the largest of the enclosing lists you would do M-: M-. M-. M-. M-. M-., that is, hit M-. five times.
For this behavior, in particular for the accurate grabbing of lists, you also need library Thing At Point+.
There is an inbuilt eval-defun. It's bound by default to C-M-x. It's similar to what you want but evals the top-level defun. Perhaps you can adapt that.