-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathorb-pdf-scrapper.el
1793 lines (1642 loc) · 72.1 KB
/
orb-pdf-scrapper.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
;;; orb-pdf-scrapper.el --- Orb Roam BibTeX: PDF reference scrapper -*- lexical-binding: t -*-
;; Copyright © 2020-2022 Mykhailo Shevchuk
;; Author: Mykhailo Shevchuk <[email protected]>
;; URL: https://github.com/org-roam/org-roam-bibtex
;; 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
;; this program; see the file LICENSE. If not, visit
;; <https://www.gnu.org/licenses/>.
;; N.B. This file contains code snippets adopted from other
;; open-source projects. These snippets are explicitly marked as such
;; in place. They are not subject to the above copyright and
;; authorship claims.
;;; Commentary:
;;
;;; Code:
;; ============================================================================
;;; Dependencies
;; ============================================================================
(require 'orb-core)
(require 'orb-anystyle)
;; it's fine here since `orb-pdf-scrapper' is autoloaded
(require 'bibtex-completion)
(require 'bibtex)
(require 'rx)
(require 'cl-extra)
(eval-when-compile
(require 'cl-lib)
(require 'cl-macs)
(require 'subr-x))
;; ============================================================================
;;; Customize definitions
;; ============================================================================
(defcustom orb-pdf-scrapper-prompt-to-generate-keys 'when-buffer-modified
"Prompt the user to generate keys in the BibTeX buffer?
After having finished editing in the BibTeX buffer and before
proceeding to Org buffer, the user will be prompted
to (re-)generate citation keys according to the value of this
option on these occasions:
- symbol `when-buffer-modified' - only when the buffer has
modified and changes have not been saved
- nil - never
- t or any other value - always."
:group 'orb-pdf-scrapper
:type '(choice
(const when-buffer-modified)
(const :tag "Yes" t)
(const :tag "No" nil)))
(defcustom orb-pdf-scrapper-grouped-export
'((in-roam "In Org Roam database" list)
(in-bib "In BibTeX file" list)
(valid "Valid citation keys" table)
(invalid "Invalid citation keys" table))
"Determines appearence of grouped references in Org view.
A list of five elements of the form (GROUP TITLE TYPE).
GROUP must be one of the symbols `parent', `in-roam', `in-bib',
`valid' or `invalid'.
TITLE is an arbitrary string, which will be the title of the
group's headline.
TYPE must be one of the symbols `list' or `table' determining how
the generated citations will appear under the group's headline.
TYPE is ignored for the `parent' group and defaults to `list' for
other groups when set to nil.
Takes effect when `orb-pdf-scrapper-group-references' is t."
:type '(list (list :tag "\nIn-roam"
(const :format "" in-roam)
(string :tag "Title")
(radio :tag "Type" :value list
(const list) (const table)))
(list :tag "\nIn-bib"
(const :format "" in-bib)
(string :tag "Title")
(radio :tag "Type" :value list
(const list) (const table)))
(list :tag "\nValid"
(const :format "" valid)
(string :tag "Title")
(radio :tag "Type" :value table
(const list) (const table)))
(list :tag "\nInvalid"
(const :format "" invalid)
(string :tag "Title")
(radio :tag "Type" :value table
(const list) (const table))))
:group 'orb-pdf-scrapper)
(defcustom orb-pdf-scrapper-ungrouped-export 'list
"Determines appearence of ungrouped references in Org view.
Valid values are the symbols `list' and `table'.
Takes effect when `orb-pdf-scrapper-group-references' is nil."
:group 'orb-pdf-scrapper
:type '(radio
(const list)
(const table)))
(defcustom orb-pdf-scrapper-table-export-fields
'("#" "citekey" "author" "editor" "journal"
"date" "volume" "pages")
"BibTeX fields for export into Org mode tables in the Org view.
A list in which each element is of form FIELD or (FIELD . TYPES).
The order of items in this list determines the order of table
columns.
FIELD is a field to export. Field mapping according to the value
of `orb-bibtex-field-aliases' is recognized. The non-standard
BibTeX field `citation-number' created during the reference
extraction process is treated specially according to the value of
the variable `orb-pdf-scrapper-reference-numbers'.
TYPES is a list of strings corresponding to BibTeX entry types
for which to export the FIELD. E.g. a value of a list cell
\(\"editor\" . \"collection\")
means to export the value of the field \"editor\" only for
entries whose entry type is \"collection\". If it is
nil (default), export the FIELD for all entry types.
See also the variables `orb-pdf-scrapper-grouped-export' and
`orb-pdf-scrapper-ungrouped-export', which allow to choose between
list and table export."
:type '(repeat (string :tag "Field"))
:group 'orb-pdf-scrapper)
(defcustom orb-pdf-scrapper-group-references t
"If this is non-nil, group the retrieved references in the Org view.
These groups are `in-roam', `in-bib', `valid' and `invalid'."
:group 'orb-pdf-scrapper
:type '(choice
(const :tag "Yes" t)
(const :tag "No" nil)))
(defcustom orb-pdf-scrapper-list-style 'unordered-hyphen
"Format of Org lists produced by ORB PDF Scrapper.
Valid values are symbols:
`ordered-point' => 1. citation
`ordered-parenthesis' => 1) citation
`unordered-hyphen' => - citation
`unordered-plus' => + citation
`unordered-asterisk' => * citation
This variable can also take a string value, in which case the
string should be a valid format string containing the '%s'
specifier, which will be used to insert citation numbers, for
example:
\"- [%s] \" => - [1] citation
The format string should take care of padding as no additional
spaces will be inserted automatically.
The variable `orb-pdf-scrapper-reference-numbers' allows to
choose the numbering scheme for ordered and custom format lists."
:group 'orb-pdf-scrapper
:type
'(choice
(const :tag "Point-terminated ordered list" ordered-point)
(const :tag "Parenthesis-terminated ordered list" ordered-parenthesis)
(const :tag "Hyphen-led unordered list" unordered-hyphen)
(const :tag "Plus-led unordered list" unordered-plus)
(const :tag "Asterisk-led unordered list" unordered-asterisk)
(string :tag "Custom ordered format")))
(defcustom orb-pdf-scrapper-reference-numbers 'citation-number
"This variable specifies the source of ordered list numbers.
Valid values are:
`citation-number' - use the extracted `citation-number',
stripping off any non-numerical characters. Fall back to
unordered hyphen-led list if this field is non-existent, empty,
or does not contain a number.
`citation-number-alnum' - use the extracted `citation-number',
stripping off any non-alphanumerical characters, fall back to
unordered hyphen-led list if this field is non-existent, empty or
does not contain alphanumerical characters. This value will only
have effect when `orb-pdf-scrapper-list-style' is a custom format
string and behave as `citation-number' otherwise.
`as-retrieved' - use the natural order of BibTeX entry in the buffer
If the value of `orb-pdf-scrapper-list-style' is one of the
'unordered' choices, this variable will have no effect."
:group 'orb-pdf-scrapper
:type '(radio
(const :tag "Citation number" citation-number)
(const :tag "Alphanumerical citation number" citation-number-alnum)
(const :tag "As retrieved" as-retrieved)))
(defcustom orb-pdf-scrapper-citekey-format "cite:%s"
"Format of the citekey for insertion into Org mode buffer."
:group 'orb-pdf-scrapper
:type 'string)
(defcustom orb-pdf-scrapper-export-options
'((org (heading "References (extracted by ORB PDF Scrapper)"
:property-drawer (("PDF_SCRAPPER_TYPE")
("PDF_SCRAPPER_SOURCE")
("PDF_SCRAPPER_DATE")))))
"Options for automatic export of references extracted by ORB PDF Scrapper.
This variable is an association list of the form
\(TYPE . ((TARGET LOCATION PROPERTIES))).
TYPE is the type of the exported data, one of the symbols `txt',
`bib' or `org'. The data will only be exported if its
corresponding symbol is present on the list.
TARGET must be one of the symbols `heading' or `path'. The
symbol `heading' means export the data under a heading in the
buffer of origin, the Org buffer where the ORB PDF Scrapper
process was started. The symbol `path' means export the data to
another file. It is possible to specify both export targets
simultaneously for a given export TYPE or multiple targets of the
same type.
Example:
\(setq orb-pdf-scrapper-export-options
'((org (heading HEADLINE PROPERTIES)
(path LOCATION PROPERTIES))))
LOCATION (HEADLINE) is a string specifying location of the TARGET.
- If TARGET is `heading', the supplied string will be used as
headline text. The data will be exported slightly differently
depending on TYPE. Text references will be exported as is.
BibTeX references will be put into an Org source code block.
Org references, if grouped under different headings, will be
exported with the headings demoted by one level.
- If TARGET is `path', the supplied string will be used as a
filesystem target. The path can be absolute or relative, in the
latter case it will be relative to the directory of the buffer of
origin. If the path (absolute or relative) is an *existing*
directory, the full path to the target file will be constructed
from the supplied string as a directory name, the #+ROAM_KEY:
property in the buffer of origin as a file name and TYPE as the
file's extension. If the path is not an existing directory, it
will be treated as a file name, and the data will be exported
there. The file will be created if it does not exist:
> \"~/org/references.org\" - absolute path
> \"this-note's-bib-references.bib\" - path relative to the buffer of origin
> \"~/orb-pdf-scrapper-references/\" - absolute directory path.
In the latter case, if the directory exists, the extracted data
will be put into a file \"Doe2020.bib\", assuming the #+ROAM_KEY:
property is \"Doe2020\" and TYPE is `bib'. If the directory does
not exist, the extracted data will be put into a (newly created)
file \"~/orb-pdf-scrapper-references/\".
Example:
\(setq orb-pdf-scrapper-export-options
'((org (heading \"Org references\" PROPERTIES))
(txt (path \"text-references/\" PROPERTIES))))
PROPERTIES is a property list providing additional export
specifications. Some properties are specific to only certain
export TYPEs or TARGETs.
`:placement' property allows to specify placement of the exported
data. It can be a symbol `prepend' or `append'.
When TARGET is `path', text data is simply put at the beginning
or end of the target file accordingly to the value of the
`:placement' property. Org data is placed before the first
or after the last heading, respectively. Similarly, BibTeX data
is placed or before the first or after the last entry, comments
and @String entries ignored.
When TARGET is `heading', this property specifies whether the
parent heading should be put before or after other headings.
When TARGET is `path' and LOCATION is an Org file, the value
of the `:placement' property can also be a list of the form
\(heading HEADLINE PROPERTIES). In this case the data will be
put in the target file under a heading with HEADLINE as the
headline text. PROPERTIES are additional export options as
described here and below. The `heading' value of the
`:placement' property cannot be used recursively in this case.
Example:
\(setq orb-pdf-scrapper-export-options
'((org (path \"references.org\" :placement append))
(bib (path \"references.bib\" :placement prepend))
(txt (path \"references.txt\"
:placement (headline \"References\" :placement append)))))
If placement is not specified, the data is appended by default.
`:property-drawer' property allows to supply a heading with some
properties. The value of this property is list with
elements (PROPERTY_NAME . PROPERTY_VALUE) or PROPERTY_NAME, the
latter form being treated as (PROPERTY_NAME . nil).
PROPERTY_NAME must be a string, it will be used as a property
name. PROPERY_VALUE can be a string, in which case it will be
used as the value of the property. It can also be a function
name as an unquoted symbol, in which case this function will be
called to get the value of the property. The return value must
be a string.
The following properties are recognized internally and will be
supplied with automatically generated values if PROPERTY_VALUE is
nil:
> PDF_SCRAPPER_TYPE - TYPE of the export data
> PDF_SCRAPPER_SOURCE - name of the PDF file the data were extracted from
> PDF_SCRAPPER_DATE - time and date the data were exported
Example:
\(setq orb-pdf-scrapper-export-options
'((org (heading \"Org references\" PROPERTIES)))
(txt (heading \"Text references\"
:property-drawer
'((\"PDF_SCRAPPER_TYPE\" . \"text\")
\"PDF_SCRAPPER_DATE\"
\"PDF_SCRAPPER_SOURCE\"
(\"PROPERTY_1\" . \"VALUE_1\")
(\"PROPERTY_2\" . my-function))))))
`:filter-bib-entries' property controls filtering of exported
BibTeX entries. If the value of this property is non-nil and
TARGET is a BibTeX file, only the entries that are not already
present in this file will be exported. The value can also be a
string or a list of strings specifying BibTeX file(s), or a
variable as an unquoted symbol holding a string or a list of
strings specifying BibTeX file(s), in which cases the entries
will be filtered also against this/these file(s) in *addition* to
the TARGET file. In such instances, filtering will also be
applied to entries exported to an Org heading.
Example:
\(setq orb-pdf-scrapper-export-options
'((bib (path \"references.bib\" :filter-bib-entries t
(heading \"BibTeX references\"
:filter-bib-entries bibtex-completion-bibliography))))."
:group 'orb-pdf-scrapper
:risky t
:type '(repeat list))
(defcustom orb-pdf-scrapper-set-fields
'(("author" orb-pdf-scrapper--invalidate-nil-value)
("editor" orb-pdf-scrapper--invalidate-nil-value
"book" "collection")
("title" orb-pdf-scrapper--invalidate-nil-value)
("journal" orb-pdf-scrapper--invalidate-nil-value
"article")
("date" orb-pdf-scrapper--invalidate-nil-value)
("volume" orb-pdf-scrapper--invalidate-nil-value
"article" "incollection")
("pages" orb-pdf-scrapper--fix-or-invalidate-range
"article" "incollection"))
"BibTeX fields to set during key generation.
A list in which each element is a list of the form (FIELD FUNCTION . TYPES).
FIELD is a BibTeX field name to be set.
FUNCTION is a function that will be called to generate the value,
it takes one argument ENTRY, which is the current entry.
TYPES is a list of strings corresponding to BibTeX entry types
for which the FIELD should be set. If it is nil, set the FIELD
for all entry types."
:risky t
:type '(repeat
(list :tag "Item"
(string :tag "Field")
(function :tag "Function")
(repeat :tag "Entry types" :inline t
(string :tag "Type"))))
:group 'orb-pdf-scrapper)
(defcustom orb-pdf-scrapper-invalid-key-pattern "\\`.*N/A.*\\'"
"Regexp to match an invalid key."
:type 'regexp
:group 'orb-pdf-scrapper)
;; ============================================================================
;;; Helper functions: BibTeX buffer and citekey-related routines
;; ============================================================================
(defvar orb-pdf-scrapper--refs nil
"Internal list with cell format (CITEKEY ENTRY . VALIDP).")
(defun orb-pdf-scrapper--invalidate-nil-value (field entry)
"Return value of FIELD or `orb-autokey-empty-field-token' if it is nil.
ENTRY is a BibTeX entry."
(bibtex-completion-get-value field entry orb-autokey-empty-field-token))
(defun orb-pdf-scrapper--fix-or-invalidate-range (field entry)
"Replace missing or non-standard delimiter between two strings with \"--\".
FIELD is the name of a BibTeX field from ENTRY. Return
`orb-autokey-empty-field-token' if the value is nil.
This function is primarily intended for fixing anystyle parsing
artefacts such as those often encountered in \"pages\" field,
where two numbers have only spaces between them."
(replace-regexp-in-string "\\`[[:alnum:]]*?\\([- –]+\\)[[:alnum:]]*\\'"
"--"
(bibtex-completion-get-value
field entry orb-autokey-empty-field-token)
nil nil 1))
(defun orb-pdf-scrapper--get-entry-info (entry &optional collect-only)
"Collect some information from and about the BibTeX ENTRY for further use.
Take a bibtex entry as returned by `bibtex-completion-get-entry' \
and return a plist with the following keys set:
:key |string | citekey generated with `orb-autokey-generate-key'
:validp |boolean| according to `orb-pdf-scrapper-invalid-key-pattern'
:set-fields |(cons) | as per `orb-pdf-scrapper-set-fields'
Each element of `:set-fields' list is a a cons cell (FIELD . VALUE).
If optional COLLECT-ONLY is non-nil, do not generate the key,
`:set-fields' is set to nil."
(let ((type (bibtex-completion-get-value "=type=" entry))
;; return values
key validp fields-to-set
;; internal variable
fields)
;; when requested to collect keys, just do that
(if collect-only
(setq key (bibtex-completion-get-value "=key=" entry)
fields entry)
;; otherwise
;; prepare fields for setting
(dolist (field-to-set orb-pdf-scrapper-set-fields)
(let ((field-name (car field-to-set))
(types-to-set (cddr field-to-set)))
;; push the field for setting only when entry type is one of the
;; specified types or nil, which means set the field regardless of
;; entry type
(when (or (not types-to-set)
(member type types-to-set))
(push (cons field-name
;; call the function if provided
(if-let ((fn (cadr field-to-set)))
(funcall fn field-name entry)
;; otherwise get the value from current entry
(bibtex-completion-get-value field-name entry "")))
fields-to-set))))
;; prioritize fields from fields-to-set over entry fields
;; for autokey generation
(let ((-compare-fn (lambda (x y)
(string= (car x) (car y)))))
(setq fields (-union fields-to-set entry)
key (orb-autokey-generate-key fields))))
;; validate the new shiny key (or the old existing one)
;; not sure if save-match-data is needed here
;; but it seems to be always a good choice
(save-match-data
(setq validp (and (not (string-match-p
orb-pdf-scrapper-invalid-key-pattern key))
t)))
;; return the entry
(list :key key
:validp validp
:set-fields fields-to-set)))
(defun orb-pdf-scrapper--update-record-at-point
(&optional collect-only natural-order)
"Generate citation key and update the BibTeX record at point.
Calls `orb-pdf-scrapper--get-entry-info' to get information about
BibTeX record at point and updates it accordingly. If optional
COLLECT-ONLY is non-nil, do not generate the key and do not set
the fields.
If optional argument NATURAL-ORDER is non-nil, set the field
'natural-order' of the returned entry to its value.
This is an auxiliary function for command
`orb-pdf-scrapper-generate-keys'."
(let* ((entry (parsebib-read-entry (parsebib-find-next-item)))
(key-plist (orb-pdf-scrapper--get-entry-info entry collect-only))
(new-key (plist-get key-plist :key))
(validp (plist-get key-plist :validp))
(fields-to-set (plist-get key-plist :set-fields)))
(unless collect-only
(save-excursion
;; update citekey
;; adjusted from bibtex-clean-entry
(bibtex-beginning-of-entry)
(re-search-forward bibtex-entry-maybe-empty-head)
(if (match-beginning bibtex-key-in-head)
(delete-region (match-beginning bibtex-key-in-head)
(match-end bibtex-key-in-head)))
(insert new-key)
;; set the bibtex fields
(when fields-to-set
(save-excursion
(dolist (field fields-to-set)
(let ((name (car field))
(value (cdr field))
bound)
;; (bibtex-set-field name value)
(bibtex-beginning-of-entry)
(when (setq bound (bibtex-search-forward-field name t))
(goto-char (car (cdr bound)))
(bibtex-kill-field nil t))
(bibtex-make-field (list name "" value) t t)))
;; Some hard-set cosmetic changes
(let ((bibtex-entry-format
'(whitespace realign unify-case braces sort-fields))
(bibtex-field-indentation 2)
(fill-column 160))
(bibtex-clean-entry))))))
;; return the result ((NEW-KEY . ENTRY) . VALIDP)
;; TODO: for testing until implemented
(when natural-order
(cl-pushnew `("natural-order" . ,natural-order) entry))
(cons new-key (cons entry validp))))
(defun orb-pdf-scrapper--sort-refs (refs)
"Sort references REFS.
Auxiliary function for `orb-pdf-scrapper-generate-keys'.
REFS should be an alist of form ((CITEKEY . FORMATTED-ENTRY) . VALIDP).
References validated by `orb-pdf-scrapper-keygen-function' function
are further sorted into four groups:
'in-roam - available in the `org-roam' database;
'in-bib - available in `bibtex-completion-bibliography' file(s);
'valid - marked valid by the keygen function but are not
available in user database(s);
'invalid - marked invalid by the keygen function."
(let* ((bibtex-completion-bibliography (orb-pdf-scrapper--get :global-bib))
;; When using a quoted list here, sorted-refs is not erased in
;; consecutive runs
(sorted-refs (list (list 'in-roam) (list 'in-bib)
(list 'valid) (list 'invalid))))
(dolist (ref refs)
(cond ((org-roam-db-query [:select [ref]
:from refs
:where (= ref $s1)]
(format "%s" (car ref)))
(push ref (cdr (assoc 'in-roam sorted-refs))))
((bibtex-completion-get-entry (car ref))
(push ref (cdr (assoc 'in-bib sorted-refs))))
((cddr ref)
(push ref (cdr (assoc 'valid sorted-refs))))
(t
(push ref (cdr (assoc 'invalid sorted-refs))))))
sorted-refs))
;; ============================================================================
;;; Helper functions: Org buffer-related routines
;; ============================================================================
(defun orb-pdf-scrapper--get-reference-number
(entry &optional numbering-source)
"ENTRY NUMBERING-SOURCE."
(let ((numbering-source
(or numbering-source orb-pdf-scrapper-reference-numbers)))
(cl-case numbering-source
(citation-number
(--> (bibtex-completion-get-value "citation-number" entry nil)
(when (and it (string-match ".*?\\([0-9]+\\).*?" it))
(match-string 1 it))))
(citation-number-alnum
(--> (bibtex-completion-get-value "citation-number" entry nil)
(when (and it (string-match "\
[^[:alnum:]]?\\([[:digit:]]*\\)\\([^[:alnum:]]*\\)\\([[:alpha:]]*\\)" it))
(concat (match-string 1 it) (match-string 3 it)))))
(as-retrieved
(bibtex-completion-get-value "natural-order" entry ""))
(t (user-error "Unsupported reference numbers source: %s"
numbering-source)))))
(defun orb-pdf-scrapper--insert-org-as-list (ref-alist)
"Insert REF-ALIST as Org list."
(let* ((numbering-source
(if (and (eq orb-pdf-scrapper-reference-numbers
'citation-number-alnum)
(not (stringp orb-pdf-scrapper-list-style)))
'citation-number
orb-pdf-scrapper-reference-numbers))
(leader
(cl-case orb-pdf-scrapper-list-style
(ordered-point "%s. ")
(ordered-parenthesis "%s) ")
(unordered-hyphen "- ")
(unordered-plus "+ ")
(unordered-asterisk "* ")
(t (if (stringp orb-pdf-scrapper-list-style)
orb-pdf-scrapper-list-style
(user-error "ORB: Unrecognized list style %s requested"
orb-pdf-scrapper-list-style)))))
(unorderedp
(memq orb-pdf-scrapper-list-style
'(unordered-hyphen unordered-plus unordered-asterisk)))
(fallback (if unorderedp leader "- ")))
(dolist (ref ref-alist)
(let* ((citekey (format orb-pdf-scrapper-citekey-format (car ref)))
(entry (cadr ref))
(number (unless unorderedp
(orb-pdf-scrapper--get-reference-number
entry numbering-source))))
(insert (orb-format leader `(,number . ,fallback)) citekey "\n")))))
(defun orb-pdf-scrapper--get-export-value (field entry)
"Get FIELD value from ENTRY.
Similar to `bibtex-completion-get-value' but does some additional cleaning."
;; list fields for org export
(let* ((field (or (car (rassoc field orb-bibtex-field-aliases))
field))
(value (bibtex-completion-get-value field entry "")))
;; truncate author list to first three names, append et.al instead
;; of the remaining names
;; This is a hard-coded "reasonable default"
;; and it may be replaced with something more
;; flexible in the future
(cond
((member field '("author" "editor"))
(--> value
(split-string it " and " t "[ ,.;:-]+")
(if (> (length it) 3)
(append (-take 3 it) '("et.al."))
it)
(concat (mapconcat #'identity it "; "))))
((string= field "citation-number")
(orb-pdf-scrapper--get-reference-number entry))
((string= field "=key=")
(format orb-pdf-scrapper-citekey-format value))
(t value))))
(defun orb-pdf-scrapper--insert-org-as-table (ref-alist)
"Insert REF-ALIST as Org table."
(insert
(format "|%s\n" (mapconcat #'identity
orb-pdf-scrapper-table-export-fields "|")))
(forward-line -1)
(org-table-insert-hline)
(forward-line 2)
(let ((table ""))
(dolist (ref ref-alist)
(setq table
(format "%s|%s|\n" table
(mapconcat
(lambda (field)
(orb-pdf-scrapper--get-export-value field (cadr ref)))
orb-pdf-scrapper-table-export-fields "|"))))
(insert table))
(forward-line -1)
(org-table-align))
(defun orb-pdf-scrapper--insert-refs ()
"Insert the references list as org structure.
If `orb-pdf-scrapper-group-references' is non-nil, sort the references into
categories `in-roam', `in-bib', `valid', `invalid'. Make a plain
list otherwise."
(cond
(orb-pdf-scrapper-group-references
(dolist (ref-group
(orb-pdf-scrapper--sort-refs orb-pdf-scrapper--refs))
(when-let* ((group (car ref-group))
(refs (cdr ref-group))
(heading
(cdr (assoc group
orb-pdf-scrapper-grouped-export)))
(title (car heading))
(type (cadr heading))
(pos (make-marker)))
;; NOTE: Investigate
;; The behaviour of org-insert-heading has changed at some point:
;; If in an empty buffer, e.g. temp-buffer, the function fails messaging "beginning of buffer"
(org-N-empty-lines-before-current 1)
(org-insert-heading '(16) nil t)
;; insert heading
(insert (format "%s\n" title))
(org-N-empty-lines-before-current 1)
;; insert references
(insert (format "#+name: %s\n" group))
(set-marker pos (point))
(set-marker-insertion-type pos t)
(cl-case type
('table
(orb-pdf-scrapper--insert-org-as-table refs))
(t
(orb-pdf-scrapper--insert-org-as-list refs)))
(goto-char pos))))
(t
(insert "\n")
(let ((refs (nreverse orb-pdf-scrapper--refs)))
(cl-case orb-pdf-scrapper-ungrouped-export
('table
(orb-pdf-scrapper--insert-org-as-table refs))
(t
(orb-pdf-scrapper--insert-org-as-list refs))))))
(goto-char (point-max))
(org-N-empty-lines-before-current 0))
;; ============================================================================
;;; Helper functions: Dispatcher
;; ============================================================================
(defvar orb-pdf-scrapper--plist nil
"Communication channel for Orb PDF Scrapper.")
(defvar orb-pdf-scrapper--buffer "*Orb PDF Scrapper*"
"Orb PDF Scrapper special buffer.")
(defmacro orb--with-scrapper-buffer! (&rest body)
"Execute BODY with `orb-pdf-scrapper--buffer' as current.
If the buffer does not exist it will be created."
(declare (indent 0) (debug t))
`(save-current-buffer
(set-buffer (get-buffer-create orb-pdf-scrapper--buffer))
,@body))
(defmacro orb--when-current-context! (context &rest body)
"Execute BODY if CONTEXT is current context.
Run `orb-pdf-scrapper-keygen-function' with `error' context
otherwise. If CONTEXT is a list then current context must be a
member of that list."
(declare (indent 1) (debug t))
`(if (not (orb-pdf-scrapper--current-context-p ,context))
(orb-pdf-scrapper-dispatcher 'error)
,@body))
(defun orb-pdf-scrapper--current-context-p (context)
"Return t if CONTEXT is current context.
CONTEXT can also be a list, in which case t is returned when
current context is its memeber."
(if (listp context)
(memq (orb-pdf-scrapper--get :context) context)
(eq (orb-pdf-scrapper--get :context) context)))
(defun orb-pdf-scrapper--refresh-mode (mode)
"Restart `orb-pdf-scrapper-mode' with new major MODE."
(cl-case mode
('txt
(text-mode)
(orb-pdf-scrapper--put :callee 'edit-bib
:context 'start
:caller 'edit-txt))
('bib
(bibtex-mode)
;; anystyle uses biblatex dialect
(bibtex-set-dialect 'biblatex t)
(orb-pdf-scrapper--put :callee 'edit-org
:context 'start
:caller 'edit-bib))
('org
(org-mode)
(orb-pdf-scrapper--put :callee 'checkout
:context 'start
:caller 'edit-org))
('xml
(xml-mode)
(cl-case (orb-pdf-scrapper--get :context)
;; since :callee is not used in training session, we set :callee here to
;; the original :caller, so that we can return to the editing mode we
;; were called from if the training session is to be cancelled
('start
(orb-pdf-scrapper--put :callee (orb-pdf-scrapper--get :caller)
:context 'edit
:caller 'edit-xml))))
('train
(fundamental-mode)
(cl-case (orb-pdf-scrapper--get :context)
('train
(orb-pdf-scrapper--put :context 'train
:caller 'train))
;; Since the session was not cancelled, we return to text, as everything
;; else should be regenerated anyway.
('finished
(orb-pdf-scrapper--put :callee 'edit-txt
:context 'continue
:caller 'train))))
(t
(unwind-protect
(error "Oops...something went wrong. \
Pressing the RED button, just in case")
(orb-pdf-scrapper-dispatcher 'error))))
(set-buffer-modified-p nil)
(setq mark-active nil)
(orb-pdf-scrapper-mode -1)
(orb-pdf-scrapper-mode +1)
(goto-char (point-min)))
(defun orb-pdf-scrapper--edit-txt ()
"Edit text references in `orb-pdf-scrapper--buffer'."
;; callee will be overridden in case of error
(cl-case (orb-pdf-scrapper--get :context)
;; parse pdf file and switch to text editing mode
('start
(let ((temp-txt (orb-temp-file "orb-pdf-scrapper-" ".txt"))
(pdf-file (orb-pdf-scrapper--get :pdf-file)))
(orb-pdf-scrapper--put :temp-txt temp-txt)
(let ((same-window-buffer-names (list orb-pdf-scrapper--buffer)))
(pop-to-buffer orb-pdf-scrapper--buffer))
(setq buffer-file-name nil)
(orb--with-message! (format "Scrapping %s.pdf" (f-base pdf-file))
(erase-buffer)
(orb-anystyle 'find
:format 'ref
:layout nil
:finder-model orb-anystyle-finder-model
:input pdf-file
:stdout t
:buffer orb-pdf-scrapper--buffer))
(setq buffer-undo-list nil)
(orb-pdf-scrapper--refresh-mode 'txt)))
;; read the previously generated text file
('continue
(if-let ((temp-txt (orb-pdf-scrapper--get :temp-txt))
(f-exists? temp-txt))
(progn
(pop-to-buffer orb-pdf-scrapper--buffer)
(erase-buffer)
(insert-file-contents temp-txt)
(setq buffer-undo-list (orb-pdf-scrapper--get :txt-undo-list))
(orb-pdf-scrapper--refresh-mode 'txt))
(orb-pdf-scrapper-dispatcher 'error)))
(t
(orb-pdf-scrapper-dispatcher 'error))))
(defun orb-pdf-scrapper--edit-bib ()
"Generate and edit BibTeX data in `orb-pdf-scrapper--buffer'."
(pop-to-buffer orb-pdf-scrapper--buffer)
(cl-case (orb-pdf-scrapper--get :context)
('start
(let* ((temp-bib (or (orb-pdf-scrapper--get :temp-bib)
(orb-temp-file "orb-pdf-scrapper-" ".bib"))))
(orb-pdf-scrapper--put :temp-bib temp-bib)
;; save previous progress in txt buffer
(write-region (orb-buffer-string)
nil (orb-pdf-scrapper--get :temp-txt) nil -1)
(orb-pdf-scrapper--put :txt-undo-list (copy-tree buffer-undo-list))
(orb--with-message! "Generating BibTeX data"
;; Starting from Emacs 27, whether shell-command erases buffer
;; is controlled by `shell-command-dont-erase-buffer', so we
;; make sure the buffer is clean
(erase-buffer)
(orb-anystyle 'parse
:format 'bib
:parser-model orb-anystyle-parser-model
:input (orb-pdf-scrapper--get :temp-txt)
:stdout t
:buffer orb-pdf-scrapper--buffer)
(write-region (orb-buffer-string) nil temp-bib nil -1))
(setq buffer-undo-list nil))
(orb-pdf-scrapper--refresh-mode 'bib))
('continue
(if-let ((temp-bib (orb-pdf-scrapper--get :temp-bib))
(f-exists? temp-bib))
(progn
(erase-buffer)
(insert-file-contents temp-bib)
(setq buffer-undo-list (orb-pdf-scrapper--get :bib-undo-list))
(orb-pdf-scrapper--refresh-mode 'bib))
(orb-pdf-scrapper-dispatcher 'error)))
(t
(orb-pdf-scrapper-dispatcher 'error))))
(defun orb-pdf-scrapper--edit-org ()
"Edit generated Org data."
(pop-to-buffer orb-pdf-scrapper--buffer)
(cl-case (orb-pdf-scrapper--get :context)
('start
;; if the BibTeX buffer was modified, save it and maybe generate keys
(orb-pdf-scrapper-generate-keys
nil
(cl-case orb-pdf-scrapper-prompt-to-generate-keys
('when-buffer-modified
(if (buffer-modified-p)
;; TODO: it's clumsy
;; not "yes" means generate
;; not "no" means collect only
(not (y-or-n-p "The buffer contents has changed. \
Generate BibTeX keys? "))
t))
;; do not prompt
(nil t)
;; always prompt
(t
(not (y-or-n-p "Generate BibTeX keys? ")))))
(when (> (cl-random 100) 98)
(orb--with-message! "Pressing the RED button"))
(write-region (orb-buffer-string)
nil (orb-pdf-scrapper--get :temp-bib) nil 1)
(orb-pdf-scrapper--put :bib-undo-list (copy-tree buffer-undo-list))
;; generate Org buffer
(let* ((temp-org (or (orb-pdf-scrapper--get :temp-org)
(orb-temp-file "orb-pdf-scrapper-" ".org"))))
(orb-pdf-scrapper--put :temp-org temp-org
:caller 'edit-org)
;; we must change the mode in the beginning to get all the Org
;; facilities
(orb-pdf-scrapper--refresh-mode 'org)
(orb--with-message! "Generating Org data"
(erase-buffer)
(orb-pdf-scrapper--insert-refs)
(write-region (orb-buffer-string) nil temp-org nil -1)
(setq buffer-undo-list nil)
(set-buffer-modified-p nil)
(goto-char (point-min)))))
('continue
(if-let ((temp-org (orb-pdf-scrapper--get :temp-org))
(f-exists? temp-org))
(progn
(erase-buffer)
(insert-file-contents temp-org)
(setq buffer-undo-list (orb-pdf-scrapper--get :org-undo-list))
(orb-pdf-scrapper--refresh-mode 'org))
(orb-pdf-scrapper-dispatcher 'error)))))
(defun orb-pdf-scrapper--edit-xml ()
"Edit XML data."
(pop-to-buffer orb-pdf-scrapper--buffer)
(cl-case (orb-pdf-scrapper--get :context)
('start
(let* ((temp-xml (or (orb-pdf-scrapper--get :temp-xml)
(orb-temp-file "orb-pdf-scrapper-" ".xml"))))
(orb-pdf-scrapper--put :temp-xml temp-xml)
(orb--with-message! "Generating XML data"
;; save progress in text mode when called from there if called from
;; anywhere else, text mode progress is already saved, other data will
;; be re-generated anyway
(when (eq (orb-pdf-scrapper--get :caller) 'edit-txt)
(write-region (orb-buffer-string)
nil (orb-pdf-scrapper--get :temp-txt) nil -1)
(orb-pdf-scrapper--put :txt-undo-list (copy-tree buffer-undo-list)))
(erase-buffer)
(orb-anystyle 'parse
:format 'xml
:parser-model orb-anystyle-parser-model
:input (orb-pdf-scrapper--get :temp-txt)
:stdout t
:buffer orb-pdf-scrapper--buffer)
(write-region (orb-buffer-string) nil temp-xml nil -1)
(setq buffer-undo-list nil)
(orb-pdf-scrapper--refresh-mode 'xml))))
('edit-master
(progn
(erase-buffer)
(insert-file-contents orb-anystyle-parser-training-set)
;; we allow the user to see which file they are editing
(setq buffer-file-name orb-anystyle-parser-training-set)
(setq buffer-undo-list nil)
(orb-pdf-scrapper--refresh-mode 'xml)))
(t
(orb-pdf-scrapper-dispatcher 'error))))
(defun orb-pdf-scrapper--update-master-file ()
"Append generated XML data to `orb-anystyle-parser-training-set'."
(orb--with-scrapper-buffer!
(orb--with-message! (format "Appending to master training set %s"
orb-anystyle-parser-training-set)
;; save any progress in XML mode
(write-region (orb-buffer-string) nil
(orb-pdf-scrapper--get :temp-xml) nil -1)
(let (new-data)
;; strip down the header and footer tokens from our data
(save-excursion
(save-match-data
(let* (beg end)
(goto-char (point-min))
(re-search-forward "\\(^[ \t]*<dataset>[ \t]*\n\\)" nil t)
(setq beg (or (match-end 1)
(point-min)))
(re-search-forward "\\(^[ \t]*</dataset>[ \t]*\n\\)" nil t)
(setq end (or (match-beginning 1)
(point-max)))