-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpubmed.el
2208 lines (2036 loc) · 97 KB
/
pubmed.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
;;; pubmed.el --- Interface to PubMed -*- lexical-binding: t; -*-
;; Author: Folkert van der Beek <[email protected]>
;; Created: 2018-05-23
;; Version: 0.6.2
;; Keywords: pubmed, hypermedia
;; Package-Requires: ((emacs "26.1") (esxml "0.3.4") (s "1.12.0") (unidecode "0.2"))
;; URL: https://gitlab.com/fvdbeek/emacs-pubmed
;; 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:
;; This is a GNU Emacs interface to the PubMed database of references on life
;; sciences and biomedical topics.
;;; Code:
;;;; Requirements
(require 'pubmed-bibtex)
(require 'pubmed-openaccessbutton)
(require 'pubmed-pmc)
(require 'esxml)
(require 'esxml-query)
(require 'ewoc)
(require 'json)
(require 's)
(require 'url)
(require 'url-http)
;;;; Variables
(defvar pubmed-eutils-url "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/"
"E-utilities base URL.")
(defvar pubmed-efetch-url (concat pubmed-eutils-url "efetch.fcgi")
"EFetch URL.")
(defvar pubmed-esearch-url (concat pubmed-eutils-url "esearch.fcgi")
"ESearch URL.")
(defvar pubmed-espell-url (concat pubmed-eutils-url "espell.fcgi")
"ESpell URL.")
(defvar pubmed-esummary-url (concat pubmed-eutils-url "esummary.fcgi")
"ESummary URL.")
(defvar pubmed-completion-url
"https://www.ncbi.nlm.nih.gov/portal/utils/autocomp.fcgi?dict=pm_related_queries_2&callback=?&q=%s")
(defvar pubmed-author-completion-url
"https://www.ncbi.nlm.nih.gov/portal/utils/autocomp.fcgi?dict=auf&q=%s")
(defvar pubmed-journal-completion-url
"https://www.ncbi.nlm.nih.gov/portal/utils/autocomp.fcgi?dict=jrz&q=%s")
;; Web environment string returned from a previous ESearch, EPost or
;; ELink call. When provided, ESearch will post the results of the
;; search operation to this pre-existing WebEnv, thereby appending the
;; results to the existing environment. In addition, providing WebEnv
;; allows query keys to be used in term so that previous search sets
;; can be combined or limited."
(defvar pubmed-webenv ""
"Web environment string.")
(defvar pubmed-history-list nil
"The PubMed history list.")
(defvar pubmed-entry-timer nil
"The timer that is set to delay EFetch calls.")
(defvar pubmed-entry-delay 0.5
"Delay in seconds before fetching the PubMed entry; default=0.5.
Seconds may be an integer or floating point number. Purpose of
the delay is to prevent frequent EFetch calls and exceeding the
E-utilities rate limit when walking fast through the PubMed
entries.")
(defvar pubmed-limit-with-api-key 10
"Maximum amount of E-utilities requests/second with API key.")
(defvar pubmed-limit-without-api-key 3
"Maximum amount of E-utilities requests/second without API key.")
(defvar pubmed-months '("Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec")
"Abbreviated months.")
;;;; Keymap
(defvar pubmed-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "RET") #'pubmed-show-current-entry)
(define-key map (kbd "f") #'pubmed-get-fulltext)
(define-key map (kbd "m") #'pubmed-mark)
(define-key map (kbd "M") #'pubmed-mark-all)
(define-key map (kbd "n") #'pubmed-show-next)
(define-key map (kbd "p") #'pubmed-show-prev)
(define-key map (kbd "q") #'quit-window)
(define-key map (kbd "s") #'pubmed-search)
(define-key map (kbd "u") #'pubmed-unmark)
(define-key map (kbd "U") #'pubmed-unmark-all)
(define-key map (kbd "w") #'pubmed-bibtex-write)
(define-key map (kbd "TAB") #'pubmed-bibtex-show)
map)
"Local keymap for `pubmed-mode'.")
(defvar pubmed-show-mode-map
(let ((map (make-sparse-keymap)))
(set-keymap-parent map (make-composed-keymap button-buffer-map special-mode-map))
map)
"Local keymap for `pubmed-show-mode'.")
(defvar pubmed-search-mode-map
(let ((map (copy-keymap minibuffer-local-map)))
(define-key map (kbd "TAB") #'completion-at-point)
map)
"Local keymap for `pubmed-search-mode'.")
(defconst pubmed-language-codes
'(("afr" "Afrikaans")
("alb" "Albanian")
("amh" "Amharic")
("ara" "Arabic")
("arm" "Armenian")
("aze" "Azerbaijani")
("ben" "Bengali")
("bos" "Bosnian")
("bul" "Bulgarian")
("cat" "Catalan")
("chi" "Chinese")
("cze" "Czech")
("dan" "Danish")
("dut" "Dutch")
("eng" "English")
("epo" "Esperanto")
("est" "Estonian")
("fin" "Finnish")
("fre" "French")
("geo" "Georgian")
("ger" "German")
("gla" "Scottish Gaelic")
("gre" "Greek, Modern")
("heb" "Hebrew")
("hin" "Hindi")
("hrv" "Croatian")
("hun" "Hungarian")
("ice" "Icelandic")
("ind" "Indonesian")
("ita" "Italian")
("jpn" "Japanese")
("kin" "Kinyarwanda")
("kor" "Korean")
("lat" "Latin")
("lav" "Latvian")
("lit" "Lithuanian")
("mac" "Macedonian")
("mal" "Malayalam")
("mao" "Maori")
("may" "Malay")
("mul" "Multiple languages")
("nor" "Norwegian")
("per" "Persian, Iranian")
("pol" "Polish")
("por" "Portuguese")
("pus" "Pushto")
("rum" "Romanian, Rumanian, Moldovan")
("rus" "Russian")
("san" "Sanskrit")
("slo" "Slovak")
("slv" "Slovenian")
("spa" "Spanish")
("srp" "Serbian")
("swe" "Swedish")
("tha" "Thai")
("tur" "Turkish")
("ukr" "Ukrainian")
("und" "Undetermined")
("urd" "Urdu")
("vie" "Vietnamese")
("wel" "Welsh"))
"The language codes used by PubMed.")
;;;; Menu
(easy-menu-define pubmed-mode-menu pubmed-mode-map
"Menu for `pubmed-mode'."
`("PubMed"
["Search PubMed" pubmed-search]
["Advanced" pubmed-advanced-search
:help "PubMed Advanced Search Builder"]
"--"
["Show record" pubmed-show-current-entry
:help "Show the summary of the current entry"]
["Fetch fulltext PDF" pubmed-get-fulltext
:help "Try to fetch the fulltext PDF of the marked entries or current entry, using multiple methods"]
["Fetch PMC fulltext PDF" pubmed-get-pmc
:help "Try to fetch the fulltext PDF from PubMed Central®"
:active (memq 'pubmed-pmc pubmed-fulltext-functions)]
["Fetch Open Access Button fulltext PDF" pubmed-get-openaccessbutton
:help "Try to fetch the fulltext PDF from Open Access Button"
:active (memq 'pubmed-openaccessbutton pubmed-fulltext-functions)]
["Fetch Unpaywall fulltext PDF" pubmed-get-unpaywall
:help "Try to fetch the fulltext PDF from Unpaywall"
:active (memq 'pubmed-unpaywall pubmed-fulltext-functions)]
["Fetch Dissemin fulltext PDF" pubmed-get-dissemin
:help "Try to fetch the fulltext PDF from Dissemin"
:active (memq 'pubmed-dissemin pubmed-fulltext-functions)]
["Fetch Springer Nature fulltext PDF" pubmed-get-springer
:help "Try to fetch the fulltext PDF from Springer Nature"
:active (memq 'pubmed-springer pubmed-fulltext-functions)]
["Fetch Sci-Hub fulltext PDF" pubmed-get-scihub
:help "Try to fetch the fulltext PDF from Sci-Hub"
:active (memq 'pubmed-scihub pubmed-fulltext-functions)]
"--"
["Write to BibTeX" pubmed-bibtex-write :help "Write the
BibTeX references of the marked entries or current entry to
file"] ["Show BibTeX" pubmed-bibtex-show :help "Show the
BibTeX references of the marked entries or current entry"]
"--"
["Mark the current entry" pubmed-mark :help "Mark the entry and move to the next line"]
["Unmark the current entry" pubmed-unmark :help "Unmark the entry and move to the next line"]
["Mark all entries" pubmed-mark-all :help "Mark all entries"]
["Unmark all entries" pubmed-unmark-all :help "Unmark all entries"]
"--"
("Sort"
["Sort by relevance" pubmed-sort-by-index
:help "Sort based on relevance to your search"]
["Sort by relevance (descending)" (pubmed-sort-by-index t)
:help "Sort reversely based on relevance to your search"]
["Sort by first author" pubmed-sort-by-firstauthor
:help "Sort alphabetically by first author name, and then by publication date"]
["Sort by first author (descending)" (pubmed-sort-by-firstauthor t)
:help "Sort reverse alphabetically by first author name, and then by publication date"]
["Sort by last author" pubmed-sort-by-lastauthor
:help "Sort alphabetically by last author name, and then by publication date"]
["Sort by last author (descending)" (pubmed-sort-by-lastauthor t)
:help "Sort reverse alphabetically by last author name, and then by publication date"]
["Sort by journal" pubmed-sort-by-journal
:help "Sort alphabetically by journal title, and then by publication date"]
["Sort by journal (descending)" (pubmed-sort-by-journal t)
:help "Sort reverse alphabetically by journal title, and then by publication date"]
["Sort by pubdate " (pubmed-sort-by-pubdate t)
:help "Sort chronologically by publication date \(with oldest first\), and then alphabetically by journal title"]
["Sort by pubdate (descending)" pubmed-sort-by-pubdate
:help "Sort chronologically by publication date \(with most recent first\), and then alphabetically by journal title"]
["Sort by title" pubmed-sort-by-title
:help "Sort alphabetically by article title, and then by publication date"]
["Sort by title (descending)" (pubmed-sort-by-title t)
:help "Sort reverse alphabetically by article title, and then by publication date"])
"--"
["Quit" quit-window :help "Quit PubMed"]
["Customize" (customize-group 'pubmed)]))
;;;; Customization
(defgroup pubmed nil
"Interface to PubMed."
:group 'external)
(defcustom pubmed-api-key ""
"E-utilities API key."
:group 'pubmed
:type 'string)
(defcustom pubmed-search-completion t
"If non-nil, use completion using PubMed suggestions."
:group 'pubmed
:type 'boolean)
(defcustom pubmed-max-results 10000
"Maximum number of search results.
A warning is issued if the count of search results exceeds this
number."
:group 'pubmed
:type 'integer)
;; The documentation mentions that "most recent" and "recently added"
;; are valid sort orders, but these result in a warning and are
;; ignored. The sort order "author" is equal to "first author".
(defcustom pubmed-sort-method 'pubdate
"Method used to sort records in the ESearch output.
The records are loaded onto the History Server in the specified
sort order and will be retrieved in that order by ESummary or
EFetch. The default sort order is \"Pub date\".
Valid sort values include:
\"First author\": Records are sorted alphabetically by first
author name, and then by publication date.
\"Last author\": Records are sorted alphabetically by last author
name, and then by publication date.
\"Journal\": Records are sorted alphabetically by journal title, and
then by publication date.
\"Pub date\": Records are sorted chronologically by publication date
\(with most recent first\), and then alphabetically by journal title.
\"Relevance\": Records are sorted based on relevance to your search.
\"Title\": Records are sorted alphabetically by article title."
:group 'pubmed
:type '(choice (const :tag "First author" firstauthor)
(const :tag "Last author" lastauthor)
(const :tag "Journal" journal)
(const :tag "Pub date" pubdate)
(const :tag "Relevance" relevance)
(const :tag "Title" title)))
(defcustom pubmed-fulltext-functions '(pubmed-pmc pubmed-openaccessbutton)
"The list of functions tried in order by `pubmed-fulltext'.
To change the behavior of ‘pubmed-get-fulltext’, remove, change
the order of, or insert functions in this list. Each function
should accept no arguments, and return a string or nil."
:group 'pubmed
:type '(repeat function)
:options '(pubmed-pmc
pubmed-openaccessbutton
pubmed-unpaywall
pubmed-dissemin
pubmed-springer
pubmed-scihub))
(defcustom pubmed-fulltext-action 'pubmed-open
"Default function called by `pubmed-get-fulltext'.
The function should accept one argument: a string with an URL."
:group 'pubmed
:type '(choice (function :tag "Open the articles using `pubmed-open-file-command'" pubmed-open)
(function :tag "Save the articles to `pubmed-default-directory'" pubmed-save)
(function :tag "Save the articles and prompt for filename" pubmed-save-as)
(function :tag "Ask a WWW browser to load the article" browse-url)
(function :tag "Function")))
(defcustom pubmed-default-directory "~"
"Default directory for saving fulltext articles."
:group 'pubmed
:type 'directory)
(defcustom pubmed-open-file-command 'find-file-other-window
"Application for opening PDF files.
Possible values are:
`system': Use the system command for opening files, like
\"open\". This value is intented for graphical desktop
environments on GNU/Linux, macOS, or Microsoft Windows.
`mailcap': Use command specified in the mailcaps.
string: A command to be executed by a shell; %s will be replaced
by the path to the file, e.g. \"evince \"%s\"\".
function: A Lisp function, which will be called with the file
path as argument."
:group 'pubmed
:type '(choice (const :tag "Use default" default)
(const :tag "Use the system command" system)
(string :tag "Command")
(function :tag "Function")))
;;;; Buttons
(define-button-type 'pubmed-pmid
'help-echo "mouse-2, RET: Search reference in PubMed."
'follow-link t
'action (lambda (button)
(pubmed-search (concat (button-get button 'pubmed-pmid) "[pmid]"))))
(define-button-type 'pubmed-mh
'help-echo "mouse-2, RET: Search MeSH heading in PubMed."
'follow-link t
'action (lambda (button)
(pubmed-search (concat (button-get button 'pubmed-mh) "[mh]"))))
;;;; Mode
;;;###autoload
(define-derived-mode pubmed-mode special-mode "Pubmed"
"Major mode for PubMed.
This buffer contains the results of the PubMed query.
All currently available key bindings:
\\{pubmed-mode-map}"
:group 'pubmed
;; Turn on highlighting
(font-lock-mode 1)
;; Turn on ẁord wrap
(visual-line-mode 1)
;; Set the number of characters preceding each entry
(setq pubmed-list-padding 2)
;; Set the number of characters preceding continuation lines
(setq-local wrap-prefix (make-string pubmed-list-padding ?\s)))
(define-derived-mode pubmed-show-mode special-mode "Pubmed-entry"
"Mode for displaying PubMed entries."
:group 'pubmed
;; Turn on highlighting
(font-lock-mode 1)
;; Turn on ẁord wrap
(visual-line-mode 1))
;;;; Commands
;;;###autoload
(defun pubmed-search (query &optional querykey webenv count)
"Search PubMed with QUERY.
The optional argument QUERYKEY specifies which of the stored sets
to the given WEBENV will be used as input to ESummary. COUNT is
the total number of records in the stored set."
(interactive
(let* ((minibuffer-setup-hook (when (eq pubmed-search-completion t)
(lambda () (add-hook 'completion-at-point-functions #'pubmed-completion-at-point nil t))))
(query (read-from-minibuffer "Query: " nil pubmed-search-mode-map nil 'pubmed-history-list)))
(list query)))
(let ((pubmed-buffer (get-buffer-create (format "*PubMed - Search Results - %s*" query)))
(inhibit-read-only t))
(with-current-buffer pubmed-buffer
(pubmed-mode)
;; Remove previous entries
(erase-buffer)
(setq-local pubmed-ewoc (ewoc-create #'pubmed--entry-pp nil nil t))
(setq-local pubmed-query query)
(setq-local pubmed-entries nil)
(setq-local pubmed-uid nil)
(setq-local pubmed-marklist nil)
(cond
((and querykey webenv count)
(pubmed--get-docsums pubmed-buffer querykey webenv count))
(t
(pubmed--esearch pubmed-buffer query))))))
(defun pubmed-show-current-entry ()
"Show the current entry in the \"pubmed-show\" buffer."
(interactive)
(pubmed--guard)
(setq pubmed-uid (pubmed-get-uid))
(when (timerp pubmed-entry-timer)
(cancel-timer pubmed-entry-timer))
(setq pubmed-entry-timer (run-with-timer pubmed-entry-delay nil #'pubmed--show-entry pubmed-uid)))
(defun pubmed-show-next ()
"Show the next item in the \"pubmed-show\" buffer."
(interactive)
(pubmed--guard)
(ewoc-goto-next pubmed-ewoc 1)
(setq pubmed-uid (pubmed-get-uid))
(when (get-buffer-window "*PubMed-entry*" "visible")
(when (timerp pubmed-entry-timer)
(cancel-timer pubmed-entry-timer))
(setq pubmed-entry-timer (run-with-timer pubmed-entry-delay nil #'pubmed--show-entry pubmed-uid))))
(defun pubmed-show-prev ()
"Show the previous entry in the \"pubmed-show\" buffer."
(interactive)
(pubmed--guard)
(ewoc-goto-prev pubmed-ewoc 1)
(setq pubmed-uid (pubmed-get-uid))
(when (get-buffer-window "*PubMed-entry*" "visible")
(when (timerp pubmed-entry-timer)
(cancel-timer pubmed-entry-timer))
(setq pubmed-entry-timer (run-with-timer pubmed-entry-delay nil #'pubmed--show-entry pubmed-uid))))
(defun pubmed-mark (&optional n)
"Mark N entries and move to the next line.
If N is omitted or nil, mark one entry. If region is active, mark
entries in active region instead."
(interactive "p")
(pubmed--guard)
(if (use-region-p)
(pubmed-mark-region (region-beginning) (region-end))
(dotimes (_ (or n 1))
(pubmed--put-tag "*" t))))
(defun pubmed-unmark (&optional n)
"Unmark N entries and move to the next line.
If N is omitted or nil, unmark one entry. If region is active,
unmark entries in active region instead."
(interactive "p")
(pubmed--guard)
(if (use-region-p)
(pubmed-unmark-region (region-beginning) (region-end))
(dotimes (_ (or n 1))
(pubmed--put-tag " " t))))
(defun pubmed-mark-region (beg end)
"Unmark all entries between point and mark.
BEG and END are the bounds of the region."
(interactive "r")
(pubmed--guard)
(save-excursion
(let* ((first-node (ewoc-locate pubmed-ewoc beg))
(last-node (ewoc-locate pubmed-ewoc end))
(node first-node)
(inhibit-read-only t))
(while (progn
(ewoc-goto-node pubmed-ewoc node)
(pubmed--put-tag "*" nil)
(setq node (ewoc-next pubmed-ewoc node))
(not (eq node (ewoc-next pubmed-ewoc last-node))))))))
(defun pubmed-unmark-region (beg end)
"Mark all entries between point and mark.
BEG and END are the bounds of the region."
(interactive "r")
(pubmed--guard)
(save-excursion
(let* ((first-node (ewoc-locate pubmed-ewoc beg))
(last-node (ewoc-locate pubmed-ewoc end))
(node first-node)
(inhibit-read-only t))
(while (progn
(ewoc-goto-node pubmed-ewoc node)
(pubmed--put-tag " " nil)
(setq node (ewoc-next pubmed-ewoc node))
(not (eq node (ewoc-next pubmed-ewoc last-node))))))))
(defun pubmed-mark-all ()
"Mark all entries."
(interactive)
(pubmed--guard)
(save-excursion
(let ((node (ewoc-nth pubmed-ewoc 0)))
(while node
(progn
(ewoc-goto-node pubmed-ewoc node)
(pubmed--put-tag "*" nil)
(setq node (ewoc-next pubmed-ewoc node)))))))
(defun pubmed-unmark-all ()
"Unmark all entries."
(interactive)
(pubmed--guard)
(save-excursion
(let ((node (ewoc-nth pubmed-ewoc 0)))
(while node
(progn
(ewoc-goto-node pubmed-ewoc node)
(pubmed--put-tag " " nil)
(setq node (ewoc-next pubmed-ewoc node)))))))
(defun pubmed-sort-by-index (&optional reverse)
"Sort the PubMed buffer by index.
With a prefix argument, the sorting order is reversed."
(interactive "P")
(pubmed--guard)
(if reverse
(pubmed--sort 'index t t)
(pubmed--sort 'index nil t)))
(defun pubmed-sort-by-firstauthor (&optional reverse)
"Sort the PubMed buffer by first author name.
If first author is equal, then sort by publication date. With a
prefix argument, the sorting order is reversed."
(interactive "P")
(pubmed--guard)
(if reverse
(pubmed--sort 'firstauthor t t)
(pubmed--sort 'firstauthor nil t)))
(defun pubmed-sort-by-lastauthor (&optional reverse)
"Sort the PubMed buffer by first author name.
If first author is equal, then sort by publication date. With a
prefix argument, the sorting order is reversed."
(interactive "P")
(pubmed--guard)
(if reverse
(pubmed--sort 'lastauthor t t)
(pubmed--sort 'lastauthor nil t)))
(defun pubmed-sort-by-journal (&optional reverse)
"Sort the PubMed buffer by journal title.
If journal title is equal, then sort by publication date. With a
prefix argument, the sorting order is reversed."
(interactive "P")
(pubmed--guard)
(if reverse
(pubmed--sort 'journal t t)
(pubmed--sort 'journal nil t)))
(defun pubmed-sort-by-pubdate (&optional reverse)
"Sort the PubMed buffer by publication date.
Sorting is chronologically with most recent first. If the
publication date is equal, then sort by journal title. With a
prefix argument, the sorting order is reversed."
(interactive "P")
(pubmed--guard)
(if reverse
(pubmed--sort 'pubdate t t)
(pubmed--sort 'pubdate nil t)))
(defun pubmed-sort-by-title (&optional reverse)
"Sort the PubMed buffer alphabetically by article title.
If article title is equal, then sort by publication date. With a
prefix argument, the sorting order is reversed."
(interactive "P")
(pubmed--guard)
(if reverse
(pubmed--sort 'title t t)
(pubmed--sort 'title nil t)))
(defun pubmed-get-uids-in-region ()
"Return a list of uids the entries in the active region."
(pubmed--guard)
(when (use-region-p)
(save-excursion
(let* ((first-node (ewoc-locate pubmed-ewoc (region-beginning)))
(last-node (ewoc-locate pubmed-ewoc (region-end)))
(node first-node)
(inhibit-read-only t)
uids)
(while (progn
(push (plist-get (ewoc-data node) :uid) uids)
(ewoc-goto-node pubmed-ewoc node)
(setq node (ewoc-next pubmed-ewoc node))
(not (eq node (ewoc-next pubmed-ewoc last-node)))))
(nreverse uids)))))
(defun pubmed-get-uids ()
"Return a list of uids.
The marked entries are used, or else the entries in the active
region, or else the current entry."
(let ((uids (or pubmed-marklist
(pubmed-get-uids-in-region)
(list (pubmed-get-uid)))))
uids))
;;;###autoload
(defun pubmed-get-fulltext (&optional uids)
"Try to fetch the fulltext PDF articles.
The entries in the optional argument UIDS are used. If no uids
are supplied, the marked entries, the entries in the active
region, or the current entry are used.
The variable `pubmed-fulltext-action' says which
function to use."
(interactive "P")
(if-let ((uids (or uids (pubmed-get-uids))))
(dolist (uid uids)
(when-let ((url (pubmed--get-fulltext-url uid)))
(save-current-buffer
(funcall pubmed-fulltext-action url))))
(error "No entry selected")))
(defun pubmed-open (url)
"Open the fulltext PDF of URL."
(let* ((filename (url-file-nondirectory url))
(path (concat (temporary-file-directory) filename)))
(when path
(condition-case err
(url-copy-file url path 1)
(file-already-exists
(message "%s" (error-message-string err))))
(funcall #'pubmed--open-file path))))
(defun pubmed-save (url)
"Save the fulltext PDF of URL.
The file is saved in `pubmed-default-directory'."
(let ((filename (expand-file-name (url-file-nondirectory url)
pubmed-default-directory)))
(condition-case err
(url-copy-file url filename 1)
(file-already-exists
(message "%s" (error-message-string err))))))
(defun pubmed-save-as (url)
"Prompt for filename and save the fulltext PDF of URL."
(let* ((default-filename (expand-file-name (url-file-nondirectory url)
pubmed-default-directory))
(filename (read-file-name "Save file:"
pubmed-default-directory
default-filename
nil
default-filename)))
(condition-case err
(url-copy-file url filename 1)
(file-already-exists
(message "%s" (error-message-string err))))))
;;;###autoload
(defun pubmed-complete (&optional _predicate)
"Perform completion using PubMed suggestions preceding point."
(interactive)
(let* ((data (pubmed-completion-at-point))
(plist (nthcdr 3 data)))
(if (null data)
(minibuffer-message "Nothing to complete")
(let ((completion-extra-properties plist))
(completion-in-region (nth 0 data) (nth 1 data) (nth 2 data)
(plist-get plist :predicate))))))
;;;###autoload
(defun pubmed-author-complete (&optional _predicate)
"Perform completion using PubMed suggestions preceding point."
(interactive)
(let* ((data (pubmed-author-completion-at-point))
(plist (nthcdr 3 data)))
(if (null data)
(minibuffer-message "Nothing to complete")
(let ((completion-extra-properties plist))
(completion-in-region (nth 0 data) (nth 1 data) (nth 2 data)
(plist-get plist :predicate))))))
;;;###autoload
(defun pubmed-journal-complete (&optional _predicate)
"Perform completion using PubMed suggestions preceding point."
(interactive)
(let* ((data (pubmed-journal-completion-at-point))
(plist (nthcdr 3 data)))
(if (null data)
(minibuffer-message "Nothing to complete")
(let ((completion-extra-properties plist))
(completion-in-region (nth 0 data) (nth 1 data) (nth 2 data)
(plist-get plist :predicate))))))
;;;###autoload
(defun pubmed-completion-at-point ()
"Function used for `completion-at-point-functions'."
(interactive)
(let* ((start (line-beginning-position))
(end (line-end-position))
(text (buffer-substring-no-properties start end)))
(list start
end
(completion-table-with-cache
(lambda (_)
(pubmed--completion-candidates text)))
:exclusive 'no)))
;;;###autoload
(defun pubmed-author-completion-at-point ()
"Function used for `completion-at-point-functions'."
(interactive)
(let* ((start (line-beginning-position))
(end (line-end-position))
(text (buffer-substring-no-properties start end)))
(list start
end
(completion-table-with-cache
(lambda (_)
(pubmed--author-completion-candidates text)))
:exclusive 'no)))
;;;###autoload
(defun pubmed-journal-completion-at-point ()
"Function used for `completion-at-point-functions'."
(interactive)
(let* ((start (line-beginning-position))
(end (line-end-position))
(text (buffer-substring-no-properties start end)))
(list start
end
(completion-table-with-cache
(lambda (_)
(pubmed--journal-completion-candidates text)))
:exclusive 'no)))
;;;; Functions
(defun pubmed--show-entry (uid)
"Display entry UID in the current buffer."
(interactive)
;; "Return the parsed summary for an UID"
;; TODO: Only the summary of the first UID is returned. Consider returning multiple summaries at once when multiple UIDs are passed as argument.
(let ((url-request-method "POST")
(url-request-extra-headers `(("Content-Type" . "application/x-www-form-urlencoded")))
(url-request-data (concat "db=pubmed"
"&retmode=xml"
"&rettype=abstract"
"&id=" uid
(unless (string-empty-p pubmed-api-key)
(concat "&api_key=" pubmed-api-key)))))
(url-retrieve pubmed-efetch-url #'pubmed--parse-efetch)))
(defun pubmed--mark-marklist ()
"Mark all entries in `pubmed-marklist'."
(pubmed--guard)
(save-excursion
(let ((node (ewoc-nth pubmed-ewoc 0)))
(while node
(progn
(ewoc-goto-node pubmed-ewoc node)
(when (member (plist-get (ewoc-data node) :uid) pubmed-marklist)
(pubmed--put-tag "*" nil))
(setq node (ewoc-next pubmed-ewoc node)))))))
(defun pubmed--put-tag (tag &optional advance)
"Put TAG in the padding area of the current node.
TAG should be a string, with length <= `pubmed-list-padding'. If
ADVANCE is non-nil, move forward by one line afterwards."
(unless (stringp tag)
(error "Invalid argument to `pubmed--put-tag'"))
(unless (> pubmed-list-padding 0)
(error "Unable to tag the current node"))
(save-excursion
(let* ((node (ewoc-locate pubmed-ewoc))
(uid (plist-get (ewoc-data node) :uid))
(inhibit-read-only t))
;; Set point to beginning of node
(ewoc-goto-node pubmed-ewoc node)
(let ((beg (point)))
(forward-char pubmed-list-padding)
(insert-and-inherit
(let ((tag-width (string-width tag)))
(if (<= tag-width pubmed-list-padding)
(concat tag
(make-string (- pubmed-list-padding tag-width) ?\s))
(truncate-string-to-width tag pubmed-list-padding))))
(delete-region beg (+ beg pubmed-list-padding))
;; Update the marklist
(cond
((and (equal tag "*") (not (member uid pubmed-marklist)))
(push uid pubmed-marklist))
((and (equal tag " ") (member uid pubmed-marklist))
(setq pubmed-marklist (delete uid pubmed-marklist)))))))
(when advance (ewoc-goto-next pubmed-ewoc 1)))
(defun pubmed--entry-pp (entry)
"Pretty print ENTRY."
(let* ((uid (plist-get entry :uid))
(doctype (plist-get entry :doctype))
(pubdate (plist-get entry :pubdate))
(epubdate (plist-get entry :epubdate))
(source (cond
((equal doctype "citation")
(plist-get entry :source))
((equal doctype "chapter")
(plist-get entry :booktitle))))
(authors (mapcar (lambda (x) (when (equal (plist-get x :authtype) "Author") (plist-get x :name))) (plist-get entry :authors)))
(title (pubmed---html-cleanup (plist-get entry :title)))
(volume (plist-get entry :volume))
(issue (plist-get entry :issue))
(pages (plist-get entry :pages))
(lang (mapcar (lambda (x) (cadr (assoc x pubmed-language-codes))) (plist-get entry :lang)))
(nlmuniqueid (plist-get entry :nlmuniqueid))
(issn (plist-get entry :issn))
(essn (plist-get entry :essn))
(pubtype (mapcar #'identity (plist-get entry :pubtype)))
(articleids (plist-get entry :articleids))
(pmid (mapconcat (lambda (x) (when (equal (plist-get x :idtype) "pubmed") (plist-get x :value))) articleids ""))
(doi (mapconcat (lambda (x) (when (equal (plist-get x :idtype) "doi") (plist-get x :value))) articleids ""))
(pii (mapconcat (lambda (x) (when (equal (plist-get x :idtype) "pii") (plist-get x :value))) articleids ""))
(pmc (mapconcat (lambda (x) (when (equal (plist-get x :idtype) "pmc") (plist-get x :value))) articleids ""))
(date (plist-get entry :sortpubdate))
(fulljournalname (plist-get entry :fulljournalname))
(attributes (plist-get entry :attributes)))
;; Title
(indent-to pubmed-list-padding)
(insert (propertize (concat title "\n") 'font-lock-face 'font-lock-constant-face 'rear-nonsticky t))
;; Citation
(indent-to pubmed-list-padding)
(insert (propertize
(concat
(cond
((eq (length authors) 0)
"[No authors listed] ")
((eq (length authors) 1)
(concat (car authors) ". "))
((> (length authors) 1)
(concat (car authors) ", et al. ")))
source
". "
pubdate
(unless (string-empty-p volume)
(concat ";" volume))
(unless (string-empty-p issue)
(concat "(" issue ")"))
(unless (string-empty-p pages)
(concat ":" pages))
"."
(unless (string-empty-p doi)
(concat " doi: " doi "."))
(unless (string-empty-p epubdate)
(concat " Epub " epubdate "."))
(unless (null lang)
;; Print only non-english languages
(cond
((and (eq (length lang) 1)
(not (string= (car lang) "English")))
(concat " " (car lang) "."))
((> (length lang) 1)
(concat " " (s-join ", " lang) "."))
(t
nil)))
(unless (null pubtype)
;; Print only non-journal article pubtypes
(cond
((and (eq (length pubtype) 1)
(not (string= (car pubtype) "Journal Article")))
(concat " " (car pubtype) "."))
((> (length pubtype) 1)
(concat " " (s-join ", " (delete "Journal Article" pubtype)) "."))
(t
nil)))
(when (null attributes)
" No abstract available.")
"\n")
'font-lock-face 'font-lock-comment-face 'rear-nonsticky t))))
(defun pubmed--guard ()
"Signal an error when the current buffer is not in `pubmed-mode'."
(unless (eq major-mode 'pubmed-mode)
(error "The current buffer is not in PubMed mode")))
(defun pubmed--html-to-unicode (string)
"Replace HTML entities with unicode in STRING."
(let* ((html-entities '(Aacute "Á" aacute "á" Acirc "Â" acirc "â" acute "´" AElig "Æ" aelig "æ" Agrave "À" agrave "à" alefsym "ℵ" Alpha "Α" alpha "α" amp "&" and "∧" ang "∠" apos "'" aring "å" Aring "Å" asymp "≈" atilde "ã" Atilde "Ã" auml "ä" Auml "Ä" bdquo "„" Beta "Β" beta "β" brvbar "¦" bull "•" cap "∩" ccedil "ç" Ccedil "Ç" cedil "¸" cent "¢" Chi "Χ" chi "χ" circ "ˆ" clubs "♣" cong "≅" copy "©" crarr "↵" cup "∪" curren "¤" Dagger "‡" dagger "†" darr "↓" dArr "⇓" deg "°" Delta "Δ" delta "δ" diams "♦" divide "÷" eacute "é" Eacute "É" ecirc "ê" Ecirc "Ê" egrave "è" Egrave "È" empty "∅" emsp " " ensp " " Epsilon "Ε" epsilon "ε" equiv "≡" Eta "Η" eta "η" eth "ð" ETH "Ð" euml "ë" Euml "Ë" euro "€" exist "∃" fnof "ƒ" forall "∀" frac12 "½" frac14 "¼" frac34 "¾" frasl "⁄" Gamma "Γ" gamma "γ" ge "≥" gt ">" harr "↔" hArr "⇔" hearts "♥" hellip "…" iacute "í" Iacute "Í" icirc "î" Icirc "Î" iexcl "¡" igrave "ì" Igrave "Ì" image "ℑ" infin "∞" int "∫" Iota "Ι" iota "ι" iquest "¿" isin "∈" iuml "ï" Iuml "Ï" Kappa "Κ" kappa "κ" Lambda "Λ" lambda "λ" lang "〈" laquo "«" larr "←" lArr "⇐" lceil "⌈" ldquo "“" le "≤" lfloor "⌊" lowast "∗" loz "◊" lrm "" lsaquo "‹" lsquo "‘" lt "<" macr "¯" mdash "—" micro "µ" middot "·" minus "−" Mu "Μ" mu "μ" nabla "∇" nbsp "" ndash "–" ne "≠" ni "∋" not "¬" notin "∉" nsub "⊄" ntilde "ñ" Ntilde "Ñ" Nu "Ν" nu "ν" oacute "ó" Oacute "Ó" ocirc "ô" Ocirc "Ô" OElig "Œ" oelig "œ" ograve "ò" Ograve "Ò" oline "‾" omega "ω" Omega "Ω" Omicron "Ο" omicron "ο" oplus "⊕" or "∨" ordf "ª" ordm "º" oslash "ø" Oslash "Ø" otilde "õ" Otilde "Õ" otimes "⊗" ouml "ö" Ouml "Ö" para "¶" part "∂" permil "‰" perp "⊥" Phi "Φ" phi "φ" Pi "Π" pi "π" piv "ϖ" plusmn "±" pound "£" Prime "″" prime "′" prod "∏" prop "∝" Psi "Ψ" psi "ψ" quot "\"" radic "√" rang "〉" raquo "»" rarr "→" rArr "⇒" rceil "⌉" rdquo "”" real "ℜ" reg "®" rfloor "⌋" Rho "Ρ" rho "ρ" rlm "" rsaquo "›" rsquo "’" sbquo "‚" scaron "š" Scaron "Š" sdot "⋅" sect "§" shy "" Sigma "Σ" sigma "σ" sigmaf "ς" sim "∼" spades "♠" sub "⊂" sube "⊆" sum "∑" sup "⊃" sup1 "¹" sup2 "²" sup3 "³" supe "⊇" szlig "ß" Tau "Τ" tau "τ" there4 "∴" Theta "Θ" theta "θ" thetasym "ϑ" thinsp " " thorn "þ" THORN "Þ" tilde "˜" times "×" trade "™" uacute "ú" Uacute "Ú" uarr "↑" uArr "⇑" ucirc "û" Ucirc "Û" ugrave "ù" Ugrave "Ù" uml "¨" upsih "ϒ" Upsilon "Υ" upsilon "υ" uuml "ü" Uuml "Ü" weierp "℘" Xi "Ξ" xi "ξ" yacute "ý" Yacute "Ý" yen "¥" yuml "ÿ" Yuml "Ÿ" Zeta "Ζ" zeta "ζ" zwj "" zwnj ""))
(pubmed--html-to-unicode (lambda (s) (or (plist-get html-entities (intern (substring s 1 -1))) s))))
(replace-regexp-in-string "&[^; ]*;" pubmed--html-to-unicode string)))
(defun pubmed--remove-html-tags (string)
"Remove all HTML tags from STRING."
(let ((regexp "<[[:alnum:][:blank:]/=\"-]*?>"))
(replace-regexp-in-string regexp "" string)))
(defun pubmed---html-cleanup (string)
"Cleanup all HTML from STRING."
(pubmed--remove-html-tags
(pubmed--html-to-unicode string)))
(defun pubmed--sort (key &optional reverse remember-pos)
"Sort the PubMed buffer by KEY.
If optional argument REVERSE is non-nil, the sorting order is
reversed. Optional argument REMEMBER-POS means to move point to
the node with the same data element as the current node."
(let* ((inhibit-read-only t)
(first-prop (cond
((eq key 'index)
nil)
((eq key 'firstauthor)
:sortpubdate)
((eq key 'lastauthor)
:sortpubdate)
((eq key 'journal)
:sortpubdate)
((eq key 'pubdate)
:fulljournalname)
((eq key 'title)
:sortpubdate)))
(second-prop (cond
((eq key 'index)
:index)
((eq key 'firstauthor)
:sortfirstauthor)
((eq key 'lastauthor)
:lastauthor)
((eq key 'journal)
:fulljournalname)
((eq key 'pubdate)
:sortpubdate)
((eq key 'title)
:sorttitle)))
;; All sorting methods are ascending by default, except by date.
;; Therefore, the sorting order of the :sortpubdate prop should be reversed
(first-pred (cond
((eq first-prop :sortpubdate)
#'string>)
(t
#'string<)))
(second-pred (cond
((eq second-prop :index)
#'<)
((eq second-prop :sortpubdate)
#'string>)
(t
#'string<)))
(first-sorter (lambda (a b) (funcall first-pred (plist-get a first-prop) (plist-get b first-prop))))
(second-sorter (lambda (a b) (funcall second-pred (plist-get a second-prop) (plist-get b second-prop))))
(second-sorter (if reverse
(lambda (a b) (funcall second-sorter b a))
second-sorter))
(current-uid (pubmed-get-uid)))
;; Sort the entries using two keys. For the 'firstauthor,
;; 'lastauthor 'journal and 'title keys, the entries are sorted
;; alphabetically, and then by publication date. For the 'pubdate
;; key, the entries are sorted chronologically by publication
;; date, and then alphabetically by journal title.
(when first-prop (setq pubmed-entries (sort pubmed-entries first-sorter)))
(when second-prop (setq pubmed-entries (sort pubmed-entries second-sorter)))