-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
lexic.el
2032 lines (1928 loc) · 84.2 KB
/
lexic.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
;;; lexic.el --- A major mode to find out more about words -*- lexical-binding: t; -*-
;; Copyright 2006~2008 pluskid,
;; 2011~2012 gucong
;; 2020~2021 tecosaur
;; Author: pluskid <pluskid@gmail.com>,
;; gucong <gucong43216@gmail.com>,
;; TEC <tec@tecosaur.com>
;;
;; Maintainer: TEC <tec@tecosaur.com>
;; Version: 0.0.1
;; Homepage: https://github.com/tecosaur/lexic
;; Package-Requires: ((emacs "26.3"))
;;; License:
;; 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 provides a major mode to view the output of dictionary tools,
;; and utilities that perform searches and nicely format the results.
;;
;; Currently tied to sdcv, but this is intended to be changed in the future.
;; Put this file into your load-path and the following into your
;; ~/.emacs:
;; (require 'lexic-mode)
;; (global-set-key (kbd "C-c d") 'lexic-search)
;;; Changelog:
;; 2020/07/28
;; * New variable: `lexic-dictionary-specs', allows for
;; - Dictionary display names
;; - Custom dictionary entry formatters
;; - Dictionary sorting
;; * Update outline function calls to replace depreciated names.'
;; * Tweak lexic-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 `lexic-next-entry' and `lexic-previous-entry'
;; * New function: `lexic-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 `lexic-program-path' to be an absolute path
;; * New functions: `lexic-format-result', `lexic-failed-p',
;; and `lexic-format-failure' to handle the upgraded entry processing
;; * New functions: `lexic-format-webster', `lexic-format-online-etym',
;; `lexic-format-element', and `lexic-format-soule' to format
;; the dictionaries recognised by default in `lexic-dictionary-specs'.
;; - with helper functions `lexic-format-webster-diacritics', and
;; `lexic-format-expand-abbreviations' for nicer content.
;; 2012/01/02
;; * New variable: `lexic-word-processor'
;; * Breaking change:
;; for `lexic-dictionary-alist', non-list (non-nil) value now means full dictionary list
;; * Rewrite `lexic-search' for both interactive and non-interactive use
;; * `lexic-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
;; * lexic-mode v 0.1 init (with background process)
;;; Code:
(require 'outline)
(require 'visual-fill-column nil t)
(require 'cl-lib)
(require 'subr-x)
(declare-function spell-fu-mode "spell-fu")
;;;;##################################################################
;;;; User Options, Variables
;;;;##################################################################
(defvar lexic-buffer-name "*lexic*"
"The name of the buffer of lexic.")
(defvar lexic-dictionary-list t
"A list of dictionaries to use.
Each entry is a string denoting the name of a dictionary, which
is then passed to lexic through the '-u' command line option.
Any non-list value means using all the dictionaries.")
(defvar lexic-dictionary-alist nil
"An alist of dictionaries, used to interactively form the dictionary list.
It has the form:
((\"full\" . t)
(\"group1\" \"dict1\" \"dict2\" ...)
(\"group2\" \"dict2\" \"dict3\"))
Any cons cell here means using all dictionaries.")
(defvar lexic-program-path (executable-find "sdcv")
"The path of lexic program.")
(defvar lexic-dictionary-path nil
"The path to the dictionaries.")
(defvar lexic-word-processor nil
"This is the function that take a word (stirng)
and return a word or a list of words for lookup by `lexic-search'.
All lookup result(s) will finally be concatenated together.
nil value means do nothing with the original word.
The following is an example. This function takes the original word and
compare whether simplified and traditional form of the word are the same.
If not, look up both of the words.
(lambda (word)
(let ((sim (chinese-conv word \"simplified\"))
(tra (chinese-conv word \"traditional\")))
(if (not (string= sim tra))
(list sim tra)
word)))
")
(defvar lexic-current-dictionary-list nil
"A list of dictionaries to use in searches.
Either entries from `lexic-dictionary-alist', or any non-list value,
which will cause all avalible dictionaries to be used.")
(defvar lexic-wait-timeout 2
"The max time (in seconds) to wait for the lexic process to produce some output.")
(defvar lexic-wait-interval 0.1
"The interval (in seconds) to sleep each time to wait for lexic's output.")
(defconst lexic-process-name " %lexic-mode-process%")
(defconst lexic-process-buffer-name " *lexic-mode-process*")
(defvar lexic-word-prompts '("Enter word or phrase: ")
"A list of prompts that lexic use to prompt for word.")
(defvar lexic-choice-prompts '("Your choice[-1 to abort]: ")
"A list of prompts that lexic use to prompt for a choice of multiple candidates.")
(defvar lexic-result-patterns '("^Found [0-9]+ items, similar to [*?/|]*\\(.+?\\)[*?]*\\.")
"A list of patterns to extract result word of lexic.
Special characters are stripped.")
(defvar lexic--search-history nil)
(defvar lexic--search-history-position -1)
(defvar lexic-expand-abbreviations t
"Whether or not to try to expand abbreviations, where they are expected.")
;;; ==================================================================
;;; Frontend, search word and display lexic buffer
;;;###autoload
(defun lexic-search (word &optional dict-list-name dict-list interactive-p no-history-p)
"Search WORD through the command line tool lexic.
The result will be displayed in buffer named with
`lexic-buffer-name' with `lexic-mode' if called interactively.
When provided with DICT-LIST-NAME, query `lexic-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 `lexic-dictionary-alist' is defined,
use prefix argument to select a new DICT-LIST-NAME.
Otherwise, prefix argument means using all dictionaries.
When INTERACTIVE-P is non-nil, a buffer displaying the result(s) is shown.
Otherwise, the result is returned as a string.
When NO-HISTORY-P is non-nil, the search is not added to the session history.
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
TODO decouple the tool from the general method."
(interactive
(let* ((dict-list-name
(and current-prefix-arg lexic-dictionary-alist
(completing-read "Select dictionary list: "
lexic-dictionary-alist nil t)))
(dict-list
(and current-prefix-arg (not lexic-dictionary-alist)))
(guess (or (and transient-mark-mode mark-active
(buffer-substring-no-properties
(region-beginning) (region-end)))
(current-word nil t)
"lexical"))
(word (read-string (format "Search dict (default: %s): " guess)
nil nil guess)))
(list word dict-list-name dict-list t)))
;; init current dictionary list
(unless lexic-current-dictionary-list
(setq lexic-current-dictionary-list lexic-dictionary-list))
;; dict-list-name to dict-list
(when (and (not dict-list) dict-list-name)
(if (not lexic-dictionary-alist)
(error "`lexic-dictionary-alist' not defined"))
(setq dict-list
(cdr (assoc dict-list-name lexic-dictionary-alist))))
;; prepare new dictionary list
(when (and dict-list (not (equal lexic-current-dictionary-list dict-list)))
(setq lexic-current-dictionary-list dict-list)
;; kill lexic process
(and (get-process lexic-process-name)
(kill-process (get-process lexic-process-name)))
(while (get-process lexic-process-name)
(sleep-for 0.01)))
(let ((result
(mapconcat
(lambda (w) (lexic-do-lookup w))
(if lexic-word-processor
(let ((processed (funcall lexic-word-processor word)))
(if (listp processed) processed (list processed)))
(list word))
"")))
(unless (or no-history-p (string= word
(nth lexic--search-history-position
lexic--search-history)))
(setq lexic--search-history
(append (cl-subseq lexic--search-history
0 (1+ lexic--search-history-position))
(list word))
lexic--search-history-position (1- (length lexic--search-history))))
(if (not interactive-p)
result
(with-current-buffer (get-buffer-create lexic-buffer-name)
(setq buffer-read-only nil)
(erase-buffer)
(insert result))
(lexic-goto-lexic)
(lexic-mode)
(lexic-mode-reinit)
(let* ((window (get-buffer-window (lexic-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)))))))
;;;###autoload
(defun lexic-search-word-at-point ()
"Perform `lexic-search' on the word at or near point."
(interactive)
(lexic-search
(downcase
(or (and transient-mark-mode mark-active
(buffer-substring-no-properties
(region-beginning) (region-end)))
(current-word nil t)
"lexical"))
nil nil t))
;;;###autoload
(defun lexic-list-dictionary ()
"Show available dictionaries."
(interactive)
(let (resize-mini-windows)
(shell-command (concat lexic-program-path " -l") lexic-buffer-name)))
(defun lexic-generate-dictionary-argument ()
"Generate the appropriate stcv dictionary argument.
Using `lexic-current-dictionary-list' and `lexic-dictionary-path'."
(append
(and lexic-dictionary-path (list "--data-dir" (expand-file-name lexic-dictionary-path)))
(and (listp lexic-current-dictionary-list)
(mapcan (lambda (dict)
(list "-u" dict))
lexic-current-dictionary-list))))
(defun lexic-search-history-backwards ()
"Show the previous word searched."
(interactive)
(if (> lexic--search-history-position 0)
(lexic-search (nth (setq lexic--search-history-position
(1- lexic--search-history-position))
lexic--search-history)
nil nil t t)
(message "At start of search history.")))
(defun lexic-search-history-forwards ()
"Show the next word searched."
(interactive)
(if (> (length lexic--search-history) lexic--search-history-position)
(lexic-search (nth (setq lexic--search-history-position
(1+ lexic--search-history-position))
lexic--search-history)
nil nil t t)
(message "At end of search history.")))
;;; ==================================================================
;;; utilities to switch from and to lexic buffer
(defvar lexic-previous-window-conf nil
"Window configuration before switching to lexic buffer.")
(defun lexic-goto-lexic ()
"Switch to lexic buffer in other window."
(interactive)
(unless (eq (current-buffer)
(lexic-get-buffer))
(setq lexic-previous-window-conf (current-window-configuration)))
(let* ((buffer (lexic-get-buffer))
(window (get-buffer-window buffer)))
(if (null window)
(switch-to-buffer-other-window buffer)
(select-window window))))
(defun lexic-return-from-lexic ()
"Bury lexic buffer and restore the previous window configuration."
(interactive)
(kill-process (get-process lexic-process-name))
(if (window-configuration-p lexic-previous-window-conf)
(progn
(set-window-configuration lexic-previous-window-conf)
(setq lexic-previous-window-conf nil)
(bury-buffer (lexic-get-buffer)))
(bury-buffer)))
(defun lexic-get-buffer ()
"Get the lexic buffer. Create one if there's none."
(let ((buffer (get-buffer-create lexic-buffer-name)))
(with-current-buffer buffer
(unless (eq major-mode 'lexic-mode)
(lexic-mode)))
buffer))
;;; ==================================================================
(defvar lexic-mode-map
(let ((map (copy-keymap special-mode-map)))
(define-key map "q" 'lexic-return-from-lexic)
(define-key map (kbd "RET") 'lexic-search-word-at-point)
(define-key map "a" 'outline-show-all)
(define-key map "h" 'outline-hide-body)
(define-key map "o" 'lexic-toggle-entry)
(define-key map (kbd "TAB") 'lexic-toggle-entry)
(define-key map "n" 'lexic-next-entry)
(define-key map "N" (lambda () (interactive) (lexic-next-entry t)))
(define-key map "p" 'lexic-previous-entry)
(define-key map "P" (lambda () (interactive) (lexic-previous-entry t)))
(define-key map "b" 'lexic-search-history-backwards)
(define-key map "f" 'lexic-search-history-forwards)
(set-keymap-parent map special-mode-map)
map)
"Keymap for `lexic-mode'.")
(define-derived-mode lexic-mode fundamental-mode "lexic"
"Major mode to look up word through lexic.
\\{lexic-mode-map}
Turning on lexic mode runs the normal hook `lexic-mode-hook'.
This mode locally removes any `spell-fu-mode' or `flyspell-mode' entries in
`text-mode-hook', but won't catch any other spell-checking initialisation.
Consider resolving any edge cases with an addition to `lexic-mode-hook'."
(setq buffer-read-only t)
(add-hook 'kill-buffer-hook
(lambda ()
(let ((proc (get-process lexic-process-name)))
(when (process-live-p proc)
(kill-process proc))))
nil t)
(setq-local outline-regexp "\u200B+")
(setq-local outline-heading-end-regexp "\u2008")
(when (featurep 'visual-fill-column)
(setq-local visual-fill-column-center-text t)
(visual-fill-column-mode 1)))
(defun lexic-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)
(lexic-parse-failed)
(setq buffer-read-only t)
(let* ((window (get-buffer-window (lexic-get-buffer)))
(win-height (window-height window))
(content-height (count-lines (point-min) (point-max))))
(when (> 0.5 (/ (float win-height) content-height))
(outline-hide-sublevels 3)))
(goto-char (point-min))
(search-forward "\u200B\u200B")
(left-char 1)))
(defun lexic-parse-failed ()
"Determine if the search failed, and if so parse the failure."
(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)
(insert (format "\n==>%s\n" save-word)))))))
(defun lexic-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 lexic-next-entry (&optional linear)
"Move to the next entry, targeting the same level unless LINEAR is set."
(interactive)
(when (< 1 (lexic-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)
(lexic-expand-entry)))))))
(lexic-expand-entry)
(recenter-top-bottom 1)
(message "%s" (lexic-get-outline-path)))
(defun lexic-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))))))
(lexic-expand-entry)
(recenter-top-bottom 2))
(message "%s" (lexic-get-outline-path)))
(defun lexic-toggle-entry ()
"Toggle the folding of the lexic entry point currently lies in."
(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 lexic process in background
(defun lexic-do-lookup (word &optional raw-p)
"Send the WORD to the lexic process and return the result.
Optional argument RAW-P signals whether the result should be formatted or not."
(let ((process (lexic-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 lexic-wait-timeout))
(when (lexic-match-tail lexic-word-prompts)
(setq result (buffer-substring-no-properties (point-min)
(point-max)))
(setq done t))
(when (lexic-match-tail lexic-choice-prompts)
(process-send-string process "-1\n"))
(unless done
(sleep-for lexic-wait-interval)
(setq i (+ i lexic-wait-interval))))
(unless (< i lexic-wait-timeout)
;; timeout
(kill-process process)
(error "ERROR: timeout waiting for lexic"))
(erase-buffer)
(if raw-p result
(lexic-format-result result))))))
(defun lexic-oneshot-lookup (word &optional raw-p args)
"Use a oneshot stcv process just to look up WORD, with ARGS.
Optional argument RAW-P signals whether the result should be formatted or not."
(let ((result (with-temp-buffer
(apply #'call-process lexic-program-path nil t nil
(append '("-n") args (list word)))
(buffer-string))))
(if raw-p result
(lexic-format-result result))))
(defun lexic-get-process ()
"Get or create the lexic process."
(let ((process (get-process lexic-process-name)))
(unless process
(with-current-buffer (get-buffer-create
lexic-process-buffer-name)
(erase-buffer)
(setq process (apply #'start-process
lexic-process-name
lexic-process-buffer-name
lexic-program-path
(lexic-generate-dictionary-argument)))
(set-process-query-on-exit-flag process nil)
;; kill the initial prompt
(let ((i 0))
(message "starting lexic...")
(while (and (not (lexic-match-tail lexic-word-prompts))
(< i lexic-wait-timeout))
(sit-for lexic-wait-interval t)
(setq i (+ i lexic-wait-interval)))
(unless (< i lexic-wait-timeout)
;; timeout
(kill-process process)
(error "ERROR: timeout waiting for lexic"))
(erase-buffer))
(message "")))
process))
(defun lexic-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 lexic-match-tail (prompts)
"Look for a sdcv prompt from PROMPTS in the tail of the current buffer.
Remove it and return t if found. Return nil otherwise."
(let ((done nil)
(prompt nil))
(while (and (not done)
prompts)
(setq prompt (car prompts))
(setq prompts (cdr prompts))
(when (string-equal prompt
(lexic-buffer-tail (length prompt)))
(delete-region (- (point-max) (length prompt))
(point-max))
(setq done t)))
done))
;;;;##################################################################
;;;; Output Processing
;;;;##################################################################
(defun lexic-format-result (result)
"For a RESULT from lexic, test for failure and format accordingly.
Entries are sorted by their :priority in `lexic-dictionary-specs' then formatted
by `lexic-format-result' in successful case, `cases-format-failure' otherwise."
(cond
((string-match-p "^Nothing similar to" result)
(lexic-consider-no-results))
((lexic-failed-p result)
(lexic-format-failure result))
(t
(let* ((entries
(sort (lexic-parse-results result)
(lambda (a b)
(< (or (lexic-dictionary-spec (plist-get a :dict) :priority) 1)
(or (lexic-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)
(lexic-format-entry
e word))
entries)))))))
(defun lexic-consider-no-results ()
"No results have been found. What should we tell the user?"
(let ((dicts? (not (string-match-p "\\`Dictionary's name +Word count[\n ]+\\'"
(shell-command-to-string (concat lexic-program-path " -l"))))))
(if dicts?
(user-error "Couldn't find anything similar to your search, sorry :(")
(user-error "No results found, but you don't seem to have any dictionaries installed! Try %s"
(propertize "M-x lexic-dictionary-help" 'face 'font-lock-keyword-face)))))
(defun lexic-parse-results (result)
"Loop through every entry in RESULT and parse each one.
Returns a list of plists with keys :word, :dict, and :info."
(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 lexic-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 lexic-format-failure (results)
"When lexic 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
(lexic-dictionary-spec (car dict-suggestions) :short)
(car dict-suggestions))
'face 'outline-3)
(propertize
(mapconcat #'identity (cadr dict-suggestions) "\n\u200B\u200B\u200B")
'face 'font-lock-keyword-face)))
(sort suggestions
(lambda (a b)
(< (or (lexic-dictionary-spec (car a) :priority) 1)
(or (lexic-dictionary-spec (car b) :priority) 1))))
"\n"))))
(defun lexic-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 `lexic-dictionary-specs' that is used as
the display name. Likewise if present, :formatter is used to generate the
entry. EXPECTED-WORD is the word expected in ENTRY."
(let ((dict (plist-get entry :dict)))
(concat
"\n\u200B\u200B"
(propertize (or (lexic-dictionary-spec dict :short)
dict) 'face 'outline-3)
"\n\u2008\n"
(if-let* ((formatter (lexic-dictionary-spec dict :formatter)))
(let ((case-fold-search nil))
(string-trim (funcall formatter entry expected-word)))
(plist-get entry :info))
"\n")))
(defun lexic-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 (lexic-outline-level))
(while (/= (point) last-pos)
(setq outline-level-current (lexic-outline-level))
(setq substring
(buffer-substring
(point)
(save-excursion (search-forward "\u2008") (point))))
(setq level-regexp
(pcase outline-level-current
(1 "^\\([^\n]+\\)")
(2 "^\\([^ \n]+\\)")
(3 "^\u200B\u200B*\\([^,]+\\(?:, [ &.;a-z]+\\)?\\)")
(4 "\\([0-9]+\\.\\( ?([^)]+)\\)?\\( \\w+\\)\\{0,4\\}\\)")
(5 "\\(([a-z])\\( ?([^)]+)\\)?\\( \\w+\\)\\{0,4\\}\\)")
(_ "^\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 lexic-outline-level ()
"It seems that while (outline-level) should work, it has issues."
(- (save-excursion (outline-back-to-heading)
(search-forward-regexp "\u200B+"))
(point)))
(defvar lexic-dictionary-specs
'(("Webster's Revised Unabridged Dictionary (1913)"
:formatter lexic-format-webster
:priority 1)
("Elements database"
:short "Element"
:formatter lexic-format-element
:priority 2)
("Hitchcock's Bible Names Dictionary"
:short "Hitcchcock's Bible Names"
:priority 3)
("Online Etymology Dictionary"
:short "Etymology"
:formatter lexic-format-online-etym
:priority 4)
("Soule's Dictionary of English Synonyms"
:short "Synonyms"
:formatter lexic-format-soule
:priority 5))
"List of dictionary specifications.
In each entry the car is the name according to lexic, 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 lexic-dictionary-spec (dict spec)
"Helper function to get a :SPEC of a given DICT."
(plist-get (cdr (assoc dict lexic-dictionary-specs)) spec))
(defun lexic-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."
(thread-last (plist-get entry :info)
(lexic-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 ; definitely 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 (lexic-format-expand-abbreviations
(replace-regexp-in-string " \\'" ""
(match-string 4 match))))
(alternative-forms (when (match-string 6 match)
(lexic-format-expand-abbreviations (match-string 5 match))))
(etymology (lexic-format-expand-abbreviations (match-string (if alternative-forms 6 5) match)))
(category (lexic-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
(lexic-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
(lexic-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 lexic-expand-abbreviations
(lexic-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 lexic-expand-abbreviations
(lexic-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)))))
(defun lexic-format-expand-abbreviations (content &optional force)
"Expand certain standard abbreviations in CONTENT when `lexic-expand-abbreviations' or FORCE are non-nil."
(when content
(when (or lexic-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")
("Cf" "Confer")