Category Archives: emacs

Using your own Emacs Lisp functions in Org Mode table calculations: easier dosage totals

UPDATE 2015-06-17: In the comments below, Will points out that if you use proper dates ([yyyy-mm-dd] instead of yyyy-mm-dd), Org will do the date arithmetic for you. Neato! Here’s what Will said:

Hi Sacha. Did you know you can do date arithmetic directly on org’s inactive or active timestamps? It can even give you an answer in fractional days if the time of day is different in the two timestamps:

| Start                  | End                    | Interval |
| [2015-06-16 Tue]       | [2015-06-23 Tue]       |        7 |
| <2015-06-13 Sat>       | <2015-06-15 Mon>       |        2 |
| [2015-06-10 Wed 20:00] | [2015-06-17 Wed 08:00] |      6.5 |
#+TBLFM: $3=$2 - $1 

Here’s my previous convoluted way of doing things… =)

I recently wrote about calculating how many doses you need to buy using an Org Mode table. On reflection, it’s easier and more flexible to do that calculation using an Emacs Lisp function instead of writing a function that processes and outputs entire tables.

First, we define a function that calculates the number of days between two dates, including the dates given. I put this in my Emacs config.

(defun my/org-days-between (start end)
  "Number of days between START and END.
This includes START and END."
  (1+ (- (calendar-absolute-from-gregorian (org-date-to-gregorian end))
         (calendar-absolute-from-gregorian (org-date-to-gregorian start)))))

Here’s the revised table. I moved the “Needed” column to the left of the medication type because this makes it much easier to read and confirm.

| Needed | Type         | Per day |      Start |        End | Stock |
|     30 | Medication A |       2 | 2015-06-16 | 2015-06-30 |     0 |
|      2 | Medication B |     0.1 | 2015-06-16 | 2015-06-30 |   0.2 |
#+TBLFM: @2$1..@>$1='(ceiling (- (* (my/org-days-between $4 $5) (string-to-number $3)) (string-to-number $6)))

C-c C-c on the #+TBLFM: line updates the values in column 1.

@2$1..@>$1 means the cells from the second row (@2) to the last row (@>) in the first column ($1).  '  tells Org to evaluate the following expression as Emacs Lisp, substituting the values as specified ($4 is the fourth column’s value, etc.).

The table formula calculates the value of the first column (Needed) based on how many you need per day, the dates given (inclusive), and how much you already have in stock. It rounds numbers up by using the ceiling function.

Because this equation uses the values from each row, the start and end date must be filled in for all rows. To quickly duplicate values downwards, set org-table-copy-increment to nil, then use S-return (shift-return) in the table cell you want to copy. Keep typing S-return to copy more.

This treats the calculation inputs as strings, so I used string-to-number to convert some of them to numbers for multiplication and subtraction. If you were only dealing with numbers, you can convert them automatically by using the ;N flag, like this:

| Needed | Type         | Per day | Days | Stock |
|      6 | Medication A |       2 |    3 |     0 |
|      1 | Medication B |     0.1 |    3 |   0.2 |
#+TBLFM: @2$1..@>$1='(ceiling (- (* $3 $4) $5)));N

Providing values to functions in org-capture-templates

Over at the Emacs StackExchange, Raam Dev asked how to define functions for org-capture-templates that could take arguments. For example, it would be useful to have a function that creates a Ledger entry for the specified account. Functions used in org-capture-templates can’t take any arguments, but you can use property lists instead. Here’s the answer I posted.

You can specify your own properties in the property list for the template, and then you can access those properties with plist-get and org-capture-plist. Here’s a brief example:

Here’s a brief example:

(defun my/expense-template ()
  (format "Hello world %s" (plist-get org-capture-plist :account)))
(setq org-capture-templates '(("x" "Test entry 1" plain
                               (file "~/tmp/test.txt")
                               (function my/expense-template)
                               :account "Account:Bank")
                              ("y" "Test entry 2" plain
                               (file "~/tmp/test.txt")
                               (function my/expense-template)
                               :account "Account:AnotherBank")))

I hope that helps!

Using Emacs Org Mode tables to calculate doses to buy

