quail.el 114 KB
Newer Older
1
;;; quail.el --- provides simple input method for multilingual text
Karl Heuer's avatar
Karl Heuer committed
2

3
;; Copyright (C) 1997-1998, 2000-2011  Free Software Foundation, Inc.
Kenichi Handa's avatar
Kenichi Handa committed
4
;; Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
5
;;   2005, 2006, 2007, 2008, 2009, 2010, 2011
Kenichi Handa's avatar
Kenichi Handa committed
6 7
;;   National Institute of Advanced Industrial Science and Technology (AIST)
;;   Registration Number H14PRO021
Karl Heuer's avatar
Karl Heuer committed
8 9 10 11

;; Author: Kenichi HANDA <handa@etl.go.jp>
;;	   Naoto TAKAHASHI <ntakahas@etl.go.jp>
;; Maintainer: Kenichi HANDA <handa@etl.go.jp>
Dave Love's avatar
Dave Love committed
12
;; Keywords: mule, multilingual, input method, i18n
Karl Heuer's avatar
Karl Heuer committed
13 14 15

;; This file is part of GNU Emacs.

16
;; GNU Emacs is free software: you can redistribute it and/or modify
Karl Heuer's avatar
Karl Heuer committed
17
;; it under the terms of the GNU General Public License as published by
18 19
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
Karl Heuer's avatar
Karl Heuer committed
20 21 22 23 24 25 26

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
27
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
Karl Heuer's avatar
Karl Heuer committed
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

;;; Commentary:

;; In Quail minor mode, you can input multilingual text easily.  By
;; defining a translation table (named Quail map) which maps ASCII key
;; string to multilingual character or string, you can input any text
;; from ASCII keyboard.
;;
;; We use words "translation" and "conversion" differently.  The
;; former is done by Quail package itself, the latter is the further
;; process of converting a translated text to some more desirable
;; text.  For instance, Quail package for Japanese (`quail-jp')
;; translates Roman text (transliteration of Japanese in Latin
;; alphabets) to Hiragana text, which is then converted to
;; Kanji-and-Kana mixed text or Katakana text by commands specified in
;; CONVERSION-KEYS argument of the Quail package.

Dave Love's avatar
Dave Love committed
45
;; [There was an input method for Mule 2.3 called `Tamago' from the
Paul Eggert's avatar
Paul Eggert committed
46
;; Japanese `TAkusan MAtasete GOmen-nasai', or `Sorry for having you
Dave Love's avatar
Dave Love committed
47 48 49 50 51 52
;; wait so long'; this couldn't be included in Emacs 20.  `Tamago' is
;; Japanese for `egg' (implicitly a hen's egg).  Handa-san made a
;; smaller and simpler system; the smaller quail egg is also eaten in
;; Japan.  Maybe others will be egged on to write more sorts of input
;; methods.]

Karl Heuer's avatar
Karl Heuer committed
53 54
;;; Code:

