Skip to content

Latest commit

 

History

History
909 lines (657 loc) · 43.1 KB

Utilities.org

File metadata and controls

909 lines (657 loc) · 43.1 KB

Emacs Utilities

Emacs Utilities

Overview

Some Emacs utilities and goodness.

FeatureEntry PointDescription
Help Commands
Help for all help commadsM-x help-for-help
Emacs built-in tutorialM-x help-with-tutorialOpen Emacs tutorial.
Emacs built-in localized tutorialM-x help-with-tutorial-spec-languageEmacs built-in tutorial in many languages like Russian, Portuguese …
Package Manager
Package ManagerM-x list-packagesList all packages available.
M-x package-installInstall some package
Info page and Man page - Unix docs
Info pageM-x info / M-x heml-infoInfo page reader. The helm-version is provided by heml package.
ManpageM-x woman / M-x helm-man-womanManpage Reader
File Manager and edit remote files
File managerM-x dired or C-x dFile manager and directory editor
Tramp modeTramp mode - edit remote files, edit as super user and open
remote directories through ssh, sftp, telnet and ftp
Programming
Compile modeM-x compileRun any compilation command, compiler or build automation tool like make or ant.
GNU Debugger InterfaceM-x gdb
Git Version Control SystemM-x magit-statusGit user interface provided by the magit package.
Diff filesM-x ediffFile diff viwer
Diff buffersM-x ediff-buffersBuffers diff viewer like ediff
VIM EmulationM-x evil-modeEmulates VI/VIM editor behavior. It is provided by the evil package.
Shells
Shell CommandM-x shell-commandRun a batch shell command like ifconfig or dmesg (Linux)
Async shell commandM-x async-shell-commandRun any shell command asynchronously.
EshelM-x eshellMulti platform shell written in Elisp and highly integrated to Emacs.
IelmM-x ielmElisp Interactive shell to control and Debug Emacs
System Related Commands
Copy fileM-x copy-fileCopy a file. Prompt user for a file to copy.
Delete fileM-x delete-filePrompt user for a file to delete.
Make directoryM-x make-directoryCreates a new directory. Equivalent to shell command $ mkdir
Delete directoryM-x delete-directoryDelete a directory. Promps the user for a directory to delete.
Copy directoryM-x copy-directoryCopy directory.
Task manager/ Process managerM-x procedHtop like multi platform task manager.
Network Tools
Network informationM-x ifconfigShow iformation about network interfaces
PingM-x pingPing a host name or ip address
TracerouteM-x tracerouteTraceroute a host name or ip address
ARPM-x arpDisplay the command arp output.
Routing TableM-x routeShow routing table.
WhoisM-x whoisRun whois command to show information about route.
TelnetM-x telnetTelnet login. It is the acient version of SSH.
Misc
CalculatorM-x calcRPN (Reverse Polish Notation) calculator like HP-48g engineering calculator.
Color PalleteM-x list-colors-displayDisplay a collor pallete.

Note:

  • M-x ifconfig - runs ipconfig on Windows and ifconfig or ip on Linux. It is platform agnostic.
  • To Emacs’ tutorial (help-with-tutorial) work the cua-mode must be disabled (M-x cua-mode to disable it).

Fun

CommandDescription
M-x doctorIf you fell bad, your country is in a endless recession …
M-x lifeRun Conway’s Life simulation.
M-x dunnetText based adventure game
M-x tetrisPlay Tetris.
M-x hanoiTowers of Hanoi.
M-x zoneMake buffers go crazy!!
M-x zone-leave-me-aloneStop zoning out.

Shells

Emacs have built-in commands to run shells.

NameCommand: M-x <command>Description
shellM-x shellRuns an inferior shell app. It can run bash, zsh and etc.
termM-x termEmacs’ terminal emulator that can run apps like top, vim, bash and etc.
It alows command line line completion inside Emacs in apps like bash, zsh and python .
eshellM-x eshellEmacs’ built-in shell written in Elisp. it has elisp implementation of cd, ls, pwd
and other standard Unix commands and apps. Works on all operating systems. Eshell
also can run Elisp functions. It is a good alternative to Microsoft Windows
terminal emulator cmd.exe.
ielmM-x ielmEmacs’ elisp shell that can be used to control, test and interact with Emacs.

Emacs also have commands to run programming languages shells:

LanguageCommandPackage
PythonM-x run-python-
OctaveM-x run-octave-
RubyM-x run-rubyinf-ruby
Elisp (Emacs Lisp)M-x ielm-
SchemeM-x run-scheme-
LispM-x run-lisp-

Async Shell Command

It can run any repls or interactive shell applications, except ncurses-based apps like htop.

Example: M-x async-shell-command “java -jar clojure.jar”.

It is useful to run programming languages shells even if there is no mode or package installed for it. It is possible to rename the shell buffer with M-x rename-buffer in order to make easier to identify the buffer.

