Emacs之望尽天涯路

Table of Contents

恭喜经历了 方生方死,死而又生,生而复死 的过程后, 你还能坚挺下来, 其实 Emacs 也是人造的并没有那么神奇,能"望尽天涯路"说明自己对 "Emacs 是什么" 这个哲学问题已经有自己的答案了, 我认为既然已经来到这个阶段, 最重要的事情就是每天使用 Emacs, 而 org-mode 毫无疑问是最佳入口. 这个过程只要把 org-mode 及其 ecosystem 深入了解下即可(也并不容易). 这个过程你对 Emacs 只会有一个感觉:

鸡肋鸡肋, 弃之可惜, 食之无味.

org mode   ORG

org-agenda is your friend

Never start to do anything before looking at the agenda view. why agenda matters? every successful people almost have a secret who will organize your time and maximize the value of your time. this is the key to long term success. remember how many time you waste on wechat

what should be in org agenda view?

  1. important and emergency things goes first, they got A priority, along with important and not evergency tasks.
  2. a few habits to keep you update to date. good habit always makes you a good person.
  3. Like: health, reading, blogging, family and friendship

when you start to do a task in the org-agenda view ,dont foget to clock in with pomodoro

  1. this way you could track your time and effect.
  2. all the goodness of the pomodoro technicals

weekly review and adjust th priority of todo items and weekly archive done items

you need only one gtd.org file, and many files in org agendafiles.

keep an eye on what you have spent on each day, each week and each month

show it in my gtd.org file

demonstration the usage of org capture

  1. capture a todo with priority and tags.
  2. capture a chrome links for later reading.
  3. capture a task with a source code file

vinum extension in chrom to select txt   Chrome vimium

i know that now, vimer prefer using "/" searching and locating cursor to moveing cursor to locate. Likely in vinum extension of chrome, user should use "/" to locate and switch to visual-mode to select and y to copy

a few tips

  1. embed pdf links to todo items such that you could easily access them.
  2. insert the current chrome tab into place
  3. learn GTD method now!

org agenda .+1w and +1w

the big diff between .+1w and +1w is when is the next time to do this task

  • .+1w means planning next schedule-time according to the finished time
  • +1w means planning next schedule-time according to the last schedule time
  • +1w will set the schedule-time to the same day of a week.
  • .+1w will set the same time-gap between two schedule-time.

add tags to org-agenda

C-c C-q to add tags for current branch of org file

use follow-mode to see different TODO tasks in different files

F when in week-agenda-view, we can dinamically see them in source file by press F by this method, we can jump directly to that file where current task located.

how to customize the agenda view

  1. C-c a enter agenda-view, and press C to enter customize-view.
  2. every node has 4 items: value menu, access key, description, component
  3. value menu has 3 choose items
    • single command means locate a single char in agenda-view and type it will get the results
    • prefix means locate a single char in agenda-view and type it will enter another choose-view
      • access key must contain the prefix char
    • command series means locate a single char in agenda-view and will give many group of results
  4. access key hot key for typing to choose this view
  5. description a text for describe this view
  6. component contains some matching conditions and matching form

how to set tags/ todo-items/ and drawers for a org file?

  1. #+SEQ_TODO
  2. #+TAGS
  3. drawers start with a line :<DRAWERNAME>: end with next line :END:
    1. customize org-log-into-drawer to LOGBOOK
    2. C-c C-z to add a note in this branch of org file, you can note everything when you do this task.

how to add note to a branch of org file

C-c C-z will add a LOGBOOK drawer in this branch, and you can note anything when you do this task.

how to clutter up your org file, archive?

  1. #+ARCHIVE: <filename>.org:: set archive file for local file

how to archive to different org file?

  1. in a branch of org file, :ARCHIVE: <filename>.org::* <Father-node-name>
  2. eg

    * Books
    :PROPERTIES:
    :ARCHIVE: track-books.org::* Read books
    :END:
    
  3. * <Father-node-name> indicate the father node name in archive file