Chong Yidong's avatar
Chong Yidong committed
55
(require 'help-mode)
56
(eval-when-compile (require 'cl))
57

Kenichi Handa's avatar
Kenichi Handa committed
58 59 60
(defgroup quail nil
  "Quail: multilingual input method."
  :group 'leim)
Karl Heuer's avatar
Karl Heuer committed
61 62 63 64

;; Buffer local variables

(defvar quail-current-package nil
65
  "The current Quail package, which depends on the current input method.
Karl Heuer's avatar
Karl Heuer committed
66 67 68 69
See the documentation of `quail-package-alist' for the format.")
(make-variable-buffer-local 'quail-current-package)
(put 'quail-current-package 'permanent-local t)

70 71 72
;; Quail uses the following variables to assist users.
;; A string containing available key sequences or translation list.
(defvar quail-guidance-str nil)
Karl Heuer's avatar
Karl Heuer committed
73 74
;; A buffer to show completion list of the current key sequence.
(defvar quail-completion-buf nil)
75 76 77
;; We may display the guidance string in a buffer on a one-line frame.
(defvar quail-guidance-buf nil)
(defvar quail-guidance-frame nil)
Karl Heuer's avatar
Karl Heuer committed
78

79
;; Each buffer in which Quail is activated should use different
80 81 82
;; guidance string.
(make-variable-buffer-local 'quail-guidance-str)
(put 'quail-guidance-str 'permanent-local t)
83

Karl Heuer's avatar
Karl Heuer committed
84 85 86 87 88 89 90 91 92 93
(defvar quail-overlay nil
  "Overlay which covers the current translation region of Quail.")
(make-variable-buffer-local 'quail-overlay)

(defvar quail-conv-overlay nil
  "Overlay which covers the text to be converted in Quail mode.")
(make-variable-buffer-local 'quail-conv-overlay)

(defvar quail-current-key nil
  "Current key for translation in Quail mode.")
94
(make-variable-buffer-local 'quail-current-key)
Karl Heuer's avatar
Karl Heuer committed
95 96 97

(defvar quail-current-str nil
  "Currently selected translation of the current key.")
98
(make-variable-buffer-local 'quail-current-str)
Karl Heuer's avatar
Karl Heuer committed
99 100

(defvar quail-current-translations nil
101 102 103 104 105 106
  "Cons of indices and vector of possible translations of the current key.
Indices is a list of (CURRENT START END BLOCK BLOCKS), where
CURRENT is an index of the current translation,
START and END are indices of the start and end of the current block,
BLOCK is the current block index,
BLOCKS is a number of  blocks of translation.")
107
(make-variable-buffer-local 'quail-current-translations)
Karl Heuer's avatar
Karl Heuer committed
108

109 110 111
(defvar quail-current-data nil
  "Any Lisp object holding information of current translation status.
When a key sequence is mapped to TRANS and TRANS is a cons
Karl Heuer's avatar
Karl Heuer committed
112
of actual translation and some Lisp object to be referred
113 114
for translating the longer key sequence, this variable is set
to that Lisp object.")
115
(make-variable-buffer-local 'quail-current-data)
116

Karl Heuer's avatar
Karl Heuer committed
117 118 119 120 121 122 123 124
;; Quail package handlers.

(defvar quail-package-alist nil
  "List of Quail packages.
A Quail package is a list of these elements:
  NAME, TITLE, QUAIL-MAP, GUIDANCE, DOCSTRING, TRANSLATION-KEYS,
  FORGET-LAST-SELECTION, DETERMINISTIC, KBD-TRANSLATE, SHOW-LAYOUT,
  DECODE-MAP, MAXIMUM-SHORTEST, OVERLAY-PLIST, UPDATE-TRANSLATION-FUNCTION,
Kenichi Handa's avatar
Kenichi Handa committed
125
  CONVERSION-KEYS, SIMPLE.
Karl Heuer's avatar
Karl Heuer committed
126 127 128 129 130 131 132 133 134 135 136 137 138

QUAIL-MAP is a data structure to map key strings to translations.  For
the format, see the documentation of `quail-map-p'.

DECODE-MAP is an alist of translations and corresponding keys.

See the documentation of `quail-define-package' for the other elements.")

;; Return various slots in the current quail-package.

(defsubst quail-name ()
  "Return the name of the current Quail package."
  (nth 0 quail-current-package))
139 140 141 142 143 144 145 146

(defun quail-indent-to (col)
  (indent-to col)
  (let ((end (point)))
    (save-excursion
      (unless (zerop (skip-chars-backward "\t "))
        (put-text-property (point) end 'display (list 'space :align-to col))))))

147 148
;;;###autoload
(defun quail-title ()
Karl Heuer's avatar
Karl Heuer committed
149
  "Return the title of the current Quail package."
150 151 152 153 154 155 156 157
  (let ((title (nth 1 quail-current-package)))
    ;; TITLE may be a string or a list.  If it is a list, each element
    ;; is a string or the form (VAR STR1 STR2), and the interpretation
    ;; of the list is the same as that of mode-line-format.
    (if (stringp title)
	title
      (condition-case nil
	  (mapconcat
158
	   (lambda (x)
159 160 161 162 163 164 165
	     (cond ((stringp x) x)
		   ((and (listp x) (symbolp (car x)) (= (length x) 3))
		    (if (symbol-value (car x))
			(nth 1 x) (nth 2 x)))
		   (t "")))
	   title "")
	(error "")))))
Karl Heuer's avatar
Karl Heuer committed
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
(defsubst quail-map ()
  "Return the translation map of the current Quail package."
  (nth 2 quail-current-package))
(defsubst quail-guidance ()
  "Return an object used for `guidance' feature of the current Quail package.
See also the documentation of `quail-define-package'."
  (nth 3 quail-current-package))
(defsubst quail-docstring ()
  "Return the documentation string of the current Quail package."
  (nth 4 quail-current-package))
(defsubst quail-translation-keymap ()
  "Return translation keymap in the current Quail package.
Translation keymap is a keymap used while translation region is active."
  (nth 5 quail-current-package))
(defsubst quail-forget-last-selection ()
  "Return `forget-last-selection' flag of the current Quail package.
See also the documentation of `quail-define-package'."
  (nth 6 quail-current-package))
(defsubst quail-deterministic ()
  "Return `deterministic' flag of the current Quail package.
See also the documentation of `quail-define-package'."
  (nth 7 quail-current-package))
(defsubst quail-kbd-translate ()
  "Return `kbd-translate' flag of the current Quail package.
See also the documentation of `quail-define-package'."
  (nth 8 quail-current-package))
(defsubst quail-show-layout ()
  "Return `show-layout' flag of the current Quail package.
See also the documentation of `quail-define-package'."
  (nth 9 quail-current-package))
(defsubst quail-decode-map ()
  "Return decode map of the current Quail package.
It is an alist of translations and corresponding keys."
  (nth 10 quail-current-package))
(defsubst quail-maximum-shortest ()
  "Return `maximum-shortest' flag of the current Quail package.
See also the documentation of `quail-define-package'."
  (nth 11 quail-current-package))
(defsubst quail-overlay-plist ()
  "Return property list of an overly used in the current Quail package."
  (nth 12 quail-current-package))
(defsubst quail-update-translation-function ()
  "Return a function for updating translation in the current Quail package."
  (nth 13 quail-current-package))
(defsubst quail-conversion-keymap ()
  "Return conversion keymap in the current Quail package.
Conversion keymap is a keymap used while conversion region is active
 but translation region is not active."
  (nth 14 quail-current-package))
Kenichi Handa's avatar
Kenichi Handa committed
215 216 217
(defsubst quail-simple ()
  "Return t if the current Quail package is simple."
  (nth 15 quail-current-package))
Karl Heuer's avatar
Karl Heuer committed
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241

(defsubst quail-package (name)
  "Return Quail package named NAME."
  (assoc name quail-package-alist))

(defun quail-add-package (package)
  "Add Quail package PACKAGE to `quail-package-alist'."
  (let ((pac (quail-package (car package))))
    (if pac
	(setcdr pac (cdr package))
      (setq quail-package-alist (cons package quail-package-alist)))))

(defun quail-select-package (name)
  "Select Quail package named NAME as the current Quail package."
  (let ((package (quail-package name)))
    (if (null package)
	(error "No Quail package `%s'" name))
    (setq quail-current-package package)
    (setq-default quail-current-package package)
    name))

;;;###autoload
(defun quail-use-package (package-name &rest libraries)
  "Start using Quail package PACKAGE-NAME.
242
The remaining arguments are LIBRARIES to be loaded before using the package.
243 244 245

This activates input method defined by PACKAGE-NAME by running
`quail-activate', which see."
246 247 248 249 250 251 252 253 254 255 256 257
  (let ((package (quail-package package-name)))
    (if (null package)
	;; Perhaps we have not yet loaded necessary libraries.
	(while libraries
	  (if (not (load (car libraries) t))
	      (progn
		(with-output-to-temp-buffer "*Help*"
		  (princ "Quail package \"")
		  (princ package-name)
		  (princ "\" can't be activated\n  because library \"")
		  (princ (car libraries))
		  (princ "\" is not in `load-path'.
Karl Heuer's avatar
Karl Heuer committed
258 259 260 261 262 263

The most common case is that you have not yet installed appropriate
libraries in LEIM (Libraries of Emacs Input Method) which is
distributed separately from Emacs.

LEIM is available from the same ftp directory as Emacs."))
264 265
		(error "Can't use the Quail package `%s'" package-name))
	    (setq libraries (cdr libraries))))))
Karl Heuer's avatar
Karl Heuer committed
266 267
  (quail-select-package package-name)
  (setq current-input-method-title (quail-title))
268 269 270
  (quail-activate)
  ;; Hide all '... loaded' message.
  (message nil))
Karl Heuer's avatar
Karl Heuer committed
271

