This section provides Elisp snippets and examples about Emacs API to help developers find what they need quickly.
1.2 Strings 1.2.1 Concatenate strings> (concat "hello" " world") "hello world" > (concat "hello" " world" " elisp ") "hello world elisp " > (apply #'concat '("hello" " world " " elisp ")) "hello world elisp "1.2.2 Join Strings by Separator
(defun join (sep lst) (mapconcat 'identity lst sep)) ELISP> (join "," '("1.232" "300" "500")) "1.232,300,500" ELISP> (join ", " '("1.232" "300" "500")) "1.232, 300, 500"1.2.3 Split String
> (split-string "100,200,300,400" ",") ("100" "200" "300" "400") > (split-string (getenv "PATH") ":") ("/usr/local/sbin" "/usr/local/bin" "/usr/bin" ...)1.2.4 Split String with quotes
> (split-string-and-unquote "/bin/app -x -y -z \"/home/user/some name with space/etc\" -k cmd ") ("/bin/app" "-x" "-y" "-z" "/home/user/some name with space/etc" "-k" "cmd")1.2.5 Replace Strings 1.2.6 Regex 1.3 Text Manipulation 1.3.1 Text alignment
Source: Init file - www.svjatoslav.eu
(defun align-to-colon (begin end) "Align region to colon (:) signs" (interactive "r") (align-regexp begin end (rx (group (zero-or-more (syntax whitespace))) ":") 1 1 )) (defun align-to-comma (begin end) "Align region to comma signs" (interactive "r") (align-regexp begin end (rx "," (group (zero-or-more (syntax whitespace))) ) 1 1 )) (defun align-to-equals (begin end) "Align region to equal signs" (interactive "r") (align-regexp begin end (rx (group (zero-or-more (syntax whitespace))) "=") 1 1 )) (defun align-to-hash (begin end) "Align region to hash ( => ) signs" (interactive "r") (align-regexp begin end (rx (group (zero-or-more (syntax whitespace))) "=>") 1 1 )) (defun align-to-comma-before (begin end) "Align region to equal signs" (interactive "r") (align-regexp begin end (rx (group (zero-or-more (syntax whitespace))) ",") 1 1 ))1.3.2 Join Multiple Lines
From: jidaikobo-shibata/join-multi-lines-to-one.el
(defun join-multi-lines-to-one () "Join multi lines." (interactive) (let ((beg (region-beginning)) (end (region-end)) strings) (goto-char beg) (back-to-indentation) (setq beg (point)) (goto-char end) (goto-char (- (point) 1)) (end-of-line) (setq end (point)) (setq strings (buffer-substring-no-properties beg end)) (setq strings (replace-regexp-in-string "\n\\|^>+ *\\|^[\t ]+" " " strings)) (setq strings (replace-regexp-in-string " +" " " strings)) (delete-region beg end) (insert strings) (goto-char beg)))1.4 S-expressions 1.4.1 Parse s-expressions
> (read "(mapc (lambda (p) (insert p) (insert \"\n\")) (buffer-list)) ") (mapc (lambda (p) (insert p) (insert " ")) (buffer-list)) > (read "(+ 1 2 3 4)") (+ 1 2 3 4)1.4.2 Evaluate s-expressions
> (eval (read "(+ 1 2 3 4)" )) 10 > (eval '(+ 1 2 3 4)) 101.5 Clipboard (Kill-ring) elisp clipboard kill ring 1.5.1 Copy string to clipboard
(defun clipboard/set (astring) "Copy a string to clipboard" (with-temp-buffer (insert astring) (clipboard-kill-region (point-min) (point-max))))1.5.2 Paste string from clipboard
(defun clipboard/get () "Return the content of clipboard as string" (interactive) (with-temp-buffer (clipboard-yank) (buffer-substring-no-properties (point-min) (point-max))))1.5.3 Copy buffer file name to clibpoard
(defun buffer/copy-file-name () (interactive) (clipboard/set (buffer-file-name))) > (buffer/copy-file-name) nil > (insert (clipboard/get)) /home/arch/projects/emacs/Emacs_Snippets.org1.5.4 Copy buffer directory to clibpoard
(defun buffer/copy-path () (interactive) (clipboard/set (file-name-directory (buffer-file-name))) (message "Copied file path to clipboard")) > (buffer/copy-path) "Copied file path to clipboard" > (clipboard/get) "/home/arch/projects/emacs/"1.5.5 Copy buffer content to clipboard
(defun buffer/copy-content () "Copy buffer content to clibpoard Usage: M-x buffer/copy-content" (interactive) (clipboard/set (buffer-substring-no-properties (point-min) (point-max) )))1.6 Elisp 1.6.1 Load an Elisp file
Load an elisp source file *.el.
(load-file "~/.emacs.d/tools.el")
Load an byte-compiled (*.elc) elisp file.
(load-file "~/.emacs.d/tools.elc")1.6.2 Load all elisp files of a directory
(defun load-dir (path) " Load all elisp files (*.el) of a directory Usage: (load-dir <path>) Example: (load-dir \"~/.emacs.d/custom\") " (mapc #'load (directory-files path t "\\.el$")))1.6.3 Add directory to load path
It adds a directory containing Emacs packages (<package name>.el) to the load path. The user can load packages by adding the code (require '<package>)
to the file init.el.
(add-to-list 'load-path "~/.emacs.d/custom") (require 'package)1.6.4 Switch and Create the Scratch Buffer
This function switches and crates the scratch buffer if it doesn't exist or was deleted. Usage: M-x scratch.
(defun scratch () " Switches to scratch buffer and creates it if it doesn't exist. Usage: M-x scratch This function is useful to Elisp developers. Suggestion: Add (defalias 's #'scratch) to the init file. You can switch to the scratch buffer with > M-x s " (interactive) (let ((buf (get-buffer-create "*scratch*"))) (switch-to-buffer buf) (lisp-interaction-mode) )) (defalias 's #'scratch)1.6.5 Eval String in Clipboard
It only works on Linux and requires Xclip to be installed, but with a few changes can be tweaked to work in another Os.
ELISP> (defun eval-string (str) (eval (read str))) eval-string ELISP> (defun eval-xclip () (eval-string (shell-command-to-string "xclip -o"))) eval-xclip ELISP> (eval-xclip) "Loading my copypaste file..." ELISP>1.6.6 Extract Function Documentation elisp
Source: Generate emacs-lisp documentation Primitives:
ELISP> ELISP> (defun sample-function (a b c) "Function Docstring" (+ a (* 5 b) (* 3 c))) ELISP> (documentation 'sample-function) "Function Docstring" ELISP> (symbol-function 'sample-function) (lambda (a b c) "Function Docstring" (+ a (* 5 b) (* 3 c))) ELISP> (help-function-arglist 'sample-function) (a b c)
Final Code
(fun2org 'sample-function) "** sample-function (a b c)\nFunction Docstring\n\n#+BEGIN_SRC emacs-lisp\n(lambda (a b c) \"Function Docstring\" (+ a (* 5 b) (* 3 c)))\n#+END_SRC\n" ELISP> ELISP> (defun fun2org (function-symbol) (let ((args (help-function-arglist function-symbol)) (doc (documentation function-symbol)) (code (symbol-function function-symbol))) (print (format "** %s %s %s #+BEGIN_SRC emacs-lisp %S " function-symbol args doc code))))
ELISP> (fun2org 'sample-function) "** sample-function (a b c) Function Docstring (lambda (a b c) \"Function Docstring\" (+ a (* 5 b) (* 3 c))) "1.6.7 Describe function
(describe-function 'find-file-noselect)1.7 Common Lisp Emulation Library 1.7.1 Reduce (fold left) function
(require 'cl) ELISP> (cl-reduce (lambda (acc x) (+ (* 10 acc) x)) '(1 2 3 4 5 6) :initial-value 0) 123456 (#o361100, #x1e240)
(require 'cl) ELISP> (cl-reduce (lambda (acc x) (and acc x)) '(t nil t t t f) :initial-value t) nil ELISP> (cl-reduce (lambda (acc x) (and acc x)) '(t t t t t f) :initial-value t) f ELISP> (cl-reduce (lambda (acc x) (and acc x)) '(t t t t t t) :initial-value t) t (defun all-p (bool-list) "Tests if all values of bool-list are true (not nil)" (cl-reduce (lambda (acc x) (and acc x)) bool-list :initial-value t)) ELISP> (all-p '(t t t)) t ELISP> (all-p '(t nil t)) nil
ELISP> (cl-reduce (lambda (acc x) (and acc x)) '(t t t t t t) :initial-value t) t ELISP> (cl-reduce (lambda (acc x) (or acc x)) '(t t t t t t) :initial-value nil) t ELISP> (cl-reduce (lambda (acc x) (or acc x)) '(nil nil nil t t nil) :initial-value nil) t ELISP> (cl-reduce (lambda (acc x) (or acc x)) '(nil nil nil nil nil nil) :initial-value nil) nil ELISP> () (defun some-p (bool-list) "Tests if at least one value bool-list is true (not nil)" (cl-reduce (lambda (acc x) (or acc x)) bool-list :initial-value nil)) ELISP> (some-p '(t t t t)) t ELISP> (some-p '(nil t nil nil)) t ELISP> (some-p '(nil nil nil nil)) nil
(kill-buffer <buffer-object or buffer-name>)
Example: Delete buffer named Elisp_Snippets.org
(kill-buffer "Elisp_Snippets.org")
Example: Delete all buffers:
(mapc #'kill-buffer (buffer-list))1.8.3 Get buffer content as string
Returns the content of a buffer referencend by its name or the buffer object.
(defun buffer-content (&optional buffer-or-name) (with-current-buffer (if buffer-or-name buffer-or-name (current-buffer)) (buffer-substring-no-properties (point-min) (point-max) )))1.8.4 Get selected text as string
Returns the selected text of the current buffer.
(defun get-selection () "Get the text selected in current buffer as string" (interactive) (buffer-substring-no-properties (region-beginning) (region-end)))1.8.5 Create a scratch buffer for Programming Languages
This function creates a Python scratch buffer like elisp *scratch*
which allows the user to play with Python without creating any file. It is possible to run
It can be easily changed to work with other languages like ruby by replacing python-mode to ruby-mode.
Python Scratch buffer
Usage: M-x python/scratch
(defun python/scratch () (interactive) (let ( (buf (get-buffer-create "*python-scratch*")) ) (with-current-buffer buf (python-mode) (pop-to-buffer buf) )))
Shell (bash, sh) scratch buffer
Usage: M-x sh/scratch
(defun sh/scratch () (interactive) (let ( (buf (get-buffer-create "*sh-scratch*")) ) (with-current-buffer buf (sh-mode) (pop-to-buffer buf) )))1.8.6 Get all buffer's local variables
Get all current buffer's local variables
Output:
((cursor-type . bar) (buffer-display-time 22711 20278 987330 737000) (buffer-display-count . 4) (buffer-invisibility-spec (org-babel-hide-hash . t) (org-babel-hide-hash . t) (org-babel-hide-hash . t) (org-babel-hide-hash . t) (org-babel-hide-result . t) (org-hide-block . t) (org-cwidth) (org-link) (outline . t) t) (buffer-file-truename . "~/Documents/projects/emacs/Elisp_Snippets.org") (point-before-scroll) (buffer-auto-save-file-format . t) (buffer-file-format) (buffer-file-coding-system . utf-8-unix) (enable-multibyte-characters . t) (mark-active) (overwrite-mode) ...)
Get all local variables of a buffer.
(buffer-local-variables <buffer-name>)1.8.7 Get a specific buffer local variable
(buffer-local-value VARIABLE BUFFER)
Get current buffer major-mode:
> (buffer-local-value 'major-mode (current-buffer)) org-mode1.8.8 Append buffer content to file
Function append to file: Append buffer's region content to file.
(append-to-file <point-min> <point-max> <file-name>)
Append current buffer content to file. If the file doesn't exist, it will be created. Otherwise the buffer content will be appended to the end of the file.
(append-to-file (point-min) (point-max) "/tmp/afile.txt")
Append a specific buffer content to file.
(with-current-buffer "my-buffer-name" (append-to-file (point-min) (point-max) "/tmp/afile.txt"))1.8.9 Write file with buffer content (overwrite file it exists)
(if (file-exists-p filename) (delete-file file)) (append-to-file (point-min) (point-max) filename))1.8.10 Revert / update buffer without asking to confirm 1.9 IO - Input and Output 1.9.1 Input - Read User Input
> (read-string "prompt > ") "user enter some string in minibuffer"
Ask the user for a string and insert in the buffer
> (insert (concat "\n" (read-string " prompt > " ))) user enter a message in the minibuffer
Reads a file name from the user and gives auto completion. Enter tab to autocomplete the file name.
> (read-file-name "Enter a file name: ") "/etc/fstab"
Opens a prompt that asks for the path in the minibuffer with completion and inserts the path at the current point.
(defun insert-path () " Opens a prompt that asks for the path in the minibuffer with completion and inserts the path at the current point. Usage: M-x insert-path " (interactive) (insert (read-file-name "file > ")))
> (read-directory-name "Enter a directory: ") "/var/log"
Display a message at the bottom of the screen.
(message "A message to the user")
Display a message, in a dialog box if possible. If a dialog box is not available, use the echo area.
(message-box "Emacs Alert. Time to drink a coffee!")
Show a tooltip
(tooltip-show "An Emacs tooltip")
[C-h-f] <name of function>
In order to Emacs find where applications such as ruby shell, scala compiler and tools are installed it is necessary to the PATH environment variable contain the path to the directories which contains those applications.
Copy this command below to the scratch buffer and enter M-x eval-print-last-last-sexp.
(getenv "PATH") "/home/archbox/opt/scala/bin:/usr/bin:/bin: ..."
(defun show-path-variable () (interactive) (switch-to-buffer (get-buffer-create "*path-variable*")) (delete-region (point-min) (point-max)) (save-excursion (mapc (lambda (p) (insert (concat p "\n"))) (split-string (getenv "PATH") (if (equal system-type 'windows/nt) ";" ":" )))))
By running this command M-x show-path-varible it will print all paths in the $PATH variable in a new buffer a easy way to read:
/home/archbox/opt/scala-2.11.8/bin /home/archbox/opt/jdk1.8.0_74/bin/ /usr/local/sbin /usr/local/bin /usr/bin /usr/lib/jvm/default/bin /usr/bin/site_perl /usr/bin/vendor_perl /usr/bin/core_perl /home/archbox/opt/java/bin /home/archbox/opt/scala-2.11.8/bin/
It will add the directory: ~/opt/scala/bin to the $PATH variable. Before run the code below when the user runs M-x async-shell-command
scala it will shows an error message like this:
/bin/bash: scala: command not found
Note: The character ':' is the separator for Unix-like OS (Linux/ BSD and OSX) and ';' is the separator for Windows.
(setenv "PATH" (concat (expand-file-name "~/opt/scala/bin") ":" (getenv "PATH"))) (setenv "PATH" (concat (expand-file-name "~/opt/scala/bin") ":" (expand-file-name "~/opt/jdk1.8.0_20/bin/") ":" "/Applications/haste-compiler/bin/" ":" (getenv "PATH")))
After it is done the Scala REPL will look like the picture below:
Figure 4: Scala in PATH variable.
(defun add-to-path-var (&rest pathlist) (let* ((path-sep (if (equal system-type 'windows/nt) ";" ":" ))) (setenv "PATH" (concat (apply #'concat (mapcar (lambda (path) (concat (expand-file-name path) path-sep)) pathlist)) (getenv "PATH")))))
Usage example:
(add-to-path-var "~/opt/scala/bin" "~/opt/jdk1.8.0_20/bin/")
Alternative way:
Use the function locally without pollute the namespace.
(require 'cl) (cl-flet ((add-to-path-var (&rest pathlist) (let* ((path-sep (if (equal system-type 'windows/nt) ";" ":" ))) (setenv "PATH" (concat (apply #'concat (mapcar (lambda (path) (concat (expand-file-name path) path-sep)) pathlist)) (getenv "PATH")))))) (add-to-path-var "~/opt/scala/bin" "~/opt/jdk1.8.0_20/bin/" ))
(shell-command "uname -a")
Display PCI cards in another frame.
(with-selected-frame (make-frame) (shell-command "lspci"))
> (shell-command-to-string "uname -a") "Linux localhost 4.7.0-1-ARCH #1 SMP PREEMPT Mon Aug 8 22:05:58 CEST 2016 x86_64 GNU/Linux " > (insert (format "\nKernel version %s " (shell-command-to-string "uname -r"))) Kernel version 4.7.0-1-ARCH nil (defun insert-debug-info () (interactive) (insert (concat "Kernel version : ") (shell-command-to-string "uname -r")) (insert (concat "Linux distribution : ") (shell-command-to-string "cat /etc/issue")) (insert (concat "Gcc version :") (shell-command-to-string "gcc --version | grep GCC")) ) Kernel version : 4.7.0-1-ARCH Linux distribution : Arch Linux \r (\l) Gcc version :gcc (GCC) 6.1.1 20160802
The function shell-command-to-lines runs a shell command and returns the output lines. This function is useful to create shell command wrappers over Unix shell commands like find.
(defun shell-command-to-lines (command) (remove-if-not (lambda (s) (/= (length s) 0)) (split-string (shell-command-to-string command) "\n"))) ELISP> (mapc #'princ (shell-command-to-lines "ls /var/log")) btmpfailloghttpdjournallastlogoldpacman.logsambaspeech-dispatcherwtmpXorg.0.logXorg.0.log.old ("btmp" "faillog" "httpd" "journal" "lastlog" "old" "pacman.log" "samba" "speech-dispatcher" "wtmp" "Xorg.0.log" "Xorg.0.log.old") ELISP> (mapc (lambda (p) (princ p) (princ "\n")) (shell-command-to-lines "ls /var/log")) btmp faillog httpd journal lastlog old pacman.log samba speech-dispatcher wtmp Xorg.0.log Xorg.0.log.old
Example: Shell command wrapper find
ELISP> (mapc (lambda (p) (princ p) (princ "\n")) (shell-command-to-lines "find ~/.local/share/ -name \"*.desktop\"")) /home/arch/.local/share/xfce4/helpers/custom-WebBrowser.desktop /home/arch/.local/share/applications/userapp-mono-IAJQMY.desktop /home/arch/.local/share/applications/userapp-sh-9VFBMY.desktop /home/arch/.local/share/applications/userapp-em-FLD8LY.desktop /home/arch/.local/share/applications/userapp-mpv-FLQ9LY.desktop /home/arch/.local/share/applications/userapp-Firefox-SOBHMY.desktop (defun search-files (directory pattern) (shell-command-to-lines (format "find %s -name '%s'" directory pattern))) ELISP> (search-files "~/.local" "*.desktop") ("/home/arch/.local/share/xfce4/helpers/custom-WebBrowser.desktop" "/home/arch/.local/share/applications/userapp-mono-IAJQMY.desktop" "/home/arch/.local/share/applications/userapp-sh-9VFBMY.desktop" "/home/arch/.local/share/applications/userapp-em-FLD8LY.desktop" ... ) ELISP> (mapc (lambda (p) (princ p) (princ "\n")) (search-files "~/.local" "*.desktop")) /home/arch/.local/share/xfce4/helpers/custom-WebBrowser.desktop /home/arch/.local/share/applications/userapp-mono-IAJQMY.desktop /home/arch/.local/share/applications/userapp-sh-9VFBMY.desktop /home/arch/.local/share/applications/userapp-em-FLD8LY.desktop /home/arch/.local/share/applications/userapp-mpv-FLQ9LY.desktop /home/arch/.local/share/applications/userapp-Firefox-SOBHMY.desktop
Pipes the buffer content to external command and print the output in the buffer *Shell Command Output*
. The command $ wc -l
counts the number of line of the current file.
> (shell-command-on-region (point-min) (point-max) "wc -l")
Pipes the buffer content to external command $wc -l
and get the output as a string.
> (with-output-to-string (shell-command-on-region (point-min) (point-max) "wc -l")) "" (defun pipe-region-to-command (pmin pmax command) (interactive) (shell-command-on-region pmin pmax command "*shell-output*") (let ((output (with-current-buffer "*shell-output*" (buffer-substring-no-properties (point-min) (point-max))))) (kill-buffer "*shell-output*") output )) > (pipe-region-to-command (point-min) (point-max) "wc -l") "1515 "
The command below will pipe the buffer *scratch*
to the command =$ sed 's/foo.*/bar/g'= which replaces all values of foo for bar.
(with-current-buffer "*scratch*" (shell-command-on-region (point-min) (point-max) "sed 's/foo.*/bar/g'" "*shell-output*" t ))
Before the form evaluation
After the form evaluation.
Usage: M-x shell-command-on-buffer Enter: sed 's/defun/defn/g' eplaces all defun words by defn.
(defun shell-command-on-buffer (&optional command) "Apply a shell command in the current buffer and replace it by the command output. Example: - Interactive usage: M-x shell-command-on-buffer Enter: sed 's/defun/defn/g'. replaces all defun words by defn. - (shell-command-on-buffer \"sed 's/defun/defn/g'\")" (interactive) (shell-command-on-region (point-min) (point-max) (if command command (read-string "Cmd on buffer: ")) "*shell-output*" t ))
Enter M-x shell-command-on-buffer and then $ ruby -ne 'printf("-%6s%s", $., $_)'
ruby -ne 'printf("-%6s%s", $., $_)'
Before running the command:
After running the command:
This function applies a ruby batch command on the buffer.
See also: Ruby One-Liners
(defun ruby-on-buffer (&optional command) "Applies a ruby command on buffer Example: The command will number each line of the current buffer. 1. M-x ruby-on-buffer 2. type: 'printf(\"%6s%s\", $., $_)' without quotes." (interactive) (shell-command-on-buffer (format "ruby -ne '%s'" (if command command (read-string "ruby cmd >")))))
Emacs regexp islimited and doesn't have lookahead like perl or ruby regex. This command can extend the functionality of Emacs regex using ruby. This function applies a ruby regex on the buffer.
Usage: M-x ruby-gsub-on-buffer
See also: Ruby One-Liners
(defun ruby-gsub-on-buffer (&optional regexp) "Applies ruby regex, the command $ ruby -pe 'gsub(regexp)' on the current buffer. Usage M-x ruby-gsub-on-buffer (ruby-gsub-on-buffer <regexp>) Example: The Command replace all occurrences of 'defun' by 'defn'. 1. M-x ruby-gsub-on-buffer 2. Type /defun/,\"defn\"" (interactive) (shell-regexp-on-buffer (format "ruby -pe 'gsub(%s)'" (if regexp regexp (read-string "ruby regex: ")))))
Refactoring to a self-contained-code, removing all dependencies.
Example: To remove all numbers in at beggining of line run:
M-x replace-regex-ruby /^\d\d?/,""
(defun replace-regexp-ruby (&optional regexp) "Replace ruby-gsub on buffer same as replace-regexp, but with ruby regex. Usage M-x ruby-gsub-on-buffer (ruby-gsub-on-buffer <regexp>) Example: The Command replace all occurrences of 'defun' by 'defn'. 1. M-x ruby-gsub-on-buffer 2. Type /defun/,\"defn\"" (interactive) (shell-command-on-region (point-min) (point-max) (format "ruby -pe 'gsub(%s)'" (if regexp regexp (read-string "ruby regex: "))) "*shell-output*" t ))
(start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS
Usage: M-x ping-host or (ping-host <hostname>)
(defun ping-host (&optional hostname) "Ping a hostname. Usage: - Interactive: M-x ping-host - Command: (ping-host <hostname>) Examples: (ping-host \"www.google.com\") (ping-host \"192.168.0.1\")" (interactive) (let ((hostname- (if hostname hostname (read-string "host to ping: ")))) (start-process "ping" "*ping*" "ping" hostname-) (switch-to-buffer-other-frame "*ping*")))
(defun traceroute-host (&optional hostname) "Run traceroute command to test connection. Usage: - Interactive: M-x traceroute-host [Enter the hostname] - Command: (traceroute-host <hostname>) Example: (traceroute-host \"www.yahoo.co.uk\")." (interactive) (let ((hostname- (if hostname hostname (read-string "host to traceroute: ")))) (start-process "traceroute" "*traceroute*" "traceroute" hostname-) (switch-to-buffer-other-frame "*traceroute*")))
Run linux htop (task manager) inside Emacs:
1.10.8 Run apps in external terminal emulator terminal shell os commandSome Linux ncurses-based applications like Htop, Top, Nmtui (Network Manager's terminal UI) doesn't work well running in Emacs terminal emulator M-x term
or M-x ansi-term
. The solution is run the command from Emacs and send to an external terminal emulator.
Read a command in launch in terminal
This command uses xfce4-terminal but it can be changed to any other terminal emulator.
(defun run-terminal () "Launch application in a terminal emulator." (interactive) (start-process "termx" nil "xfce4-terminal" "-e" (read-shell-command "Shell: ")))
Launch specific commands
(defun shell-command-in-terminal (command) (start-process "termx" nil "xfce4-terminal" "-e" command))
To launch htop:
(shell-command-in-terminal "htop")
To launch nmtui:
(shell-command-in-terminal "nmtui")
Command M-x htop
to launch htop.
(defun htop () "Launch htop task manager." (interactive) (shell-command-in-terminal "htop"))1.10.9 Launch applicatiosn from Emacs
This command asks the user a shell command providing tab completion and launches an asynchronous process (it doesn't freeze Emacs). Unlike asynchronous-shell-command this command doesn't create a new buffer. It is useful to launch desktop GUI applications from Emacs like Firefox, terminal emulator, file mangers and so on.
Note: In order to this command find the app the directory of the app must be in the $PATH variable.
(defun shell-launch () "Launch a process without creating a buffer. It is useful to launch apps from Emacs." (interactive) (let* ((cmd-raw (read-shell-command "Launch command: ")) (cmd-args (split-string-and-unquote cmd-raw)) (cmd (car cmd-args)) (args (cdr cmd-args))) (apply #'start-process `(,cmd nil ,cmd ,@args ))))
This comamnd can be bound to a keybiding with the code bellow that bidns the key combination SUPER (Windows Key) + 8.
(global-set-key (kbd "s-8") #'shell-launch)1.10.10 Send regions, commands and buffer to M-x shell repl.
(defun shell/buffer-repl () "Create " (interactive) (delete-other-windows) (split-window-right) (shell) (let ((buf (get-buffer-create "*shell-buffer*"))) (with-current-buffer buf (sh-mode) (pop-to-buffer buf)))) (defun shell/buffer-repl-frame () (interactive) (with-selected-frame (make-frame) (shell/buffer-repl)))
This functions are useful to send regions, lines and regions to M-x shell
repl from a shell-buffer or shell scratch buffer to the repl.
(defun shell/send-region () "Send selected text to M-x shell repl." (interactive) (comint-send-region (get-buffer-process "*shell*" ) (region-beginning) (region-end)) (comint-send-string (get-buffer-process "*shell*" ) "\n")) (defun shell/insert-region () "Insert selected text into M-x shell repl and run it." (interactive) (let ((text (buffer-substring-no-properties (region-beginning) (region-end) ))) (with-current-buffer "*shell*" (insert text) (comint-send-input) ))) (defun shell/send-line () "Send current line to M-x shell repl." (interactive) (comint-send-region (get-buffer-process "*shell*") (line-beginning-position) (line-end-position) ) (comint-send-string (get-buffer-process "*shell*" ) "\n")) (defun shell/insert-line () "Insert current line to M-x shell repl." (interactive) (let ((line (buffer-substring-no-properties (line-beginning-position) (line-end-position) ))) (with-current-buffer "*shell*" (insert line) (comint-send-input) ))) (defun shell/execute-line () "Execute current line as shell command." (interactive) (shell-command (buffer-substring (line-beginning-position) (line-end-position)))) (defun shell/execute-region () "Execute current region as shell command." (interactive) (shell-command (buffer-substring (region-beginning) (region-end)))) (defun shell/insert-buffer () "Insert all buffer content into M-x shell repl and run it." (interactive) (let ((text (buffer-substring-no-properties (point-min) (point-max) ))) (with-current-buffer "*shell*" (insert text) (comint-send-input) )))
Example:
Figure 13: Example of M-x shell/buffer-repl-frame.
Figure 14: Demonstration of M-x shell/buffer-repl-frame and shell/insert-region
1.11 Compilation compile tool building shell process 1.11.1 Enhanced Compilation CommandThis command is similar to emacs M-x compile, however it expands '%f' to the buffer file name, '%n' to buffer base name and '%d' to buffer directory.
Example: if the current buffer is associated to the file /home/arch/scripts/gui1.scala and the user types the command M-x compile2 followed by the command below.
$ scalac %f -d app-%n.jar && scala app-%n.jar
Emacs will run M-x compile with:
$ scalac gui1.scala -d app-gui1.jar && scala scala app-gui1.jar
The advantage of this command is that user doesn't need to type the file name to be compiled.
(setq compile2-command-history "") (defun compile2 () "Enhanced compilation command. - %f - is expanded to current buffer file name. - %d - is expanded to current buffer current directory. - %n - is expanded to current buffer base name. Example: if the current buffer is associated to the file. - /home/arch/scripts/gui1.scala If the user enter the command: $ scalac %f -d app-%n.jar && scala app-%n.jar It will run M-x compile with: $ scalac gui1.scala -d app-gui1.jar && scala scala app-gui1.jar" (interactive) (let* ((file (buffer-file-name)) (cmd (read-shell-command "cmd> " compile2-command-history)) (cmd1 (replace-regexp-in-string "%f" (file-name-nondirectory file) cmd)) (cmd2 (replace-regexp-in-string "%n" (file-name-base file) cmd1)) (cmd3 (replace-regexp-in-string "%d" (file-name-directory file) cmd2))) (setq compile2-command-history cmd) (save-buffer) (compile cmd3)))1.11.2 Compile a single c++ file related to current buffer and run it.
Usage: When the user run the command M-x cpp/compile-run-buffer at the current buffer (file code1.cpp) it will compile and run this file running the command $ g++ code1.cpp -o code1.bin && ./code1.bin
.
(defun cpp/compile-run-buffer () "Compile and run current c++ buffer (single-file C++ code). Usage: By running M-x cpp/compile-buffer-run at current buffer (file code1.cpp) will run $ g++ code1.cpp -o code1.bin && ./code1.bin" (interactive) (let* ((file-name (file-name-nondirectory (buffer-file-name))) (output (concat (file-name-base file-name) ".bin"))) (save-buffer) (compile (format "g++ %s -o %s && ./%s" file-name output output ))))1.11.3 Compile and run a single c++ file at point in dired mode
Usage: In dired mode mode, place the cursor at the file to be compiled and run M-x cpp/compile-run-dired.
(defun cpp/compile-run-dired () "Compile single c++ file at point in dired mode. Usage: Position the cursor at the file to be compiled and run M-x cpp/compile-dired." (interactive) (let* ((file-name (file-name-nondirectory (dired-file-name-at-point))) (output (concat (file-name-base file-name) ".bin"))) (save-buffer) (compile (format "g++ %s -o %s && ./%s" file-name output output ))))1.12 File 1.12.1 Test if file or directory exists
> (file-exists-p "/var/log/pacman.log") t > (file-exists-p "/var/log/pcaman.log.err") nil > (file-exists-p "/var/log") t > (file-exists-p "/var/log-dont-exists") nil1.12.2 Expand file name
ELISP> (expand-file-name "~") "/home/arch" ELISP> (expand-file-name "~/.emacs.d/init.el") "/home/arch/.emacs.d/init.el" ELISP> (expand-file-name ".") "/home/arch/projects/emacs"1.12.3 Read file to string
The Emacs API doesn't provide a straightforward way to read file directly to a string. The only way to perform this taks is using a temporary buffer.
(defun read-file (filename) (with-temp-buffer (insert-file-contents filename) (buffer-substring-no-properties (point-min) (point-max)))) ELISP> (read-file "/etc/host.conf") "#\n# /etc/host.conf\n#\n\norder hosts,bind\nmulti on\n\n# End of file\n" ELISP> (princ (read-file "/etc/host.conf")) # # /etc/host.conf # order hosts,bind multi on # End of file1.12.4 Open file to edit
> (find-file "/etc/fstab")
(find-file-other-window "/etc/fstab")
(find-file-other-frame "/etc/fstab")
Function: find-file-nonselect
Emacs Documentation: Read file FILENAME into a buffer and return the buffer.If a buffer exists visiting FILENAME, return that one, but verify that the file has not changed since visited or saved. The buffer is not selected, just returned to the caller.
Open a file and returns a buffer:
> (setq b1 (find-file-noselect "~/.bashrc")) #<buffer .bashrc> > b1 #<buffer .bashrc>1.12.6 Edit File as Root utils edit
(defun open-as-root (filename) (interactive) (find-file (concat "/sudo:root@localhost:" filename))) (defun open-buffer-as-root () (interactive) (let ( (filename (buffer-file-name (current-buffer))) (bufname (buffer-name (current-buffer))) ) (progn (kill-buffer bufname) (open-as-root filename))))1.13 File Name Manipulation 1.13.1 Get absolute path to current buffer's file.
ELISP> (buffer-file-name) "/home/archbox/.emacs.d/init.el" ELISP>1.13.2 File name without path
ELISP> (file-name-nondirectory "/home/archbox/.emacs.d/init.el") "init.el" ELISP>1.13.3 File name to base name
Transform file name to name without path and extension.
ELISP> (file-name-base "/home/archbox/.emacs.d/init.el") "init" ELISP>1.13.4 Get file's path
Get the directory that contais a file.
ELISP> (file-name-directory "/home/archbox/.emacs.d/init.el") "/home/archbox/.emacs.d/" ELISP>1.13.5 Expand file name
ELISP> (expand-file-name ".") "/home/archbox/.emacs.d" ELISP> (expand-file-name "./init.el") "/home/archbox/.emacs.d/init.el" ELISP> ELISP> (expand-file-name "~") "/home/archbox" ELISP> (expand-file-name "~/.bashrc") "/home/archbox/.bashrc" ELISP>1.13.6 Replace file extension
Example: It will replace the extension of file name init.el to init.py. Note: it will not modify the file.
ELISP> (let ((file "/home/archbox/.emacs.d/init.el")) (concat (file-name-directory file) (file-name-base file) ".py" )) "/home/archbox/.emacs.d/init.py" ELISP>
or
(defun file-replace-extension (ext file) (concat (file-name-directory file) (file-name-base file) ext )) ELISP> (file-replace-extension ".py" "/home/archbox/.emacs.d/init.el") "/home/archbox/.emacs.d/init.py" ELISP>1.14 Directory directory 1.14.1 Open directory
(dired-other-window "/var/log")
(dired-other-frame "/var/log")
Get directory content
ELISP> (directory-files "/var/log") ("." ".." "Xorg.0.log" "Xorg.0.log.old" ... )
Print the directory content in elisp shell IEML.
ELISP> (mapc #'(lambda (p) (princ (concat "\n" p))) (directory-files "/var/log") ) . .. Xorg.0.log Xorg.0.log.old btmp faillog httpd journal lastlog old pacman.log samba speech-dispatcher wtmp
Get directory content with absolute file name.
ELISP> (directory-files "/var/log" t) ("/var/log/." "/var/log/.." "/var/log/Xorg.0.log" "/var/log/Xorg.0.log.old" ... ) ELISP> (mapc #'(lambda (p) (princ (concat "\n" p))) (directory-files "/var/log" t )) /var/log/. /var/log/.. /var/log/Xorg.0.log /var/log/Xorg.0.log.old /var/log/btmp ...
List files of a specific extension:
ELISP> (directory-files "/etc/" nil "\\.conf") ("asound.conf" "dhcpcd.conf" "fuse.conf" "gai.conf" ...) ELISP> (directory-files "/etc/" t "\\.conf") ("/etc/asound.conf" "/etc/dhcpcd.conf" "/etc/fuse.conf" ...) ELISP> (directory-files "/etc/" t "\\.cfg") ("/etc/rc_maps.cfg" "/etc/vdpau_wrapper.cfg") ELISP> (directory-files "/etc/" nil "\\.cfg") ("rc_maps.cfg" "vdpau_wrapper.cfg")1.15 Dired mode snippets directory dired 1.15.2 Copy path of file at point
(defun dired-copy-path () "In dired, copy file path to kill-buffer. At 2nd time it copy current directory to kill-buffer." (interactive) (let (path) (setq path (dired-file-name-at-point)) (if (string= path (current-kill 0 1)) (setq path (dired-current-directory))) (message path) (kill-new path)))1.15.3 Paste a file from clibpboard
This command pastes a file which path is stored in clibpoard.
Usage:
(defun dired-paste-file-from-clipboard () "Paste a file from clpboard to current directory." (interactive) (flet ((clipboard-get () (with-temp-buffer (clipboard-yank) (buffer-substring-no-properties (point-min) (point-max))))) (copy-file (clipboard-get) ".") (revert-buffer)))1.15.4 Create empty file (touch)
(defun dired-touch () "Creates empty file at current directory." (interactive) (append-to-file "" nil (read-string "New file: ")) (if (equal major-mode 'dired-mode) (revert-buffer)))1.15.5 Open multiple marked files
(defun dired-open-files (files) "Open all marked files in dired mode with m. Usage: 1. Mark the files with m 2. M-x dired-open-files" (interactive (list (dired-get-marked-files)) ) (mapc #'find-file files))1.15.6 Close multiple marked files
(setq lexical-binding t) (defun compose (fn1 fn2) (let ((lexical-binding t)) (lambda (x) (funcall fn2 (funcall fn1 x))))) (defun dired-close-files (files) (interactive (list (dired-get-marked-files)) ) (mapc (compose #'get-file-buffer #'kill-buffer) files))1.15.7 Open a file with default system application dired file open system
Usage. Select a file in dired mode and enter M-x dired-xdg
Function: xdg-open. Open any file with system's default application.
(defun xdg-open (filename) "Open a file FILENAME with default system application. This function is operating system independent." (cl-case system-type (gnu/linux (let ((process-connection-type nil)) (start-process "proc" nil "xdg-open" (expand-file-name filename)))) (gnu/kfreebsd (let ((process-connection-type nil)) (start-process "proc" nil "xdg-open" (expand-file-name filename)))) (darwing (start-process "proc" nil "open" (concat (expand-file-name filename)))) (windows-nt (start-process "proc" nil "cmd" "/C" "start" "" (expand-file-name filename) ))))
Function: dired-xdg
(defun dired-xdg () "Open file at point with systems' default app. Usage: In the dired mode select a file and type M-x dired-xdg to execute the file with the system default app. " (interactive) (with-current-buffer (xdg-open (dired-get-filename))))1.15.8 Close all dired buffers
(defun dired-close-all () "Close all dired buffers." (interactive) (mapc (lambda (buf) (if (equal (buffer-local-value 'major-mode buf) 'dired-mode) (kill-buffer buf))) (buffer-list)))1.15.9 Browse bookmarked directories dired directory helm browse
The function M-x dired-bookmarks
opens a helm menu where the user can select its favorites directories. It provides quick directory navigation.
(defvar dired-bookmarks-path-list '("~" "~/Desktop" "~/Downloads" "~/Documents" "~/Documents/projects" "~/Documents/wiki" "/tmp" "/var/log" "/etc" "/etc/init.d" "~/.config" "~/.local" "~/.local/share" "~/.emacs.d" )) (defun dired-bookmarks () "Open a directory by selecting it in Helm menu." (interactive) (helm :prompt "Bookmarks: " :sources `(( (name . "Bookmark: ") (candidates . dired-bookmarks-path-list) (action . dired) ))))1.15.10 Filter dired buffer by file extensions
Usage:
(defun dired/filter-extension () "Filter dired buffer by file extensions. Usage: 1. M-x dired/filter-extension 2. Enter the file extensions separated by space like: exe dll It will only show files ending with extensions *.exe and *.dll. To show all files of dired buffer again type 'g'." (interactive) (dired-mark-files-regexp (mapconcat 'identity (mapcar (lambda (ext) (format "\\.%s$" ext)) (split-string (read-string "Extension: "))) "\\\|" )) (dired-toggle-marks) (dired-do-kill-lines))
The key (') quote can be used to invoke this command:
(define-key dired-mode-map "'" #'dired/filter-extension)1.15.11 Filter dired buffer by regex
This command only displays files matching the given regex (Emacs' regex).
Example: By entering M-x dired/filter '\.pdf$' without quotes it will only show file names ending with .pdf. To display all files again type 'g'.
(defun dired/filter () "Show only files which name matches a regex." (interactive) (dired-mark-files-regexp (read-regexp "Regex: ")) (dired-toggle-marks) (dired-do-kill-lines))1.15.12 Open directory at point with Microsoft Explorer in Windows OS.
(defun dired-exec-explorer () "In dired, execute Explorer" (interactive) (let (path) (setq path (dired-file-name-at-point)) (setq path (replace-regexp-in-string "~" "c:/home" path)) (setq path (replace-regexp-in-string "/" "\\\\" path)) (message path) (start-process "explorer" nil "explorer" (concat "/select," path))))1.16 Date Time 1.16.2 Function format-time-string
Format date and time:
ELISP> (format-time-string "%Y-%m-%d") "2017-07-15" ELISP> (format-time-string "%Y%m%d") "20170715" ELISP>
Unix time stamp (Number of seconds or microseconds since January first of 1970):
ELISP> (format-time-string "%s") "1500103484" ELISP>1.16.3 Function current-time
ELISP> (current-time) (22889 50074 486018 948000)1.16.4 Function current-time-string
ELISP> (current-time-string) "Sat Jul 15 04:26:27 2017" ELISP>1.16.5 Function float-time
ELISP> (float-time) 1500103652.678849 ELISP>1.16.6 Function current-time-zone
ELISP> (current-time-zone) (-10800 "-03") ELISP>1.17 Emacs Introspection 1.17.1 User init file
ELISP> user-init-file "/home/arch/.emacs.d/init.el" ELISP> (expand-file-name user-init-file) "/home/arch/.emacs.d/init.el"1.17.2 User Emacs Directory
ELISP> user-emacs-directory "~/.emacs.d/" ELISP> (expand-file-name user-emacs-directory) "/home/arch/.emacs.d/"1.17.3 Enviroment Variables 1.17.4 Get current Operating System 1.17.5 Test if Emacs is running in terminal or in window system
The variable window-system is the name of window system through which the selected frame is displayed.
Its value is a symbol:
(defun test-window-system () (interactive) (if window-system (message "Running in Window System / GUI") (message "Running in terminal ") )) > (test-window-system) "Running in Window System / GUI" > (test-window-system) "Running in terminal "1.18 Web Browser http web browser 1.18.1 Browse Url
Open http://www.yandex.com in the web browser
> (browse-url "http://www.yandex.com")
Function to open Yandex.com. Usage M-x open-yandex
(defun open-yandex () "Open the web site http://www.yandex.com." (interactive) (browse-url "http://www.yandex.com"))1.18.2 Browser Url setting the web browser
Open url with firefox
(let ((browse-url-browser-function 'browse-url-firefox)) (browse-url "http://www.yandex.com")) (setq browse-url-browser-function 'browse-url-firefox)
Open url with chromium browser or chrome
(let ((browse-url-browser-function 'browse-url-chromium)) (browse-url "http://www.yandex.com")) (setq browse-url-browser-function 'browse-url-chromium)
Open url with Emacs eww browser
(let ((browse-url-browser-function 'eww-browse-url)) (browse-url "http://www.yandex.com") (setq browse-url-browser-function 'eww-browse-url)1.18.3 Search Web sites with Emacs web search url browser
Usage: M-x search-google
(require 'url-util) (defun search-google () (interactive) "Search www.google.ca." (browse-url (format "http://www.google.ca?gws_rd=ssl#q=%s" (url-encode-url (read-string "Google: ")))))
Usage:
Usage: M-x search-google (require 'url-util) (defun search-google-url (url params) (let ((google-url (format "site:%s %s" url params))) (browse-url (format "http://www.google.ca?gws_rd=ssl#q=%s" (url-encode-url google-url))))) (search-google-url "https://news.ycombinator.com" "haskell production") (defun search-hackernews-with-google () (interactive) (search-google-url "https://news.ycombinator.com" (read-string "Hnews: "))) (defun search-reddit-with-google () (interactive) (search-google-url "https://www.reddit.com" (read-string "Reddit: "))) (defun search-stackoverflow-with-google () (interactive) (search-google-url "http://stackoverflow.com" (read-string "S.O Search: ")))
(require 'url-util) (defun search-github () (interactive) "Search www.google.ca" (browse-url (format "https://github.com/search?q=%s" (url-encode-url (read-string "Github Search: ")))))
(require 'url-util) (defun search-gisthub () "Search gisthub : http://gist.github.com. Usage: M-x search-gisthub" (interactive) (browse-url (format "https://gist.github.com/search?p=50&q=%s&ref=searchresults" (url-encode-url (read-string "Gisthub Search: ")))))
(defun open-emacs-manual () "Open Emacs online Manual. Usage: M-x open-emacs-manual. It opens the web site: https://www.gnu.org/software/emacs/manual" (interactive) (browse-url "https://www.gnu.org/software/emacs/manual/"))
(defun search/dictionary () "Search Merrian Webster Dictionary·" (interactive) (browse-url (format "https://www.merriam-webster.com/dictionary/%s" (url-encode-url (read-string "Dictionary: ")))))
Emacs Provides a built-in lightweight web browser eww browser that can be used to quick access web sites in terminal or Emacs GUI.
Open a Url with eww-browser:
M-x eww <url>
(eww-browse-url "http://m.reddit.com/r/emacs")
Open a html file with eww-browser
M-x eww-open-file <file-name>
It is useful to view html documentation inside Emacs.
(eww-open-file "/some/html/file.html")
Key Bindings
Key Binding Description C-h m Show all keybindings of eww-mode q Quit eww browser Return/Enter Open url at point Tab Jump to next hyperlink C-A i Jump to previous hyperlink Space Scrow Down Esc Scrow Up w Copy page Url l Go to previous page n Got to next page g Update/ RefreshTo load web sites faster use mobile url. Some suggestions:
Google Search
http://www.google.com/m?q=<query>
- Country/Culture sensitive searchhttp://www.google.ca/m?q=<query>
- Country/Culture insensitive search, always English.Google News:
Arch Linux Wiki
Wikipedia
Hackernews
See the browser http request:
1.19 Http Requests http request url network 1.19.1 Download File http web download(url-copy-file <url> <filename>)
(url-copy-file "http://www.httpbin.org/get" "/tmp/output") (find-file "/tmp/output")1.19.2 url-retrieve-synchronously http web download sync
(url-retrieve-synchronously URL &optional SILENT INHIBIT-COOKIES)
Example:
(with-current-buffer (url-retrieve-synchronously "http://www.httpbin.org/get") (buffer-substring-no-properties (point-min) (point-max)))
Output:
HTTP/1.1 200 OK Server: nginx Date: Fri, 23 Sep 2016 23:44:21 GMT Content-Type: application/json Content-Length: 304 Connection: keep-alive Access-Control-Allow-Origin: * Access-Control-Allow-Credentials: true { "args": {}, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip", "Extension": "Security/Digest Security/SSL", "Host": "www.httpbin.org", "Mime-Version": "1.0", "User-Agent": "URL/Emacs" }, "origin": "179.176.152.199", "url": "http://www.httpbin.org/get" }1.19.3 Download a file interactively http web download file
This function downloads a file from the url copied to clipboard and then asks the user to which file the data will be downloaded suggesting the file name extracted from the url.
This function updates the current buffer (revert buffer) if executed in a dired buffer (directory).
Testing the function:
C-x d
to open it.Usage: M-x download-url-to-file
(defun download-url-to-file () "Download a file from a URL in the clibpoard. This command asks the user for the url suggesting the url stored in the clipboard and then asks the user for the file name to be downloaded suggesting the file name extracted from the url. " (interactive) (let* ((text (with-temp-buffer (clipboard-yank) (buffer-substring-no-properties (point-min) (point-max)))) (url (read-string "Url: " text))) (url-copy-file url (read-file-name "File name: " (car (last (split-string url "/"))))) (when (equal major-mode 'dired-mode) (revert-buffer))))1.19.4 Download a file and display it on a buffer http web buffer clipboard
This command reads an url from the user and download the file content and displays it on a buffer without write a file to disk.
Example:
http://patterns.cs.up.ac.za/examples/ch9/iterator-theory.cs
M-x download-code-view
(defun download-code-view () "Download a source code from url and displays it on a buffer." (interactive) (let* ( (clipboard (with-temp-buffer (clipboard-yank) (buffer-substring-no-properties (point-min) (point-max)))) (url (read-string "Url: " clipboard)) (buf (url-retrieve-synchronously url)) (filename (car (last (split-string url "/")))) (bufname (concat "*" filename "*")) ) (switch-to-buffer buf) (goto-char (point-min)) (re-search-forward "^$") (delete-region (point) (point-min)) (kill-whole-line) (replace-string (char-to-string 13) "") (with-current-buffer buf (rename-buffer bufname))))1.19.5 Http and Post Request utils connections http
(defun url-http-post (url args) "Send ARGS to URL as a POST request." (let ( (response-string nil) (url-request-method "POST") (url-request-extra-headers '(("Content-Type" . "application/x-www-form-urlencoded"))) (url-request-data (mapconcat (lambda (arg) (concat (url-hexify-string (car arg)) "=" (url-hexify-string (cdr arg)))) args "&"))) (switch-to-buffer (url-retrieve-synchronously url)) (goto-char (point-min)) (re-search-forward "\n\n") (setq response-string (buffer-substring-no-properties (point) (point-max))) (kill-buffer (current-buffer)) response-string)) (defun url-http-get (url args) "Send ARGS to URL as a GET request." (let ( (response-string nil) (url-request-method "GET") (url-request-data (mapconcat (lambda (arg) (concat (url-hexify-string (car arg)) "=" (url-hexify-string (cdr arg)))) args "&"))) (switch-to-buffer (url-retrieve-synchronously (concat url "?" url-request-data))) (goto-char (point-min)) (re-search-forward "\n\n") (setq response-string (buffer-substring-no-properties (point) (point-max))) (kill-buffer (current-buffer)) response-string)) ELISP> (princ (url-http-get "http://httpbin.org/get" nil)) { "args": {}, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip", "Content-Length": "0", "Extension": "Security/Digest Security/SSL", "Host": "httpbin.org", "Mime-Version": "1.0", "User-Agent": "URL/Emacs" }, "origin": "167.103.159.147", "url": "http://httpbin.org/get" } ELISP> (princ (url-http-post "http://httpbin.org/post" '(("use" . "dummy") ("pass" . "something else") ("code" . "pxyz0011213")))) { "args": {}, "data": "", "files": {}, "form": { "code": "pxyz0011213", "pass": "something else", "use": "dummy" }, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip", "Content-Length": "48", "Content-Type": "application/x-www-form-urlencoded", "Extension": "Security/Digest Security/SSL", "Host": "httpbin.org", "Mime-Version": "1.0", "User-Agent": "URL/Emacs" }, "json": null, "origin": "167.103.159.147", "url": "http://httpbin.org/post" }1.20 Packages package install library 1.20.1 Test if package is installed
If the package is installed returns t (true) and nil otherwise.
(package-installed-p PACKAGE &optional MIN-VERSION)
> (package-installed-p 'helm-core) t1.20.2 Install a package if it is not installed 1.20.3 Install a single-file package from URL
This command install a single-file elisp package from a given URL to source file.
Usage:
To find where the package was intalled type M-x find-library <library-name>.
(defun package-install-url () "Install a single-file package *.el file from Url." (interactive) (let* ( (clipboard (with-temp-buffer (clipboard-yank) (buffer-substring-no-properties (point-min) (point-max)))) (url (read-string "Url: " clipboard)) ) (with-current-buffer (url-retrieve-synchronously url) (goto-char (point-min)) (re-search-forward "^$") (delete-region (point) (point-min)) (kill-whole-line) (package-install-from-buffer))))1.21 Helm Snippets framework library helm 1.21.1 Switch between buffers in same directory
Usage: M-x buffer/switch-in-directory
This command switches between buffer with files that are in current directory.
(defun buffer/with-file-in-directory-p (directory buf) "Check if a buffer has file associated and is is in DIRECTORY. Parameters: - directory string - root directory - buf buffer object - buffer object" (and (buffer-file-name buf) (string-prefix-p (expand-file-name directory) (expand-file-name (buffer-file-name buf) )))) (defun buffer/switch-in-directory () "Switch between buffers in same directory." (interactive) (helm :prompt "Buffer switch: " :sources `(( (name . "Dir: ") (candidates . ,(mapcar (lambda (b) (cons (buffer-name b) b)) (remove-if-not (lambda (b) (buffer/with-file-in-directory-p (or (file-name-directory (buffer-file-name)) default-directory ) b )) (buffer-list) ))) (action . switch-to-buffer) ))))1.21.2 Browser Recent files
Usage: M-x helm-recent-files
(require 'helm) (defun helm-recent-files () (interactive) (helm :prompt "File: " :sources `(( (name . "File: ") (candidates . ,recentf-list) (action . find-file) ))))1.21.3 Browser Recent directories
Usage M-x helm-recent-dirs
(require 'helm) (defun unique (xs) "Remove repeated elements from list xs Example: > (unique '(x y a b 21 21 10 21 x y a )) (x y a b 21 10)." (let ((result nil)) (dolist (x xs) (if (not (member x result)) (push x result))) (reverse result))) (defun helm-recent-dirs () (interactive) (helm :prompt "Dir: " :sources `(( (name . "Dir: ") (candidates . (lambda () (unique (map #'file-name-directory recentf-list)))) (action . dired)))))1.21.4 Launch ansync shell command with helm
This piece of code gets all executables in the $PATH variable and searche for one that matches the user input and then launches it. It is useful to launch applications without block Emacs.
Usage: M-x helm-laucher
(defun get-executables () "Returns a list of all files available in the directories of the $PATH variable." (apply #'append (mapcar (lambda (p) (directory-files p t)) (remove-if-not #'file-exists-p (split-string (getenv "PATH") ":"))))) (defun run-async (&optional command) "Run a shell command in asynchronous mode. It doesn't block Emacs while the command is running. Usage: (run-async \"python -m http.server\") M-x run-async -> User enters a command." (interactive) (apply #'start-process `( "proc-any" nil ,@(split-string-and-unquote (if command command (read-string "Command: " ) ))))) (defun run-async-lst (&rest commands) "Run a shell command in asynchronus mode, not blocking Emacs. Usage: > (run-async-lst <program> <argument 1> <agurment2> ...) Example: > (run-async \"thunar\" \"/usr/share/applications\")" (apply #'start-process `( "dontcare" nil ,@commands ))) (defun helm-launcher () "Launches apps available in $PATH without blocking Emacs. Usage M-x heml-launcher" (interactive) (let ((data (mapcar (lambda (p) (cons (file-name-nondirectory p) p )) (get-executables) ))) (helm :prompt "Shell: " :sources `(( (name . "Shell: ") (candidates . ,data) (action . run-async) )))))1.21.5 Switch between buffers associated with files
Switch between buffers associated with files.
(defun switch-file () "Switch between buffers that are associated with files. Usage: M-x switch file." (interactive) (let ((data (mapcar (lambda (b) (cons (buffer-file-name b) b )) (remove-if-not #'buffer-file-name (buffer-list))))) (helm :prompt "Buffer: " :sources `(( (name . "File Buffers") (candidates . ,data) (action . switch-to-buffer) )))))1.21.6 Switch between Emacs major modes
(defun helm-switch-mode () "Switch between all major programming modes available in Emacs. Usage: M-x helm-switch-mode." (interactive) (cl-flet ((unique (xs) (let ((result nil)) (dolist (x xs) (if (not (member x result)) (push x result))) (reverse result)))) (helm :prompt "Mode: " :sources `(( (name . "Emacs Major Modes") (candidates . ,(unique (mapcar #'symbol-name (remove-if-not #'symbolp (mapcar #'cdr auto-mode-alist))))) (action . ,(lambda (m) (funcall (intern-soft m)))))))))1.21.7 Open a list of web sites
(setq helm-url-default-url-list '( ("google" . "http://www.google.ca") ("yandex" . "http://www.yandex.com") ("reddit" . "http://www.reddit.com") ("/r/haskell". "http://www.reddit.com/r/haskell") ("/r/emacs" . "http://www.reddit.com/r/emacs") ("/r/csharp" . "http://www.reddit.com/r/csharp") )) (defun helm-web () (interactive) (helm :prompt "Web Site: " :sources `(( (name . "Bookmarks") (candidates . helm-url-default-url-list) (action . (lambda (c) (browse-url (cdr c))) ) ))))1.21.8 Interface Makefile
This command extracts the build tasks from a Makefile and shows it as a helm menu where the user can select the task to be executed. It will be run as a asynchronous process.
Usage: M-x helm-make
Version1:
(defun re-seq (regexp string) "Get a list of all regexp matches in a string" (save-match-data (let ((pos 0) matches) (while (string-match regexp string pos) (push (match-string 0 string) matches) (setq pos (match-end 0))) matches))) (defun helm-make () (interactive) (let ((tasks (re-seq "^\\w+" (with-temp-buffer (insert-file "Makefile") (buffer-substring-no-properties (point-min) (point-max)))))) (helm :prompt "Makefile task: " :sources `(( (name . "Task") (candidates . ,tasks) (action . (lambda (task) (start-process "make" "*make*" "make" task )))))) (switch-to-buffer "*make*")))
Version2: Remove dependency re-seq.
(defun helm-make2 () (interactive) (flet ((re-seq2 (regexp string) (save-match-data (let ((pos 0) matches) (while (string-match regexp string pos) (push (match-string 0 string) matches) (setq pos (match-end 0))) matches)))) (let ((tasks (re-seq2 "^\\w+" (with-temp-buffer (insert-file "Makefile") (buffer-substring-no-properties (point-min) (point-max) ))))) (helm :prompt "Makefile task: " :sources `(( (name . "Task") (candidates . ,tasks) (action . (lambda (task) (start-process "make" "*make*" "make" task )))))) (switch-to-buffer "*make*"))))
Example: Assuming that the current directory has the Makefile with content. The command M-x helm-make will show the tasks all, html, browse and clean.
all: html html: mkdir -p dist emacs --batch -q -l build.el --kill mv dist/README.html dist/index.html cp -r -v images dist/images cp -r *.org dist/ browse: firefox dist/index.html clean: rm -rf dist/*.html dist/*.html~1.22 Persistence 1.22.1 Save and Reload Current Session
Interactive Developement
ELISP> (defun file-contents (filename) (interactive "fFind file: ") (with-temp-buffer (insert-file-contents filename) (buffer-substring-no-properties (point-min) (point-max)))) file-contents ELISP> ELISP> (defun write-file (filename content) (append-to-file content nil filename)) write-file ELISP> ELISP> (remove-if 'null (mapcar 'buffer-file-name (buffer-list))) ("/home/tux/.emacs.d/init.el" "/sudo:root@localhost:/etc/host.conf") ELISP> (setq session-file "~/.emacs.d/lastsession.el") "~/.emacs.d/lastsession.el" ELISP> ELISP> ELISP> (format "(setq last-session-files '%S)" (remove-if 'null (mapcar 'buffer-file-name (buffer-list)))) "(setq last-session-files '(\"/home/tux/.emacs.d/init.el\" \"/sudo:root@localhost:/etc/host.conf\"))" ELISP> (setq code (format "(setq last-session-files '%S)" (remove-if 'null (mapcar 'buffer-file-name (buffer-list))))) "(setq last-session-files '(\"/home/tux/.emacs.d/init.el\" \"/sudo:root@localhost:/etc/host.conf\"))" ELISP> ELISP> (setq session-file "~/.emacs.d/lastsession.el") ELISP> (delete-file session-file) nil ELISP> (write-file session-file code) nil ELISP> ELISP> (file-contents session-file) "(setq last-session-files '(\"/home/tux/.emacs.d/init.el\" \"/sudo:root@localhost:/etc/host.conf\"))" ELISP> ELISP> (load-file session-file) t ELISP> last-session-files ("/home/tux/.emacs.d/init.el" "/sudo:root@localhost:/etc/host.conf") ELISP> ELISP> (mapcar 'find-file last-session-files) (#<buffer init.el> #<buffer host.conf>) ELISP>
Joining Everything
File: sessions.el
(setq session-file "~/.emacs.d/lastsession.el") (defun write-file (filename content) (append-to-file content nil filename)) (defun make-session-code () (interactive) (format "(setq last-session-files '%S)" (remove-if 'null (mapcar 'buffer-file-name (buffer-list))))) (defun save-session () "Save Current Session" (interactive) (when (file-exists-p session-file) (delete-file session-file)) (write-file session-file (make-session-code))) (defun load-session () (interactive) (load-file session-file) (mapcar 'find-file last-session-files) ) (message "Reloaded")
To save all bufffers with files:
M-x load-file ;; Enter session.el M-x save-session
To reload the files save in the seesion enter:
M-x load-file ;; Enter session.el M-x load-session ;; All previous files in the session ;; saved will be opened1.22.2 Save and Restore Current Window Configuration
Press <F7> to save the curren window configuration and <F8> to restore. The functions can also be executed with A-x save-view or A-x restore-view.
(defun save-view () "Save current window configuration" (interactive) (setq winconf (current-window-configuration)) (message "View Saved - Press to restore")) (defun restore-view () "Restore saved window configuration" (interactive) (set-window-configuration winconf) (message "View loaded")) (global-set-key (kbd "<f7>") #'save-view) (global-set-key (kbd "<f8>") #'restore-view)1.23 Non categorized 1.23.1 Save the scratch buffer and reload every Emacs startup
Saves the scratch buffer to a file every times Emacs is closed.
Source: scratch.el
(setq scratch-buffer-file "~/.emacs.d/scratch.el") (setq initial-scratch-message "") (add-hook 'kill-emacs-hook 'scratch-save) (add-hook 'window-setup-hook 'scratch-resume) (add-hook 'kill-buffer-hook (lambda () (if (equal (buffer-name) "*scratch*") (scratch-save)))) (add-hook 'after-save-hook (lambda () (unless (get-buffer "*scratch*") (scratch-resume)))) (defun scratch-save () (let ((buf (get-buffer "*scratch*"))) (when buf (set-buffer buf) (write-file scratch-buffer-file) (ignore-errors (kill-buffer "scratch.el"))))) (defun scratch-resume () "*scratch* " (interactive) (set-buffer (get-buffer-create "*scratch*")) (funcall initial-major-mode) (insert-file-contents scratch-buffer-file nil nil nil t) (ignore-errors (kill-buffer ".scratch")))1.23.2 Code Navigation with Occur edit
The function occur is useful for code navigation and scan code statements, this function is invoked by M-x occur.
Examples:
The function python/scan-functions will scan for all lines that starts with def statement in a Python code and show the matching lines in the right side.
(defun python/scan-functions () (interactive) (split-window-horizontally) (occur "def"))
Example:
It can also be useful to Scan code tags like: @FIXME, @TODO, @README, @NOTE. This fuction can be excuted by typing: M-x scan-code-tags
Example:
(defun scan-code-tags () "Scan code tags: @TODO: , @FIXME:, @BUG:, @NOTE:." (interactive) (split-window-horizontally) (occur "@FIXME:\\|@TODO:\\|@BUG:\\|@NOTE:"))1.23.3 Quick edit and reload Emacs Configuration File. elisp customization
It is useful to quick edit and reload ~/emacs.d/init.el without restart emacs. Those functions can be put in the init.el file.
(defun reload-init-file () "Reload init.el file." (interactive) (load user-init-file) (message "Reloaded init.el OK.")) (defun open-init-file () (interactive) (find-file user-init-file))1.23.5 Create a menu with all color themes available
Using Eval
Copy and paste the code below to the scratch buffer and enter M-x eval-buffer. This code can also be put in ~/emacs.d/init.el, in the config file.
(defun eval-string (str) (eval (read str))) (defun make-menu-rows () (mapcar (lambda (x) (format "[\"%s\" (load-theme '%s)]" (symbol-name x) (symbol-name x) )) (custom-available-themes))) (defun make-color-menu-code () (format " (easy-menu-define djcb-menu global-map \"Color Themes\" '(\"Color Themes\" %s ) ) " (mapconcat 'identity (make-menu-rows) "\n"))) (eval-string (make-color-menu-code))
Using Macros
Developement:
ELISP> (custom-available-themes) (cyberpunk adwaita deeper-blue dichromacy leuven light-blue manoj-dark misterioso tango-dark tango tsdh-dark tsdh-light wheatgrass whiteboard wombat) ELISP> (mapcar (lambda (sym) `[,(symbol-name sym) (load-theme (quote ,sym))]) (custom-available-themes) ) (["adwaita" (load-theme 'adwaita)] ["deeper-blue" (load-theme 'deeper-blue)] ["dichromacy" (load-theme 'dichromacy)] ["leuven" (load-theme 'leuven)] ["light-blue" (load-theme 'light-blue)] ["manoj-dark" (load-theme 'manoj-dark)] ["misterioso" (load-theme 'misterioso)] ["tango-dark" (load-theme 'tango-dark)] ... ELISP> (defun make-menu-rows () (mapcar (lambda (sym) `[,(symbol-name sym) (load-theme (quote ,sym))]) (custom-available-themes))) make-menu-rows ELISP> ELISP> (make-menu-rows) (["adwaita" (load-theme 'adwaita)] ["deeper-blue" (load-theme 'deeper-blue)] ["dichromacy" (load-theme 'dichromacy)] ["leuven" (load-theme 'leuven)] ... ELISP> `(easy-menu-define djcb-menu global-map "Color Themes" '("Color Themes" ,@(make-menu-rows))) (easy-menu-define djcb-menu global-map "Color Themes" '("Color Themes" ["adwaita" (load-theme 'adwaita)] ["deeper-blue" (load-theme 'deeper-blue)] ["dichromacy" (load-theme 'dichromacy)] ["leuven" (load-theme 'leuven)] ["light-blue" (load-theme 'light-blue)] ... ELISP> (eval `(easy-menu-define djcb-menu global-map "Color Themes" '("Color Themes" ,@(make-menu-rows)))) nil
Final code
(defun make-menu-rows () (mapcar (lambda (sym) `[,(symbol-name sym) (load-theme (quote ,sym))]) (custom-available-themes))) (defmacro make-color-menu () `(easy-menu-define djcb-menu global-map "Color Themes" '("Color Themes" ,@(make-menu-rows)))) (make-color-menu) (progn (defun make-menu-rows () (mapcar (lambda (sym) `[,(symbol-name sym) (load-theme (quote ,sym))]) (custom-available-themes))) (defmacro make-color-menu () `(easy-menu-define djcb-menu global-map "Color Themes" '("Color Themes" ,@(make-menu-rows)))) (make-color-menu)) ELISP> (macroexpand '(make-color-menu)) (progn (defvar djcb-menu nil "Color Themes") (easy-menu-do-define 'djcb-menu global-map "Color Themes" '("Color Themes" ["adwaita" (load-theme 'adwaita)] ["deeper-blue" (load-theme 'deeper-blue)] ["dichromacy" (load-theme 'dichromacy)] ["leuven" (load-theme 'leuven)] ["light-blue" (load-theme 'light-blue)] ...2 IELM - Inferior Emacs Lisp Mode 2.1 Change Prompt
Change the default IELM prompt "ELISP> " to "> ".
2.2 Clear IELM shellClear IELM buffer. Usage: M-x ielm/clear
(defun ielm/clear () "Clear IELM buffer." (interactive) (with-current-buffer "*ielm*" (let ((inhibit-read-only t)) (erase-buffer))))2.3 Send Region to IELM
Send selected text (region) to IELM and print the output.
(defun ielm/send-region () (interactive) (let ((text (buffer-substring-no-properties (region-beginning) (region-end)))) (with-current-buffer "*ielm*" (insert text) (ielm-send-input))))2.4 Set other window's buffer as working buffer
Usage: M-x ielm-select-buffer-other-window
(defun ielm-select-buffer-other-window () "Select other window' buffer as IELM's working buffer." (interactive) (let ((buf (save-window-excursion (other-window 1) (current-buffer)))) (ielm-change-working-buffer buf) (ielm-print-working-buffer)))2.5 Start IELM in other window setting the working buffer to current buffer
This command starts IELM in other window setting the working buffer to current buffer. It allows the user to manipulate the current buffer.
Usage: M-x ielm-this-buffer
(defun ielm-this-buffer () "Start IELM in other window with current buffer set to current windows' buffer." (interactive) (let ((buf (current-buffer))) (ielm-other-window) (ielm-change-working-buffer buf) (ielm-print-working-buffer)))2.6 Launch IELM in other frame
Usage: M-x ielm-other-frame
(defun ielm-other-frame () "Launch IELM in other frame." (interactive) (with-selected-frame (make-frame) (ielm)))3 Emacs Server and Client 5 Selected Gists and Source Codes
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4