STARTED timer in org   TIMER

In spacemacs, many org related commands are lead by hotkey , includes timer priority tag archive capture Drawer sparse-tree pomodoro

  1. ,I record the start time of this org branch
  2. ,O record the end time of this org branch
  3. C-c C-x <tab> record the start time of this org branch
  4. C-c C-x C-o record the end time of this org branch

automatic logging of status changes   LOG

Goal: get a logbook entry whenever a TODO keyword chenges

#+SEQ_TODO:TODO(t@/!)
t - hotkey assigned to that TODO keyword
@ - log a timestamp and note when this is entered
! - log a timestamp when you leave that keyword

the configuration of TODO should be:

Goal: log a "CLOSED" timestamp when something is done

customize variable org-log-done

Goal: log a note with a timestamp every time something is rescheduled

customize variable org-log-reschedule

how to add CLOCKING drawer automatically when clock in/out?   TIMER

add '(org-clock-into-drawer "CLOCKING")

Function: the :PROPERTIES: drawer

the :PROPERTIES: drawer stores task specific settings and user defined attributes. Important : the :PROPERTIES: drawer must immediately follow the headline!

Goal: you dont want to create a log entry every time a repeating task is done

recipe: define a :LOGGING: property with value nil matching properties in agenda views is possible too.

how to setup a template for reading books in org file   PROPERTY DRAWER

* SOMEDAY %^{Author} - %^{Title}
:PROPERTIES:
:PAGES: %^{Pages}
:GENRE: %^{Genre}
:END:

- Recommended by %^{recommended by}
:LOGBOOK:
- Added: %U
:END:

[tips] org-agenda view can match TAGS/PROP/TODO

so, TAGS PROP TODO can be searched as an index. you should orgnize your PROP properly. you can search PROP like <PROP-ITEM>=XX

Function ordered tasks

Goal: task should be completed one after one

Recipe: define an :ORDERED: property with value 't' Toggle the :ORDERED: with C-c C-x o Customizing variables: '(org-enforce-todo-dependencies t) '(org-track-ordered-property-with-tag t) More customization: org-agenda-dim-blocked-tasks org-enforce-todo-checkbox-dependencies

Column view in org

Goal: show your org file in columns

Recipe : define columns that

#+COLUMNS: %7TODO(To Do) %58ITEM(Task)... Column view can set locally with the :COLUMNS: property in a property drawer Show column view C-c C-x C-c Leave view q

Effort estimates   EFFORT

Goal: Estimate the effort that your task will need

Recipe: effort estimates are stored in a property

setup: add definition to head of org file

#+PROPERTY: Effort_ALL 0:05 0:10 0:15 0:20 0:30 1:00 2:00 4:00 6:00 #+PROPERTY: Rating_ALL + ++ +++ ++++ +++++ and then possible values. add this to column view with %8Effort(Effort){:} . The {:} menas sum up times. Increase Effort : Shift -> Decrease Effort : Shift <-

Rating the importance of org TODO items   RATING

setup: add definition to head of org file

press C-c C-x C-c to enter org column view step into the unit-box of "Rating", and press Shift <- Shift -> to give the Rating to certain org branch

Linking to other items in actual file   LINK

Goal: Link to other items in the actual file Recipe: A link looks like that \[\[ target\]\] Function ordered tasks Targets: A headline - link name should identical with head name Any place in the document with a #+NAME: <target name> An item with a :CUSTOM_ID: <ID> in :PROPERTIES:, with [[#<ID>] Special: Radio targets that look like this target create links ont the fly Key combinations: Edit links with C-c C-l Follow link with C-c C-o Return to previous position C-c &

linking to other items somewhere in the world   LINK