Examples:

Run sqlite3:

  • M-x async-shell-command sqlite3

Run scala repl:

  • M-x async-shell-command scala and then M-x rename-buffer *scala*

to change the default buffer name to a more readable name *scala*.

Run mono’s csharp repl:

  • M-x async-shell-command csharp

Run Windows powershell:

  • M-x async-shell-command powershell -Command -

Run Java bean shell (Java Interpreter):

  • M-x async-shell-command “java -cp ~/opt/bsh-2.0b4.jar bsh.Interpreter”

or programatically:

(async-shell-command "java -cp ~/opt/bsh-2.0b4.jar bsh.Interpreter")

Defining a command:

(defun run-bsh ()
    "Run Java bean shell."
    (interactive)
    (async-shell-command "java -cp ~/opt/bsh-2.0b4.jar bsh.Interpreter"))

Example: Running Haskell REPL.

  • M-x async-shell-command stack ghci

http://i.imgur.com/I90yeoX.gif

Example: Install a Haskell package

  • M-x async-shell-command stack instal turtle

http://i.imgur.com/btfaK3k.gif

Example: Running Fsharp REPL

  • M-x async-shell-command fsi

http://i.imgur.com/tRKPfXG.gif

Example: Ping a server to test connection 8.8.8.8 (Google’s DNS)

  • M-x async-shell-command ping 8.8.8.8

http://i.imgur.com/3OeuGNj.gif

Compiling in Emacs - M-x compile

Compilation Commands

To compile any code use:

  • To compile: M-x compile <compilation command>
  • To recompile: M-x recompile or type g at the compilation buffer.

Compilation Commands

CommandKey bindingDescription
M-x compileRun a compilation command
M-x recompileg (compilation buffer)Run a compilation command again.
M-x kill-compilationC-c C-k (compilation bufffer)Stop compilation process.
M-x compilation-next-errorM-nGo to next error
M-x compilation-previous-errorM-pGo to previous error

Compilation Buffer Key bindings

  • Note: The command M-x compile provides completion for Makefile targets by typing M-x compile make <tab>.
CommandKey bindingDescription
M-x recompilegCompile again running same compilation command.
M-x quit-windowqQuit compilation buffer
M-x kill-compilationC-c C-kStop compilation process
<Go to beginning of compilation buffer.
>Go to end of compilation buffer.
M-x describe-modeh
RETTyping Return at compilation error goes to error location.
M-x rename-bufferTo use multiple compilation buffers, rename it with this command.

Setting compilation key bindings

The code block bellow will set the key bindings as shown in the following tables:

Key bindings for outside compilation buffer.

Key bindingDescription
f9Run M-x compile
Windows-Key/Super-f9Run M-x
M-[Go to next compilation error
M-]Go to previous compilation erro

Key bindings for compilation buffer

