Note Taking with PDF Tools

NOTE: This post has been modified as of 2015-11-22 Sun – the new code is a little cleaner, and I think the discussion a little fuller.

Almost all of my job-related reading is now done on a screen. There are still disadvantages – I find it much harder to concentrate when reading online – but in other ways it is markedly more convenient.

In particular, it is now much easier to assemble quotations from sources; and now that I’ve found PDF Tools, it has become even easier. I’ve just started to use it to extract annotations from my PDF’s, and it works much better than the lousy command-line hack I was using previously.

As we’re mid-semester, most of my reading is for classes I teach. My current workflow is as follows:

  • Assemble the relevant readings in a Dropbox-synced directory (ClassName/Readings)
  • Using Repligo Reader (apparently no longer available in the app store?), highlight the passages I’m interested in.
  • execute code block (see below) to insert org headings with all highlights from one or more pdfs
  • Assemble reveal.js lecture presentation around those highlights, using org-reveal or Pandoc.

Activating PDF Tools

Begin by installing pdf-tools and org-pdfview from ELPA with package-list~packages or package-install.

<p>
  Then make sure they are activated by adding these lines in your init file:
</p>

<div class="org-src-container">
  <pre class="src src-emacs-lisp"><span style="color: #707183;">(</span>pdf-tools-install<span style="color: #707183;">)</span>

(eval-after-load ‘org ‘(requireorg-pdfview)) (add-to-list ‘org-file-apps ‘("\.pdf\'" . org-pdfview-open)) (add-to-list ‘org-file-apps ‘("\.pdf::\([[:digit:]]+\)\'" . org-pdfview-open))

Switching to PDF Tools for annotating and extracting PDF’s

Last month Penguim proposed some changes in a pull request, that export annotations as a set of org headlines. It’s potentially very interesting but not quite what I want to do, so I modified this code. pdf-annot-markups-as-org-text extracts the text of an annotation (stored as the subject attribute in an alist), and also generates a link back to the page in the pdf. mwp/pdf-multi-extract is just a helper function that makes it easier to construct elisp source blocks the way I’m used to doing:

<div class="org-src-container">
  <pre class="src src-emacs-lisp"><span style="color: #b22222;">;; </span><span style="color: #b22222;">modified from https://github.com/politza/pdf-tools/pull/133 </span>

(defun mwp/pdf-multi-extract (sources) “Helper function to print highlighted text from a list of pdf’s, with one org header per pdf, and links back to page of highlight." (let ( (output "")) (dolist (thispdf sources) (setq output (concat output (pdf-annot-markups-as-org-text thispdf nil level )))) (princ output)) )

;; this is stolen from https://github.com/pinguim06/pdf-tools/commit/22629c746878f4e554d4e530306f3433d594a654 (defun pdf-annot-edges-to-region (edges) “Attempt to get 4-entry region (LEFT TOP RIGHT BOTTOM) from several edges. We need this to import annotations and to get marked-up text, because annotations are referenced by its edges, but functions for these tasks need region."

(let ((left0 (nth 0 (car edges))) (top0 (nth 1 (car edges))) (bottom0 (nth 3 (car edges))) (top1 (nth 1 (car (last edges)))) (right1 (nth 2 (car (last edges)))) (bottom1 (nth 3 (car (last edges)))) (n (safe-length edges))) ;; we try to guess the line height to move ;; the region away from the boundary and ;; avoid double lines (list left0 (+ top0 (/ (- bottom0 top0) 2)) right1 (- bottom1 (/ (- bottom1 top1) 2 )))))

