bashemacsansi-term

Sending bash commands to an open terminal buffer in emacs


I've been trying to improve my emacs life lately, and one thing I've done is make use of projectile and perspective to organize my buffers sensibly.

As part of this I wrote an elisp function to open up (or return to) a named ansi-term buffer that is project-specific. This allows me to quickly drop into a bash terminal for the project I'm currently looking at.

What I have been having trouble finding out after plumbing the interwebs is whether or not it is possible to send bash commands to an open ansi-term buffer from within emacs. Specifically, I'm trying to make sure the ansi-term buffer cds to the correct project root directory when it's first opened. This requires grabbing context from the projectile package first, so it's not something I can plop into my .bashrc.

Ideally I would be able to write an elisp function that:

1) selects an ansi-term buffer by name (since I can have one open with a unique name for every project)

2) sends and executes a command in that buffer

Is there any way to do this?

EDIT

Final solution for anyone who is interested:

(defun visit-project-term-buffer ()
  "Create or visit a terminal buffer."
  (interactive)
  (if (not (get-buffer (persp-ansi-buffer-name)))
  (progn
    (split-window-sensibly (selected-window))
    (other-window 1)
    (ansi-term (getenv "SHELL"))
    (rename-buffer (persp-ansi-buffer-name))
    (end-of-buffer)
    (insert (format "cd %s" (projectile-project-root)))
    (term-send-input))
(switch-to-buffer-other-window (persp-ansi-buffer-name))))

Solution

  • Does this work for you? It switches to a buffer named *terminal* and runs echo hello:

    (defun my-echo ()
      (interactive)
      (switch-to-buffer "*terminal*")
      (end-of-buffer)
      (insert "echo hello")
      (term-send-input))