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

* Built in Emacs Features
** Advising a named Function
[[info:elisp#Advising%20Named%20Functions][info:elisp#Advising Named Functions]]
** Bookmarks
  Emacs bookmarks are nifty ways of saving your place in a file.

  - =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
** 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
  - ~u~ unmark the current file under point
  - ~* /~ mark all directories
  - ~* *~ mark all executables
  - ~* s~ mark all files in the current sub-directory
  - ~% m REGEXP <RET>  mark files based on a regular expression
  - ~Q~ dired-do-query-replace-regexp lets you search and replace all marked files
    -  Press y, to replace the current match
    -  press ~n~ to skip the current match
    -  press ~!~ to replace all the matches in the current buffer
    -  Press ~Y~ to replace all the remaining matches in all buffers
  - how to recursively search and replace

    M-x find-name-dired: you will be prompted for a root directory and a filename pattern, but this file name pattern uses find’s version of grep.  So it does not understand “.*“.  Instead “*” is equivalent to “.*”

    Press t to "toggle mark" for all files found.

    Press Q for "Query-Replace in Files...": you will be prompted for query/substitution regexps.

    Proceed as with query-replace-regexp: SPACE to replace and move to next match, n to skip a match, etc.

      -  Press y, to replace the current match
      -  press ~n~ to not skip the current match
      -  press ~!~ to replace all the matches in the current buffer
      -  Press ~Y~ to replace all the remaining matches without question

  - M-x wdired-change-to-wdired-mode
    Makes the contents of the dired buffer editable.  Once you are done making changes type =C-c C-c=.  This saves your changes.  It is a nifty way to easily change file permissions, file names, etc.
*** image dired
lets you view images inside dired.

Mark the images you wish to view, then press C-t d (image-dired-display-thumbs)

You could also just do a M-x image-dired
** Macros
A Macro is a remembered sequence of Emacs keychords that can be repeated.  This is useful to easily repeat similar text, or delete, edit similar text.  For example, I can write out the numbers 1 through a 100, if I hit 30 keys.  I could write the numbers 1 through 1,000 by typing 31 keys!

  - ~C-x (~ begin recording a keyboard macro
  - ~C-x )~ end recording a keyboard macro
  - ~C-x e~  performs the last created keyboard macro
  - =C-x q= prompt, when you use this macro if you want to continue.  You can enter C-r to briefly step out of the macro
    and do some edits yourself, then C-M-c will allow you to continue execution of the macro.
  - ~C-x Q~  prompt the user for input during a macro.

    # FIXME specify where I found this defun
    This is not a standard emacs command; I found it on the emacs wiki.  Essentially this command tells the macro to prompt the user for input every time you call the macro.  This is useful if you have a macro that wants to write out a convoluted sequence of numbers.  The code for this is here:

    # FIXME:  WHERE DID I find this defun?? emacs wiki?
    #+BEGIN_SRC emacs-lisp
      ;; When you define a macro, you can type C-x Q to prompt the user for input.
      ;; Very helpful and cool!
      (defun my-macro-query (arg)
        "Prompt for input using minibuffer during kbd macro execution.
          With prefix argument, allows you to select what prompt string to use.
          If the input is non-empty, it is inserted at point."
        (interactive "P")
        (let* ((query (lambda () (kbd-macro-query t)))
               (prompt (if arg (read-from-minibuffer "PROMPT: ") "Input: "))
               (input (unwind-protect
                          (progn
                            (add-hook 'minibuffer-setup-hook query)
                            (read-from-minibuffer prompt))
                        (remove-hook 'minibuffer-setup-hook query))))
          (unless (string= "" input) (insert input))))

      (global-set-key "\C-xQ" #'my-macro-query)
    #+END_SRC

*** My personal keybindings                                                   :noexport:
  - `C-c r <letter>` begin recording keyboard macro
  - `C-c r <letter>` end recording keyboard macro
  - `@ <letter>` perform keyboard macro
** narrowing
  are entered via this syntax
  ~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:

  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
** Rectangles
  You can easily create a rectangle with evil mode with C-v.  Once you have a rectangle you can do these commands:

  =C-x r o= insert blank spaces to the left of the rectangle region
  =C-x r N= insert numbers all along the left of the rectangle region
** Registers
  Number Registers
  -`C-u number C-x r n r`
  Store number into register r (number-to-register).

  `C-u number C-x r + r`
  If r contains a number, increment the number in that register by number. Note that command C-x r + (increment-register) behaves differently if r contains text. See Text Registers.

  `C-x r i r`
  Insert the number from register r into the buffer.

  `C-x r i` is the same command used to insert any other sort of register contents into the buffer. `C-x r +` with no numeric argument increments the register value by 1; `C-x r n` with no numeric argument stores zero in the register.

  =C-x r s R=  save text to register R
  =M-x append-to-register R= appends text to Register R
** Selective Display
  Emacs can display portions of the buffer based on level of indentention.  This lets you get a nice overview of the file, which is quite cool.
  - =C-u n C-x $= hides rows that are indented n times
  - =C-x $=  shows all rows
** windows commands
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
  - =C-x -= shrink this window if it doesn't need that many lines.
  - =C-x += make all the windows the same height
** org-mode
*** Org-mode's syntax structure
# I can learn more here:  http://orgmode.org/worg/dev/org-syntax.html
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.

# "-----"  5 hyphens in an org document makes a horizontal rule.
**** 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
**** Tables

If a column in an org table contains <N>, where N is a number, then that table column will be that many characters wide.
|------------+-------+-----------------+----------------------|
| <10>       | <5>   | <15>            | <20>                 |
| I          | am    | a               | table                |
|            |       |                 |                      |
|------------+-------+-----------------+----------------------|
*** 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.  For example here is some javascript:

#+BEGIN_SRC js :exports code
  // initialize the variable
  var i = 5;
  if (i < 6) {
    i++;
  }
  console.log (i);
#+END_SRC

The comment "initialize the variable" comes after the comment syntax "//".  In literate programming the code portion of the file is "commented" and the comments do not hide behind a comment syntax.  Let me give you an example of the literate kind:

#+BEGIN_SRC org
  Let's write a trivial js function the literate way
  ,#+BEGIN_SRC js :exports code
    var i = 5;
    if (i < 6) {
      i++;
    }
    console.log (i);
  ,#+END_SRC
#+END_SRC

#+BEGIN_SRC calc
5 + 5
#+END_SRC

#+RESULTS:
: 10

How cool is that?
**** 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----- 1 joshua 1000  28K Mar  9 14:51 emacs.org

- :exports [code | results | node | both]
- :dir
  Specify a default directory that the code is to be run in
  :dir <dir>
*** Extending Org-mode
read about org's parser here http://orgmode.org/worg/dev/org-element-api.html
* Helpful Emacs modes
** bug-hunter
   This will help you find bugs in your init file.  Ensure that you have installed bug-hunter toward the top of your init file.  That way, when something breaks later in your init file, you can run ~M-x bug-hunter-init-file~ to find the problem.

   So your init file would look like this:

   #+BEGIN_SRC emacs-lisp :exports code
     (require 'package)
     (add-to-list 'package-archives '("gnu"   . "http://elpa.gnu.org/packages/"))
     ;;; Also use Melpa for most packages
     (add-to-list 'package-archives '("melpa" . "http://melpa.org/packages/"))
     (use-package bug-hunter :ensure t :defer t)

     ;;the rest of your init file
   #+END_SRC

  https://github.com/Malabarba/elisp-bug-hunter
** helm mode
Helm mode is a completion framework.  The default Emacs completion framework is ido-mode.  You can see ido-mode in action with ~M-x ID-find-file~.

  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 work 'manage' and end is 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)

  C-c C-u lets you view an image

  Apparently helm lets you open files externally in helm-find-files with C-c C-x (not working though)

  I can make personal actions on to run on files via eshell WOW!!!!

  C-SPC will mark files that you can perform actions on

  You can then hit copy files in the action menu, which will let you select a new destionation to copy the files. so cool!
  You can do the same thing from the action menu with rename, symlink, hardlink

  helm has support for etags
  C-h e  will search the tags file
  the above should create the TAGS file with tags, but it's not working
  find . -iregex .*\.el$ | xargs etags

  check out pcomplete extension
  https://github.com/thierryvolpiatto/pcomplete-extension

*** commands
  I can also write my own helm commands cool!
  [[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 instance that you were on
  =M-<space>= mark candidate
  =C-h m= inside a helm window will show you all of helm's keybindings

*** helm-descbinds
** evil mode
  " <letter> yy   stores the whole line into register <letter>
  " <letter> p    puts the whole line back
  =vip= select the paragraph that point is in.

  check out filters. It lets you take a line, and throw that line as a command.
  It lets you create macros that you can take a line as a command to line in bash.
  interesting
*** filters
Evil-mode lets you put the contents of the buffer through a shell command!

   You can take a line like

   hello how are you   :.!wc -w   -->   4
   hello how are you   :.!wc -c   -->   21

   5 / 6  :.!bc -l   -->  .83333333333333333333

 5    :105,109!sort --> 1
 4                    2
 3                    3
 2                    4
 1                    5

 Sort has lots of options.  I can do sort -r by reverse order, sort -k4  the 4th column, sort -n sort numerically

** El-doc
  El-doc shows you what a function in the mini-bar as you write it.  By default it works for emacs lisp extremely well.  You'll notice that my emacs-lisp-mode-hook sharp quotes eldoc-mode, which means it's using the syntax =#'eldoc-mode=.  Sharping quoting is only necessary if you are quoting named emacs lisp functions.
#+BEGIN_SRC emacs-lisp
  (add-hook 'emacs-lisp-mode-hook #'eldoc-mode)
#+END_SRC

** COMMENT Semantic

   Most emacs modes use a bunch of regular expressions to highlight source code. BUT semantic tries to make this better by
   parsing the code and creating grammar with it.
*** User commands
    - =C-c , j= prompt for a tag in the currect file and move point to it.
    - =C-c , J= prompt for a tag in any file that emacs has parsed and move point to it.
** ttd-mode let's you specify a compile command. Everytime you save a file, it will run your compile command.
  If it finds an error, it will alert you at the bottom!
** yasnippet
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
learn more about undo tree
** Paredit mode
http://danmidwood.com/content/2014/11/21/animated-paredit.html
Paredit mode is a superior way to interact with lisps.

*** slurping

slurping elongates the current sexp by pulling in the closest sexp (either forward or backward)

 #+BEGIN_SRC emacs-lisp
   ;; here I've called "C-c 0" paredit-forward-slurp-sexp
   ;; point was always on the "h" in hello
   ((hello) this is a nice little sentence)
   ((hello this) is a nice little sentence)
   ((hello this is) a nice little sentence)
   ((hello this is a) nice little sentence)
   ((hello this is a nice) little sentence)
   ((hello this is a nice little) sentence)
   ((hello this is a nice little sentence))

   ;; here I've called C-c 0 paredit-backward-slurp-sexp
   ;; which pulls in another sexp or atom into my current sexp
   ;; point was always on "e" in sentence
   (hello this is a nice little (sentence))
   (hello this is a nice (little sentence))
   (hello this is a (nice little sentence))
   (hello this is (a nice little sentence))
   (hello this (is a nice little sentence))
   (hello (this is a nice little sentence))
   ((hello this is a nice little sentence))
     #+END_SRC

*** barfing

barfing shortens the currect sexp by pushing out the closest sexp (either forward or backward)
 #+BEGIN_SRC emacs-lisp
   ;; here I've called "C-c ]" paredit-forward-barf-sexp
   ;; point was always at the "h" in hello
   ((hello this is a nice little sentence))
   ((hello this is a nice little) sentence)
   ((hello this is a nice) little sentence)
   ((hello this is a) nice little sentence)
   ((hello) this is a nice little sentence)

   ;; here I've called paredit-backward-barf-sexp
   ;; point was always at the "e" in sentence
   ((hello this is a nice little sentence))
   (hello (this is a nice little sentence))
   (hello this (is a nice little sentence))
   (hello this is (a nice little sentence))
   (hello this is a (nice little sentence))
   (hello this is a nice (little sentence))
   (hello this is a nice little (sentence))
   (hello this is a nice little sentence())

       #+END_SRC

   Paredit
   #+BEGIN_SRC emacs-lisp

   #+END_SRC

*** paredit-splice-sexp
This removes the parentheses around the current sexpression
#+BEGIN_SRC emacs-lisp
(cool (cool (cool (cool (cool)))))
(cool (cool (cool (cool (cool)))))
(cool (cool (cool (cool (cool)))))
(cool (cool (cool (cool (cool)))))
(cool (cool (cool (cool (cool)))))

#+END_SRC
** Restclient mode
  install restclient. It lets you query the server via get and post.  I can view the results via emacs!
** sunrise-commander is a dired derived mode that acts like filezilla inside emacs.
   =C= copy the current file into the other directory
   =C-u C= copy the current file/files into the other directory in a background process
** ediff
   Ediff is emacs's cool way of camparing two files.  It's very cool.
*** 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 is an emacs extension that lets you edit remote files
  it's syntax is done by pressing C-x C-f (find-file) then typing one of the following:

     /METHOD:USER@HOST:FILENAME
     /METHOD:USER@HOST#PORT:FILENAME

     method can be ftp, ssh, rlogin, or telnet

     If ssh-agent is running, Emacs uses scp.  This probably is a clue about how to use ssh without a password.
      I need to use scp
** etags
Etags is Emacs solution to creating elisp based tagging in Emacs.  It is the prefect tagging system for your init files.

The shell command Etags needs to be run to generate a TAGS file.  This looks like ~etags files~ or ~COMMAND | etags -~

The simple way to do it is, which finds certain types of files and throws them in the TAGS file.

#+BEGIN_SRC sh :results output :exports both :dir ~/.emacs.d/
find . -wholename "*lisp/[a-zA-Z-]*.el" -print | etags -
#+END_SRC

#+RESULTS:

The command ~(xref-find-definitions)~ does the rest.  I bind it like so:

~(global-set-key (kbd "C-c .") #'xref-find-definitions)~

** auto-insert mode
Auto-insert mode is a minor mode that will automatically populate a newly created file with default text.  It is bundled with Emacs.
*** Set up auto insertion
Since autoinsert mode is bundled with Emacs, enabling it is trivial.  Simply, require the autoinsert library, and when you open up an empty file, perform auto-insertion, if applicable.

#+BEGIN_SRC emacs-lisp
  (require 'autoinsert)
  (add-hook 'find-file-hook 'auto-insert)
#+END_SRC

*** auto-insert variables
- auto-insert-directory
  A string variable that specifies where to look for default file templates to insert into newly created files.

- auto-insert-mode
  Enable auto-insert mode.
Enable autoinsert mode, and do not ask me if I want to perform automatic insertion.  Just do it.

- auto-insert-query
  If the value is non-nil, then ask the user if they wish to perform auto-insertion.

- auto-insert-alist
  A list specifying text to insert by default into a new file. Elements look like (CONDITION . ACTION) or ((CONDITION . DESCRIPTION) . ACTION). CONDITION may be a regexp that must match the new file's name, or it may be a symbol that must match the major mode for this element to apply. Only the first matching element is effective. Optional DESCRIPTION is a string for filling `auto-insert-prompt'. ACTION may be a skeleton to insert (see `skeleton-insert'), an absolute file-name or one relative to `auto-insert-directory' or a function to call. ACTION may also be a vector containing several successive single actions as described above, e.g. [\"header.insert\" date-and-author-update].

#+BEGIN_SRC emacs-lisp
  (setq auto-insert-alist '((web-mode . my/yas-web-mode-snippet)
                            (org-mode . my/yas-org-snippet)))
#+END_SRC

An minimal working setup of autoinsert-mode might look like this:

#+BEGIN_SRC emacs-lisp
  (require 'autoinsert)
  (add-hook 'find-file-hook 'auto-insert)
  (setq auto-insert-directory "~/.emacs.d/auto-insert-directory/")
  (setq auto-insert-mode t
        auto-insert-query nil)

  (setq auto-insert-alist '((web-mode . my/web-mode-template-function)
                            (org-mode . "my-default-org-mode-file.org")
                            (text-mode . ["my-default-org-mode-file.org" my/finishing-function])))

#+END_SRC

*** Use Snippets instead of templates

Insertion of template files into buffers is cool, but auto-insert mode is more powerful than than.  One can expand a yasnippet into a newly created file.  For example, if you write your Emacs init file in several org-mode files in "~/.emacs.d/lisp/", then you could insert a snippet specific to your Emacs configuration.  The following does this.

#+BEGIN_SRC emacs-lisp
  (defun my/yas-elisp-init-files-snippet ()
    (interactive)
    (yas-expand-snippet (yas-lookup-snippet "<elisp-init-files")))
#+END_SRC

#+BEGIN_SRC emacs-lisp
(add-to-list 'auto-insert-alist '((".*/lisp/.*\\.org$") . [my/yas-elisp-init-files-snippet]))
#+END_SRC
*** Set up yasnippet

Inserting a predefined snippet via Emacs lisp is defined [[http://joaotavora.github.io/yasnippet/snippet-expansion.html#sec-1-6][here]].  In case you don't like reading, then just do the following:

~(yas-expand-snippet (yas-lookup-snippet "SnippetName"))~

I'm defining some functions that will automatically expand when I open a file.  Cool eh?
#+BEGIN_SRC emacs-lisp
  (defun my/yas-org-snippet ()
    (interactive)
    (yas-expand-snippet (yas-lookup-snippet "<org")))

  (defun my/yas-elisp-init-files-snippet ()
    (interactive)
    (yas-expand-snippet (yas-lookup-snippet "<elisp-init-files")))

  (defun my/yas-web-mode-snippet ()
    (interactive)
    (yas-expand-snippet (yas-lookup-snippet "<web-mode")))
#+END_SRC

** calc

Emacs calc mode is amazing!  It can do all sorts of things.  Just reading the manual will make your head swim!

To open it type M-x calc  Or C-x * c.  The latter command is cooler, because it lets you toggle calc's visibility.

*** How to solve systems of equations

First enter into Algebraic mode via "m a"

Enter a vector of equations

[42 = 7p + 7c, 126 = 40p + 21c] RET

"a S" will solve the equation.

* 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 function names.  The following will do just that.

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

  But let's get a basic understanding of regexps.

* some nice emacs add on modes/APIs that make elisp programming nice
- ctable https://github.com/kiwanami/emacs-ctable
- s https://github.com/magnars/s.el
- f https://github.com/rejeep/f.el
* Elisp macro add-function
  This is the old way of doing it. The newer was is to say add-function
* debugging weird errors
** wrong type argument errors

If you get a weird error like "wrong type argument : arrayp , nil", or "wrong type argument : stringp", it might be an issue with package.el.  The following might fix the error:

# This may copywrited!
# http://emacs.stackexchange.com/questions/17823/wrong-type-argument-arrayp-nil
- Change the address for the melpa archive to: "http://melpa.org/packages"
- Delete the ~/.emacs.d/elpa/archives/melpa/archive-contents file

 #+BEGIN_SRC sh
 rm ~/.emacs.d/elpa/archives/melpa/archive-contents
 #+END_SRC
- Run package-initialize and package-refresh-contents.

  #+BEGIN_SRC emacs-lisp
  (package-initialize)
  (package-refresh-contents)
  #+END_SRC

  #+RESULTS:
** debugging your init file
   https://github.com/Malabarba/elisp-bug-hunter.  This is SOOO helpful!
   M-x bug-hunter-init-file RET e
** Variable binding depth exceeds max-specpdl-size
   Check out this stackoverflow question:
   http://stackoverflow.com/questions/1322591/tracking-down-max-specpdl-size-errors-in-emacs

   #+BEGIN_SRC emacs-lisp
     ;;   To track the problem down, you can try this:

     (setq max-specpdl-size 5)  ; default is 1000, reduce the backtrace level
     (setq debug-on-error t)    ; now you should get a backtrace
     ;; C-h a ; in speedbar
   #+END_SRC

   #+RESULTS:
   : t

   to go back to the state that you wanted again, you can do this:

   #+BEGIN_SRC emacs-lisp
     (setq max-specpdl-size 2580)  ; default is 1000, reduce the backtrace level
     (setq debug-on-error nil)    ; now you should get a backtrace
   #+END_SRC

   #+RESULTS:
* java development

You will probably want to use eclim  https://github.com/ervandew/eclim

It turns eclipse into a server.  Emacs sends info to that server, the server responds back, and Emacs shows you code errors, code completion, etc.  It's probably the best way to do java development in Emacs.
* building Emacs
--with-cairo builds Emacs with the ability to render Emacs with Cairo.  Cairo is a 2D drawing library.  It is failing its own test suite.  So it might not be a great thing for Emacs.  And currently it doesn't work so well.

sudo ../emacs-src/configure --with-modules --enable-link-time-optimization  --with-x-toolkit=gtk3 --with-xwidgets
* connecting to a database
:PROPERTIES:
:engine: mysql
:dbhost: localhost
:dbuser: joshua
:dbpassword: password
:database: wordpress
:END:

#+BEGIN_SRC sql :results replace :exports both
SELECT user_login, display_name FROM wpHonorsCollege_users WHERE ID = 1
#+END_SRC

#+RESULTS:
| user_login | display_name |
|------------+--------------|
| joshua     | joshua       |

#+BEGIN_SRC js :results output
console.log (6 + 2)
#+END_SRC

#+RESULTS:
: 8

#+BEGIN_SRC python :results output
print (3 + 8)
#+END_SRC

#+RESULTS:
: 11

#+BEGIN_SRC emacs-lisp
(+ 2 4 )
#+END_SRC

#+RESULTS:
: 6

#+BEGIN_SRC sh :results output :exports both
ls
#+END_SRC
* debugging emacs crashes
https://www.gnu.org/software/emacs/manual/html_node/emacs/Crashing.html

Essentially you do this:

#+BEGIN_SRC sh
cd /path/to/emacs/src
gdb ./emacs
...
(gdb) run
#+END_SRC

Now you use Emacs as usual when it crashes... you run

#+BEGIN_SRC sh
(gdb) thread apply all bt

#+END_SRC
* tweaking the Gnus manual, because it is super confusing!

Make the [[info:gnus#Maildir][info:gnus#Maildir]] section readable, because it is not!

https://emacs.stackexchange.com/questions/34274/gnus-gmail-and-mbsync-do-i-need-dovecot
* get company ebdb to work.

I basically need to bind tab to company-ebdb in
* TODO getting emacs better performance on remote files
:LOGBOOK:
- State "TODO"       from              [2020-02-25 Tue 10:26]
:END:

This is really weird!

It seems that helm-mode is causing a really slow performance on opening and saving remote files.

https://emacs.stackexchange.com/questions/5359/how-can-i-troubleshoot-a-very-slow-emacs

What can cause this problem? Is it caused by Emacs or it is due to my
pc's performance? Generally what are the variables that affect Emacs'
performance?

Emacs has around 50,000 internal variables and a few thousand external
packages averaging at a few dozen variables each, you can't expect
someone to answer this in a general sense. :-)

You can see that just by looking at the comments thread under your
question. There are half a dozen different suggestions in there, all
equally valid.  What can you do to pinpoint the problem?  Option 1:
Disable modes

Start disabling those minor-modes you've listed, and see which one
solves you performance issue. I would start with smartparens,
auto-complete, line-number and font-lock, and then follow down the
list.

"I didn't have this problem yesterday" means very little, don't rely
on it too heavily. Just start disabling minor-modes until something
solves it.

If none of the minor-modes fix your issue, then start commenting out
portions of your init file until you find out which snippet was
causing this. In any case, ask a new question when you have something
more specific.  Option 2: The profiler

    Invoke M-x profiler-start RET RET (the second RET is to confirm
    cpu); Do some typing, preferably an entire paragraph or more;
    Invoke M-x profiler-report.

That will give you a buffer describing the cpu time taken by each
function. Hitting TAB on a line expands it to display the functions
inside it. Navigate this buffer until you find out which function is
taking so much CPU time.  What do I do afterwards?

Once you find the function or package or snippet causing lag you can
(in no particular order):

Ask a new question here regarding that specific minor-mode (or
function or snippet).  Report a bug to the package maintainer.  Check
the comments at the top of the package's source file. If it contains a
URL (specially on github), there's probably an issue tracker there.
Some packages offer a command like M-x PACKAGE-bug-report.  His or her
email should be at the top of the package's source file.  If it's a
built-in package, you can report it with M-x report-emacs-bug.  Even
for packages that are not built-in, you can ask for help at the
help-gnu-emacs mailing list.


code:
#+TITLE:Evil Dvorak CheatSheat
#+AUTHOR:Joshua Branson

repo_name: hwpplayers/cheatsheets

license: mit


code:
#+TITLE:Evil cheatsheet
# The next lines says that I can make 10 levels of headlines, and org will treat those headlines as how to structure the book into

# chapters, then sections, then subsections, then sub-sub-sections, etc.
#+OPTIONS: H:10

* Editing with Evil

Evil is an amazing way to edit text in emacs.  It's built on top of vim, which is an amazing text editor in its own right!  When you edit text with evil mode enabled, you have three different states that you use: normal, insert, and emacs.  Emacs state is a normal emacs session with evil commands temporarily disabled.  Insert mode lets you type characters, delete them, and use normal emacs commands.  Normal mode is like emacs' god-mode, which lets you call commands without pressing alt, meta, esc, or ctrl.  For example in normal mode =dd= lets you delete the line, on which point sits.

# I got the following info here: http://blog.carbonfive.com/2011/10/17/vim-text-objects-the-definitive-guide/
An evil command in normal mode looks like the following:

<number><command><text object or motion>

<edit command><text object>

** Some text objects

- =aw= around word.  So a including the surrounding whitespace.
- =iw= inner  word.  The word not including whitespace.
- =as= around sentence
- =is= inner  sentence
- =ip= inner  paragraph
- =ap= around paragraph
- =i"= inner  string
- =a"= around string
- =i)= inner  paren
- =a)= around paren
- =i]= inner  block
- =a]= around block
- =i}= inner  brace
- =a}= around brace
- =it= inner  tag
  To change all of the contents of an inner tag, you could do =cst(=

  hello

  ( hello )
- =at= around tag
- =i>= inner  single tag

  hello

=ci>p=

  hello

- =a>= around single tag

  CamelCaseMotion lets you change camel cased text i,w is inner word of the camel cased word, but it's not working

- =aa= around function argument
- =ia= inner  function argument
  foo (42, bar(5), 'hello')

There's a nice delete indent object, that is also not working
- =ai= around indentation (including the line above)
- =ii= inner  indentation (excluding the line above)
  #+BEGIN_SRC python
    def foo():
        if 3 > 5:
            return True
        return "foo"

  #+END_SRC

** cool commands

  find a replace text only in lines 50-100
  ~:50,100s/old/new/g~

  visually select words. u changes them into lowercase. U uppercases them.

  3fh moves point to the 3rd occurrence of "h" on the current line

  ~C-o~ in normal mode lets you jump back to the previous location

  ~o~ moves you back to the beginning of the last word
  ~O~ moves you back to the end of the last word
  ~e~ moves you forward to the beginning of the next word
  ~E~ moves you forward to the end of the next word

  ~)~ move to the next sentence
  ~(~ move to the last sentence

  ~}~ move to the next paragraph
  ~{~ move to the last paragraph

  =m<char>= mark the current position of point and store it in that mark "char".
  ~'<char>~ moves to the mark named by "<char>.

  http://keyxl.com/aaa8263/290/VIM-keyboard-shortcuts.htm
  https://www.maketecheasier.com/vim-keyboard-shortcuts-cheatsheet/

** evil-surround
Evil surround is a really cool way to surround highlighted regions of text.

*** Commands
  - =dst  deletes the surrounding html element=

text text text point text text text

    With point at the position "point" typing dst will delete the surrounding html element and change the text into:

  - =cs<char><char>= change the surrounding char to char

    "What whats point up dog?"

    With point at the position "point" typing cs,' will delete the surrounding html element and change the text into:

    'What whats point up dog?'

    With point at 'point' =cs'<q>= will change the above into

    <q>What whats point up dog?</q>

    type =cst*= to change the surrounding pair to =

    =*What whats point up dog?*=

    =Hello world!=

    =ysiw]=

    =[Hello] world!=

    =cs](=

    ={ Hello } world!=

  - =S<text object>= or =gs<text object>= in visual state will surround a text object

  - =ys<text object>= or =yS<text object>= will surround an object in normal state

*** extending
 A surround pair is a char and the char's surrounding chars.  It can look like this:

 #+BEGIN_SRC emacs-lisp
 (?* . ("*" . "*"))
 #+END_SRC

 or this:

 #+BEGIN_SRC emacs-lisp
 (?< . surround-read-tag)
 #+END_SRC

 which calls a function that lets you surround a text object with an html element.  It would be nice to have a surround for elisp function for "(" that would let you surround a text object with a lisp function!
** use bash commands in evil with the ! operator

Here is some original text:

4 I went home
3 I drank the juice
2 I bought the juice
1 I went to the store

When select the paragraph, !sort,  you get the text sorted by number

 1 I went to the store
 2 I bought the juice
 3 I drank the juice
 4 I went home

 When you select the paragraph, !sort -r, you get reverse order

  4 I went home
  3 I drank the juice
  2 I bought the juice
  1 I went to the store

  When you select a large paragraph, !sort -R, is random order

    2 I bought the juice
    2 I bought the juice
    4 I drank the juice
    5 I went to the store
    66666 nt home
    9 I went to the store
    1 I went to the store
    3 I drank the juice
    3 I drank the juice
    3 I drank the juice
    422 I bought the juice
    2391 I went to the store
    232 I bought the juice
    4 I went home
    4 I went home
    4 I went home
* delete all text in a file that doesn't have this in it!
 =:v/TEXT /d=
* replace in a file

=:<range> s/<search_string>/<replace_string>/<modifer>=

- range
  Possible values are "%" which means the whole file.
  Or <start_line>,<end_line>
- modifier determines the replace behavior
  - g "global" replace on all lines w/o prompting
  - gc "Ask for confirmation before making the replacement
  - gn ignore the place function and highlight the finds


code:
#+TITLE: FFMPEG Cheatsheet
* Convert mp4 to ogg

ffmpeg -i input.mp4 -acodec libvorbis -vcodec libtheora -f ogv output.ogv

converting all mp4's in a directory to ogg

systemctl | grep -m 1 ifplugd | awk '{print $1}' | xargs systemctl status {}
#+BEGIN_SRC sh :results output :dir ~/videos
for file in *.mp4
do
  echo "$file" "${file/.mp4/.ogg}"
  ffmpeg -i "$file" -acodec libvorbis -vcodec libtheora -f ogv "${file/.mp4/.ogg}"
done
#+END_SRC

#+RESULTS:


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

* Find
** Basic operation
~find DIRECTORY EXPRESSION~

As an example, here is the command that looks for a file with "captcha" somewhere in the name and the file name ends in "html".

#+BEGIN_SRC sh :results output :exports both :dir ~/programming/html/
find ./ -name '*captcha*html'
#+END_SRC

#+RESULTS:
: ./math-captcha.html

You can also search using some basic regexp functionality.  It uses bash's [[info:find#Shell%20Pattern%20Matching][Shell Pattern Matching]], which is

- *

  match any 0 or more characters.

- ?

  matches any 1 character

- [STRING]

  This is a character class.  It matches one character in the string.  ~[aA]~ will match both "a" and "A".  ~[a-zA-Z]~ matches all letters.  If the character class starts with the "!" in "^" it will match 1 character that is not in the string.  So ~[^0-9]~ will find any non-numbers.

#+BEGIN_SRC sh :results output :exports both
find ~/programming/html/ -name '*[gG][nN][uU]*'
#+END_SRC

#+RESULTS:
: /home/joshua/programming/html/assign-copyright-to-GNU
: /home/joshua/programming/html/my-wordpress-blog/images/GNUGuileLogo.png
: /home/joshua/programming/html/GNUSites
: /home/joshua/programming/html/my-portfolio-site/images/gnu.png

The above command was a bit cumbersome to write.  Luckily, find lets you search case insensitively.
#+BEGIN_SRC sh :results output :exports both
find ~/programming/html/ -iname '*gnu*'
#+END_SRC

#+RESULTS:
: /home/joshua/programming/html/assign-copyright-to-GNU
: /home/joshua/programming/html/my-wordpress-blog/images/GNUGuileLogo.png
: /home/joshua/programming/html/GNUSites
: /home/joshua/programming/html/my-portfolio-site/images/gnu.png

Find also lets you combine options together.
#+BEGIN_SRC sh :results output :exports both
find ~/programming/html/ -iname '*gnu*' -path '*images*'
#+END_SRC

#+RESULTS:
: /home/joshua/programming/html/my-wordpress-blog/images/GNUGuileLogo.png
: /home/joshua/programming/html/my-portfolio-site/images/gnu.png

#+BEGIN_SRC sh :results output :exports both
find ~/manuals/ -regex '.*manuals.*yas.*org'
#+END_SRC

#+RESULTS:
: /home/joshua/manuals/cheatsheets/yasnippet.org

You can also have find print like ~ls -l~ does.

#+BEGIN_SRC sh :results output :exports both
find . -name '*arch.org' -ls
#+END_SRC

#+RESULTS:
:   8260652     60 -rw-r--r--   1  joshua   home        57385 Sep 20 12:01 ./arch.org

Find also supports running commands on the files that are found.  For example here I am looking for a particular manual with the word keyboard in it.

#+BEGIN_SRC sh :results output :exports both
find ~/manuals -name '*arch*' -execdir grep 'keyboard' '{}' ';'
#+END_SRC

#+RESULTS:
: * Change the virtual console keyboard layout
: * Configuring Xorg Settings (keyboard layout)
: ** change the X keyboard layout & swap caps
:         Identifier "libinput keyboard catchall"
: * Change the virtual console keyboard layout
: * Configuring Xorg Settings (keyboard layout)
: ** change the X keyboard layout & swap caps
:         Identifier "libinput keyboard catchall"

** Find expressions
Find has several groups of expressions.
- options
- tests
- actions
- operators


code:
#+AUTHOR: Joshua Branson
#+TITLE: Firefox tips

* keysnail is an awesome firefox add-on!  It lets you emulate emacs inside firefox.  It's not as powerful as konkeror,
but it keeps firefox super fast!  And it lets you add more emacs like packages to firefox! wow!
** Change the default firefox modifier key from control to alt
So in firefox if you press C-t it opens a new tab, C-l highlights the text in your url bar.  Well that's lame behavior.
I want to have awesome keychords using emacs, and I don't want firefox's C-<char> shortcuts getting in my way.  No worries,  I'll make firefox's modifier key be alt instead of ctrl!
In about:config, I changed ui.key.accelKey from 17 to 18.  This worked!!!
https://snarfed.org/emacs_keybindings_in_firefox


code:
#+TITLE: Functional Programming
#+AUTHOR: Joshua Branson

* Functional programming in a basic sense does two things:

- there are no while or for loops
- One does not assign values.  The "=" operator is not allowed.  The
  only way a variable can get a value is an argument to a function.


code:
#+TITLE: Gnu Gawk Cheatsheet
* Introducion
  An AWK program does things to a sequence of data.  It can easily be used to certain columns of data in a text file.  More
  generally, awk looks through every line of a file, if that line matches a patters, then awk does some action on it. So an awk
  program looks like:

  PATTERN { action }
  PATTERN { action }
  ...
* awk regexp
  awk regexps are enclodes in slashes.  So =/this/= is the regexp this.
* Our first AWK program
  This program searches each line in a file, and if that line matches the regexp ~/the/~, then the second column in

  #+BEGIN_SRC awk
    awk '/the/ { print $2 }' mail-list
  #+END_SRC

  #+RESULTS:

  I can also narrow the regexp matching.  I can make it not match the whole line, but just an expression of that line

  #+BEGIN_SRC awk
    awk '$2 ~ /the/ { print $2 }' mail-list
  #+END_SRC

  #+RESULTS:


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

* GCC
* how to make faster code

The -fopt-info flag will give hints about how to make faster code.


code:
#+TITLE:GDB
#+AUTHOR:Joshua Branson
#+LATEX_HEADER: \usepackage{lmodern}
#+LATEX_HEADER: \usepackage[QX]{fontenc}

* GDB

** You can debug a C program in GDB with an argument with "set args"

gdb RET

(gdb) show args
Argument list to give program being debugged when it is started is "".

(gdb) set args -f hello.c
Argument list to give program being debugged when it is started is "hello.c".

run


code:
#+TITLE:Emacs Cheatsheat
#+AUTHOR: Joshua Branson
#+OPTIONS: H:10
* Basic Concepts
** Layers
You can stack transparent layers on top of one another in gimp to create one complete image that is looked at from above all layers.
   This lets you change one layer without affecting any other layer
*** layers dialog
    Click on Windows > dockable dialogs > Layers or C-l
    Each layer has a eye. If you see the eye, the layer is visible. Click on it, the eye will disappear and the layer will be invisible.
    Each layer has a chain. If you see a chain, on several layers, then you can do operations on all of those layers. ie:
    You can have the chain visible on 2 layers but not the 3rd layer. When you select a part of the image to cut, you cut the 1st and
    2nd layer, BUT not the 3rd.
** Channels
   There are basically 3 channels.  Blue, red, and green.  The blue channel, is what the image looks like when all you see is blue.
   This is nice, because you can easily delete or change just the blue on the image without affecting the image's red or green parts.
** To see the colors in GIMP press `O` for color picker, then open the pointer window

Window > Dockable Dialogues > Pointer

As you move your mouse over a color, the pointer window will show you the color in a variety of formats.
** To enter single window mode Windows > Single-Window-Mode
** To show the tools menu
** to delete a selection (ie: make that selection have no colors, and you'll see the grey and black of the layer)
select the area, via recangle, elipse, or magic wand, then press edit > clear
** to copy part of an image
  select the part that you want to copy, right click on it, edit > copy

  In the top of the menu bar edit > paste as new image or now layer
** You can merge layers by right clicking on any layer and clicking merge visible layers
 Entered on [2015-08-16 Sun 18:29]

   [[file:~/manuals/gimp.org]]
** You can expand the layer boundary by right clicking on the layer and clicking on layer boundary size or clicking on layer
to image size
 Entered on [2015-08-16 Sun 18:29]

   [[file:~/manuals/gimp.org]]
** PSD images opened in GMIP that have had Adjustment Layers applied to them in photoshop will not show up in GIMP.
 Entered on [2015-08-30 Sun 12:11]

   [[file:~/programming/org/gtd/gtd.org]]

** save a single layer as PNG
In the layers window, select a layer, press "C-c" (Copy), press "S-C-v" (File > create > from clipboard), "C-e" (File > Export)
** basic functionality I need to know for GIMP
    - to see the colors of various stuff, open
    Windows > dockable Dialogue > pointer

    - to measure the lengths of stuff `Shift-M`
    - to crop stuff `Shift-C`


code:
#+TITLE: Git CheatSheet
#+AUTHOR: Joshua Branson

* Introduction
  Linus Torvalds created git to remind you how stupid you are.  In fact "git" is British slang for idiot.

  It's syntax looks like git <command> [<args>]

  You can always look up help on a specific git command with man git-<command>
** Basic vocab

man gitglossary
- Repository
  A copy of a directory tree.  It has the complete history for that directory.  It has snapshots of how the project looked when you first got started up until now.  A repository can be a local repository, in which case it resides on your computer.  Or it can be a remote repository, in which case it is on someone else' computer.
- blob
  A git object representing a file.  Each blob has an associated sha-1 hash that refers to it.  With git cat-file blog "commitHash"
- branches
  A repository can store different versions of the same program.  Suppose you wish that your program had a stable version and a developmental version.  Branches give you that.  Your stable branch will probably share lots of code with your developmental branch, but they can differ.  Git lets you keep many different versions (branches) of your program.
- commit
  Once you have your repository set up, whenever you make a change to any file in the repository, git tracks those changes.  It then will let you create a new snapshot of your repository with these new changes.  One can have a program that has features a, b in commit 3aeusn4tuhsantehusn...;  when you create features c and d, one then commits those changes to the repository.  Now the latest commit is 398gasuth349ageuntsh...  Now your program has features a, b, c, d.  AND, at any point you can revisit your program when it only had features a and b.
- chain
  A list of objects that each refer to parent changes.
- cherry pick
  To pick a subset of commits and commit them to your HEAD.  If a development branch has changes that you want master to have, then you can cherry pick them.
- clean
  A working directory is clean, if corresponds to HEAD.  There is nothing to commit.
- dangling object
  An object that no other object references.
- detaches HEAD
  Your latest commit has not been attached to any branches.  If you visit a branch, then your latest changes with be lost, but you can recover them.
- dirty
  A working tree is dirty if it contains uncommitted changes.
- fast forward
  A special type of merge that where you are updating your outdated branch to someone else's updated changes.
- glob
  like regexps.
  - ~a/**/b~
    can refer to a/b/b or a/c/d/b or a/f/g/h/i/b
  - ~a/**~
    Means  match everything under a
  - **/a
    means match any directories named a
- head
  A named reference to the tip of one of your branches.
- HEAD
  HEAD refers to a specific snapshot of your repository.  It is the current checked out commit.  So when you add feature a, then commit it.  That commit is referred to as HEAD.  HEAD can be on any branch.  So your repository might say, HEAD is on branch master.
- history
  Your repository evolves over time.  Features are added, improved or removed.  All of this is tracked.  And one is always able to look back in the history of the project to see how things differed.
- hook
  git lets you run arbitrary scripts before it does certain actions.  This could check to see if you are trying to stage or commit
  your ssh key for instance and then stop you.
- octopus
  to merge more than 2 branches.
- origin
  the default upstream repository.
- merge
  Ayouge occurs when two branches are fused into one, which sometimes requires a developer to resolve incompatibilities between them.
  This can happen when you wish to update your stable branch with some of the features of a developmental branch.
- master
  This is the default branch of your repository.  Traditionally it is also the developmental branch.
  you can examine it.
- pull
  to fetch a branch and merge it into HEAD
- push
  Push your changes to a remote repository.  If the remote is an ancestor to your repository, that remote is fast forwarded to match your current HEAD.
- tree
  A git object that represents the state of a single directory.  It stores any files in the directory into blobs and any sub directories into other trees.
- working tree
  This is similar to HEAD.  When you make a commit, you commit it into your working tree.  So a working tree is the current branch and commit upon which HEAD rests.
- index file
  This represents staged and uncommitted changes to your repository.

** Basic commands

 - push your changes to a remote git repo
   git push

 - pulling your changes from a remote to a local git repo
   git pull

 - pulling changes from a remote repo and discarding your local changes
   git fetch origin
   git reset --hard origin/[master | tag | branch | commit-id ]

** common tasks
*** Removing a file from git
=git rm -r --cached /path/to/file=

Note that this DOES not delete the file.  It only makes git stop keeping track of it, and it removes it completely from the repo.
To stop git from tracking the file add =/path/to/file= into the =.gitignore= file.

*** push an existing repo to github

Create a repo on github, and don't add a license or a readme.

Go to the directory where you want to create the git repo:
=git init=
=touch README.md=
=touch license=
=git add README.md=
=git add license=
=git remote add origin https://path/to/your/github/account.git=
=git push -u origin master=

* Make git sign commits
- ~git config commit.gpgsign true~

  Make all of your future commits in a repo to be signed by default.
- ~git config --global commit.gpgsign true~

https://git-scm.com/book/en/v2/Git-Tools-Signing-Your-Work
git config --global user.signingkey 0A46826A

  make all repos on your computer sign commits by default
* Make git remember your password

#+BEGIN_SRC sh :results output
git config credential.helper store
git push -u origin master
#+END_SRC

Now the next time you push a repo, git will remember your credentials.
* merging

#+BEGIN_SRC
            G -- H wip
           /
C -- D -- E -- F master

#+END_SRC

Suppose you are on the master branch (aka HEAD is on master).  You can pull the changes from the wip branch into the master branch by typing: =git merge wip=.  The result is this:

#+BEGIN_SRC
            G -- H wip
           /      \
C -- D -- E -- F -- I master

#+END_SRC

* recovering dangling commits

Sometimes it is possible to create a commit w/o putting that commit on a branch.

You can see these dangling commits with

#+BEGIN_SRC sh :results output :exports both
git fsck
#+END_SRC

#+RESULTS:
: dangling blob 28b3db8d657b0bf9b5d1eecc1b55fe6fd0535a50
: dangling blob 68329d103af2cfc59874d6355137e3e28f388a47
: dangling blob 6f3d64581e4a5f1d602a26ce4446cc417e65e835
: dangling blob a67fc356b723c40c9704f66bb91d197723d0d7dc

If you see "dangling commit", then you have found a dangling commit that is NOT merged with your head.

~git checkout HASH~ will switch HEAD to that commit.  You can then merge HEAD with master.  OR you can create a new branch and merge master to that branch.
* removing secret files from the git history
https://help.github.com/articles/remove-sensitive-data/
* cherry-pick

Suppose I am working on a feature branch.  And master branch adds a commit.

Before I can commit my feature branch to master, I need to cherry pick the new commits from master.

So git checkout feature-branch

git cherry-pick <SHA of commit from master branch to apply to feature-branch>


code:
#+TITLE: GNU Plot Cheatsheet
* Introduction
  Gnuplot is Gnu's program to let you plot 2D and 3D graphs.  It is amazing what it can do.

  - A simple Example
    #+BEGIN_SRC gnuplot
      Title = "Hello World"
      set logscale x
      set arrow 100,5 rto 10,2
    #+END_SRC

    #+RESULTS:

    #+BEGIN_SRC gnuplot
      Title = "Absolute Value of X"
      plot abs(x)
    #+END_SRC

    #+RESULTS:

    #+BEGIN_SRC gnuplot
      plot ceil (x)
    #+END_SRC

    #+RESULTS:

    #+BEGIN_SRC gnuplot
      # set polar
      plot cos (x)
    #+END_SRC

    #+RESULTS:

    #+BEGIN_SRC gnuplot
      plot cosh (x) lt rgb "violet"
    #+END_SRC

    #+RESULTS:

* Plotting commands
  Gnuplot uses 3 different commands to create a plot: *splot* (3D graphs), *plot* (2D) graphs. *replot*

  Plot operates in rectangular or polor cordinates.  ie: set polar
  Plot lets you use each of the 4 borders as axises.  *x* (bottom), *x2* (top), *y* (left), *y2* (right)

  Splot operates in cartesian coordinates, but it can also plot surfaces with isosamples [[info:gnuplot#isosamples][info:gnuplot#isosamples]]

Plot also lets you use each of the four borders – x (bottom), x2 (top), y (left) and y2 (right) – as an independent axis. The axes option lets you choose which pair of axes a given function or data set is plotted against. A full complement of set commands exists to give you complete control over the scales and labelling of each axis. Some commands have the name of an axis built into their names, such as set xlabel. Other commands have one or more axis names as options, such as set logscale xy. Commands and options controlling the z axis have no effect on 2D graphs.

I probably want to plot via a histogram.  http://www.gnuplotting.org/manpage-gnuplot-4-6/#Q1-1-147

* Basic Syntax
  Options and accompanying parameters are separated by spaces.  Lines and coordinater are separated by commans.  Ranges are
  separated by colons and enclosed in brackets.  Text and file names are enclosed in quotation marks.

* Plotting styles
  Gnuplot comes with many different plotting styles.  Some of the popular ones are:
  - boxes
  - boxplot
  - circles
  - ellipses
  - dots
  - filledcurves
  - lines
  - polar
  - points

    In one plot you can mix different plotting styles ie:

    #+BEGIN_SRC gnuplot
      set style fill pattern
      plot sin(x) with boxes, cos(x) with lines
    #+END_SRC

    #+RESULTS:

    #+BEGIN_SRC gnuplot
      plot x**3 - 5x**2
    #+END_SRC

    #+RESULTS:

* One can plot date from a data file too
http://www.gnuplotting.org/plotting-data/

Let's say we have a data file with the contents:

# plotting_data1.dat
# X   Y
  1   2
  2   3
  3   2
  4   1

Then we could plot a line through the data like so:

# Set linestyle 1 to blue (#0060ad)
set style line 1 \
    linecolor rgb '#0060ad' \
    linetype 1 linewidth 2 \
    pointtype 7 pointsize 1.5

plot 'plotting_data1.dat' with linespoints linestyle 1

     #+PLOT: title:"Collatz" ind:1 deps:(3) type:2d with:lines set:"yrange [0:]"
     | Sede      | Max cites | H-index |
     |-----------+-----------+---------|
     | Chile     |    257.72 |   21.39 |
     | Leeds     |    165.77 |   19.68 |
     | Sao Paolo |     71.00 |   11.50 |
     | Stockholm |    134.19 |   14.33 |
     | Morelia   |    257.56 |   17.67 |


code:
#+TITLE:Gnus Cheatsheat
#+OPTIONS: H:10
#+STARTUP: overview
* Gnus Cheatsheat
** Introduction
Follow the quick start guide [[http://www.emacswiki.org/emacs/GnusGmail#toc1][here]] to get started using gnus for gmail.

This cheatsheet, should give you the basics of how to use gnus, but
the official gnus manual has more detail. Before you read the Gnus
manual, here is a word of caution.  The official Gnus manual blurs the
distinction between news and email.  News is public and email is
private. Gnus was designed to read and post questions on usenet, which
is a little like reddit.  Later on, Gnus became an email client.  If
you read a section in the manual that mentions news or nntp, then it
is probably referring to usenet, and you may safely skip that section.
If it refers to "mail", then it really means email.

GNUS has a few buffers that you need to know how to use:

+ the group buffer, which might display your inbox, sent, drafts,
  and junk folders
+ the summary buffer, which is a more detailed view of one folder.
  One summary buffer will be your inbox, which will be a long
  listing of the emails that you can examine in your inbox.
+ the article buffer, which will display one email.

Each of these buffers has various assorted commands with them.  When
you first set up gnus, you need to call gnus by executing

~M-x gnus~

As gnus starts, you should see the emacs icon.  Gnus will show you
the icon until you press

~t~

Then you should see the default group buffer.

An article is one piece of information.  it'll have a to and a from. it could be an email or an rss iteam

a backend is one way for guns to get articles
  rss backend
  backend for getting stuff from the uniq spool

*** Making Gnus faster
**** Dovecot
Currently Gnus is kind of slow at accessing your email, because it Gnus only understands how to connect to a server, like IMAP.  Meaning if you want to read your email from gmail, then Gnus has to connect to gmail and download your message.

Other mail clients (MUAs), like Thunderbird, store your email locally.  This makes searching your mail super fast.

One way to make Gnus faster is by storing your mail locally and having running a local Mail Transfer Agent, probably running an IMAP server.

One program that does this is Dovecot.  Unfortunately dovecot won't send your mail.  You'll have to configure another program, probably postfix, to send your email.  You'll also have to find a way to synchronize your local email and the remote email.  You could use offlineimap or mbsync.

**  Terminology [[info:gnus#Terminology][info:gnus#Terminology]]
*** Specific Email terminology
  + *mail* is anything delivered to me personally.  This is private.  It usually is email.
  + *reply* is to reply to mail.  My reply is just between me and the person I'm sending it to.
  + a *mail message* is a message that has been mailed.  This is usually an email.
  + *splitting* sorts your emails according to certain rules.  This is something incorrectly called mail filtering. DO NOT use GNUS to split your email.  Use the email server for this.  Gnus is super slow at splitting email.
*** Specific usenet terminology
  + *news* is public to everyone.  If I post to news, the whole world
    can see it.  News is usenet.  Notice that an email list is also
    news.
  + *follow up* is a response to a public article.  My follow up is
    public.  It is usually responding the public article that I've
    read.
  + an *article* is a message that has been posted as news
  + *message* is a mail message or a news article
  + *threading* to arrange mail, such that all mail related to the
    original article is organized by date.  This apparently does not
    work for mail.
  + *root* the first article in the thread.  And may not apply to mail.
*** Everything else
  + message is an email or article.
  + *backend* is the underlying service that Gnus accesses the messages (messages mean either mail or articles).  Since the front-end side of GNUS doesn't care where the articles come from, Gnus can can support several backends and treat them all the same.  This means that Gnus can access RSS articles, usenet articles, and email, treat them all the same and forwarded them all as email.  So I can easily read a phoronix article in Gnus and then forward that article in an email.

    Gnus supports several backends.  The most commonly used is the nnimap backend, which uses IMAP to access email.  This is how Gnus can read your hotmail or your gmail accounts.

    The list of backends are:
      + *nnimap* is the backend that access remote IMAP servers like gmail.
      + *nntp* accesses mail.  This is probably usenet.
      + *nnspool* accesses local spool news.
      + *nnml*  accesses local mail.

    Unfortunately, Gnus does not support Maildir, which is the cooler local mail format at this time.  If you wish Gnus to access local mail quickly, the best way to do it is via creating an Maildir via isync, running a local dovecot server to turn it into an local IMAP server, and then configuring Gnus to point to that.

    The types of backends are
      + *native* backends are the default backend Gnus uses to connect to servers.  Groups like this have names like:
        "gnu.emacs.gnus".  An example to connect to gmail is this:
           #+BEGIN_SRC emacs-lisp :export code

              (setq gnus-select-method
                    '(nnimap "gmail"
                             (nnimap-inbox "Google")
                             (nnimap-address "imap.gmail.com")  ; it could also be imap.googlemail.com if that's your server.
                             (nnimap-server-port "993")
                             (nnimap-stream ssl)
                             (nnimap-split-methods default)))
           #+END_SRC

      + *secondary* backends are halfway between native and foreign backends.  They also have names like:
        nntp+news.gmane.org:gmane.emacs.gnus.devel
      + *foreign* these are groups that are accessed by non-native and non-secondary select methods.  They have names like
        nntp+news.gmane.org:gmane.emacs.gnus.devel

    Honestly I do not understand the difference between the types of backends or why one should choose one over the other.
  + *server* is a machine that Gnus connects to, from which to get news and mail.
  + *select method* is the structure that specifies the Gnus backend, the server to connect to, and the virtual server settings.
  + *virual server* is the bit of code that specifies the backend and the server, which to connect.  A virtual server specifies the backend to use and the virtual server's name.  A virtual server in emails lisp that connects to gmail using the native method looks using the nnimp backend looks like:
    #+BEGIN_SRC emacs-lisp :export code

      (setq gnus-select-method
            '(nnimap "gmail"
                     (nnimap-inbox "Google")
                     (nnimap-address "imap.gmail.com")  ; it could also be imap.googlemail.com if that's your server.
                     (nnimap-server-port "993")
                     (nnimap-stream ssl)
                     (nnimap-split-methods default)))
    #+END_SRC
    The =nnimap "gmail"= is all that is required to define a virtual server, BUT the other segments like =(nnimap-inbox "Google")= are special options specific to the imap backend.
  + *solid groups* all groups listed in the group buffer are solid groups
  + head the top part of a message where info is put
  + body is part of the message
  + NOV is news overview.  They are provied by the nntp backend. Everytime gnus enters a group it asks the backend
    for the headers of all unread articles.  Most servers do this by using the NOV format, which is faster
  + *level* each group has a level
     1-5 are subscribed
     6-7 are unsubscribed
     8 are zombie
     9 are killed
     no info is stored or updated on killed groups
  + zombie groups are like killed groups
  + active file is where the server stores info on the articles they carry. This file can be large
  + a bogus group exists in the .newsrc file BUT is not known to the server aka it likely doesn't exist
  + activating is asking the server for info on a group and computing the number of unread article that group has
  + spool news servers store their files locally. Having 1 file per article is a traditonal spool
  + a server connects to and gets the mail
  + select method  specifying the backend
  + washing taking a buffer and running it through a filter, which makes it more visually pleasing
  + ephemeral most groups store data on what articles one has read.  but store nada and disapear when you exit the group
  + root the first artcile in a thread
  + parent an article that has responses
  + a child an article that responds to the parents
  + digest is a collect of mesages in a file
  + splitting is sorting your emails according to certain rules
** Find the News
*** gnu-select-method tells guns where to look for news.
   it is a list where the first element says how and the 2nd says where like
   #+BEGIN_SRC emacs-lisp
     (setq gnus-select-method '(nntp "news.somewhere.edu"))
   #+END_SRC

   gnus-select-method is your native group. Any other news that you get is a secondary group or a foreign group.

   Also note that a group is just the mail connections you have to 1 server. ie: my "news.gwene.org" is a group,
   BUT I have several different feeds from it.  I have xkcd, etc.

   Also, if you need to change servers, think before you change gnus-select-methods.  When you change gnus-select-methods,
   your .newsr file becomes worthless, and gnus no longer knows what articles you have read.

   Just read [[info:gnus#Changing%20Servers][info:gnus#Changing Servers]] before you change gnus-select-method

*** Getting mail from multiple servers

   Of course.  You can specify more sources for articles in the variable
   gnus-secondary-select-methods.  These are secondary groups. NOT foreign groups.
   Add something like this in ‘~/.gnus.el’:

   #+BEGIN_SRC emacs-lisp
     (add-to-list 'gnus-secondary-select-methods
                  '(nntp "news.yourSecondProvider.net"))
     (add-to-list 'gnus-secondary-select-methods
                  '(nntp "news.yourThirdProvider.net"))
   #+END_SRC

*** the backends
**** the nntp backend commonly gathers news articles via NNTP
**** the nnimap backend grabs mail via IMAP
**** the nnspool backend grabs mail via the spool directory.  This is local mail.
     This is the way that GNUS recommends to do it in the manual.

     Though I wonder if that is the best way to do it.  The Emacs maintainer John Wigley, uses a dovecot server for his IMAP mail.
**** the nnml backend grabs mail via a file format
**** native
   gnus will always use one method (and back end) as the "native" or default way of gathering news.
   groups from the native select method have names like gnu.emacs.gnus.
   You get this group from the gnus-select-method.
**** secondary
   a secondary backend acts like a native backend but has names like
   nnpt+news.gmane.org:gname.emacs.gnus.devel.  You get this from (setq gnus-secondary-methods)
**** foreign groups
     These groups are gotten NOT from the select elips methods.
     - =G m= make a new group, and gnus will prompt you for a address and such.

*** Start up Files
    Gnus writes information to .newsrc and .newsrc.eld.  This is a duplication.  I can safely tell GNUS to using the .newsrc
    file, and just use .newsrc.eld.

    #+BEGIN_SRC elisp
    (setq gnus-save-newsrc-file nil
    gnus-read-newsrc-file nil
    gnus-startup-file "~/.newsrc.eld"
    )
    #+END_SRC

    By default when GNUS starts it will read "~/.gnus.elc". If that file is not there, then it will check "~/.gnus.el", and finally it
    checks "~/.gnus".
** Gnus Buffers
*** The Server Buffer

The Server buffer lists what servers gnus knows how to connect to.  This is where you get your email, news, and RSS feeds.
    You can enter the server buffer by pressing ^ inside the group buffer.
**** Various Commands
     - Su | u  toggles subscription of a usenet group
*** The Group Buffer

The Group Buffer is the various folders buffer.  It looks like:

0:*nnimap+imap.fastmail.com:INBOX
0: nnimap+imap.fastmail.com:Sent
0: nnimap+imap.fastmail.com:Fun Stuff
0: nnimap+imap.fastmail.com:mailing list 1

**** Group mode line
     You can customize how you want your group buffer to display your groups.

     You can highlight how groups look based on how many unread articles are there.
**** Various commands
   - ~m~
     send a new email
   - ~n~
     go to the next group that has unread mail
   - ~p~
     go to the previous group that has unread mail
   - =P= go to the previous group
   - =N= go to the next group
   - =c= mark all unread articles in this group as read.

   - =G p/c= show the group parameters. p shows you the lisp, c shows you the customize interface.
   - ~Enter~ over an attachment when open the attachment
     On Linux you need to customize ~/.mailcap

     #+BEGIN_SRC org
       # url
       text/html; w3m -I %{charset} -T text/html; copiousoutput;

       # image viewer
       image/*; feh -F -d -S filename '%s';

       # pdf
       application/pdf; zathura '%s';
       image/pdf; zathura '%s'

       # video
       video/* ; mplayer '%s'
       audio/* ; mplayer '%s'

       # Office files.
       application/msword; soffice '%s'
       application/rtf; soffice '%s'
       text/richtext; soffice '%s'
       application/vnd.ms-excel; soffice '%s'
       application/vnd.ms-powerpoint; soffice '%s'

     #+END_SRC

   - =SPC= open this group and read the first unread article
   - =C-u 10 SPC= opens the first 10 unread articles and starts reading the first one
   - =C-u RET= opens all email
   - =A u= lists all groups whether they have unread articles or not.
   - =G S u= sort by number of unread articles
   - =S l= list the level of the current group. You are reccommeded to keep all of your groups on level 1 or 2 (low).
   - =G S v= sort by group score
   - =C= marked all articles in the buffer (even the ticked ones) as read
   - =c= mark all unticked articles as read

***** Searching
     - ~#~ mark groups
     - ~G G~ with point on a folder, will search the server side for email matching the search term that is in that folder
     or for marked groups
     - ~//~ limit the mails by subject at the summary buffer (this is done locally)
     - ~/a~ limit by author at the summary buffer (this is done locally)
     - ~/A~ limit by address From/To/Cc match a given address
     - ~/w~ to cancel the current filter
     - more info: https://www.gnu.org/software/emacs/manual/html_mono/gnus.html#Limiting

**** levels
***** - =S l= will set the level of subscribedness for the group.
      The lower the number the group, the more important it is.  All groups should be on level 1 or 2
**** browse foreign server
     - =B= lets you browse a foreign server and look for groups
       You will be asked for a select method and a server name.

     Once you are in the new server. you can do
     - =u= to toggle subscription to the group or not.
**** group topics
     You can apparently arrange your groups by topic. ie;
     [[info:gnus#Topic%20Commands][info:gnus#Topic Commands]]

     Gnus
       Emacs -- I wuw it!
          3: comp.emacs
          2: alt.religion.emacs
         Naughty Emacs
          452: alt.sex.emacs
            0: comp.talk.emacs.recovery
       Misc
          8: comp.binaries.fractals
         13: comp.sources.unix

     Just press "t" to try it out.  To make it permanent, do a

     #+BEGIN_SRC emacs-lisp
       (add-hook 'gnus-group-mode-hook 'gnus-topic-mode)
     #+END_SRC

     Once you have enabled this minor mode you can sort out your groups into topics.

     - =T n= create a new topic
     - =T TAB= indent the current topic so it becomes a subtopic on the previous topic.
     - =M TAB= unindent the current topic
     - =C-k= and =C-y= work to seamlessly to reorganize the groups by topic.
     - =RET= or =SPC= either fold a group or select a group
     - =T m= move the group to a topic
     - =T j= jump to a topic
**** What article to show by default when you press space?
[[info:gnus#Selecting%20a%20Group][     info:gnus#Selecting a Group]]

     Show the unread article with the highest score.
     (setq gnus-auto-select-first 'best)
**** group parameters
You can specify that specific groups have mail-to addresses.

[[info:gnus#Group%20Parameters][info:gnus#Group Parameters]]

gnus-parameters variable

(to-address . "bransj@hotmail.com")

You can set this via

[[info:gnus#Group%20Parameters][info:gnus#Group Parameters]]

I can also set mail to be auto-expirable.

     (setq gnus-parameters
           '(("mail\\..*"
              (gnus-show-threads nil)
              (gnus-use-scoring nil)
              (gnus-summary-line-format
               "%U%R%z%I%(%[%d:%ub%-23,23f%]%) %s\n")
              (gcc-self . t)
              (display . all))

             ("^nnimap:\\(foo.bar\\)$"
              (to-group . "\\1"))

             ("mail\\.me"
              (gnus-use-scoring t))

             ("list\\..*"
              (total-expire . t)
              (broken-reply-to . t))))
**** default sorting of groups

(setq gnus-group-sort-function 'gnus-group-sort-by-score)

OR

(setq gnus-group-sort-function 'gnus-group-sort-by-rank)
*** The Summary Buffer
The summary buffer contains all of your unread email from a email folder.  Your summary buffer could be your inbox, or your sent folder.

**** Various commands
   - ~//~ limit local mail by subject.  Limiting means to search mail locally.
   - ~/a~
   - ~C-c C-f~
    forward the current email under point

   - =SPC= scrolls the article forward by one page
   - =RET= scrolls the article backward by one page
   - =>= go to end of article
   - =<= go to beginning of article
   - =u= or =!= ticks the message.  The next time you open that folder, this message will be there EVEN if it is already read
     =d= removes the tick.
   - =W w= wraps long lines.  Which might make the message prettier.
   - =W r= Decodes  ROT13, which fixes the quotes from the microsoft products.
   - =E= makes an email as expirable.  That means that gnus will automatically delete my email for me in a week after
     I mark it expirable.
   - ~o~ over an attachment will save the file
   - =T n= go to the next article in thread
   - =T p= go to the previous article in thread
   - =C-M-S n= go to the next article in thread
   - =C-M-S p= go to the next article in thread
   - =*= mark the email as persistent.  The email won't be deleted.
   - =o= save the attached MIME part of the email
   - =K o= save the attached MIME part of the email
   - =^= show the parent of the current article
   - =M-g or C-u M-g=  fetch new or old articles.
   - =S z= kill zombie groups
   - =S L= reply to the mailing list with the content of the previous email.
   - =l= list all groups that have unread articles
   - =A != list groups with ticked articles
   - =C-c C-s= sorts the groups
   - =G S a= sort via alphbetically
   - =G S u= by number of unread emails
   - =G n= go to the next article with the same subject
   - =G p= go to the previous article with the same subject
   - =b= delete bogus groups
   - =F= find new groups and process 'em
   - =C-c C-M-x= run expire on all groups. DELETE expired articles
   - =B= browse foriegn server looking for groups
     kind of cool.
     [[info:gnus#Browse%20Foreign%20Server][info:gnus#Browse Foreign Server]]
   - =f= follow up to article w/o including article
   - =F= follow up to the article an include the article
   - =r= replies without including the original message
   - =R= replies and includes the original message.  I might want to swap those.
**** limiting commands
- =//= limit by subject
- =/ s= limit by subject
- =/ a= limit by author
**** threading commands
- =T T= toggle threading
- =T h= hide the current subthread
- =T l= lower the score of the current article
- =T i= increase the score of the current article
- =T k= kill all articles in the current thread
- =T d= descend the thread
- =T a= ascend the thread
- =T o= go to the top of the thread
**** Pick and Read.  You pick which articles you wish to read before you read them.  Very cool.
     [[info:gnus#Pick%20and%20Read][info:gnus#Pick and Read]]
**** show threading

(setq gnus-show-threads t)
**** customizing the summary buffer line
The summary buffer shows the articles in a group.  You can show all sorts of cool stuff with it via
(setq gnus-summary-line-format "%B%U%R%z%I%(%[%4L: %-23,23f%]%) %s\n")

The B option looks particularly cool.  It sorts messages via thread.

[[info:gnus#Summary%20Buffer%20Lines][info:gnus#Summary Buffer Lines]]

apparently it's possible to change the ASCII of the messages to tiny images and look super rad.
*** The Article Buffer

**** various commands

   + ~C-c C-a~ to attach a file
   + ~C-c C-m f~
     attach a file
   + ~C-c C-m C-s~
     sign the message
   + ~C-c C-m C-e~
     encrypt and sign the message
   + ~C-c C-m C-c~
     encrypt the message.  You do NOT have to enter in your password.

**** Hiding Headers
     I could customize Gnus to only show me the author of the email and the subject and hide all other headers

          (setq gnus-visible-headers "^From:\\|^Subject:")
     [[info:gnus#Hiding%20Headers][info:gnus#Hiding Headers]]

** Signing and Encrypting Email
    [[info:gnus#Signing%20and%20encrypting][info:gnus#Signing and encrypting]]
** Check section "Subscribe groups" for details.
  After subscribing the group INBOX, the INBOX could still be invisible if INBOX does not contain unread emails. That makes no
  sense for an email client (It does make sense for a stone age news reader)! Anyway, the solution is simple, `C-u 5
  gnus-group-list-all-groups` will get desired result. I assigned hotkey "o" to it. Here is my elisp code you could paste into
  your .emacs. See the Gnus Manual on Listing Groups for more details.  Or just press j

  #+BEGIN_SRC emacs-lisp
    (defun my-gnus-group-list-subscribed-groups ()
          "List all subscribed groups with or without un-read messages"
          (interactive)
          (gnus-group-list-all-groups 5)
          )
         (add-hook 'gnus-group-mode-hook
                   ;; list all the subscribed groups even they contain zero un-read messages
                   (lambda () (local-set-key "o" 'my-gnus-group-list-subscribed-groups ))
                   )
  #+END_SRC

** pressing RET on a folder will show you "smart messages" that gnus thinks are important.
  These messages are usually the unread messages.
  pressing C-u RET will show you all messages
** online documentation
http://www.xsteve.at/prg/gnus/
** things I can change/add documentation for
*** changing servers is only accurate for nntp, not nnimap or nnmaildir

[[info:gnus#Changing%20Servers][info:gnus#Changing Servers]]
*** the active file page is not relevant to maildirs
[[info:gnus#The%20Active%20File][info:gnus#The Active File]]
** things to play with my Gnus
*** group highlighting
[[info:gnus#Group%20Highlighting][info:gnus#Group Highlighting]]
** searching with RSS in gnus
https://www.emacswiki.org/emacs/NotMuch#toc1
** problems with gnus
https://www.rath.org/whats-wrong-with-gnus.html


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

* Introduction
Gnu Privacy Guard (GPG) is a tool for securing communicating with someone else.  Traditionally, every user of GPG has a public key and a private key.  In order to communicate everyone should share their public key, but you always want to keep your secret key, secret.  Your public key is like a safe.  When Bob wants to send you a message.  He uses your public key to put your message in the safe.  You then use your private key to open the safe.  Since you are the only person that has your private key, you are the only person that can read the message Bob sent to you.

Most users, probably do not need to specify a date that your key expires.  You can keep your key forever, if you so choose.

A key has at least one user ID associated with it like a name and email address, but it is possible to add more later.

A Revocation certificate, is a generated file that I should share with my friends if I lose my private key.  It will mean that my friends should stop using the old key to encrypt messages to me.  BUT if I still have the compromised private key, I can still decrypt encrypted messages that were sent with that key.

* receive gpg keys:

#+BEGIN_SRC bash
gpg --recv-keys 0x7BD63126
#+END_SRC

#+RESULTS:
* list keys
#+BEGIN_SRC sh :results output :export code
gpg --list-keys
#+END_SRC

#+RESULTS:
#+begin_example
/home/joshua/.gnupg/pubring.kbx
-------------------------------
pub   rsa2048 2016-05-17 [SC] [expires: 2017-05-17]
      AAD617F76D505C188A558D0BC8FA3D82C7B1326F
uid           [ultimate] Joshua Branson (This is my hotmail gpg key.) <bransoj@hotmail.com>
sub   rsa2048 2016-05-17 [E] [expires: 2017-05-17]
sub   rsa2048 2016-09-09 [A] [expires: 2018-09-09]

pub   rsa4096 2010-07-21 [SC] [expires: 2016-11-15]
      A4626CBAFF376039D2D7554497BA9CE761A0963B
uid           [ unknown] William John Sullivan <johns@gnu.org>
uid           [ unknown] William John Sullivan <johns@fsf.org>
uid           [ unknown] William John Sullivan <johns@debian.org>
uid           [ unknown] William John Sullivan <john@wjsullivan.net>
sub   rsa4096 2010-07-21 [E]

pub   rsa2048 2014-07-08 [SCA] [expires: 2019-07-07]
      3841FFC6AEB62783D42EE5AEAF241CE008FFB3A4
uid           [ unknown] Jeanne Rasata <jrasata@fsf.org>
sub   rsa2048 2014-07-08 [E] [expires: 2019-07-07]

pub   rsa2048 2013-02-22 [SC]
      6E4574DBAE662DF315AEDE6ED26FFEC1474FA472
uid           [ unknown] Jeann Rasata <rms-assist@gnu.org>
sub   rsa2048 2013-02-22 [E]

#+end_example

My userID is then C7B1326F
* Export your public gpg key
#+BEGIN_SRC sh :results output :export code
gpg --armor --export bransoj@hotmail.com > bransoj.gpg
cat bransoj.gpg
#+END_SRC

#+RESULTS:
#+begin_example
-----BEGIN PGP PUBLIC KEY BLOCK-----

mQENBFc7GcUBCAC4MLbnQJ2Hjh3xBRcTupmJuzFJzu8zx6bb0GBzucg+gDZ0PES9
pZWW7vekeoqkoFImeo/eaEzYSzqCdFb/p02mWEjpP4+DPv2qRYbDg3xGdvlxkPqi
MmdiOCRaAdEBKtAaPJdm1yio2I5zVqK0fBumdrL47UTpeh4IZF1h+srKZNY7Ylaq
E8FhjTVJLAaVbcC84xzAP+pJSHwu8jR/xJEo/p/GCMFd1TiOKEl+7imogd1iJRNC
1pRS52CAqYO5GPUOu5bLMC0O3npiJCcebJ84oaIwu7YPjsUv/ZXKbw2Bw8Sg9ZZD
uUASdB8K2FFidJByV3q5UB58Tv1JSAg5xEepABEBAAG0Qkpvc2h1YSBCcmFuc29u
IChUaGlzIGlzIG15IGhvdG1haWwgZ3BnIGtleS4pIDxicmFuc29qQGhvdG1haWwu
Y29tPokBPQQTAQgAJwUCVzsZxQIbAwUJAeEzgAULCQgHAgYVCAkKCwIEFgIDAQIe
AQIXgAAKCRDI+j2Cx7Eyb0LyCACw2SR+pavE3RzSo86zy/mRFLn+UkpmYXqBp8sB
j24ogRs2kI0VeM1kS1tKZ6h9IsWFuiQHtCCgD17mGmxZ51Uvx27aWfzlN91gmY4C
DpZVX3PAZ4h5Q2jWNhkZE1K3U8GBzApYnwN0uJ5CT+oiLweCOQJqwDdKfalAwoH+
/eTbezip8DTD5hgaBu3day6LyJ6ajDIYL6jn/uUcXhGrykBUjqfe3rpeIRSjIlAt
PwzBWlceRAYGgpUi6g5SBpjG6vP53X91U3fN7qqy6YNzLW3iGa9a/p7AsTBZFLgp
E0VtN42uOJ2Vc8UhD3wdeYqf6HxUTpDoviDoc608SJuALUK8uQENBFc7GcUBCADE
a5JosRi4VX4VYUdzXDhgoCRV0kl6TU304+D6Q27/k+Yy99txwClD3ug9JeLMiZ0L
e2Sm/jkmPiivW68yV3Ipt800n8YB4SeEWJcOZH5E8MQyKX1DxAS28kG6XTU3CiCY
gQDhWKcTkdptA74pq836EypBw7zwK/qKI66PefHccAKRe5ckNzhmuOgHaD47wtzC
mxiKaTft883S8lidxVgbTa0pY22A1S8HlCxg56kStg2OHhwyPNSoasZJ4wkt95Ii
xQS6qH7uNfTxQmwVslY9uSgO7H5CTMQJHBUYlqWSNmAvD1cW7W7yPC1JKE1Y2Lbt
Fg859J7Z5kmMzCnXfVeNABEBAAGJASUEGAEIAA8FAlc7GcUCGwwFCQHhM4AACgkQ
yPo9gsexMm8Uegf/f3mcwyeCcBZB/i0yxqkjcHky8OL77lUyIznTXhngd6xxh/kz
OId4ixZ17LQSJfDINMZYMvC2YmlM8Q+RPcrVmtVGHlzGlDYziOb0GOX6ZZgi+uuI
pbRi6mXMXLBjdJ8Az6JhnZTEbcLX36C7PrsYy6Vf/mkJWQ9dXiiWStZFkwH+jhux
/5iEyzif4ufk2gMfaWE7pGO3PLewQyZYnvVBPmlb2EM7UbEXbKGjh0d0rwmljXBp
Nm93zwF0DIhmaAVOGNlteScjCo07LPcAcb3RZJu9MM3vlnOuRWDJGYEkkQzoOAOt
WARlwOYBOT7hp5sQKnwg2EKH+MF6yMu3HHso2rkBDQRX0gAxAQgA2f3oUu2g82tS
aGdq7/KMyM7cDGkM5mcUVsmKSyesPqlw7/3ZhPEzly1ehvzDt3KC5s6XtSCgnFEw
LH7akFG8ssmPnsB/fN7KZQiegK5acd5DcukznFBFWYOyYNi5Fwzu/y92TDAoQj/e
/QmYdYy6MG8HzD4h/OEkrUz7ChUE1iJrSVNrIGzPLqK2HeXf0h/agwGvG/bXf7JB
VmHKB5+gUFxh+pqP83bRniGyP3/Rb5YajFqAC/HCKUoJbGWrcpJyijcEi14pIZiv
MkMemtKSEnXyptMfnC6pWWPAZwoHpM7eQ0i/sA5z15C8XczBYaXEZmAJAgPy3NZd
nWPQ/voiLQARAQABiQElBBgBCAAPBQJX0gAxAhsgBQkDwmcAAAoJEMj6PYLHsTJv
IbYH/jHTL/FdzHKSA0REET3DDwrqbxFJbLQyXzKMipwIfhPo2kVhT6CB+pLJAurN
zVA9rm1IggAsdgeeDmxxdA3xHuouJ+vIfmKxqrrmJ/M7idyobbMM71isofR9eBKY
ZBy8TuId1UdyNG7g7DR4cfm3TrhU1dmfOt0Y9WtDu1OokWjhRjrHAVu/6m58r3G1
8RA6g26cbp7XG2Uxd7S43oIe0uYeGYGJTwKRbxFPPV55rrhUAlJCOW6o3xKUVmKu
u33TivQ1ySuHr4qMS64OfIYjYARDzIXKW+NZivwGe0x7IBwTleqanzip6s0VYTiC
8GqzXhfl9G+eoq42U15KQskVilg=
=34nH
-----END PGP PUBLIC KEY BLOCK-----
#+end_example
* import a public key
#+BEGIN_SRC sh :results output :exports both
gpg --import bransoj.gpg
#+END_SRC

#+RESULTS:

Once a key has been imported, you should validate it.

#+BEGIN_SRC sh :results output :exports both
gpg --edit-key johns@gnu.org
fpr
#+END_SRC

#+RESULTS:

This will output the key's fingerprint.  If johns@gnu.org if with you, he can tell you if the fingerprint is correct.  If it is,
then run the command ~sign~.

The command ~check~ will show you the signature that you added to the key.
* encrypting and decrypting documents

The basic scenario for two users to share a document is like this:

#+BEGIN_SRC emacs-lisp
gpg --output somefile.gpg --encrypt --recipient someEmail@hotmail.com somefile.txt
#+END_SRC

But you can also encrypt a document so 2 users can read it.  Like so:

#+BEGIN_SRC emacs-lisp
gpg --output somefile.gpg --encrypt --recipient someEmail@hotmail.com --recipient bransoj@hotmail.com somefile.txt
#+END_SRC

For every person that you need to encrypt a document, you just add a ~--recipient email~

To decrypt a document, use the following command

#+BEGIN_SRC emacs-lisp
gpg --decrypt --output file.txt doc.gpg
#+END_SRC
** symmetric encryption
* change default key...I've no idea how to do this.

My stupid hotmail key is so annoying.  It no longer works, but I have old documents that use it. grrr.

Basically I just made my hotmail key not expire ever.
* Making and validating signatures
A signature is a way to proving that a document has not been modified.  If I encrypt a document to you, I should also send a document.sig file that acts like a signature.  The signature, if it can be verified, proves that I sent the document, and whilst it was traveling to you, it has not changed.

BUT what if someone changes the document and the signature whilst it is being sent to someone?
* learn some gpg from this blog
https://sanctum.geek.nz/arabesque/series/gnu-linux-crypto/
https://riseup.net/en/security/message-security/openpgp/gpg-best-practices

https://www.reddit.com/r/GPGpractice/

* I can learn a lot of gpg from this gnome site
https://help.gnome.org/users/seahorse/stable/index.html.en

* create a new gpg key:

To do this: you need to create a gpg conf file. and ensure pinentry is
installed.

#+BEGIN_SRC sh
  cat /home/joshua/.gnupg/gpg-agent.conf
#+END_SRC

#+RESULTS:
default-cache-ttl 28800
# 8 hours
pinentry-program /home/joshua/.guix-profile/bin/pinentry-curses
allow-loopback-pinentry
# enable ssh support
enable-ssh-support

* https://www.ryanlue.com/posts/2017-06-29-gpg-for-ssh-auth

* kill gpg agent
gpgconf --kill gpg-agent

* using gpg for ssh authentication linode
https://linode.com/docs/security/authentication/gpg-key-for-ssh-authentication/

good blog post too.
https://www.ryanlue.com/posts/2017-06-29-gpg-for-ssh-auth

You need to import the gpg key into ssh.

    vm2-$ gpg  --export-options export-reset-subkey-passwd,export-minimal,no-export-attributes --export-secret-subkeys 20EE3BF8 | openpgp2ssh 20EE3BF8 >  '.anishn'

#+BEGIN_SRC sh
  gpg -k --with-keygrip
#+END_SRC

#+RESULTS:
joshua@dobby ~/.gnupg$ gpg -k --with-keygrip
/home/joshua/.gnupg/pubring.kbx
-------------------------------
pub   rsa4096 2019-10-05 [SC]
      /secret/
      Keygrip = /secret/
uid           [ultimate] Joshua Branson <jbranso@dismail.de>
sub   rsa4096 2019-10-05 [E]
      Keygrip = 5B85A72E18EAFCD69C212494B1DC92BE77A5CB62

The keygrip is "5B85A72E1..."

Somehow to need to import the gpg key into ssh-agent.

#+BEGIN_SRC sh
echo 5B85A72E18EAFCD69C212494B1DC92BE77A5CB62 > ~/.gnupg/sshcontrol
#+END_SRC

When you have done so, verify that the key is there via:

ssh-add -L, which will list all of your keys.

Now you can add your gpg keys to your remote server with

#+BEGIN_SRC sh
  ssh-copy-id root@<ip address>
#+END_SRC

This will copy your gpg key to your remote server.  If the command
succeeds, then you can then use your ssh key log into the remote server!

* how to determine if gpg-agent is running:

=gpg-agent=

it will tell you.
* starting ssh agent
https://www.ssh.com/ssh/agent

* this seems like a good guide for getting gpg-agent to work as ssh-agent
https://incenp.org/notes/2014/gnupg-for-ssh-authentication.html
* vocab

    sec The master/primary secret key. Contains ( key size, keyid, creation date, expiration date and fingerprint)
    ssb Secret Subkeys. These can be your sub signing key, encryption key or authentication key. Users can have multiple subkeys
    uid User information associated with the secret key. You can have multiple uids.
    pub The following is public key Information
    sec# # after sec means that your secret key is missing from the machine contains a refrence
    ssb> > after ssb means that your subkeys are not the machine. Instead they are on a smartcard (YubiKube)
    sub your public subkey info.
* archlinux.org

https://wiki.archlinux.org/index.php/GnuPG#gpg-agent

#+BEGIN_SRC sh
  cat ~/.pam_environment
#+END_SRC

#+RESULTS:

#+BEGIN_SRC shell
ls
#+END_SRC

#+RESULTS:
* using gpg-agent to authenticate to servers with gpg keys

<mbakke> joshuaBPMan: so you have --enable-ssh-support in gpg-agent.conf, and
         "export SSH_AUTH_SOCK=$XDG_RUNTIME_DIR/gnupg/S.gpg-agent.ssh" in
         .bashrc?  [18:26]
* it may not be a good idea to use GPG for server authentication

ssh keys are used for server authentication.

gpg keys are used for signing commits and sending emails.


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

* Grub
** Booting an OS From Grub
*** multiboot

 boot to an installed GNU/Linux distro on your machine

#+BEGIN_EXAMPLE
set root=(hd0,PartionNumberWhere/BootIs)
linux /boot/vmlinuz-linux-libre root=/dev/sdaPartionNumberWhereRootIs
initrd /boot/initramfs-linux-libre.img
boot
#+END_EXAMPLE

For me this looks like:

#+BEGIN_EXAMPLE
set root=(hd0,1)
linux /boot/vmlinuz-linux-libre root=/dev/sda1
initrd /boot/initramfs-linux-libre.img
boot
#+END_EXAMPLE
*** chainloading

As soon as you see the grub command line press the "c" key. You'll be dropped into a grub shell.  You'll know you're there, because you'll see

#+BEGIN_EXAMPLE
grub >
#+END_EXAMPLE

Now, this is what you type

=set root=(=

Now press TAB and grub will give you some options.  Grub will expand what you wrote into

#+BEGIN_EXAMPLE
set root=(hd
#+END_EXAMPLE

Grub will then tell you to either press 1 or 0.  hd0 is your hard drive.  You don't want that.  So type

#+BEGIN_EXAMPLE
set root=(hd1)
#+END_EXAMPLE

Now type

#+BEGIN_EXAMPLE
chainloader +1
#+END_EXAMPLE

That will essentially tell the grub that is on your harddisk, to chainload to the usb.  This means that the usb stick has grub (or some other similiar software on it).  So grub won't try to find a bootable kernel on the usb stick.  Instead, your harddrive's grub will hand over controll to the usb stick's grub.

#+BEGIN_EXAMPLE
boot
#+END_EXAMPLE
*** booting from guixSD

configfile (hd0,gpt1)/boot/grub/grub.cfg
** Changing Grub's keyboard layout

First, check that you're using GRUB v2 or above.

grub-install --version

Generate a GRUB keyboard layout file. Below is the command for a french keyboard. For other languages, check /usr/share/X11/xkb/symbols/. Filename choice is not important (you can change bepo).

sudo grub-kbdcomp -o /boot/grub/bepo.gkb fr

Edit /etc/default/grub with root rights to have:

#GRUB_HIDDEN_TIMEOUT=0
GRUB_TERMINAL_INPUT="at_keyboard"

Edit /etc/grub.d/40_custom with root rights to have:

#!/bin/sh
exec tail -n +3 $0

insmod keylayouts
keymap /boot/grub/bepo.gkb

Finally:

sudo update-grub

Note: Forget immediately about using the Shift key to display GRUB menu! It may be normal that terminal_input at_keyboard make this key not work anymore. So make sure #GRUB_HIDDEN_TIMEOUT=0 is properly commented.

http://askubuntu.com/questions/751259/how-to-change-grub-command-line-grub-shell-keyboard-layout


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

* GTK3 cheatsheets

#+BEGIN_SRC sh :results output :exports both
apropos gtk
#+END_SRC

This outputs some really cool gtk commands.  Many of them are gtk examples:

gtk3-demo
gtk3-demo-application
gtk3-widget-factory