I got tired of manually calculating how many I needed to buy based on a daily protocol and how many I had in stock, so I wrote a little bit of Emacs Lisp to figure it out. You can specify the type, daily dose, start and end dates (inclusive; defaults to the last specified date if blank), and how many you have in stock.

First, define a table of this form, and give it a name.

#+NAME: input
| Type         | Per day |      Start |        End | Stock |
| Medication A |       2 | 2015-06-09 | 2015-06-16 |     5 |
| Medication B |       1 |            |            |     0 |
| Medication C |     0.1 | 2015-06-12 | 2015-06-16 |   0.2 |
Type Per day Start End Stock
Medication A 2 2015-06-09 2015-06-16 5
Medication B 1 0
Medication C 0.1 2015-06-12 2015-06-16 0.2

To call the code from the bottom of this post, use something like:

#+CALL: calculate-meds-needed(meds=input) :hlines yes :colnames yes
Type Total In stock Needed
Medication A 16 5 11
Medication B 8 0 8
Medication C 0.5 0.2 1

Here’s the code that processes it:

#+name: calculate-meds-needed :var meds=meds :colnames yes :hlines yes
#+begin_src emacs-lisp
(let (start end)
   (list (list "Type" "Total" "In stock" "Needed"))
   (list 'hline)
   (sort (delq nil (mapcar
                    (lambda (row)
                      (unless (or (eq row 'hline) (string= (elt row 0) "Type"))
                        (let (total)
                          (setq start (if (string< "" (elt row 3)) (elt row 3) start)
                                end (if (string< "" (elt row 2)) (elt row 2) end)
                                total (* (elt row 1)
                                         (- (calendar-absolute-from-gregorian (org-date-to-gregorian start))
                                            (calendar-absolute-from-gregorian (org-date-to-gregorian end))
                           (elt row 0)
                           (elt row 4)
                           (max 0 (ceiling (- total (elt row 4))))))))
                    meds)) (lambda (a b) (string< (car a) (car b))))))

Adding calculations based on time to the Org Agenda clock report

Duplicating this answer on my blog in case StackOverflow goes away. =)

Leo asked:

I’m trying to make the Agenda Clockreport show how many pomodoros I’ve invested in a task. A Pomodoro is 25 minutes. For example, 1:15 hours of work is 3 pomodoros.

I’m trying to customize org-agenda-clockreport-paramater-plist, and I would like to extract “Time” and convert it to a pomodoro. I.e., (time in minutes / 25) = pomodoro.

I wrote:

This will create a column in your clocktable report that sums the hours from columns 3 and 4, and then another column that shows you the round number of pomodoros that took up.

(setq org-agenda-clockreport-parameter-plist
      '(:link t :maxlevel 2 :formula "$5=$3+$4;t::$6=ceil($5*60/25);N"))

If you don’t want in-between columns, here’s a totally hackish approach:

(defun my/org-minutes-to-clocksum-string (m)
  "Format number of minutes as a clocksum string.
Shows the number of 25-minute pomodoros."
  (format "%dp" (ceiling (/ m 25))))
(fset 'org-minutes-to-clocksum-string 'my/org-minutes-to-clocksum-string)

Alternatively, you can use :formatter, but the formatting function looks very long and annoying to change.

Leo eventually configured it with:

(setq org-agenda-clockreport-parameter-plist
 '(:fileskip0 t :link t :maxlevel 2 :formula "$5=($3+$4)*(60/25);t"))

(He didn’t mind the decimals, I guess! =) )

2015-05-13 Emacs Hangout

Console Emacs vs GUI Emacs, keybindings, Org Mode, cooking, nyan, window management, calendars, SuperCollider Usual disclaimer: times are approximate, and the note-taker often gets distracted. =)

  • 0:00:00 Emacs configuration
  • 0:11:22 Console Emacs vs GUI Emacs? iTerm integration, mouse support, 256 colours, drop-down menus (although you can get a text one), …
  • 0:14:59 multihop TRAMP
  • 0:16:01 keybinding philosophies, Hyper and Super
  • 0:22:15 Remapping keys on Mac OS X (dealing with separate Alt and Meta)
  • 0:28:04 Org and mobile
  • 0:30:25 emulating hyper and super keys
  • 0:32:15 orgzly
  • 0:33:33 Org Mode and cooking, org-map-entries
  • 0:39:31 nyan
  • 0:43:04 One window, workgroups
  • 0:46:56 winner-mode
  • 0:53:30 rinari, zeus, ruby
  • 0:54:53 neotree
  • 0:58:22 keyboards
  • 1:03:24 conference
  • 1:09:22 calw; also, something about rainbow-mode, and palette, and then later Org Mode
  • 1:23:13 SuperCollider, Overtone, yasnippet
  • 1:45:13 blackink?

Text chat: Here’s the gif I have as my nyan

Sahil Sinha 9:23 PM
Jack G. 9:24 PM (setq mac-right-command-modifier ‘hyper)<br>(setq mac-right-option-modifier ‘super) (global-set-key (kbd “H-h”) ‘er/expand-region
George Jones 9:32 PM
Jack G. 9:36 PM nyan Cranky_walk.gif
Jack G. 9:42 PM
me 9:42 PM ?
Daniel H 9:46 PM
me 9:48 PM winner-mode
George Jones 9:59 PM
George Jones 9:59 PM Xah Lee writes a LOT about keyboards
Jack G. 10:02 PM
Bogdan Popa 10:10 PM
me 10:11 PM org-gcal
Daniel H 10:12 PM
George Jones 10:12 PM having real trouble hearing…
George Jones 10:20 PM when you open a PDF in docview you can get the text with ^C^T (default bindings)
Jack G. 10:21 PM Thanks George!
George Jones 10:21 PM C-c C-t runs the command doc-view-open-text
me 10:27 PM
sai tejaa Cluri 10:27 PM hi
Jack G. 10:37 PM link
me 10:37 PM This was a fun demo of Org Mode and SuperCollider
Levi Strope 10:40 PM Jack your audio is crystal clear now… whatever that change was
Jack G. 10:45 PM
me 10:48 PM

2015-04-30 Emacs Hangout – hosted by Philip Stark

Thanks to Philip Stark for organizing an Emacs Hangout that’s more conducive to European timezones! Here’s the video and the notes.

You can add more comments on the event page. For more about upcoming Hangouts, check out our Google+ page.

Show notes (times might need a little adjustment):

  • 0:00:03 Introductions!
  • 0:03:03 A couple of Emacs semi-newbies =)
  • 0:03:52 Java and C# language support (autocomplete, refactoring, etc.); bridging the gap between Emacs and the runtime (Unity, Android, etc.). Batch mode for the latter. OmniSharp actually went pretty darn well this time around!
  • 0:06:10 OmniSharp demo
  • 0:06:13
  • 0:07:23 OmniSharp + company config, demo of completion. Includes API. Jump to definition as well.
  • 0:10:59 Cool refactoring stuff. Ex: intelligent rename. Watch out for bugs. Still neat!
  • 0:12:30 MS Visual Studio Code seems to run on the same backend =)
  • 0:13:18 OmniSharp background info
  • 0:14:53 New participant, working out the tech issues
  • 0:16:28 Java? Haven’t looked into it much yet, lower priority. Pain point: Eclipse project build chain. eclim? May give it a second chance.
  • 0:19:37 Wishlist: batch mode Unity for headless testing?
  • 0:20:05 Emacs and Python – working through the Google Code Jam problems. C-c C-c to execute code in the REPL, so much fun. Suggestion: org-babel blocks? =)
  • 0:21:37 Discussion about Scala and Ensime. Ooh, Ensime does Java too. Neat!
  • 0:22:49 New to Emacs Lisp. Discovering things and implementing them – good enough, but not well-polished. Writing. Helm, etc. So many things to learn! Balancing studying the Emacs Lisp intro and manual, and discovering things day to day.
  • 0:25:00 Separate Lisp file loading for experimental stuff.
  • 0:25:30 Woodnotes guide?
  • 0:26:32 Emacs StackExchange,, Planet Emacsen
  • 0:29:17 Spacemacs, packaged defaults. Learning with index cards. Learning curve. Emacs community is obsessed with documentation. Phenomenal! =)
  • 0:34:23 Documented conventions, nicely-designed keybindings etc. for Spacemacs
  • 0:35:50 Spacemacs setup asks you which tradition you want to follow
  • 0:36:46 nerdtree replacement – neotree
  • 0:37:27 Goal is to not rely on Spacemacs, but for it to be a stepping-stone / scaffold
  • 0:38:30 Differences between Linux window managers; simplified workflows
  • 0:40:24 Looking at configuration frameworks piecemeal, learning workflows
  • 0:43:05 Discoverability is a big issue. helm-c-yasnippet has helm-yas-complete, helm-yas-create-snippet-on-region . Can be configured to display the keys. (setq helm-yas-display-key-on-candidate t) Has additional actions if you TAB.
  • 0:50:24 Hydra demo. Ex: moving lines up and down. Hydra for Helm?
  • 0:57:25 Lispy-mnemonic
  • 1:02:58 Usability
  • 1:05:30 Lispy-mnemonic workflow – minor mode
  • 1:06:15 back-to-indentation and restoring the binding in Lispy
  • 1:07:36 org-timer and meeting notes
  • 1:08:14 Make timestamps better! =)
  • 1:10:53 Cognitive overhead of new IDEs. Ex: SublimeText C-d marks a thing (Emacs equivalent: expand-region)? More organic, flexible commands versus specific ones, staying within your mental model.
  • 1:13:00 multiple-cursors, transpose-chars versus backward-kill-word.
  • 1:17:30 helm-swoop
  • 1:21:06 micro-optimizations, command-log-mode, keyfreq, mc/mark-all-like-this(-dwim), guru-mode
  • 1:26:06 Dealing with Eclipse wizards, things that shift you out of your mental model. Discussion of Helm and Ido. Also, helm-show-kill-ring.
  • 1:31:59 Hydra and leader keys.
  • 1:32:31 Dan’s intro. Figuring out workflow. Export Org Mode to HTML. Yasnippet for HTML5 declarations? Org Mode publishing project support (org) Publishing options
  • 1:37:20 Magit, git-timemachine, git-gutter-fringe, git-wip (for committing work in progress each time you save;, git-wip-timemachine (forked git-wip,
  • 1:41:44 undo-tree
  • 1:42:57 git-messenger
  • 1:43:48 C-x v g, vc-annotate, colour-coding
  • 1:45:13 Emacs load times, profiling
  • 1:47:59 markdown and flycheck not finding an external command, checking the *Messages* buffer

Text chat:

M. Ian Graham 2:06 PM
M. Ian Graham 2:14 PM
Tim K 2:15 PM should be ok
Tim K 2:15 PM maybe someone has to unmute me
M. Ian Graham 2:15 PM
Tim K 2:15 PM i’ll just keep lurking for now then
me 2:18 PM
Tim K 2:19 PM tangentially related: ENSIME I used it for developing a web play framework project
M. Ian Graham 2:20 PM Ooo, scala goodness
Tim K 2:21 PM yeah it targets scala BUT it works for java as well !!
Philip Stark 2:23 PM Excellent.. Thank you Tim !
M. Ian Graham 2:25 PM
Tim K 2:25 PM @Will: Are you on Emacs.SE?
Philip Stark 2:26 PM right?
Tim K 2:26 PM yes There’s lots of good content for non-programmers there
Philip Stark 2:26 PM cool. I gotta check that out.
me 2:27 PM Yakshaving:
Tim K 2:32 PM For people who know their way around some of the starter kits: You could definitely score some points answering questions on Emacs.SE. My impression is that there usually aren’t that many people around who can answer these types of questions.
me 2:32 PM Good point!
Will Monroe 2:33 PM Thanks, Tim. That sounds like a good place for someone like me to start.
Tim K 2:33 PM Prelude is probably the one you’re thinking of
M. Ian Graham 2:45 PM
me 2:47 PM (setq helm-yas-display-key-on-candidate t)
Will Monroe 2:58 PM Hey everyone, I’ve really enjoyed listening to and talking with each of you. Have to go. See you all next time!
Tim K 3:03 PM Bye Will!
me 3:04 PM For the text chat: You might like
Tim K 3:12 PM Also: multiple cursors
me 3:23 PM keyfreq?
Tim K 3:25 PM guru-mode ?
me 3:41 PM
Tim K 3:41 PM
me 3:43 PM
Philip Stark 3:43 PM ah thx

Thanks, everyone!