1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
|
;;; nov.el --- Featureful EPUB reader mode
;; Copyright (C) 2017-2019 Vasilij Schneidermann <mail@vasilij.de>
;; Author: Vasilij Schneidermann <mail@vasilij.de>
;; URL: https://github.com/wasamasa/nov.el
;; Version: 0.3.0
;; Package-Requires: ((dash "2.12.0") (esxml "0.3.3") (emacs "24.4"))
;; Keywords: hypermedia, multimedia, epub
;; This file is NOT part of GNU Emacs.
;; 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 <http://www.gnu.org/licenses/>.
;;; Commentary:
;; nov.el provides a major mode for reading EPUB documents.
;;
;; Features:
;;
;; - Basic navigation (jump to TOC, previous/next chapter)
;; - Remembering and restoring the last read position
;; - Jump to next chapter when scrolling beyond end
;; - Storing and following Org links to EPUB files
;; - Renders EPUB2 (.ncx) and EPUB3 (<nav>) TOCs
;; - Hyperlinks to internal and external targets
;; - Supports textual and image documents
;; - Info-style history navigation
;; - View source of document files
;; - Metadata display
;; - Image rescaling
;;; Code:
(require 'cl-lib)
(require 'dash)
(require 'esxml-query)
(require 'shr)
(require 'url-parse)
(require 'recentf)
(require 'bookmark)
(require 'org)
(when (not (fboundp 'libxml-parse-xml-region))
(message "Your Emacs wasn't compiled with libxml support"))
;;; EPUB preparation
(defgroup nov nil
"EPUB reader mode"
:group 'multimedia)
(defcustom nov-unzip-program (executable-find "unzip")
"Path to `unzip` executable."
:type '(file :must-match t)
:group 'nov)
(defcustom nov-variable-pitch t
"Non-nil if a variable pitch face should be used.
Otherwise the default face is used."
:type 'boolean
:group 'nov)
(defcustom nov-text-width nil
"Width filled text shall occupy.
An integer is interpreted as the number of columns. If nil, use
the full window's width. If t, disable filling completely. Note
that this variable only has an effect in Emacs 25.1 or greater."
:type '(choice (integer :tag "Fixed width in characters")
(const :tag "Use the width of the window" nil)
(const :tag "Disable filling" t))
:group 'nov)
(defcustom nov-render-html-function 'nov-render-html
"Function used to render HTML.
It's called without arguments with a buffer containing HTML and
should change it to contain the rendered version of it."
:type 'function
:group 'nov)
(defcustom nov-pre-html-render-hook nil
"Hook run before `nov-render-html'."
:type 'hook
:group 'nov)
(defcustom nov-post-html-render-hook nil
"Hook run after `nov-render-html'."
:type 'hook
:group 'nov)
(defcustom nov-save-place-file (locate-user-emacs-file "nov-places")
"File name where last reading places are saved to and restored from.
If set to `nil', no saving and restoring is performed."
:type '(choice (file :tag "File name")
(const :tag "Don't save last reading places" nil))
:group 'nov)
(defvar-local nov-file-name nil
"Path to the EPUB file backing this buffer.")
(defvar-local nov-temp-dir nil
"Temporary directory containing the buffer's EPUB files.")
(defvar-local nov-content-file nil
"Path to the EPUB buffer's .opf file.")
(defvar-local nov-epub-version nil
"Version string of the EPUB buffer.")
(defvar-local nov-metadata nil
"Metadata of the EPUB buffer.")
(defvar-local nov-documents nil
"Alist for the EPUB buffer's documents.
Each alist item consists of the identifier and full path.")
(defvar-local nov-documents-index 0
"Index of the currently rendered document in the EPUB buffer.")
(defvar-local nov-toc-id nil
"TOC identifier of the EPUB buffer.")
(defvar-local nov-history nil
"Stack of documents user has visited.
Each element of the stack is a list (NODEINDEX BUFFERPOS).")
(defvar-local nov-history-forward nil
"Stack of documents user has visited with `nov-history-back' command.
Each element of the stack is a list (NODEINDEX BUFFERPOS).")
(defun nov-make-path (directory file)
"Create a path from DIRECTORY and FILE."
(concat (file-name-as-directory directory) file))
(defun nov-directory-files (directory)
"Returns a list of files in DIRECTORY except for . and .."
(--remove (string-match-p "/\\.\\(?:\\.\\)?\\'" it)
(directory-files directory t)))
(defun nov-contains-nested-directory-p (directory)
"Non-nil if DIRECTORY contains exactly one directory."
(let* ((files (nov-directory-files directory))
(file (car files)))
(and (= (length files) 1)
(file-directory-p file)
file)))
(defun nov-unnest-directory (directory child)
"Move contents of CHILD into DIRECTORY, then delete CHILD."
;; FIXME: this will most certainly fail for con/con
(dolist (item (nov-directory-files child))
(rename-file item directory))
(delete-directory child))
(defun nov--fix-permissions (file-or-directory mode)
(->> (file-modes file-or-directory)
(file-modes-symbolic-to-number mode)
(set-file-modes file-or-directory)))
(defun nov-fix-permissions (directory)
"Iterate recursively through DIRECTORY to fix its files."
(nov--fix-permissions directory "+rx")
(dolist (file (nov-directory-files directory))
(if (file-directory-p file)
(nov-fix-permissions file)
(nov--fix-permissions file "+r"))))
(defun nov-unzip-epub (directory filename)
"Extract FILENAME into DIRECTORY.
Unnecessary nesting is removed with `nov-unnest-directory'."
(let ((status (call-process nov-unzip-program nil nil t
"-d" directory filename))
child)
(while (setq child (nov-contains-nested-directory-p directory))
(nov-unnest-directory directory child))
;; HACK: unzip preserves file permissions, no matter how silly they
;; are, so ensure files and directories are readable
(nov-fix-permissions directory)
status))
(defmacro nov-ignore-file-errors (&rest body)
"Like `ignore-errors', but for file errors."
`(condition-case nil (progn ,@body) (file-error nil)))
(defun nov-slurp (filename &optional parse-xml-p)
"Return the contents of FILENAME.
If PARSE-XML-P is t, return the contents as parsed by libxml."
(with-temp-buffer
(insert-file-contents filename)
(if parse-xml-p
(libxml-parse-xml-region (point-min) (point-max))
(buffer-string))))
(defun nov-mimetype-valid-p (directory)
"Return t if DIRECTORY contains a valid EPUB mimetype file."
(nov-ignore-file-errors
(let ((filename (nov-make-path directory "mimetype")))
(equal (nov-slurp filename) "application/epub+zip"))))
(defun nov-container-filename (directory)
"Return the container filename for DIRECTORY."
(let ((filename (nov-make-path directory "META-INF")))
(nov-make-path filename "container.xml")))
(defun nov-container-content-filename (content)
"Return the content filename for CONTENT."
(let* ((query "container>rootfiles>rootfile[media-type='application/oebps-package+xml']")
(node (esxml-query query content)))
(esxml-node-attribute 'full-path node)))
(defun nov-container-valid-p (directory)
"Return t if DIRECTORY holds a valid EPUB container."
(let ((filename (nov-container-filename directory)))
(when (and filename (file-exists-p filename))
(let* ((content (nov-slurp filename t))
(content-file (nov-container-content-filename content)))
(when (and content content-file)
(file-exists-p (nov-make-path directory content-file)))))))
(defun nov-epub-valid-p (directory)
"Return t if DIRECTORY makes up a valid EPUB document."
(when (not (nov-mimetype-valid-p directory))
(message "Invalid mimetype"))
(nov-container-valid-p directory))
(defun nov-urldecode (string)
"Return urldecoded version of STRING or nil."
(when string
(url-unhex-string string)))
(defun nov-content-version (content)
"Return the EPUB version for CONTENT."
(let* ((node (esxml-query "package" content))
(version (esxml-node-attribute 'version node)))
(when (not version)
(error "Version not specified"))
version))
(defun nov-content-unique-identifier-name (content)
"Return the unique identifier name referenced in CONTENT.
This is used in `nov-content-unique-identifier' to retrieve the
the specific type of unique identifier."
(let* ((node (esxml-query "package[unique-identifier]" content))
(name (esxml-node-attribute 'unique-identifier node)))
(when (not name)
(error "Unique identifier name not specified"))
name))
(defun nov-content-unique-identifier (content)
"Return the the unique identifier for CONTENT."
(let* ((name (nov-content-unique-identifier-name content))
(selector (format "package>metadata>identifier[id='%s']"
(regexp-quote name)))
(id (car (esxml-node-children (esxml-query selector content)))))
(when (not id)
(error "Unique identifier not found by its name: %s" name))
(intern id)))
;; NOTE: unique identifier is queried separately as identifiers can
;; appear more than once and only one of them can be the unique one
(defvar nov-required-metadata-tags '(title language)
"Required metadata tags used for `nov-content-metadata'.")
(defvar nov-optional-metadata-tags
'(contributor coverage creator date description format
publisher relation rights source subject type)
"Optional metadata tags used for 'nov-content-metadata'.")
(defun nov-content-metadata (content)
"Return a metadata alist for CONTENT.
Required keys are 'identifier and everything in
`nov-required-metadata-tags', optional keys are in
`nov-optional-metadata-tags'."
(let* ((identifier (nov-content-unique-identifier content))
(candidates (mapcar (lambda (node)
(cons (esxml-node-tag node)
(car (esxml-node-children node))))
(esxml-query-all "package>metadata>*" content)))
(required (mapcar (lambda (tag)
(let ((candidate (cdr (assq tag candidates))))
(when (not candidate)
;; NOTE: this should ideally be a
;; warning, but `warn' is too obtrusive
(message "Required metadatum %s not found" tag))
(cons tag candidate)))
nov-required-metadata-tags))
(optional (mapcar (lambda (tag) (cons tag (cdr (assq tag candidates))))
nov-optional-metadata-tags)))
(append `((identifier . ,identifier)) required optional)))
(defun nov-content-manifest (directory content)
"Extract an alist of manifest files for CONTENT in DIRECTORY.
Each alist item consists of the identifier and full path."
(mapcar (lambda (node)
(-let [(&alist 'id id 'href href) (esxml-node-attributes node)]
(cons (intern id)
(nov-make-path directory (nov-urldecode href)))))
(esxml-query-all "package>manifest>item" content)))
(defun nov-content-spine (content)
"Extract a list of spine identifiers for CONTENT."
(mapcar (lambda (node) (intern (esxml-node-attribute 'idref node)))
(esxml-query-all "package>spine>itemref" content)))
(defun nov--content-epub2-files (content manifest files)
(let* ((node (esxml-query "package>spine[toc]" content))
(id (esxml-node-attribute 'toc node)))
(when (not id)
(error "EPUB 2 NCX ID not found"))
(setq nov-toc-id (intern id))
(let ((toc-file (assq nov-toc-id manifest)))
(when (not toc-file)
(error "EPUB 2 NCX file not found"))
(cons toc-file files))))
(defun nov--content-epub3-files (content manifest files)
(let* ((node (esxml-query "package>manifest>item[properties=nav]" content))
(id (esxml-node-attribute 'id node)))
(when (not id)
(error "EPUB 3 <nav> ID not found"))
(setq nov-toc-id (intern id))
(let ((toc-file (assq nov-toc-id manifest)))
(when (not toc-file)
(error "EPUB 3 <nav> file not found"))
(setq files (--remove (eq (car it) nov-toc-id) files))
(cons toc-file files))))
(defun nov-content-files (directory content)
"Create correctly ordered file alist for CONTENT in DIRECTORY.
Each alist item consists of the identifier and full path."
(let* ((manifest (nov-content-manifest directory content))
(spine (nov-content-spine content))
(files (mapcar (lambda (item) (assq item manifest)) spine)))
(if (version< nov-epub-version "3.0")
(nov--content-epub2-files content manifest files)
(nov--content-epub3-files content manifest files))))
(defun nov--walk-ncx-node (node depth)
(let ((tag (esxml-node-tag node))
(children (--filter (eq (esxml-node-tag it) 'navPoint)
(esxml-node-children node))))
(cond
((eq tag 'navMap)
(insert "<ol>\n")
(mapc (lambda (node) (nov--walk-ncx-node node (1+ depth))) children)
(insert "</ol>\n"))
((eq tag 'navPoint)
(let* ((label-node (esxml-query "navLabel>text" node))
(content-node (esxml-query "content" node))
(href (nov-urldecode (esxml-node-attribute 'src content-node)))
(label (car (esxml-node-children label-node))))
(when (not href)
(error "Navigation point is missing href attribute"))
(let ((link (format "<a href=\"%s\">%s</a>" href (or label href))))
(if children
(progn
(insert (format "<li>\n%s\n<ol>\n" link))
(mapc (lambda (node) (nov--walk-ncx-node node (1+ depth)))
children)
(insert (format "</ol>\n</li>\n")))
(insert (format "<li>\n%s\n</li>\n" link)))))))))
(defun nov-ncx-to-html (path)
"Convert NCX document at PATH to HTML."
(let ((root (esxml-query "navMap" (nov-slurp path t))))
(with-temp-buffer
(nov--walk-ncx-node root 0)
(buffer-string))))
;;; UI
(defvar nov-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "g") 'nov-render-document)
(define-key map (kbd "v") 'nov-view-source)
(define-key map (kbd "V") 'nov-view-content-source)
(define-key map (kbd "a") 'nov-reopen-as-archive)
(define-key map (kbd "m") 'nov-display-metadata)
(define-key map (kbd "n") 'nov-next-document)
(define-key map (kbd "]") 'nov-next-document)
(define-key map (kbd "p") 'nov-previous-document)
(define-key map (kbd "[") 'nov-previous-document)
(define-key map (kbd "t") 'nov-goto-toc)
(define-key map (kbd "l") 'nov-history-back)
(define-key map (kbd "r") 'nov-history-forward)
(define-key map (kbd "RET") 'nov-browse-url)
(define-key map (kbd "c") 'nov-copy-url)
(define-key map (kbd "<follow-link>") 'mouse-face)
(define-key map (kbd "<mouse-2>") 'nov-browse-url)
(define-key map (kbd "TAB") 'shr-next-link)
(define-key map (kbd "M-TAB") 'shr-previous-link)
(define-key map (kbd "<backtab>") 'shr-previous-link)
(define-key map (kbd "SPC") 'nov-scroll-up)
(define-key map (kbd "S-SPC") 'nov-scroll-down)
(define-key map (kbd "DEL") 'nov-scroll-down)
(define-key map (kbd "<home>") 'beginning-of-buffer)
(define-key map (kbd "<end>") 'end-of-buffer)
map))
(defun nov-clean-up ()
"Delete temporary files of the current EPUB buffer."
(when nov-temp-dir
(let ((identifier (cdr (assq 'identifier nov-metadata)))
(index (if (integerp nov-documents-index)
nov-documents-index
0)))
(nov-save-place identifier index (point)))
(nov-ignore-file-errors
(delete-directory nov-temp-dir t))))
(defun nov-clean-up-all ()
"Delete temporary files of all opened EPUB buffers."
(dolist (buffer (buffer-list))
(with-current-buffer buffer
(when (eq major-mode 'nov-mode)
(nov-clean-up)))))
(defun nov-external-url-p (url)
"Return t if URL refers to an external document."
(and (url-type (url-generic-parse-url url)) t))
(defun nov-url-filename-and-target (url)
"Return a list of URL's filename and target."
(setq url (url-generic-parse-url url))
(mapcar 'nov-urldecode (list (url-filename url) (url-target url))))
(defun nov-insert-image (path alt)
"Insert an image for PATH at point, falling back to ALT.
This function honors `shr-max-image-proportion' if possible."
(cond
((not (display-graphic-p))
(insert alt))
;; TODO: add native resizing support once it's official
((fboundp 'imagemagick-types)
;; adapted from `shr-rescale-image'
(let ((edges (window-inside-pixel-edges
(get-buffer-window (current-buffer)))))
(insert-image
(create-image path 'imagemagick nil
:ascent 100
:max-width (truncate (* shr-max-image-proportion
(- (nth 2 edges)
(nth 0 edges))))
:max-height (truncate (* shr-max-image-proportion
(- (nth 3 edges)
(nth 1 edges))))))))
(t
;; `create-image' errors out for unsupported image types
(let ((image (ignore-errors (create-image path nil nil :ascent 100))))
(if image
(insert-image image)
(insert alt))))))
(defvar nov-original-shr-tag-img-function
(symbol-function 'shr-tag-img))
(defun nov-render-img (dom &optional url)
"Custom <img> rendering function for DOM.
Uses `shr-tag-img' for external paths and `nov-insert-image' for
internal ones."
(let ((url (or url (cdr (assq 'src (cadr dom)))))
(alt (or (cdr (assq 'alt (cadr dom))) "")))
(if (nov-external-url-p url)
;; HACK: avoid hanging in an infinite loop when using
;; `cl-letf' to override `shr-tag-img' with a function that
;; might call `shr-tag-img' again
(funcall nov-original-shr-tag-img-function dom url)
(setq url (expand-file-name (nov-urldecode url)))
(nov-insert-image url alt))))
(defun nov-render-title (dom)
"Custom <title> rendering function for DOM.
Sets `header-line-format' to a combination of the EPUB title and
chapter title."
(let ((title (cdr (assq 'title nov-metadata)))
(chapter-title (car (esxml-node-children dom))))
(when (not chapter-title)
(setq chapter-title '(:propertize "No title" face italic)))
;; this shouldn't happen for properly authored EPUBs
(when (not title)
(setq title '(:propertize "No title" face italic)))
(setq header-line-format (list title ": " chapter-title))))
(defvar nov-shr-rendering-functions
'(;; default function uses url-retrieve and fails on local images
(img . nov-render-img)
;; titles are rendered *inside* the document by default
(title . nov-render-title))
"Alist of rendering functions used with `shr-render-region'.")
(defun nov-render-html ()
"Render HTML in current buffer with shr."
(run-hooks 'nov-pre-html-render-hook)
(let (;; HACK: make buttons use our own commands
(shr-map nov-mode-map)
(shr-external-rendering-functions nov-shr-rendering-functions)
(shr-use-fonts nov-variable-pitch))
;; HACK: `shr-external-rendering-functions' doesn't cover
;; every usage of `shr-tag-img'
(cl-letf (((symbol-function 'shr-tag-img) 'nov-render-img))
(if (eq nov-text-width t)
(cl-letf (((symbol-function 'shr-fill-line) 'ignore))
(shr-render-region (point-min) (point-max)))
(let ((shr-width nov-text-width))
(shr-render-region (point-min) (point-max))))))
(run-hooks 'nov-post-html-render-hook))
(defun nov-render-document ()
"Render the document referenced by `nov-documents-index'.
If the document path refers to an image (as determined by
`image-type-file-name-regexps'), an image is inserted, otherwise
the HTML is rendered with `nov-render-html-function'."
(interactive)
(let* ((document (aref nov-documents nov-documents-index))
(id (car document))
(path (cdr document))
;; HACK: this should be looked up in the manifest
(imagep (--find (string-match-p (car it) path)
image-type-file-name-regexps))
;; NOTE: allows resolving image references correctly
(default-directory (file-name-directory path))
buffer-read-only)
(erase-buffer)
(cond
(imagep
(nov-insert-image path ""))
((and (version< nov-epub-version "3.0")
(eq id nov-toc-id))
(insert (nov-ncx-to-html path)))
(t
(insert (nov-slurp path))))
(when (not imagep)
(funcall nov-render-html-function))
(goto-char (point-min))))
(defun nov-find-document (predicate)
"Return first item in `nov-documents' PREDICATE is true for."
(let ((i 0)
done)
(while (and (not done)
(< i (length nov-documents)))
(when (funcall predicate (aref nov-documents i))
(setq done t))
(setq i (1+ i)))
(when done
(1- i))))
(defun nov-goto-document (index)
"Go to the document denoted by INDEX."
(let ((history (cons (list nov-documents-index (point))
nov-history)))
(setq nov-documents-index index)
(nov-render-document)
(setq nov-history history)))
(defun nov-goto-toc ()
"Go to the TOC index and render the TOC document."
(interactive)
(let ((index (nov-find-document (lambda (doc) (eq (car doc) nov-toc-id)))))
(when (not index)
(error "Couldn't locate TOC"))
(nov-goto-document index)))
(defun nov-view-source ()
"View the source of the current document in a new buffer."
(interactive)
(find-file (cdr (aref nov-documents nov-documents-index))))
(defun nov-view-content-source ()
"View the source of the content file in a new buffer."
(interactive)
(find-file nov-content-file))
(defun nov-reopen-as-archive ()
"Reopen the EPUB document using `archive-mode'."
(interactive)
(with-current-buffer (find-file-literally nov-file-name)
(archive-mode)))
(defun nov-display-metadata ()
"View the metadata of the EPUB document in a new buffer."
(interactive)
(let ((buffer "*EPUB metadata*")
(metadata nov-metadata)
(version nov-epub-version))
(with-current-buffer (get-buffer-create buffer)
(special-mode)
(let (buffer-read-only)
(erase-buffer)
(insert (format "EPUB Version: %s\n" version))
(dolist (item metadata)
(-let [(key . value) item]
(insert (format "%s: " (capitalize (symbol-name key))))
(if value
(if (eq key 'description)
(let ((beg (point)))
(insert value)
(shr-render-region beg (point)))
(insert (format "%s" value)))
(insert (propertize "None" 'face 'italic)))
(insert "\n")))
(goto-char (point-min))))
(pop-to-buffer buffer)))
(defun nov-next-document ()
"Go to the next document and render it."
(interactive)
(when (< nov-documents-index (1- (length nov-documents)))
(nov-goto-document (1+ nov-documents-index))))
(defun nov-previous-document ()
"Go to the previous document and render it."
(interactive)
(when (> nov-documents-index 0)
(nov-goto-document (1- nov-documents-index))))
(defun nov-scroll-up (arg)
"Scroll with `scroll-up' or visit next chapter if at bottom."
(interactive "P")
(if (>= (window-end) (point-max))
(nov-next-document)
(scroll-up arg)))
(defun nov-scroll-down (arg)
"Scroll with `scroll-down' or visit previous chapter if at top."
(interactive "P")
(if (and (<= (window-start) (point-min))
(> nov-documents-index 0))
(progn
(nov-previous-document)
(goto-char (point-max)))
(scroll-down arg)))
(defun nov-visit-relative-file (filename target)
"Visit the document as specified by FILENAME and TARGET."
(when (not (zerop (length filename)))
(let* ((current-path (cdr (aref nov-documents nov-documents-index)))
(directory (file-name-directory current-path))
(path (file-truename (nov-make-path directory filename)))
(index (nov-find-document
(lambda (doc) (equal path (file-truename (cdr doc)))))))
(when (not index)
(error "Couldn't locate document"))
(setq nov-documents-index index)))
(let ((shr-target-id target))
(nov-goto-document nov-documents-index))
(when target
(let ((pos (next-single-property-change (point-min) 'shr-target-id)))
(when (not pos)
(error "Couldn't locate target"))
(goto-char pos)
(recenter (1- (max 1 scroll-margin))))))
;; adapted from `shr-browse-url'
(defun nov-browse-url (&optional mouse-event)
"Follow an external url with `browse-url'.
Internal URLs are visited with `nov-visit-relative-file'."
(interactive (list last-nonmenu-event))
(mouse-set-point mouse-event)
(let ((url (get-text-property (point) 'shr-url)))
(when (not url)
(user-error "No link under point"))
(if (nov-external-url-p url)
(browse-url url)
(apply 'nov-visit-relative-file (nov-url-filename-and-target url)))))
(defun nov-copy-url (&optional mouse-event)
(interactive (list last-nonmenu-event))
(mouse-set-point mouse-event)
(let ((url (get-text-property (point) 'shr-url)))
(when (not url)
(user-error "No link under point"))
(kill-new url)
(message "%s" url)))
(defun nov-saved-places ()
"Retrieve saved places in `nov-save-place-file'."
(when (and nov-save-place-file (file-exists-p nov-save-place-file))
(with-temp-buffer
(insert-file-contents-literally nov-save-place-file)
(goto-char (point-min))
(read (current-buffer)))))
(defun nov-saved-place (identifier)
"Retrieve saved place for IDENTIFIER in `nov-saved-place-file'."
(cdr (assq identifier (nov-saved-places))))
(defun nov-save-place (identifier index point)
"Save place as identified by IDENTIFIER, INDEX and POINT.
Saving is only done if `nov-save-place-file' is set."
(when nov-save-place-file
(let* ((place `(,identifier (index . ,index)
(point . ,point)))
(places (cons place (assq-delete-all identifier (nov-saved-places))))
print-level
print-length)
(with-temp-file nov-save-place-file
(insert (prin1-to-string places))))))
(defun nov--index-valid-p (documents index)
(and (integerp index)
(>= index 0)
(< index (length documents))))
(defun nov-history-back ()
"Go back in the history to the last visited document."
(interactive)
(or nov-history
(user-error "This is the first document you looked at"))
(let ((history-forward
(cons (list nov-documents-index (point))
nov-history-forward))
(index (car (car nov-history)))
(opoint (cadr (car nov-history))))
(setq nov-history (cdr nov-history))
(nov-goto-document index)
(setq nov-history (cdr nov-history))
(setq nov-history-forward history-forward)
(goto-char opoint)))
(defun nov-history-forward ()
"Go forward in the history of visited documents."
(interactive)
(or nov-history-forward
(user-error "This is the last document you looked at"))
(let ((history-forward (cdr nov-history-forward))
(index (car (car nov-history-forward)))
(opoint (cadr (car nov-history-forward))))
(nov-goto-document index)
(setq nov-history-forward history-forward)
(goto-char opoint)))
;;;###autoload
(define-derived-mode nov-mode special-mode "EPUB"
"Major mode for reading EPUB documents"
(add-hook 'kill-buffer-hook 'nov-clean-up nil t)
(add-hook 'kill-emacs-hook 'nov-clean-up-all)
(add-hook 'change-major-mode-hook 'nov-clean-up nil t)
(when (not buffer-file-name)
(error "EPUB must be associated with file"))
(setq nov-temp-dir (make-temp-file "nov-" t ".epub"))
(let ((exit-code (nov-unzip-epub nov-temp-dir buffer-file-name)))
(when (not (integerp exit-code))
(nov-clean-up)
(error "EPUB extraction aborted by signal %s" exit-code))
(when (not (zerop exit-code))
(nov-clean-up)
(error "EPUB extraction failed with exit code %d" exit-code)))
(when (not (nov-epub-valid-p nov-temp-dir))
(nov-clean-up)
(error "Invalid EPUB file"))
(let* ((content (nov-slurp (nov-container-filename nov-temp-dir) t))
(content-file (->> (nov-container-content-filename content)
(nov-make-path nov-temp-dir)))
(work-dir (file-name-directory content-file))
(content (nov-slurp content-file t)))
(setq nov-content-file content-file)
(setq nov-epub-version (nov-content-version content))
(setq nov-metadata (nov-content-metadata content))
(setq nov-documents (->> (nov-content-files work-dir content)
(apply 'vector)))
(setq nov-documents-index 0))
(setq buffer-undo-list t)
(setq nov-file-name (buffer-file-name))
(setq-local bookmark-make-record-function
'nov-bookmark-make-record)
(set-visited-file-name nil t) ; disable autosaves and save questions
(let ((place (nov-saved-place (cdr (assq 'identifier nov-metadata)))))
(if place
(let ((index (cdr (assq 'index place)))
(point (cdr (assq 'point place))))
(if (nov--index-valid-p nov-documents index)
(progn
(setq nov-documents-index index)
(nov-render-document)
(goto-char point))
(warn "Couldn't restore last position")
(nov-render-document)))
(nov-render-document))))
;;; recentf interop
(defun nov-add-to-recentf ()
(when nov-file-name
(recentf-add-file nov-file-name)))
(add-hook 'nov-mode-hook 'nov-add-to-recentf)
(add-hook 'nov-mode-hook 'hack-dir-local-variables-non-file-buffer)
(defun nov--find-file (file index point)
"Open FILE(nil means current buffer) in nov-mode and go to the specified INDEX and POSITION."
(when file
(find-file file))
(unless (eq major-mode 'nov-mode)
(nov-mode))
(when (not (nov--index-valid-p nov-documents index))
(error "Invalid documents index"))
(setq nov-documents-index index)
(nov-render-document)
(goto-char point))
;; Bookmark Integration
(defun nov-bookmark-make-record ()
"Create a bookmark epub record."
(cons (buffer-name)
`((filename . ,nov-file-name)
(index . ,nov-documents-index)
(position . ,(point))
(handler . nov-bookmark-jump-handler))))
(defun nov-bookmark-jump-handler (bmk)
"The bookmark handler-function interface for bookmark BMK.
See also `nov-bookmark-make-record'."
(let ((file (bookmark-prop-get bmk 'filename))
(index (bookmark-prop-get bmk 'index))
(position (bookmark-prop-get bmk 'position)))
(nov--find-file file index position)))
;;; org interop
(defun nov-org-link-follow (path)
(if (string-match "^\\(.*\\)::\\([0-9]+\\):\\([0-9]+\\)$" path)
(let ((file (match-string 1 path))
(index (string-to-number (match-string 2 path)))
(point (string-to-number (match-string 3 path))))
(nov--find-file file index point))
(error "Invalid nov.el link")))
(defun nov-org-link-store ()
(when (and (eq major-mode 'nov-mode) nov-file-name)
(when (not (integerp nov-documents-index))
(setq nov-documents-index 0))
(org-store-link-props
:type "nov"
:link (format "nov:%s::%d:%d" nov-file-name nov-documents-index (point))
:description (format "EPUB file at %s" nov-file-name))))
(org-link-set-parameters
"nov"
:follow 'nov-org-link-follow
:store 'nov-org-link-store)
(provide 'nov)
;;; nov.el ends here
|