code:
android debugger                            - adb.service                                disabled
let libreoffice/emacs find printers         - avahi-daemon.service                       enabled
as above                                    - avahi-dnsconfd.service                     enabled
finding block devices                       - blk-availability.service                   disabled
play bootup sound                           - canberra-system-bootup.service             disabled
play reboot sound                           - canberra-system-shutdown-reboot.service    disabled
play shutdown sound                         - canberra-system-shutdown.service           disabled
store data on computer clusters             - ceph-mds@.service                          disabled
store data on computer clusters             - ceph-mon@.service                          disabled
store data on computer clusters             - ceph-osd@.service                          disabled
agetty manages TTYs                         - console-getty.service                      enabled
single user login                           - console-shell.service                      enabled
apply cpu power info                        - cpupower.service                           disabled
cron scheduling                             - cronie.service                             disabled
wanted by networkd                          - dbus-org.freedesktop.network1.service      enable
wanted by networkd                          - dbus-org.freedesktop.resolve1.service      enable
debug early boot                            - debug-shell.service                        disabled
torrenting                                  - deluge-web.service                         disabled
torrenting                                  - deluged.service                            disabled
wireless get ip address                     - dhclient@.service                          disabled
wireless get ip addr                        - dhcpcd.service                             disabled
wireless get ip addr                        - dhcpcd@.service                            disabled
lvm helper stuff                            - dm-event.service                           disabled
local mail server for gnus                  - dovecot.service                            disabled
dependancy for gst plugins bad              - fluidsynth.service                         disabled
ftp daemon                                  - ftpd.service                               disabled
my own script                               - github.service                             disabled
accessing gnunet                            - gnunet.service                             disabled
virtual console mouse server                - gpm.service                                disabled
alternate way of encrypted authentication   - gssproxy.service                           enabled
apache web server                           - httpd.service                              disabled
netctl ethernet stuff                       - ifplugd@.service                           disabled
ip6 stuff                                   - ip6tables.service                          disabled
 an outdated encryption thing ?             - krb5-kadmind.service                       disabled
outdated encrypted stuff                    - krb5-kdc.service                           disabled
outdated encrypted stuff                    - krb5-kpropd.service                        disabled
let laptop stuff spin down                  - laptop-mode.service                        disabled
gnome boxes                                 - libvirt-guests.service                     disabled
gnome boxes                                 - libvirtd.service                           disabled
translate tv remote key press into commands - lircd.service                              disabled
translate tv remote key press into commands - lircmd.service                             disabled
laptop mode tools                           - lmt-poll.service                           disabled
logical volume management                   - lvm2-lvmetad.service                       disabled
logical volume management                   - lvm2-monitor.service                       disabled
wifi stuff                                  - netctl-auto@.service                       disabled
wifi stuff                                  - netctl-sleep.service                       disabled
wifi stuff                                  - netctl.service                             disabled
network file system                         - nfs-blkmap.service                         disabled
network file system                         - nfs-server.service                         disabled
nginx web server                            - nginx.service                              disabled
name service cache daemon                   - nscd.service                               enabled
pacman stuff                                - pacman_databas-_mon.service                disabled
firefox sync cache                          - pdnsd.service                              disabled
make php run fast                           - php-fpm.service                            disabled should be Enabled!
a faster sendmail alternative               - postfix.service                            disabled should be Enabled!
???                                         - prelink-tue.service                        disabled
sync remote files                           - rsyncd.service                             disabled
realtime policy and watchdog daemon         - rtkit-daemon.service                       disabled
part of systemd                             - serial-getty@.service                      enabled
systemd stuff                               - systemd-bootchart.service                  enabled
systemd stuff                               - systemd-journal-upload.service             enabled
systemd stuff                               - systemd-networkd-wait-online.service       enabled
systemd stuff                               - systemd-networkd.service                   enabled
systemd stuff                               - systemd-nspawn@.service                    enabled
systemd stuff                               - systemd-resolved.service                   enabled
man udisks                                  - udisks2.service                            enabled
gnome stuff that gdm uses                   - upower.service                             disabled
change the nice level of programs           - verynice.service                           disabled
doing wifi stuff                            - wpa_supplicant-nl80211@.service            disabled
doing wifi stuff                            - wpa_supplicant-wired@.service              disabled
doing wifi stuff                            - wpa_supplicant.service                     disabled
doing wifi stuff                            - wpa_supplicant@.service                    disabled
find printers                               - avahi-daemon.socket                        enabled
local mail server                           - dovecot.socket                             disabled should be Enabled!
????                                        - git-daemon.socket                          disabled
outdated encryption                         - krb5-kpropd.socket                         disabled
used with kodi                              - lircd.socket                               disabled
remote login                                - rlogin.socket                              disabled
remote procedure calls                      - rpcbind.socket                             disabled should be Enabled?
stuff                                       - rsh.socket                                 disabled
stuff                                       - rsyncd.socket                              disabled
should be enabled                           - sshd.socket                                enabled
important                                   - systemd-journal-gatewayd.socket            enabled
important                                   - systemd-journal-remote.socket              enabled
important                                   - systemd-networkd.socket                    enabled
outdated talking utility                    - talk.socket                                disabled
outdated communication                      - telnet.socket                              disabled
enabled                                     - uuidd.socket                               enabled
virtual machine stuff                       - virtlockd.socket                           disabled
virtual machine stuff                       - virtlogd.socket                            disabled
force reboot                                - ctrl-alt-del.target                        enabled
systemd stuff                               - exit.target                                enabled
systemd stuff                               - halt.target                                enabled
needed for ctl alt delete                   - kexec.target                               enabled
systemd stuff                               - machines.target                            enabled
network filesystem                          - nfs-client.target                          disabled should be Enabled!
systemd stuff                               - poweroff.target                            enabled
systemd stuff                               - reboot.target                              enabled
systemd stuff                               - rescue.target                              enabled
removed unused blocks on filesytem          - fstrim.timer                               enabled
laptop mode tools                           - laptop-mode.timer                          disabled
pacman-database-mon.timer                  disabled
pacman keyring updater                      - pacman_keyring.timer                       enabled
prelink-tue.timer                          disabled


code:
#+AUTHOR:Joshua Branson
#+TITLE: DNS
#+LATEX_HEADER: \usepackage{lmodern}
#+LATEX_HEADER: \usepackage[QX]{fontenc}
#+OPTIONS: H:10 toc:nil

* DNS

https://help.hover.com/hc/en-us/articles/217282457-How-to-Edit-DNS-records-A-CNAME-MX-TXT-and-SRV-Updated-Aug-2015-

https://help.hover.com/hc/en-us/articles/217282457-How-to-Edit-DNS-records-A-CNAME-MX-TXT-and-SRV-Updated-Aug-2015-

https://help.hover.com/hc/en-us/articles/217282457-How-to-Edit-DNS-records-A-AAAA-CNAME-MX-TXT-SRV-

A or AAAA records are for IP and IP6 respectively.

CNAME records are for when you're offering

repo_name: hwpplayers/cheatsheets

license: mit


code:
#+TITLE: Emacs Lisp Cheat Sheet
#+AUTHOR: Joshua Branson
#+LATEX_HEADER: \usepackage{lmodern}
#+LATEX_HEADER: \usepackage[QX]{fontenc}

* The 3 fundamental Lisp Syntax things
1) =(<command> <arg1> <arg2> <arg3>)= means to run command with arguments 1-3.
2) ='(<command> <arg1> <arg2> <arg3>)=  is like a quoted string.  The computer does NOT run any command.
3) =;= is a comment.  Anything after the =;= on that line will not be interpreted as code by the elisp interpreter.
* Flow Control/Conditionals
- *cond* is the most powerful of the conditionals, which is essentially a switch statement.  It looks like this:
  #+BEGIN_SRC emacs-lisp
    (cond
     ((condition 1) body-forms)
     ((condition 2) body-forms)
     ((condition 3) body forms)
     (t default-body-forms))
  #+END_SRC

- *when* is a simple if statement with no attached else.
  When =COND= is true evaluate the body forms and return the value of the last one, but if COND is not true, return nil.
  #+BEGIN_SRC emacs-lisp
  (when COND BODY...)
                     #+END_SRC
* Buffers
A buffer is a region of memory that contains the contents of a file.  The current buffer is what is displayed in an Emacs window.  However, it is possible to manipulate buffers without displaying them to the screen.

- (buffer-name) is the name of the current buffer
- (buffer-file-name) is the full path of the current buffer
- (current-buffer) returns the full text in the current buffer.
- (other-buffer) returns the full text from the last visited buffer.
- You can switch to another buffer in emacs with
  #+BEGIN_SRC emacs-lisp
   (switch-to-buffer (other-buffer))
  #+END_SRC

  OR

  #+BEGIN_SRC emacs-lisp
   (switch-to-buffer (<buffer name>))
  #+END_SRC
- (buffer-size) tells you the size of the current buffer
- (point) tells you how many chars are between the beginning of the buffer and point
* defuns
  a function definition,

  #+BEGIN_SRC emacs-lisp
     (defun FUNCTION-NAME (ARGUMENTS…)
       "OPTIONAL-DOCUMENTATION…"
       (interactive ARGUMENT-PASSING-INFO)     ; optional
       BODY…)

  #+END_SRC

  The cool thing about lisp is that you DO NOT need to use (return) to return a value. Instead, the last evaluated form in a defun
  is what is returned!