Goal: link to other items some where in the world Recipe: \[\[XXXX\]\] Target: protocol:location [[file:///home/yiddi/…] [[http://www.youtube.com] [[nil Jones] Special: Linking to items with an ID property ID is an UUID that you can create with M-x org-id-get-create Customizing: copy the code from the video description to the end of your ~/.emacs file org-id-locations-file stores in what file orgmode should look for IDS

Attachments   ATTACH

  • Goal Attach some files to your task
  • Recipe Call the attachment system with C-c C-a

    • s : set a specific directory for task attachment
    • l : inherit the attachment directory to the children of task

    The attachments are usually stored under ./data/ and then a structure based on the ID property

    • a : attach file with the method configured in org-attach-method
    • c : attach file by copying
    • m : attach file by moving(deletes original file)
    • l : attach file by creating a hard link
    • y : attach file by creating a symbolic link
    • o : open attachment, if more than one ask for the name
    • O : open attachment in emacs
    • f : open the tasks attachment directory
    • F : open th tasks attachment directory by dired in emacs
    • d : select and delete a single attachment
    • D : delete all attachments
    • n : create a new attachment
    • z : synchronize the task with its attachment directory

Priority   PRIORITY

set priority of org branch org-mode priority are usually ABC you can change them by a configuration line:

Export   EXPORT

Export org files to HTML or PDF C-c C-e customization: Setting org-file-apps determines the application to open files. Add a line with #+OPTIONS: to fine tune the output d:t show the contents of drawers \n:t perserve line breaks p:t Export planing information(SCHEDULE/DEADLINE) todo:t Include TODO keywords into exprorted text

Advanced org export   EXPORT

by M-x customize-group choose org-export you can customize many items. or by add some text head of org file:


+AUTHOR: name the author of the document +TITLE: to define a title +SUBTITLE: to define a subtitle +DESCRIPTION: produces meta data, no output by default +BEAMER_THEME: select a beamer theme, goolge for "latex beamer themes" to get an idea what is avaible +BEAMER_FONT_THEME: select a font for the beamer slides


followed by #+OPTIONS:

option what does it do?
toc enable table of contents
^ enable sub/superscripting
tags export tags
f export footnotes
\n toggle line break preservation
  toggle line bread preservation

Even if org-mode offers several export backends, your file si ususally defined for one sepcial backend. The beamer backend is nice for standardized outline slides, but its lacking of desing and images. SO there is a good chance that your presentation is boring. Book recommondation: Garr Reynolds - Presentation Zen

Publish org to extenal server(like bolg)   EXPORT

  1. Customize your web server Enable user directory public_html (eg. On Debian 8 this is done as root user by)
  2. Customize your ~/.emacs file

    (setq org-publish-project-alist
          '(("org"
             :base-directory "~/org/"
             :publishing-directory "~/public_html"
             :publishing-function org-html-publish-to-html
             :section-numbers nil
             :with-toc nil
             )))
    
  3. Try the export function
    • Open your webbrouser and go to http://loacalhost/~joe/
    • Call the export dispatcher with C-c C-e
    • Press "P" for Publish
    • Choose what to publish
  4. Additional information OrgMode is keeping timestamps of the exported files in ~/.org-timestamps/ delete this directory if you delete public_html, otherwise only files changed since the last run will be exported

Reporting clock time in org   TIMER CLOCK_TABLE

  1. Gereral info on dynamic blocks
    • A dynamic block calls a function to create content dynamically
    • A dynamic block starts with a line #+BEGIN: name
      • The name is the name of function to call
    • A dynamic block can have :parameters
      • Parameters are written as :parameter1 value1
    • A dynamic block ends with a line #+END:
    • Some predefined functions are available
      • clocktable to build a time accounting table
      • columnview do capture a columnview inside a document
  2. Building a clock table
    • We add a clock table to it:
      • position on the headline and press C-c C-x C-r
      • adjust :scope for the scope : subree,file,file-with-archives … etc.
      • adjust depth by changing :maxlevel
    • Update the table at any time with C-c C-c
      • Cursor needs to be on the line with #+BEGIN:
      • You will see the time of the latest update in the caption line

Advanced clocktable

