tags:

views:

127

answers:

3

I usually play with elisp code on my scratch buffer. I find it hard to play with elisp code that moves cursors in this way because I don't know how to separate the buffer for editing code and the buffer for testing the code.

For example if I want to play with the following code:

(backward-up-list 1)
(backward-sexp 1)
(kill-sexp 2)

from searching with intelligent bracket counting elisp, I'd like to run one line at a time and see what each line does. But the code moves the caret in the very scratch buffer I pasted that code in and I'm already using that caret to edit or run the code. Another problem is that this code is supposed to be tested on a TeX document and my scratch buffer is not a TeX document.

It all comes down to how to separate the painter and the painting.

Though in that example, just looking at the C-h f manual would be enough to understand what's going on. But that's only because this example code is simple enough.

+5  A: 

Compile the function with edebug (C-u C-M-x instead of C-M-x), switch to a buffer to experiment in, invoke the function via M-:, and then single-step (n) in the debugger.

Otherwise, learn to think in bigger chunks, and test in your test buffer with M-:. This is what I do for nearly everything, including very complicated code like cperl-mode.

jrockway
+3  A: 

In addition to M-: (i.e., eval-expression), also look at with-selected-window. It executes its body in the context of a given window. For example, assuming you have two windows,

(with-selected-window (next-window)
  (backward-up-list 1))

will perform the backward-up-list operation in the other window.

huaiyuan
+1  A: 

I found some other workarounds (Similar to with-selected-window)

Using set-buffer with progn:

(progn
  (set-buffer "edithere.el")
  (insert "hello")
  (beginning-of-line))

The buffer name edithere.el must be present. Press C-M-x to evaluate the progn form. You can also use let. When you want to write a command that edits buffer or moves cursor, instead of starting with "(defun ...", you may start with "(progn ..." like above, and once it's finished, change to defun.

Using with-current-buffer: (Press C-M-x to evaluate the with-current-buffer form)

(with-current-buffer "edithere.el"
  (insert "hello")
  (beginning-of-line))
RamyenHead