-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spell-fu.el
1905 lines (1630 loc) · 72.7 KB
/
spell-fu.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
;;; spell-fu.el --- Fast & light spelling highlighter -*- lexical-binding: t -*-
;; SPDX-License-Identifier: GPL-2.0-or-later
;; Copyright (C) 2020 Campbell Barton
;; Author: Campbell Barton <ideasman42@gmail.com>
;; URL: https://codeberg.org/ideasman42/emacs-spell-fu
;; Keywords: convenience
;; Version: 0.3
;; Package-Requires: ((emacs "26.2"))
;;; Commentary:
;; This package checks the spelling of on-screen text.
;;
;;; Usage
;;
;; Write the following code to your .emacs file:
;;
;; (require 'spell-fu)
;; (spell-fu-global-mode)
;;
;; Or with `use-package':
;;
;; (use-package spell-fu)
;; (spell-fu-global-mode)
;;
;; If you prefer to enable this per-mode, you may do so using
;; mode hooks instead of calling `spell-fu-global-mode'.
;; The following example enables this for org-mode:
;;
;; (add-hook 'org-mode-hook
;; (lambda ()
;; (setq spell-fu-faces-exclude '(org-meta-line))
;; (spell-fu-mode)))
;;
;;; Code:
;; ---------------------------------------------------------------------------
;; Require Dependencies
;; For `face-list-p'.
(require 'faces)
;; For variables we read `ispell-personal-dictionary' local dictionary, etc.
(require 'ispell)
;; For `string-blank-p'.
(require 'subr-x)
;; ---------------------------------------------------------------------------
;; Compatibility
(when (and (version< emacs-version "29.1") (not (and (fboundp 'pos-bol) (fboundp 'pos-eol))))
(defun pos-bol (&optional n)
"Return the position at the line beginning."
(declare (important-return-value nil) (side-effect-free t))
(let ((inhibit-field-text-motion t))
(line-beginning-position n)))
(defun pos-eol (&optional n)
"Return the position at the line end."
(declare (important-return-value nil) (side-effect-free t))
(let ((inhibit-field-text-motion t))
(line-end-position n))))
;; ---------------------------------------------------------------------------
;; Custom Variables
(defgroup spell-fu nil
"Fast, configurable spell checking of visible text, updated on a timer."
:group 'ispell)
(defcustom spell-fu-directory (locate-user-emacs-file "spell-fu" ".emacs-spell-fu")
"The directory to store dictionary data."
:type 'string)
(defcustom spell-fu-idle-delay 0.25
"Idle time to wait before highlighting.
Set to 0.0 to highlight immediately (as part of syntax highlighting)."
:type 'float)
(defcustom spell-fu-ignore-modes nil
"List of major-modes to exclude when `spell-fu' has been enabled globally."
:type '(repeat symbol))
(defcustom spell-fu-word-delimit-camel-case nil
"Support camel-case for delimiting word boundaries.
So `HelloWorld' would be checked a two words instead of one.
This is performed as an additional check for words that would
otherwise be marked as incorrect."
:type 'boolean)
(defcustom spell-fu-debug nil
"Enable debug messages, use for troubleshooting unexpected behavior."
:type 'boolean)
(defvar-local spell-fu-buffer-session-localwords nil
"Optional buffer-local word-list of words.
This is intended to be set by file-locals or dir-locals.
Call `spell-fu-buffer-session-localwords-refresh' after run-time modifications.")
;;;###autoload
(put 'spell-fu-buffer-session-localwords 'safe-local-variable #'spell-fu-list-of-strings-p)
(define-obsolete-variable-alias
'global-spell-fu-ignore-buffer 'spell-fu-global-ignore-buffer "0.4")
(defvar-local spell-fu-global-ignore-buffer nil
"When non-nil, the global mode will not be enabled for this buffer.
This variable can also be a predicate function, in which case
it'll be called with one parameter (the buffer in question), and
it should return non-nil to make Global `spell-fu' Mode not
check this buffer.")
;; A spell-fu dictionary is a symbol, the variable value of which is a hash table with the
;; dictionary's words. The symbol additionally has these properties:
;; - 'description - short human-readable description of the dictionary.
;; - 'update - function, called to update the words hash table.
;; - 'add-word - function, called to permanently add a word to the dictionary.
;; Not set for read-only dictionaries.
;; - 'remove-word - ditto
(defvar-local spell-fu-dictionaries nil
"List of dictionaries enabled in the current buffer.
Use the spell-fu-get-...-dictionary functions to construct values
suitable for populating this list. To add a dictionary, please
use `spell-fu-dictionary-add'.")
(defface spell-fu-incorrect-face
'((((supports :underline (:style wave))) :underline (:style wave :color "red"))
(t :underline t :inherit error))
"Face for incorrect spelling.")
;; See '-' as a word boundary \b, so 'full-screen' is detected as two words.
(defvar-local spell-fu-syntax-table
(let ((table (copy-syntax-table (standard-syntax-table))))
(modify-syntax-entry ?- "-" table)
table)
"The syntax table to use when scanning words.")
;; This regex handles:
;;
;; - ``Quotation'' <= don't match multiple trailing apostrophes.
;; ^^^^^^^^^
;;
;; - we're <= Connect letters with a single apostrophe.
;; ^^^^^
;;
;; - don't''join <= don't connect multiple apostrophes.
;; ^^^^^ ^^^^
;;
;; - word' <= don't count the final apostrophe.
;; ^^^^
(defvar-local spell-fu-word-regexp "\\b\\([[:alpha:]]+\\(['\u2019][[:alpha:]]+\\)?\\)\\b"
"Regex used to scan for words to check.
Used by `spell-fu-check-range'.")
(defvar-local spell-fu-faces-include nil
"List of faces to check or nil to include all.
Used by `spell-fu-check-range'.")
(defvar-local spell-fu-faces-exclude nil
"List of faces not to check or nil to exclude none.
Used by `spell-fu-check-range'.")
(defvar-local spell-fu-check-range 'spell-fu-check-range-default
"Function that takes a beginning & end points to check for the current buffer.
Users may want to write their own functions to have more control
over which words are being checked.
Notes:
- The ranges passed in a guaranteed to be on line boundaries.
- Calling `spell-fu-check-word' on each word.
- You may explicitly mark a range as incorrect using
`spell-fu-mark-incorrect' which takes the range to mark as arguments.")
;; ---------------------------------------------------------------------------
;; Internal Variables
;; Use to ensure the cache is not from a previous release.
;; Only ever increase.
(defconst spell-fu--cache-version "0.2")
;; Keep track of the last overlay, this allows expanding the existing overlay where possible.
;; Useful since font-locking often uses multiple smaller ranges which can be merged into one range.
;; Always check this has not been deleted (has a valid buffer) before use.
(defvar-local spell-fu--idle-overlay-last nil)
;; Cache the result of: `(mapcar (lambda (dict) (symbol-value dict)) spell-fu-dictionaries)'
(defvar-local spell-fu--cache-table-list nil)
;; The buffer local dictionary generated from `spell-fu-buffer-session-localwords'.
(defvar-local spell-fu--buffer-localwords-cache-table nil)
;; Map `spell-fu-buffer-session-localwords' identity to existing
;; `spell-fu--buffer-localwords-cache-table' entries to avoid conversions from
;; word lists to dictionaries by checking if the conversion has already been done.
;;
;; NOTE: The keys are the objects for the local-word list,
;; so this relies on the lists being shared between buffers (not just matching contents).
(defvar spell-fu--buffer-localwords-global-cache-table-map nil)
;; ---------------------------------------------------------------------------
;; Internal Macros
;; Developer note, don't use this for logging the checking of individual words,
;; that is far too verbose, this is mainly for checking why dictionaries aren't
;; being properly initialized.
(defmacro spell-fu--debug-message (fmt &rest args)
"Debug message logging passing FMT and ARGS to `message'."
;; When emacs 28.2 support is dropped,
;; this can simply check `spell-fu-debug', see: #36.
(when (bound-and-true-p spell-fu-debug)
`(apply #'message (list (concat "spell-fu-debug: " ,fmt) ,@args))))
;; ---------------------------------------------------------------------------
;; Dictionary Utility Functions
(defsubst spell-fu--canonicalize-word-downcase (word)
"Return lowercase UTF-8 encoded WORD (must already be `downcase')."
(encode-coding-string word 'utf-8))
(defsubst spell-fu--canonicalize-word (word)
"Return lowercase UTF-8 encoded WORD."
(spell-fu--canonicalize-word-downcase (downcase word)))
(defun spell-fu--default-dictionaries ()
"Construct the default value of `spell-fu-dictionaries'."
(declare (important-return-value t))
(let ((result))
;; Push in reverse order (so first used dictionary is last).
(cond
(spell-fu-buffer-session-localwords
(push (spell-fu-get-buffer-session-localwords-dictionary) result)
(spell-fu--debug-message
"default-dictionary: `spell-fu-buffer-session-localwords' found, using!"))
(t
(spell-fu--debug-message
"default-dictionary: `spell-fu-buffer-session-localwords' not found, skipping!")))
(cond
((and ispell-personal-dictionary (file-exists-p ispell-personal-dictionary))
(push (spell-fu-get-personal-dictionary "default" ispell-personal-dictionary) result)
(spell-fu--debug-message
"default-dictionary: `ispell-personal-dictionary' found at \"%s\" using!"
ispell-personal-dictionary))
(t
(spell-fu--debug-message
"default-dictionary: `ispell-personal-dictionary' not found, skipping!")))
(let ((dict (or ispell-local-dictionary ispell-dictionary "default")))
(push (spell-fu-get-ispell-dictionary dict) result)
(spell-fu--debug-message "default-dictionary: name \"%s\" main ispell dictionary!" dict))
result))
(defun spell-fu--dictionary-ensure-update (dict)
"Call DICT update function if it exists."
(declare (important-return-value nil))
(let ((update-fun (get dict 'update)))
(when update-fun
(funcall update-fun)
(spell-fu--debug-message "updating [%s], found [%d] word(s)"
(get dict 'description)
(hash-table-size (symbol-value dict))))))
(defun spell-fu--dictionaries-test-any (test-fn)
"Remove any dictionaries that match TEST-FN."
(declare (important-return-value t))
(let ((result nil))
(let ((dict-list spell-fu-dictionaries))
(while dict-list
(let ((dict (pop dict-list)))
(when (funcall test-fn dict)
(setq result t)
(setq dict-list nil)))))
result))
(defun spell-fu--dictionaries-remove-any (test-fn)
"Return non-nil if any dictionaries match TEST-FN."
(declare (important-return-value nil))
(setq spell-fu-dictionaries
(remq
nil
(mapcar
(lambda (dict)
(cond
((funcall test-fn dict)
dict)
(t
nil)))
spell-fu-dictionaries))))
(defun spell-fu--cache-file (dict)
"Return the location of the cache file with dictionary DICT."
(declare (important-return-value t))
(expand-file-name (format "words_%s.el.data" (symbol-name dict)) spell-fu-directory))
(defun spell-fu--words-file (dict)
"Return the location of the word-list with dictionary DICT."
(declare (important-return-value t))
(expand-file-name (format "words_%s.txt" (symbol-name dict)) spell-fu-directory))
(defun spell-fu--refresh-cache-table-list ()
"Refresh internal list `spell-fu--cache-table-list'."
(declare (important-return-value nil))
(setq spell-fu--cache-table-list
(mapcar (lambda (dict) (symbol-value dict)) spell-fu-dictionaries)))
(defun spell-fu--refresh ()
"Reset spell-checked overlays in the current buffer."
(declare (important-return-value nil))
;; For now simply clear syntax highlighting.
(unless (<= spell-fu-idle-delay 0.0)
(spell-fu--idle-overlays-remove))
(spell-fu--overlays-remove)
(font-lock-flush))
(defun spell-fu--buffers-refresh-with-dict (dict)
"Reset spell-checked overlays for buffers using the dictionary DICT."
(declare (important-return-value nil))
(dolist (buf (buffer-list))
(with-current-buffer buf
(when (and (bound-and-true-p spell-fu-mode)
(bound-and-true-p spell-fu-dictionaries)
(member dict spell-fu-dictionaries))
(spell-fu--refresh)))))
(defun spell-fu--get-edit-candidate-dictionaries (word action)
"Return dictionaries for which it make sense to perform ACTION on WORD.
ACTION is `'remove' or `'add'. Returned candidates are dictionaries
which support the operation, and correspondingly do / do not
already contain WORD."
(declare (important-return-value t))
(let ((adding (eq action 'add))
(encoded-word (spell-fu--canonicalize-word word)))
(delq
nil
(mapcar
(lambda (dict)
(and
;; Operation supported?
(get
dict
(cond
(adding
'add-word)
(t
'remove-word)))
;; Word is / is not in dictionary?
(eq adding (null (gethash encoded-word (symbol-value dict))))
;; Result.
dict))
spell-fu-dictionaries))))
(defun spell-fu--read-dictionary (candidate-dicts prompt)
"Ask the user to select one dictionary from CANDIDATE-DICTS.
PROMPT is shown to the users completing read."
(declare (important-return-value t))
(cond
((<= (length candidate-dicts) 1)
;; Return the single choice
(car candidate-dicts))
(t
(let ((completion-extra-properties
'(:annotation-function (lambda (candidate) (get (intern candidate) 'description)))))
(intern (completing-read prompt (mapcar #'symbol-name candidate-dicts)))))))
;; ---------------------------------------------------------------------------
;; Generic Utility Functions
;;
;; Helpers, not directly related to checking spelling.
;;
(defmacro spell-fu--with-advice (fn-orig where fn-advice &rest body)
"Execute BODY with WHERE advice on FN-ORIG temporarily enabled."
(declare (indent 3))
(let ((function-var (gensym)))
`(let ((,function-var ,fn-advice))
(unwind-protect
(progn
(advice-add ,fn-orig ,where ,function-var)
,@body)
(advice-remove ,fn-orig ,function-var)))))
(defmacro spell-fu--with-message-prefix (prefix &rest body)
"Add text before the message output.
Argument PREFIX is the text to add at the start of the message.
Optional argument BODY runs with the message prefix."
(declare (indent 1))
`(spell-fu--with-advice #'message :around
(lambda (fn-orig arg &rest args)
(apply fn-orig (append (list (concat "%s" arg)) (list ,prefix) args)))
,@body))
(defmacro spell-fu--with-add-hook-depth-override (depth-override &rest body)
"Support overriding the depth of a hook added by an indirect call.
Argument DEPTH-OVERRIDE the depth value to call `add-hook' with.
Optional argument BODY runs with the depth override."
(declare (indent 1))
`(spell-fu--with-advice #'add-hook :around
(lambda (fn-orig hook function &optional _depth local)
(funcall fn-orig hook function ,depth-override local))
,@body))
(defmacro spell-fu--setq-expand-range-to-line-boundaries (pos-beg pos-end)
"Set POS-BEG the the line beginning, POS-END to the line end."
;; Ignore field boundaries.
(let ((inhibit-field-text-motion t))
`(save-excursion
;; Extend the ranges to line start/end.
(goto-char ,pos-end)
(setq ,pos-end (pos-eol))
(goto-char ,pos-beg)
(setq ,pos-beg (pos-bol)))))
(defun spell-fu--buffer-as-line-list (buffer lines)
"Add lines from BUFFER to LINES, returning the updated LINES."
(declare (important-return-value t))
(with-current-buffer buffer
(save-excursion
(goto-char (point-min))
(while (not (eobp))
(push (buffer-substring-no-properties (pos-bol) (pos-eol)) lines)
(forward-line 1))))
lines)
(defun spell-fu--removed-changed-overlay (overlay after _beg _end &optional _len)
"Hook for removing OVERLAY which is being edited.
Argument AFTER, ignore when true."
(declare (important-return-value nil))
(unless after
(delete-overlay overlay)))
(defun spell-fu--faces-at-point (pos)
"Add the named faces that the `read-face-name' or `face' property use.
Argument POS return faces at this point."
(declare (important-return-value t))
(let ((faces nil) ; List of faces to return.
;; NOTE: use `get-text-property' instead of `get-char-property' so overlays are excluded,
;; since this causes overlays with `hl-line-mode' (for example) to mask other faces.
;; If we want to include faces of overlays, this could be supported.
(faceprop (or (get-text-property pos 'read-face-name) (get-text-property pos 'face))))
(cond
((facep faceprop)
(push faceprop faces))
((face-list-p faceprop)
(dolist (face faceprop)
(when (facep face)
(push face faces)))))
faces))
(defun spell-fu--next-faces-prop-change (pos limit)
"Return the next face change from POS restricted by LIMIT."
(declare (important-return-value t))
(next-single-property-change pos 'read-face-name
nil
(next-single-property-change pos 'face nil limit)))
(defun spell-fu--file-is-older-list (file-test file-list)
"Return t when FILE-TEST is older than any files in FILE-LIST."
(declare (important-return-value t))
(catch 'result
(let ((file-test-time (file-attribute-modification-time (file-attributes file-test))))
(dolist (file-new file-list)
(when (time-less-p
file-test-time (file-attribute-modification-time (file-attributes file-new)))
(throw 'result t)))
nil)))
(defun spell-fu--file-is-older (file-test &rest file-list)
"Return t when FILE-TEST is older than any files in FILE-LIST."
(declare (important-return-value t))
(spell-fu--file-is-older-list file-test file-list))
;; Auto load as this is a callback for `safe-local-variable'.
;;;###autoload
(defun spell-fu-list-of-strings-p (obj)
"Return t when OBJ is a list of strings."
(declare (important-return-value t))
(and (listp obj) (not (memq nil (mapcar #'stringp obj)))))
;; ---------------------------------------------------------------------------
;; Word List Cache
(defun spell-fu--cache-from-word-list-impl (words-file cache-file)
"Create CACHE-FILE from WORDS-FILE.
The resulting cache is returned as a minor optimization for first-time loading,
where we need to create this data in order to write it,
save some time by not spending time reading it back."
(declare (important-return-value t))
(message "%S" (file-name-nondirectory cache-file))
(let ((cache-header
;; The header, an associative list of items.
(list (cons "version" spell-fu--cache-version)))
(word-table nil)
;; Needed for Windows to prevent CRLF including new-lines in strings.
(coding-system-for-read 'utf-8-unix)
(coding-system-for-write 'utf-8-unix))
(with-temp-buffer
(insert-file-contents-literally words-file)
(setq word-table (make-hash-table :test #'equal :size (count-lines (point-min) (point-max))))
(while (not (eobp))
(let ((l (buffer-substring-no-properties (pos-bol) (pos-eol))))
;; Value of 't' is just for simplicity, it's no used except for check the item exists.
(puthash (spell-fu--canonicalize-word l) t word-table)
(forward-line 1))))
;; Write write it to a file.
(with-temp-buffer
(prin1 cache-header (current-buffer))
(prin1 word-table (current-buffer))
(write-region nil nil cache-file nil 0))
;; Return the resulting word table.
word-table))
(defun spell-fu--cache-from-word-list (words-file cache-file)
"Create CACHE-FILE from WORDS-FILE."
(declare (important-return-value t))
(spell-fu--with-message-prefix "Spell-fu generating cache: "
(condition-case err
(spell-fu--cache-from-word-list-impl words-file cache-file)
(error
;; Should be rare: if the file is corrupt or cannot be read for any reason.
(progn
(message "failed, %s" (error-message-string err))
nil)))))
(defun spell-fu--cache-words-load-impl (cache-file)
"Return the Lisp content from reading CACHE-FILE.
On failure of any kind, return nil,
the caller will need to regenerate the cache."
(declare (important-return-value t))
(with-temp-buffer
(insert-file-contents-literally cache-file)
(goto-char (point-min))
;; Check header.
(let ((cache-header (read (current-buffer))))
(unless (listp cache-header)
(error "Expected cache-header to be list, not %S" (type-of cache-header)))
(let ((version (assoc-default "version" cache-header)))
(unless (string-equal version spell-fu--cache-version)
(error "Require cache version %S, not %S" spell-fu--cache-version version))))
;; Read the contents.
(let ((word-table (read (current-buffer))))
(unless (hash-table-p word-table)
(error "Expected cache to contain a hash-table, not %S" (type-of word-table)))
word-table)))
(defun spell-fu--cache-words-load (cache-file)
"Return the Lisp content from reading CACHE-FILE."
(declare (important-return-value t))
(spell-fu--with-message-prefix "Spell-fu reading cache: "
(condition-case err
(spell-fu--cache-words-load-impl cache-file)
(error
;; Should be rare: if the file is corrupt or cannot be read for any reason.
(progn
(message "failed, %s" (error-message-string err))
nil)))))
;; ---------------------------------------------------------------------------
;; Explode Words (Calculate Extra Delimiters)
(defun spell-fu--maybe-explode-word-by-camel-case (word word-locase word-upcase)
"Explode WORD by camel-case.
Arguments WORD-LOCASE & WORD-UPCASE are simply to avoid extra computation."
(declare (important-return-value t))
(let* ((was-caps t)
(was-ignore nil)
(word-length (length word))
(i-prev word-length)
(i word-length)
;; Build list in reverse so it's ordered from first to last.
(result nil))
(while (not (zerop i))
(setq i (1- i))
(let* ((ch-nat (aref word i))
(ch-locase (aref word-locase i))
(ch-upcase (aref word-upcase i))
(is-caps (not (eq ch-nat ch-locase))))
(cond
;; Ignore punctuation (typically apostrophe).
;; Needed for "TODO's" not to be split into ("TOD" "O's").
((eq ch-locase ch-upcase)
(setq was-caps is-caps)
(setq was-ignore t))
(t
(cond
(was-ignore
(setq was-ignore nil))
((and is-caps (not was-caps))
(when (< i i-prev)
(push (cons i i-prev) result)
(setq i-prev i)))
((and was-caps (not is-caps))
(let ((i-ofs (1+ i)))
(when (< i-ofs i-prev)
(push (cons i-ofs i-prev) result)
(setq i-prev i-ofs)))))))
(setq was-caps is-caps)))
(when result
(unless (zerop i-prev)
(push (cons 0 i-prev) result)))
result))
(defsubst spell-fu--maybe-explode-word-ex (word word-locase word-upcase)
"Return a list of ranges or return nil when no delimiters found.
Uses WORD, WORD-LOCASE & WORD-UPCASE to calculate delimiting."
(cond
;; The option to delimit by camel-case isn't enabled, early exit.
((null spell-fu-word-delimit-camel-case)
nil)
;; Early exit common case Where only the first letter is capitalized.
((string-equal (substring word 1) (substring word-locase 1))
nil)
(t
(spell-fu--maybe-explode-word-by-camel-case word word-locase word-upcase))))
(defun spell-fu--maybe-explode-word (word)
"Explode WORD into components or return nil."
(declare (important-return-value t))
(spell-fu--maybe-explode-word-ex word (downcase word) (upcase word)))
;; ---------------------------------------------------------------------------
;; Shared Functions
(defun spell-fu--overlays-remove (&optional pos-beg pos-end)
"Remove symbol `spell-fu-mode' overlays from current buffer.
If optional arguments POS-BEG and POS-END exist
remove overlays from range POS-BEG to POS-END
Otherwise remove all overlays."
(declare (important-return-value nil))
(remove-overlays pos-beg pos-end 'spell-fu-mode t))
(defun spell-fu-mark-incorrect (pos-beg pos-end)
"Mark the text from POS-BEG to POS-END with incorrect spelling overlay."
(declare (important-return-value nil))
(let ((item-ov (make-overlay pos-beg pos-end)))
(overlay-put item-ov 'spell-fu-mode t)
(overlay-put item-ov 'face 'spell-fu-incorrect-face)
(overlay-put item-ov 'modification-hooks 'spell-fu--removed-changed-overlay)
(overlay-put item-ov 'insert-in-front-hooks 'spell-fu--removed-changed-overlay)
(overlay-put item-ov 'insert-behind-hooks 'spell-fu--removed-changed-overlay)
(overlay-put item-ov 'evaporate t)
item-ov))
(defsubst spell-fu--check-word-in-dict-list (encoded-word)
"Return t if ENCODED-WORD is found in `spell-fu-dictionaries'."
(let ((found nil)
(cache-table-list spell-fu--cache-table-list))
(while cache-table-list
(let ((cache-table (pop cache-table-list)))
(when (gethash encoded-word cache-table nil)
(setq found t)
(setq cache-table-list nil))))
found))
(defun spell-fu-check-word (pos-beg pos-end word)
"Run the spell checker on a word.
Marking the spelling as incorrect using `spell-fu-incorrect-face' on failure.
Argument POS-BEG the beginning position of WORD.
Argument POS-END the end position of WORD."
(declare (important-return-value nil))
;; Dictionary search.
(let ((word-locase (downcase word)))
(unless (spell-fu--check-word-in-dict-list (spell-fu--canonicalize-word-downcase word-locase))
(let ((word-upcase (upcase word)))
;; Ignore all uppercase words.
(unless (equal word word-upcase)
(let ((bounds (spell-fu--maybe-explode-word-ex word word-locase word-upcase)))
(cond
;; Handle bounds.
(bounds
(pcase-dolist (`(,beg . ,end) bounds)
;; Dictionary search.
(let ((subword-locase (substring word-locase beg end)))
(unless (spell-fu--check-word-in-dict-list
(spell-fu--canonicalize-word-downcase subword-locase))
(let ((subword (substring word beg end))
(subword-upcase (substring word-upcase beg end)))
;; Ignore all uppercase words.
(unless (equal subword subword-upcase)
(spell-fu-mark-incorrect (+ pos-beg beg) (+ pos-beg end))))))))
(t
;; Mark as incorrect otherwise.
(spell-fu-mark-incorrect pos-beg pos-end)))))))))
(defun spell-fu--word-at-point ()
"Return the word at the current point or nil."
(declare (important-return-value t))
(let ((point-init (point))
(pos-beg (pos-bol))
(pos-end (pos-eol)))
(save-excursion
(goto-char pos-beg)
(catch 'result
(with-syntax-table spell-fu-syntax-table
(save-match-data
(while (re-search-forward spell-fu-word-regexp pos-end t)
(let* ((match-beg (match-beginning 0))
(match-end (match-end 0))
(word (buffer-substring-no-properties match-beg match-end)))
(when (and (<= match-beg point-init) (<= point-init match-end))
(let ((bounds
(or (spell-fu--maybe-explode-word word) (list (cons 0 (length word))))))
(pcase-dolist (`(,beg . ,end) bounds)
(when (and (<= (+ match-beg beg) point-init)
(<= point-init (+ match-beg end)))
(throw 'result (substring word beg end))))))))))
(throw 'result nil)))))
;; ---------------------------------------------------------------------------
;; Range Checking Commands
;;
;; These functions are value values for the `spell-fu-check-range' buffer local variable.
;;
;; Note that the callers of these function extends the range to line delimiters,
;; to ensure there no chance of the points being in the middle of a word.
;;
(defun spell-fu--check-faces-at-point (pos)
"Check if position POS has faces that match include/exclude."
(declare (important-return-value t))
(let ((result (null spell-fu-faces-include))
(faces-at-pos (spell-fu--faces-at-point pos)))
(while faces-at-pos
(let ((face (pop faces-at-pos)))
(when (memq face spell-fu-faces-exclude)
(setq faces-at-pos nil)
(setq result nil))
(when (and (null result) (memq face spell-fu-faces-include))
(setq result t))))
result))
(defun spell-fu--check-range-with-faces (pos-beg pos-end)
"Check spelling for POS-BEG & POS-END.
This only checks the text matching face rules."
(declare (important-return-value nil))
(spell-fu--overlays-remove pos-beg pos-end)
(with-syntax-table spell-fu-syntax-table
(save-match-data ; For regex search.
(save-excursion ; For moving the point.
(save-restriction ; For narrowing.
;; Avoid duplicate calls that check if `pos-beg' passes the face test.
(let ((ok-beg (spell-fu--check-faces-at-point pos-beg)))
;; It's possible the face changes part way through the word.
;; In practice this is likely caused by escape characters, e.g.
;; "test\nthe text" where "\n" may have separate highlighting.
(while (< pos-beg pos-end)
(let* ((point-end-iter ; Set to `ok-beg' next iteration to avoid duplicate checks.
(spell-fu--next-faces-prop-change pos-beg pos-end))
(ok-end-iter
(and (< point-end-iter pos-end)
(spell-fu--check-faces-at-point point-end-iter))))
;; No need to check faces of each word
;; as face-changes are being stepped over.
(when ok-beg
;; Extend `point-end-iter' out for as long as the face isn't being ignored,
;; needed when `whitespace-mode' sets a margin,
;; splitting words in this case isn't desirable, see: #16.
;;
;; This may also have some advantage
;; in reducing the number of narrowing calls.
;;
;; NOTE: this could be made into an option.
;; Currently there doesn't seem much need for this at the moment.
(while ok-end-iter
(setq point-end-iter (spell-fu--next-faces-prop-change point-end-iter pos-end))
(setq ok-end-iter
(and (< point-end-iter pos-end)
(spell-fu--check-faces-at-point point-end-iter))))
;; Use narrowing so the regex correctly handles boundaries
;; that happen to fall on face changes.
(narrow-to-region pos-beg point-end-iter)
(goto-char pos-beg)
(while (re-search-forward spell-fu-word-regexp point-end-iter t)
(let ((word-beg (match-beginning 0))
(word-end (match-end 0)))
(spell-fu-check-word
word-beg word-end (buffer-substring-no-properties word-beg word-end))))
(widen))
(setq pos-beg point-end-iter)
(setq ok-beg ok-end-iter)))))))))
(defun spell-fu--check-range-without-faces (pos-beg pos-end)
"Check spelling for POS-BEG & POS-END, checking all text."
(declare (important-return-value nil))
(spell-fu--overlays-remove pos-beg pos-end)
(with-syntax-table spell-fu-syntax-table
(save-match-data
(save-excursion
(goto-char pos-beg)
(while (re-search-forward spell-fu-word-regexp pos-end t)
(let ((word-beg (match-beginning 0))
(word-end (match-end 0)))
(spell-fu-check-word word-beg word-end (match-string-no-properties 0))))))))
(defun spell-fu-check-range-default (pos-beg pos-end)
"Check spelling POS-BEG & POS-END, checking comments and strings."
(declare (important-return-value nil))
(cond
((or spell-fu-faces-include spell-fu-faces-exclude)
(spell-fu--check-range-with-faces pos-beg pos-end))
(t
(spell-fu--check-range-without-faces pos-beg pos-end))))
;; ---------------------------------------------------------------------------
;; Immediate Style (spell-fu-idle-delay zero or lower)
(defun spell-fu--font-lock-fontify-region (pos-beg pos-end)
"Update spelling for POS-BEG & POS-END to the queue, checking all text."
(declare (important-return-value nil))
(spell-fu--setq-expand-range-to-line-boundaries
;; Warning these values are set in place.
pos-beg pos-end)
(funcall spell-fu-check-range pos-beg pos-end))
(defun spell-fu--immediate-enable ()
"Enable immediate spell checking."
(declare (important-return-value nil))
;; It's important this is added with a depth of 100,
;; because we want the font faces (comments, string etc) to be set so
;; the spell checker can read these values which may include/exclude words.
(spell-fu--with-add-hook-depth-override 100
(jit-lock-register #'spell-fu--font-lock-fontify-region)))
(defun spell-fu--immediate-disable ()
"Disable immediate spell checking."
(declare (important-return-value nil))
(jit-lock-unregister #'spell-fu--font-lock-fontify-region)
(spell-fu--overlays-remove))
;; ---------------------------------------------------------------------------
;; Timer Style (spell-fu-idle-delay over zero)
(defun spell-fu--idle-overlays-remove (&optional pos-beg pos-end)
"Remove `spell-fu-pending' overlays from current buffer.
If optional arguments POS-BEG and POS-END exist
remove overlays from range POS-BEG to POS-END
Otherwise remove all overlays."
(declare (important-return-value nil))
(remove-overlays pos-beg pos-end 'spell-fu-pending t))
(defun spell-fu--idle-handle-pending-ranges-impl (visible-beg visible-end)
"VISIBLE-BEG and VISIBLE-END typically from `window-start' and `window-end'.
Although you can pass in specific ranges as needed,
when checking the entire buffer for example."
(declare (important-return-value nil))
(let ((overlays-in-view (overlays-in visible-beg visible-end)))
(while overlays-in-view
(let ((item-ov (pop overlays-in-view)))
(when (and (overlay-get item-ov 'spell-fu-pending)
;; It's possible these become invalid while looping over items.
(overlay-buffer item-ov))
;; Window clamped range.
(let ((pos-beg (max visible-beg (overlay-start item-ov)))
(pos-end (min visible-end (overlay-end item-ov))))
;; Expand so we don't spell check half a word.
(spell-fu--setq-expand-range-to-line-boundaries
;; Warning these values are set in place.
pos-beg pos-end)
(when (condition-case err
;; Needed so the idle timer won't quit mid-spelling.
(let ((inhibit-quit nil))
(funcall spell-fu-check-range pos-beg pos-end)
t)
(error
(progn
;; Keep since this should be very rare.
(message "Early exit 'spell-fu-mode': %s" (error-message-string err))
;; Break out of the loop.
(setq overlays-in-view nil)
nil)))
;; Don't delete the overlay since it may extend outside the window bounds,
;; always delete the range instead.
;;
;; While we could remove everything in the window range,
;; avoid this because it's possible `spell-fu-check-range' is interrupted.
;; Allowing interrupting is important, so users may set this to a slower function
;; which doesn't lock up Emacs as this is run from an idle timer.
(spell-fu--idle-overlays-remove pos-beg pos-end))))))))
(defun spell-fu--idle-handle-pending-ranges ()
"Spell check the on-screen overlay ranges."
(declare (important-return-value nil))
(spell-fu--idle-handle-pending-ranges-impl (window-start) (window-end)))
(defun spell-fu--idle-font-lock-region-pending (pos-beg pos-end)
"Track the range to spell check, adding POS-BEG & POS-END to the queue."
(declare (important-return-value nil))
(when (and spell-fu--idle-overlay-last (not (overlay-buffer spell-fu--idle-overlay-last)))
(setq spell-fu--idle-overlay-last nil))
(unless (and spell-fu--idle-overlay-last
(let ((last-beg (overlay-start spell-fu--idle-overlay-last))
(last-end (overlay-end spell-fu--idle-overlay-last)))
(cond
((> last-beg pos-end)
nil)
((< last-end pos-beg)
nil)
(t ; Extend when overlap.
(move-overlay
spell-fu--idle-overlay-last (min pos-beg last-beg) (max pos-end last-end))
t))))
(let ((item-ov (make-overlay pos-beg pos-end)))
;; Handy for debugging pending regions to be checked.
;; (overlay-put item-ov 'face '(:background "#000000" :extend t))
(overlay-put item-ov 'spell-fu-pending t)
(overlay-put item-ov 'evaporate 't)
(setq spell-fu--idle-overlay-last item-ov)))
;; Use `inhibit-quit' as a way to check if `jit-lock-stealth' is in use.
(when inhibit-quit
(spell-fu--idle-handle-pending-ranges-impl pos-beg pos-end)))
;; ---------------------------------------------------------------------------
;; Internal Timer Management
;;
;; This works as follows:
;;
;; - The timer is kept active as long as the local mode is enabled.
;; - Entering a buffer runs the buffer local `window-state-change-hook'
;; immediately which checks if the mode is enabled,
;; set up the global timer if it is.
;; - Switching any other buffer wont run this hook,
;; rely on the idle timer it's self running, which detects the active mode,
;; canceling it's self if the mode isn't active.
;;
;; This is a reliable way of using a global,
;; repeating idle timer that is effectively buffer local.
;;
;; Global idle timer (repeating), keep active while the buffer-local mode is enabled.
(defvar spell-fu--global-timer nil)
;; When t, the timer will update buffers in all other visible windows.
(defvar spell-fu--dirty-flush-all nil)
;; When true, the buffer should be updated when inactive.
(defvar-local spell-fu--dirty nil)
(defun spell-fu--time-callback-or-disable ()
"Callback that run the repeat timer."
(declare (important-return-value nil))
;; Ensure all other buffers are highlighted on request.
(let ((is-mode-active (bound-and-true-p spell-fu-mode)))
;; When this buffer is not in the mode, flush all other buffers.
(cond
(is-mode-active
;; Don't update in the window loop to ensure we always
;; update the current buffer in the current context.
(setq spell-fu--dirty nil))
(t
;; If the timer ran when in another buffer,
;; a previous buffer may need a final refresh, ensure this happens.
(setq spell-fu--dirty-flush-all t)))