Add some config at the end of #+BEGIN: clocktable...

  • Use :block thismonth to show a block of time for a month
    • move forward with type Shift -> immediately after :block thismonth
    • move backward with Shift <- immediately after :block thismonth
  • Use :step week to show weekly values
  • Use :tstart and :tend to specify a time range
    • Date specifiers inside double quotes "<2017-2-28>"(you must type in by org-time-stamp)
    • org-time-stamp ususally ,. or C-c .

Capture column view   COLUMN_VIEW

Goal: export column-view (to another file)

"Since column view is just an overlay over a buffer, it cannot be exported or printed directly" (The org menual)

  • But you can create a dynamic block with a column view
  • Place your cursor where you want the block to be and press C-c C-x i
  • You will be asked for a value of the parameter :id
    • local : uses the tree in which the block is located
    • global : uses all headings in the file
    • "path-to-file" : uses the whole file
    • "ID" : uses the subtree with this :ID: property

Bulk agenda actions   AGENDA

  1. Setting marks in agenda view

    Key Action
    m mark entry at point
    u unmakr entry at point
    * makr all entries
    U unmark all entries
    M-m toggle mark at point
    M-* toggle all marks
    % mark enties base don a regular expression
  2. Bulk actions in agenda view
    • Call for bulk actions by pressing B
      • then choose what action to preform
      • after the action is performed the marks are removed
      • you can toggle persistent marks with *
    • Archiving entries
      • $ archive all marked entries to their archive files
      • A archive entries by moving them to their reprctive siblings
  3. Bulk actions: Change and refile entries

    Key Meaning
    t change TODO state
    + Add a tag to all selected entries
    - remove a tag from all selected entries
    f apply a function to marked entries.see menual for details
    r prompt for a single refile target and move all entries
       

Tacking Habit   AGENDA HABIT

  1. what is a habit? Habits are recurring tasks that you do frequently. Examples:
    • Brush your teeth everyday
    • Water your plants in the house every second day
    • Go to gym every week
  2. Once habit are really installed in your brain you dont need a remainder to do them
  3. Prerequisites to track habits
    • You need to enable the habits module in org-modules
      • M-x customize-variable then org-modules
    • Your habit is a recurring item with a TODO keyword representing an "open" state
    • You need to define a property STYLE: habit
    • The syntax for repetitions is a bit different: '.2d/3d' means you do the task at least every three days, at most every days
    • Important: Logging of changes to DONE needs do be enbaled
      • when you mark the current occurence done dont kill the log entry with C-c C-k!
  4. Real life example
    • Play the bass for 10min everyday
      • recurring task with repetition interval '.+1d'
      • Style "habit" defined as a property
    • Play guitar every 3rd day at least, better every 2nd day
      • recurring task with repetition interval '.+2d/3d'
      • Style "habit" defined as a property
  5. How does a habit look in an angenda view?
    • looks like a scheduled task, but with a block graph at the end.
      • The "!" marks the actual date
      • Every "*" marks a completed task on that day
      • Background color meanning:
        • Blue: task was to be done yet on that day
        • Green: task could have been done on that day
        • Yellow: task will be overdue the next day
        • Red: task is overdue on that day
  6. Additional tips
    1. customize org-habit-show-habits-only-for-today if you want to see habits that are not due today
    2. Habit tracking tracks just the successful completion of your habit so, if you use it like we did in our example define another task to track your progress
    3. Once a habit is successfully installed(usually around 3 weeks) you could also delete the habit tracking task

Tables in org   TABLE

Organize reference material in tables

  • Separate columns with "|"
  • Start rows with "|-" and press tab
  • Move columns with Alt <- or Alt ->
    • spacemacs: Alt h/j/k/l move column/row up/down/left/right
  • Delete/insert column with Alt shift <- Alt shift ->
    • spacemacs: Alt shift h/j/k/l insert/delete column/row
  • Insert a horizontal line with Ctrl c -
  • Define constants with #+CONSTANTS:
  • Define forumulas #+TBLFM:
    • Columns referenced by $ column-num
    • Rows referenced by @ row-num
  • eg.
      curr new  
