forked from tecosaur/lexic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsdcv.el
1859 lines (1787 loc) · 77.3 KB
/
sdcv.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
;;; sdcv.el --- major mode to do dictionary query through sdcv -*- lexical-binding: t; -*-
;; Copyright 2006~2008 pluskid,
;; 2011~2012 gucong
;; 2020 tecosaur
;;
;; Author: pluskid <[email protected]>,
;; gucong <[email protected]>,
;; tecosaur <[email protected]>
;;
;; 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 2, 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, write to the Free Software
;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
;;; Commentary:
;; This is a major mode to view output of dictionary search of sdcv.
;; Put this file into your load-path and the following into your
;; ~/.emacs:
;; (require 'sdcv-mode)
;; (global-set-key (kbd "C-c d") 'sdcv-search)
;;; Changelog:
;; 2020/07/28
;; * New variable: `sdcv-dictionary-specs', allows for
;; - Dictionary display names
;; - Custom dictionary entry formatters
;; - Dictionary sorting
;; * Update outline function calls to replace depreciated names.'
;; * Tweak sdcv-mode
;; - Remove font-locking
;; - Change `outline-regexp' to ZERO WIDTH SPACE
;; - Add `outline-heading-end-regexp', a PUNCTUATION SPACE
;; - Expand the mode map, to bind
;; - Two modes of entry navigation
;; - History navigation
;; - TAB for toggling an entry
;; * Expand popup window
;; * Add linear history navigation
;; * Revise behaviour of `sdcv-next-entry' and `sdcv-previous-entry'
;; * New function: `sdcv-get-outline-path' which gives the structural path
;; to the current position in buffer, e.g. dict → word v. t. → 1. (Chem.)
;; * Remove (now unused) custom face vars, could do with adding some
;; new face vars in the future
;; * Change the default of `sdcv-program-path' to be an absolute path
;; * New functions: `sdcv-format-result', `sdcv-failed-p',
;; and `sdcv-format-failure' to handle the upgraded entry prodessing
;; * New functions: `sdcv-format-webster', `sdcv-format-online-etym',
;; `sdcv-format-element', and `sdcv-format-soule' to format
;; the dictionaries recognised by default in `sdcv-dictionary-specs'.
;; - with helper functions `sdcv-format-webster-diacritics', and
;; `sdcv-format-expand-abbreviations' for nicer content.
;; 2012/01/02
;; * New variable: `sdcv-word-processor'
;; * Breaking change:
;; for `shttps://github.com/gucong/emacs-sdcv/blob/master/sdcv-mode.elhttps://github.com/gucong/emacs-sdcv/blob/master/sdcv-mode.eldcv-dictionary-list' and `sdcv-dictionary-alist',
;; non-list (non-nil) value now means full dictionary list
;; * Rewrite `sdcv-search' for both interactive and non-interactive use
;; * `sdcv-dictionary-list' is left for customization use only
;; * Better highlighting.
;;
;; 2011/06/30
;; * New feature: parse output for failed lookup
;; * Keymap modification
;;
;; 2008/06/11
;; * sdcv-mode v 0.1 init (with background process)
;;; Code:
(require 'outline)
(require 'dash)
(require 'cl-lib)
(provide 'sdcv)
;;; ==================================================================
;;; Frontend, search word and display sdcv buffer
(defun sdcv-search (word &optional dict-list-name dict-list interactive-p no-history-p)
"Search WORD through the command-line tool sdcv.
The result will be displayed in buffer named with
`sdcv-buffer-name' with `sdcv-mode' if called interactively.
When provided with DICT-LIST-NAME, query `sdcv-dictionary-alist'
to get the new dictionary list before search.
Alternatively, dictionary list can be specified directly
by DICT-LIST. Any non-list value of it means using all dictionaries.
When called interactively, prompt for the word.
Prefix argument have the following meaning:
If `sdcv-dictionary-alist' is defined,
use prefix argument to select a new DICT-LIST-NAME.
Otherwise, prefix argument means using all dictionaries.
Word may contain some special characters:
* match zero or more characters
? match zero or one character
/ used at the beginning, for fuzzy search
| used at the beginning, for data search
\ escape the character right after"
(interactive
(let* ((dict-list-name
(and current-prefix-arg sdcv-dictionary-alist
(completing-read "Select dictionary list: "
sdcv-dictionary-alist nil t)))
(dict-list
(and current-prefix-arg (not sdcv-dictionary-alist)))
(guess (or (and transient-mark-mode mark-active
(buffer-substring-no-properties
(region-beginning) (region-end)))
(current-word nil t)))
(word (read-string (format "Search dict (default: %s): " guess)
nil nil guess)))
(list word dict-list-name dict-list t)))
;; init current dictionary list
(when (null sdcv-current-dictionary-list)
(setq sdcv-current-dictionary-list sdcv-dictionary-list))
;; dict-list-name to dict-list
(when (and (not dict-list) dict-list-name)
(if (not sdcv-dictionary-alist)
(error "`sdcv-dictionary-alist' not defined"))
(setq dict-list
(cdr (assoc dict-list-name sdcv-dictionary-alist))))
;; prepare new dictionary list
(when (and dict-list (not (equal sdcv-current-dictionary-list dict-list)))
(setq sdcv-current-dictionary-list dict-list)
;; kill sdcv process
(and (get-process sdcv-process-name)
(kill-process (get-process sdcv-process-name)))
(while (get-process sdcv-process-name)
(sleep-for 0.01)))
(let ((result
(mapconcat
(lambda (w) (sdcv-do-lookup w))
(if sdcv-word-processor
(let ((processed (funcall sdcv-word-processor word)))
(if (listp processed) processed (list processed)))
(list word))
"")))
(unless (or no-history-p (string= word
(nth sdcv--search-history-position
sdcv--search-history)))
(setq sdcv--search-history
(append (cl-subseq sdcv--search-history
0 (1+ sdcv--search-history-position))
(list word))
sdcv--search-history-position (1- (length sdcv--search-history))))
(if (not interactive-p)
result
(with-current-buffer (get-buffer-create sdcv-buffer-name)
(setq buffer-read-only nil)
(erase-buffer)
(insert result))
(sdcv-goto-sdcv)
(sdcv-mode)
(sdcv-mode-reinit)
(let* ((window (get-buffer-window (sdcv-get-buffer)))
(height (window-height window))
(min-height (pcase (count-lines (point-min) (point-max))
((pred (> 50)) 12)
((pred (> 100)) 16)
(_ 20))))
(when (> min-height height)
(window-resize window (- 12 height)))))))
(defun sdcv-search-word-at-point ()
(interactive)
(sdcv-search
(downcase
(or (and transient-mark-mode mark-active
(buffer-substring-no-properties
(region-beginning) (region-end)))
(current-word nil t))) nil nil t))
(defun sdcv-list-dictionary ()
"Show available dictionaries."
(interactive)
(let (resize-mini-windows)
(shell-command "sdcv -l" sdcv-buffer-name)))
(defvar sdcv-current-dictionary-list nil)
(defun sdcv-generate-dictionary-argument ()
"Generate dictionary argument for sdcv from `sdcv-current-dictionary-list'
and `sdcv-dictionary-path'."
(append
(and sdcv-dictionary-path (list "--data-dir" sdcv-dictionary-path))
(and (listp sdcv-current-dictionary-list)
(mapcan (lambda (dict)
(list "-u" dict))
sdcv-current-dictionary-list))))
(defvar sdcv--search-history nil)
(defvar sdcv--search-history-position -1)
(defun sdcv-search-history-backwards ()
(interactive)
(if (> sdcv--search-history-position 0)
(sdcv-search (nth (setq sdcv--search-history-position
(1- sdcv--search-history-position))
sdcv--search-history)
nil nil t t)
(message "At start of search history.")))
(defun sdcv-search-history-forwards ()
(interactive)
(if (> (length sdcv--search-history) sdcv--search-history-position)
(sdcv-search (nth (setq sdcv--search-history-position
(1+ sdcv--search-history-position))
sdcv--search-history)
nil nil t t)
(message "At end of search history.")))
;;; ==================================================================
;;; utilities to switch from and to sdcv buffer
(defvar sdcv-previous-window-conf nil
"Window configuration before switching to sdcv buffer.")
(defun sdcv-goto-sdcv ()
"Switch to sdcv buffer in other window."
(interactive)
(unless (eq (current-buffer)
(sdcv-get-buffer))
(setq sdcv-previous-window-conf (current-window-configuration)))
(let* ((buffer (sdcv-get-buffer))
(window (get-buffer-window buffer)))
(if (null window)
(switch-to-buffer-other-window buffer)
(select-window window))))
(defun sdcv-return-from-sdcv ()
"Bury sdcv buffer and restore the previous window configuration."
(interactive)
(if (window-configuration-p sdcv-previous-window-conf)
(progn
(set-window-configuration sdcv-previous-window-conf)
(setq sdcv-previous-window-conf nil)
(bury-buffer (sdcv-get-buffer)))
(bury-buffer)))
(defun sdcv-get-buffer ()
"Get the sdcv buffer. Create one if there's none."
(let ((buffer (get-buffer-create sdcv-buffer-name)))
(with-current-buffer buffer
(unless (eq major-mode 'sdcv-mode)
(sdcv-mode)))
buffer))
;;; ==================================================================
(defvar sdcv-mode-map
(let ((map (make-sparse-keymap)))
(define-key map "q" 'sdcv-return-from-sdcv)
(define-key map (kbd "RET") 'sdcv-search-word-at-point)
(define-key map "a" 'outline-show-all)
(define-key map "h" 'outline-hide-body)
(define-key map "o" 'sdcv-toggle-entry)
(define-key map (kbd "TAB") 'sdcv-toggle-entry)
(define-key map "n" 'sdcv-next-entry)
(define-key map "N" (lambda () (interactive) (sdcv-next-entry t)))
(define-key map "p" 'sdcv-previous-entry)
(define-key map "P" (lambda () (interactive) (sdcv-previous-entry t)))
(define-key map "b" 'sdcv-search-history-backwards)
(define-key map "f" 'sdcv-search-history-forwards)
map)
"Keymap for `sdcv-mode'.")
(define-derived-mode sdcv-mode text-mode "sdcv"
"Major mode to look up word through sdcv.
\\{sdcv-mode-map}
Turning on Text mode runs the normal hook `sdcv-mode-hook'."
(setq buffer-read-only t)
(setq-local outline-regexp "\u200B+")
(setq-local outline-heading-end-regexp "\u2008"))
(defun sdcv-mode-reinit ()
"Re-initialize buffer.
Hide all entrys but the first one and goto
the beginning of the buffer."
(ignore-errors
(setq buffer-read-only nil)
(sdcv-parse-failed)
(setq buffer-read-only t)
(when (< 30 (count-lines (point-min) (point-max)))
(outline-hide-sublevels 3))
(goto-char (point-min))
(search-forward "\u200B\u200B")
(left-char 1)))
(defun sdcv-parse-failed ()
(goto-char (point-min))
(let (save-word)
(while (re-search-forward "^[0-9]+).*-->\\(.*\\)$" nil t)
(let ((cur-word (match-string-no-properties 1)))
(unless (string= save-word cur-word)
(setq save-word cur-word)
(re-search-backward "^\\(.\\)" nil t)
(match-string 1)
(insert (format "\n==>%s\n" save-word)))))))
(defun sdcv-expand-entry ()
"Show the children of the current entry, or subtree if there are none."
(outline-show-children)
(when ; no children
(<= 0 (- (save-excursion (outline-next-heading) (point))
(save-excursion (outline-end-of-subtree) (point))))
(outline-show-subtree)))
(defun sdcv-next-entry (&optional linear)
"Move to the next entry, targeting the same level unless LINEAR is set."
(interactive)
(when (< 1 (sdcv-outline-level))
(outline-hide-subtree))
(if linear
(outline-next-heading)
(condition-case nil
(outline-forward-same-level 1)
(error
(condition-case nil
(progn
(outline-up-heading 1 t)
(outline-forward-same-level 1))
(error (progn (outline-next-heading)
(sdcv-expand-entry)))))))
(sdcv-expand-entry)
(recenter-top-bottom 1)
(message "%s" (sdcv-get-outline-path)))
(defun sdcv-previous-entry (&optional linear)
"Move to the previous entry, targeting the same level unless LINEAR is set."
(interactive)
(outline-hide-subtree)
(if (= 2 (line-number-at-pos))
(recenter-top-bottom -1)
(if linear
(outline-previous-heading)
(condition-case nil
(outline-backward-same-level 1)
(error
(condition-case nil
(outline-up-heading 1 t)
(error (outline-previous-heading))))))
(sdcv-expand-entry)
(recenter-top-bottom 2))
(message "%s" (sdcv-get-outline-path)))
(defun sdcv-toggle-entry ()
(interactive)
(save-excursion
(outline-back-to-heading)
(if (not (save-excursion
(outline-end-of-heading)
(outline-invisible-p (line-end-position))))
(outline-hide-subtree)
(outline-show-subtree))))
;;; ==================================================================
;;; Support for sdcv process in background
(defun sdcv-do-lookup (word &optional raw-p)
"Send the word to the sdcv process and return the result."
(let ((process (sdcv-get-process)))
(process-send-string process (concat word "\n"))
(with-current-buffer (process-buffer process)
(let ((i 0) result done)
(while (and (not done)
(< i sdcv-wait-timeout))
(when (sdcv-match-tail sdcv-word-prompts)
(setq result (buffer-substring-no-properties (point-min)
(point-max)))
(setq done t))
(when (sdcv-match-tail sdcv-choice-prompts)
(process-send-string process "-1\n"))
(unless done
(sleep-for sdcv-wait-interval)
(setq i (+ i sdcv-wait-interval))))
(unless (< i sdcv-wait-timeout)
;; timeout
(kill-process process)
(error "ERROR: timeout waiting for sdcv"))
(erase-buffer)
(if raw-p result
(sdcv-format-result result))))))
(defun sdcv-oneshot-lookup (word &optional raw-p args)
(let ((result (shell-command-to-string
(concat sdcv-program-path " -n " args
" '" (replace-regexp-in-string "'" "\\'" word) "'"))))
(if raw-p result
(sdcv-format-result result))))
(defvar sdcv-wait-timeout 2
"The max time (in seconds) to wait for the sdcv process to
produce some output.")
(defvar sdcv-wait-interval 0.1
"The interval (in seconds) to sleep each time to wait for
sdcv's output.")
(defconst sdcv-process-name "%sdcv-mode-process%")
(defconst sdcv-process-buffer-name "*sdcv-mode-process*")
(defvar sdcv-word-prompts '("Enter word or phrase: ")
"A list of prompts that sdcv use to prompt for word.")
(defvar sdcv-choice-prompts '("Your choice[-1 to abort]: ")
"A list of prompts that sdcv use to prompt for a choice
of multiple candicates.")
(defvar sdcv-result-patterns '("^Found [0-9]+ items, similar to [*?/|]*\\(.+?\\)[*?]*\\.")
"A list of patterns to extract result word of sdcv. Special
characters are stripped.")
(defun sdcv-get-process ()
"Get or create the sdcv process."
(let ((process (get-process sdcv-process-name)))
(when (null process)
(with-current-buffer (get-buffer-create
sdcv-process-buffer-name)
(erase-buffer)
(setq process (apply 'start-process
sdcv-process-name
sdcv-process-buffer-name
sdcv-program-path
(sdcv-generate-dictionary-argument)))
(set-process-query-on-exit-flag process nil)
;; kill the initial prompt
(let ((i 0))
(message "starting sdcv...")
(while (and (not (sdcv-match-tail sdcv-word-prompts))
(< i sdcv-wait-timeout))
(sit-for sdcv-wait-interval t)
(setq i (+ i sdcv-wait-interval)))
(unless (< i sdcv-wait-timeout)
;; timeout
(kill-process process)
(error "ERROR: timeout waiting for sdcv"))
(erase-buffer))
(message "")))
process))
(defun sdcv-buffer-tail (length)
"Get a substring of length LENGTH at the end of
current buffer."
(let ((beg (- (point-max) length))
(end (point-max)))
(if (< beg (point-min))
(setq beg (point-min)))
(buffer-substring-no-properties beg end)))
(defun sdcv-match-tail (prompts)
(let ((done nil)
(prompt nil))
(while (and (not done)
prompts)
(setq prompt (car prompts))
(setq prompts (cdr prompts))
(when (string-equal prompt
(sdcv-buffer-tail (length prompt)))
(delete-region (- (point-max) (length prompt))
(point-max))
(setq done t)))
done))
;;;;##################################################################
;;;; Output Processing
;;;;##################################################################
(defun sdcv-format-result (result)
"For a given RESULT from sdcv, test for failure and format accordingly.
Entries are sorted by their :priority in `sdcv-dictionary-specs', and formatted by
`sdcv-format-result' in the case of success; `sdcv-format-failure' otherwise."
(if (sdcv-failed-p result)
(sdcv-format-failure result)
(let* ((entries
(sort (sdcv-parse-results result)
(lambda (a b)
(< (or (sdcv-dictionary-spec (plist-get a :dict) :priority) 1)
(or (sdcv-dictionary-spec (plist-get b :dict) :priority) 1)))))
(word (save-match-data
(string-match "\\`Found.* similar to \\(\\w+\\)\\." result)
(downcase (match-string 1 result)))))
(concat
"\u200B"
(propertize (capitalize word) 'face 'outline-1)
"\u2008"
(apply #'concat
(mapcar (lambda (e)
(sdcv-format-entry
e word))
entries))))))
(defun sdcv-parse-results (result)
"TODO"
(let (entries latest-match last-match dict word)
(with-temp-buffer
(insert result)
(goto-char (point-min))
(while
(setq latest-match (re-search-forward
"-->\\([^\n]+\\)\n-->\\(.+\\)\n\n" nil t))
(when last-match
(forward-line -3)
(setq entries
(append entries
`((:word ,word
:dict ,dict
:info ,(buffer-substring last-match (point))))))
(forward-line 3))
(setq last-match latest-match)
(setq dict (match-string 1))
(setq word (match-string 2)))
(when last-match
(setq entries
(append entries
`((:word ,word
:dict ,dict
:info ,(buffer-substring last-match (point-max)))))))))
)
(defun sdcv-failed-p (results)
"Whether the RESULTS match the hardcoded failure pattern."
(if (string-match-p "Found [0-9]+ items, similar to [^.]+\\.\n0)" results) t nil))
(defun sdcv-format-failure (results)
"When sdcv failed to match the word, format the suggestions in RESULTS."
(let (suggestions last-match)
(while (setq last-match
(string-match "^[0-9]+)\\(.*\\)-->\\([A-Za-z]+\\)"
results
(when last-match (1+ last-match))))
(let ((dict (match-string 1 results))
(word (match-string 2 results)))
(if (assoc dict suggestions)
(setcdr (assoc dict suggestions)
(list (append (cadr (assoc dict suggestions)) (list word))))
(setq suggestions (append suggestions `((,dict . ((,word)))))))))
(concat
(propertize
(replace-regexp-in-string
"items" "entries"
(substring results 0 (string-match "\n" results)))
'face 'warning)
"\n"
(mapconcat (lambda (dict-suggestions)
(format "\u200B\u200B%s\n\u200B\u200B\u200B%s"
(propertize (or
(sdcv-dictionary-spec (car dict-suggestions) :short)
(car dict-suggestions))
'face 'outline-3)
(propertize (s-join "\n\u200B\u200B\u200B"
(cadr dict-suggestions))
'face 'font-lock-keyword-face)))
(sort suggestions
(lambda (a b)
(< (or (sdcv-dictionary-spec (car a) :priority) 1)
(or (sdcv-dictionary-spec (car b) :priority) 1))))
"\n"))))
(defun sdcv-format-entry (entry &optional expected-word)
"Format a given ENTRY, a plist with :word :dict and :info.
If the DICT has a :short value in `sdcv-dictionary-specs' that is used as
the display name. Likewise if present, :formatter is used to generate the
entry."
(let ((dict (plist-get entry :dict)))
(concat
"\n\u200B\u200B"
(propertize (or (sdcv-dictionary-spec dict :short)
dict) 'face 'outline-3)
"\n\u2008\n"
(if-let* ((formatter (sdcv-dictionary-spec dict :formatter)))
(let ((case-fold-search nil))
(string-trim (funcall formatter entry expected-word)))
entry)
"\n")))
(defun sdcv-get-outline-path ()
"Return a string giving the structural path to the current position."
(let ((outline-path "")
(last-pos 0)
outline-level-current substring level-regexp)
(save-excursion
(outline-back-to-heading)
(setq outline-level-current (sdcv-outline-level))
(while (/= (point) last-pos)
(setq outline-level-current (sdcv-outline-level))
(setq substring
(buffer-substring
(point)
(save-excursion (search-forward "\u2008") (point))))
(setq level-regexp
(case outline-level-current
(1 "^\\([^\n]+\\)")
(2 "^\\([^ \n]+\\)")
(3 "^\u200B\u200B*\\([^,]+\\(?:, [ &.;a-z]+\\)?\\)")
(4 "\\([0-9]+\\.\\( ?([^)]+)\\)?\\( \\w+\\)\\{0,4\\}\\)")
(5 "\\(([a-z])\\( ?([^)]+)\\)?\\( \\w+\\)\\{0,4\\}\\)")
(t "^\u200B\u200B*\\([^ ]+\\)")))
(setq outline-path
(concat
(propertize " → " 'face 'bold)
(save-match-data
(string-match level-regexp substring)
(match-string 1 substring))
outline-path))
(setq last-pos (point))
(ignore-errors
(outline-up-heading 1)))
(substring outline-path 2))))
(defun sdcv-outline-level ()
"It seems that while (outline-level) should work, it has issues."
(- (save-excursion (outline-back-to-heading)
(search-forward-regexp "\u200B+"))
(point)))
(defun sdcv-dictionary-spec (dict spec)
"Helper function to get a :SPEC of a given DICT."
(plist-get (cdr (assoc dict sdcv-dictionary-specs)) spec))
(defvar sdcv-dictionary-specs
'(("Webster's Revised Unabridged Dictionary (1913)"
:formatter sdcv-format-webster
:priority 1)
("Elements database"
:short "Element"
:formatter sdcv-format-element
:priority 2)
("Hitchcock's Bible Names Dictionary"
:short "Hitcchcock's Bible Names"
:priority 3)
("Online Etymology Dictionary"
:short "Etymology"
:formatter sdcv-format-online-etym
:priority 4)
("Soule's Dictionary of English Synonyms"
:short "Synonyms"
:formatter sdcv-format-soule
:priority 5))
"Alist of dictionary information, where the car is the name
according to sdcv, and the cdr is a plist whith the following options:
:short - a (usually) shorter display name for the dictionary
:formatter - a function with signature (ENTRY WORD) that returns a string
:priority - sort priority, defaults to 1")
(defun sdcv-format-webster (entry &optional expected-word)
"Make a Webster's dictionary ENTRY for WORD look nice.
Designed for Webster's Revised Unabridged Dictionary (1913),
as found at http://download.huzheng.org/dict.org/stardict-dictd-web1913-2.4.2.tar.bz2.
This should also work nicely with GCIDE."
(->> (plist-get entry :info)
(sdcv-format-webster-diacritics)
(replace-regexp-in-string ; entry dividors
(format "\n\n\\(%s\\)" (plist-get entry :word))
"\n ━━━━━━━━━ ■ ━━━━━━━━━\n\n\\1")
(replace-regexp-in-string ; entry headline
(rx line-start
(group-n 1 ; word
(any "A-Z")
(+ (any "a-z")))
(optional " \\" ; word2
(group-n 2 (+ (not (any "\\"))))
"\\")
(optional " (" ; pronounciation
(group-n 3 (+ (not (any ")"))))
")")
", "
(group-n 4 ; part of speech
(+ (any "A-Z" "a-z" ".;&" " ")))
(optional "[" ; etymology / alternative forms
(group-n 5
(+ (or (+ (not (any "][")))
(and "[" (+ (not (any "]["))) "]"))))
"]")
(optional ; definately etymology
(+ (any "\n" " ")) "["
(group-n 6
(+ (or (+ (not (any "][")))
(and "[" (+ (not (any "]["))) "]"))))
"]")
(optional " (" ; category
(group-n 7 (+ (not (any ")"))))
")"))
(lambda (match)
(let* ((word2 (match-string 2 match))
(pronounciation (match-string 3 match))
(part-of-speech (sdcv-format-expand-abbreviations
(replace-regexp-in-string " \\'" ""
(match-string 4 match))))
(alternative-forms (when (match-string 6 match)
(sdcv-format-expand-abbreviations (match-string 5 match))))
(etymology (sdcv-format-expand-abbreviations (match-string (if alternative-forms 6 5) match)))
(category (sdcv-format-expand-abbreviations (match-string 7 match)))
(last-newline (lambda (text) (- (length text)
(or (save-match-data
(string-match "\n[^\n]*\\'" text)) 0)))))
(concat
"\u200B\u200B\u200B"
(propertize word2
'face 'bold)
(when pronounciation
(propertize (format " %s" pronounciation)
'face 'font-lock-type-face))
", "
(propertize part-of-speech
'face '(bold font-lock-keyword-face))
(when alternative-forms
(setq alternative-forms
(sdcv-format-reflow-text
(format " [%s]" alternative-forms)
80 10
(+ 3 (if pronounciation 1 0)
(funcall last-newline
(concat word2 pronounciation part-of-speech)))
" "))
(propertize alternative-forms
'face 'diff-context))
(when etymology
(setq etymology
(sdcv-format-reflow-text
(format " [%s]" etymology)
80 10
(+ 3 (if pronounciation 1 0)
(funcall last-newline
(concat word2 pronounciation part-of-speech alternative-forms)))
" "))
(propertize etymology
'face 'font-lock-comment-face))
(when category
(propertize (format " (%s)" category)
'face 'font-lock-constant-face))
"\u2008"))))
(replace-regexp-in-string ; categorised terms
"{\\([^}]+?\\)}\\(.?\\) (\\([^)]+?\\))"
(lambda (match)
(let ((term (match-string 1 match))
(punct (match-string 2 match))
(category (match-string 3 match)))
(concat
(propertize term 'face 'font-lock-keyword-face)
punct
(propertize (format " (%s)"
(if sdcv-expand-abbreviations
(sdcv-format-expand-abbreviations category)
category))
'face 'font-lock-constant-face)))))
(replace-regexp-in-string ; other terms
"{\\([^}]+?\\)}"
(lambda (match)
(let ((term (match-string 1 match)))
(concat
(propertize term 'face 'font-lock-keyword-face)))))
(replace-regexp-in-string ; quotations
"^\n +\\(\\w[[:ascii:]]+?\\)\\(\n? *--[A-Za-z0-9. ]+\n? *[A-Za-z0-9. ]*\\)"
(lambda (match)
(let ((body (match-string 1 match))
(author (match-string 2 match)))
(concat
"\n "
(propertize (format "❝%s❞" body)
'face 'font-lock-doc-face)
author "\n"))))
(replace-regexp-in-string ; attributions
" --\\([A-Z][A-Za-z. ]+\n? *[A-Za-z0-9. ]*\\)"
(lambda (match)
(propertize (concat " ──" (match-string 1 match))
'face '(italic font-lock-type-face))))
(replace-regexp-in-string ; inline quotations (1)
"``" "“")
(replace-regexp-in-string ; inline quotations (1)
"''" "”")
(replace-regexp-in-string ; em dash approximation
" -- " " ─── ")
(replace-regexp-in-string ; lists
" \\(?:\\([0-9]+\\.\\)\\|\\( ([a-z])\\)\\) \\(?: ?(\\([^)]+\\)) \\)?\\(.*\\)"
(lambda (match)
(let ((number (match-string 1 match))
(letter (match-string 2 match))
(category (match-string 3 match))
(rest-of-line (match-string 4 match)))
(concat
(when letter "\u200B")
"\u200B\u200B\u200B\u200B "
(when number
(propertize number 'face '(bold font-lock-string-face)))
(when letter
(propertize letter 'face 'font-lock-string-face))
(when category
(propertize (format " (%s)"
(if sdcv-expand-abbreviations
(sdcv-format-expand-abbreviations category)
category))
'face 'font-lock-constant-face))
" "
rest-of-line
"\u2008"))))
(replace-regexp-in-string ; note
" Note: "
(concat " "
(propertize " " 'display '(space . (:width 0.55)))
(propertize "☞" 'face 'font-lock-function-name-face)
" "))
(replace-regexp-in-string ; subheadings
" \\(\\w+\\): "
(lambda (match)
(propertize (concat " "(match-string 1 match) ": ")
'face 'bold)))))
(defvar sdcv-expand-abbreviations t
"Whether or not to try to expand abbreviations, where they are expected.")
(defun sdcv-format-expand-abbreviations (content &optional force)
(when content
(when (or sdcv-expand-abbreviations force)
(let ((abbreviations
'(; A
("adj" "adjective")
("a" "adjective")
("abbrev" "abbreviated")
("abl" "ablative")
("Abp" "Archbishop")
("acc" "Acoustics")
("act" "active")
("adv" "adverb")
("Agric" "Agriculture")
("Alban" "Albanian")
("Alg" "Algebra")
("Am" "America")
("Amer" "American")
("Am" "Amos")
("Am\\. Cyc" "Appleton's American Cyclopedia")
("Anal. Geom" "Analytical Geometry")
("Anat" "Anatomy")
("Anc" "Ancient")
("Angl\\. Ch" "Anglican Church")
("aor" "aorist")
("Ar" "Arabic")
("Arch" "Architecture")
("Arch\\. Pub\\. Soc" "Architectural Pub. Society")
("Arith" "Arithmetic")
("Arm\\., Armor" "Armorican")
("AS" "Anglo-Saxon")
("Astrol" "Astrology")
("Astron" "Astronomy")
("aug" "augmentative")
;; B
("Bank" "Banking")
("Beau\\. & Fl" "Beaumont & Fletcher")
("B\\. & Fl" "Beaumont & Fletcher")
("Bib\\. Sacra" "Bibliotheca Sacra")
("Bib" "Biblical")
("Bibliog" "Bibliography")
("Biol" "Biology")
("Bisc" "Biscayan")
("B\\. Jon" "Ben Jonson")
("Bk\\. of Com\\. Prayer " "Book of Common Prayer")
("Blackw\\. Mag" "Blackwood's Magazine")
("Bohem" "Bohemian")
("Bot" "Botany")
("Bp" "Bishop")
("Brande & C" "Brande & Cox")
("Braz" "Brazilian")
("Brit\\. Critic" "British Critic")
("Brit\\. Quar\\. Rev" "British Quarterly Review")
("Burl" "Burlesque")
;; C
("C" "Centigrade")
("Cant" "Canticles")
("Carp" "Carpentry")
("Catal" "Catalan")
("Cath\\. Dict" "Catholic Dictionary")
("Celt" "Celtic")
("cf" "confer")
("Ch" "Church")
("Chald" "Chaldee")
("Chem" "Chemistry")
("Ch\\. Hist" "Church History")
("Chron" "Chronology, Chronicles")
("Civ" "Civil")
("Class" "Classical")
("Class\\. Myth" "Classical Mythology")
("Col" "Colossians")
("colloq\\., coll" "colloquial, colloquially")
("Com" "Commerce, Common")
("comp" "compound, compounded, composition")
("compar" "comparative")
("conj" "conjunction")
("Con\\. Sect" "Conic Sections")
("contr" "contracted, contraction")
("Copt" "Coptic")
("Corn" "Cornish")
("corrupt" "corrupted, corruption")
("Cotgr" "Cotgrave")
("Cyc\\. Med" "Cyclopedia of Practical Medicine")
("Crim\\. Law" "Criminal Law")
("Crystallog" "Crystallography")
("Cyc" "Cyclopedia")
;; D
("D" "Dutch (sometimes Daniel)")
("Dan" "Danish")
("dat" "dative")
("def" "definitions")
("Deut" "Deuteronomy")
("Dial" "Dialectic")
("dim" "diminutive")
("Diosc" "dioscorides")
("Disp" "Dispensatory")
("Disus" "Disused")
("Dom\\. Econ" "Domestic Economy")
("Dublin Univ\\. Mag" "Dublin University Magazine")
("Dyn" "Dynamics")
;; E
("E" "English")
("Eccl" "Ecclesiastical, Ecclesiastes")
("Eccl\\. Hist" "Ecclesiastical History")
("Ecclus" "Ecclesiasticus")
("Eclec\\. Rev" "Eclectic Review")
("Ed\\. Rev" "Edinburgh Review")
;; ("e\\. g" "exempli gratia (for example)")
("Egypt" "Egyptian")
("Elect" "Electricity")
("Elec" "Electrical")
("emph" "emphatic")
("Encyc\\. Amer" "Encyclopedia Americana")
("Encyc\\. Crit" "Encyclopedia Britannica")
("Encyc\\. Dict" "Hunter's Encyclopedic Dictionary")
("Encyc" "Encyclopedia")
("Eng\\. Cyc" "English Cyclopedia")
("Eng" "English")
("Engin" "Engineering")
("Eol" "Eolic")
("Eph\\., Ephes" "Ephesians")
("equiv" "equivalent")
("Esd" "Esdras")
("esp" "especially")
("Etch\\. & Eng" "Etching & Engraving")
("Ethnol" "Ethnology")
("etym\\., etymol" "etymology")
("Ex\\., Exod" "Exodus")
("Ezek" "Ezekiel")
;; F
("F" "French")
("f" "feminine")
("fem" "feminine")
("Fahr" "Fahrenheit")
("Far" "Farriery")
("Feud" "Feudal")
("Fig" "Figurative, figuratively")
("Fin" "Finnish")
("For\\. Quart\\. Rev" "Foreign Quarterly Review")
("Fort" "Fortification")
("Fr" "French")
("fr" "from")
("freq" "frequentative")
("Fries" "Friesic")
("fut" "future")
;; G
("G" "German")
("Gael" "Gaelic")
("Gal" "Galen")
("Gal" "Galatians")
("Galv" "Galvanism")
("gen" "generally, genitive")
("Geneal" "Genealogy")
("Gent\\. Mag" "Gentleman's Magazine")
("Geog" "Geography")
("Geol" "Geology")
("Geom" "Geometry")
("Ger" "Germanic or German")
("Gk" "Greek")
("Goth" "Gothic")
("Gov\\. of Tongue" "Government of the Tongue")
("Gr" "Greek")
("Gram" "Grammar")
("Gris" "Grisons")
("Gun" "Gunnery")
;; H
("H" "High")
("Hab" "Habakkuk")
("Hag" "Haggai")
("Ham\\. Nav\\. Encyc" "Hamersly's Naval Encyclopedia")
("Heb" "Hebrew")
("Her" "Heraldry")
("Hind" "Hindostanee")
("Hipp" "Hippocrates")
("Hist" "History")
("Horol" "Horology")
("Hort" "Horticulture")