1 ;;; wcheck-mode.el --- General interface for text checkers
3 ;; Copyright (C) 2009-2014 Free Software Foundation, Inc.
5 ;; Author: Teemu Likonen <tlikonen@iki.fi>
6 ;; Maintainer: Teemu Likonen <tlikonen@iki.fi>
8 ;; URL: https://github.com/tlikonen/wcheck-mode
9 ;; Keywords: text spell check languages ispell
12 ;; This program is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or (at
15 ;; your option) any later version.
17 ;; This program is distributed in the hope that it will be useful, but
18 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 ;; General Public License for more details.
22 ;; The license text: <http://www.gnu.org/licenses/gpl-3.0.html>
27 ;; Put this file to some directory in your Emacs's "load-path" and add
28 ;; the following lines to Emacs's initialization file (~/.emacs):
30 ;; (autoload 'wcheck-mode "wcheck-mode"
31 ;; "Toggle wcheck-mode." t)
32 ;; (autoload 'wcheck-change-language "wcheck-mode"
33 ;; "Switch wcheck-mode languages." t)
34 ;; (autoload 'wcheck-actions "wcheck-mode"
35 ;; "Open actions menu." t)
36 ;; (autoload 'wcheck-jump-forward "wcheck-mode"
37 ;; "Move point forward to next marked text area." t)
38 ;; (autoload 'wcheck-jump-backward "wcheck-mode"
39 ;; "Move point backward to previous marked text area." t)
41 ;; See customize group "wcheck" for information on how to configure
42 ;; Wcheck mode. (M-x customize-group RET wcheck RET)
47 ;; A general interface for text checkers
49 ;; Wcheck mode is a general-purpose text-checker interface for Emacs
50 ;; text editor. Wcheck mode a minor mode which provides an on-the-fly
51 ;; text checker. It checks the visible text area, as you type, and
52 ;; possibly highlights some parts of it. What is checked and how are all
55 ;; Wcheck mode can use external programs or Emacs Lisp functions for
56 ;; checking text. For example, Wcheck mode can be used with
57 ;; spell-checker programs such as Ispell, Enchant and Hunspell, but
58 ;; actually any tool that can receive text from standard input stream
59 ;; and send text to standard output can be used. Wcheck mode sends parts
60 ;; of buffer's content to an external program or an Emacs Lisp function
61 ;; and, based on their output, decides if some parts of text should be
62 ;; marked in the buffer.
69 (declare-function show-entry "outline"))
77 "General interface for text checkers."
81 (defconst wcheck--language-data-customize-interface
83 :format "%[Option%] %v"
85 (cons :tag "Program" :format "%v"
86 (const :tag "Program" :format "%t: " program)
87 (choice :format "%[Type%] %v"
88 (file :tag "Filename" :format "\n\t\t%t: %v")
89 (function :tag "Function" :format "\n\t\t%t: %v")))
91 (cons :tag "Arguments" :format "%v"
92 (const :format "" args)
93 (repeat :tag "Arguments"
94 (string :format "%v")))
96 (cons :tag "Output parser function" :format "%v"
97 (const :tag "Output parser" :format "%t: " parser)
98 (choice :format "%[Parser%] %v" :value nil
99 (const :tag "Lines" wcheck-parser-lines)
100 (const :tag "Whitespace" wcheck-parser-whitespace)
101 (function :tag "Custom function"
102 :format "%t:\n\t\t%v")))
104 (cons :tag "Connection type" :format "%v"
105 (const :tag "Connection: " :format "%t" connection)
106 (choice :format "%[Type%] %v" :value nil
107 (const :tag "pipe (nil)" nil)
108 (const :tag "pty" :match (lambda (widget value)
113 (cons :tag "Face" :format "%v"
114 (const :tag "Face" :format "%t: " face)
115 (symbol :format "%v"))
117 (cons :tag "Syntax table" :format "%v"
118 (const :tag "Syntax table" :format "%t: " syntax)
119 (variable :format "%v"))
121 (cons :tag "Regexp start" :format "%v"
122 (const :tag "Regexp start" :format "%t: " regexp-start)
123 (regexp :format "%v"))
125 (cons :tag "Regexp body" :format "%v"
126 (const :tag "Regexp body" :format "%t: " regexp-body)
127 (regexp :format "%v"))
129 (cons :tag "Regexp end" :format "%v"
130 (const :tag "Regexp end" :format "%t: " regexp-end)
131 (regexp :format "%v"))
133 (cons :tag "Regexp discard" :format "%v"
134 (const :tag "Regexp discard" :format "%t: " regexp-discard)
135 (regexp :format "%v"))
137 (cons :tag "Regexp case" :format "%v"
138 (const :tag "Regexp" :format "%t: " case-fold)
139 (choice :format "%[Case%] %v" :value nil
140 :match (lambda (widget value) t)
141 :value-to-internal (lambda (widget value)
143 (const :tag "sensitive" nil)
144 (const :tag "insensitive" t)))
147 :tag "Read or skip faces" :format "%v"
148 (const :tag "Read or skip faces" :format "%t" read-or-skip-faces)
153 (choice :format "%[Major mode%] %v"
154 (const :tag "All major modes"
155 :match (lambda (widget value) (null value))
158 :tag "Select major modes"
159 :match (lambda (widget value)
160 (or (symbolp value) (consp value)))
161 :value-to-internal (lambda (widget value)
165 :value-to-external (lambda (widget value)
166 (if (and (consp value)
167 (symbolp (car value))
171 (symbol :format "%v")))
173 (choice :format "%[Operation mode%] %v"
174 (const :tag "Read everything" nil)
175 (cons :tag "Read selected faces" :format "%v"
176 (const :tag "Read selected faces"
178 (repeat :tag "" (sexp :format "%v")))
179 (cons :tag "Skip selected faces" :format "%v"
180 (const :tag "Skip selected faces"
182 (repeat :tag "" (sexp :format "%v")))))))
184 (cons :tag "Action program" :format "%v"
185 (const :tag "Action program" :format "%t: " action-program)
186 (choice :format "%[Type%] %v"
187 (file :tag "Filename" :format "\n\t\t%t: %v")
188 (function :tag "Function" :format "\n\t\t%t: %v")))
190 (cons :tag "Action program's arguments" :format "%v"
191 (const :format "" action-args)
192 (repeat :tag "Action program's arguments"
193 (string :format "%v")))
195 (cons :tag "Action parser function" :format "%v"
196 (const :tag "Action parser" :format "%t: "
198 (choice :format "%[Parser%] %v" :value nil
199 (const :tag "Ispell" wcheck-parser-ispell-suggestions)
200 (const :tag "Lines" wcheck-parser-lines)
201 (const :tag "Whitespace" wcheck-parser-whitespace)
202 (function :tag "Custom function"
203 :format "%t:\n\t\t%v")))
205 (cons :tag "Action autoselect mode" :format "%v"
206 (const :tag "Action autoselect" :format "%t: " action-autoselect)
207 (choice :format "%[Mode%] %v" :value nil
208 :match (lambda (widget value) t)
209 :value-to-internal (lambda (widget value)
211 (const :tag "off" nil)
212 (const :tag "on" t)))))
216 (defcustom wcheck-language-data
217 ;; FIXME: Auto-fill by looking at installed spell-checkers and dictionaries!
219 "Language configuration for `wcheck-mode'.
221 The variable is an association list (alist) and its elements are
224 (LANGUAGE (KEY . VALUE) [(KEY . VALUE) ...])
226 LANGUAGE is a name string for this particular configuration unit
227 and KEY and VALUE pairs denote settings for the language.
229 Below is the documentation of possible KEYs and corresponding
230 VALUEs. The documentation is divided in two parts: checker
231 options and action options. The first part describes all options
232 related to checking the content of an Emacs buffer (and possibly
233 marking some of it). The second part describes options which
234 configure actions which user can choose for a marked text on
237 NOTE: There is also variable `wcheck-language-data-defaults'
238 which is used to define default values. The defaults are used
239 when a language-specific option in `wcheck-language-data' does
240 not exist or is not valid.
246 The checker options configure LANGUAGE's text-checking and
247 text-marking features. With these you can configure how buffer's
248 content is examined, what checker engine is used and how text is
249 marked in the buffer.
253 `program' is either the name (a string) of an external
254 executable program or an Emacs Lisp function (a symbol or a
255 lambda expression). They are used as the checker engine for
256 the LANGUAGE. When `program' names an external executable
257 program then `args' are the command-line arguments (a list of
258 strings) for the program.
260 `wcheck-mode' collects text strings from the buffer and sends
261 them to `program' to analyze. When `program' is an external
262 executable program the collected strings are sent (each on a
263 separate line) through the standard input stream to the
264 program. The program must write to standard output stream all
265 the strings which it thinks should be marked in the Emacs
266 buffer. The output of the program is then parsed with
267 `parser' function (see below).
269 When `program' is an Emacs Lisp function (a symbol or a
270 lambda expression) the function is called with one argument:
271 a list of strings collected from the buffer. The function is
272 supposed to check them and return a list of strings (or nil).
273 The returned strings will be marked in the buffer.
275 See options `regexp-start', `regexp-body' and `regexp-end'
276 below for details on how text is collected from the buffer.
279 VALUE of this option is an Emacs Lisp function which is
280 responsible for parsing the output of `program'. This parser
281 function is only used when `program' is an external
282 executable program (not a function).
284 The parser function is run without arguments and within the
285 context of a buffer that contains all the output from the
286 external program. The point is located at the beginning of
287 the buffer. From that buffer the `parser' function should
288 collect all the strings that are meant to be marked in the
289 buffer that is being checked. The function must return them
290 as a list of strings or nil if there are none to be marked.
292 For the most common cases there are two parser functions
295 `wcheck-parser-lines' turns each line in program's output
296 to a separate string. You should use this function as the
297 output parser if you spell-check with Ispell-like program
298 with its \"-l\" command-line option. They output each
299 misspelled word on a separate line. This is the default
302 `wcheck-parser-whitespace' turns each whitespace-
303 separated token in the output to a separate string.
306 The VALUE is used to set variable `process-connection-type'
307 when starting the process for LANGUAGE. If the VALUE is nil
308 use a pipe for communication; if it's `pty' (or t) use a PTY.
309 The default is to use a pipe (nil). (This option is ignored
310 when the program is a function.)
313 A symbol referring to the face which is used to mark text with
314 this LANGUAGE. The default is `wcheck-default-face'.
317 VALUE is a variable (a symbol) referring to an Emacs syntax
318 table. This option temporarily sets the effective syntax
319 table when buffer's content is scanned with `regexp-start',
320 `regexp-body', `regexp-end' and `regexp-discard' (see below)
321 as well as when `program', `parser', `action-program' and
322 `action-parser' functions are called. The default value is
323 `text-mode-syntax-table'. This option does not affect syntax
324 table settings anywhere else. See the Info node
325 `(elisp)Syntax Tables' for more information on the topic.
330 Regular expression strings which match the start of a string
331 body, characters within the body and the end of the body,
334 This is how they are used in practice: `wcheck-mode' scans
335 buffer's content and looks for strings that match the
336 following regular expression
338 REGEXP-START\\(REGEXP-BODY\\)REGEXP-END
340 The regular expression back reference \\1 is used to extract
341 `regexp-body' part from the matched string. That string is
342 then matched against `regexp-discard' (see below) and if it
343 doesn't match the string is sent to the text checker program
344 or function to analyze.
346 Strings returned from the program or function are quoted for
347 regular expression special characters (with `regexp-quote'
348 function) and marked in Emacs buffer using the following
349 construction: `regexp-start + STRING + regexp-end'. The
350 STRING part is marked with `face' (see above).
352 You can't use grouping constructs `\\( ... \\)' in
353 `regexp-start' because the back reference `\\1' is used for
354 separating the `regexp-body' match string from the
355 `regexp-start' and `regexp-end' match strings. You can use
356 \"shy\" groups `\\(?: ... \\)' which do not record the
357 matched substring. Grouping constructs `\\( ... \\)' are
358 allowed in `regexp-body' and `regexp-end'. Just note that the
359 first group and back reference \\1 is already taken.
361 The default values for the regular expressions are
363 \\=\\<'* (regexp-start)
365 '*\\=\\> (regexp-end)
367 Effectively they match a series of word characters defined in
368 the effective syntax table. Single quotes (') at the start
369 and end of a word are excluded. This is probably a good thing
370 when using `wcheck-mode' as a spelling checker.
373 The string that matched `regexp-body' is then matched against
374 the value of this option. If this regular expression matches,
375 then the string is discarded and won't be sent to the
376 text-checker program or function to analyze. You can use this
377 to define exceptions to the `regexp-body' match. The default
382 which discards the body string if it consists only of single
383 quotes. This was chosen as the default because the default
384 syntax table `text-mode-syntax-table' defines single quote as
385 a word character. It's probably not useful to mark individual
386 single quotes in a buffer when `wcheck-mode' is used as a
389 If you don't want to have any discarding rules set this
390 option to empty string (\"\").
393 This boolean value is used to temporarily bind the value of
394 variable `case-fold-search'. The nil value means
395 case-sensitive and a non-nil means case-insensitive search.
396 The default is case-sensitive (nil). This option is effective
397 with `regexp-start', `regexp-body', `regexp-end' and
398 `regexp-discard' as well as when `program', `parser',
399 `action-program' and `action-parser' functions are called.
402 This option controls which faces `wcheck-mode' should read or
403 skip when scanning buffer's content. The value must be a list
404 and its items are also lists:
406 (MAJOR-MODE [OPERATION-MODE [FACE ...]])
408 MAJOR-MODE is a symbol or a list of symbols. Symbols refer to
409 the major mode(s) which the settings are for. Use nil as the
410 MAJOR-MODE to define default settings. Settings that come
411 after the pseudo major-mode nil are ignored.
413 OPERATION-MODE is symbol `read' or `skip' defining whether
414 the FACEs should be read or skipped. If it's `read' then only
415 the listed faces are read. If it's `skip' then the listed
416 faces are skipped and all other faces are read. If there is
417 no OPERATION-MODE at all (i.e., the list has just one
418 element, MAJOR-MODE) then everything is read.
420 The rest of the items are FACEs. They are typically symbols
421 but some Emacs modes may use strings, property lists or cons
422 cells for defining faces. For more information see Info
423 node `(elisp) Special Properties'. Use nil as the face to
424 refer to the normal text which does not have a face text
430 ((emacs-lisp-mode c-mode) read
431 font-lock-comment-face font-lock-doc-face)
432 (org-mode skip font-lock-comment-face org-link)
436 It says that in `emacs-lisp-mode' and `c-mode' only the text
437 which have been highlighted with `font-lock-comment-face' or
438 `font-lock-doc-face' is read (i.e., checked). In `org-mode'
439 faces `font-lock-comment-face' and `org-link' are
440 skipped (i.e., not checked) and all other faces are read. In
441 `text-mode' everything is read. Finally, in all other major
442 modes only the normal text (nil) is read.
444 Most likely not all `read-or-skip-faces' settings are
445 specific to a certain language so it could be more useful to
446 put them in variable `wcheck-language-data-defaults' instead.
447 That way they are used with all languages. Normally the
448 global default is equivalent to
453 which means that in all major modes read everything. It is
454 sometimes useful to have this setting in language-specific
455 options because the parsing stops right there. Therefore it
456 overrides all global settings which user may have changed
457 with variable `wcheck-language-data-defaults'.
459 Note: You can use command `\\[what-cursor-position]' with a
460 prefix argument to see what faces are active at the cursor
461 position. Then you can use the information to configure this
468 \"Actions\" are any kind of operations that can be executed for
469 marked text in an Emacs buffer. Actions are presented to user
470 through a menu which is activated either by (1) clicking the
471 right mouse button on a marked text or (2) executing interactive
472 command `wcheck-actions' while the cursor (the point) is on a
475 If you use `wcheck-mode' as a spelling checker then it's natural
476 to configure an action menu that offers spelling suggestions for
477 the misspelled word. The action menu could also have an option to
478 add the word to spell-checker's dictionary, so that the word is
479 recognized next time.
483 `action-program' is either the name (a string) of an external
484 executable program or an Emacs Lisp function (a symbol or a
485 lambda expression). When it's the name of an executable
486 program then `action-args' are the command-line arguments (a
487 list of strings) for the program.
489 When `action-program' is an external executable program the
490 marked text is sent to the program through the standard input
491 stream. The program should send its feedback data (usually
492 suggested substitute strings) to the standard output stream.
493 The output is parsed with `action-parser' function (see
494 below) and function's return value is used to construct an
495 action menu for user. The format and effect of
496 `action-parser' function's return value is described below.
498 When `action-program' is an Emacs Lisp function the function
499 is called with one argument: a vector returned by
500 `wcheck-marked-text-at' function. The `action-program'
501 function is supposed to gather some substitute suggestion
502 strings or give other actions for the marked text in the
503 buffer. Function's return value is used to construct an
504 action menu for user. The format and effect of
505 `action-program' function's return value is described below.
508 VALUE of this option is an Emacs Lisp function which is
509 responsible for parsing the output of `action-program'. This
510 parser function is only used when `action-program' is an
511 external executable program (not a function).
513 The parser function is run with one argument: a vector
514 returned by `wcheck-marked-text-at' for the marked text in
515 question. The parser function is called within the context of
516 a buffer that contains all the output from `action-program'.
517 The point is located at the beginning of the buffer.
519 The `action-parser' function should examine the buffer for
520 interesting information (such as spelling suggestions) and
521 return them in the format that is described below.
523 For the most common cases there are three parser functions
526 `wcheck-parser-ispell-suggestions' parses substitute
527 suggestions from the output of Ispell or compatible
528 program, such as Enchant. Use this function as the
529 `action-parser' if you get spelling suggestions from an
530 Ispell-like program with its \"-a\" command-line option.
532 `wcheck-parser-lines' function turns each line in the
533 output to individual substitute suggestions.
535 `wcheck-parser-whitespace'. Each whitespace-separated
536 token in the program's output is a separate suggestion.
539 If this option is non-nil and the action menu has only one
540 menu item then the item is chosen automatically without
541 actually showing the menu. If this option is nil (which is
542 the default) then the menu is always shown.
545 The return value of `action-program' function and `action-parser'
546 function must be a list. The empty list (nil) means that there
547 are no actions available for the marked text. Otherwise each
548 elements in the list must be either a string or a cons cell. If
549 an element is a string it is an individual substitute suggestion
550 string for the original marked text. The same string is shown in
551 the actions menu. When user chooses such option from the action
552 menu the original text is substituted in the Emacs buffer.
554 If an element is a cons cell it must be one of
556 (\"Menu item\" . \"substitute string\")
557 (\"Menu item\" . some-function)
559 The \"car\" value of the cons cell must be a string. The string
560 is shown in the action menu as one of the options. The \"cdr\"
561 value of the cons cell defines the action that is taken for the
562 menu option. If the \"cdr\" value is a string then that string is
563 the substitute string. If the \"cdr\" value is a function (a
564 symbol or a lambda expression) then that function is called when
565 user chooses the menu option. The function is called with one
566 argument: a vector returned by `wcheck-marked-text-at' function
567 for the marked text in question.
569 Effectively `action-program' function or `action-program'
570 executable program with `action-parser' function provide a
571 feature that can offer spelling suggestions for user: just return
572 suggestions as a list of strings. Alternatively they can offer
573 any kind of useful actions by calling custom functions. There are
574 a lot of possibilities.
577 For configuration examples, see the README file in URL
578 `https://github.com/tlikonen/wcheck-mode'."
584 (string :tag "Language")
587 ,wcheck--language-data-customize-interface))))
591 (defconst wcheck--language-data-defaults-hard-coded
592 '((parser . wcheck-parser-lines)
594 (face . wcheck-default-face)
595 (syntax . text-mode-syntax-table)
596 (regexp-start . "\\<'*")
597 (regexp-body . "\\w+?")
598 (regexp-end . "'*\\>")
599 (regexp-discard . "\\`'+\\'")
601 (read-or-skip-faces (nil))
602 (action-autoselect . nil))
603 "Hard-coded default language configuration for `wcheck-mode'.
604 This constant is for Wcheck mode's internal use only. This
605 provides useful defaults if both `wcheck-language-data' and
606 `wcheck-language-data-defaults' fail.")
610 (defcustom wcheck-language-data-defaults
611 wcheck--language-data-defaults-hard-coded
612 "Default language configuration for `wcheck-mode'.
613 These default values are used when language-specific settings
614 don't provide a valid value. `wcheck-mode' will choose some
615 useful defaults even if this variable is not (properly) set. See
616 variable `wcheck-language-data' for information about possible
619 Here's an example value for the variable:
621 ((parser . wcheck-parser-lines)
622 (action-parser . wcheck-parser-ispell-suggestions)
624 (face . wcheck-default-face)
625 (syntax . text-mode-syntax-table)
626 (regexp-start . \"\\\\=\\<'*\")
627 (regexp-body . \"\\\\w+?\")
628 (regexp-end . \"'*\\\\=\\>\")
629 (regexp-discard . \"\\\\`'+\\\\'\")
632 ((emacs-lisp-mode c-mode) read
633 font-lock-comment-face font-lock-doc-face)
634 (message-mode read nil
635 message-header-subject message-cited-text)))"
638 :type `(repeat ,wcheck--language-data-customize-interface))
642 (defcustom wcheck-language ""
643 "Default language for `wcheck-mode'.
645 Normally the global value defines the language for new buffers.
646 If a buffer-local value exists it is used instead. This variable
647 becomes automatically buffer-local when `wcheck-mode' is turned
648 on in a buffer, so changing the global value does not affect
649 buffers which already have `wcheck-mode' turned on.
651 User is free to set this variable directly (e.g., in programs)
652 but in interactive use it is usually better to use the command
653 `\\[wcheck-change-language]' instead. The command can change
654 language immediately while `wcheck-mode' is turned on, whereas
655 changing just the value of this variable takes effect only when
656 `wcheck-mode' is turned on next time."
657 :type '(string :tag "Default language")
659 (make-variable-buffer-local 'wcheck-language)
663 (defface wcheck-default-face
664 '((t (:underline "red")))
665 "Default face for marking strings in a buffer.
666 This is used when language does not define a face."
673 (defvar wcheck-mode nil)
674 (defvar wcheck-mode-map (make-sparse-keymap)
675 "Keymap for `wcheck-mode'.")
677 (defvar wcheck--timer nil)
678 (defvar wcheck--timer-idle .3
679 "`wcheck-mode' idle timer delay (in seconds).")
680 (defvar wcheck--timer-paint-event-count 0)
682 (defvar wcheck--timer-paint-event-count-std 3
683 "Run buffer paint event this many times in a row.
684 With too low values all data from external processes may not have
685 arrived and window gets only partially painted. A higher value
686 increases the probability that windows get fully painted but it
687 also makes `wcheck-jump-forward' and `wcheck-jump-backward'
688 slower. A suitable compromise may be 3 or 4.")
690 (defvar wcheck--change-language-history nil
691 "Language history for command `wcheck-change-language'.")
693 (defvar wcheck--buffer-data nil)
695 (defvar wcheck--jump-step 5000)
701 (defmacro wcheck--define-condition (name superclass &optional message)
702 (declare (indent defun))
704 (put ',name 'error-conditions
705 (append (get ',superclass 'error-conditions) (list ',name)))
706 (put ',name 'error-message ,message)
710 (defmacro wcheck--loop-over-reqs-engine (key var &rest body)
711 `(dolist (,var (delq nil (mapcar (lambda (buffer)
712 (when (wcheck--buffer-data-get
715 (wcheck--buffer-data-get-all :buffer))))
716 (when (buffer-live-p ,var)
717 (with-current-buffer ,var
721 (defmacro wcheck--loop-over-read-reqs (var &rest body)
723 `(wcheck--loop-over-reqs-engine :read-req ,var ,@body))
724 (defmacro wcheck--loop-over-paint-reqs (var &rest body)
726 `(wcheck--loop-over-reqs-engine :paint-req ,var ,@body))
727 (defmacro wcheck--loop-over-jump-reqs (var &rest body)
729 `(wcheck--loop-over-reqs-engine :jump-req ,var ,@body))
732 (defmacro wcheck--with-language-data (var-lang bindings &rest body)
734 (let ((language (make-symbol "--wck-language--")))
735 `(let* ((,language ,(cadr var-lang))
736 ,@(when (car var-lang)
737 `((,(car var-lang) ,language)))
741 (list var `(wcheck-query-language-data
743 ((and var (listp var))
744 (list (car var) `(wcheck-query-language-data
745 ,language ',(cadr var))))))
753 (wcheck--define-condition wcheck--error error)
754 (wcheck--define-condition wcheck--language-does-not-exist-error wcheck--error)
755 (wcheck--define-condition wcheck--program-not-configured-error wcheck--error)
756 (wcheck--define-condition wcheck--not-a-list-of-strings-error wcheck--error)
757 (wcheck--define-condition wcheck--funcall-error wcheck--error)
758 (wcheck--define-condition wcheck--action-error wcheck--error)
759 (wcheck--define-condition wcheck--action-program-error wcheck--action-error)
760 (wcheck--define-condition wcheck--parser-function-not-configured-error
761 wcheck--action-error)
762 (wcheck--define-condition wcheck--overlay-not-found-error wcheck--error)
765 ;;; Interactive commands
769 (defun wcheck-change-language (language &optional global)
770 "Change language for current buffer (or globally).
771 Change `wcheck-mode' language to LANGUAGE. The change is
772 buffer-local but if GLOBAL is non-nil (prefix argument if called
773 interactively) then change the global default language."
775 (let* ((comp (mapcar #'car wcheck-language-data))
776 (default (cond ((and current-prefix-arg
777 (member (default-value 'wcheck-language) comp))
778 (default-value 'wcheck-language))
779 ((member wcheck-language comp)
783 (list (completing-read
784 (format (if current-prefix-arg
785 "Global default language (%s): "
786 "Language for the current buffer (%s): ")
788 comp nil t nil 'wcheck--change-language-history default)
789 current-prefix-arg)))
791 (condition-case error-data
792 (when (stringp language)
793 ;; Change the language, locally or globally, and update buffer
794 ;; database, if needed.
796 ;; Just change the global value and leave.
797 (setq-default wcheck-language language)
799 ;; Change the buffer-local value.
800 (setq wcheck-language language)
801 ;; If the mode is currently turned on check if language's
802 ;; checker program or function is configured and if all is OK
803 ;; request update for the buffer.
805 (if (wcheck--program-configured-p wcheck-language)
806 ;; It's OK; update the buffer.
808 (wcheck--buffer-lang-proc-data-update
809 (current-buffer) wcheck-language)
810 (wcheck--buffer-data-set (current-buffer) :read-req t)
811 (wcheck--remove-overlays))
813 (signal 'wcheck--program-not-configured-error wcheck-language))))
815 ;; Return the language.
818 (wcheck--program-not-configured-error
820 (message "Language \"%s\": checker program is not configured"
824 (defun wcheck--mode-turn-on ()
825 ;; Turn the mode on, but first some checks.
826 (let ((buffer (current-buffer))
827 (language wcheck-language))
828 (condition-case error-data
830 ((minibufferp buffer)
831 (signal 'wcheck--error "Can't use `wcheck-mode' in a minibuffer"))
833 ((not (wcheck--language-exists-p language))
834 (signal 'wcheck--language-does-not-exist-error language))
836 ((not (wcheck--program-configured-p language))
837 (signal 'wcheck--program-not-configured-error language))
840 (make-local-variable 'wcheck-language)
841 (wcheck--add-local-hooks buffer)
842 (wcheck--add-global-hooks)
843 (wcheck--buffer-lang-proc-data-update buffer language)
844 (wcheck--timer-start)
845 (wcheck--buffer-data-set buffer :read-req t)))
847 (wcheck--program-not-configured-error
849 (message "Language \"%s\": checker program not configured"
852 (wcheck--language-does-not-exist-error
854 (message "Language \"%s\" does not exist" (cdr error-data))))))
857 (defun wcheck--mode-turn-off ()
858 (let ((buffer (current-buffer)))
859 ;; We clear overlays form the buffer, remove the buffer from buffer
861 (wcheck--remove-overlays)
862 (wcheck--buffer-lang-proc-data-update buffer nil)
864 ;; If there are no buffers using wcheck-mode anymore, stop the idle
865 ;; timer and remove global hooks.
866 (when (null (wcheck--buffer-data-get-all :buffer))
868 (wcheck--remove-global-hooks))
869 (wcheck--remove-local-hooks buffer)))
872 (defun wcheck--mode-line-lang ()
877 (when (char-equal ?w (char-syntax c))
879 (when (>= (length lang-code) 2)
881 (wcheck--buffer-data-get :buffer (current-buffer) :language)))
882 (apply #'string (nreverse lang-code)))
887 (define-minor-mode wcheck-mode
888 "General interface for text checkers.
890 With optional (prefix) ARG turn on the mode if ARG is positive,
891 otherwise turn it off. If ARG is not given toggle the mode.
893 Wcheck is a minor mode for automatically checking and marking
894 strings in Emacs buffer. Wcheck sends (parts of) buffer's content
895 to a text-checker back-end and, based on its output, decides if
896 some parts of text should be marked.
898 Wcheck can be used with external spell-checker programs such as
899 Ispell and Enchant, but actually any tool that can receive text
900 stream from standard input and send text to standard output can
901 be used. The checker back-end can also be an Emacs Lisp function.
903 Different configuration units are called \"languages\". See the
904 documentation of variables `wcheck-language-data',
905 `wcheck-language-data-defaults' and `wcheck-language' for
906 information on how to configure Wcheck mode. You can access and
907 configure the variables through customize group `wcheck'.
909 Interactive command `wcheck-change-language' is used to switch
910 languages. Command `wcheck-actions' gives an action menu for the
911 marked text at point (also accessible through the right-click
912 mouse menu). Commands `wcheck-jump-forward' and
913 `wcheck-jump-backward' move point to next/previous marked text
916 A note for Emacs Lisp programmers: Emacs Lisp function
917 `wcheck-marked-text-at' returns information about marked text at
918 a buffer position. Function `wcheck-query-language-data' can be
919 used for querying effective configuration data for any language."
922 :lighter (" W:" (:eval (wcheck--mode-line-lang)))
923 :keymap wcheck-mode-map
925 (condition-case error-data
927 (wcheck--mode-turn-on)
928 (wcheck--mode-turn-off))
932 (message "%s" (cdr error-data)))))
938 (defun wcheck--timer-start ()
939 "Start `wcheck-mode' idle timer if it's not running already."
940 (unless wcheck--timer
942 (run-with-idle-timer wcheck--timer-idle t
943 #'wcheck--timer-read-event))))
946 (defun wcheck--timer-stop ()
947 "Stop `wcheck-mode' idle timer."
949 (cancel-timer wcheck--timer)
950 (setq wcheck--timer nil)))
953 (defun wcheck--funcall-after-idle (function &rest args)
954 (apply #'run-with-idle-timer
955 (+ wcheck--timer-idle (wcheck--current-idle-time-seconds))
959 (defun wcheck--timer-paint-event-run (&optional count)
961 (let ((at-least (max count wcheck--timer-paint-event-count)))
962 (if (> wcheck--timer-paint-event-count 0)
963 (setq wcheck--timer-paint-event-count at-least)
964 (setq wcheck--timer-paint-event-count at-least)
965 (wcheck--funcall-after-idle #'wcheck--timer-paint-event)))
966 (if (> (setq wcheck--timer-paint-event-count
967 (1- wcheck--timer-paint-event-count))
969 (wcheck--funcall-after-idle #'wcheck--timer-paint-event)
970 (wcheck--timer-jump-event))))
973 (defun wcheck--force-read (buffer)
975 (wcheck--buffer-data-set buffer :read-req t)
976 (wcheck--timer-read-event))
979 (defun wcheck--timer-read-event ()
980 "Send windows' content to checker program or function.
982 This function is usually called by the `wcheck-mode' idle timer.
983 The function walks through all windows which belong to buffers
984 that have requested update. It reads windows' content and sends
985 it checker program or function associated with the buffer's
986 language. Finally, this function starts another idle timer for
987 marking strings in buffers."
989 (wcheck--loop-over-read-reqs buffer
990 (unless (wcheck--buffer-data-get :buffer buffer :jump-req)
991 ;; We are about to fulfill buffer's window-reading request so
992 ;; remove the request. Reset also the list of received strings and
993 ;; visible window areas.
994 (wcheck--buffer-data-set buffer :read-req nil)
995 (wcheck--buffer-data-set buffer :strings nil)
996 (wcheck--buffer-data-set buffer :areas nil)
998 ;; Walk through all windows which belong to this buffer.
999 (let (area-alist strings)
1000 (walk-windows (lambda (window)
1001 (when (eq buffer (window-buffer window))
1002 ;; Store the visible buffer area.
1003 (push (cons (window-start window)
1004 (window-end window t))
1008 ;; Combine overlapping buffer areas and read strings from all
1010 (let ((combined (wcheck--combine-overlapping-areas area-alist)))
1011 (wcheck--buffer-data-set buffer :areas combined)
1012 (dolist (area combined)
1013 (setq strings (append (wcheck--read-strings
1014 buffer (car area) (cdr area))
1016 ;; Send strings to checker engine.
1017 (wcheck--send-strings buffer strings))))
1019 ;; Start a timer which will mark text in buffers/windows.
1020 (wcheck--timer-paint-event-run wcheck--timer-paint-event-count-std))
1023 (defun wcheck--send-strings (buffer strings)
1024 "Send STRINGS for the process that handles BUFFER.
1025 STRINGS is a list of strings to be sent as input for the external
1026 process which handles BUFFER. Each string in STRINGS is sent as
1028 (wcheck--with-language-data
1029 (nil (wcheck--buffer-data-get :buffer buffer :language))
1030 (program syntax (case-fold-search case-fold))
1033 (cond ((or (wcheck--buffer-data-get :buffer buffer :process)
1035 (process-send-string
1036 (wcheck--start-get-process buffer)
1037 (concat (mapconcat #'identity strings "\n") "\n"))
1039 (with-current-buffer
1040 (process-buffer (wcheck--buffer-data-get
1041 :buffer buffer :process))
1045 ((functionp program)
1046 (when (buffer-live-p buffer)
1047 (with-current-buffer buffer
1051 (with-syntax-table (eval syntax)
1052 (funcall program strings))
1053 (error (signal 'wcheck--funcall-error nil))))))
1054 (if (wcheck--list-of-strings-p received)
1056 (wcheck--buffer-data-set buffer :strings received)
1057 (wcheck--buffer-data-set buffer :paint-req t))
1058 (signal 'wcheck--not-a-list-of-strings-error nil)))))))
1060 (wcheck--not-a-list-of-strings-error
1061 (with-current-buffer buffer
1063 (message (concat "Checker function did not return a list of "
1064 "strings (or nil)"))))
1066 (wcheck--funcall-error
1067 (message "Checker function signaled an error")))))
1070 (defun wcheck--receive-strings (process string)
1071 "`wcheck-mode' process output handler function."
1072 (let ((buffer (wcheck--buffer-data-get :process process :buffer)))
1073 (wcheck--with-language-data
1074 (nil (wcheck--buffer-data-get :process process :language))
1075 (parser syntax (case-fold-search case-fold))
1076 (when (buffer-live-p buffer)
1077 (with-current-buffer buffer
1079 ;; If process is running proceed to collect and paint the
1081 (condition-case error-data
1082 (if (wcheck--process-running-p process)
1083 (with-current-buffer (process-buffer process)
1085 (goto-char (point-max))
1087 (let ((parsed-strings
1090 (goto-char (point-min))
1092 (with-syntax-table (eval syntax)
1094 (error (signal 'wcheck--funcall-error
1096 (when (and parsed-strings
1097 (wcheck--list-of-strings-p parsed-strings))
1098 (wcheck--buffer-data-set
1099 buffer :strings parsed-strings)
1100 (wcheck--buffer-data-set buffer :paint-req t)))))
1102 ;; It's not running. Turn off the mode.
1104 (signal 'wcheck--error
1105 (format "Process is not running for buffer \"%s\""
1106 (buffer-name buffer))))
1108 (wcheck--funcall-error
1109 (message "Checker output parser function signaled an error"))
1112 (message "%s" (cdr error-data)))))))))
1115 (defun wcheck--timer-paint-event ()
1116 "Mark strings in windows.
1118 This is normally called by the `wcheck-mode' idle timer. This
1119 function marks (with overlays) strings in the buffers that have
1122 (wcheck--loop-over-paint-reqs buffer
1123 (unless (wcheck--buffer-data-get :buffer buffer :jump-req)
1124 (wcheck--remove-overlays))
1125 ;; We are about to mark text in this buffer so remove this buffer's
1127 (wcheck--buffer-data-set buffer :paint-req nil)
1128 ;; Walk through the visible text areas and mark text based on the
1129 ;; string list returned by an external process.
1131 (dolist (area (wcheck--buffer-data-get :buffer buffer :areas))
1132 (wcheck--paint-strings buffer (car area) (cdr area)
1133 (wcheck--buffer-data-get :buffer buffer
1135 ;; If jump-req is active then paint
1136 ;; invisible text too.
1137 (wcheck--buffer-data-get :buffer buffer
1140 (wcheck--timer-paint-event-run))
1143 (defun wcheck--timer-jump-event ()
1144 (wcheck--loop-over-jump-reqs buffer
1145 (let* ((jump-req (wcheck--buffer-data-get :buffer buffer :jump-req))
1146 (start (wcheck--jump-req-start jump-req))
1147 (bound (wcheck--jump-req-bound jump-req))
1148 (window (wcheck--jump-req-window jump-req)))
1150 (wcheck--buffer-data-set buffer :jump-req nil)
1153 (cond ((> bound start)
1154 (let ((ol (wcheck--overlay-next start bound)))
1156 (if (and (window-live-p window)
1157 (eq buffer (window-buffer window)))
1158 (set-window-point window (overlay-end ol))
1159 (goto-char (overlay-end ol)))
1160 (when (invisible-p (point))
1162 (message "Found from line %s"
1163 (line-number-at-pos (point)))
1164 (wcheck--force-read buffer))
1165 ((< bound (point-max))
1166 (wcheck--jump-req buffer window (1+ bound)
1167 (+ (1+ bound) wcheck--jump-step)))
1169 (signal 'wcheck--overlay-not-found-error nil)))))
1171 (let ((ol (wcheck--overlay-previous start bound)))
1173 (if (and (window-live-p window)
1174 (eq buffer (window-buffer window)))
1175 (set-window-point window (overlay-start ol))
1176 (goto-char (overlay-start ol)))
1177 (when (invisible-p (point))
1179 (message "Found from line %s"
1180 (line-number-at-pos (point)))
1181 (wcheck--force-read buffer))
1182 ((> bound (point-min))
1183 (wcheck--jump-req buffer window (1- bound)
1184 (- (1- bound) wcheck--jump-step)))
1186 (signal 'wcheck--overlay-not-found-error nil)))))
1188 (signal 'wcheck--overlay-not-found-error nil)))
1190 (wcheck--overlay-not-found-error
1191 (message "Found nothing")
1192 (wcheck--force-read buffer))))))
1198 (defun wcheck--add-local-hooks (buffer)
1199 (with-current-buffer buffer
1200 (dolist (hook '((kill-buffer-hook . wcheck--hook-kill-buffer)
1201 (window-scroll-functions . wcheck--hook-window-scroll)
1202 (after-change-functions . wcheck--hook-after-change)
1203 (change-major-mode-hook . wcheck--hook-change-major-mode)
1204 (outline-view-change-hook
1205 . wcheck--hook-outline-view-change)))
1206 (add-hook (car hook) (cdr hook) nil t))))
1209 (defun wcheck--remove-local-hooks (buffer)
1210 (with-current-buffer buffer
1211 (dolist (hook '((kill-buffer-hook . wcheck--hook-kill-buffer)
1212 (window-scroll-functions . wcheck--hook-window-scroll)
1213 (after-change-functions . wcheck--hook-after-change)
1214 (change-major-mode-hook . wcheck--hook-change-major-mode)
1215 (outline-view-change-hook
1216 . wcheck--hook-outline-view-change)))
1217 (remove-hook (car hook) (cdr hook) t))))
1220 (defun wcheck--add-global-hooks ()
1221 (dolist (hook '((window-size-change-functions
1222 . wcheck--hook-window-size-change)
1223 (window-configuration-change-hook
1224 . wcheck--hook-window-configuration-change)))
1225 (add-hook (car hook) (cdr hook))))
1228 (defun wcheck--remove-global-hooks ()
1229 (dolist (hook '((window-size-change-functions
1230 . wcheck--hook-window-size-change)
1231 (window-configuration-change-hook
1232 . wcheck--hook-window-configuration-change)))
1233 (remove-hook (car hook) (cdr hook))))
1236 (defun wcheck--hook-window-scroll (window _window-start)
1237 "`wcheck-mode' hook for window scroll.
1238 Request update for the buffer when its window have been scrolled."
1239 (with-current-buffer (window-buffer window)
1241 (wcheck--buffer-data-set (current-buffer) :read-req t))))
1244 (defun wcheck--hook-window-size-change (frame)
1245 "`wcheck-mode' hook for window size change.
1246 Request update for the buffer when its window's size has
1248 (walk-windows (lambda (window)
1249 (with-current-buffer (window-buffer window)
1251 (wcheck--buffer-data-set (current-buffer)
1257 (defun wcheck--hook-window-configuration-change ()
1258 "`wcheck-mode' hook for window configuration change.
1259 Request update for the buffer when its window's configuration has
1261 (walk-windows (lambda (window)
1262 (with-current-buffer (window-buffer window)
1264 (wcheck--buffer-data-set (current-buffer)
1270 (defun wcheck--hook-after-change (_beg _end _len)
1271 "`wcheck-mode' hook for buffer content change.
1272 Request update for the buffer when its content has been edited."
1273 ;; The buffer that has changed is the current buffer when this hook
1274 ;; function is called.
1276 (wcheck--buffer-data-set (current-buffer) :read-req t)))
1279 (defun wcheck--hook-outline-view-change ()
1280 "`wcheck-mode' hook for outline view change.
1281 Request update for the buffer when its outline view has changed."
1283 (wcheck--buffer-data-set (current-buffer) :read-req t)))
1286 (defun wcheck--hook-kill-buffer ()
1287 "`wcheck-mode' hook for kill-buffer operation.
1288 Turn off `wcheck-mode' when buffer is being killed."
1292 (defun wcheck--hook-change-major-mode ()
1293 "`wcheck-mode' hook for major mode change.
1294 Turn off `wcheck-mode' before changing major mode."
1301 (defun wcheck--start-get-process (buffer)
1302 "Start or get external process for BUFFER.
1303 Start a new process or get already existing process for BUFFER.
1304 Return the object of that particular process or nil if the
1305 operation was unsuccessful."
1306 ;; If process for this BUFFER exists return it.
1307 (or (wcheck--buffer-data-get :buffer buffer :process)
1308 ;; It doesn't exist so start a new one.
1309 (wcheck--with-language-data
1310 (nil (wcheck--buffer-data-get :buffer buffer :language))
1311 (program args (process-connection-type connection))
1313 (when (wcheck--program-executable-p program)
1314 ;; Start the process.
1315 (let ((proc (apply #'start-process "wcheck" nil program args)))
1316 ;; Add the process Lisp object to database.
1317 (wcheck--buffer-data-set buffer :process proc)
1318 ;; Set the output handler function and the associated buffer.
1319 (set-process-filter proc #'wcheck--receive-strings)
1320 (set-process-buffer proc (generate-new-buffer
1321 (concat " *wcheck-process <"
1322 (buffer-name buffer) ">*")))
1323 ;; Prevent Emacs from querying user about running processes
1324 ;; when killing Emacs.
1325 (set-process-query-on-exit-flag proc nil)
1326 ;; Return the process object.
1330 (defun wcheck--buffer-lang-proc-data-update (buffer language)
1331 "Update process and language data for BUFFER.
1332 Calling this function is the primary way to maintain the language
1333 and process data associated to BUFFER. If LANGUAGE is nil remove
1334 BUFFER from the list."
1335 (when (and (bufferp buffer)
1336 (or (stringp language)
1339 ;; Construct a list of currently used processes.
1340 (let ((old-processes (remq nil (wcheck--buffer-data-get-all :process))))
1342 ;; Remove dead buffers and possible minibuffers from the list.
1343 (dolist (item (wcheck--buffer-data-get-all :buffer))
1344 (when (or (not (buffer-live-p item))
1346 (wcheck--buffer-data-delete item)))
1350 ;; LANGUAGE was given. If data for this buffer does not
1352 (unless (wcheck--buffer-data-get :buffer buffer)
1353 (wcheck--buffer-data-create buffer))
1354 ;; Add this BUFFER's language info and reset the process
1356 (wcheck--buffer-data-set buffer :language language)
1357 (wcheck--buffer-data-set buffer :process nil))
1359 ;; LANGUAGE was not given so this normally means that
1360 ;; wcheck-mode is being turned off for this buffer. Remove
1362 (wcheck--buffer-data-delete buffer))
1364 ;; Construct a list of processes that are still used.
1365 (let ((new-processes (remq nil (wcheck--buffer-data-get-all :process))))
1366 ;; Stop those processes which are no longer needed.
1367 (dolist (proc old-processes)
1368 (unless (memq proc new-processes)
1369 (kill-buffer (process-buffer proc))
1370 (delete-process proc))))))
1372 (wcheck--buffer-data-get :buffer buffer))
1375 ;;; Read and paint strings
1378 (defun wcheck--read-strings (buffer beg end &optional invisible)
1379 "Return a list of text elements in BUFFER.
1380 Scan BUFFER between positions BEG and END and search for text
1381 elements according to buffer's language settings (see
1382 `wcheck-language-data'). If INVISIBLE is non-nil read all buffer
1383 areas, including invisible ones. Otherwise skip invisible text."
1385 (when (buffer-live-p buffer)
1386 (with-current-buffer buffer
1389 (when font-lock-mode
1391 (jit-lock-fontify-now (min beg end) (max beg end))))
1393 (wcheck--with-language-data
1394 (language (wcheck--buffer-data-get :buffer buffer :language))
1395 (regexp-start regexp-body regexp-end regexp-discard
1396 syntax (case-fold-search case-fold))
1399 (concat regexp-start "\\(" regexp-body "\\)" regexp-end))
1400 (face-p (wcheck--generate-face-predicate language major-mode))
1401 (search-spaces-regexp nil)
1405 (with-syntax-table (eval syntax)
1408 (while (and (re-search-forward regexp end t)
1409 (> (point) old-point))
1410 (cond ((and (not invisible)
1411 (invisible-p (match-beginning 1)))
1412 ;; This point is invisible. Let's jump forward
1413 ;; to next change of "invisible" property.
1414 (goto-char (next-single-char-property-change
1415 (match-beginning 1) 'invisible buffer
1419 (or (equal regexp-discard "")
1422 (match-string-no-properties 1)))))
1423 ;; Add the match to the string list.
1424 (push (match-string-no-properties 1) strings)))
1425 (setq old-point (point)))))
1426 (delete-dups strings)))))))
1429 (defun wcheck--paint-strings (buffer beg end strings &optional invisible)
1430 "Mark strings in buffer.
1432 Mark all strings in STRINGS which are visible in BUFFER within
1433 position range from BEG to END. If INVISIBLE is non-nil paint all
1434 buffer areas, including invisible ones. Otherwise skip invisible
1437 (when (buffer-live-p buffer)
1438 (with-current-buffer buffer
1441 (wcheck--with-language-data
1442 (language (wcheck--buffer-data-get :buffer buffer :language))
1443 (regexp-start regexp-end syntax (case-fold-search case-fold)
1444 (ol-face face) action-program)
1446 (let ((face-p (wcheck--generate-face-predicate language major-mode))
1447 (search-spaces-regexp nil)
1448 (ol-keymap (make-sparse-keymap))
1453 (when action-program
1454 (define-key ol-keymap [down-mouse-3] 'wcheck--mouse-click-overlay)
1455 (define-key ol-keymap [mouse-3] 'undefined)
1456 (setq ol-mouse-face 'highlight
1457 ol-help-echo "mouse-3: show actions"))
1459 (with-syntax-table (eval syntax)
1461 (dolist (string strings)
1462 (setq regexp (concat regexp-start "\\("
1463 (regexp-quote string) "\\)"
1468 (while (and (re-search-forward regexp end t)
1469 (> (point) old-point))
1470 (cond ((and (not invisible)
1471 (invisible-p (match-beginning 1)))
1472 ;; The point is invisible so jump forward to
1473 ;; the next change of "invisible" text
1475 (goto-char (next-single-char-property-change
1476 (match-beginning 1) 'invisible buffer
1480 (wcheck--make-overlay
1481 buffer ol-face ol-mouse-face ol-help-echo ol-keymap
1482 (match-beginning 1) (match-end 1))))
1483 (setq old-point (point))))))))))))
1486 ;;; Jump forward or backward
1489 (defun wcheck--overlay-next (start bound)
1490 (unless (>= start (point-max))
1492 (dolist (ol (overlays-at start))
1493 (when (overlay-get ol 'wcheck-mode)
1494 (throw 'overlay ol)))
1496 (while (and (setq pos (next-overlay-change pos))
1497 (< pos (min bound (point-max))))
1498 (dolist (ol (overlays-at pos))
1499 (when (overlay-get ol 'wcheck-mode)
1500 (throw 'overlay ol))))))))
1503 (defun wcheck--overlay-previous (start bound)
1504 (unless (<= start (point-min))
1508 (setq pos (previous-overlay-change pos))
1509 (dolist (ol (overlays-at pos))
1510 (when (overlay-get ol 'wcheck-mode)
1511 (throw 'overlay ol)))
1512 (when (<= pos (max bound (point-min)))
1513 (throw 'overlay nil)))))))
1516 (defun wcheck--line-start-at (pos)
1519 (line-beginning-position)))
1522 (defun wcheck--line-end-at (pos)
1525 (line-end-position)))
1528 (defun wcheck--jump-req (buffer window start bound)
1529 (unless (= start bound)
1530 (with-current-buffer buffer
1531 (setq bound (funcall (if (> bound start)
1532 'wcheck--line-end-at
1533 'wcheck--line-start-at)
1535 (message "Searching in lines %d-%d..."
1536 (line-number-at-pos start)
1537 (line-number-at-pos bound))
1538 (wcheck--buffer-data-set buffer :jump-req (wcheck--jump-req-create
1539 window start bound))
1540 (wcheck--buffer-data-set buffer :areas (list (cons (min start bound)
1541 (max start bound))))
1542 (wcheck--send-strings buffer (wcheck--read-strings
1543 buffer (min start bound)
1544 (max start bound) t))
1545 (wcheck--timer-paint-event-run wcheck--timer-paint-event-count-std))))
1548 (defun wcheck--invisible-text-in-area-p (buffer beg end)
1550 (let ((pos (min beg end))
1551 (end (max beg end)))
1552 (when (invisible-p pos)
1553 (throw 'invisible t))
1554 (while (and (setq pos (next-single-char-property-change
1555 pos 'invisible buffer))
1557 (when (invisible-p pos)
1558 (throw 'invisible t))))))
1562 (defun wcheck-jump-forward ()
1563 "Move point forward to next marked text area."
1565 (let ((buffer (current-buffer))
1566 (window (selected-window)))
1570 (wcheck--buffer-data-set buffer :jump-req nil)
1571 (let ((ol (wcheck--overlay-next
1572 (point) (window-end (selected-window) t))))
1573 (if (and ol (not (wcheck--invisible-text-in-area-p
1574 buffer (point) (overlay-end ol))))
1575 (goto-char (overlay-end ol))
1577 (message "End of buffer")
1578 (wcheck--jump-req buffer window (point)
1579 (+ (point) wcheck--jump-step))))))))
1583 (defun wcheck-jump-backward ()
1584 "Move point backward to previous marked text area."
1586 (let ((buffer (current-buffer))
1587 (window (selected-window)))
1591 (wcheck--buffer-data-set buffer :jump-req nil)
1592 (let ((ol (wcheck--overlay-previous
1593 (point) (window-start (selected-window)))))
1594 (if (and ol (not (wcheck--invisible-text-in-area-p
1595 buffer (point) (overlay-start ol))))
1596 (goto-char (overlay-start ol))
1598 (message "Beginning of buffer")
1599 (wcheck--jump-req buffer window (point)
1600 (- (point) wcheck--jump-step))))))))
1606 (defun wcheck-marked-text-at (pos)
1607 "Return information about marked text at POS.
1609 POS is a buffer position. The return value is a vector of five
1610 elements: (1) the marked text string, (2) buffer position at the
1611 beginning of the text, (3) position at the end of the text, (4)
1612 the overlay object which marks the text and (5) the current
1613 language as a string. The return value is nil if there are no
1616 If you need more information about the current language settings
1617 use `wcheck-query-language-data' for querying effective language
1620 (let ((overlay (catch 'my-overlay
1621 (dolist (ol (overlays-at pos))
1622 (when (overlay-get ol 'wcheck-mode)
1623 (throw 'my-overlay ol))))))
1625 (let ((start (overlay-start overlay))
1626 (end (overlay-end overlay)))
1627 (vector (buffer-substring-no-properties start end)
1629 (wcheck--buffer-data-get
1630 :buffer (current-buffer) :language))))))
1634 (defun wcheck-actions (pos &optional event)
1635 "Offer actions for marked text.
1637 This function is usually called through a right mouse button
1638 event or interactively by a user. In both cases function's
1639 arguments are filled automatically.
1641 If buffer position POS is on marked text (and action program is
1642 properly configured) show a menu of actions. When this function
1643 is called interactively POS is automatically the current point
1644 position. Optional EVENT argument is a mouse event which is
1645 present if this function is called through a right mouse button
1646 click on marked text. If EVENT is non-nil use a graphic toolkit's
1647 menu (when available) for selecting actions. Otherwise use a text
1650 When user chooses one of the options from the menu the related
1651 action is executed. It could mean that the original marked text
1652 is replaced with the chosen substitute. Menu options can trigger
1653 any kind of actions, though."
1656 (condition-case error-data
1657 (let ((marked-text (or (wcheck-marked-text-at pos)
1658 (wcheck-marked-text-at (1- pos))))
1661 (if (not marked-text)
1662 (signal 'wcheck--action-error "There is no marked text here")
1663 (let* ((start (copy-marker (aref marked-text 1)))
1664 (end (copy-marker (aref marked-text 2)))
1665 (actions (wcheck--get-actions marked-text))
1666 (choice (cond ((and (null (cdr actions))
1667 (wcheck-query-language-data
1668 (aref marked-text 4) 'action-autoselect))
1670 ((and event (display-popup-menus-p))
1671 (wcheck--choose-action-popup actions event))
1672 (t (wcheck--choose-action-minibuffer actions)))))
1674 (cond ((and (stringp choice)
1677 (with-current-buffer (marker-buffer start)
1678 (if buffer-read-only
1679 (signal 'wcheck--action-error "Buffer is read-only")
1680 (delete-region start end)
1683 (setq return-value choice))))
1685 (funcall choice marked-text)
1686 (setq return-value choice)))
1688 (if (markerp start) (set-marker start nil))
1689 (if (markerp end) (set-marker end nil))))
1692 (wcheck--action-program-error
1693 (message "Language \"%s\": action program is not configured"
1696 (wcheck--parser-function-not-configured-error
1697 (message "Language \"%s\": parser function is not configured"
1701 (message "%s" (cdr error-data)))))
1704 (defun wcheck--get-actions (marked-text)
1705 "Get actions from external program or a function.
1707 MARKED-TEXT must be a vector such as the one returned by
1708 `wcheck-marked-text-at' function."
1710 (wcheck--with-language-data
1711 (language (aref marked-text 4))
1712 ((program action-program)
1714 (parser action-parser)
1715 (case-fold-search case-fold)
1718 (with-syntax-table (eval syntax)
1719 (cond ((not (wcheck--action-program-configured-p language))
1720 (signal 'wcheck--action-program-error language))
1722 ((and (stringp program)
1724 (signal 'wcheck--parser-function-not-configured-error language))
1728 (insert (aref marked-text 0))
1729 (apply #'call-process-region (point-min) (point-max)
1730 program t t nil args)
1731 (goto-char (point-min))
1732 (wcheck--clean-actions
1734 (condition-case nil (funcall parser marked-text)
1735 (error (signal 'wcheck--funcall-error
1736 (concat "Action parser function "
1737 "signaled an error"))))))))
1739 ((functionp program)
1740 (wcheck--clean-actions
1742 (condition-case nil (funcall program marked-text)
1743 (error (signal 'wcheck--funcall-error
1744 (concat "Action function signaled "
1745 "an error")))))))))))
1748 (defun wcheck--clean-actions (actions)
1749 (when (listp actions)
1750 (delete nil (mapcar (lambda (item)
1751 (cond ((stringp item)
1752 (cons (wcheck--clean-string item)
1755 (stringp (car item))
1756 (or (functionp (cdr item))
1757 (stringp (cdr item))))
1758 (cons (wcheck--clean-string (car item))
1763 (defun wcheck--clean-string (string)
1764 (if (equal string "")
1766 (setq string (replace-regexp-in-string "[^[:print:]]+" "" string))
1767 (if (not (string-match "[^[:space:]]" string))
1768 "[Space or control chars]"
1769 (replace-regexp-in-string "\\(?:\\` +\\| +\\'\\)" "" string))))
1772 (defun wcheck--choose-action-popup (actions event)
1773 "Create a pop-up menu to choose an action.
1774 ACTIONS is a list of strings. EVENT is the mouse event that
1775 originated this sequence of function calls. Return user's
1776 choice (a string) or nil."
1777 (let ((menu (list "Choose"
1778 (cons "" (if actions
1779 (mapcar (lambda (item)
1780 (cons (wcheck--clean-string
1784 (list "[No actions]"))))))
1785 (x-popup-menu event menu)))
1788 (defun wcheck--read-key (prompt)
1789 (if (fboundp 'read-key)
1791 (read-char prompt)))
1794 (defun wcheck--choose-action-minibuffer (actions)
1795 "Create a text menu to choose a substitute action.
1796 ACTIONS is a list of strings. Return user's choice (a string)
1799 (let ((chars (append (number-sequence ?1 ?9) (list ?0)
1800 (number-sequence ?a ?z)))
1804 (setq mode-line-format (list "--- Choose %-")
1809 (while (and actions chars)
1810 (setq sug (car actions)
1811 actions (cdr actions)
1812 string (concat (propertize (format "%c)" (car chars))
1814 " " (wcheck--clean-string (car sug)) " ")
1815 alist (cons (cons (car chars) (cdr sug)) alist)
1818 (when (and actions chars
1819 (> (+ (- (point) (line-beginning-position))
1820 (length (concat "x) " (caar actions))))
1826 (goto-char (point-min))
1827 (setq buffer-read-only t)
1829 (let* ((window-min-height 2)
1830 (split-window-keep-point t)
1831 (window (split-window-vertically
1832 (- 0 (min (count-lines (point-min) (point-max))
1833 (- (window-body-height) 2))
1837 (let ((last (caar alist)))
1838 (format "Number %s(%s):"
1839 (if (memq last (number-sequence ?a ?z))
1842 (cond ((= last ?1) "1")
1843 ((memq last (number-sequence ?2 ?9))
1844 (format "1-%c" last))
1845 ((= last ?0) "1-9,0")
1846 ((= last ?a) "1-9,0,a")
1847 ((memq last (number-sequence ?b ?z))
1848 (format "1-9,0,a-%c" last))
1850 minibuffer-prompt-properties)))
1851 (set-window-buffer window (current-buffer))
1852 (set-window-dedicated-p window t)
1853 ;; Return the choice or nil.
1854 (cond ((cdr (assq (wcheck--read-key prompt) alist)))
1855 (t (message "Abort") nil)))))
1856 (message "No actions")
1860 (defun wcheck-parser-lines (&rest _ignored)
1861 "Parser for newline-separated output.
1862 Return current buffer's lines as a list of strings."
1863 (delete-dups (split-string (buffer-substring-no-properties
1864 (point-min) (point-max))
1868 (defun wcheck-parser-whitespace (&rest _ignored)
1869 "Parser for whitespace-separated output.
1870 Split current buffer's content to whitespace-separated tokens and
1871 return them as a list of strings."
1872 (delete-dups (split-string (buffer-substring-no-properties
1873 (point-min) (point-max))
1874 "[ \f\t\n\r\v]+" t)))
1877 (defun wcheck-parser-ispell-suggestions (&rest _ignored)
1878 "Parser for Ispell-compatible programs' spelling suggestions."
1879 (let ((search-spaces-regexp nil))
1880 (when (re-search-forward "^& [^ ]+ \\([0-9]+\\) [0-9]+: \\(.+\\)$" nil t)
1881 (let ((count (string-to-number (match-string-no-properties 1)))
1882 (words (split-string (match-string-no-properties 2) ", " t)))
1883 (delete-dups (nbutlast words (- (length words) count)))))))
1886 ;;; Face information functions
1889 (defun wcheck--collect-faces (beg end)
1890 "Return a list of faces between positions BEG and END."
1894 (setq face (get-text-property pos 'face)
1896 (if (and face (listp face))
1897 (setq faces (append face faces))
1899 (delete-dups faces)))
1902 (defun wcheck--major-mode-face-settings (language mode)
1903 "Return read/skip face settings for MODE."
1904 (let ((data (wcheck-query-language-data language 'read-or-skip-faces))
1908 (setq conf (pop data))
1909 (when (or (eq nil (car conf))
1910 (eq mode (car conf))
1911 (and (listp (car conf))
1912 (memq mode (car conf))))
1913 (throw 'answer conf))))))
1916 (defun wcheck--face-found-p (user-faces buffer-faces)
1917 "Return t if a symbol in USER-FACES is found from BUFFER-FACES.
1918 Both arguments are lists."
1920 (dolist (face user-faces)
1921 (when (member face buffer-faces)
1922 (throw 'found t)))))
1925 (defun wcheck--generate-face-predicate (language mode)
1926 "Generate a face predicate expression for scanning buffer.
1927 Return a predicate expression that is used to decide whether
1928 `wcheck-mode' should read or paint text at the current point
1929 position with LANGUAGE and MODE. Evaluating the predicate
1930 expression will return a boolean."
1931 (let* ((face-settings (wcheck--major-mode-face-settings
1933 (mode (nth 1 face-settings))
1934 (faces (nthcdr 2 face-settings)))
1935 (cond ((not font-lock-mode)
1938 `(wcheck--face-found-p
1939 ',faces (wcheck--collect-faces
1940 (match-beginning 1) (match-end 1))))
1942 `(not (wcheck--face-found-p
1943 ',faces (wcheck--collect-faces
1944 (match-beginning 1) (match-end 1)))))
1948 ;;; Miscellaneous low-level functions
1951 (defun wcheck--language-data-valid-p (key value)
1952 (cond ((and (eq key 'syntax)
1953 (syntax-table-p (and (boundp value) (eval value)))))
1954 ((and (eq key 'face)
1956 ((and (memq key '(regexp-start regexp-body regexp-end regexp-discard))
1958 ((and (memq key '(program action-program))
1961 (and value (symbolp value)
1962 (error "Invalid %s value: %S" key value)))))
1963 ((and (eq key 'args)
1964 (wcheck--list-of-strings-p value)))
1965 ((and (eq key 'action-args)
1966 (wcheck--list-of-strings-p value)))
1967 ((and (memq key '(parser action-parser))
1968 (or (functionp value)
1970 (error "%s not a function: %S" key value)))))
1971 ((memq key '(connection case-fold action-autoselect)))
1972 ((and (eq key 'read-or-skip-faces)
1973 (wcheck--list-of-lists-p value)))))
1976 (defun wcheck-query-language-data (language key)
1977 "Query `wcheck-mode' language data.
1979 Return LANGUAGE's value for KEY. Valid keys (symbols) are
1980 described in the documentation of user variable
1981 `wcheck-language-data'. If that variable does not define
1982 a (valid) value for the KEY then query the value from
1983 `wcheck-language-data-defaults' or use internal defaults."
1985 (when (wcheck--language-exists-p language)
1987 (and (wcheck--list-of-lists-p wcheck-language-data)
1988 (assq key (cdr (assoc language wcheck-language-data)))))
1990 (and (wcheck--list-of-lists-p wcheck-language-data-defaults)
1991 (assq key wcheck-language-data-defaults)))
1993 (and (wcheck--list-of-lists-p
1994 wcheck--language-data-defaults-hard-coded)
1995 (assq key wcheck--language-data-defaults-hard-coded)))
1997 (list (when (wcheck--language-data-valid-p key (cdr data))
1999 (when (wcheck--language-data-valid-p key (cdr default))
2001 (when (wcheck--language-data-valid-p key (cdr hard-coded))
2004 (if (eq key 'read-or-skip-faces)
2005 (apply #'append (mapcar #'cdr conf))
2006 (cdr (assq key conf))))))
2009 (defun wcheck--language-exists-p (language)
2010 "Return t if LANGUAGE exists in `wcheck-language-data'."
2011 (and (wcheck--list-of-lists-p wcheck-language-data)
2012 (member language (mapcar #'car wcheck-language-data))
2014 (> (length language) 0)
2018 (defun wcheck--program-executable-p (program)
2019 "Return non-nil if PROGRAM is executable regular file."
2020 (when (stringp program)
2021 (let ((f (executable-find program)))
2022 (and (file-regular-p f)
2023 (file-executable-p f)))))
2026 (defun wcheck--program-configured-p (language)
2027 (let ((program (wcheck-query-language-data language 'program)))
2028 (or (wcheck--program-executable-p program)
2029 (functionp program))))
2032 (defun wcheck--action-program-configured-p (language)
2033 (let ((program (wcheck-query-language-data language 'action-program)))
2034 (or (wcheck--program-executable-p program)
2035 (functionp program))))
2038 (defun wcheck--list-of-strings-p (object)
2040 (not (memq nil (mapcar #'stringp object)))))
2043 (defun wcheck--list-of-lists-p (object)
2045 (not (memq nil (mapcar #'listp object)))))
2048 (defun wcheck--process-running-p (process)
2049 (eq 'run (process-status process)))
2052 (defun wcheck--current-idle-time-seconds ()
2053 "Return current idle time in seconds.
2054 The returned value is a floating point number."
2055 (let* ((idle (or (current-idle-time)
2059 (micros (nth 2 idle)))
2063 (/ micros 1000000.0))))
2066 (defun wcheck--combine-overlapping-areas (alist)
2067 "Combine overlapping items in ALIST.
2068 ALIST is a list of (A . B) items in which A and B are integers.
2069 Each item denote a buffer position range from A to B. This
2070 function returns a new list which has items in increasing order
2071 according to A's and all overlapping A B ranges are combined."
2072 (let ((alist (sort (copy-sequence alist)
2074 (< (car a) (car b)))))
2077 (while (not (equal previous alist))
2078 (setq previous alist
2079 alist (append (wcheck--combine-two (car previous) (cadr previous))
2080 (nthcdr 2 previous))))
2081 (setq final (cons (car alist) final)
2087 (defun wcheck--combine-two (a b)
2094 (list (cons a1 (if (> b2 a2) b2 a2)))
2097 (t (append (list a) b)))))
2103 (defun wcheck--make-overlay (buffer face mouse-face help-echo keymap beg end)
2104 "Create an overlay to mark text.
2105 Create an overlay in BUFFER from range BEG to END. FACE,
2106 MOUSE-FACE, HELP-ECHO and KEYMAP are overlay's properties."
2107 (let ((overlay (make-overlay beg end buffer)))
2108 (dolist (prop `((wcheck-mode . t)
2110 (mouse-face . ,mouse-face)
2111 (modification-hooks wcheck--remove-changed-overlay)
2112 (insert-in-front-hooks wcheck--remove-changed-overlay)
2113 (insert-behind-hooks wcheck--remove-changed-overlay)
2116 (help-echo . ,help-echo)))
2117 (overlay-put overlay (car prop) (cdr prop)))))
2120 (defun wcheck--remove-overlays (&optional beg end)
2121 "Remove `wcheck-mode' overlays from current buffer.
2122 If optional arguments BEG and END exist remove overlays from
2123 range BEG to END. Otherwise remove all overlays."
2124 (remove-overlays beg end 'wcheck-mode t))
2127 (defun wcheck--remove-changed-overlay (overlay after _beg _end &optional _len)
2128 "Hook for removing overlay which is being edited."
2130 (delete-overlay overlay)))
2133 (defun wcheck--mouse-click-overlay (event)
2134 "Overlay mouse-click event.
2135 Send the mouse pointer position and mouse event to the
2136 `wcheck-actions' function."
2138 (wcheck-actions (posn-point (event-end event)) event))
2141 ;;; Buffer data access functions
2144 (defconst wcheck--buffer-data-keys
2145 '(:buffer :process :language :read-req :paint-req :jump-req :areas :strings))
2148 (defun wcheck--buffer-data-key-index (key)
2149 "Return the index of KEY in buffer data object."
2152 (dolist (data-key wcheck--buffer-data-keys nil)
2153 (if (eq key data-key)
2154 (throw 'answer index)
2155 (setq index (1+ index)))))))
2158 (defun wcheck--buffer-data-create (buffer)
2159 "Create data instance for BUFFER.
2160 But only if it doesn't exist already."
2161 (unless (wcheck--buffer-data-get :buffer buffer)
2162 (let ((data (make-vector (length wcheck--buffer-data-keys) nil)))
2163 (aset data (wcheck--buffer-data-key-index :buffer) buffer)
2164 (push data wcheck--buffer-data))))
2167 (defun wcheck--buffer-data-delete (buffer)
2168 "Delete all data associated to BUFFER."
2169 (let ((index (wcheck--buffer-data-key-index :buffer)))
2170 (setq wcheck--buffer-data
2171 (delq nil (mapcar (lambda (item)
2172 (unless (eq buffer (aref item index))
2174 wcheck--buffer-data)))))
2177 (defun wcheck--buffer-data-get (key value &optional target-key)
2178 "Query the first matching KEY VALUE pair and return TARGET-KEY.
2179 If optional TARGET-KEY is not given return all data associated
2180 with the matching KEY VALUE."
2182 (dolist (item wcheck--buffer-data)
2183 (when (equal value (aref item (wcheck--buffer-data-key-index key)))
2184 (throw 'answer (if target-key
2185 (aref item (wcheck--buffer-data-key-index
2190 (defun wcheck--buffer-data-get-all (&optional key)
2191 "Return every buffer's value for KEY.
2192 If KEY is nil return all buffer's all data."
2194 (let ((index (wcheck--buffer-data-key-index key)))
2195 (mapcar (lambda (item)
2197 wcheck--buffer-data))
2198 wcheck--buffer-data))
2201 (defun wcheck--buffer-data-set (buffer key value)
2202 "Set KEY's VALUE for BUFFER."
2203 (let ((item (wcheck--buffer-data-get :buffer buffer)))
2205 (aset item (wcheck--buffer-data-key-index key) value))))
2208 (defun wcheck--jump-req-create (window start bound)
2209 (when (and (number-or-marker-p start)
2210 (number-or-marker-p bound)
2212 (vector window start bound)))
2215 (defun wcheck--jump-req-window (jump-req)
2217 (defun wcheck--jump-req-start (jump-req)
2219 (defun wcheck--jump-req-bound (jump-req)
2223 (provide 'wcheck-mode)
2225 ;;; wcheck-mode.el ends here