272
(defvar quail-translation-keymap
Karl Heuer's avatar
Karl Heuer committed
273
  (let ((map (make-keymap))
274 275 276 277
	(i 0))
    (while (< i ?\ )
      (define-key map (char-to-string i) 'quail-other-command)
      (setq i (1+ i)))
Karl Heuer's avatar
Karl Heuer committed
278 279 280
    (while (< i 127)
      (define-key map (char-to-string i) 'quail-self-insert-command)
      (setq i (1+ i)))
281
    (setq i 128)
282
    (while (< i 256)
283 284
      (define-key map (vector i) 'quail-self-insert-command)
      (setq i (1+ i)))
Karl Heuer's avatar
Karl Heuer committed
285 286 287 288 289
    (define-key map "\177" 'quail-delete-last-char)
    (define-key map "\C-f" 'quail-next-translation)
    (define-key map "\C-b" 'quail-prev-translation)
    (define-key map "\C-n" 'quail-next-translation-block)
    (define-key map "\C-p" 'quail-prev-translation-block)
290 291 292 293
    (define-key map [right] 'quail-next-translation)
    (define-key map [left] 'quail-prev-translation)
    (define-key map [down] 'quail-next-translation-block)
    (define-key map [up] 'quail-prev-translation-block)
Karl Heuer's avatar
Karl Heuer committed
294 295
    (define-key map "\C-i" 'quail-completion)
    (define-key map "\C-@" 'quail-select-current)
296 297 298 299 300 301
    ;; Following simple.el, Enter key on numeric keypad selects the
    ;; current translation just like `C-SPC', and `mouse-2' chooses
    ;; any completion visible in the *Quail Completions* buffer.
    (define-key map [kp-enter] 'quail-select-current)
    (define-key map [mouse-2] 'quail-mouse-choose-completion)
    (define-key map [down-mouse-2] nil)
Karl Heuer's avatar
Karl Heuer committed
302
    (define-key map "\C-h" 'quail-translation-help)
303
    (define-key map [?\C- ] 'quail-select-current)
Karl Heuer's avatar
Karl Heuer committed
304 305 306
    (define-key map [tab] 'quail-completion)
    (define-key map [delete] 'quail-delete-last-char)
    (define-key map [backspace] 'quail-delete-last-char)
307
    map)
308 309 310 311 312
  "Keymap used processing translation in complex Quail modes.
Only a few especially complex input methods use this map;
most use `quail-simple-translation-keymap' instead.
This map is activated while translation region is active.")

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
(defvar quail-translation-docstring
  "When you type keys, the echo area shows the possible characters
which correspond to that key sequence, each preceded by a digit.  You
can select one of the characters shown by typing the corresponding
digit.  Alternatively, you can use C-f and C-b to move through the
line to select the character you want, then type a letter to begin
entering another Chinese character or type a space or punctuation
character.

If there are more than ten possible characters for the given spelling,
the echo area shows ten characters at a time; you can use C-n to move
to the next group of ten, and C-p to move back to the previous group
of ten.")

;; Categorize each Quail commands to make the output of quail-help
;; concise.  This is done by putting `quail-help' property.  The value
;; is:
;;	hide -- never show this command
;;	non-deterministic -- show only for non-deterministic input method
(let ((l '((quail-other-command . hide)
	   (quail-self-insert-command . hide)
	   (quail-delete-last-char . hide)
	   (quail-next-translation . non-deterministic)
	   (quail-prev-translation . non-deterministic)
	   (quail-next-translation-block . non-deterministic)
	   (quail-prev-translation-block . non-deterministic))))
Kenichi Handa's avatar
Kenichi Handa committed
339
  (while l
340
    (put (car (car l)) 'quail-help (cdr (car l)))
Kenichi Handa's avatar
Kenichi Handa committed
341 342
    (setq l (cdr l))))

343
(defvar quail-simple-translation-keymap
344
  (let ((map (make-keymap))
345 346 347 348
	(i 0))
    (while (< i ?\ )
      (define-key map (char-to-string i) 'quail-other-command)
      (setq i (1+ i)))
349 350 351
    (while (< i 127)
      (define-key map (char-to-string i) 'quail-self-insert-command)
      (setq i (1+ i)))
352 353 354 355
    (setq i 128)
    (while (< i 256)
      (define-key map (vector i) 'quail-self-insert-command)
      (setq i (1+ i)))
356
    (define-key map "\177" 'quail-delete-last-char)
357 358
    (define-key map [delete] 'quail-delete-last-char)
    (define-key map [backspace] 'quail-delete-last-char)
359 360 361
    ;;(let ((meta-map (make-sparse-keymap)))
    ;;(define-key map (char-to-string meta-prefix-char) meta-map)
    ;;(define-key map [escape] meta-map))
362
    map)
363
  "Keymap used while processing translation in simple Quail modes.
364
A few especially complex input methods use `quail-translation-keymap' instead.
Karl Heuer's avatar
Karl Heuer committed
365 366
This map is activated while translation region is active.")

367
(defvar quail-conversion-keymap
Karl Heuer's avatar
Karl Heuer committed
368
  (let ((map (make-keymap))
369
	(i ?\ ))
Karl Heuer's avatar
Karl Heuer committed
370
    (while (< i 127)
371
      (define-key map (char-to-string i) 'quail-self-insert-command)
Karl Heuer's avatar
Karl Heuer committed
372
      (setq i (1+ i)))
373
    (setq i 128)
374
    (while (< i 256)
375
      (define-key map (vector i) 'quail-self-insert-command)
376
      (setq i (1+ i)))
Karl Heuer's avatar
Karl Heuer committed
377 378 379 380 381
    (define-key map "\C-b" 'quail-conversion-backward-char)
    (define-key map "\C-f" 'quail-conversion-forward-char)
    (define-key map "\C-a" 'quail-conversion-beginning-of-region)
    (define-key map "\C-e" 'quail-conversion-end-of-region)
    (define-key map "\C-d" 'quail-conversion-delete-char)
382
    (define-key map "\C-k" 'quail-conversion-delete-tail)
383
    (define-key map "\C-h" 'quail-translation-help)
Karl Heuer's avatar
Karl Heuer committed
384 385 386
    (define-key map "\177" 'quail-conversion-backward-delete-char)
    (define-key map [delete] 'quail-conversion-backward-delete-char)
    (define-key map [backspace] 'quail-conversion-backward-delete-char)
387
    map)
Karl Heuer's avatar
Karl Heuer committed
388
  "Keymap used for processing conversion in Quail mode.
Karl Heuer's avatar
Karl Heuer committed
389
This map is activated while conversion region is active but translation
Karl Heuer's avatar
Karl Heuer committed
390 391
region is not active.")

Kenichi Handa's avatar
Kenichi Handa committed
392 393 394 395 396
;; Just a dummy definition.
(defun quail-other-command ()
  (interactive)
  )

397
;;;###autoload
Karl Heuer's avatar
Karl Heuer committed
398 399 400 401 402 403
(defun quail-define-package (name language title
				  &optional guidance docstring translation-keys
				  forget-last-selection deterministic
				  kbd-translate show-layout create-decode-map
				  maximum-shortest overlay-plist
				  update-translation-function
404
				  conversion-keys simple)
Karl Heuer's avatar
Karl Heuer committed
405 406
  "Define NAME as a new Quail package for input LANGUAGE.
TITLE is a string to be displayed at mode-line to indicate this package.
407
Optional arguments are GUIDANCE, DOCSTRING, TRANSLATION-KEYS,
Karl Heuer's avatar
Karl Heuer committed
408 409
 FORGET-LAST-SELECTION, DETERMINISTIC, KBD-TRANSLATE, SHOW-LAYOUT,
 CREATE-DECODE-MAP, MAXIMUM-SHORTEST, OVERLAY-PLIST,
410
 UPDATE-TRANSLATION-FUNCTION, CONVERSION-KEYS and SIMPLE.
Karl Heuer's avatar
Karl Heuer committed
411 412 413 414 415 416 417 418 419

GUIDANCE specifies how a guidance string is shown in echo area.
If it is t, list of all possible translations for the current key is shown
 with the currently selected translation being highlighted.
If it is an alist, the element has the form (CHAR . STRING).  Each character
 in the current key is searched in the list and the corresponding string is
 shown.
If it is nil, the current key is shown.

420 421
DOCSTRING is the documentation string of this package.  The command
`describe-input-method' shows this string while replacing the form
422 423
\\=\\<VAR> in the string by the value of VAR.  That value should be a
string.  For instance, the form \\=\\<quail-translation-docstring> is
424 425
replaced by a description about how to select a translation from a
list of candidates.
Karl Heuer's avatar
Karl Heuer committed
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

TRANSLATION-KEYS specifies additional key bindings used while translation
region is active.  It is an alist of single key character vs. corresponding
command to be called.

FORGET-LAST-SELECTION non-nil means a selected translation is not kept
for the future to translate the same key.  If this flag is nil, a
translation selected for a key is remembered so that it can be the
first candidate when the same key is entered later.

DETERMINISTIC non-nil means the first candidate of translation is
selected automatically without allowing users to select another
translation for a key.  In this case, unselected translations are of
no use for an interactive use of Quail but can be used by some other
programs.  If this flag is non-nil, FORGET-LAST-SELECTION is also set
to t.

KBD-TRANSLATE non-nil means input characters are translated from a
user's keyboard layout to the standard keyboard layout.  See the
documentation of `quail-keyboard-layout' and
`quail-keyboard-layout-standard' for more detail.

SHOW-LAYOUT non-nil means the `quail-help' command should show
the user's keyboard layout visually with translated characters.
If KBD-TRANSLATE is set, it is desirable to set also this flag unless
this package defines no translations for single character keys.

CREATE-DECODE-MAP non-nil means decode map is also created.  A decode
map is an alist of translations and corresponding original keys.
Although this map is not used by Quail itself, it can be used by some
other programs.  For instance, Vietnamese supporting needs this map to
convert Vietnamese text to VIQR format which uses only ASCII
characters to represent Vietnamese characters.

MAXIMUM-SHORTEST non-nil means break key sequence to get maximum
length of the shortest sequence.  When we don't have a translation of
key \"..ABCD\" but have translations of \"..AB\" and \"CD..\", break
the key at \"..AB\" and start translation of \"CD..\".  Hangul
packages, for instance, use this facility.  If this flag is nil, we
break the key just at \"..ABC\" and start translation of \"D..\".

OVERLAY-PLIST if non-nil is a property list put on an overlay which
covers Quail translation region.

UPDATE-TRANSLATION-FUNCTION if non-nil is a function to call to update
Karl Heuer's avatar
Karl Heuer committed
471 472
the current translation region according to a new translation data.  By
default, a translated text or a user's key sequence (if no translation
Karl Heuer's avatar
Karl Heuer committed
473 474 475 476
for it) is inserted.

CONVERSION-KEYS specifies additional key bindings used while
conversion region is active.  It is an alist of single key character
477 478 479 480 481
vs. corresponding command to be called.

If SIMPLE is non-nil, then we do not alter the meanings of
commands such as C-f, C-b, C-n, C-p and TAB; they are treated as
non-Quail commands."
Karl Heuer's avatar
Karl Heuer committed
482 483 484
  (let (translation-keymap conversion-keymap)
    (if deterministic (setq forget-last-selection t))
    (if translation-keys
485
	(progn
486 487 488
	  (setq translation-keymap (copy-keymap
				    (if simple quail-simple-translation-keymap
				      quail-translation-keymap)))
489 490 491 492
	  (while translation-keys
	    (define-key translation-keymap
	      (car (car translation-keys)) (cdr (car translation-keys)))
	    (setq translation-keys (cdr translation-keys))))
493 494 495
      (setq translation-keymap
	    (if simple quail-simple-translation-keymap
	      quail-translation-keymap)))
496 497 498 499 500 501
    (when conversion-keys
      (setq conversion-keymap (copy-keymap quail-conversion-keymap))
      (while conversion-keys
	(define-key conversion-keymap
	  (car (car conversion-keys)) (cdr (car conversion-keys)))
	(setq conversion-keys (cdr conversion-keys))))
Karl Heuer's avatar
Karl Heuer committed
502 503 504 505 506 507
    (quail-add-package
     (list name title (list nil) guidance (or docstring "")
	   translation-keymap
	   forget-last-selection deterministic kbd-translate show-layout
	   (if create-decode-map (list 'decode-map) nil)
	   maximum-shortest overlay-plist update-translation-function
Kenichi Handa's avatar
Kenichi Handa committed
508
	   conversion-keymap simple))
509 510 511 512 513 514 515

    ;; Update input-method-alist.
    (let ((slot (assoc name input-method-alist))
	  (val (list language 'quail-use-package title docstring)))
      (if slot (setcdr slot val)
	(setq input-method-alist (cons (cons name val) input-method-alist)))))

Karl Heuer's avatar
Karl Heuer committed
516 517 518 519 520
  (quail-select-package name))

;; Quail minor mode handlers.

;; Setup overlays used in Quail mode.
521
(defun quail-setup-overlays (conversion-mode)
Karl Heuer's avatar
Karl Heuer committed
522 523 524
  (let ((pos (point)))
    (if (overlayp quail-overlay)
	(move-overlay quail-overlay pos pos)
525
      (setq quail-overlay (make-overlay pos pos))
526 527
      (if input-method-highlight-flag
	  (overlay-put quail-overlay 'face 'underline))
Karl Heuer's avatar
Karl Heuer committed
528 529 530 531
      (let ((l (quail-overlay-plist)))
	(while l
	  (overlay-put quail-overlay (car l) (car (cdr l)))
	  (setq l (cdr (cdr l))))))
532 533 534 535
    (if conversion-mode
	(if (overlayp quail-conv-overlay)
	    (if (not (overlay-start quail-conv-overlay))
		(move-overlay quail-conv-overlay pos pos))
536
	  (setq quail-conv-overlay (make-overlay pos pos))
537 538
	  (if input-method-highlight-flag
	      (overlay-put quail-conv-overlay 'face 'underline))))))
Karl Heuer's avatar
Karl Heuer committed
539 540 541

;; Delete overlays used in Quail mode.
(defun quail-delete-overlays ()
542
  (if (and (overlayp quail-overlay) (overlay-start quail-overlay))
Karl Heuer's avatar
Karl Heuer committed
543
      (delete-overlay quail-overlay))
544
  (if (and (overlayp quail-conv-overlay) (overlay-start quail-conv-overlay))
Karl Heuer's avatar
Karl Heuer committed
545 546
      (delete-overlay quail-conv-overlay)))

547
(defun quail-inactivate ()
548 549 550
  "Inactivate Quail input method.

This function runs the normal hook `quail-inactivate-hook'."
551 552 553 554 555
  (interactive)
  (quail-activate -1))

(defun quail-activate (&optional arg)
  "Activate Quail input method.
556
With ARG, activate Quail input method if and only if arg is positive.
557

558 559 560
This function runs `quail-activate-hook' if it activates the input
method, `quail-inactivate-hook' if it deactivates it.

561 562 563 564 565 566 567 568 569
While this input method is active, the variable
`input-method-function' is bound to the function `quail-input-method'."
  (if (and arg
	  (< (prefix-numeric-value arg) 0))
      ;; Let's inactivate Quail input method.
      (unwind-protect
	  (progn
	    (quail-delete-overlays)
	    (setq describe-current-input-method-function nil)
570 571
	    (quail-hide-guidance)
	    (remove-hook 'post-command-hook 'quail-show-guidance t)
572 573
	    (run-hooks 'quail-inactivate-hook))
	(kill-local-variable 'input-method-function))
574
    ;; Let's activate Quail input method.
Karl Heuer's avatar
Karl Heuer committed
575 576 577 578 579 580 581
    (if (null quail-current-package)
	;; Quail package is not yet selected.  Select one now.
	(let (name)
	  (if quail-package-alist
	      (setq name (car (car quail-package-alist)))
	    (error "No Quail package loaded"))
	  (quail-select-package name)))
582
    (setq inactivate-current-input-method-function 'quail-inactivate)
Karl Heuer's avatar
Karl Heuer committed
583 584
    (setq describe-current-input-method-function 'quail-help)
    (quail-delete-overlays)
585 586
    (setq quail-guidance-str "")
    (quail-show-guidance)
587 588
    ;; If we are in minibuffer, turn off the current input method
    ;; before exiting.
589 590 591
    (when (eq (selected-window) (minibuffer-window))
      (add-hook 'minibuffer-exit-hook 'quail-exit-from-minibuffer)
      (add-hook 'post-command-hook 'quail-show-guidance nil t))
592 593 594
    (run-hooks 'quail-activate-hook)
    (make-local-variable 'input-method-function)
    (setq input-method-function 'quail-input-method)))
Karl Heuer's avatar
Karl Heuer committed
595 596

(defun quail-exit-from-minibuffer ()
597
  (inactivate-input-method)
Karl Heuer's avatar
Karl Heuer committed
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
  (if (<= (minibuffer-depth) 1)
      (remove-hook 'minibuffer-exit-hook 'quail-exit-from-minibuffer)))

;; Keyboard layout translation handlers.

;; Some Quail packages provide localized keyboard simulation which
;; requires a particular keyboard layout.  In this case, what we need
;; is locations of keys the user entered, not character codes
;; generated by those keys.  However, for the moment, there's no
;; common way to get such information.  So, we ask a user to give
;; information of his own keyboard layout, then translate it to the
;; standard layout which we defined so that all Quail packages depend
;; just on it.

(defconst quail-keyboard-layout-standard
  "\
614
                              \
Karl Heuer's avatar
Karl Heuer committed
615 616 617
  1!2@3#4$5%6^7&8*9(0)-_=+`~  \
  qQwWeErRtTyYuUiIoOpP[{]}    \
  aAsSdDfFgGhHjJkKlL;:'\"\\|    \
618 619
  zZxXcCvVbBnNmM,<.>/?        \
                              "
Karl Heuer's avatar
Karl Heuer committed
620 621 622 623 624 625
  "Standard keyboard layout of printable characters Quail assumes.
See the documentation of `quail-keyboard-layout' for this format.
This layout is almost the same as that of VT100,
 but the location of key \\ (backslash) is just right of key ' (single-quote),
 not right of RETURN key.")

626
(defconst quail-keyboard-layout-len 180)
Karl Heuer's avatar
Karl Heuer committed
627 628

;; Here we provide several examples of famous keyboard layouts.
629
;; This is a candidate for a language environment-dependent setting.
Karl Heuer's avatar
Karl Heuer committed
630 631
(defvar quail-keyboard-layout-alist
  (list
Kenichi Handa's avatar
Kenichi Handa committed
632
   (cons "standard" quail-keyboard-layout-standard)
Karl Heuer's avatar
Karl Heuer committed
633
   '("sun-type3" . "\
634
                              \
Karl Heuer's avatar
Karl Heuer committed
635 636 637
  1!2@3#4$5%6^7&8*9(0)-_=+\\|`~\
  qQwWeErRtTyYuUiIoOpP[{]}    \
  aAsSdDfFgGhHjJkKlL;:'\"      \
638 639
  zZxXcCvVbBnNmM,<.>/?        \
                              ")
640 641 642 643 644 645 646
   '("atari-german" . "\
                              \
  1!2\"3\2474$5%6&7/8(9)0=\337?'`#^  \
  qQwWeErRtTzZuUiIoOpP\374\334+*    \
  aAsSdDfFgGhHjJkKlL\366\326\344\304~|    \
<>yYxXcCvVbBnNmM,;.:-_        \
                              ")
647 648 649 650 651 652 653 654 655

   '("pc102-de" . "\
                              \
^\2601!2\"3\2474$5%6&7/8(9)0=\337?\264`#'  \
  qQwWeErRtTzZuUiIoOpP\374\334+*    \
  aAsSdDfFgGhHjJkKlL\366\326\344\304      \
<>yYxXcCvVbBnNmM,;.:-_        \
                              ")

Kenichi Handa's avatar
Kenichi Handa committed
656 657 658 659 660 661 662
   '("jp106" . "\
                              \
  1!2\"3#4$5%6&7'8(9)0~-=^~\\|  \
  qQwWeErRtTyYuUiIoOpP@`[{    \
  aAsSdDfFgGhHjJkKlL;+:*]}    \
  zZxXcCvVbBnNmM,<.>/?\\_      \
                              ")
Dave Love's avatar
Dave Love committed
663 664
   '("pc105-uk" . "\
                              \
665
`\2541!2\"3\2434$5%6^7&8*9(0)-_=+    \
Dave Love's avatar
Dave Love committed
666 667 668 669
  qQwWeErRtTyYuUiIoOpP[{]}    \
  aAsSdDfFgGhHjJkKlL;:'@#~    \
\\|zZxXcCvVbBnNmM,<.>/?        \
                              ")
Kenichi Handa's avatar
Kenichi Handa committed
670
   )
Karl Heuer's avatar
Karl Heuer committed
671 672
  "Alist of keyboard names and corresponding layout strings.
See the documentation of `quail-keyboard-layout' for the format of
Kenichi Handa's avatar
Kenichi Handa committed
673 674
the layout string.")

675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
(defcustom quail-keyboard-layout quail-keyboard-layout-standard
  "A string which represents physical key layout of a particular keyboard.
We assume there are six rows and each row has 15 keys (columns),
	the first row is above the `1' - `0' row,
	the first column of the second row is left of key `1',
	the first column of the third row is left of key `q',
	the first column of the fourth row is left of key `a',
	the first column of the fifth row is left of key `z',
	the sixth row is below the `z' - `/' row.
Nth (N is even) and (N+1)th characters in the string are non-shifted
and shifted characters respectively at the same location.
The location of Nth character is row (N / 30) and column ((N mod 30) / 2).
The command `quail-set-keyboard-layout' usually sets this variable."
  :group 'quail
  :type `(choice
	  ,@(mapcar (lambda (pair)
		      (list 'const :tag (car pair) (cdr pair)))
		    quail-keyboard-layout-alist)
	  (string :tag "Other")))

Kenichi Handa's avatar
Kenichi Handa committed
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
;; A non-standard keyboard layout may miss some key locations of the
;; standard layout while having additional key locations not in the
;; standard layout.  This alist maps those additional key locations to
;; the missing locations.  The value is updated automatically by
;; quail-set-keyboard-layout.
(defvar quail-keyboard-layout-substitution nil)

(defun quail-update-keyboard-layout (kbd-type)
  (let ((layout (assoc kbd-type quail-keyboard-layout-alist)))
    (if (null layout)
	;; Here, we had better ask a user to define his own keyboard
	;; layout interactively.
	(error "Unknown keyboard type `%s'" kbd-type))
    (setq quail-keyboard-layout (cdr layout))
    (let ((i quail-keyboard-layout-len)
	  subst-list missing-list)
      ;; Sum up additional key locations not in the standard layout in
      ;; subst-list, and missing key locations in missing-list.
      (while (> i 0)
	(setq i (1- i))
	(if (= (aref quail-keyboard-layout i) ? )
	    (if (/= (aref quail-keyboard-layout-standard i) ? )
		(setq missing-list (cons i missing-list)))
	  (if (= (aref quail-keyboard-layout-standard i) ? )
	      (setq subst-list (cons (cons i nil) subst-list)))))
      (setq quail-keyboard-layout-substitution subst-list)
      ;; If there are additional key locations, map them to missing
      ;; key locations.
      (while missing-list
	(while (and subst-list (cdr (car subst-list)))
	  (setq subst-list (cdr subst-list)))
	(if subst-list
	    (setcdr (car subst-list) (car missing-list)))
	(setq missing-list (cdr missing-list))))))

(defcustom quail-keyboard-layout-type "standard"
  "Type of keyboard layout used in Quail base input method.
Available types are listed in the variable `quail-keyboard-layout-alist'."
  :group 'quail
Dave Love's avatar
Dave Love committed
734 735 736
  :type (cons 'choice (mapcar (lambda (elt)
				(list 'const (car elt)))
			      quail-keyboard-layout-alist))
Kenichi Handa's avatar
Kenichi Handa committed
737 738 739
  :set #'(lambda (symbol value)
	   (quail-update-keyboard-layout value)
	   (set symbol value)))
Karl Heuer's avatar
Karl Heuer committed
740

741
;;;###autoload
Karl Heuer's avatar
Karl Heuer committed
742 743 744 745 746 747 748 749 750
(defun quail-set-keyboard-layout (kbd-type)
  "Set the current keyboard layout to the same as keyboard KBD-TYPE.

Since some Quail packages depends on a physical layout of keys (not
characters generated by them), those are created by assuming the
standard layout defined in `quail-keyboard-layout-standard'.  This
function tells Quail system the layout of your keyboard so that what
you type is correctly handled."
  (interactive
751
   (let* ((completion-ignore-case t)
Karl Heuer's avatar
Karl Heuer committed
752 753 754
	  (type (completing-read "Keyboard type: "
				 quail-keyboard-layout-alist)))
     (list type)))
Kenichi Handa's avatar
Kenichi Handa committed
755 756
  (quail-update-keyboard-layout kbd-type)
  (setq quail-keyboard-layout-type kbd-type))
Karl Heuer's avatar
Karl Heuer committed
757

Kenichi Handa's avatar
Kenichi Handa committed
758 759
(defun quail-keyboard-translate (char)
  "Translate CHAR to the one in the standard keyboard layout."
Karl Heuer's avatar
Karl Heuer committed
760
  (if (eq quail-keyboard-layout quail-keyboard-layout-standard)
761 762
      ;; All Quail packages are designed based on
      ;; `quail-keyboard-layout-standard'.
Kenichi Handa's avatar
Kenichi Handa committed
763
      char
Karl Heuer's avatar
Karl Heuer committed
764
    (let ((i 0))
Kenichi Handa's avatar
Kenichi Handa committed
765
      ;; Find the key location on the current keyboard layout.
Karl Heuer's avatar
Karl Heuer committed
766
      (while (and (< i quail-keyboard-layout-len)
Kenichi Handa's avatar
Kenichi Handa committed
767
		  (/= char (aref quail-keyboard-layout i)))
Karl Heuer's avatar
Karl Heuer committed
768 769
	(setq i (1+ i)))
      (if (= i quail-keyboard-layout-len)
Kenichi Handa's avatar
Kenichi Handa committed
770
	  ;; CHAR is not in quail-keyboard-layout, which means that a
771
	  ;; user typed a key which generated a character code to be
Kenichi Handa's avatar
Kenichi Handa committed
772
	  ;; handled out of Quail.  Just return CHAR and make
773
	  ;; quail-execute-non-quail-command handle it correctly.
Kenichi Handa's avatar
Kenichi Handa committed
774 775 776 777 778 779 780 781 782 783 784 785
	  char
	(let ((ch (aref quail-keyboard-layout-standard i)))
	  (if (= ch ?\ )
	      ;; This location not available in the standard keyboard
	      ;; layout.  Check if the location is used to substitute
	      ;; for the other location of the standard layout.
	      (if (setq i (cdr (assq i quail-keyboard-layout-substitution)))
		  (aref quail-keyboard-layout-standard i)
		;; Just return CHAR as well as above.
		char)
	    ch))))))

786 787 788 789 790
(defun quail-keyseq-translate (keyseq)
  (apply 'string
	 (mapcar (function (lambda (x) (quail-keyboard-translate x)))
		 keyseq)))

Kenichi Handa's avatar
Kenichi Handa committed
791
(defun quail-insert-kbd-layout (kbd-layout)
Dave Love's avatar
Dave Love committed
792 793
"Insert the visual keyboard layout table according to KBD-LAYOUT.
The format of KBD-LAYOUT is the same as `quail-keyboard-layout'."
Kenichi Handa's avatar
Kenichi Handa committed
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
  (let (done-list layout i ch)
    ;; At first, convert KBD-LAYOUT to the same size vector that
    ;; contains translated character or string.
    (setq layout (string-to-vector kbd-layout)
	  i 0)
    (while (< i quail-keyboard-layout-len)
      (setq ch (aref kbd-layout i))
      (if (quail-kbd-translate)
	  (setq ch (quail-keyboard-translate ch)))
      (let* ((map (cdr (assq ch (cdr (quail-map)))))
	     (translation (and map (quail-get-translation
				    (car map) (char-to-string ch) 1))))
	(if translation
	    (progn
	      (if (consp translation)
809 810 811
		  (if (> (length (cdr translation)) 0)
		      (setq translation (aref (cdr translation) 0))
		    (setq translation " ")))
Kenichi Handa's avatar
Kenichi Handa committed
812
	      (setq done-list (cons translation done-list)))
813
	  (setq translation (aref kbd-layout i)))
Kenichi Handa's avatar
Kenichi Handa committed
814 815 816 817 818 819 820
	(aset layout i translation))
      (setq i (1+ i)))

    (let ((pos (point))
	  (bar "|")
	  lower upper row)
      ;; Make table without horizontal lines.  Each column for a key
U. Ser's avatar
U. Ser committed
821
      ;; has the form "| LU |" where L is for lower key and U is
Kenichi Handa's avatar
Kenichi Handa committed
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
      ;; for a upper key.  If width of L (U) is greater than 1,
      ;; preceding (following) space is not inserted.
      (put-text-property 0 1 'face 'bold bar)
      (setq i 0)
      (while (< i quail-keyboard-layout-len)
	(when (= (% i 30) 0)
	  (setq row (/ i 30))
	  (if (> row 1)
	      (insert-char 32 (+ row (/ (- row 2) 2)))))
	(setq lower (aref layout i)
	      upper (aref layout (1+ i)))
	(insert bar)
	(if (= (if (stringp lower) (string-width lower) (char-width lower)) 1)
	    (insert " "))
	(insert lower upper)
	(if (= (if (stringp upper) (string-width upper) (char-width upper)) 1)
	    (insert " "))
	(setq i (+ i 2))
	(if (= (% i 30) 0)
	    (insert bar "\n")))
      ;; Insert horizontal lines while deleting blank key columns at the
      ;; beginning and end of each line.
      (save-restriction
	(narrow-to-region pos (point))
	(goto-char pos)
	;;(while (looking-at "[| ]*$")
	;;(forward-line 1)
	;;(delete-region pos (point)))
	(let ((from1 100) (to1 0) from2 to2)
	  (while (not (eobp))
	    (if (looking-at "[| ]*$")
		;; The entire row is blank.
		(delete-region (point) (match-end 0))
	      ;; Delete blank key columns at the head.
	      (if (looking-at " *\\(|    \\)+")
		  (subst-char-in-region (point) (match-end 0) ?| ? ))
	      ;; Delete blank key columns at the tail.
	      (if (re-search-forward "\\(    |\\)+$" (line-end-position) t)
		  (delete-region (match-beginning 0) (point)))
	      (beginning-of-line))
	    ;; Calculate the start and end columns of a horizontal line.
	    (if (eolp)
		(setq from2 from1 to2 to1)
	      (skip-chars-forward " ")
	      (setq from2 (current-column))
	      (end-of-line)
	      (setq to2 (current-column))
	      (if (< from2 from1)
		  (setq from1 from2))
	      (if (> to2 to1)
		  (setq to1 to2))
	      (beginning-of-line))
	    ;; If the previous or the current line has at least one key
	    ;; column, insert a horizontal line.
	    (when (> to1 0)
	      (insert-char 32 from1)
	      (setq pos (point))
	      (insert "+")
	      (insert-char ?- (- (- to1 from1) 2))
	      (insert "+")
	      (put-text-property pos (point) 'face 'bold)
	      (insert "\n"))
	    (setq from1 from2 to1 to2)
	    (forward-line 1)))
	;; Insert "space bar" box.
	(forward-line -1)
	(setq pos (point))
	(insert
"		    +-----------------------------+
		    |          space bar          |
		    +-----------------------------+
")
	(put-text-property pos (point) 'face 'bold)
	(insert ?\n)))

    done-list))

;;;###autoload
(defun quail-show-keyboard-layout (&optional keyboard-type)
901 902 903 904
  "Show the physical layout of the keyboard type KEYBOARD-TYPE.

The variable `quail-keyboard-layout-type' holds the currently selected
keyboard type."
Kenichi Handa's avatar
Kenichi Handa committed
905
  (interactive
906
   (list (completing-read "Keyboard type (default current choice): "
Kenichi Handa's avatar
Kenichi Handa committed
907 908 909 910 911 912 913 914
			  quail-keyboard-layout-alist
			  nil t)))
  (or (and keyboard-type (> (length keyboard-type) 0))
      (setq keyboard-type quail-keyboard-layout-type))
  (let ((layout (assoc keyboard-type quail-keyboard-layout-alist)))
    (or layout
	(error "Unknown keyboard type: %s" keyboard-type))
    (with-output-to-temp-buffer "*Help*"
915
      (with-current-buffer standard-output
Kenichi Handa's avatar
Kenichi Handa committed
916 917 918 919
	(insert "Keyboard layout (keyboard type: "
		keyboard-type
		")\n")
	(quail-insert-kbd-layout (cdr layout))))))
Karl Heuer's avatar
Karl Heuer committed
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942

;; Quail map

(defsubst quail-map-p (object)
  "Return t if OBJECT is a Quail map.

A Quail map holds information how a particular key should be translated.
Its format is (TRANSLATION . ALIST).
TRANSLATION is either a character, or a cons (INDEX . VECTOR).
In the latter case, each element of VECTOR is a candidate for the translation,
and INDEX points the currently selected translation.

ALIST is normally a list of elements that look like (CHAR . DEFN),
where DEFN is another Quail map for a longer key (CHAR added to the
current key).  It may also be a symbol of a function which returns an
alist of the above format.

Just after a Quail package is read, TRANSLATION may be a string or a
vector.  Then each element of the string or vector is a candidate for
the translation.  These objects are transformed to cons cells in the
format \(INDEX . VECTOR), as described above."
  (and (consp object)
       (let ((translation (car object)))
943
	 (or (integerp translation) (null translation)
Karl Heuer's avatar
Karl Heuer committed
944
	     (vectorp translation) (stringp translation)
945 946
	     (symbolp translation)
	     (and (consp translation) (not (vectorp (cdr translation))))))
Karl Heuer's avatar
Karl Heuer committed
947
       (let ((alist (cdr object)))
948 949
	 (or (and (listp alist) (consp (car alist)))
	     (symbolp alist)))))
Karl Heuer's avatar
Karl Heuer committed
950

951
;;;###autoload
Karl Heuer's avatar
Karl Heuer committed
952 953 954 955 956
(defmacro quail-define-rules (&rest rules)
  "Define translation rules of the current Quail package.
Each argument is a list of KEY and TRANSLATION.
KEY is a string meaning a sequence of keystrokes to be translated.
TRANSLATION is a character, a string, a vector, a Quail map, or a function.
957
If it is a character, it is the sole translation of KEY.
Karl Heuer's avatar
Karl Heuer committed
958 959 960 961 962 963
If it is a string, each character is a candidate for the translation.
If it is a vector, each element (string or character) is a candidate
  for the translation.
In these cases, a key specific Quail map is generated and assigned to KEY.

If TRANSLATION is a Quail map or a function symbol which returns a Quail map,
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
 it is used to handle KEY.

The first argument may be an alist of annotations for the following
rules.  Each element has the form (ANNOTATION . VALUE), where
ANNOTATION is a symbol indicating the annotation type.  Currently
the following annotation types are supported.

  append -- the value non-nil means that the following rules should
	be appended to the rules of the current Quail package.

  face -- the value is a face to use for displaying TRANSLATIONs in
	candidate list.

  advice -- the value is a function to call after one of RULES is
	selected.  The function is called with one argument, the
	selected TRANSLATION string, after the TRANSLATION is
	inserted.

  no-decode-map --- the value non-nil means that decoding map is not
	generated for the following translations."
  (let ((l rules)
	append no-decode-map props)
    ;; If the first argument is an alist of annotations, handle them.
    (if (consp (car (car l)))
	(let ((annotations (car l)))
	  (setq append (assq 'append annotations))
	  (if append
	      (setq annotations (delete append annotations)
		    append (cdr append)))
	  (setq no-decode-map (assq 'no-decode-map annotations))
	  (if no-decode-map
	      (setq annotations (delete no-decode-map annotations)
		    no-decode-map (cdr no-decode-map)))
997 998
	  ;; Convert the remaining annotations to property list PROPS.
	  (dolist (annotation annotations)
999
	    (setq props
1000 1001 1002
		  (cons (car annotation)
			(cons (cdr annotation)
			      props))))
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
	  (setq l (cdr l))))
    ;; Process the remaining arguments one by one.
    (if append
	;; There's no way to add new rules at compiling time.
	`(let ((tail ',l)
	       (map (quail-map))
	       (decode-map (and (quail-decode-map) (not ,no-decode-map)))
	       (properties ',props)
	       key trans)
	   (while tail
	     (setq key (car (car tail)) trans (car (cdr (car tail)))
		   tail (cdr tail))
	     (quail-defrule-internal key trans map t decode-map properties)))
      ;; We can build up quail map and decode map at compiling time.
      (let ((map (list nil))
	    (decode-map (if (not no-decode-map) (list 'decode-map)))
	    key trans)
Karl Heuer's avatar
Karl Heuer committed
1020
	(while l
1021 1022
	  (setq key (car (car l)) trans (car (cdr (car l))) l (cdr l))
	  (quail-defrule-internal key trans map t decode-map props))
1023 1024
	`(if (prog1 (quail-decode-map)
	       (quail-install-map ',map))
1025
	   (quail-install-decode-map ',decode-map))))))
Karl Heuer's avatar
Karl Heuer committed
1026

1027
;;;###autoload
1028
(defun quail-install-map (map &optional name)
Karl Heuer's avatar
Karl Heuer committed
1029
  "Install the Quail map MAP in the current Quail package.
1030 1031 1032 1033

Optional 2nd arg NAME, if non-nil, is a name of Quail package for
which to install MAP.

Karl Heuer's avatar
Karl Heuer committed
1034 1035 1036 1037 1038 1039 1040
The installed map can be referred by the function `quail-map'."
  (if (null quail-current-package)
      (error "No current Quail package"))
  (if (null (quail-map-p map))
      (error "Invalid Quail map `%s'" map))
  (setcar (cdr (cdr quail-current-package)) map))

1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
;;;###autoload
(defun quail-install-decode-map (decode-map &optional name)
  "Install the Quail decode map DECODE-MAP in the current Quail package.

Optional 2nd arg NAME, if non-nil, is a name of Quail package for
which to install MAP.

The installed decode map can be referred by the function `quail-decode-map'."
  (if (null quail-current-package)
      (error "No current Quail package"))
1051 1052 1053 1054 1055 1056 1057
  (if (if (consp decode-map)
	  (eq (car decode-map) 'decode-map)
	(if (char-table-p decode-map)
	    (eq (char-table-subtype decode-map) 'quail-decode-map)))
      (setcar (nthcdr 10 quail-current-package) decode-map)
    (error "Invalid Quail decode map `%s'" decode-map)))

1058

1059
;;;###autoload
1060
(defun quail-defrule (key translation &optional name append)
Karl Heuer's avatar
Karl Heuer committed
1061 1062
  "Add one translation rule, KEY to TRANSLATION, in the current Quail package.
KEY is a string meaning a sequence of keystrokes to be translated.
1063
TRANSLATION is a character, a string, a vector, a Quail map,
1064
 a function, or a cons.
Karl Heuer's avatar
Karl Heuer committed
1065 1066 1067
It it is a character, it is the sole translation of KEY.
If it is a string, each character is a candidate for the translation.
If it is a vector, each element (string or character) is a candidate
1068
 for the translation.
1069
If it is a cons, the car is one of the above and the cdr is a function
1070 1071 1072
 to call when translating KEY (the return value is assigned to the
 variable `quail-current-data').  If the cdr part is not a function,
 the value itself is assigned to `quail-current-data'.
Karl Heuer's avatar
Karl Heuer committed
1073 1074 1075 1076
In these cases, a key specific Quail map is generated and assigned to KEY.

If TRANSLATION is a Quail map or a function symbol which returns a Quail map,
 it is used to handle KEY.
1077 1078

Optional 3rd argument NAME, if specified, says which Quail package
Karl Heuer's avatar
Karl Heuer committed
1079
to define this translation rule in.  The default is to define it in the
1080 1081 1082 1083
current Quail package.

Optional 4th argument APPEND, if non-nil, appends TRANSLATION
to the current translations for KEY instead of replacing them."
Karl Heuer's avatar
Karl Heuer committed
1084 1085 1086 1087 1088
  (if name
      (let ((package (quail-package name)))
	(if (null package)
	    (error "No Quail package `%s'" name))
	(setq quail-current-package package)))
1089
  (quail-defrule-internal key translation (quail-map) append))
Karl Heuer's avatar
Karl Heuer committed
1090

Stefan Monnier's avatar
Stefan Monnier committed
1091 1092
(defun quail-vunion (v1 v2)
  (apply 'vector
1093 1094 1095 1096
         ;; No idea why this was here, but it seems to cause the
         ;; incorrect ordering, according to Nils Anders Danielsson.
         ;; (nreverse
         (delete-dups (nconc (append v1 ()) (append v2 ()))))) ;; )
Stefan Monnier's avatar
Stefan Monnier committed
1097

1098
;;;###autoload
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
(defun quail-defrule-internal (key trans map &optional append decode-map props)
  "Define KEY as TRANS in a Quail map MAP.

If Optional 4th arg APPEND is non-nil, TRANS is appended to the
current translations for KEY instead of replacing them.

Optional 5th arg DECODE-MAP is a Quail decode map.

Optional 6th arg PROPS is a property list annotating TRANS.  See the
function `quail-define-rules' for the detail."
1109
  (if (not (or (stringp key) (vectorp key)))
1110
      (error "Invalid Quail key `%s'" key))
Karl Heuer's avatar
Karl Heuer committed
1111
  (if (not (or (numberp trans) (stringp trans) (vectorp trans)
1112
	       (consp trans)
Karl Heuer's avatar
Karl Heuer committed
1113 1114 1115 1116 1117 1118 1119 1120
	       (symbolp trans)
	       (quail-map-p trans)))
      (error "Invalid Quail translation `%s'" trans))
  (if (null (quail-map-p map))
      (error "Invalid Quail map `%s'" map))
  (let ((len (length key))
	(idx 0)
	ch entry)
1121
    ;; Make a map for registering TRANS if necessary.
Karl Heuer's avatar
Karl Heuer committed
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
    (while (< idx len)
      (if (null (consp map))
	  ;; We come here, for example, when we try to define a rule
	  ;; for "ABC" but a rule for "AB" is already defined as a
	  ;; symbol.
	  (error "Quail key %s is too long" key))
      (setq ch (aref key idx)
	    entry (assq ch (cdr map)))
      (if (null entry)
	  (progn
	    (setq entry (cons ch (list nil)))
	    (setcdr map (cons entry (cdr map)))))
      (setq map (cdr entry))
      (setq idx (1+ idx)))
    (if (symbolp trans)
	(if (cdr map)
	    ;; We come here, for example, when we try to define a rule
	    ;; for "AB" as a symbol but a rule for "ABC" is already
	    ;; defined.
	    (error "Quail key %s is too short" key)
	  (setcdr entry trans))
      (if (quail-map-p trans)
	  (if (not (listp (cdr map)))
	      ;; We come here, for example, when we try to define a rule
	      ;; for "AB" as a symbol but a rule for "ABC" is already
	      ;; defined.
	      (error "Quail key %s is too short" key)
	    (if (not (listp (cdr trans)))
		(if (cdr map)
		    ;; We come here, for example, when we try to
		    ;; define a rule for "AB" as a symbol but a rule
		    ;; for "ABC" is already defined.
		    (error "Quail key %s is too short" key)
		  (setcdr entry trans))
	      (setcdr entry (append trans (cdr map)))))
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
	;; If PROPS is non-nil or DECODE-MAP is non-nil, convert TRANS
	;; to a vector of strings, add PROPS to each string and record
	;; this rule in DECODE-MAP.
	(when (and (or props decode-map)
		   (not (consp trans)) (not (symbolp trans)))
	  (if (integerp trans)
	      (setq trans (vector trans))
	    (if (stringp trans)
		(setq trans (string-to-vector trans))))
	  (let ((len (length trans))
		elt)
	    (while (> len 0)
	      (setq len (1- len))
	      (setq elt (aref trans len))
	      (if (integerp elt)
		  (setq elt (char-to-string elt)))
	      (aset trans len elt)
	      (if props
		  (add-text-properties 0 (length elt) props elt))
	      (if decode-map
		  (setcdr decode-map
			  (cons (cons elt key) (cdr decode-map)))))))
1179
	(if (and (car map) append)
Stefan Monnier's avatar
Stefan Monnier committed
1180 1181 1182 1183
	    (let* ((prev (quail-get-translation (car map) key len))
                   (prevchars (if (integerp prev)
                                  (vector prev)
                                (cdr prev))))
1184 1185 1186 1187
	      (if (integerp trans)
		  (setq trans (vector trans))
		(if (stringp trans)
		    (setq trans (string-to-vector trans))))
Stefan Monnier's avatar
Stefan Monnier committed
1188
              (let ((new (quail-vunion prevchars trans)))
1189
	      (setq trans
Stefan Monnier's avatar
Stefan Monnier committed
1190 1191 1192 1193
                      (if (equal new prevchars)
                          ;; Nothing to change, get back to orig value.
                          prev
                        (cons (list 0 0 0 0 nil) new))))))
1194
	(setcar map trans)))))
Karl Heuer's avatar
Karl Heuer committed
1195

1196 1197
(defun quail-get-translation (def key len)
  "Return the translation specified as DEF for KEY of length LEN.
Karl Heuer's avatar
Karl Heuer committed
1198 1199 1200 1201
The translation is either a character or a cons of the form (INDEX . VECTOR),
where VECTOR is a vector of candidates (character or string) for
the translation, and INDEX points into VECTOR to specify the currently
selected translation."
1202
  (if (and def (symbolp def))
1203 1204 1205 1206
      (if (functionp def)
	  ;; DEF is a symbol of a function which returns valid translation.
	  (setq def (funcall def key len))
	(setq def nil)))
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
  (if (and (consp def) (not (vectorp (cdr def))))
      (setq def (car def)))

  (cond
   ((or (integerp def) (consp def))
    def)

   ((null def)
    ;; No translation.
    nil)

   ((stringp def)
Kenichi Handa's avatar
Kenichi Handa committed
1219 1220
    ;; If the length is 1, we don't need vector but a single candidate
    ;; as the translation.