** Sharpquoting

Here is a sharp quote:

#+BEGIN_SRC emacs-lisp
(add-hook 'org-mode-hook #'toggle-word-wrap)
#+END_SRC

You should only sharp quote something when you are quoting a named function.  This gives the byte compiler more useful information in case of future debugging.  BUT there's no need to sharp quote a lambda expression.  So don't do this:

#+BEGIN_SRC emacs-lisp
  (add-hook 'org-mime-html-hook #'(lambda ()
                                    (org-mime-change-element-style
                                     "pre" (format "color: %s; background-color: %s; padding: 0.5em;"
                                                   "#E6E1DC" "#232323"))))
#+END_SRC

* Data Types
Lisp Date types are a way of categories each lisp object.  Every object has at least one type, but it can also have more than 1 type.  This is why you can ask if an object is of type =a=, but you cannot ask what type an object is.

Each object in lisp not only stores that object's value, it also stores that objects type/s.  This means that if an object is of type number, then you cannot concatenate a string to it, because lisp knows that that object is a number, NOT a string, which is why this will fail:
#+BEGIN_SRC emacs-lisp
  (setq number 5)
  (print (concat "5" number))
#+END_SRC
** Programming types
*** Sequence Types
   A sequence in lisp is a set of elements.  It can either be a "list" or a "array".

   A list can hold elements of any type. ie:
   #+BEGIN_SRC emacs-lisp
   '(hello '(I am supper cool) '(hello again ) yup that is me)
   #+END_SRC

   So a list is like a digital shopping list.  The shopping list can have items from ANY store, and it can be nearly infinitely long!

   An array is a fixed length sequence.  If the array can hold any element, then it is a
   vector array.  A vector array is like a written shopping list, because a written shopping list can only hold soo many items on it.

   Strings just hold characters. So string arrays are like a written novel w/o pictures.  The book can only have words and a written book cannot be infinitely long.

   Bool-vectors are a sequence of t and nil in any order.  So bool vector are like lie detector games where you can only answer yes or no.

   [[info:elisp#Sequence%20Type][info:elisp#Sequence Type]]
   Char tables are like strings, except they can hold any valid character code like =?\C-t=

   Lists string and arrays share some similiarities.  ie: all have a length L, and all are
   indexed from 0 to L minus one.

   Also take
*** integer
Integers are whole numbers lacking any fractional part.  So the following are all -1
#+BEGIN_SRC emacs-lisp
-1
-1.
#+END_SRC

and the following are all 1
#+BEGIN_SRC emacs-lisp
1
+1
1.
+1.
#+END_SRC
**** some interesting ints
[[https://www.reddit.com/r/emacs/comments/48je3z/understanding_numbers_in_emacs_internals_int/][reddit]]
- int is a C signed integer type.
- EMACS_INT is a typedef in lisp.h - signed integer wide enough to hold an Emacs value. Either int, or long int, or long long int.
- XINT is a macro for extracting integer. Something like # define lisp_h_XINT(a) (XLI (a) >> INTTYPEBITS). And XLI is # define lisp_h_XLI(o) ((o).i).
- make_number is # define lisp_h_make_number(n) XIL ((EMACS_INT) (((EMACS_UINT) (n) << INTTYPEBITS) + Lisp_Int0))
- CHARPOS is #define CHARPOS(POS) (POS).charpos.

*** float
Floats are for storing numbers that contain fractional parts.  They can be written with an explicit decimal part, or they can be written in scientific notation to be considered a float.

All of the following numbers represent 150.0.
#+BEGIN_SRC emacs-lisp
150.0
15e1
.15e3
1500e-1
#+END_SRC

#+RESULTS:
: 150.0

*** character types

**** character
A character is a letter.  Internally elisp stores chars as an integer, so "R" has the value:

#+BEGIN_SRC emacs-lisp
?R
#+END_SRC

#+RESULTS:
: 82

You can also discover the syntax for the special characters.

#+BEGIN_SRC emacs-lisp
?\(
?\\
#+END_SRC

#+RESULTS:
: 92

#+BEGIN_SRC :exports code
  ?\a ⇒ 7                 ; control-g, ‘C-g’
  ?\b ⇒ 8                 ; backspace, <BS>, ‘C-h’
  ?\t ⇒ 9                 ; tab, <TAB>, ‘C-i’
  ?\n ⇒ 10                ; newline, ‘C-j’
  ?\v ⇒ 11                ; vertical tab, ‘C-k’
  ?\f ⇒ 12                ; formfeed character, ‘C-l’
  ?\r ⇒ 13                ; carriage return, <RET>, ‘C-m’
  ?\e ⇒ 27                ; escape character, <ESC>, ‘C-[’
  ?\s ⇒ 32                ; space character, <SPC>
  ?\\ ⇒ 92                ; backslash character, ‘\’
  ?\d ⇒ 127               ; delete character, <DEL>
#+END_SRC

#+RESULTS:

*** Boolean Values: nil and t
nil has 3 separate values.  It can mean false, a symbol, and it is the empty list =()=.

t is the boolean value true.  Technically any non-nil value will evaluate to a true value.

For example =(when 5 BODY)= will evaluate the body forms because 5 is non-nil.

#+BEGIN_SRC emacs-lisp :exports both
  (when 5 (print "hello"))

#+END_SRC

#+RESULTS:
: hello

BUT =(booleanp 5) produces no output, because 5 is not boolean.
#+BEGIN_SRC emacs-lisp  :exports both
(booleanp 5)
#+END_SRC

#+RESULTS:

*** cons
A cons cell is an object has two slots the CAR and the CDR.  Each slot can "hold" any lisp object.

(CAR . CDR)

Emacs uses cons cells to link together elements to form lists.

So the list =(a b c d)=

internally looks like =(a . (b . (c . (d . nil))))

*** associated lists
Associated lists are also alists is a lisp list, where each element is a cons cell.  So for example:

#+BEGIN_SRC emacs-lisp
  (setq fibanocci-alist
        '((0 . 1) (1 . 1) (2 . 2) (3 . 3) (4 . 5) (5 . 8)))
#+END_SRC

In the fibanocci-alist, the CARs of each element in the list, are reference points to each respective values of the list.

If you have experience with C-like languages this is like an array.

# FIXME give a better example.
#+BEGIN_SRC C
  char string[5] = "hello";
  printf ("%d", string[3]);
#+END_SRC

#+RESULTS:
: 108

*** symbol
=foo= and =Foo= are symbols
*** string

*** vector
*** hash-table
A good example of a hash-table is buffer objects like =(current-buffer)=.  Lisp tells you this when you evaluate
#+BEGIN_SRC emacs-lisp :exports both
(current-buffer)
#+END_SRC

#+RESULTS:
: #<buffer elisp.org>

The syntax #<buffer buffer-name> lets you know that that buffer is a hash table.

*** subr
*** other special types
- byte-code function
** Editing Types
* let
Let is a special lisp form that lets you define local variables.  Since all variables in lisp are global,
you need to be able to say HEY, these variables are local to this defun

Let looks like

  #+BEGIN_SRC emacs-lisp
    (let VAR-LIST BODY)
  #+END_SRC

  http://www.emacswiki.org/emacs/DynamicBindingVsLexicalBinding
  An interesting example:

  A ‘let’ expression is indeed just “syntatic sugar”, a convenience, for the corresponding ‘lambda’ form:

  #+BEGIN_SRC emacs-lisp
    (let ((a 1)
          (b 3))
      (+ a b))

  #+END_SRC

  is equivalent to:

  #+BEGIN_SRC emacs-lisp

    ((lambda (a b) (+ a b)) 1 3)

  #+END_SRC
* frames
When you create a new frame, it is set up with the "default-frame-alist".

* Functional Programming

Lisp is a functional programming language.  It's not a truly functional language like Haskell, but it is close.  Functional programming, in the simplest terms does not use loops: no for loops, no while loops, no do until loops, etc.  Instead any sort of looping construct is done via recursion.  Recursion occurs when a function calls itself to evaluate some result.  Recursive functions tend to be extremely short and remarkably easy to understand. [fn:1]  However, any recursive function can be written non-recursively.

Emacs Lisp does have loops.  This is why it is not a purely functional programming language.  BUT here is a functional method to add all the numbers less than a number n.

#+BEGIN_SRC emacs-lisp
  (defun sum-numbers-less-than-n (n)
    "sum all the numbers less than n"
    ;; if the number is 1, then return 1
    (cond ((eq n 1) 1)
    ;; if the number is greater than 1, then return the sum of n plus sum-numbers-less-than-n (- n 1)
          ((+ n (sum-numbers-less-than-n (- n 1))))))
#+END_SRC

#+RESULTS:
: sum-numbers-less-than-n

Suppose we wish to sum all the integers less than 3.  The function call would look like this

#+BEGIN_EXAMPLE
   (sum-numbers-less-than-n 3)
       |
       |
      \ /

   (+ 3 (sum-numbers-less-than-n 2))
       |
       |
      \ /

   (+ 3 (+ 2 (sum-numbers-less-than 1)))
       |
       |
      \ /

   (+ 3 (+ 2 1))
       |
       |
      \ /

  (+ 3 3)
       |
       |
      \ /
       6
#+END_EXAMPLE

Here is another recursive example that will create the nth fibonacci number.

#+BEGIN_SRC emacs-lisp
  (setq fibonacciCalls 0)
  (defun fibonacci (n)
    "generate the nth fibonacci number"
    (setq fibonacciCalls (+ 1 fibonacciCalls))
    (cond
     ((eq n 0) nil)
     ((eq n 1) 0)
     ((eq n 2) 1)
     ((+ (fibonacci (- n 1)) (fibonacci (- n 2)) ))))
#+END_SRC

#+RESULTS:
: fibonacci

(fibonacci 30)

#+BEGIN_EXAMPLE
(fibonacci 5)
  |
  |
  |
 \ /
(+ (fibonacci 4) (fibonacci 3))
  |
  |
  |
 \ /
(+ (+ (fibonacci 3) (fibonacci 2)) (+ (fibonacci 2) (fibonacci 1)))
  |
  |
  |
 \ /
(+ (+ (+ (fibonacci 2) (fibonacci 1)) (fibonacci 2)) (+ (fibonacci 2) (fibonacci 1)))
#+END_EXAMPLE

To calculate the 11th fibonacci number, it has to call fibonacci 177 times.  To calculate the 30th fibonacci number, there are
1,664,079 recursive function calls!

But maybe we can rewrite the elisp fibonacci generator, so that it doesn't have to calculate numerous fibonacci numbers multiple times.  So every time that it calculates a fibonacci number, it'll add it to a hash table.  Then when calculating another fibonacci (n) it'll check to see if that number is already in the hash table.

#+BEGIN_SRC emacs-lisp
  (defvar fibonacciCalls 0 "How many times fibonacci has been called.")
  (defvar fibonacciHashTable (make-hash-table :weakness t))
  (defun fibonacci (n)
    "generate the nth fibonacci number"
    (setq fibonacciCalls (+ 1 fibonacciCalls))
    (cond
     ((eq n 0) nil)
     ((eq n 1.0) 0)
     ((eq n 2.0) 1)
     ((if (gethash n fibonacciHashTable)
          (gethash n fibonacciHashTable)
        (puthash n (+ (fibonacci (- n 1)) (fibonacci (- n 2)) ) fibonacciHashTable)))))
#+END_SRC

#+RESULTS:
: fibonacci

(fibonacci 110)
* Strings
** Some functions

This function returns true, if the object is a string
#+BEGIN_SRC emacs-lisp
(stringp "hello")
#+END_SRC

#+RESULTS:
: t

This function will return true if the object is a string or a char.
#+BEGIN_SRC emacs-lisp
(char-or-string-p "t")
#+END_SRC

#+RESULTS:
: t

If a function returns a type looking like ~#("point" 0 5 (fontified t))~, then that is a string with some text properties.

* Lists
A list is a sequence of 0 or more elements.  You can insert or delete any of the elements in a list.

A list is made of up cons cells, which are a pair of elements.  The first is the CAR and the second is the CDR.  So

#+BEGIN_SRC emacs-lisp
'("CAR" . nil)
#+END_SRC

#+RESULTS:
| CAR |

That cons cell is a list, whose only element is the string "CAR".

In a true list, the CDR refers to the next element in the list and the last CDR in the last cons cell is the symbol 'nil'.  For example

#+BEGIN_SRC emacs-lisp
  '("This" . ("is" . ("a" . ("true" .  ("list" . nil)))))
#+END_SRC

#+RESULTS:
| This | is | a | true | list |

If the list's last CDR is not the symbol 'nil', then it is a dotted list.  Like this:

#+BEGIN_SRC emacs-lisp
'("this" . ("is" . ("a" . ("dotted" . "list"))))
#+END_SRC

#+RESULTS:
: (this is a dotted . list)

A list can also be circular, which means the last CDR refers to another item in the list.
** Functions on lists

- consp object
  returns t if the object is a cons cell
  #+BEGIN_SRC emacs-lisp
  (consp '("hello" . nil))
  #+END_SRC

  #+RESULTS:
  : t

  #+BEGIN_SRC emacs-lisp
    (consp '(nil))
  #+END_SRC

  #+RESULTS:
  : t

  #+BEGIN_SRC emacs-lisp
  (consp '("list" . ("item" . nil)))
  #+END_SRC

  #+RESULTS:
  : t

- atom object
  return true if the object is an atom.  The symbol 'nil' is an atom and a list.
  #+BEGIN_SRC emacs-lisp
  (consp '(5))
  #+END_SRC

  #+RESULTS:
  : t

- listp
  returns true if the object is a cons cell
#+BEGIN_SRC emacs-lisp
(listp '("cons" . ("cell" . nil)))
#+END_SRC

#+RESULTS:
: t

- add to list
   Here is an example of how to add an element to a list.  Add to list, only adds one element at a time.
   #+BEGIN_SRC emacs-lisp
    (add-to-list 'auto-insert-alist '(org-mode . ["default-org-file.txt"]))
    (add-to-list 'auto-insert-alist '(web-mode . ["default-web-file.txt"]))
   #+END_SRC

- push
  push is very like add-to-list.  It may even be a better version.
* Nice Elisp libraries for programming

String manipulation library
(use-package f)

String manipulation library
(use-package dash)

String manipulation library
(use-package s)
* edebug

When you begin an edebug session, you can press "?" to see a list of available commands.
* macros
A macro expands a bit of code into another bit of code.
* tweaking my .emacs.d
** how can I lazy load my init file?
*** It would be nice to show the agenda w/o having to load org-mode.

When I press "q" to exit the agenda, then org-mode and evil-mode would be loaded.
*** I should be able to lazy load projectile and helm
** I should really revamp my init-org.org file
** init-editing-utils.el is now being really slow!
* Footnotes

[fn:1] It is important to understand that in languages not optimized for recursion, recursion uses for memory than non-recursive methods.  Recursion is usually slightly slower too.


code:
#+TITLE:Emacs Cheatsheat
#+AUTHOR:Joshua Branson
#+LATEX_HEADER: \usepackage{lmodern}
#+LATEX_HEADER: \usepackage[QX]{fontenc}
#+OPTIONS: H:10 toc:nil

* Why use Emacs?

For starters, Emacs is freedom respecting software.  This is often shortened to "free software", or "libre software".  This means that one has the right to:
- 0 run the program for any reason.
- 1 the right to help yourself.
  This is the right to study the source code and change it.
- 2 The right to help your neighbor.
  This is the right to distribute unmodified copies of Emacs to your neighbor.  You could also even sell this program to your neighbor!
- 3 The right to help your community.
  This is the right to distribute your modified version of Emacs.  You could also sell your modified version!

  So Emacs grants you, the user, many freedoms that other programs lack.  Please notice that this is computing freedom.  Free software is liberty software, not necessarily gratis software.  However,  Emacs is Free software, and it can usually be obtained as gratis software.

There are also some practical reasons to use Emacs. Plenty of programmers these days use drastically simple programming editors like notepad, notepad++, nano.  These editors are "What you see is what you get" type editors, and they are frustratingly lacking in good features, and one cannot easily configure these editors.  Emacs gives you the ability to install hundreds, if not thousands of add-ons, and configure *everything* that your text editor does.

So what can Emacs do?  You can use emacs to use commands to manipulate and transpose regions of text, write in nearly every programming language imaginable, read your email, browse the internet, play games, browse local files, look at a photo gallery, stream internet music, watch online movies (coming soon), create text expandable abbreviations, clock your working hours, invoice clients, schedule your weekly agenda, syntax checking, browse documentation, commit your development changes to version control, emulate vim, all of which can be configured and tweaked emacs in numerous ways.  If that doesn't satisfy you, then you can programmatically change emacs' behavior to better suit your development workflow.

* Emacs Introduction
Emacs is a incredibly old software.  It's been around since the late 80s and early 90s, and its amazing flexibility is probably what has kept it alive this long.  Learning Emacs can be a huge challenge of its own, but if you take the time to learn Emacs, the rewards are astonishing.

\\
\\

[[~/pictures/emacs_learning_curves.png]]

(Original source appears to be Steve Rowe's blog. “A friend of mine put this together” [[https://blogs.msdn.microsoft.com/steverowe/2004/11/17/code-editor-learning-curves/][Source]]).

Since Emacs is so old, it created some terminology that modern text editors do not use.  For example Emacs has "Frames" and "Windows", "yanking" and "killing" and no other text editor uses those terms, but the best way to learn Emacs, is to dive into the terminology.  So put on your big programming pants, and follow me down the Emacs golden brick road of confusion!

So go ahead and launch Emacs. When you do, you should see a blinking rectangle.  When you start to type this rectangle moves and letters appear.  That blinking rectangle is called /point/.  When /point/ moves around the text, we say that point moves in the /buffer/.  The /buffer/ then is a region in Emacs that contains text.  Since you've just started Emacs, the whole Emacs graphical display is one /frame/.  You can also launch Emacs from the terminal and that is still just one frame of Emacs.  If you open a second instance of Emacs, you now have two frames.  Emacs also has windows.  An Emacs /window/ is the portion of Emacs that contains the buffer, or the text.  It's also possible to for a frame to have multiple windows.  You can read more about creating and deleting windows and frames in [[#frameAndWindow][Frame and Window Commands]].

* Built in Emacs Features
** Movement
One can always use the arrow keys to move point, but Emacs provides some nifty ways of moving point as well.  Pressing and holding the control key whilst hitting "f" will move point forward one character.  In Emacs lingo we call that a keychord, and it is denoted like this "C-f".  Similarly, holding and pressing the control key, then hitting "b" will move point backward one character.  That keychord is denoted as "C-b".  "C-p" will move point back to the up previous line, and "C-n" will move point down to the next line.  So the basic movement keys look like this:

#+BEGIN_EXAMPLE
                  "C-p"
                    /\
                    ||
                    ||
                    ||
                    ||
"C-b" <-------------||--------------> "C-f"
                    ||
                    ||
                    ||
                    ||
                    ||
                    ||
                    \/
                  "C-n"

#+END_EXAMPLE

** Yanking and Killing
Most text editors use the words "cutting", "pasting", and "coping" for the commands ~C-x~, ~C-v~, and ~C-c~.  Emacs used different words and different commands.  What is normally called cutting is /killing/ in Emacs.  In this way, one kills to the kill region, a section where Emacs stores killed text.  Pasting is called /yanking/.  One yanks from the kill region to past into the buffer.  Copying in Emacs is also called copying.

To kill or copy a region of text, you must first /mark/ that region or highlight it.  To begin marking a region of text one presses ~C-<space>~ or ~C-SPC~.  =<space>= and =SPC= means hitting the spacebar key.    Then you can move around point until you have marked the entire region.  To kill the region type ~C-w~.  To copy the region type ~M-w~.  M stands for the meta key, which on today's keyboard usually means the alt key.  So ~M-w~ means to press and hold the alt key, then hit the w key.  Alternatively hitting the ESC key is the same as pressing and holding the alt key.  So ~M-w~ is the same thing as ~ESC-w~.

To yank the killed or copied text back into the buffer press the ~C-y~ keychord.

** Opening, Closing, and Saving Files
When one opens and edits a file in Emacs, Emacs opens the file and puts the contents in an editable buffer.  As you edit the buffer, you only change the a region in memory.  When you type ~C-x s~ to save the current buffer, the buffer's content are saved in the file.

Since I am constantly changing multiple files, I've modified my save function to save every open file.  If you would like to do the same, you can put the following in your init file:

#+BEGIN_SRC emacs-lisp :exports code
(add-hook 'after-save-hook #'(lambda ()
                               (interactive)
                               (save-some-buffers 1)))
#+END_SRC

Emacs' default method of opening a files is ido mode, which is pronounced like "I do mode".  ~C-x C-f~ or (find-file) opens a file in Emacs.  One can press the tab key to complete a partially completed file name.  Typing "~/" means to make ido search in the user's home directory.  I personally do not enjoy using ido-mode. Instead I prefer [[#helmMode][helm-mode]].
** Frame and Window Commands
:PROPERTIES:
:CUSTOM_ID: frameAndWindow
:END:
Emacs has windows and frames, and they are probably not what you think they are.  A Frame is probably what you would think a window is.  So when you follow a link in your browser in a new window, that is a window in browser terminology.  In Emacs you can do the same thing, but it is called opening a new frame.  Go ahead and open a new frame now by typing ~C-x 5 2~.  To get back to one Emacs frame, you can either close the additional frame normally, or you can press ~C-x 5 0~.

An Emacs window then is the buffer portion of the frame that displays text.  One frame can have multiple windows.  If you type ~C-x 1~, then Emacs is only displaying one window.  Then, if you type ~C-x 2~ or ~C-x 3~, then Emacs is displaying 2 windows.  So a window then is a section of the Emacs Frame that contains text from a buffer.  To make the current frame only display one buffer, you can press ~C-x 1~.

In emacs the entire emacs program takes up a *frame*.  But emacs allows you to view two different files in the same frame, by splitting the frame in half, or in two *windows*.
  - =C-x o= Delete the selected window
  - =C-x 1= Delete all the windows except the one that currently has point
  - =C-x ^= make the selected window taller
  - =C-x {= make the selected window narrower
  - =C-x }= make the selected window wider
** Bookmarks
Emacs bookmarks are nifty ways of saving your place in a file.  If you wish to return to some obscure local or remote file, you can easily save point's current position, and return to it later.

  - =C-x r m=  sets a bookmark for you at point and it prompts you to name it
  - =C-x r b=  jumps you to a bookmark
** Learning About Emacs
Emacs comes with some amazing documentation.  ~M-x info~ will show you a list of the available documentation that comes with Emacs.  This documentation is contained in info files, which can be easily navigated via Emacs.

Emacs also has a pretty powerful help command:  ~C-h~.  ~C-h v~ will let you learn some documentation about a particular Emacs variable, while ~C-h f~ will show you documentation for an Emacs elisp function.  Every time that you hit a keychord, an equivalent Emacs function is called.  In fact ~C-h k KEYCHORD~, will tell you the documentation for the a function based on its keychord.  For example, ~C-h k C-n~ will display documentation for the function "next-line".

** Configuring Emacs with Lisp
Emacs' flexibility stems from the ability to program-matically change it via Emacs lisp.  If you dislike a particular aspect of Emacs, then you can easily change it by putting in some Emacs lisp code into your init file.  This is the file that Emacs loads every time on startup.  Any Emacs lisp functionality that you code in your init file, will be available every time you start emacs. You can find your init file by checking out the variable ~user-init-file~.  To do this press the keychord ~C-h v RET user-init-file RET~.
** Dired
Dired is the emacs file manager.  It opens a buffer displaying all your files in the specified directory.  With it you can perform numerous commands on marked files, like deleting, copying, moving, or even creating your own command.
*** Commands
  - ~n~ next line
  - ~p~ previous line
  - ~m~ mark the current file under point
  - ~% m REGEXP <RET>~  mark files based on a regular expression
*** Image Dired
You can also view images inside dired!  Mark the images you wish to view, then press C-t d (image-dired-display-thumbs). Alternatively, you could also just run the command M-x image-dired.
** Macros
A Macro is a remembered sequence of Emacs keychords that can be repeated.  This is useful to easily repeat complicated commands.  For example, I can write out the numbers 1 through a 1000 by typing a few keys.

  - ~C-x (~ begin recording a keyboard macro
  - ~C-x )~ end recording a keyboard macro
  - ~C-x e~  performs the last created keyboard macro
** Narrowing
Narrowing commands make Emacs only display portions of the buffer, whilst hidding all other regions.  While Emacs is narrowed, all entered commands only affected the displayed regions.  This means any hidden area cannot be modified while Emacs is narrowed.  This is useful if you only want a macro to execute within a specific function.  Here are the relevant narrowing commands:

~C-x n <letter>~
   - ~d~ narrow to defun
   - ~r~ widen to region
   - ~s~ narrow to a org subtree
   - ~w~ widden to the whole buffer

A much better way to use the narrowing commands is just to make emacs guess what you want whenever you press "C-x n", and that's what the following snippet does.   I recommend that you put it in your .emacs file.  The code works by figuring out which narrowing command you want to use.  If point is currently in a definition, then the buffer will be narrowed to that definition.  If point is in an org-subtree, then the buffer will be narrowed to that subtree.

You can see the blog post where I found this code snippet [[http://endlessparentheses.com/emacs-narrow-or-widen-dwim.html][here.]]

  #+BEGIN_SRC emacs-lisp
    ;; Also set up narrow dwin
    (defun narrow-or-widen-dwim (p)
      "Widen if buffer is narrowed, narrow-dwim otherwise.
    Dwim means: region, org-src-block, org-subtree, or defun,
    whichever applies first. Narrowing to org-src-block actually
    calls `org-edit-src-code'.

    With prefix P, don't widen, just narrow even if buffer is
    already narrowed."
      (interactive "P")
      (declare (interactive-only))
      (cond ((and (buffer-narrowed-p) (not p)) (widen))
            ((region-active-p)
             (narrow-to-region (region-beginning) (region-end)))
            ((derived-mode-p 'org-mode)
             ;; `org-edit-src-code' is not a real narrowing
             ;; command. Remove this first conditional if you
             ;; don't want it.
             (cond ((ignore-errors (org-edit-src-code))
                    (delete-other-windows))
                   ((ignore-errors (org-narrow-to-block) t))
                   (t (org-narrow-to-subtree))))
            ((derived-mode-p 'latex-mode)
             (LaTeX-narrow-to-environment))
            (t (narrow-to-defun))))

    ;; This line actually replaces Emacs' entire narrowing
    ;; keymap, that's how much I like this command. Only copy it
    ;; if that's what you want.
    (define-key ctl-x-map "n" #'narrow-or-widen-dwim)
  #+END_SRC
** org-mode
Emacs org-mode really deserves its own cheatsheat, so I won't go into much detail here, but I'll start you off with the basics.  Org-mode is Emacs' organizational mode, and it's pure gold!  With Org-mode I organize my daily agenda, todo lists. Parts of my emacs init files are written in it.  I use it to keep track of my working hours, with which I then invoice clients.  I use its markup to write MIME emails.  I wrote all of my documentation in it, and I keep track of my finances with it!  It truly is a remarkable emacs mode!
*** Org-mode's hierarchical structure
Org-mode lets you easily insert headings and sub headings with "C-RET".  If you press it many times, you'll have something like this:

#+BEGIN_SRC org :exports code
  ,*
  ,*
  ,*
  ,*
#+END_SRC

A line with just one "*" is a top level heading.  If it has a two "**" below it, then it now has a sub-heading.  Just like the following:
#+BEGIN_SRC org :exports code
  ,* I am a top level heading
  ,** I am a sub-heading.
#+END_SRC

You can use the tab key to show/hide any sub level headings.

Org-mode is also great for todo lists.  Hitting ~C-c C-t~ lets you mark an item as TODO or DONE.
**** Todo lists
One can easily create simple todo lists with org-mode.  In any org file ~C-RET~ inserts a "*" into the buffer.  Pressing "C-c C-t" will add the words "TODO".  It'll look like:

#+BEGIN_SRC org :exports code
  ,* TODO
#+END_SRC

Pressing ~C-c C-t~ again, will change the status to DONE.  You will end up with something looking like:

#+BEGIN_SRC org :exports code
  ,* DONE
#+END_SRC

*** org-babel
Org babel is a the best approach towards literate programming ever attempted, and it works!  Almost all programming languages treat code as the first order citizen and hides comments behind a simple syntax.  I will eventually move org babel into its own cheatsheet, but I will describe the basics for you here.  For example here is some javascript:

#+BEGIN_SRC js :exports code
  console.log("hello world")
#+END_SRC

Let's write a trivial js function the literate way

#+BEGIN_SRC org
  ,#+BEGIN_SRC js :exports code
    var i = 5;
    if (i < 6) {
      i++;
    }
    console.log (i);
  ,#+END_SRC
#+END_SRC

Literate programming might not be the best method of coding large projects, but it incredibly useful for writing your Emacs config files.  You can see an example of my org more custom-izations [[https://github.com/jbranso/.emacs.d/blob/master/lisp/init-org.org][here]].
**** Specific header arguments

http://orgmode.org/manual/Specific-header-arguments.html \\
[[info:org#Specific%20header%20arguments][info:org#Specific header arguments]] \\

- :results \\
  syntax: \\
  :results [raw | silent | value | output ] \\
  value is function mode.  It means that org-mode will use the last executed command as the value of the output. ie:

  #+BEGIN_SRC python :results value
    import time
    print("Hello, today's date is %s" % time.ctime())
    print('Two plus two is')
    return 2 + 2
  #+END_SRC

  #+RESULTS:
  : 4

  #+BEGIN_SRC sh :results output
    echo "hello world"
    echo "big cat"
    ls -lh | grep emacs.org
  #+END_SRC

  #+RESULTS:
  : hello world
  : big cat
  : -rw-r--r-- 1 joshua home  29K Jun  3 09:12 emacs.org
- :exports [code | results | node | both]
- :dir
  Specify a default directory that the code is to be run in
  :dir dir

  #+BEGIN_SRC sh :results output :dir ~/pictures
  ls
  #+END_SRC

  #+RESULTS:
  : emacs_learning_curves.png
  : emacs.png
  : gnu-logo.png
  : gnu-logo.svg
  : guix.png
  : lion.jpg
  : me.jpg
  : this-is-freedom-wallpaper.png

:dir can also specify remote directories to run code!
#+BEGIN_SRC sh :dir /USER@HOST :export code
ls
#+END_SRC
** rectangles

Emacs has a notion of rectangular blocks of text.  Essentially if you
have structural text files that looks like lots of rectangles, then
you might want to consider investing some time in learning about Emacs
rectangle features.

Suppose that you wanted to delete the "godmother" rectangle, and add
in line numbers before the "bible" rectangle.  You can do this pretty
easily with Emacs rectangles!  To begin, mark point at one corner of
the rectangle, then put point at the other end of the rectangle.
=C-x r k= kills the rectangle and =C-x r d=.

#+BEGIN_SRC text
  test  dog  godmother alpha  blue  bible  fairy
  test  dog  godmother alpha  blue  bible  fairy
  test  dog  godmother alpha  blue  bible  fairy
  test  dog  godmother alpha  blue  bible  fairy
  test  dog  godmother alpha  blue  bible  fairy
  test  dog  godmother alpha  blue  bible  fairy
#+END_SRC

After killing your text it'll look like.  Now you want to add line
numbers next to the bible recangle.  To do that, set mark at one
corner, and point at the other corner of the rectangle.  Now press
=C-x r N=
#+BEGIN_SRC text
      test  dog  alpha  blue  bible  fairy
      test  dog  alpha  blue  bible  fairy
      test  dog  alpha  blue  bible  fairy
      test  dog  alpha  blue  bible  fairy
      test  dog  alpha  blue  bible  fairy
      test  dog  alpha  blue  bible  fairy
#+END_SRC

The result is this:

#+BEGIN_SRC text
      test  dog  alpha  blue  1 bible  fairy
      test  dog  alpha  blue  2 bible  fairy
      test  dog  alpha  blue  3 bible  fairy
      test  dog  alpha  blue  4 bible  fairy
      test  dog  alpha  blue  5 bible  fairy
      test  dog  alpha  blue  6 bible  fairy
#+END_SRC

Other rectangle commands are:

- =C-x r y=  yank rectangle
- =C-x r o=  add a blank space to the left of the rectangle
- =C-x r c=  clear the rectangle by replacing its content with spaces.

** Registers
Emacs has a method of saving various states in temporary memory called
registers.  You can store point's position, window configuration,
numbers, text, buffers, rectangles, etc.

You can save current position in point via

=C-x r <SPC> R=

The "R" is the register, but you can use any character to be the
register like "1", "@", or "=", or "b".  You can also always check
what each register has via =M-x view-register=

Now you can jump to that position from any buffer via this command.
You could even kill that file, run the below command, and emacs will
attempt to re-open the buffer for you!
=C-x r j R=

You can use the register commands to save a region of text inside a
register, but helm-show-kill-ring would probably work better for most
people.

You can also use the register commands to save your window
configuration in your current frame with =C-x r w r=.  You could also
save your window configuration of all of your frames via =C-x r f r=.
The command =C-x r j r= restores your frame (or frames) configurations.

Registers can also store numbers in them.  You can add a number to the
register and then insert the number in keyboard macros.  Consider this
crazy example.  You want to add the numbers to the right of each
sentence.  As if you are assigning verse numbers:  You could store a
number 22 into the register "r" via =C-u 1 C-x r n r=.  Then you could
put point before the first sentence, start your macro via =C-x (=,
=C-c r i r= will insert the number.  =C-x r + r= increase r by one.
Then search forward to the next start of the sentence. =C-x )= ends
the macro.  =C-x e= repeats it.

#+BEGIN_SRC text
  Then He said to His disciples: "Therefore I tell you, don't worry
  about your life, what you will eat; or about the body, what you will
  wear.  For life is more than food and the body more than clothing.
  Consider the ravens: They don't sow or reap; they don't have a
  storeroom or a barn; yet God feeds them.  Aren't you worth much more
  than the birds?  Can any of you add a cubit to his height by worrying?
  If then you're not able to do even a little thing, why worry about the
  rest?"
#+END_SRC

#+BEGIN_SRC text
  1 Then He said to His disciples: "Therefore I tell you, don't worry
  about your life, what you will eat; or about the body, what you will
  wear.  2 For life is more than food and the body more than clothing.
  3 Consider the ravens: They don't sow or reap; they don't have a
  storeroom or a barn; yet God feeds them.  4 Aren't you worth much more
  than the birds?  Can any of you add a cubit to his height by worrying?
  If then you're not able to do even a little thing, why worry about the
  rest?"
#+END_SRC

* Helpful Emacs modes
** Bug Hunter
If you fairly regularly change your init file, then you will at some
  point open your init file with a broken emacs.  Bug hunter helps you
  quickly narrow down the cause of the error.  You want to make sure
  that bug-hunter is loaded early in your init, but then anytime that
  you find another issue, just run.  ~M-x bug-hunter-init-file e RET~

  https://github.com/Malabarba/elisp-bug-hunter
** Helm Mode
:PROPERTIES:
:CUSTOM_ID: helmMode
:END:
Helm mode is an interactive completetion framework that is much better than ido mode.
  C-c C-f helm-find-files

  In this mode typing "~/ manage js$"
  will display a list of files in my home directory that contain the word "manage" and end with "js"

  Typing C-l will display the files is the parent directory.

  Typing C-z when point is on a directory, will show the files in that directory.

  Helm has nth commands. Instead of typing tab to get to the action menu
  just press C-e for the 2nd action
  and C-j for the 3rd action.
  You can also bind a key to an action menu
  (define-key helm-map (kbd "<C-tab>") 'helm-select-4th-action)

*** commands
You can learn how to write your own helm commands here: [[http://wikemacs.org/wiki/How_to_write_helm_extensions][write your own helm extentions]]
  =C-c h m=  open helm-man-woman
  =C-c h h g= open helm info gnus
  =C-c h h r= open the helm-emacs-info
  =C-c h b= is helm-resume which opens up the last helm instance.
  =M-<space>= mark candidate
  =C-h m= inside a helm window will show you all of helm's keybindings

*** helm-descbinds                                                            :noexport:
** El-doc
  El-doc shows you a function's documentation in the mini-bar as you write it.  By default it works for emacs lisp extremely well.  functions.  You can add this to your init file if you'd like to try it for emacs lisp.
#+BEGIN_SRC emacs-lisp
  (add-hook 'emacs-lisp-mode-hook 'eldoc-mode)
#+END_SRC

** Yasnippet
Yasnippet is Emacs non-official but pretty much most commonly used snippet system.  You can define an abbreviation, then when expanded does what the snippet file says to do.
http://ergoemacs.org/emacs/yasnippet_templates_howto.html

*** Important Characters
- =$&= indents the line according to the major mode
- =`(some-lisp-code)`= embods lisp code
- =$0= where point will be when the snippet ends
- =$n= where n is a number ie: =$1=, =$2=, etc.  If you have multiple $3, then typing some text in one $3 will also be put in
  the other $3.
- =${n:<placeholder text>}
** Undo Tree
Undo tree is a mode that lets you visually step through the changes that you have done to the buffer.  You can step backwards and forwards through time.  In normal creation of a documentent, a user typically creates several changes that the emacs undo command is not sufficient to solve.  A document's historical content is not always linear.  Instead, during normal editing, a user can write content that the normal emacs undo command forgets about.  This is where undo tree is helpful.  Invoking ~M-x undo-tree~ shows the user a visual representation of the buffer in time.  Using the arrow keys (or conventional emacs replacements), one can step through a documentent's progression.
** Ediff
Ediff is emacs's cool way of comparing two files and merging them into one.  ~M-x ediff~ starts the process.  Emacs will prompt you to ediff two files, and then you can begin merging the files together.
*** Commands
   - =a= copies buffer a diff to buffer b
   - =b= copies buffer b diff to buffer a
   - =A= toggles readonly mode of buffer a
   - =B= toggles readonly mode of buffer b
   - =wa= save buffer a
   - =wb= save buffer b
   - =!= update the differance regions.  If you press =a= and =b= multiple times, you should probably do a =!=
   - =*= highlights the words in the diff region that differ
   - =ra= restore the diff region in buffer a
   - =rb= restore the diff region in buffer b
   - =z= suspend the ediff session
   - =s= make the merge buffer as small as possible

   When you specify files, you can edit the files as root using tramp's syntax like this.

   /su::/path/to/file
** Tramp
Tramp is an emacs extension that lets you edit remote files. To use tramp, just begin by opening a file via ~C-x C-f~ (find-file) then typing one of the following special syntaxes:

     /HOST:FILENAME
     /USER@HOST:FILENAME
     /USER@HOST#PORT:FILENAME
     /METHOD:USER@HOST:FILENAME
     /METHOD:USER@HOST#PORT:FILENAME
* Regexp
  Regular expressions are nifty ways of searching/replacing regions of text.

  Consider this example

  #+BEGIN_SRC php
    if (isadmin() || ismanager ()) {
        //some code here
    }
  #+END_SRC

  Suppose that you want to add a space between both "is" in the functions.  The following would do this:

  ~M-x dired-do-query-replace-regexp is\(admin\|manager\) RET is \1 RET~

  But let's get a basic understanding of regexps.

* Useful Elisp Libraries
- ctable https://github.com/kiwanami/emacs-ctable
- s https://github.com/magnars/s.el
- f https://github.com/rejeep/f.el
- dash [[https://github.com/magnars/dash.el]]


code:
% Created 2018-04-09 Mon 10:25
% Intended LaTeX compiler: pdflatex
\documentclass[11pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage{grffile}
\usepackage{longtable}
\usepackage{wrapfig}
\usepackage{rotating}
\usepackage[normalem]{ulem}
\usepackage{amsmath}
\usepackage{textcomp}
\usepackage{amssymb}
\usepackage{capt-of}
\usepackage{hyperref}
\usepackage{lmodern}
\usepackage[QX]{fontenc}
\author{Joshua Branson}
\date{\today}
\title{Emacs Cheatsheat}
\hypersetup{
 pdfauthor={Joshua Branson},
 pdftitle={Emacs Cheatsheat},
 pdfkeywords={},
 pdfsubject={},
 pdfcreator={Emacs 25.3.1 (Org mode 9.1.9)},
 pdflang={English}}
\begin{document}

\maketitle

\section{Why use Emacs?}
\label{sec:orgd8d41e3}

For starters, Emacs is freedom respecting software.  This is often shortened to "free software", or "libre software".  This means that one has the right to:
\begin{itemize}
\item 0 run the program for any reason.
\item 1 the right to help yourself.
This is the right to study the source code and change it.
\item 2 The right to help your neighbor.
This is the right to distribute unmodified copies of Emacs to your neighbor.  You could also even sell this program to your neighbor!
\item 3 The right to help your community.
This is the right to distribute your modified version of Emacs.  You could also sell your modified version!

So Emacs grants you, the user, many freedoms that other programs lack.  Please notice that this is computing freedom.  Free software is liberty software, not necessarily gratis software.  However,  Emacs is Free software, and it can usually be obtained as gratis software.
\end{itemize}

There are also some practical reasons to use Emacs. Plenty of programmers these days use drastically simple programming editors like notepad, notepad++, nano.  These editors are "What you see is what you get" type editors, and they are frustratingly lacking in good features, and one cannot easily configure these editors.  Emacs gives you the ability to install hundreds, if not thousands of add-ons, and configure \textbf{everything} that your text editor does.

So what can Emacs do?  You can use emacs to use commands to manipulate and transpose regions of text, write in nearly every programming language imaginable, read your email, browse the internet, play games, browse local files, look at a photo gallery, stream internet music, watch online movies (coming soon), create text expandable abbreviations, clock your working hours, invoice clients, schedule your weekly agenda, syntax checking, browse documentation, commit your development changes to version control, emulate vim, all of which can be configured and tweaked emacs in numerous ways.  If that doesn't satisfy you, then you can programmatically change emacs' behavior to better suit your development workflow.

\section{Emacs Introduction}
\label{sec:org9a8e7e3}
Emacs is a incredibly old software.  It's been around since the late 80s and early 90s, and its amazing flexibility is probably what has kept it alive this long.  Learning Emacs can be a huge challenge of its own, but if you take the time to learn Emacs, the rewards are astonishing.

\begin{center}
\includegraphics[width=.9\linewidth]{/home/joshua/pictures/emacs_learning_curves.png}
\end{center}

(Original source appears to be Steve Rowe's blog. “A friend of mine put this together” \href{https://blogs.msdn.microsoft.com/steverowe/2004/11/17/code-editor-learning-curves/}{Source}).

Since Emacs is so old, it created some terminology that modern text editors do not use.  For example Emacs has "Frames" and "Windows", "yanking" and "killing" and no other text editor uses those terms, but the best way to learn Emacs, is to dive into the terminology.  So put on your big programming pants, and follow me down the Emacs golden brick road of confusion!

So go ahead and launch Emacs. When you do, you should see a blinking rectangle.  When you start to type this rectangle moves and letters appear.  That blinking rectangle is called \emph{point}.  When \emph{point} moves around the text, we say that point moves in the \emph{buffer}.  The \emph{buffer} then is a region in Emacs that contains text.  Since you've just started Emacs, the whole Emacs graphical display is one \emph{frame}.  You can also launch Emacs from the terminal and that is still just one frame of Emacs.  If you open a second instance of Emacs, you now have two frames.  Emacs also has windows.  An Emacs \emph{window} is the portion of Emacs that contains the buffer, or the text.  It's also possible to for a frame to have multiple windows.  You can read more about creating and deleting windows and frames in \hyperref[sec:orgcd0af05]{Frame and Window Commands}.

\section{Built in Emacs Features}
\label{sec:org0ecb61a}
\subsection{Movement}
\label{sec:orgc25e6fb}
One can always use the arrow keys to move point, but Emacs provides some nifty ways of moving point as well.  Pressing and holding the control key whilst hitting "f" will move point forward one character.  In Emacs lingo we call that a keychord, and it is denoted like this "C-f".  Similarly, holding and pressing the control key, then hitting "b" will move point backward one character.  That keychord is denoted as "C-b".  "C-p" will move point back to the up previous line, and "C-n" will move point down to the next line.  So the basic movement keys look like this:

\begin{verbatim}
                  "C-p"
                    /\
                    ||
                    ||
                    ||
                    ||
"C-b" <-------------||--------------> "C-f"
                    ||
                    ||
                    ||
                    ||
                    ||
                    ||
                    \/
                  "C-n"

\end{verbatim}

\subsection{Yanking and Killing}
\label{sec:orge6ac8d8}
Most text editors use the words "cutting", "pasting", and "coping" for the commands \texttt{C-x}, \texttt{C-v}, and \texttt{C-c}.  Emacs used different words and different commands.  What is normally called cutting is \emph{killing} in Emacs.  In this way, one kills to the kill region, a section where Emacs stores killed text.  Pasting is called \emph{yanking}.  One yanks from the kill region to past into the buffer.  Copying in Emacs is also called copying.

To kill or copy a region of text, you must first \emph{mark} that region or highlight it.  To begin marking a region of text one presses \texttt{C-<space>} or \texttt{C-SPC}.  \texttt{<space>} and \texttt{SPC} means hitting the spacebar key.    Then you can move around point until you have marked the entire region.  To kill the region type \texttt{C-w}.  To copy the region type \texttt{M-w}.  M stands for the meta key, which on today's keyboard usually means the alt key.  So \texttt{M-w} means to press and hold the alt key, then hit the w key.  Alternatively hitting the ESC key is the same as pressing and holding the alt key.  So \texttt{M-w} is the same thing as \texttt{ESC-w}.

To yank the killed or copied text back into the buffer press the \texttt{C-y} keychord.

\subsection{Opening, Closing, and Saving Files}
\label{sec:orga52ca85}
When one opens and edits a file in Emacs, Emacs opens the file and puts the contents in an editable buffer.  As you edit the buffer, you only change the a region in memory.  When you type \texttt{C-x s} to save the current buffer, the buffer's content are saved in the file.

Since I am constantly changing multiple files, I've modified my save function to save every open file.  If you would like to do the same, you can put the following in your init file:

\begin{verbatim}
(add-hook 'after-save-hook #'(lambda ()
                               (interactive)
                               (save-some-buffers 1)))
\end{verbatim}

Emacs' default method of opening a files is ido mode, which is pronounced like "I do mode".  \texttt{C-x C-f} or (find-file) opens a file in Emacs.  One can press the tab key to complete a partially completed file name.  Typing "\textasciitilde{}/" means to make ido search in the user's home directory.  I personally do not enjoy using ido-mode. Instead I prefer \hyperref[sec:org2d2c82c]{helm-mode}.
\subsection{Frame and Window Commands}
\label{sec:orgcd0af05}
Emacs has windows and frames, and they are probably not what you think they are.  A Frame is probably what you would think a window is.  So when you follow a link in your browser in a new window, that is a window in browser terminology.  In Emacs you can do the same thing, but it is called opening a new frame.  Go ahead and open a new frame now by typing \texttt{C-x 5 2}.  To get back to one Emacs frame, you can either close the additional frame normally, or you can press \texttt{C-x 5 0}.

An Emacs window then is the buffer portion of the frame that displays text.  One frame can have multiple windows.  If you type \texttt{C-x 1}, then Emacs is only displaying one window.  Then, if you type \texttt{C-x 2} or \texttt{C-x 3}, then Emacs is displaying 2 windows.  So a window then is a section of the Emacs Frame that contains text from a buffer.  To make the current frame only display one buffer, you can press \texttt{C-x 1}.

In emacs the entire emacs program takes up a \textbf{frame}.  But emacs allows you to view two different files in the same frame, by splitting the frame in half, or in two \textbf{windows}.
\begin{itemize}
\item \texttt{C-x o} Delete the selected window
\item \texttt{C-x 1} Delete all the windows except the one that currently has point
\item \texttt{C-x \textasciicircum{}} make the selected window taller
\item \texttt{C-x \{} make the selected window narrower
\item \texttt{C-x \}} make the selected window wider
\end{itemize}
\subsection{Bookmarks}
\label{sec:org43ddfcc}
Emacs bookmarks are nifty ways of saving your place in a file.  If you wish to return to some obscure local or remote file, you can easily save point's current position, and return to it later.

\begin{itemize}
\item \texttt{C-x r m}  sets a bookmark for you at point and it prompts you to name it
\item \texttt{C-x r b}  jumps you to a bookmark
\end{itemize}
\subsection{Learning About Emacs}
\label{sec:org4c3ad76}
Emacs comes with some amazing documentation.  \texttt{M-x info} will show you a list of the available documentation that comes with Emacs.  This documentation is contained in info files, which can be easily navigated via Emacs.

Emacs also has a pretty powerful help command:  \texttt{C-h}.  \texttt{C-h v} will let you learn some documentation about a particular Emacs variable, while \texttt{C-h f} will show you documentation for an Emacs elisp function.  Every time that you hit a keychord, an equivalent Emacs function is called.  In fact \texttt{C-h k KEYCHORD}, will tell you the documentation for the a function based on its keychord.  For example, \texttt{C-h k C-n} will display documentation for the function "next-line".

\subsection{Configuring Emacs with Lisp}
\label{sec:orga27941d}
Emacs' flexibility stems from the ability to program-matically change it via Emacs lisp.  If you dislike a particular aspect of Emacs, then you can easily change it by putting in some Emacs lisp code into your init file.  This is the file that Emacs loads every time on startup.  Any Emacs lisp functionality that you code in your init file, will be available every time you start emacs. You can find your init file by checking out the variable \texttt{user-init-file}.  To do this press the keychord \texttt{C-h v RET user-init-file RET}.
\subsection{Dired}
\label{sec:org25797aa}
Dired is the emacs file manager.  It opens a buffer displaying all your files in the specified directory.  With it you can perform numerous commands on marked files, like deleting, copying, moving, or even creating your own command.
\subsubsection{Commands}
\label{sec:org4fee3b2}
\begin{itemize}
\item \texttt{n} next line
\item \texttt{p} previous line
\item \texttt{m} mark the current file under point
\item \texttt{\% m REGEXP <RET>}  mark files based on a regular expression
\end{itemize}
\subsubsection{Image Dired}
\label{sec:org8ebe122}
You can also view images inside dired!  Mark the images you wish to view, then press C-t d (image-dired-display-thumbs). Alternatively, you could also just run the command M-x image-dired.
\subsection{Macros}
\label{sec:orgbcfe604}
A Macro is a remembered sequence of Emacs keychords that can be repeated.  This is useful to easily repeat complicated commands.  For example, I can write out the numbers 1 through a 1000 by typing a few keys.

\begin{itemize}
\item \texttt{C-x (} begin recording a keyboard macro
\item \texttt{C-x )} end recording a keyboard macro
\item \texttt{C-x e}  performs the last created keyboard macro
\end{itemize}
\subsection{Narrowing}
\label{sec:org7ce16de}
Narrowing commands make Emacs only display portions of the buffer, whilst hidding all other regions.  While Emacs is narrowed, all entered commands only affected the displayed regions.  This means any hidden area cannot be modified while Emacs is narrowed.  This is useful if you only want a macro to execute within a specific function.  Here are the relevant narrowing commands:

\texttt{C-x n <letter>}
\begin{itemize}
\item \texttt{d} narrow to defun
\item \texttt{r} widen to region
\item \texttt{s} narrow to a org subtree
\item \texttt{w} widden to the whole buffer
\end{itemize}

A much better way to use the narrowing commands is just to make emacs guess what you want whenever you press "C-x n", and that's what the following snippet does.   I recommend that you put it in your .emacs file.  The code works by figuring out which narrowing command you want to use.  If point is currently in a definition, then the buffer will be narrowed to that definition.  If point is in an org-subtree, then the buffer will be narrowed to that subtree.

You can see the blog post where I found this code snippet \href{http://endlessparentheses.com/emacs-narrow-or-widen-dwim.html}{here.}

\begin{verbatim}
;; Also set up narrow dwin
(defun narrow-or-widen-dwim (p)
  "Widen if buffer is narrowed, narrow-dwim otherwise.
Dwim means: region, org-src-block, org-subtree, or defun,
whichever applies first. Narrowing to org-src-block actually
calls `org-edit-src-code'.

With prefix P, don't widen, just narrow even if buffer is
already narrowed."
  (interactive "P")
  (declare (interactive-only))
  (cond ((and (buffer-narrowed-p) (not p)) (widen))
        ((region-active-p)
         (narrow-to-region (region-beginning) (region-end)))
        ((derived-mode-p 'org-mode)
         ;; `org-edit-src-code' is not a real narrowing
         ;; command. Remove this first conditional if you
         ;; don't want it.
         (cond ((ignore-errors (org-edit-src-code))
                (delete-other-windows))
               ((ignore-errors (org-narrow-to-block) t))
               (t (org-narrow-to-subtree))))
        ((derived-mode-p 'latex-mode)
         (LaTeX-narrow-to-environment))
        (t (narrow-to-defun))))

;; This line actually replaces Emacs' entire narrowing
;; keymap, that's how much I like this command. Only copy it
;; if that's what you want.
(define-key ctl-x-map "n" #'narrow-or-widen-dwim)
\end{verbatim}
\subsection{org-mode}
\label{sec:orgd079476}
Emacs org-mode really deserves its own cheatsheat, so I won't go into much detail here, but I'll start you off with the basics.  Org-mode is Emacs' organizational mode, and it's pure gold!  With Org-mode I organize my daily agenda, todo lists. Parts of my emacs init files are written in it.  I use it to keep track of my working hours, with which I then invoice clients.  I use its markup to write MIME emails.  I wrote all of my documentation in it, and I keep track of my finances with it!  It truly is a remarkable emacs mode!
\subsubsection{Org-mode's hierarchical structure}
\label{sec:org137506d}
Org-mode lets you easily insert headings and sub headings with "C-RET".  If you press it many times, you'll have something like this:

\begin{verbatim}
*
*
*
*
\end{verbatim}

A line with just one "\textbf{" is a top level heading.  If it has a two "*}" below it, then it now has a sub-heading.  Just like the following:
\begin{verbatim}
* I am a top level heading
** I am a sub-heading.
\end{verbatim}

You can use the tab key to show/hide any sub level headings.

Org-mode is also great for todo lists.  Hitting \texttt{C-c C-t} lets you mark an item as TODO or DONE.
\paragraph{Todo lists}
\label{sec:org1209f0c}
One can easily create simple todo lists with org-mode.  In any org file \texttt{C-RET} inserts a "*" into the buffer.  Pressing "C-c C-t" will add the words "TODO".  It'll look like:

\begin{verbatim}
* TODO
\end{verbatim}

Pressing \texttt{C-c C-t} again, will change the status to DONE.  You will end up with something looking like:

\begin{verbatim}
* DONE
\end{verbatim}

\subsubsection{org-babel}
\label{sec:org0265631}
Org babel is a the best approach towards literate programming ever attempted, and it works!  Almost all programming languages treat code as the first order citizen and hides comments behind a simple syntax.  I will eventually move org babel into its own cheatsheet, but I will describe the basics for you here.  For example here is some javascript:

\begin{verbatim}
console.log("hello world")
\end{verbatim}

Let's write a trivial js function the literate way

\begin{verbatim}
#+BEGIN_SRC js :exports code
  var i = 5;
  if (i < 6) {
    i++;
  }
  console.log (i);
#+END_SRC
\end{verbatim}

Literate programming might not be the best method of coding large projects, but it incredibly useful for writing your Emacs config files.  You can see an example of my org more custom-izations \href{https://github.com/jbranso/.emacs.d/blob/master/lisp/init-org.org}{here}.
\paragraph{Specific header arguments}
\label{sec:org631391f}

\url{http://orgmode.org/manual/Specific-header-arguments.html} \\
\href{org\#Specific\%20header\%20arguments}{info:org\#Specific header arguments} \\

\begin{itemize}
\item :results \\
syntax: \\
:results [raw | silent | value | output ] \\
value is function mode.  It means that org-mode will use the last executed command as the value of the output. ie:

\begin{verbatim}
import time
print("Hello, today's date is %s" % time.ctime())
print('Two plus two is')
return 2 + 2
\end{verbatim}

\begin{verbatim}
echo "hello world"
echo "big cat"
ls -lh | grep emacs.org
\end{verbatim}
\item :exports [code | results | node | both]
\item :dir
Specify a default directory that the code is to be run in
:dir dir

\begin{verbatim}
ls
\end{verbatim}
\end{itemize}

:dir can also specify remote directories to run code!
\begin{verbatim}
ls
\end{verbatim}

\section{Helpful Emacs modes}
\label{sec:org406102e}
\subsection{Bug Hunter}
\label{sec:org0ea84be}
If you fairly regularly change your init file, then you will at some point open your init file with a broken emacs.  Bug hunter helps you quickly narrow down the cause of the error.  You want to make sure that bug-hunter is loaded early in your init, but then anytime that you find another issue, just run.
  \texttt{M-x bug-hunter-init-file e RET}

\url{https://github.com/Malabarba/elisp-bug-hunter}
\subsection{Helm Mode}
\label{sec:org2d2c82c}
Helm mode is an interactive completetion framework that is much better than ido mode.
  C-c C-f helm-find-files

In this mode typing "\textasciitilde{}/ manage js\$"
will display a list of files in my home directory that contain the word "manage" and end with "js"

Typing C-l will display the files is the parent directory.

Typing C-z when point is on a directory, will show the files in that directory.

Helm has nth commands. Instead of typing tab to get to the action menu
just press C-e for the 2nd action
and C-j for the 3rd action.
You can also bind a key to an action menu
(define-key helm-map (kbd "<C-tab>") 'helm-select-4th-action)

\subsubsection{commands}
\label{sec:orga94123e}
You can learn how to write your own helm commands here: \href{http://wikemacs.org/wiki/How\_to\_write\_helm\_extensions}{write your own helm extentions}
  \texttt{C-c h m}  open helm-man-woman
  \texttt{C-c h h g} open helm info gnus
  \texttt{C-c h h r} open the helm-emacs-info
  \texttt{C-c h b} is helm-resume which opens up the last helm instance.
  \texttt{M-<space>} mark candidate
  \texttt{C-h m} inside a helm window will show you all of helm's keybindings
\subsection{El-doc}
\label{sec:org98d6ece}
El-doc shows you a function's documentation in the mini-bar as you write it.  By default it works for emacs lisp extremely well.  functions.  You can add this to your init file if you'd like to try it for emacs lisp.
\begin{verbatim}
(add-hook 'emacs-lisp-mode-hook 'eldoc-mode)
\end{verbatim}

\subsection{Yasnippet}
\label{sec:org8d0d875}
Yasnippet is Emacs non-official but pretty much most commonly used snippet system.  You can define an abbreviation, then when expanded does what the snippet file says to do.
\url{http://ergoemacs.org/emacs/yasnippet\_templates\_howto.html}

\subsubsection{Important Characters}
\label{sec:org7fe9ab0}
\begin{itemize}
\item \texttt{\$\&} indents the line according to the major mode
\item \texttt{`(some-lisp-code)`} embods lisp code
\item \texttt{\$0} where point will be when the snippet ends
\item \texttt{\$n} where n is a number ie: \texttt{\$1}, \texttt{\$2}, etc.  If you have multiple \$3, then typing some text in one \$3 will also be put in
the other \$3.
\item =\$\{n:<placeholder text>\}
\end{itemize}
\subsection{Undo Tree}
\label{sec:org74fa4be}
Undo tree is a mode that lets you visually step through the changes that you have done to the buffer.  You can step backwards and forwards through time.  In normal creation of a documentent, a user typically creates several changes that the emacs undo command is not sufficient to solve.  A document's historical content is not always linear.  Instead, during normal editing, a user can write content that the normal emacs undo command forgets about.  This is where undo tree is helpful.  Invoking \texttt{M-x undo-tree} shows the user a visual representation of the buffer in time.  Using the arrow keys (or conventional emacs replacements), one can step through a documentent's progression.
\subsection{Ediff}
\label{sec:org053654a}
Ediff is emacs's cool way of comparing two files and merging them into one.  \texttt{M-x ediff} starts the process.  Emacs will prompt you to ediff two files, and then you can begin merging the files together.
\subsubsection{Commands}
\label{sec:orgd027687}
\begin{itemize}
\item \texttt{a} copies buffer a diff to buffer b
\item \texttt{b} copies buffer b diff to buffer a
\item \texttt{A} toggles readonly mode of buffer a
\item \texttt{B} toggles readonly mode of buffer b
\item \texttt{wa} save buffer a
\item \texttt{wb} save buffer b
\item \texttt{!} update the differance regions.  If you press \texttt{a} and \texttt{b} multiple times, you should probably do a \texttt{!}
\item \texttt{*} highlights the words in the diff region that differ
\item \texttt{ra} restore the diff region in buffer a
\item \texttt{rb} restore the diff region in buffer b
\item \texttt{z} suspend the ediff session
\item \texttt{s} make the merge buffer as small as possible
\end{itemize}

When you specify files, you can edit the files as root using tramp's syntax like this.

/su::/path/to/file
\subsection{Tramp}
\label{sec:orgd2d54a3}
Tramp is an emacs extension that lets you edit remote files. To use tramp, just begin by opening a file via \texttt{C-x C-f} (find-file) then typing one of the following special syntaxes:

/HOST:FILENAME
/USER@HOST:FILENAME
/USER@HOST\#PORT:FILENAME
/METHOD:USER@HOST:FILENAME
/METHOD:USER@HOST\#PORT:FILENAME
\section{Regexp}
\label{sec:orga50996f}
Regular expressions are nifty ways of searching/replacing regions of text.

Consider this example

\begin{verbatim}
if (isadmin() || ismanager ()) {
    //some code here
}
\end{verbatim}

Suppose that you want to add a space between both "is" in the functions.  The following would do this:

\texttt{M-x dired-do-query-replace-regexp is\textbackslash{}(admin\textbackslash{}|manager\textbackslash{}) RET is \textbackslash{}1 RET}

But let's get a basic understanding of regexps.

\section{Useful Elisp Libraries}
\label{sec:orgf1745b5}
\begin{itemize}
\item ctable \url{https://github.com/kiwanami/emacs-ctable}
\item s \url{https://github.com/magnars/s.el}
\item f \url{https://github.com/rejeep/f.el}
\item dash \url{https://github.com/magnars/dash.el}
\end{itemize}
\end{document}