Skip to content

Latest commit

 

History

History
2147 lines (1700 loc) · 66.7 KB

pres.org

File metadata and controls

2147 lines (1700 loc) · 66.7 KB

Deal with Emacs

README

Hack to tell you to read the next subsections :-)

Go to the next subsection about General conventions.

General conventions

Emacs heavily uses the Control key and the Alt key. The shortcuts are combinations of press Control or Alt and in the same time press other keys.

How to use Control key: example

For example, the shortcut to go at the beginning of the current line is press Control and continuing to press Control you also press a. Move with the arrows the cursor here. Try!

For example, the shortcut to quit Emacs is press Control and continuing to press Control you press x, then you again press Control and continuing to press Control you also press c. Try… bye. :-)

Convention about Control key

The convention to document these shortcuts is:

  • C-a which means press Control and a in the same time.
  • C-x C-c which press Control and x in the same time, then Control and c again in the same time.

How to use Alt key: example

It is exactly the same principle for Alt.

For example, the shortcut to move backward a word is press Alt and continuing to press Alt you also press b.

For example, press Alt and continuing to press Alt you also press x. Then type beginning-of-line, following by Enter. Magic, isn’t? :-)

Convention about Alt key

The convention used elsewhere is:

  • M-b which means press Alt and b in the same time
  • M-x beginning-of-line which means press Alt and x in the same time, then type beginning-of-line, followed by Enter.

The letter M comes from Meta, the old name on old keyboards.

Note: that you can also use Esc as Meta key. In other words, the shortcut M-b means: press Alt and b or press Esc and b.

Export all the files used to show off

To ease the first experience, all the files are included in the repository. However, all these files are generated by this document. They are described by the blocks #+BEGIN_SRC … #+END_SRC.

If you want to generate them, you will use org-babel. It is as simply as the sequence: Control c Control v t or in short C-c C-v t.

Export the presentation: Org->HTML with Reveal.js

Warning about Reveal.js

The framework Reveal.js is a moving target. Therefore what is working today may not work in the near future. Mainly, two sources of issues:

  1. CDN: see #+REVEAL_ROOT; which could point to deleted URL
  2. ox-reveal: hard to keep up-to-date the exporter with Emacs, Org and Reveal.js versions

If one consider long term support of the material, then one should consider to carefully track the Git commit of both Reveal.js and ox-reveal.

Else, say that Reveal.js presentations is one shot presentation (junk presentation; junk as in junk food.)

The default parameters change and if the result is not compliant with the expectations (font size, etc.) then an additional file tune them; see #+REVEAL_EXTRA_CSS.

Last, the highlighting colours of the Emacs theme are used when exporting. Therefore, the last export before publishing must be done with the right Emacs theme—the default one seems well adapted; be careful to which highlighting colours are loaded, e.g., the option -nw changes the output—and the easiest way is to use this command line:

emacs -Q                           \
      pres.org                     \
      -l config.el                 \
      -f org-reveal-export-to-html \
      --kill

or to just run make where:

# Makefile works with TAB
# therefore this is a syntax hack to avoid to be confused
# ### rule: dependencies ; command
# M-x whitespace-mode will show you if spaces are TAB or SPACE

bootstrap: .git-version init.el pres.html ; @echo Done.

.git-version: ; git --version > $@

init.el: pres.org ; emacs --batch -Q	\
    pres.org				\
    -f org-babel-tangle		\
    1>&2 2> /dev/null

pres.html: pres.org ; emacs -Q		\
    pres.org						\
    -l config.el					\
    -f org-reveal-export-to-html	\
    --kill

