0

Am trying to use read-string to read a string from the user. With that name I want to create a new buffer.

Have seen that read-string is sometimes called from within an interactive expression, but at other times, read-string is called outside on interactive expression. How can I understand when to use one versus the other?

(defun workspace (name)
  "Make a new buffer with unique name."
  (interactive
    (read-string "Name: " initial nil nil))

(let ( ($buf (generate-new-buffer name)) ) (switch-to-buffer $buf) )

Dilna
  • 1
  • 3
  • 11

2 Answers2

0

Your function has an argument name that would be supplied another way when called from lisp. Example:

(workspace "*foo*")

When called interactively, you need a way for the user to supply that argument which is what the read-string inside the interactive is for.

Other functions might need user input for a different purpose than filling in an argument and, in that case, no interactive will be involved:

(defun pointless-game ()
 "Ask user for a word, forever."
 (while 1
   (message "You said: %s\n"
            (read-string "Tell me a word: "))))
Fran Burstall
  • 3,855
  • 11
  • 18
0

Normally you should use one of the predefined argument types rather than calling read-string yourself. Did you read the docstring for interactive? It is long but complete.

(defun db48x/test-workspace (name)
  "Make a new buffer with unique name."
  (interactive "BName: ")
  (let (($buf (generate-new-buffer name)))
    (switch-to-buffer $buf)))
db48x
  • 17,977
  • 1
  • 22
  • 28
  • I know about Code Characters for interactive. But seeing other's code, I also see calls that use, read-string, completing read. But not much advice on when to choose what. You have any advice on this? – Dilna Jun 27 '22 at 12:25
  • Yes, avoid it when possible. – db48x Jun 27 '22 at 12:32
  • By default, B uses the name of a recently used buffer. I want to avoid that when making the new buffer. Can I get emacs to generate a unique name, but also let the user change it? – Dilna Jun 27 '22 at 12:37
  • OP: Since you accepted this answer, and it doesn't correspond to what you asked, which is about using read-string (interactively or not), please retitle and reword your question to better fit the answer. Thx. – Drew Jun 27 '22 at 18:40