Take the 2-minute tour ×

So I have this function which gives me start and end position of selected text

(defun start-end (pos1 pos2)
  (interactive "r")
  ; …
  (message "start: %d. end: %d." pos1 pos2)

Now I want to write to other file buffer named "result" (or create buffer if not exists), something like:


where param1, param2 should be asked on cmd line. How do I make this happen ?

share|improve this question
add comment

2 Answers

Try something like:

(defun start-end (pos1 pos2 param1 param2)
  (interactive "r\nsParam1: \nsParam2: ")
  (message "%d,%d,%s,%s" pos1 pos2 param1 param2))

interactive supports a range of different input forms. You can separate them with newline:s to use more than one. In fact, you could supply an expression rather than a string, which is executed to perform any interactive action.


To create buffer you can use the following, it allows you to use all standard print function to insert anything in the new buffer:

(defun start-end (pos1 pos2 param1 param2)
  (interactive "r\nsParam1: \nsParam2: ")
  (with-output-to-temp-buffer "*Result*"
    (princ (format "%d,%d,%s,%s" pos1 pos2 param1 param2))))
share|improve this answer
thx, how about new buffer ? –  Zdanozdan Nov 20 '12 at 21:41
@Zdanozdan, see the addition in the answer. –  Lindydancer Nov 21 '12 at 8:09
add comment

Here's the code to create a buffer (if it doesn't exist) then append the text you want to it:

(defun start-end (pos1 pos2)
  (interactive "nStart: \nnEnd: ")
  (switch-to-buffer (get-buffer-create "*start-end*"))
  (goto-char (point-max))
  (insert (format "start: %d. end: %d.\n" pos1 pos2)))
share|improve this answer
And you could use format instead of message if you don't want the information shown in the mini buffer and in *messages*. –  Moritz Bunkus Nov 21 '12 at 10:36
To quote the docstring of switch-to-buffer: "WARNING: This is NOT the way to work on another buffer temporarily within a Lisp program! Use set-buffer instead. That avoids messing with the window-buffer correspondences.". And often instead of set-buffer you're even better off using with-current-buffer. –  Stefan Nov 21 '12 at 14:36
@Moritz: Yeah I should have used format, forgot to change it. –  justinhj Nov 21 '12 at 17:19
@Stefan I don't know where you got that text from but it's not in the help for the function in my emacs (24.1.1). I would use with-current-buffer but this code switches to the buffer when done. It's up to the person asking the question to choose the behaviour they prefer. –  justinhj Nov 21 '12 at 17:21
@justinhj: Indeed, the warning was accidentally dropped from 24.1. It'll be back in 24.3. –  Stefan Nov 21 '12 at 17:45
show 1 more comment

Your Answer