The order of the arguments matters:

  1. do not load all the user’s configuration
  2. open the file pres.org
  3. load the file make.el and evaluate the ELisp
    (defvar ox-reveal-path
      (expand-file-name "elpa/org-reveal.git" user-emacs-directory))
    (defvar htmlize-path
      (expand-file-name "elpa/htmlize.git" user-emacs-directory))
    
    (defun git-clone (from to)
      (when (not (file-directory-p to))
          (shell-command (format
                          "git clone %s %s" from to))))
    
    (git-clone "https://github.com/yjwen/org-reveal.git" ox-reveal-path)
    (git-clone "https://github.com/emacsmirror/htmlize.git" htmlize-path)
    
    
    (add-to-list 'load-path ox-reveal-path)
    (add-to-list 'load-path htmlize-path)
    
    (require 'ox-reveal)
        
  4. apply the function org-reveal-export-to-html
  5. close Emacs.

The file make.el is a tiny file containing helpful paths: where org-reveal and htmlize are located.

Check your version of Emacs

Check your version of Emacs, choose a method:

  1. Open Emacs, then press Alt and x and type version In short: M-x version (see above about the General conventions)
  2. Open a Terminal, then type: emacs -version

Emacs >= 26

If the version is upper than 26, nothing to do and it should work out-of-box. Otherwise, email me!

Emacs < 26

If the version is lower than 26, then the built-in version of Org-mode does not work with Reveal.js. See the issue 324: yjwen/org-reveal#324 One fix is below.

Clone the org+reveal repository

  1. Open a Terminal
  2. Create the right folders, by typing mkdir -p ~/.emacs.d/elpa
  3. Clone the repo by typing git clone https://github.com/yjwen/org-reveal.git ~/.emacs.d/elpa/org-reveal.git

If you use Windows, then please consider using Linux (or at least MacOS).

Add init.el to your Emacs directory ~/.emacs.d/

;;;;
;;
;; Set Org and Reveal.js
;;
;; WARNING: issue with Org 8.2
;; Not sure this code fixed the issue
;; The idea is:
;; 1. Trick from https://github.com/jwiegley/use-package/issues/319
;;    Download the newer version of Org by ensuring org-plus-contrib
;; 2. DO NOT FORGET to manually clone org-reveal from Github
;;    Put it somewhere and give this inforamtion to :load-path
;; 3. Done.
;;
;; General config about Org
;; This can be reused if even yo do not use Reveal.js
(use-package org
  :ensure org-plus-contrib		; tricks!
                                      ; ensure the last version of Org
  :defer t
  :config
  (setq org-hide-emphasis-markers t)
  ;; hook to limit the number of characters per line
  ;; this number is controled by the variable fill-column
  (add-hook 'org-mode-hook 'turn-on-auto-fill)
  (setq org-src-fontify-natively t)	; coloring   inside blocks
  (setq org-src-tab-acts-natively t)	; completion inside blocks
  (setq org-tag-faces
        '(
          ("config" . (:foreground "mediumseagreen" :weight bold))
          ("LIVE" . (:foreground "Red" :underline t))
          ))

  ;; execute blocks (can be reused if even you do not use Reveal.js)
  (org-babel-do-load-languages
   'org-babel-load-languages '((python . t)
                               (R . t)
                               (shell . t)))
  ;; do not ask before eval code blocks
  (setq org-confirm-babel-evaluate nil)

  ;; store time when TODO is DONE
  (setq org-log-done (quote time)))

;; https://github.com/yjwen/org-reveal/issues/324
(setq ox-reveal-path "~/.emacs.d/elpa/org-reveal.git")
(if (file-directory-p ox-reveal-path)
    ;; then-clause
    (use-package ox-reveal
      :load-path ox-reveal-path
      :init
      ;; always load ox-reveal at startup
      ;; comment this line if you want not
      ;; but do not forget to load it manually M-: (require 'ox-reveal)
      (require 'ox-reveal))
  ;; else-clause
  (warn
   (format "Cannot load org exporter to Reveal.js.\nFix two steps: 1) Clone and 2) Reload.\n\ngit clone https://github.com/yjwen/org-reveal.git %s\n\nM-x load-file \"~/.emacs.d/init.el\"" ox-reveal-path)))
;;
;; ;end Reveal.js
;;
;;;;

;;;;
;;
;; Set syntax coloring
;;
(use-package htmlize
  :ensure t
  :defer t)
;;
;; ;end
;;
;;;;

Load manually the Org-mode module of Reveal.js

  1. Start Emacs If you use the init.el file, then the exporter is already loaded. Else go to 2.
  2. Press Alt : In short: M-:
  3. Type (require ‘ox-reveal)

(see above about the General conventions)

Export as any exporter

  1. Press Control c then Control e
  2. Press Shift R Shift R (twice)

In short: C-c C-e R R (see above about the General conventions)

Script to copy config

mkdir -p ~/.emacs.d/snippets
cp init.el ~/.emacs.d/
cp -R eg/snippets/* ~/.emacs.d/snippets/

From where I talk ?

Who I am ?

  • Mainly a geek guy
  • Research Engineer at Univ. Paris 7 Diderot

-

  • Post-Doc Católica (Chile)
  • Post-Doc Univ. Liège (hi Berty!)
  • PhD at ONERA Toulouse

simon.tournier@univ-paris-diderot.fr

https://github.com/zimoun

My life

  • 2006-2010: Vim user… and happy!
  • 2011 New Year Resolutions: Switch to Emacs (video)

    $⇒$ because the sysadmin showed me crazy stuff

    && he helped me to start.

I am only an enthusiast user, not a guru

My typical use-cases

  • Edit multiple languages: Python, Julia, C/C++, (Fortran), R, Shell, $\LaTeX$, Haskell, Scheme, etc.
  • Git (pull, commit, merge)
  • Organize my tasks and log them
  • Write docs and few papers, compose “workflow”
(defun ask-at-point (&optional i-know)
  "Feel free to ask everything."
  (interactive "P")
  (if i-know (message "Quick Answer.")
   (browse-url
    (concat "https://www.ddg.gg/?q=emacs+" (thing-at-point 'symbol)))))

Contents

  1. Quick Intro to Emacs
  2. How to configure: use-package
  3. Quick Demo:
    • $\LaTeX$
    • Python
  4. Goodies
  5. Org-mode: markdown on steroid
  6. A bit of Emacs Lisp (power to the people)

What Emacs is ?

Definition

Emacs is a User Interface (UI) to manipulate text

Theorem

All what X is able, Emacs does it too.

Proof: Let as an exercise after this presentation.

Corollary

https://i.redd.it/l58yl5wh6fk11.png

(counter) Example

Start Emacs

How you feel when you start

https://www.woodbrass.com/images/SQUARE400/woodbrass/EAGLETONE+BLADE.JPG

http://drumshop.ru/i/1/3/13dda81c116fcdba42d29d63d4d29a3bm.jpg

Weirdness comes from Oldness

Initial release: 1976; 42 years ago (timeline)

  • Macintosh : 1984

    First mass-market computer with GUI and mouse

  • Windows 1.0: 1985

    (claim starting dev. GUI in 1981)

A window is not a window

  • /”Frames”/ are to Emacs what windows are to everything else
  • /”Windows”/ are subdivisions of frames
  • /”Buffer”/ hold the content of a file

    “Open a file” means open a buffer that “visits” that file

https://i.stack.imgur.com/SAJFO.jpg

Control C is not Copy

C-x C-f means

press Control and x then Control and f

M-x means press Alt and x

CopyC-w
PasteC-y
CutM-w
FindC-s
Find-ReplaceM-%

Ah Bon?

http://blog.zepyaf.com/wp-content/uploads/2011/12/Capture-d’écran-2011-12-21-à-09.54.32.png

Keep Calm and Practise

http://www.starsportsbet.co.uk/wp-content/uploads/2015/11/garyplayer.jpg

Show me

The included TUTORIAL is a good start. To open it: C-h t

Some basics

Ressources

http://sachachua.com/blog/wp-content/uploads/2013/05/How-to-Learn-Emacs-v2-Large.png

http://sachachua.com/blog/wp-content/uploads/2013/05/How-to-Learn-Emacs8.png

Refcard

https://www.gnu.org/graphics/gnuemacsref.png https://www.gnu.org/software/emacs/refcards/pdf/refcard.pdf

A demo speaks better than words

@simon: check your cheatsheet :-)

Show me

How to change the background color and the selected region:

  1. M-x set-background-color
  2. (set-face-attribute 'region nil :background "yellow")

  • GUI
  • Write text
  • Options->CUA
  • Options->Customize
  • Change theme M-x load-theme leuven
  • Mouse is allowed
  • Shortcut is Command C-h k
  • List all the shortcuts C-h m
  • Panic quit: C-g several times
  • Move (word, line), up down C-v, M-v, C-l
  • Move paragraph M-{, M-}
  • Beginning/end of line
  • Move sentence M-a, M-e
  • Mark C-SPC
  • Kill, Paste, Kill-ring
  • Kill/paste rectangle C-x r k / C-x r y
  • Undo C-_ or C-x u
  • Copy text from Web, then justify M-q
  • Search, Regex search C-u C-s
  • Completion M-/
  • Split screen (window) C-x 2 / C-x 3
  • Minibuffer: M-x command
  • M-x split-window-below
  • M-x linum-mode
  • M-x whitespace-mode
  • M-x hl-line-mode
  • M-x sort-lines / M-x reverse-region
  • M-x align-regexp
  • Macro
    1. C-x ( do actions C-x )
    2. Apply C-x e
    3. Save it: C-x name-last-kbd-macro with a funky name
    4. Call it: M-x funky-name

Summary

“Habit is habit, and not to be flung out of the window by any man, but coaxed downstairs a step at a time.” – Mark Twain

Remember

  • Keyboard driven (source of power)
  • Command is first class citizen
  • one command should be binded to one Keymap
describe-keyC-h k
describe-functionC-h f
describe-modeC-h m
isearch-forwardC-s

Remember 2

find-fileC-x C-f
set-markC-SPC
kill-ring-saveM-w
kill-regionC-w
yankC-y

I DO NOT recommand CUA-mode (windows-like shortcuts)

Remember 3

Muscle one small step after another

https://as2.ftcdn.net/jpg/00/93/86/03/500_F_93860366_VpWf1VVnEGzVQwCeHTOsPLrvNHEfGOdb.jpg

How to configure

The configuration is driven by

$HOME/.emacs.d/init.el

Basics

Basics 1

Set variables

;; to see the life in colours
(global-font-lock-mode 1)
;; to remove the icons bar
(tool-bar-mode 0)
;; what?!? who use the latteral bar to scroll ? :-)
(scroll-bar-mode 0)

Set other variables

;; remove the initial starting message
(setq inhibit-startup-message t)

;; delete the *scratch* initial message
(setq initial-scratch-message nil)

@simon: quick demo-it

Show me

  • Open init.el
  • Type (scroll-bar-mode 0)
  • GUI Eval Defun
  • Change 0 to 1
  • Eval again
  • Show help: C-h f scroll-bar-mode
  • Do it with (tool-bar-mode 0)
  • Write (setq inhibit-startup-message t)
  • Close Emacs and reopen Emacs
  • Show help: C-h v inhibit-startup-message
  • Do again with (setq initial-scratch-message nil)

Basics 2

Conditional set

;; remove the menu when inside terminal
(if (display-graphic-p)
    (menu-bar-mode 1)
  (menu-bar-mode 0))

Rename commands

;; simplify the question-answer process
(defalias 'yes-or-no-p 'y-or-n-p)

;; M-x mode-* instead of the long name
(defalias 'mode-whitespace 'whitespace-mode)
(defalias 'mode-highlight 'global-hl-line-mode)
;; change the default file manager
(defalias 'list-directory 'dired)

Basics 3

Bind

;; set global shortcuts
(global-set-key [?\C-k] 'kill-whole-line)
(global-set-key [?\C-$] 'ispell-region)
;; special binding for specific mode (here dired)
(define-key dired-mode-map (kbd "E") 'dired-toggle-read-only))

Hook

;; delete dirty spaces
(add-hook 'before-save-hook 'delete-trailing-whitespace)

A journey of a thousand miles begins with a single step

https://i.pinimg.com/originals/a9/6f/db/a96fdbb368f4b75e4feccbece41721f2.jpg

Config more

Packages

“The coolest feature of Emacs is all the available packages.” – Doctor Who, the coolest nerd ever

Repos: ELPA and MELPA

Built-in since Emacs 24

(require 'package)
(setq package-enable-at-startup nil)
(add-to-list 'package-archives
             ;; `use-package' is not in ELPA, as many more ;-)
             '("melpa" . "http://melpa.org/packages/"))
(add-to-list 'package-archives
               ;; Add org-plus-contrib
               '("org" . "http://orgmode.org/elpa/"))
(package-initialize)

M-x package-list-packages

;; boostrap `use-package' by John Wiegley
(unless (package-installed-p 'use-package)
  (package-refresh-contents)
  (package-install 'use-package))
;; load it
(require 'use-package)

Example:

;; change the default file manager
(use-package dired
  :defer t
  :init
  (defalias 'list-directory 'dired)
  :config
  (define-key dired-mode-map (kbd "E") 'dired-toggle-read-only))

use-package 2

;; example of Julia configuration
(use-package ess
  :ensure t
  :defer t
  ;; :init	                            ; example with non-standard loc.
  ;; (setq inferior-julia-program
  ;; 	"/Applications/Julia-0.6.app/Contents/Resources/julia/bin/julia")
  :mode (("\\.jl\\'" . ess-julia-mode))
  :defines ess-indent-offset            ; silent warning
  :config
  (require 'ess-julia)
  (require 'ess-utils)
  (setq ess-eval-visibly-p nil)
  (setq ess-use-eldoc'script-only))

Config all unshown tangled here

Yes, it’s awesome!

https://pics.me.me/that-awesome-moment-doctor-who-and-the-ta-r-d-is-when-you-34353243.png

Two live Examples

@simon: do not forget to: sh config-me.sh

@simon: do not forget to turn-on command-log-mode :-)

Show me

  1. Create ~/.emacs.d then Copy init.el into it
  2. Open Emacs: it is downloading everything
  3. Setup done. Happy hacking!
  4. Close Emacs and restart it
  5. It warns about Reveal.js
    • Turn off in init.el
    • Or clone it
  6. Let’s go!

latex-mode

# apt-get install aspell

Config

;;;;
;;
;; TeX/LaTeX configuration
;;
;; be careful, the names of the modes are a bit a messy
(use-package tex-mode
  :defer t
  :config
  ;; automatically bound paragraph length
  (add-hook 'latex-mode-hook 'turn-on-auto-fill)
  ;; turn on the nice RefTeX package
  (add-hook 'latex-mode-hook 'turn-on-reftex))

;; compilation show first the first error
;; instead of the end of the compilation buffer
(setq compilation-scroll-output 'first-error)

;; mispelling correction using dictionary
(use-package ispell
  :defer t
  :config
  ;; you need to install the program aspell
  (setq-default ispell-program-name "aspell"))

Show me

  • Insert environment C-c C-o equation, table, tabular, figure
  • RefTeX C-c =
  • Insert stuff C-c )
  • Insert citation from the.bib C-c [
  • Compile all
    1. Compile [pdflatex] C-c C-c
    2. Compile again if require C-c C-c
    3. Compile bibtex C-c TAB
    4. Compile C-c C-c and try again
    5. Display the PDF? Again C-c C-c
  • Spell word M-$
  • Spelling corrector C-$ (M-x ispell-change-dictionary)
  • Close the file
  • Install Auc\TeX: M-x package-list-packages then C-u C-s ^ auctex and i x. It is ^ two spaces auctex. The character ^ means for regexp: beginning of the line.
  • Reopen the file
  • Insert section C-c C-s TAB
  • Insert environement C-c C-e TAB
  • Completion M-TAB
  • Preview on/off at Point (GUI)
  • GUI LaTeX->Show/Hide->

python-mode

# apt-get install virtualenv ipython
$ pip install jedi epc pylint --user

Config

;;;;
;;
;; Python configuration
;;
;; better interface to imenu
(use-package idomenu
  :ensure t
  :bind ("C-c i" . idomenu))

(use-package direx
  :ensure t
  :defer t)

(use-package jedi-direx
  :ensure t
  :defer t)

(use-package jedi
  :ensure t
  :defer t
  :init
  (setq
   py-electric-colon-active t
   py-smart-indentation t)

  ;; I do not understand well the Jedi's config
  (require 'jedi-direx)

  (setq jedi:complete-on-dot t)
  (setq  jedi:setup-keys t)
  (add-hook 'python-mode-hook 'jedi:setup)
  (add-hook 'python-mode-hook
            (lambda ()
              (local-set-key "\C-ch" 'jedi:show-doc)
              (local-set-key "\C-cg" 'jedi:goto-definition)
              (local-set-key "\C-cd" 'jedi-direx:pop-to-buffer)))
  (add-hook 'jedi-mode-hook 'jedi-direx:setup))

;; switch to IPython because it rocks!
(when (executable-find "ipython")
  (setq python-shell-interpreter "ipython")
  (setq python-shell-interpreter-args "--simple-prompt"))


(use-package yasnippet
  :ensure t
  :defer t
  :init
  (yas-global-mode 1)
  :config
  (yas-global-mode 1))

(use-package yasnippet-classic-snippets
  :ensure t
  :defer t)
(use-package yasnippet-snippets
  :ensure t
  :defer t)
# -*- mode: snippet -*-
# name: licence
# key: gpl...
# --
# coding: utf-8
#
#
# Copyright 2018 John Doe
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
# -*- coding: utf-8 -*-
# -*- mode: snippet -*-
# name: def
# key: def...
# --
def ${1:fname}(${2:args}):
    """
    The well written doc !
"""
    $0
# -*- coding: utf-8 -*-
# -*- mode: snippet -*-
# name: num...
# key: num...
# --

import numpy as np
import matplotlib.pyplot as plt
import scipy.linalg as la

Show me

  • imenu C-c C-j
  • M-x indent-rigidly
  • Yasnippet

More features (demo)

Show me

  • Dired C-x C-d
    • Open the help: C-h m
    • create directory
    • copy, rename file
    • edit name C-x C-q then C-c C-c
    • mark files and copy them to subfolder
  • EDiff
    • M-x ediff-files
    • Choose eg/tex/article.tex
    • Then choose eg/tex/article-modif.tex
    • Press n to visualize the next diff
    • Or press p to visualize the previous diff
    • Help with h
  • List all the buffers open C-x C-b
  • Open a file under Git then M-x magit / C-x g
  • Add spaces everywhere in the file then M-x mode-whitespace
  • Terminal: M-x term then full terminal
  • Change tabs vs space convention (python) M-x tabify
  • Select region then M-x indent-rigidly then Shift-<arrow>

Another killer feature: Org-mode

org-mode is…

Awesome!” – John Kitchin (video)

  • Markup language (see the backstage of this presentation)
  • Note-taking utility
  • TODO lists maintainer
  • Planner, agenda
  • Tables editor
  • Helper to manage your projects (CEO explains his experience)
  • included by default since Emacs 22 (2006)

Org is vast…

start small!

“Don’t try to set up the ‘final’ task managing system from the start. Because you have no idea yet what your system should look like. […] Start by creating and managing a small TODO list and then develop your own system as the needs arises.” – Carsten Dominik (creator of org)

My experience

  • Learn a couple of its capabilities
  • Integrate them into your workflow
  • You’ll find yourself thinking, “Hum?, it would be nice if I could X”
  • Then check the manual, browse the web

… and, in fact, Org can do X

Demo

Show me

  • Markup:
    • underline: _
    • bold: *
    • italic: /
    • verbatim: =
    • code: ~
    • strike: +
    • list, section, link
  • C-c C-n /C-p
  • C-c C-u (upper header)
  • C-c C-j (interresting move)
  • Move M-up M-down
  • M-left M-right
  • M-S-left right (item)
  • =C-c - =(change item kind)
  • C-c ^ (sort)
  • Tags: search C-c / m

table and $\LaTeX$

  • Write table with Org-mode (easy!)
  • Export to .tex: C-c C-e C-b l l (body only)
  • Use \input{}

(or epxort to buffer C-c C-e C-b l L and copy/paste)

DEMO!

makefile

all: doc.tex table1.tex table2.tex
	  pdflatex doc.tex

%.tex: %.org
	   emacs -batch -q $< --eval="(org-latex-export-to-latex nil nil t t)"

clean:
	  -rm table?.tex
	  -rm doc.{aux,log}

Ressources

Computational Document / Reproducible workflow

“Buzzword – What’chu talkin’ ‘bout, Willis?” – Arnold

Emacs Lisp

Lisp? Really?!?

Lisp is (Lots of ((Irritating, Spurious) (Parentheses)))

https://imgs.xkcd.com/comics/lisp_cycles.png

Lisp? tell me more…

First appeared 1958; 60 years ago

“A bad workman blames his tools.” – Barack Obama

“Another language is a new life.” – Persian proverb

“Learn a language, and you will avoid a war.” – Arab proverb

Hacker (Paul Graham) citing Hacker (Eric S. Raymond): More here, here or here.

Finally, the truly serious hacker should consider learning Lisp:

Lisp is worth learning for the profound enlightenment experience you will have when you finally get it; that experience will make you a better programmer for the rest of your days, even if you never actually use Lisp itself a lot.

This is the same argument you tend to hear for learning Latin.

More here, here or here.

True!

https://media.giphy.com/media/maIEBUU5OmrMA/giphy-facebook_s.jpg

Old pot, good jam

Emacs Lisp (ELisp) Ressources

Basics

;; work with parenthesis
(show-paren-mode 1)       ; highlight matching parens
(electric-pair-mode 1)    ; open-close parens
  • Start REPL

    M-x ielm

  • Eval in mini-buffer: M-:
  • Buffer with M-x emacs-lisp-mode

    C-x C-e

    end of S-expression

Basics 1

;; Declare variable
(setq x 1)

;; Compute (infix)
(+ x 42)
(* x 4.2)

;; List (linked)
(setq ll (list 1 2 3 4))
;; First element (head)
(car ll)
;; Rest (tail)
(cdr ll)
;; Concatenate lists
(append ll (list 11 22 33 44 55) (list "a" "bb" "ccc"))

Basics 2

Function

(defun hello-world (name)
  "Simply Hello World function.

Do stuff.
And other stuff.
The argument name provides a name to helloing."
  (message "Hello World: %s!" name))

Anonymous function

(lambda (name)
  (message "Hello: %s!" name))

Call/Apply a function: (hello-world "Dude")

Basics 3

<<ask-at-point>>

All the Lisp power at your fingertips

https://sayingimages.com/wp-content/uploads/minion-awesome-quote.jpg

Emacs is just a Lisp machine

  • Few built-in functions coded in C

    C-h f list or car, cdr, etc.

  • And lot of Emacs Lisp ones

    C-h f ibuffer or find-file, dired, org, etc.

Read manual then read code on ELPA and MELPA

e.g., eshell

MIT museum

https://upload.wikimedia.org/wikipedia/commons/thumb/7/7d/MIT_lisp_machine.jpg/1836px-MIT_lisp_machine.jpg

Simple functions

Upcase a word

(defun eg/upcase-word ()
  "Change from any word to UPPERCASE."
  (interactive)
  (let ((beg (progn
               (backward-word)
               (point)))
        (end (progn
               (forward-word)
               (point))))
        (upcase-region beg end)))

Next!

(global-set-key (kbd "M-u") 'my/upcase-word)

What about Downcase ?

(defun eg/downcase-word ()
  "Change from any word to DOWNCASE."
  (interactive)
  (let ((beg (progn
               (backward-word)
               (point)))
        (end (progn
               (forward-word)
               (point))))
        (downcase-region beg end)))

Pattern ?

http://mathandmultimedia.com/wp-content/uploads/2010/11/amazing1.png

Refactor

(defun eg/change-case-word (fun)
  "Generic function to change the case of a word.

When the `point' is somewhere in word, first get the `backward-word'
position, second get the `forward-line' position, and last apply FUN
to these both."
  (interactive)
  (let ((beg (progn
               (backward-word)
               (point)))
        (end (progn
               (forward-word)
               (point))))
        (funcall fun beg end)))

Simple, isn’t?

(defun eg/capitalize-word ()
  "Remap of `capitalize-word'."
  (interactive)
  (eg/change-case-word 'capitalize-region))

(defun eg/upcase-word ()
  "Remap of `upcase-word'."
  (interactive)
  (eg/change-case-word 'upcase-region))

(defun eg/downcase-word ()
  "Remap of `downcase-word'."
  (interactive)
  (eg/change-case-word 'downcase-region))

;; add quick bindings to the new nice functions
(global-set-key (kbd "M-c") 'eg/capitalize-word)
(global-set-key (kbd "M-u") 'eg/upcase-word)
(global-set-key (kbd "M-l") 'eg/downcase-word)

Count Words

Tutorial from VSCode to extend it

https://code.visualstudio.com/docs/extensions/example-word-count

Come on! It is not simpler than X.

(me: javascript is aweful)

Hum?

M-=

or

M-x count-words-region

Ok, do naive way!

(defun eg/count-words-region (start end)
  "Count words in the selected region.

Worse than `count-words-region'."
  (interactive "r")
  (let ((count-words->how-many 0))
    (goto-char start)
    (while (< (point) end)
      (if (forward-word 1)
          (setq count-words->how-many (1+ count-words->how-many))))

    (message "Region has %d words." count-words->how-many)
    count-words->how-many))

M-x eg/count-words-region

mini-fem solver with ELisp

Let only consider:

  • list and the 4 arithmitic operations on integers and floats
  • functions and recurcivity

$$cos(x) = \textrm{real}~ ∑_n \frac{ix}{n!}$$

\begin{array}{ccl} u′\prime + k^2 u &=& 0
& \textrm{with} & u(0) = 1 \ & \textrm{and} & u^′(1)=iku(1) \end{array}

Demo

see https://github.com/zimoun/elfem1

A bit of elisp history

  • Richard Stallman (father of GNU Emacs) speaks about Lisp
  • Guy Steele (co-“father” of Emacs) still shares insights (video)
  • Stefan Monnier (prev. maint. of GNU Emacs) exposes internals

ELisp is not truly a Lisp?

http://happilyevertinder.com/wp-content/uploads/2017/11/photo-20161216233158566.jpg

Facts

Lisp-2 vs Lisp-1

  1. Naive
    (defun f1 (arg)
      (if (listp arg)
          (mapcar (lambda (x) (f1 x)) arg)
        arg))
        
  2. Wrong
    (defun f2 (arg)
      (if (listp arg)
          (mapcar f2 arg)
        arg))
        

    -> *** Eval error *** Symbol’s value as variable is void: f2

  3. Fix
    (defun f3 (arg)
      (if (listp arg)
          (mapcar #'f3 arg)
        arg))
        
  4. Explanations: Elisp is Lisp-2: two namespaces. The function f2 does not work because mapcar looks in the variable table and f2 is not in because it is in function table. The functions f1 and f3 work because… please!

    #'foo means (function foo) and =’foo= means (quote foo). See Info and Help documentation.

What Emacs is ?

https://upload.wikimedia.org/wikipedia/commons/thumb/b/b7/Unico_Anello.png/220px-Unico_Anello.png

Start now!

https://spaceplace.nasa.gov/review/galactic-explorer/galactic_explorer.en.png

Alternative Reality

Key of Success

  • /Master a tool needs large amount of work/

    think all the maths you learn before complete non-trivial proofs

  • /Master a tool is not easy; otherwise it is a lie/

    think nunchaku practise to be as efficient as Bruce Lee

Why computing tools should be different ?

Be good at something is long

My personal conclusion

Why flamewar editor ?

  • Our daily life is interacting with computers
  • We are all differently wired
  • Cognition is not straightforward

Editor should be freedom, not constraint and pain.

… because Emacs is the best! ;-)

http://hackles.org/strips/cartoon92.png

Happy end?

Emacs is first at productive procrastination :-)

http://www.phdcomics.com/comics/archive/phd010408s.gif