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

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

;; 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
11
;; Keywords: mule, multilingual, input method, i18n
Karl Heuer's avatar
Karl Heuer committed
12 13 14 15 16 17 18 19 20 21 22 23 24 25

;; This file is part of GNU Emacs.

;; GNU Emacs is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.

;; 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
Karl Heuer's avatar
Karl Heuer committed
26
;; along with GNU Emacs; see the file COPYING.  If not, write to the
Lute Kamstra's avatar
Lute Kamstra committed
27 28
;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.
Karl Heuer's avatar
Karl Heuer committed
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

;;; 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
46 47 48 49 50 51 52 53
;; [There was an input method for Mule 2.3 called `Tamago' from the
;; Japanese `TAkusan MAtasete GOmenasai', or `Sorry for having you
;; 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
54 55
;;; Code:

56 57
(require 'help-mode)

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
;;;###autoload
(defun quail-title ()
Karl Heuer's avatar
Karl Heuer committed
141
  "Return the title of the current Quail package."
142 143 144 145 146 147 148 149
  (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
150
	   (lambda (x)
151 152 153 154 155 156 157
	     (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
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
(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
207 208 209
(defsubst quail-simple ()
  "Return t if the current Quail package is simple."
  (nth 15 quail-current-package))
Karl Heuer's avatar
Karl Heuer committed
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233

(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.
234 235 236 237
The remaining arguments are libraries to be loaded before using the package.

This activates input method defined by PACKAGE-NAME by running
`quail-activate', which see."
238 239 240 241 242 243 244 245 246 247 248 249
  (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
250 251 252 253 254 255

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."))
256 257
		(error "Can't use the Quail package `%s'" package-name))
	    (setq libraries (cdr libraries))))))
Karl Heuer's avatar
Karl Heuer committed
258 259
  (quail-select-package package-name)
  (setq current-input-method-title (quail-title))
260 261 262
  (quail-activate)
  ;; Hide all '... loaded' message.
  (message nil))
Karl Heuer's avatar
Karl Heuer committed
263

264
(defvar quail-translation-keymap
Karl Heuer's avatar
Karl Heuer committed
265
  (let ((map (make-keymap))
266 267 268 269
	(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
270 271 272
    (while (< i 127)
      (define-key map (char-to-string i) 'quail-self-insert-command)
      (setq i (1+ i)))
273
    (setq i 128)
274
    (while (< i 256)
275 276
      (define-key map (vector i) 'quail-self-insert-command)
      (setq i (1+ i)))
Karl Heuer's avatar
Karl Heuer committed
277 278 279 280 281
    (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)
282 283 284 285
    (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
286 287
    (define-key map "\C-i" 'quail-completion)
    (define-key map "\C-@" 'quail-select-current)
288 289 290 291 292 293
    ;; 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
294
    (define-key map "\C-h" 'quail-translation-help)
295
    (define-key map [?\C- ] 'quail-select-current)
Karl Heuer's avatar
Karl Heuer committed
296 297 298
    (define-key map [tab] 'quail-completion)
    (define-key map [delete] 'quail-delete-last-char)
    (define-key map [backspace] 'quail-delete-last-char)
299
    map)
300 301 302 303 304
  "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.")

305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
(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
331
  (while l
332
    (put (car (car l)) 'quail-help (cdr (car l)))
Kenichi Handa's avatar
Kenichi Handa committed
333 334
    (setq l (cdr l))))

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

359
(defvar quail-conversion-keymap
Karl Heuer's avatar
Karl Heuer committed
360
  (let ((map (make-keymap))
361
	(i ?\ ))
Karl Heuer's avatar
Karl Heuer committed
362
    (while (< i 127)
363
      (define-key map (char-to-string i) 'quail-self-insert-command)
Karl Heuer's avatar
Karl Heuer committed
364
      (setq i (1+ i)))
365
    (setq i 128)
366
    (while (< i 256)
367
      (define-key map (vector i) 'quail-self-insert-command)
368
      (setq i (1+ i)))
Karl Heuer's avatar
Karl Heuer committed
369 370 371 372 373
    (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)
374
    (define-key map "\C-k" 'quail-conversion-delete-tail)
375
    (define-key map "\C-h" 'quail-translation-help)
Karl Heuer's avatar
Karl Heuer committed
376 377 378
    (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)
379
    map)
Karl Heuer's avatar
Karl Heuer committed
380
  "Keymap used for processing conversion in Quail mode.
Karl Heuer's avatar
Karl Heuer committed
381
This map is activated while conversion region is active but translation
Karl Heuer's avatar
Karl Heuer committed
382 383
region is not active.")

Kenichi Handa's avatar
Kenichi Handa committed
384 385 386 387 388
;; Just a dummy definition.
(defun quail-other-command ()
  (interactive)
  )

389
;;;###autoload
Karl Heuer's avatar
Karl Heuer committed
390 391 392 393 394 395
(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
396
				  conversion-keys simple)
Karl Heuer's avatar
Karl Heuer committed
397 398
  "Define NAME as a new Quail package for input LANGUAGE.
TITLE is a string to be displayed at mode-line to indicate this package.
399
Optional arguments are GUIDANCE, DOCSTRING, TRANSLATION-KEYS,
Karl Heuer's avatar
Karl Heuer committed
400 401
 FORGET-LAST-SELECTION, DETERMINISTIC, KBD-TRANSLATE, SHOW-LAYOUT,
 CREATE-DECODE-MAP, MAXIMUM-SHORTEST, OVERLAY-PLIST,
402
 UPDATE-TRANSLATION-FUNCTION, CONVERSION-KEYS and SIMPLE.
Karl Heuer's avatar
Karl Heuer committed
403 404 405 406 407 408 409 410 411

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.

412 413
DOCSTRING is the documentation string of this package.  The command
`describe-input-method' shows this string while replacing the form
414 415
\\=\\<VAR> in the string by the value of VAR.  That value should be a
string.  For instance, the form \\=\\<quail-translation-docstring> is
416 417
replaced by a description about how to select a translation from a
list of candidates.
Karl Heuer's avatar
Karl Heuer committed
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462

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
463 464
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
465 466 467 468
for it) is inserted.

CONVERSION-KEYS specifies additional key bindings used while
conversion region is active.  It is an alist of single key character
469 470 471 472 473
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
474 475 476
  (let (translation-keymap conversion-keymap)
    (if deterministic (setq forget-last-selection t))
    (if translation-keys
477
	(progn
478 479 480
	  (setq translation-keymap (copy-keymap
				    (if simple quail-simple-translation-keymap
				      quail-translation-keymap)))
481 482 483 484
	  (while translation-keys
	    (define-key translation-keymap
	      (car (car translation-keys)) (cdr (car translation-keys)))
	    (setq translation-keys (cdr translation-keys))))
485 486 487
      (setq translation-keymap
	    (if simple quail-simple-translation-keymap
	      quail-translation-keymap)))
488 489 490 491 492 493
    (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
494 495 496 497 498 499
    (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
500
	   conversion-keymap simple))
501 502 503 504 505 506 507

    ;; 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
508 509 510 511 512
  (quail-select-package name))

;; Quail minor mode handlers.

;; Setup overlays used in Quail mode.
513
(defun quail-setup-overlays (conversion-mode)
Karl Heuer's avatar
Karl Heuer committed
514 515 516
  (let ((pos (point)))
    (if (overlayp quail-overlay)
	(move-overlay quail-overlay pos pos)
517
      (setq quail-overlay (make-overlay pos pos))
518 519
      (if input-method-highlight-flag
	  (overlay-put quail-overlay 'face 'underline))
Karl Heuer's avatar
Karl Heuer committed
520 521 522 523
      (let ((l (quail-overlay-plist)))
	(while l
	  (overlay-put quail-overlay (car l) (car (cdr l)))
	  (setq l (cdr (cdr l))))))
524 525 526 527
    (if conversion-mode
	(if (overlayp quail-conv-overlay)
	    (if (not (overlay-start quail-conv-overlay))
		(move-overlay quail-conv-overlay pos pos))
528
	  (setq quail-conv-overlay (make-overlay pos pos))
529 530
	  (if input-method-highlight-flag
	      (overlay-put quail-conv-overlay 'face 'underline))))))
Karl Heuer's avatar
Karl Heuer committed
531 532 533

;; Delete overlays used in Quail mode.
(defun quail-delete-overlays ()
534
  (if (and (overlayp quail-overlay) (overlay-start quail-overlay))
Karl Heuer's avatar
Karl Heuer committed
535
      (delete-overlay quail-overlay))
536
  (if (and (overlayp quail-conv-overlay) (overlay-start quail-conv-overlay))
Karl Heuer's avatar
Karl Heuer committed
537 538
      (delete-overlay quail-conv-overlay)))

539
(defun quail-inactivate ()
540 541 542
  "Inactivate Quail input method.

This function runs the normal hook `quail-inactivate-hook'."
543 544 545 546 547 548 549
  (interactive)
  (quail-activate -1))

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

550 551 552
This function runs `quail-activate-hook' if it activates the input
method, `quail-inactivate-hook' if it deactivates it.

553 554 555 556 557 558 559 560 561
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)
562 563
	    (quail-hide-guidance)
	    (remove-hook 'post-command-hook 'quail-show-guidance t)
564 565
	    (run-hooks 'quail-inactivate-hook))
	(kill-local-variable 'input-method-function))
566
    ;; Let's activate Quail input method.
Karl Heuer's avatar
Karl Heuer committed
567 568 569 570 571 572 573
    (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)))
574
    (setq inactivate-current-input-method-function 'quail-inactivate)
Karl Heuer's avatar
Karl Heuer committed
575 576
    (setq describe-current-input-method-function 'quail-help)
    (quail-delete-overlays)
577 578
    (setq quail-guidance-str "")
    (quail-show-guidance)
579 580
    ;; If we are in minibuffer, turn off the current input method
    ;; before exiting.
581 582 583
    (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))
584 585 586
    (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
587 588

(defun quail-exit-from-minibuffer ()
589
  (inactivate-input-method)
Karl Heuer's avatar
Karl Heuer committed
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
  (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
  "\
606
                              \
Karl Heuer's avatar
Karl Heuer committed
607 608 609
  1!2@3#4$5%6^7&8*9(0)-_=+`~  \
  qQwWeErRtTyYuUiIoOpP[{]}    \
  aAsSdDfFgGhHjJkKlL;:'\"\\|    \
610 611
  zZxXcCvVbBnNmM,<.>/?        \
                              "
Karl Heuer's avatar
Karl Heuer committed
612 613 614 615 616 617
  "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.")

618
(defconst quail-keyboard-layout-len 180)
Karl Heuer's avatar
Karl Heuer committed
619 620

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

   '("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
648 649 650 651 652 653 654
   '("jp106" . "\
                              \
  1!2\"3#4$5%6&7'8(9)0~-=^~\\|  \
  qQwWeErRtTyYuUiIoOpP@`[{    \
  aAsSdDfFgGhHjJkKlL;+:*]}    \
  zZxXcCvVbBnNmM,<.>/?\\_      \
                              ")
Dave Love's avatar
Dave Love committed
655 656
   '("pc105-uk" . "\
                              \
Dave Love's avatar
Dave Love committed
657
`\2541!2\"3\2434$5%6^7&8*9(0)-_=+     \
Dave Love's avatar
Dave Love committed
658 659 660 661
  qQwWeErRtTyYuUiIoOpP[{]}    \
  aAsSdDfFgGhHjJkKlL;:'@#~    \
\\|zZxXcCvVbBnNmM,<.>/?        \
                              ")
Kenichi Handa's avatar
Kenichi Handa committed
662
   )
Karl Heuer's avatar
Karl Heuer committed
663 664
  "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
665 666
the layout string.")

667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
(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
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
;; 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
726 727 728
  :type (cons 'choice (mapcar (lambda (elt)
				(list 'const (car elt)))
			      quail-keyboard-layout-alist))
Kenichi Handa's avatar
Kenichi Handa committed
729 730 731
  :set #'(lambda (symbol value)
	   (quail-update-keyboard-layout value)
	   (set symbol value)))
Karl Heuer's avatar
Karl Heuer committed
732

733
;;;###autoload
Karl Heuer's avatar
Karl Heuer committed
734 735 736 737 738 739 740 741 742
(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
743
   (let* ((completion-ignore-case t)
Karl Heuer's avatar
Karl Heuer committed
744 745 746
	  (type (completing-read "Keyboard type: "
				 quail-keyboard-layout-alist)))
     (list type)))
Kenichi Handa's avatar
Kenichi Handa committed
747 748
  (quail-update-keyboard-layout kbd-type)
  (setq quail-keyboard-layout-type kbd-type))
Karl Heuer's avatar
Karl Heuer committed
749

Kenichi Handa's avatar
Kenichi Handa committed
750 751
(defun quail-keyboard-translate (char)
  "Translate CHAR to the one in the standard keyboard layout."
Karl Heuer's avatar
Karl Heuer committed
752
  (if (eq quail-keyboard-layout quail-keyboard-layout-standard)
753 754
      ;; All Quail packages are designed based on
      ;; `quail-keyboard-layout-standard'.
Kenichi Handa's avatar
Kenichi Handa committed
755
      char
Karl Heuer's avatar
Karl Heuer committed
756
    (let ((i 0))
Kenichi Handa's avatar
Kenichi Handa committed
757
      ;; Find the key location on the current keyboard layout.
Karl Heuer's avatar
Karl Heuer committed
758
      (while (and (< i quail-keyboard-layout-len)
Kenichi Handa's avatar
Kenichi Handa committed
759
		  (/= char (aref quail-keyboard-layout i)))
Karl Heuer's avatar
Karl Heuer committed
760 761
	(setq i (1+ i)))
      (if (= i quail-keyboard-layout-len)
Kenichi Handa's avatar
Kenichi Handa committed
762
	  ;; CHAR is not in quail-keyboard-layout, which means that a
763
	  ;; user typed a key which generated a character code to be
Kenichi Handa's avatar
Kenichi Handa committed
764
	  ;; handled out of Quail.  Just return CHAR and make
765
	  ;; quail-execute-non-quail-command handle it correctly.
Kenichi Handa's avatar
Kenichi Handa committed
766 767 768 769 770 771 772 773 774 775 776 777
	  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))))))

778 779 780 781 782
(defun quail-keyseq-translate (keyseq)
  (apply 'string
	 (mapcar (function (lambda (x) (quail-keyboard-translate x)))
		 keyseq)))

Kenichi Handa's avatar
Kenichi Handa committed
783
(defun quail-insert-kbd-layout (kbd-layout)
Dave Love's avatar
Dave Love committed
784 785
"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
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
  (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)
		  (setq translation (aref (cdr translation) 0)))
	      (setq done-list (cons translation done-list)))
	  (setq translation ch))
	(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
      ;; has the form "| LU |" where L is for lower key and and U is
      ;; 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)))
	(if (and (integerp lower) (>= lower 128) (< lower 256))
	    (setq lower (unibyte-char-to-multibyte lower)))
	(if (and (integerp upper) (>= upper 128) (< upper 256))
	    (setq upper (unibyte-char-to-multibyte upper)))
	(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)
895 896 897 898
  "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
899
  (interactive
900
   (list (completing-read "Keyboard type (default current choice): "
Kenichi Handa's avatar
Kenichi Handa committed
901 902 903 904 905 906 907 908
			  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*"
909
      (with-current-buffer standard-output
Kenichi Handa's avatar
Kenichi Handa committed
910 911 912 913
	(insert "Keyboard layout (keyboard type: "
		keyboard-type
		")\n")
	(quail-insert-kbd-layout (cdr layout))))))
Karl Heuer's avatar
Karl Heuer committed
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936

;; 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)))
937
	 (or (integerp translation) (null translation)
Karl Heuer's avatar
Karl Heuer committed
938
	     (vectorp translation) (stringp translation)
939 940
	     (symbolp translation)
	     (and (consp translation) (not (vectorp (cdr translation))))))
Karl Heuer's avatar
Karl Heuer committed
941
       (let ((alist (cdr object)))
942 943
	 (or (and (listp alist) (consp (car alist)))
	     (symbolp alist)))))
Karl Heuer's avatar
Karl Heuer committed
944

945
;;;###autoload
Karl Heuer's avatar
Karl Heuer committed
946 947 948 949 950
(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.
951
If it is a character, it is the sole translation of KEY.
Karl Heuer's avatar
Karl Heuer committed
952 953 954 955 956 957
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,
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
 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)))
	  ;; Convert the remaining annoations to property list PROPS.
	  (while annotations
	    (setq props
		  (cons (car (car annotations))
			(cons (cdr (car annotations))
			      props))
		  annotations (cdr annotations)))
	  (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
1015
	(while l
1016 1017 1018 1019 1020 1021
	  (setq key (car (car l)) trans (car (cdr (car l))) l (cdr l))
	  (quail-defrule-internal key trans map t decode-map props))
	`(if (not (quail-decode-map))
	     (quail-install-map ',map)
	   (quail-install-map ',map)
	   (quail-install-decode-map ',decode-map))))))
Karl Heuer's avatar
Karl Heuer committed
1022

1023
;;;###autoload
1024
(defun quail-install-map (map &optional name)
Karl Heuer's avatar
Karl Heuer committed
1025
  "Install the Quail map MAP in the current Quail package.
1026 1027 1028 1029

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
1030 1031 1032 1033 1034 1035 1036
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))

1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
;;;###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"))
1047 1048 1049 1050 1051 1052 1053
  (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)))

1054

1055
;;;###autoload
1056
(defun quail-defrule (key translation &optional name append)
Karl Heuer's avatar
Karl Heuer committed
1057 1058
  "Add one translation rule, KEY to TRANSLATION, in the current Quail package.
KEY is a string meaning a sequence of keystrokes to be translated.
1059
TRANSLATION is a character, a string, a vector, a Quail map,
1060
 a function, or a cons.
Karl Heuer's avatar
Karl Heuer committed
1061 1062 1063
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
1064
 for the translation.
1065
If it is a cons, the car is one of the above and the cdr is a function
1066 1067 1068
 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
1069 1070 1071 1072
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.
1073 1074

Optional 3rd argument NAME, if specified, says which Quail package
Karl Heuer's avatar
Karl Heuer committed
1075
to define this translation rule in.  The default is to define it in the
1076 1077 1078 1079
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
1080 1081 1082 1083 1084
  (if name
      (let ((package (quail-package name)))
	(if (null package)
	    (error "No Quail package `%s'" name))
	(setq quail-current-package package)))
1085
  (quail-defrule-internal key translation (quail-map) append))
Karl Heuer's avatar
Karl Heuer committed
1086

1087
;;;###autoload
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
(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."
Karl Heuer's avatar
Karl Heuer committed
1098
  (if (null (stringp key))
1099
      (error "Invalid Quail key `%s'" key))
Karl Heuer's avatar
Karl Heuer committed
1100
  (if (not (or (numberp trans) (stringp trans) (vectorp trans)
1101
	       (consp trans)
Karl Heuer's avatar
Karl Heuer committed
1102 1103 1104 1105 1106 1107 1108 1109
	       (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)
1110
    ;; Make a map for registering TRANS if necessary.
Karl Heuer's avatar
Karl Heuer committed
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
    (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)))))
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
	;; 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)))))))
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
	(if (and (car map) append)
	    (let ((prev (quail-get-translation (car map) key len)))
	      (if (integerp prev)
		  (setq prev (vector prev))
		(setq prev (cdr prev)))
	      (if (integerp trans)
		  (setq trans (vector trans))
		(if (stringp trans)
		    (setq trans (string-to-vector trans))))
	      (setq trans
		    (cons (list 0 0 0 0 nil)
			  (vconcat prev trans)))))
	(setcar map trans)))))
Karl Heuer's avatar
Karl Heuer committed
1181

1182 1183
(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
1184 1185 1186 1187
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."
1188
  (if (and def (symbolp def))
1189 1190 1191 1192
      (if (functionp def)
	  ;; DEF is a symbol of a function which returns valid translation.
	  (setq def (funcall def key len))
	(setq def nil)))
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
  (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
1205 1206
    ;; If the length is 1, we don't need vector but a single candidate
    ;; as the translation.
1207 1208
    (if (= (length def) 1)
	(aref def 0)
Kenichi Handa's avatar
Kenichi Handa committed
1209 1210 1211
      ;; Each character in DEF is a candidate of translation.  Reform
      ;; it as (INDICES . VECTOR).
      (cons (list 0 0 0 0 nil) (string-to-vector def))))
1212 1213

   ((vectorp def)
Kenichi Handa's avatar
Kenichi Handa committed
1214 1215 1216 1217 1218 1219 1220 1221
    ;; If the length is 1, and the length of element string is 1, we
    ;; don't need vector but a single candidate as the translation.
    (if (and (= (length def) 1)
	     (= (length (aref def 0)) 1))
	(aref (aref def 0) 0)
      ;; Each element (string or character) in DEF is a candidate of
      ;; translation.  Reform it as (INDICES . VECTOR).
      (cons (list 0 0 0 0 nil) def)))
1222 1223 1224

   (t
    (error "Invalid object in Quail map: %s" def))))
Karl Heuer's avatar
Karl Heuer committed
1225

1226
(defun quail-lookup-key (key &optional len not-reset-indices)
Karl Heuer's avatar
Karl Heuer committed
1227 1228
  "Lookup KEY of length LEN in the current Quail map and return the definition.
The returned value is a Quail map specific to KEY."
1229 1230
  (or len
      (setq len (length key)))
Karl Heuer's avatar
Karl Heuer committed
1231 1232 1233
  (let ((idx 0)
	(map (quail-map))
	(kbd-translate (quail-kbd-translate))
1234
	slot ch translation def)
Karl Heuer's avatar
Karl Heuer committed
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
    (while (and map (< idx len))
      (setq ch (if kbd-translate (quail-keyboard-translate (aref key idx))
		 (aref key idx)))
      (setq idx (1+ idx))
      (if (and (cdr map) (symbolp (cdr map)))
	  (setcdr map (funcall (cdr map) key idx)))
      (setq slot (assq ch (cdr map)))
      (if (and (cdr slot) (symbolp (cdr slot)))
	  (setcdr slot (funcall (cdr slot) key idx)))
      (setq map (cdr slot)))
1245
    (setq def (car map))
1246
    (setq quail-current-translations nil)
1247
    (if (and map (setq translation (quail-get-translation def key len)))
Karl Heuer's avatar
Karl Heuer committed
1248
	(progn
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
	  (if (and (consp def) (not (vectorp (cdr def))))
	      (progn
		(if (not (equal (car def) translation))
		    ;; We must reflect TRANSLATION to car part of DEF.
		    (setcar def translation))
		(setq quail-current-data
		      (if (functionp (cdr def))
			  (funcall (cdr def))
			(cdr def))))
	    (if (not (equal def translation))
		;; We must reflect TRANSLATION to car part of MAP.
		(setcar map translation)))
Dave Love's avatar
Dave Love committed
1261
	  (if (and (consp translation) (vectorp (cdr translation)))
Karl Heuer's avatar
Karl Heuer committed
1262 1263
	      (progn
		(setq quail-current-translations translation)
1264
		(if (and (not not-reset-indices) (quail-forget-last-selection))
1265 1266 1267 1268
		    (setcar (car quail-current-translations) 0))))))
    ;; We may have to reform cdr part of MAP.
    (if (and (cdr map) (functionp (cdr map)))
	(setcdr map (funcall (cdr map) key len)))