(defun pdf-annot-markups-as-org-text (pdfpath &optional title level) “Acquire highligh annotations as text, and return as org-heading”

(interactive “fPath to PDF: “)
(let* ((outputstring "") ;; the text to be returned (title (or title (replace-regexp-in-string "-" ” “ (file-name-base pdfpath )))) (level (or level (1+ (org-current-level)))) ;; I guess if we’re not in an org-buffer this will fail (levelstring (make-string level ?*)) ;; set headline to proper level (annots (sort (pdf-info-getannots nil pdfpath) ;; get and sort all annots ‘pdf-annot-compare-annotations)) ) ;; create the header (setq outputstring (concat levelstring ” Quotes From “ title "\n\n”)) ;; create heading

<span style="color: #b22222;">;; </span><span style="color: #b22222;">extract text</span>
<span style="color: #707183;">(</span>mapc
 <span style="color: #707183;">(</span><span style="color: #a020f0;">lambda</span> <span style="color: #707183;">(</span>annot<span style="color: #707183;">)</span> <span style="color: #b22222;">;; </span><span style="color: #b22222;">traverse all annotations</span>
   <span style="color: #707183;">(</span><span style="color: #a020f0;">if</span> <span style="color: #707183;">(</span>eq 'highlight <span style="color: #707183;">(</span>assoc-default 'type annot<span style="color: #707183;">))</span>
       <span style="color: #707183;">(</span><span style="color: #a020f0;">let*</span> <span style="color: #707183;">((</span>page <span style="color: #707183;">(</span>assoc-default 'page annot<span style="color: #707183;">))</span>
              <span style="color: #b22222;">;; </span><span style="color: #b22222;">use pdf-annot-edges-to-region to get correct boundaries of highlight</span>
              <span style="color: #707183;">(</span>real-edges <span style="color: #707183;">(</span>pdf-annot-edges-to-region
                           <span style="color: #707183;">(</span>pdf-annot-get annot 'markup-edges<span style="color: #707183;">)))</span>
              <span style="color: #707183;">(</span>text <span style="color: #707183;">(</span><span style="color: #a020f0;">or</span> <span style="color: #707183;">(</span>assoc-default 'subject annot<span style="color: #707183;">)</span> <span style="color: #707183;">(</span>assoc-default 'content annot<span style="color: #707183;">)</span>
                        <span style="color: #707183;">(</span>replace-regexp-in-string <span style="color: #8b2252;">"\n"</span> <span style="color: #8b2252;">" "</span> <span style="color: #707183;">(</span>pdf-info-gettext page real-edges nil pdfpath<span style="color: #707183;">)</span>
                                                  <span style="color: #707183;">)</span> <span style="color: #707183;">))</span>

              <span style="color: #707183;">(</span>height <span style="color: #707183;">(</span>nth 1 real-edges<span style="color: #707183;">))</span> <span style="color: #b22222;">;; </span><span style="color: #b22222;">distance down the page</span>
              <span style="color: #b22222;">;; </span><span style="color: #b22222;">use pdfview link directly to page number</span>
              <span style="color: #707183;">(</span>linktext <span style="color: #707183;">(</span>concat <span style="color: #8b2252;">"[[pdfview:"</span> pdfpath <span style="color: #8b2252;">"::"</span> <span style="color: #707183;">(</span>number-to-string page<span style="color: #707183;">)</span> 
                                <span style="color: #8b2252;">"++"</span> <span style="color: #707183;">(</span>number-to-string height<span style="color: #707183;">)</span> <span style="color: #8b2252;">"]["</span> title  <span style="color: #8b2252;">"]]"</span> <span style="color: #707183;">))</span>
              <span style="color: #707183;">)</span>
         <span style="color: #707183;">(</span><span style="color: #a020f0;">setq</span> outputstring <span style="color: #707183;">(</span>concat outputstring text <span style="color: #8b2252;">" ("</span>
                                    linktext <span style="color: #8b2252;">", "</span> <span style="color: #707183;">(</span>number-to-string page<span style="color: #707183;">)</span> <span style="color: #8b2252;">")\n\n"</span><span style="color: #707183;">))</span>
         <span style="color: #707183;">)))</span>
 annots<span style="color: #707183;">)</span>
outputstring <span style="color: #b22222;">;; </span><span style="color: #b22222;">return the header</span>
<span style="color: #707183;">)</span>

)

Using in Org with a Source Block

Now it’s more or less trivial to quickly generate the org headers using a source block:

<pre class="example">

#+BEGIN_SRC elisp :results output raw :var level=(1+ (org-current-level)) (mwp/pdf-multi-extract ‘( “/home/matt/HackingHistory/readings/Troper-becoming-immigrant-city.pdf” “/home/matt/HackingHistory/readings/historical-authority-hampton.pdf”))

#+END_SRC

<p>
  And the output gives something like
</p>

<p>
  #+BEGIN_EXAMPLE
</p>

Quotes From Troper becoming immigrant city

Included in the Greater Toronto Area multiethnic mix are an estimated 450,000 Chinese, 400,000 Italians, and 250,000 African Canadians, the largest component of which are ofCar- ibbean background, although a separate and distinct infusion of Soma- lis, Ethiopians, and other Africans is currently taking place. (Troper becoming immigrant city, 3)

<p>
  Although Toronto is Canada&rsquo;s leading immigrant-receiving centre, city officials have neither a hands-on role in immigrant selection nor an official voice in deciding immigration policy. In Canada, immigration policy and administration is a constitutional responsibility of the fed- eral government, worked out in consultation with the provinces. (<a href="http://matt.hackinghistory.ca/wp-content/uploads/2015/11/wpid-Troper-becoming-immigrant-city.pdf">Troper becoming immigrant city</a>, 4)
</p>

<p>
  #+END_EXAMPLE
</p>

Alternative: Temporary buffer with custom link type

An alternative workflow would be to pop to a second, temporary buffer and insert the annotations there; one could do this with a custom link type. PDF-Tools already has a mechanism for listing annotations in a separate buffer, but it’s not designed for quick access to all annotations at once. Anyway, here’s one way to do this; I’m not really using it at the moment.

<div class="org-src-container">
  <pre class="src src-emacs-lisp"><span style="color: #707183;">(</span>org-add-link-type <span style="color: #8b2252;">"pdfquote"</span> 'org-pdfquote-open 'org-pdfquote-export<span style="color: #707183;">)</span>

(defun org-pdfquote-open (link) “Open a new buffer with all markup annotations in an org headline." (interactive) (pop-to-buffer (format "Quotes from %s" (file-name-base link))) (org-mode) (erase-buffer) (insert (pdf-annot-markups-as-org-text link nil 1)) (goto-char 0) )

(defun org-pdfquote-export (link description format) “Export the pdfview LINK with DESCRIPTION for FORMAT from Org files." (let* ((path (when (string-match "\(.+\)::.+" link) (match-string 1 link))) (desc (or description link))) (when (stringp path) (setq path (org-link-escape (expand-file-name path))) (cond ((eq format ‘html) (format "<a href="%s">%s</a>" path desc)) ((eq format ‘latex) (format "\href{%s}{%s}" path desc)) ((eq format ‘ascii) (format "%s (%s)" desc path)) (t path)))))

(defun org-pdfquote-complete-link () “Use the existing file name completion for file. Links to get the file name, then ask the user for the page number and append it."

(replace-regexp-in-string "^file:" “pdfquote:" (org-file-complete-link)))

<p>
  I&rsquo;ve also added two bindings to make highlighting easier from the PDF buffer:
</p>

<div class="org-src-container">
  <pre class="src src-emacs-lisp"><span style="color: #707183;">(</span>eval-after-load 'pdf-view 
                '<span style="color: #707183;">(</span>define-key pdf-view-mode-map <span style="color: #707183;">(</span>kbd <span style="color: #8b2252;">"M-h"</span><span style="color: #707183;">)</span> 'pdf-annot-add-highlight-markup-annotation<span style="color: #707183;">))</span>

(eval-after-load ‘pdf-view ‘(define-key pdf-view-mode-map (kbd "<tab>") ‘pdf-annot-add-highlight-markup-annotation))

<p>
  All of this is getting me very close to using Emacs for all my PDF work. I am doing maybe 50% of my PDF work in Emacs instead of on my tablet. It&rsquo;s incredibly convenient, although I still find it a little harder to concentrate on my laptop than on the tablet (for reasons ergonomic, optical, and psychological). Here are the remaining papercuts from my perspective:
</p>

<ul class="org-ul">
  <li>
    Highlighting text with the mouse is more awkward and less intimate than using my fingertip on a laptop. I often find mouse movement a little awkward in Emacs, but pdf-view purposely relies on the mouse for movement (for good reasons).
  </li>
  <li>
    Scrolling in pdf-view is also a bit awkward, and there&rsquo;s no &ldquo;continuous&rdquo; mode as one might find in Evince or acroread. Again, I often find scrolling an issue in Emacs, so this might not be so easy to fix.
  </li>
  <li>
    Finally, the laptop screen is just harder on my eyes than my high-res tablet. pdf-view hasa &ldquo;midnight mode&rdquo; which makes it a little easier to read, but it&rsquo;s not quite enough.
  </li>
</ul>

<p>
  So, for the time being I will probably do much of my reading on the tablet. But for short pieces and for review (e.g., papers that I&rsquo;m reading for the third year in a row in a graduate seminar&#x2026;) PDF Tools is now my main interface. Which is pretty sweet.
</p>

Todo

UPDATE: I would like to extend the pdfview link type (in org-pdfview) to permit me to specify the precise location of an annotation, so I can jump precisely to that part of the page. This has now been done and the code above has been updated to reflect the new syntax.

<p>
  <b>UPDATE:</b> <del>Also, now that I think about it, it might be interesting to just have a link type that pops up a temporary buffer with all of the annotations; I could then cut and paste the annotations into the master document. This might be even more convenient.</del> OK, I&rsquo;ve implemented this, see above!
</p>

<p>
  <b>Update <span class="timestamp-wrapper"><span class="timestamp">2015-11-22 Sun</span></span>:</b> I&rsquo;ve cleaned up some of the code, and added a bit more commentary at the end.
</p>
Last modified: 11 November 2015