Board System CPU BIOS BIOS action
        1.15.0 update

Code Snippets in OrgMode   CODE

Programming in org SRC block,

  • we can use <s <tab> to create this block automatically.
  • when code in that block, we can use ,' to enter a special-edit-window and use ,c to commit it.
  • we also can add line-num and reference to that block, by just add -n and -r to end of the #+BEGIN_SRC line.
  • we can ref to certain line by add (ref: <ref-name>) to end of that line. and C-c C-l to link to that <ref-name>
  • eg.

    1: @bottle.route('/'):
    2: def blog_index():
    3:    cookie = bottle.request.get_cookie("session")
    4:    username = sessions.get_username(cookie)
    5:    if not username:
    6:        username = "Unknown"
    7:    # snip
    8:    return bottle.template('blog_template', dict(username=username))
    

Table of contents in org :Export:Table of Content:

TOC is normally inserted directly before the headline of the file.

choose the depth of TOC

---------------------
#+OPTIONS: toc:2
#+OPTIONS: toc:nil  (no TOC)
---------------------

choose the location of TOC

---------------------
#+OPTIONS: toc:nil  (no default TOC)
#+TOC: headlines 2  (insert TOC here, with two headline levels)
---------------------

generate a list of tables or listing

you can also add a TOC to all the tables created in your org files

---------------------
#+TOC: listings     (build a list of listing)
#+TOC: tables       (build a list of tables)
---------------------

Org-babel with programming   org babel

Calculation using a formula

Emacs org-mode example and cookbook

:exports will export the source-code and result

def times_two(x):
    y = x*2
    return y
print times_two(5)

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("hello,world");
    }
}
hello,world


airmass zenith_seeing delivered_seeing
1.3 0.95 1.1119612
1.3 1.0 1.1704854
1.3 1.1 1.2875340
1.3 1.2 1.4045825
print delsee
import matplotlib.pyplot as plt
x, y, z = zip(*delsee)
fig = plt.figure()
axes = fig.add_subplot(1,1,1)
axes.plot(y, z, marker='o')
fig.savefig(fname)
return fname

Interactive with python

Contents: 23.1 Using an org-mode table in python 23.2 Plotting with python


23.1 Using an org-mode table in python

airmass zenith_seeing delivered_seeing
1.3 0.95 1.1119612
1.3 1.0 1.1704854
1.3 1.1 1.2875340
1.3 1.2 1.4045825
print delsee

23.2 Plotting with python

This:

airmass zenith_seeing delivered_seeing
1.3 0.95 1.1119612
1.3 1.0 1.1704854
1.3 1.1 1.2875340
1.3 1.2 1.4045825
import matplotlib.pyplot as plt
x, y, z = zip(*delsee)
fig = plt.figure()
axes = fig.add_subplot(1,1,1)
axes.plot(y, z, marker='o')
fig.savefig(fname)
return fname

Running Test

You can run the doctests from with org-mode with this bash code snippet:

python -m doctest test_HelloWorld.txt 2>&1
true

If the test succeeds, it will produce no output

Defining unittest tests

Define the unit test like any other piece of python code:

class TestFoo(unittest.TestCase):
    def test_foo(self):
        greeter = HelloWorld('foo')
        self.assertEqual(greeter.who, 'foo')

Making TestHelloWorld.py

Define the main testing module like this:

Running all tests

Use this bash source block to run all tests:

python -m doctest test_HelloWorld.py 2>&1

The output looks like this:

python TestHelloWorld.py 2>&1 test_HelloWorld.txt Doctest: test_HelloWorld.txt … ok test_foo (main.TestFoo) … ok


Ran 2 tests in 0.004s

OK

Add reference link in source block

官方名字: code line label:

1: (defun yiddi/test ()
2:   (message "tst"))
3: 

2

Author: yiddishkop (yiddishkop@163.com)

Date:

Emacs 26.1 (Org mode 9.1.13)

Validate