Skip to content

Instantly share code, notes, and snippets.

@jackrusher
Created April 28, 2017 14:25
Show Gist options
  • Save jackrusher/26be42a5a60d0372c872161d81114784 to your computer and use it in GitHub Desktop.
Save jackrusher/26be42a5a60d0372c872161d81114784 to your computer and use it in GitHub Desktop.
An example elisp function presented at Emacs Berlin
(defun giraffe ()
"Passes a the active region (highlighted text in non-emacs
speak) to an external command that produces an SVG graph of the
data, which is then placed in a buffer called *giraffe* and
viewed as an image."
;; Declare that this is an interactive command. Whenever a function
;; starts this way emacs will make it available to be called with
;; M-x or bound to a key.
(interactive)
;; If there's no region we can't do this, so raise an error
(unless (mark)
(user-error "The mark is not set now, so there is no region"))
;; (get-buffer-create "*whatever") will either get the buffer if it
;; exists or make a new buffer with name. The asterisks around the
;; name (called "earmuffs" in lisp slang) are used to indicate a
;; dynamic variable or -- in emacs -- a special buffer. We bind the
;; result to a let-scoped variable called giraffe-buffer.
(let ((giraffe-buffer (get-buffer-create "*giraffe*")))
;; the code inside this macro will be executed relative to giraffe-buffer
(with-current-buffer giraffe-buffer
;; We want to erase whatever might already be in the buffer
;; before inserting the result of calling the giraffe command
;; line program. However, buffers that are in image-mode are
;; read-only, so switch it to fundamental mode first, then erase.
(fundamental-mode)
(erase-buffer))
;; Execute a shell command on the characters whose indices in the
;; current buffer are the range described by the first and second
;; parameters, which we're getting from two functions that return
;; the beginning and end indices of the region. (Thus we want to
;; run the command on the whole region). The third parameter is
;; the name of the shell command to run, the fourth tells it to
;; which buffer the output should be written.
(shell-command-on-region (region-beginning)
(region-end)
"giraffe"
giraffe-buffer)
;; Set the giraffe-buffer to image-mode so we'll see the SVG
;; returned by the command as an image rather than as the XML text
;; of the SVG.
(with-current-buffer giraffe-buffer (image-mode))
;; Tell emacs to open another window showing the giraffe buffer so
;; we can see it!
(switch-to-buffer-other-window giraffe-buffer)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment