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

3
;; Copyright (C) 1995, 2000 Electrotechnical Laboratory, JAPAN.
Richard M. Stallman's avatar
Richard M. Stallman committed
4
;; Licensed to the Free Software Foundation.
5
;; Copyright (C) 2001, 2002 Free Software Foundation, Inc.
Karl Heuer's avatar
Karl Heuer committed
6 7 8 9

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

;; 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
25 26 27
;; along with GNU Emacs; see the file COPYING.  If not, write to the
;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
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 46 47 48 49 50 51 52
;; [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
53 54
;;; Code:

55 56
(require 'help-mode)

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

;; Buffer local variables

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

69 70 71
;; 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
72 73
;; A buffer to show completion list of the current key sequence.
(defvar quail-completion-buf nil)
74 75 76
;; 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
77

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

Karl Heuer's avatar
Karl Heuer committed
83 84 85 86 87 88 89 90 91 92
(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.")
93
(make-variable-buffer-local 'quail-current-key)
Karl Heuer's avatar
Karl Heuer committed
94 95 96

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

(defvar quail-current-translations nil
100 101 102 103 104 105
  "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.")
106
(make-variable-buffer-local 'quail-current-translations)
Karl Heuer's avatar
Karl Heuer committed
107

108 109 110
(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
111
of actual translation and some Lisp object to be referred
112 113
for translating the longer key sequence, this variable is set
to that Lisp object.")
114
(make-variable-buffer-local 'quail-current-data)
115

Karl Heuer's avatar
Karl Heuer committed
116 117 118 119 120 121 122 123
;; 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
124
  CONVERSION-KEYS, SIMPLE.
Karl Heuer's avatar
Karl Heuer committed
125 126 127 128 129 130 131 132 133 134 135 136 137

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

(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.
233 234 235 236
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."
237 238 239 240 241 242 243 244 245 246 247 248
  (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
249 250 251 252 253 254

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

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

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

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

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

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

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

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.

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

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

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

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

;; Quail minor mode handlers.

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

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

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

This function runs the normal hook `quail-inactivate-hook'."
542 543 544 545 546 547 548
  (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.

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

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

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

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

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

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

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

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

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

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

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

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

944
;;;###autoload
Karl Heuer's avatar
Karl Heuer committed
945 946 947 948 949
(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.
950
If it is a character, it is the sole translation of KEY.
Karl Heuer's avatar
Karl Heuer committed
951 952 953 954 955 956
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,
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
 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
1014
	(while l
1015 1016 1017 1018 1019 1020
	  (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
1021

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

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

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

1053

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

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

1086
;;;###autoload
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
(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
1097 1098 1099
  (if (null (stringp key))
      "Invalid Quail key `%s'" key)
  (if (not (or (numberp trans) (stringp trans) (vectorp trans)
1100
	       (consp trans)
Karl Heuer's avatar
Karl Heuer committed
1101 1102 1103 1104 1105 1106 1107 1108
	       (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)
1109
    ;; Make a map for registering TRANS if necessary.
Karl Heuer's avatar
Karl Heuer committed
1110 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
    (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)))))
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
	;; 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)))))))
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
	(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
1180

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

   ((vectorp def)
Kenichi Handa's avatar
Kenichi Handa committed
1213 1214 1215 1216 1217 1218 1219 1220
    ;; 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)))
1221 1222 1223

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

1225
(defun quail-lookup-key (key &optional len not-reset-indices)
Karl Heuer's avatar
Karl Heuer committed
1226 1227
  "Lookup KEY of length LEN in the current Quail map and return the definition.
The returned value is a Quail map specific to KEY."
1228 1229
  (or len
      (setq len (length key)))
Karl Heuer's avatar
Karl Heuer committed
1230 1231 1232
  (let ((idx 0)
	(map (quail-map))
	(kbd-translate (quail-kbd-translate))
1233
	slot ch translation def)
Karl Heuer's avatar
Karl Heuer committed
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
    (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)))
1244
    (setq def (car map))
1245
    (setq quail-current-translations nil)
1246
    (if (and map (setq translation (quail-get-translation def key len)))
Karl Heuer's avatar
Karl Heuer committed
1247
	(progn
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
	  (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
1260
	  (if (and (consp translation) (vectorp (cdr translation)))
Karl Heuer's avatar
Karl Heuer committed
1261 1262
	      (progn
		(setq quail-current-translations translation)
1263
		(if (and (not not-reset-indices) (quail-forget-last-selection))
1264 1265 1266 1267
		    (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)))
Karl Heuer's avatar
Karl Heuer committed
1268 1269
    map))

1270 1271