Elisp snippets
Snippets
Execute command in shell buffer
comint-send-string
is the function we’re looking for.1
It takes a PROCESS
and a STRING
.
You can get the process from the shell buffer, and conveniently the shell function returns the buffer, so you can streamline it all into something like:
(defun my-server ()
"SSH to my.server.com in `shell' buffer."
(interactive)
(comint-send-string
(get-buffer-process (shell))
"ssh my.server.com\n"))
Where the (shell) call will take care of creating the shell buffer and/or process if necessary.2
Free variables
In some situations, for instance when setting a variable in a DOOM Emacs like
(setq my/variable "value")
You might get the warning
Warning: assignment to free variable `er/try-expand-list'
This is because set
and setq
do not declare lexical variables3.
The solution is to use4
(defvar my/variable "value")
Lists to arrays
List of lists
To convert a list of lists, e.g.
(defvar mylist (("1" "a") ("2" "b") ("3" "c")))
The method to convert a single element from the list is
(require 'cl)
(coerce (nth 0 mylist) 'vector)
;; ["1" "a"]
We now just need to map this for all the list
(mapcar (lambda (arg) (coerce arg 'vector)) mylist)
Lists conversion
To convert a vector
to list
:
(coerce [1 2 3] 'list)
;; (1 2 3)
and to convert a list
to vector
:
(coerce '(1 2 3) 'vector)
;; [1 2 3]
Reference
defcustom
You can specify variables using defcustom
so that you and others can then use Emacs’s customize
feature to set their values. (You cannot use customize
to write function definitions; but you can write defuns
in your .emacs
file. Indeed, you can write any Lisp expression in your .emacs~ file
.)5
Footnotes
SQLite
Emacs provides functionality to interact with SQLite databases. For these examples we will use the emacSQL package.
To open a database file /tmp/foo.sqlite
we issue:
(defvar db (emacsql-sqlite "~/tmp/foo.sqlite"))
We can then issue SELECT
statements with
;; Query the database for results:
(emacsql db [:select [name id]
:from people
:where (> salary 62000)])
;; => (("Susan" 1001))