Key bindingDescription
qQuit compilation buffer (default)
gRun M-x recompile (default)
cRun a new compilation command
kKill compilation
mmRun make - M-x compile ‘make’
mcRun make clean - M-x compile ‘make clean’
mpRun make clean and make again.
(global-set-key [f9]    #'compile)

;; Not s-f9 means Windows Key/f9
(global-set-key [s-f9]  #'recompile)

(global-set-key (kbd "M-[") #'compilation-previous-error)
(global-set-key (kbd "M-]") #'compilation-next-error)

(define-key compilation-mode-map "c" #'compile)
(define-key compilation-mode-map "k" #'kill-compilation)

(define-key compilation-mode-map "mm" (lambda () (interactive)
                                        (compile "make")))

(define-key compilation-mode-map "mc" (lambda () (interactive)
                                        (compile "make clean")))

(define-key compilation-mode-map "mp" (lambda () (interactive)
                                        (compile "make clean && make")))

Creating custom compilation commands

Compile Haskell

Compile single-file haskell apps with stack:

(defun compile-haskell ()
  "Compile a haskell .hs file."
  (interactive)
  (save-buffer)
  (compile (format "stack exec -- ghc %s -o %s.bin"
                   (buffer-file-name)
                   (file-name-base (buffer-file-name))
                   )))


(defun compile-haskell-run ()
  "Compile a haskell .hs file and runs the executable."
  (interactive)
  (save-buffer)
  (compile (format "stack exec -- ghc %s -o %s.bin && ./%s.bin"
                   (buffer-file-name)
                   (file-name-base (buffer-file-name))
                   (file-name-base (buffer-file-name))
                   )))

The command M-x compile-haskell can be used to compile this code bellow that will produce the executable myApp.bin.

The command M-x compile-haskell-run compiles the code and runs the app.

File: file:codes/myApp.hs

import qualified System.Directory as D

main :: IO ()
main = do 
  putStrLn "Hello World Haskell!"
  D.getDirectoryContents "/" >>= mapM_ putStrLn    

Compile F# (Fsharp)

The command M-x compile-fsharp-run compiles a F# app .fsx to .exe and runs it with mono.

(defun compile-fsharp-run ()
  "Compile a Fhsarp .fsx file to .exe .NET executable."
  (interactive)
  (save-buffer)
  (compile (format "fsc --target:winexe --platform:anycpu --standalone %s --out:%s.exe && mono %s.exe"
                   (buffer-file-name)
                   (file-name-base (buffer-file-name))
                   (file-name-base (buffer-file-name))                   
                   )))

This command can be used to compile the file helloWinform.fsx to helloWinform.exe and run it.

File: file:codes/helloWinform.fsx

open System.Windows.Forms
open System.Drawing 

let f = new Form () 
f.Text <- "Hello world"
f.Name <- "Form1"
f.BackColor <- Color.Blue

let btn = new Button (Text= "Click Me", BackColor = Color.Green)
f.Controls.Add(btn)
btn.Click.Subscribe(fun _ -> printfn "Click me again")

Application.Run(f)

Example

Example: Running a F# script. To see the image fullscreen open: http://imgur.com/a/7Hvrz and click at the image.

http://i.imgur.com/mBMJmqp.gif

In this case was used the command M-x compile fsi helloWinform.fsx. That runs a F# script performing and all syntax errors and value errors will be shown at the compilation buffer.

Note: This code also works in Linux or OSX. It was recorded in Windows because there was no good GIF recording apps available for Linux at the time this was recorded.

Code used in this example: File - helloWinform.fsx

open System.Windows.Forms
open System.Drawing 

let f = new Form () 
f.Text <- "Hello world"
f.Name <- "Form1"
f.BackColor <- Color.Blue

let btn = new Button (Text= "Click Me", BackColor = Color.Green)
f.Controls.Add(btn)
btn.Click.Subscribe(fun _ -> printfn "Click me again")

Application.Run(f)

Emacs in Terminal

Running Emacs in terminal:

  • emacs -nw

Running Emacs fast without read ~/emacs.d/init.el or ~/.emacs startup file:

  • emacs -nw -Q
  • Start Emacs in terminal running Eshell:

Running Emacs in terminal or executing some Elisp command or app:

$ emacs -nw -q --eval '(eshell)'
  • Start Emacs in terminal running python:
$ emacs -nw -q --eval '(progn (run-python "python3") (switch-to-buffer "*Python*"))'

See also:

Manpage Reader

To read manpages enter M-x woman.

Example: Rsync manpage.

file:images/utilities_manpage.png

Info Page Reader

  • To Browser info pages and also the Emacs documentation. M-x info
  • Search Info pages. M-x info-apropos

Example: Top info page.

file:images/utilities_infopage_root.png

file:images/utilities_infopage_tramp.png

Calculator - M-x calc

Overview:

  • RPN Calculation (Like HP48g series)
  • Good for small calculation and verify expected values.
  • Scientific calculator
  • Bitwise operation: Useful for low level programming like: C-programming, embedded systems, network and machine instructions
  • Units - Convert units like meters, inches, feets, min, seconds, bits, bytes …
  • Functions (cos, sin, exp bound to keybindings)
  • Date calculations
  • Symbolic Math

Documentation

Describe keybindingsC-h m
Calc Info manualM-x calc-info

Stack Commands

DupRETDuplicate last number of stack.
SwapTabSwap the last two numbers of stack.

Scientific Functions

FunctionKey
set precisionp
change signn
reciprocal 1/n&
square rootQ
lnL
exp (e^x)E
10^xH E
sinS
cosC
tanT
radian modem r
degree modem d
pi π (3.415…)P
factorial!, k d
Prime factorizationk f
GCDk g
LCMk l
Error function - erff e
Error fuinction - erfcI f e

Financial Functions

Enter percentageM-%
Convert to percentagec %
Percentage changeb %
present valueb P
future valueb F
rate of returnb T
number of paymentsb #
size of paymentsb M
net present value, int rate of returnb N, b I

Formula transformation

DescriptionKey bindingOutput
Enter a formula’ (-b + sqrt(b^2 - 4*a*c) / (2 * a))
Print the formula in Latex modedL\frac{\sqrt{b^2 - 4 a c} - b}{2 a}
Creates a C-lanaguage codedC(sqrt(pow(b, 2) - 4*(a*c)) - b) / (2*a)
Normal LanguagedN_' (-b + sqrt(b^2 - 4*a*c) / (2 * a))_
Show formula in big display modedB

Unit Conversions

DescriptionM-x command
Enter number with unites’ 100 ft/hr
Convert to new unit, base unitu c, u b
Convert temperature unitsu t
Simplify unit expressionu s
View unit tableu v

Numbers with different base

DescriptionEmacs CalcBase 10
Binary2#11110101245
Octal8#2723
Hexadecimal16#FFFF65535

Bitwise Operations

KeybindingM-x commandDescription
Number Representation
d 0Decimal (Standard )
d 2Number representation to binary 2#00100111
0 d 2Two-complement binary
d 6Hexadecimal
Word Size
b wSet word size (8 bits, 16 bits, 32 bits …)
b ccalc-clipClip the current number to current word size.
Bitwise operation
b acalc-andBitwise AND
b ocalc-orBitwise OR
b xcalc-xorBitwise XOR
b ncalc-notBitwise NOT
b dcalc-diffBitwise difference
b rcalc-rshift-binaryBitwise right shift by 1 bit
b lcalc-lshift-binaryBitwise left shift by 1 bit

See also

Magit - Emacs Interface to GIT

See:

Magit Remote Branches

Magit Reference Card:

Another Reference Card

Command M-xKey bindGIT
magit-status
magit-statusgit statusMagit status is the main entry point to Magit
magit-initgit initInit a git repository
magit-loggit log
magit-process-bufffer$Displays the git command and its output
gUpdate magit status buffer
lHistory
LVerbose history
!!git <command>Run a git command
!sMagit shell command

Remote Branches

Command M-x
magit-add-remoteAdd a remote branch to magit
magit-remote-addM-a add remote repository
magit-remote-removeM-d remove remote repository

Untracked files commands:

sAdd untracked file to staging area
C-u SStage all untracked and tracked files
iAdd filename to .gitignore
kDelete untracked file, forever

Staging and Commiting

uUnstage
C-u sPrompt file for stagin
UUnstage everything that has been staged
cPop buffer for commit message
C-c C-cAmend commit message
C-c C-kErage magit-log-edit buffer and bury it

Tagging

t tCreate a lightweight tag
t aCreate annotated tag

Stashing

z zCreate new stash
aApply stash
APop a stash
kDrop a stash

Branch

b vBranch manager
b bSwitch to a different branch
b nCreate a new branch
kDelete current branch
C-u kDelte branch event if it hasn’t been merged
m mMerge the branch in current line to specified
gRefresh branch list
qBuries the branch list and deletes the window

Helm utilities

CommandDescription
Elisp Programming
M-x helm-M-xShow all M-x commands
M-x helm-aproposApropos with helm interface.
Search Documentation
M-x helm-infoSearch Info pages.
M-x helm-man-womanSearch man pages.
Files and buffer
M-x helm-buffers-listSwitch buffers
M-x helm-find-filesHelm equivalent of M-x find-files
Search
M-x helm-occurOccur-like command with helm interface.
Org-mode
M-x helm-org-in-buffer-headingsFilter org-mode files by headlines.
Code Navigation
M-x helm-imenuCode navigation with Imenu
Process Manager
M-x helm-topTask/Process manager like M-x proced
Color Pallete
M-x helm-colorsSelect a color and copy to clipboard

Spell Checker

Emacs uses external programs to check the spell. It supports ispell, aspell and hunspell. The variable ispell-program-name sets the spell check software used by Emacs. The default dictionary used by Emacs is US English, but it can be changed with the command M-x ispell-change-dicitonary.

Spell check interface commands:

CommandDefault Key BindDescription
M-x ispell-bufferCheck the spelling of all buffer.
M-x ispell-wordM-$Check the spell of word at cursor position.
M-x ispell-regionCheck the spell of selected text.
M-x ispell-change-dictionaryChange the language of dictionary used by the spell check.
M-x flyspell-modeToggle flyspell mode. When active, it will highlight all misspelled .
M-x flyspell-bufferCheck the hole buffer in flyspell minor mode.
M-x ispell-kill-ispellKill the Ispell subprocess.

Set the default Spell checker:

(setq ispell-program-name "aspell")

;; or
(setq ispell-program-name "ispell")

;;
(setq ispell-program-name "hunspell")

The dictionary can be changed with the Elisp code:

(ispell-chage-dictionary "en")
(ispell-chage-dictionary "castellano")
(ispell-chage-dictionary "german")


;; M-x ispell-spanish
;;
(defun ispell-spanish ()
 (interactive)
 (ispell-change-diciontary "castellano"))

;; M-x ispell-en
;;
(defun ispell-en ()
  (interactive)
   (ispell-change-diciontary "en"))

To right click in the word and get suggestions use:

(eval-after-load "flyspell"
  '(progn
     (define-key flyspell-mouse-map [down-mouse-3] #'flyspell-correct-word)
     (define-key flyspell-mouse-map [mouse-3] #'undefined)))

The ispell doesn’t check the spell of comments and strings. This behavior can be changed with the code below that allows it to check the spell in all programming modes like python-mode, haskell-mode and so on.

(add-hook 'prog-mode-hook 'flyspell-prog-mode)

See also: