-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathref-man-export.el
1662 lines (1484 loc) · 73 KB
/
ref-man-export.el
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
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; ref-man-export.el --- Document export and publishing functionality for `ref-man'. ;;; -*- lexical-binding: t; -*-
;; Copyright (C) 2018,2019,2020,2021,2022,2023
;; Akshay Badola
;; Author: Akshay Badola <akshay.badola.cs@gmail.com>
;; Maintainer: Akshay Badola <akshay.badola.cs@gmail.com>
;; Time-stamp: <Monday 28 August 2023 08:30:07 AM IST>
;; Keywords: pdfs, references, bibtex, org, eww
;; 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, 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
;; GNU Emacs; see the file COPYING. If not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
;;; Commentary:
;;
;; Export functions for `ref-man'.
;;
;; We use `pandoc' for exporting. Currently we export from an `org-mode'
;; buffers but other modes can also be handled easily.
;;
;; We use markdown as intermediate format for exporting as then it can be used
;; by many other frameworks and `pandoc' has good support for embedding extra
;; metadata in markdown. While data like username and email can be setup easily
;; in `org', we also generate the bibliography directly from org text
;; links. Which means we either keep temporary .bib files corresponding to each
;; generated file or embed the bibliography in the metadata. Putting all that
;; data inside the org properties or any other drawer would be redundant, so we
;; include that information in the yaml header in the markdown file.
;;; Code:
(require 'util)
(require 'ox)
(require 'ox-gfm)
(require 'yaml) ; TODO: yaml is actually not used
(require 'ref-man-core)
(defcustom ref-man-export-blog-dir (expand-file-name "~/.ref-man/blog/")
"Directory where the org files corresponding to documents will be stored."
:type 'directory
:group 'ref-man)
(defcustom ref-man-export-pandoc-templates-dir (expand-file-name "~/.pandoc/templates")
"Directory for pandoc templates."
:type 'directory
:group 'ref-man)
(defcustom ref-man-export-pandoc-csl-dir (expand-file-name "~/.pandoc/csl")
"Directory for csl files."
:type 'directory
:group 'ref-man)
(defcustom ref-man-export-author-name ""
"Name of the author for export articles."
:type 'string
:group 'ref-man)
(defcustom ref-man-export-author-email ""
"Default email of the author for export articles."
:type 'string
:group 'ref-man)
(defcustom ref-man-export-author-affiliation ""
"Default affiliation key of the author for export articles.
The affiliation details are the values of the alist.
See `ref-man-research-article-affiliations-alist'."
:type 'string
:group 'ref-man)
(defcustom ref-man-research-article-affiliations-alist nil
"Affiliation alist of the author for export articles."
:type 'alist
:group 'ref-man)
;; TODO: Import from an alist like `ref-man-export-research-article-args'
(defcustom ref-man-export-default-opts
'(("title" . "")
("author" . "")
("link-citations" . t)
("mathjax" . "")
("csl" . ""))
"Default options for `ref-man-export'."
:type 'alist
:group 'ref-man)
(defcustom ref-man-export-blog-extra-opts
'(("date" . "")
("category" . "")
("tags" . "")
("keywords" . "")
("draft" . t))
"Default blog options for `ref-man-export'."
:type 'alist
:group 'ref-man)
(defcustom ref-man-export-research-article-args nil
"Extra arguments for exporting a research article.
Should be an `alist' parseable by `yaml-encode'."
:type 'alist
:group 'ref-man)
(defcustom ref-man-export-journal-args nil
"Extra journal specific arguments."
:type 'alist
:group 'ref-man)
(defcustom ref-man-export-output-dir ""
"Export output directory."
:type 'directory
:group 'ref-man)
(defcustom ref-man-export-mathjax-dir ""
"Directory of docproc."
:type 'directory
:group 'ref-man)
(defcustom ref-man-export-bib-no-warn-types '((blog . ("http" "https")))
"Don't warn for these links."
:type 'alist
:group 'ref-man)
(defcustom ref-man-export-csl-urls-file nil
"Path to csl file which would allow including urls."
:type 'file
:group 'ref-man)
(defcustom ref-man-export-csl-no-urls-file nil
"Path to csl file which would not allow including urls."
:type 'file
:group 'ref-man)
(defcustom ref-man-export-python-executable "/usr/bin/python3"
"Path to the python executable for calling `pndconf'."
:type 'file
:group 'ref-man)
(defvar ref-man-export-temp-org-buf " *ref-man-export-org-buf*"
"Intermediate org buffer for preprocessing while exporting.")
(defvar ref-man-export-temp-md-buf " *ref-man-export-md-buf*"
"Markdown buffer name where org buffer is exported.")
(defvar ref-man-export-pre-export-md-functions
'(ref-man-replace-multiple-spaces-with-a-single-space)
"Functions to run on org buffer just before export to markdown.
Functions added to this hook should run with no arguments on the
current buffer. The functions would manipulate the org buffer
accordingly and must preserve the org buffer structure.
The default value is
`ref-man-replace-multiple-spaces-with-a-single-space' which is a
clean up function replacing multiple spaces with a single space.")
(defvar ref-man-export-metadata-hook '(ref-man-export-get-paper-metadata
ref-man-export-get-article-metadata)
"Hook to run while exporting org properties as pandoc metadata.
The functions in this hook should modify
`ref-man-export-metadata' by appending to it an alist of any
custom metadata extraction method.
See `ref-man-export-get-paper-metadata' and
`ref-man-export-get-journal-metadata' for examples.")
(defvar ref-man-export-journal-specific-metadata-hook nil
"Like `ref-man-export-metadata-hook' but for individual journals/venues.")
(defvar ref-man-export-metadata nil
"Variable to gather results of `ref-man-export-metadata-hook'.")
(defcustom ref-man-export-pdflatex-env-vars ""
"Environment variables for pdflatex."
:type 'string
:group 'ref-man)
(defcustom ref-man-export-paper-version-org-file nil
"Save current org version file to disk for output type \\='paper.
When non-nil write an org file with md5 sum suffix also along
with markdown file. Only for output type \\='paper."
:type 'boolean
:group 'ref-man)
(defcustom ref-man-export-no-confirm-overwrite nil
"Do not confirm to overwrite markdown file.
This variable controls the global confirmation behaviour, while
for individual documents it can be set as NO_CONFIRM nil or t
in the properties drawer of the subtree."
:type 'boolean
:group 'ref-man)
(defvar ref-man-export-pndconf-config-file nil
"`pndconf' config file.")
(defvar ref-man-pandoc-bibtex-executable ref-man-pandoc-executable
"Pandoc executable for converting bibtex to yaml.
Defaults to `ref-man-pandoc-executable'.")
;; TEST
;; (with-current-buffer "test.org"
;; (let ((ref-man-export-no-confirm-overwrite t))
;; (pcase (org-entry-get (point) "NO_CONFIRM" nil t)
;; ("t" t)
;; ("nil" nil)
;; (_ ref-man-export-no-confirm-overwrite))))
(defun ref-man-pandoc-has-server ()
"Pandoc bibtex executable is compiled with server.
Both the executable `ref-man-pandoc-bibtex-executable' and if the
server is running are checked."
(and
(string-match-p "\\+server"
(shell-command-to-string
(format "%s -v" ref-man-pandoc-bibtex-executable)))
(condition-case nil
(with-current-buffer (url-retrieve-synchronously "http://localhost:3030/version")
(buffer-string))
(error nil))))
(defun ref-man-export-templates ()
"Get templates as an alist from `ref-man-export-pandoc-templates-dir'."
(mapcar
(lambda (x) (cons
(downcase (replace-regexp-in-string "\\.template\\|default\\." ""
(f-filename x)))
x))
(f-files ref-man-export-pandoc-templates-dir)))
(defun ref-man-export-csl-files (csl-file)
"Get the full path for CSL-FILE.
Files are searched in `ref-man-export-pandoc-csl-dir'"
(a-get (mapcar
(lambda (x) (cons
(downcase (string-remove-suffix ".csl" (f-filename x)))
x))
(-filter (lambda (x) (string-suffix-p ".csl" (f-filename x)))
(f-files ref-man-export-pandoc-csl-dir)))
(string-remove-suffix ".csl" csl-file)))
;; TODO: This should be a macro
(defun ref-man-export-pdf-template ()
"Get template for PDF generation."
(a-get (ref-man-export-templates)
(or (org-entry-get (point) "TEMPLATE") "latex")))
(defun ref-man-export-paper-template ()
"Get template for paper generation."
(a-get (ref-man-export-templates)
(or (org-entry-get (point) "TEMPLATE") "ieee")))
(defun ref-man-export-html-template ()
"Get template for html generation."
(a-get (ref-man-export-templates)
(or (org-entry-get (point) "TEMPLATE") "blog")))
;; NOTE: For customization of filtering various org elements
(eval-when-compile
(if (version< org-version "9.6.0")
(org-export-define-derived-backend 'ref-md 'html
:filters-alist '((:filter-parse-tree . org-md-separate-elements))
:menu-entry
'(?m "Export to Markdown"
((?M "To temporary buffer"
(lambda (a s v b) (org-md-export-as-markdown a s v)))
(?m "To file" (lambda (a s v b) (org-md-export-to-markdown a s v)))
(?o "To file and open"
(lambda (a s v b)
(if a (org-md-export-to-markdown t s v)
(org-open-file (org-md-export-to-markdown nil s v)))))))
:translate-alist '((bold . org-md-bold)
(center-block . org-md--convert-to-html)
(code . org-md-verbatim)
(drawer . org-md--identity)
(dynamic-block . org-md--identity)
(example-block . org-md-example-block)
(export-block . org-md-export-block)
(fixed-width . org-md-example-block)
(headline . org-md-headline)
(horizontal-rule . org-md-horizontal-rule)
(inline-src-block . org-md-verbatim)
(inlinetask . org-md--convert-to-html)
(inner-template . org-md-inner-template)
(italic . org-md-italic)
(item . org-md-item)
(keyword . org-md-keyword)
(latex-environment . org-md-latex-environment)
(latex-fragment . org-md-latex-fragment)
(line-break . org-md-line-break)
(link . org-md-link)
(node-property . org-md-node-property)
(paragraph . org-md-paragraph)
(plain-list . org-md-plain-list)
(plain-text . org-md-plain-text)
(property-drawer . org-md-property-drawer)
(quote-block . org-md-quote-block)
(section . org-md-section)
(special-block . org-md--convert-to-html)
(src-block . org-md-example-block)
(table . org-md-verbatim)
(template . org-md-template)
(verbatim . org-md-verbatim))
:options-alist
'((:md-footnote-format nil nil org-md-footnote-format)
(:md-footnotes-section nil nil org-md-footnotes-section)
(:md-headline-style nil nil org-md-headline-style)))
(org-export-define-derived-backend 'ref-md 'html
:filters-alist '((:filter-parse-tree . org-md-separate-elements))
:menu-entry
'(?m "Export to Markdown"
((?M "To temporary buffer"
(lambda (a s v b) (org-md-export-as-markdown a s v)))
(?m "To file" (lambda (a s v b) (org-md-export-to-markdown a s v)))
(?o "To file and open"
(lambda (a s v b)
(if a (org-md-export-to-markdown t s v)
(org-open-file (org-md-export-to-markdown nil s v)))))))
:translate-alist '((bold . org-md-bold)
(center-block . org-md--convert-to-html)
(code . org-md-verbatim)
(drawer . org-md--identity)
(dynamic-block . org-md--identity)
(example-block . org-md-example-block)
(export-block . org-md-export-block)
(fixed-width . org-md-example-block)
(headline . org-md-headline)
(horizontal-rule . org-md-horizontal-rule)
(inline-src-block . org-md-verbatim)
(inlinetask . org-md--convert-to-html)
(inner-template . org-md-inner-template)
(italic . org-md-italic)
(item . org-md-item)
(keyword . org-md-keyword)
(latex-environment . org-md-latex-environment)
(latex-fragment . org-md-latex-fragment)
(line-break . org-md-line-break)
(link . org-md-link)
(node-property . org-md-node-property)
(paragraph . org-md-paragraph)
(plain-list . org-md-plain-list)
(plain-text . org-md-plain-text)
(property-drawer . org-md-property-drawer)
(quote-block . org-md-quote-block)
(section . org-md-section)
(special-block . org-md--convert-to-html)
(src-block . org-md-example-block)
(table . org-md-verbatim)
(template . org-md-template)
(verbatim . org-md-verbatim))
:options-alist
'((:md-footnote-format nil nil org-md-footnote-format)
(:md-footnotes-section nil nil org-md-footnotes-section)
(:md-headline-style nil nil org-md-headline-style)
(:md-toplevel-hlevel nil nil org-md-toplevel-hlevel)))))
;; NOTE: Copied from `ox-gfm' in case modifications are needed
(org-export-define-derived-backend 'ref-gfm 'gfm
:filters-alist '((:filter-parse-tree . org-md-separate-elements))
:menu-entry
'(?g "Export to Github Flavored Markdown"
((?G "To temporary buffer"
(lambda (a s v b) (org-gfm-export-as-markdown a s v)))
(?g "To file" (lambda (a s v b) (org-gfm-export-to-markdown a s v)))
(?o "To file and open"
(lambda (a s v b)
(if a (org-gfm-export-to-markdown t s v)
(org-open-file (org-gfm-export-to-markdown nil s v)))))))
:translate-alist '((inner-template . org-gfm-inner-template)
(paragraph . org-gfm-paragraph)
(strike-through . org-gfm-strike-through)
(src-block . org-gfm-src-block)
(table-cell . org-gfm-table-cell)
(table-row . org-gfm-table-row)
(table . org-gfm-table)))
(defun ref-man-export-org-to-md (type &optional subtree output-org-file)
"Copy the org buffer to temp buffer and export to markdown.
We convert all internal org links to file-local links so that
they'll be subbed with citation formats later.
Hook `ref-man-export-pre-export-md-functions' is run before export to markdown.
TYPE controls the backend used to generate the markdown buffer.
With optional non-nil SUBTREE, export only subtree.
If optional OUTPUT-ORG-FILE is non-nil, then the buffer is
written to it after `ref-man-export-pre-export-md-functions'
execution."
(save-restriction
(let ((buf-string (if (not subtree)
(buffer-string)
(org-narrow-to-subtree)
(buffer-string)))
(link-re ref-man-maybe-file-fuzzy-custid-link-re)
(backend (pcase type
((or 'html 'pdf 'blog 'both 'ref-gfm) 'ref-gfm)
('paper 'ref-md)
(_ nil)))
(ref-man-export-pre-export-md-functions
'(util/org-remove-all-time-stamps ref-man-replace-multiple-spaces-with-a-single-space))
org-export-show-temporary-export-buffer)
(with-current-buffer (get-buffer-create ref-man-export-temp-org-buf)
(erase-buffer)
(insert buf-string)
(org-mode)
;; NOTE: Promote subtree to top level
(while (progn (goto-char (point-min))
(and (or (org-at-heading-p)
(outline-next-heading))
(> (org-current-level) 1)))
(while (re-search-forward "\\(^\\*+\\)\\( +\\)\\(.+\\)" nil t)
(beginning-of-line)
(delete-char 1)
(end-of-line)))
;; (when output-org-file
;; (write-region (point-min) (point-max) output-org-file))
(goto-char (point-min))
(while (re-search-forward link-re nil t)
(pcase-let ((`(,a ,b) (list (match-string 1) (match-string 2))))
(replace-match
(format "[[%s][%s]]" (replace-regexp-in-string "\\(?:file:\\)?.+::" "" a) b))))
(run-hook-with-args 'ref-man-export-pre-export-md-functions)
(org-export-to-buffer backend ref-man-export-temp-md-buf nil nil nil nil)
(when output-org-file
(write-file output-org-file))))))
(defun ref-man-export-get-abstract-bibtexs (type metadata)
"Get abstract and bibtexs from the buffer.
Org buffer may be possibly narrowed.
TYPE is the type of article being processed.
METADATA is the existing metadata.
METADATA is modified and returned in a list along with bibtexs and abstract."
(let (abstract bibtexs)
;; NOTE: Get bounds of article
(pcase type
('paper (let ((beg (a-get metadata "sections-beg"))
(end (a-get metadata "sections-end")))
;; NOTE: When it's a paper, first paragraph is abstract and we
;; go to first subheading
(setq abstract (a-get metadata "abstract"))
(narrow-to-region beg end)
(setq metadata (a-dissoc metadata "abstract" "doc-root" "sections-beg" "sections-end"))))
(_ nil))
(setq bibtexs (ref-man-export-parse-references type (a-get ref-man-export-bib-no-warn-types type)))
(setq bibtexs (mapcar (lambda (x)
`(,(car x) ,(nth 1 x) ,(replace-regexp-in-string "venue=" "booktitle=" (nth 2 x))))
bibtexs))
(list abstract bibtexs metadata)))
;; FIXME: blog-opts is unused
(defun ref-man-export-get-opts (type title bib-file mathjax-path csl-file
&optional no-refs)
"Generate alist for yaml metadata for `ref-man-export-docproc-article'.
TYPE is one of \\='html \\='pdf \\='both \\='blog, TITLE is the title of the
article, BIB-FILE is the additional bibliography file for
citations, MATHJAX-PATH is the path where Mathjax scripts would
be located and CSL-FILE is the Citation Style File.
Don't include bibliography when NO-REFS is non-nil."
(let ((opts ref-man-export-default-opts)
(blog-opts ref-man-export-blog-extra-opts)
(author ref-man-export-author-name))
(setq opts (a-assoc opts
"title" title
"author" author
"mathjax" mathjax-path
"csl" csl-file))
(unless no-refs
(setq opts (a-assoc opts
"bibliography"
(if bib-file
(cons bib-file ref-man-bib-files)
ref-man-bib-files))))
(when (eq type 'blog)
(setq opts
(a-assoc opts
"date" (time-stamp-string "%Y-%m-%d")
"category" (or (util/org-get-tree-prop "CATEGORY_ROOT" t)
(downcase (let ((category (ref-man-org-ask-to-set-property "BLOG_CATEGORY")))
(if (and category (not (string-empty-p category)))
category
(user-error "Cannot export to blog without category")))))
"tags" (or (org-get-tags nil t)
(downcase (let ((blog-tags (ref-man-org-ask-to-set-property "BLOG_TAGS")))
(if (and blog-tags (not (string-empty-p blog-tags)))
blog-tags
(user-error "Cannot export to blog without tags")))))
"keywords" (downcase (or (ref-man-org-ask-to-set-property "BLOG_KEYWORDS")
(ref-man-org-ask-to-set-property "BLOG_TAGS"))))))
(when (eq type 'article)
(setq opts
(a-assoc opts
"date" (time-stamp-string "%Y-%m-%d")
"toc" t
"toc-depth" 2)))
opts))
(defun ref-man-export-bibtex-to-yaml-via-shell (citeproc temp-file)
"Get bibtex yaml metadata via executing pandoc shell command on TEMP-FILE.
CITEPROC is the citation processor to use with pandoc."
(replace-regexp-in-string
"^---\\|^nocite.*" ""
(shell-command-to-string (format "%s -s -f %s -t markdown %s"
ref-man-pandoc-executable
citeproc
temp-file))))
(defun ref-man-export-bibtex-to-yaml-via-pandoc-server (bib-text citeproc)
"Get bibtex yaml metadata for BIB-TEXT via pandoc server.
CITEPROC is the citation processor to use with pandoc."
(replace-regexp-in-string
"^---\\|^nocite.*" ""
(let* ((url "http://localhost:3030")
(data `((text . ,bib-text)
(standalone . t)
(from . ,citeproc)
(to . markdown)))
(url-request-extra-headers
'(("Content-Type" . "application/json")))
(url-request-method "POST")
(url-request-data
(encode-coding-string (json-encode data) 'utf-8)))
(with-current-buffer (url-retrieve-synchronously url)
(goto-char (point-min))
(forward-paragraph)
(buffer-substring (point) (point-max))))))
(defun ref-man-export-bib-strings-to-yaml-via-temp-file (citeproc)
"Export bibtex strings BIBTEXS to yaml via `pandoc' and temp file.
CITEPROC is the citation processor. One of `bibtex' or `biblatex'."
(let ((temp-file (make-temp-file ".tmp-bib"))
(cur (point-max)))
(write-region (point-min) (point-max) temp-file)
(goto-char cur)
(insert (ref-man-export-bibtex-to-yaml-via-shell citeproc temp-file))
(delete-file temp-file)
(util/delete-blank-lines-in-region cur (point-max))
(buffer-substring-no-properties cur (point-max))))
(defun ref-man-export-bib-strings (bibtexs citeproc &optional tmp-bib-file no-gdrive)
"Export bibtex strings BIBTEXS to yaml or bib file.
CITEPROC is the citation processor to use. Can be one of
`bibtex' or `biblatex'.
If optional TMP-BIB-FILE is given then write to that file.
Default is to export the BIBTEXS string as yaml metadata which is
read by `pandoc'.
Optional NO-GDRIVE implies to remove the gdrive keys if present."
(when bibtexs
(with-temp-buffer
(insert (mapconcat (lambda (x)
(ref-man--replace-non-ascii (nth 2 x)))
bibtexs ""))
(unless no-gdrive
(goto-char (point-min))
;; Replace "gdrive" with "issn" in bibs
(while (re-search-forward "gdrive=" nil t nil)
(replace-match "issn=")))
(cond (tmp-bib-file
(write-region (point-min) (point-max) tmp-bib-file))
;; Just use pandoc server if available
((ref-man-pandoc-has-server)
(ref-man-export-bibtex-to-yaml-via-pandoc-server (buffer-string) citeproc))
;; NOTE: Write to a temp file if \' accents are present
((string-match-p "'" (buffer-string))
(ref-man-export-bib-strings-to-yaml-via-temp-file citeproc))
(t
(ref-man-export-bib-strings-to-yaml-via-temp-file citeproc))))))
(defun ref-man-export-check-author (author)
"Check and return AUTHOR type as an alist.
Author is a string of comma separated author names with each
author being combination affiliation:name:email.
If no author or an incorrect type is given then return the
default author alist."
(if (and author (not (string-empty-p author)))
(let ((splits (-remove #'string-empty-p (split-string author ","))))
(when (-all? (lambda (y) (= y 3))
(mapcar (lambda (x) (length (split-string x ":"))) splits))
(mapcar (lambda (x)
(unless (string-empty-p x)
(pcase-let
((`(,aff ,name ,email)
(mapcar 'string-trim (split-string
(replace-regexp-in-string "<\\|>" "" x) ":"))))
`(("affiliation" . ,aff) ("name" . ,name) ("email" . ,email)))))
splits)))
`((("name" . ,ref-man-export-author-name)
("email" . ,ref-man-export-author-email)
("affiliation" . ,ref-man-export-author-affiliation)))))
(defun ref-man-export-get-article-metadata (type)
"Extract keywords and standard metadata for journal.
TYPE has to be \\='paper for this hook to run."
(when (or (eq type 'paper) (eq type 'pdf))
(let* ((props (org-entry-properties))
(author (ref-man-export-check-author (a-get props "AUTHOR")))
(affiliations (mapcar (lambda (y)
(a-get ref-man-research-article-affiliations-alist y))
(-uniq (mapcar
(lambda (x) (a-get x "affiliation"))
author)))))
(setq ref-man-export-metadata
(-concat ref-man-export-metadata
`(("author" . ,author)
("keywords" . ,(when (a-get props "KEYWORDS")
(split-string (a-get props "KEYWORDS") ",")))
("caption" . ,(a-get props "CAPTION"))
("affiliations" . ,affiliations)))))))
(defun ref-man-export-get-journal-metadata (type)
"Extract journal type and template from property drawer.
TYPE has to be \\='paper for this hook to run."
(when (eq type 'paper)
(let* ((props (org-entry-properties)))
(setq ref-man-export-metadata
(-concat ref-man-export-metadata
`(("journal" . ,(a-get props "JOURNAL"))
("template" . ,(a-get props "TEMPLATE")))
(a-get ref-man-export-journal-args (a-get props "JOURNAL")))))))
(defun ref-man-export-get-paper-metadata (type)
"Extract abstract and section demarcations for TYPE \\='paper."
(when (eq type 'paper)
(save-excursion
(save-restriction
(org-narrow-to-subtree)
(pcase-let* ((`(,root ,before-refs) (ref-man-org-get-bounds-before-references))
(`(,beg ,end ,has-body) (progn (goto-char root)
(ref-man-org-text-bounds))))
(when has-body
(setq ref-man-export-metadata
(a-assoc ref-man-export-metadata
"abstract" (buffer-substring-no-properties beg end))))
(setq ref-man-export-metadata
(a-assoc ref-man-export-metadata
"doc-root" root
"sections-beg" end
"sections-end" before-refs)))))))
(defun ref-man-export-get-all-imgs-subr (doc-root)
(let (imgs)
(save-excursion
(if doc-root
(goto-char doc-root)
(goto-char (point-min)))
(save-restriction
(when doc-root
(org-narrow-to-subtree))
(while (re-search-forward "\\includegraphics\\(?:\\[.+?]\\){\\(.+?\\)}" nil t)
(push (substring-no-properties (match-string 1)) imgs))))
imgs))
(defun ref-man-export-get-all-imgs (&optional buffer-or-filename)
"Return list of all file paths in `includegraphics' directives for org subtree.
Optional BUFFER specifies the org buffer."
(let* ((buffer (unless (stringp buffer-or-filename)
(or buffer-or-filename (current-buffer))))
(doc-root (when buffer (util/org-get-tree-prop "DOC_ROOT"))))
(if buffer
(with-current-buffer buffer
(unless doc-root
(user-error "For extraction of images for a research article, a DOC_ROOT must be specified"))
(ref-man-export-get-all-imgs-subr doc-root))
(let ((buffer (find-file-noselect buffer-or-filename)))
(with-current-buffer buffer
(prog1 (ref-man-export-get-all-imgs-subr nil)
(kill-buffer)))))))
(defun ref-man-export-link-standalone-files (&optional tex-file out-dir)
"Copy all supporting files corresponding to a TEX-FILE.
Create a new folder based on the title of the document and copy
the img, supporting tex and bib files for easy upload to
servers.
With a \\[universal-argument] the name is read from the
minibuffer, else it's determined from the \"title\" field of the
tex file."
(interactive "p")
(unless tex-file
(error "Latex file must be given when calling non-interactively"))
(let* ((interactive-p (numberp tex-file))
(tex-file (or (and (not interactive-p) tex-file)
(ido-read-file-name "Enter the tex file path: ")))
(bib-file (concat (string-remove-suffix ".tex" tex-file) ".bib"))
(docs-dir ref-man-export-output-dir)
(buf (find-file-noselect tex-file))
(doc-name (with-current-buffer buf
(progn
(goto-char (point-min))
(re-search-forward "\\title{\\(\\(.\\|\n\\)?+?\\)}")
(downcase
(string-join
(mapcar #'ref-man--remove-punc
(split-string
(substring-no-properties (match-string 1))))
"-")))))
(out-dir (or out-dir (f-join docs-dir (concat doc-name "-standalone/"))))
(out-file (f-join out-dir (f-filename tex-file)))
(out-bib-file (concat (string-remove-suffix ".tex" out-file) ".bib")))
(kill-buffer buf)
(unless (f-exists? out-dir)
(f-mkdir out-dir))
(copy-file tex-file out-file t)
(when (find-buffer-visiting out-file)
(kill-buffer (find-buffer-visiting out-file)))
(make-symbolic-link bib-file out-bib-file t)
(let ((buf (find-file-noselect out-file))
cls-file sty-files img-files)
(with-current-buffer buf
(goto-char (point-min))
(re-search-forward "\\documentclass\\[.*?]{\\(.+?\\)}")
(setq cls-file (substring-no-properties (match-string 1)))
(maybe-delete-link out-dir (format "%s.cls" cls-file))
(setq cls-file
(string-trim (shell-command-to-string
(format "kpsewhich %s.cls"
(substring-no-properties (match-string 1))))))
(goto-char (point-min))
(while (re-search-forward "\\(\\usepackage\\(?:\\[.+?]\\)?\\){\\(.+?\\)}" nil t)
(push (split-string (substring-no-properties (match-string 2)) ",") sty-files))
(goto-char (point-min))
(while (re-search-forward "\\(\\includegraphics\\(?:\\[.+?]\\)?\\){\\(\\(.\\|\n\\)?+?\\)}" nil t)
(unless (syntax-ppss-context (syntax-ppss))
(push (match-string 2) img-files)
(replace-match (format "%s{%s}"
(match-string 1)
(concat "./" (f-filename (match-string 2)))))))
(make-symbolic-link cls-file out-dir t)
(seq-do (lambda (x)
(maybe-delete-link out-dir (format "%s.sty" x))
(make-symbolic-link (string-trim
(shell-command-to-string (format "kpsewhich %s.sty" x)))
out-dir t))
(-flatten sty-files))
(seq-do (lambda (x)
(make-symbolic-link x out-dir t))
img-files)
(save-buffer))
(kill-buffer buf))))
;; FIXME: compile-cmd is unused
(defun ref-man-export-generate-standalone-from-org ()
"Create a folder from doc-root with all files required for a self contained document.
Copy the img, tex and bib files in the folder for easy upload to
servers.
Requires the bib and other files to be generated once with
`ref-man-export-docproc-article'."
;; NOTE: Perhaps output to a different directory also?
(interactive)
(let* ((imgs (ref-man-export-get-all-imgs))
(doc-root (util/org-get-tree-prop "DOC_ROOT"))
(docs-dir ref-man-export-output-dir)
(title (if doc-root
(save-excursion
(goto-char doc-root)
(substring-no-properties (org-get-heading t t t t)))
(user-error "For generation of a research article, a DOC_ROOT must be specified")))
(title-words (split-string (downcase (ref-man--remove-punc title t))))
(checksum (save-restriction
(org-narrow-to-subtree)
(md5 (buffer-substring-no-properties (point-min) (point-max)))))
(doc-name (concat (string-join
(-take 3 title-words) "-")
"-" (substring checksum 0 10)))
(existing-files-dir (f-join docs-dir (string-join title-words "-")))
(out-dir (concat existing-files-dir "-standalone/"))
(files (mapcar (lambda (x) (path-join existing-files-dir (concat doc-name x)))
'(".tex" ".bib")))
(compile-cmd (s-lex-format "pdflatex ${doc-name}.tex && bibtex ${doc-name}.aux && pdflatex ${doc-name}.tex && pdflatex ${doc-name}.tex && rm *.out *.aux *.log *.blg"))
article-file)
(unless (-all? (lambda (x) (and (f-exists? x) (f-file? x))) files)
(user-error "Some files for document are missing. Generate first?"))
(when (f-exists? out-dir)
(f-delete out-dir t))
(f-mkdir out-dir)
(seq-do (lambda (x) (copy-file x out-dir t)) files)
(seq-do (lambda (x) (copy-file x out-dir t)) imgs)
(let ((buf (find-file-noselect (path-join out-dir (concat doc-name ".tex")))))
(with-current-buffer buf
(goto-char (point-min))
(re-search-forward "\\documentclass\\[.*?]{\\(.+?\\)}")
(setq article-file (string-trim (shell-command-to-string
(format "kpsewhich %s.cls"
(substring-no-properties (match-string 1))))))
(copy-file article-file out-dir t)
(goto-char (point-min))
(while (re-search-forward "\\(\\includegraphics\\(?:\\[.+?]\\)?\\){\\(.+?\\)}" nil t)
(replace-match (format "\\1{%s}" (concat "./" (f-filename (match-string 2))))))
(seq-do (lambda (x)
(goto-char (point-min))
(when (re-search-forward (format "\\(\\usepackage\\(?:\\[.+?]\\)?\\){%s}" (car x)) nil t)
(replace-match (format "\\1{%s}" (format "%s" (car x)))) ; (format "sty/%s" (car x))
(copy-file (cdr x) out-dir)))
'(("authblk" . "/home/joe/texmf/tex/latex/authblk.sty")
("algorithm2e" . "/usr/share/texlive/texmf-dist/tex/latex/algorithm2e/algorithm2e.sty")
("algorithmic" . "/usr/share/texlive/texmf-dist/tex/latex/algorithms/algorithmic.sty")
("algorithmicx" . "/usr/share/texlive/texmf-dist/tex/latex/algorithmicx/algorithmicx.sty")
("algpseudocode" . "/usr/share/texlive/texmf-dist/tex/latex/algorithmicx/algpseudocode.sty")))
(save-buffer))
(kill-buffer buf))))
;; FIXME: docs-dir and compile-cmd are unused
(defun ref-man-export-generate-standalone-from-latex ()
"Create a folder from a latex file with all files required for a self contained document.
Copy the img, tex and bib files in the folder for easy upload to
servers.
Requires the bib and other files to be generated once."
;; NOTE: Perhaps output to a different directory also?
(interactive)
(let* ((file (ido-read-file-name "Enter the path of the LaTeX file "))
(imgs (ref-man-export-get-all-imgs file))
(docs-dir ref-man-export-output-dir)
(doc-name (f-base (f-filename file)))
(existing-files-dir (f-parent file))
(out-dir (concat existing-files-dir "-standalone/"))
(files (mapcar (lambda (x) (path-join existing-files-dir (concat doc-name x)))
'(".tex" ".bib")))
(default-directory existing-files-dir)
(compile-cmd (if current-prefix-arg
(s-lex-format "pdflatex ${doc-name}.tex && biber ${doc-name} && pdflatex ${doc-name}")
(s-lex-format "pdflatex ${doc-name}.tex && bibtex ${doc-name}.aux && pdflatex ${doc-name}.tex && pdflatex ${doc-name}.tex && rm *.out *.aux *.log *.blg")))
article-file)
(unless (-all? (lambda (x) (and (f-exists? x) (f-file? x))) files)
(user-error "Some files for document are missing. Generate first?"))
(when (f-exists? out-dir)
(f-delete out-dir t))
(f-mkdir out-dir)
(seq-do (lambda (x) (copy-file x out-dir t)) files)
(seq-do (lambda (x) (copy-file x out-dir t)) imgs)
(let ((buf (find-file-noselect (path-join out-dir (concat doc-name ".tex")))))
(with-current-buffer buf
(goto-char (point-min))
(re-search-forward "\\documentclass\\[.*?]{\\(.+?\\)}")
(setq article-file (string-trim (shell-command-to-string
(format "kpsewhich %s.cls"
(substring-no-properties (match-string 1))))))
(copy-file article-file out-dir t)
(goto-char (point-min))
(while (re-search-forward "\\(\\includegraphics\\(?:\\[.+?]\\)?\\){\\(.+?\\)}" nil t)
(replace-match (format "\\1{%s}" (concat "./" (f-filename (match-string 2))))))
(seq-do (lambda (x)
(goto-char (point-min))
(when (re-search-forward (format "\\(\\usepackage\\(?:\\[.+?]\\)?\\){%s}" (car x)) nil t)
(replace-match (format "\\1{%s}" (format "%s" (car x)))) ; (format "sty/%s" (car x))
(copy-file (cdr x) out-dir)))
'(("authblk" . "/home/joe/texmf/tex/latex/authblk.sty")
("algorithm2e" . "/usr/share/texlive/texmf-dist/tex/latex/algorithm2e/algorithm2e.sty")
("algorithmic" . "/usr/share/texlive/texmf-dist/tex/latex/algorithms/algorithmic.sty")
("algorithmicx" . "/usr/share/texlive/texmf-dist/tex/latex/algorithmicx/algorithmicx.sty")
("algpseudocode" . "/usr/share/texlive/texmf-dist/tex/latex/algorithmicx/algpseudocode.sty")))
(save-buffer))
(kill-buffer buf))))
(defun ref-man-export-blog-no-urls (&optional buffer)
"Export BUFFER as \\='blog.
BUFFER defaults to `current-buffer'.
See `ref-man-export-docproc-article' for details."
(interactive)
(ref-man-export-docproc-article buffer 'blog t (not current-prefix-arg)
'(:with-toc t :with-tables t)))
(defun ref-man-export-both-no-urls (&optional buffer)
"Export BUFFER as both \\='blog and \\='pdf.
BUFFER defaults to `current-buffer'.
See `ref-man-export-docproc-article' for details."
(interactive)
(ref-man-export-docproc-article buffer 'both t (not current-prefix-arg)
'(:with-toc t :with-tables t)))
(defun ref-man-export-html-no-urls (&optional buffer)
"Export BUFFER as \\='html.
BUFFER defaults to `current-buffer'.
See `ref-man-export-docproc-article' for details."
(interactive)
(ref-man-export-docproc-article buffer 'html t (not current-prefix-arg)
'(:with-toc t :with-tables t)
nil current-prefix-arg))
(defun ref-man-export-article-no-urls-current-buffer-from-doc-root (doc-root)
"Call interactively `ref-man-export-article-no-urls' from DOC-ROOT.
DOC-ROOT is a point from where subtree is to be exported."
(save-excursion
(goto-char doc-root)
(call-interactively 'ref-man-export-article-no-urls)))
(defun ref-man-export-article-no-urls (pref-arg &optional buffer)
"Export BUFFER as a pdf article.
If Optional BUFFER is non-nil then export the entire buffer, else
export only the subtree.
The output type depends on the prefix.
1. (default) Export buffer as PDF. Don't overwrite if output
file exists.
2. Export buffer as HTML. Don't overwrite.
3. Export both HTML, PDF. Don't overwrite.
4. Export HTML. Overwrite.
5. Export both. Overwrite.
This function calls `ref-man-export-docproc-article' with
appropriate arguments."
(interactive "p")
(pcase pref-arg
(1 (ref-man-export-docproc-article
buffer 'pdf t t '(:with-tables t)))
(2 (ref-man-export-docproc-article ; html
buffer 'html t t '(:with-tables t)))
(3 (ref-man-export-docproc-article ; both html pdf
buffer 'both t t '(:with-tables t)))
(4 (ref-man-export-docproc-article ; force pdf
buffer 'pdf t t '(:with-tables t) nil t))
(5 (ref-man-export-docproc-article ; force html
buffer 'html t t '(:with-tables t) nil t))
(6 (ref-man-export-docproc-article ; force both
buffer 'both t t '(:with-tables t) nil t))))
(defun ref-man-export-paper-no-urls (&optional pref-arg)
"Export BUFFER as a research article.
Optional PREF-ARG reads the prefix argument as a number and if:
> 1 then don't use citeproc or bibtex or biber on PDF.
Useful for repeated generation of PDFs when references
don't need to be updated.
> 4 then force overwrite and don't run a citation command.
See `ref-man-export-docproc-article' for details."
(interactive "p")
(let ((doc-root (util/org-get-tree-prop "DOC_ROOT"))
(no-cite (> pref-arg 1))
(force (> pref-arg 4)))
(unless doc-root
(user-error "For generation of a research article, a DOC_ROOT must be specified"))
(save-excursion
(goto-char doc-root)
(message "Exporting to PDF...")
(ref-man-export-docproc-article nil 'paper t t
'(:with-src (ref-man-export-remove-src-blocks))
no-cite force))))
(defun ref-man-export-paper-plain-no-urls (&optional buffer)
"Export BUFFER as a plain research article.
See `ref-man-export-paper-no-urls'."