I want to create a keyboard shortcut that will prompt me for a string and then open a new ansi-term buffer with that string as the buffer name. How would I do this?

1 Answer 1


To write-up this answer, I first typed C-h f ansi-term RET and saw that the *Help* buffer let me know that there are two possible arguments, one mandatory being PROGRAM, and the secondary optional being NEW-BUFFER-NAME. From there, I wrote the function my-ansi-term asking the user to input the new-buffer-name (if not provided programmatically), and to ask the user for the program name (if not provided programmatically) ... which will default to the same defaults that are included in the original function ansi-term if no program is specified. [This information was derived by typing M-x find-function RET ansi-term RET and reading the code.] I arbitrarily chose the keyboard shortcut of the f5 key. Inasmuch as the variable explicit-shell-file-name is not defined in Emacs 27 until the library term.el is loaded, I chose to define it with a nil value (which is the default value in the aforementioned library).

(defvar explicit-shell-file-name nil)

(defun my-ansi-term (&optional program new-buffer-name)
  (let ((program (if program
                     (read-string "PROGRAM:  " nil nil (or explicit-shell-file-name
                                                           (getenv "ESHELL")
        (new-buffer-name (if new-buffer-name
                             (read-string "NEW-BUFFER-NAME:  "))))
    (ansi-term program new-buffer-name)))

(global-set-key [f5] 'my-ansi-term)
  • When i input the buffer name "mybuffer" the resulting buffer name is "*mybuffer*". is there a way to remove the asterisks from the buffer name?
    – Andrew
    Jul 28, 2021 at 6:18
  • 1
    Yes, but that would involve a re-write of original function consisting of approximately 20 lines of code without the comments. In general, most forum participants frown upon rewriting built-in functions because they fear it will potentially incur too much maintenance if the developers modify the base code, and/or they view such modification as taboo / sacrilege. To re-write the function, just type M-x find-function RET ansi-term RET and copy the function and paste it over to your .emacs / init.el file and remove the asterisks ... perhaps defining explicit-shell-file-name beforehand.
    – lawlist
    Jul 28, 2021 at 6:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.