zero-input-framework.el 37.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
;;; zero-input-framework.el --- Zero Chinese input method framework -*- lexical-binding: t -*-

;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;;     http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.

;;; Commentary:

;; zero-input-framework is a Chinese input method framework for Emacs,
;; implemented as an Emacs minor mode.
;;
;; You can cycle zero-input-punctuation-level in current buffer by C-c , ,
;; You can change default Chinese punctuation level:
;;
23
;;   (setq-default zero-input-punctuation-level zero-input-punctuation-level-full)
24 25 26 27
;;
;; You can toggle full-width mode in current buffer by C-c , .
;; You can enable full-width mode by default:
;;
28
;;   (setq-default zero-input-full-width-p t)
29 30 31 32 33 34 35 36
;;

;;; Code:

;;==============
;; dependencies
;;==============

37 38
(eval-when-compile (require 'cl-lib) (require 'cl-macs))
(require 'ring)
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
(require 's)
(require 'zero-input-panel)

;;=======
;; utils
;;=======

;; this function is from ibus.el
(defun zero-input--ibus-compute-pixel-position (&optional pos window)
  "Return geometry of object at POS in WINDOW as a list like \(X Y H).
X and Y are pixel coordinates relative to top left corner of frame which
WINDOW is in.  H is the pixel height of the object.

Omitting POS and WINDOW means use current position and selected window,
respectively."
  (let* ((frame (window-frame (or window (selected-window))))
	 (posn (posn-at-point (or pos (window-point window)) window))
	 (line (cdr (posn-actual-col-row posn)))
	 (line-height (and line
			   (or (window-line-height line window)
			       (and (redisplay t)
				    (window-line-height line window)))))
	 (x-y (or (posn-x-y posn)
		  (let ((geom (pos-visible-in-window-p
			       (or pos (window-point window)) window t)))
		    (and geom (cons (car geom) (cadr geom))))
		  '(0 . 0)))
	 (ax (+ (car (window-inside-pixel-edges window))
		(car x-y)))
	 (ay (+ (cadr (window-pixel-edges window))
		(or (nth 2 line-height) (cdr x-y))))
	 (height (or (car line-height)
		     (with-current-buffer (window-buffer window)
		       (cond
			;; `posn-object-width-height' returns an incorrect value
			;; when the header line is displayed (Emacs bug #4426).
			((and posn
			      (null header-line-format))
			 (cdr (posn-object-width-height posn)))
			((and (bound-and-true-p text-scale-mode)
			      (not (zerop (with-no-warnings
					    text-scale-mode-amount))))
			 (round (* (frame-char-height frame)
				   (with-no-warnings
				     (expt text-scale-mode-step
					   text-scale-mode-amount)))))
			(t
			 (frame-char-height frame)))))))
    (list ax ay height)))

(defun zero-input-get-point-position ()
  "Return current point's position (x y).
Origin (0, 0) is at screen top left corner."
  (cl-destructuring-bind (x y line-height) (zero-input--ibus-compute-pixel-position)
    (cond
     ((functionp 'window-absolute-pixel-position)
      ;; introduced in emacs 26
      (cl-destructuring-bind (x . y) (window-absolute-pixel-position)
	(list x (+ y line-height))))
     ((functionp 'frame-edges)
      ;; introduced in emacs 25
      (cl-destructuring-bind (frame-x frame-y &rest rest)
	  (frame-edges nil 'inner-edges)
	(list (+ frame-x x) (+ frame-y y line-height))))
     (t
      ;; <= emacs 24, used guessed pixel size for tool-bar, menu-bar, WM title
      ;; bar. Since I can't get that from elisp.
      (list (+ (frame-parameter nil 'left)
	       (if (and (> (frame-parameter nil 'tool-bar-lines) 0)
			(eq (frame-parameter nil 'tool-bar-position) 'left))
		   96 0)
	       x)
	    (+ (frame-parameter nil 'top)
	       (if (and (> (frame-parameter nil 'tool-bar-lines) 0)
			(eq (frame-parameter nil 'tool-bar-position) 'top))
		   42 0)
	       (if (> (frame-parameter nil 'menu-bar-lines) 0) (+ 30 30) 0)
	       line-height
	       y))))))

(defun zero-input-cycle-list (lst item)
  "Return the object next to given ITEM in LST.

If item is the last object, return the first object in lst.
If item is not in lst, return nil."
  (let ((r (member item lst)))
    (cond
     ((null r) nil)
     (t (or (cadr r)
	    (car lst))))))

;;=====================
;; key logic functions
;;=====================

;; zero-input-el version
(defvar zero-input-version nil "Zero package version.")
136
(setq zero-input-version "2.7.1")
137 138 139 140 141 142 143 144 145 146

;; FSM state
(defconst zero-input--state-im-off 'IM-OFF)
(defconst zero-input--state-im-waiting-input 'IM-WAITING-INPUT)
(defconst zero-input--state-im-preediting 'IM-PREEDITING)

(defconst zero-input-punctuation-level-basic 'BASIC)
(defconst zero-input-punctuation-level-full 'FULL)
(defconst zero-input-punctuation-level-none 'NONE)

147
(defvar-local zero-input-im nil
148 149 150 151 152 153 154 155
  "Stores current input method.

If nil, the empty input method will be used.  In the empty input
method, only punctuation is handled.  Other keys are pass
through")
(defvar zero-input-ims nil
  "A list of registered input methods.")

156
(defvar-local zero-input-buffer nil
157 158 159
  "Stores the associated buffer.
this is used to help with buffer focus in/out events")

160
(defvar-local zero-input-state zero-input--state-im-off)
161
(defcustom zero-input-full-width-p nil
162 163 164 165
  "Set to t to enable full-width mode.
In full-width mode, commit ascii char will insert full-width char if there is a
corresponding full-width char.  This full-width char map is
independent from punctuation map.  You can change this via
166 167 168 169 170
`zero-input-toggle-full-width'"
  :group 'zero-input
  :safe t
  :type 'boolean)
(make-variable-buffer-local 'zero-input-full-width-p)
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194

(defcustom zero-input-punctuation-basic-map
  '((?, ",")
    (?, ",")
    (?. "。")				; 0x3002
    (?? "?")
    (?! "!")
    (?\\ "、")				; 0x3001
    (?: ":"))
  "Punctuation map used when `zero-input-punctuation-level' is not 'NONE."
  :group 'zero-input
  :type '(alist :key-type character :value-type (group string)))

(defcustom zero-input-punctuation-full-map
  '((?_ "——")
    (?< "《")				;0x300A
    (?> "》")				;0x300B
    (?\( "(")
    (?\) ")")
    (?\[ "【")				;0x3010
    (?\] "】")				;0x3011
    (?^ "……")
    (?~ "~")
    (?\; ";")
195
    (?\` "·")
196 197 198 199 200
    (?$ "¥"))
  "Additional punctuation map used when `zero-input-punctuation-level' is 'FULL."
  :group 'zero-input
  :type '(alist :key-type character :value-type (group string)))

201 202
(defcustom zero-input-punctuation-level zero-input-punctuation-level-basic
  "Default punctuation level.
203 204 205 206

Should be one of
`zero-input-punctuation-level-basic'
`zero-input-punctuation-level-full'
207 208 209 210 211 212 213 214 215 216
`zero-input-punctuation-level-none'"
  :group 'zero-input
  :safe t
  :type `(choice (const :tag "zero-input-punctuation-level-basic"
			,zero-input-punctuation-level-basic)
		 (const :tag "zero-input-punctuation-level-full"
			,zero-input-punctuation-level-full)
		 (const :tag "zero-input-punctuation-level-none"
			,zero-input-punctuation-level-none)))
(make-variable-buffer-local 'zero-input-punctuation-level)
217
(defvar zero-input-punctuation-levels (list zero-input-punctuation-level-basic
218 219
					    zero-input-punctuation-level-full
					    zero-input-punctuation-level-none)
220
  "Punctuation levels to use when `zero-input-cycle-punctuation-level'.")
221

222
(defvar-local zero-input-double-quote-flag nil
223 224 225 226 227
  "Non-nil means next double quote insert close quote.

Used when converting double quote to Chinese quote.
If nil, next double quote insert open quote.
Otherwise, next double quote insert close quote.")
228
(defvar-local zero-input-single-quote-flag nil
229 230 231 232 233
  "Non-nil means next single quote insert close quote.

Used when converting single quote to Chinese quote.
If nil, next single quote insert open quote.
Otherwise, next single quote insert close quote.")
234 235 236 237 238 239
(defvar-local zero-input-recent-insert-chars (make-ring 3)
  "Store recent insert characters.

Used to handle Chinese dot in digit input.
e.g. 1。3 could be converted to 1.3.")
(defcustom zero-input-auto-fix-dot-between-numbers t
240
  "Non-nil means zero should change 1。3 to 1.3, H。264 to H.264."
241
  :group 'zero-input
242
  :type 'boolean)
243 244
(defvar-local zero-input-preedit-str "")
(defvar-local zero-input-candidates nil)
245
(defcustom zero-input-candidates-per-page 10
246 247 248
  "How many candidates to show on each page.

Change will be effective only in new `zero-input-mode' buffer."
249
  :group 'zero-input
250
  :type 'integer)
251
(defvar-local zero-input-current-page 0 "Current page number.  count from 0.")
252 253 254 255 256
(defvar-local zero-input-initial-fetch-size 21
  "How many candidates to fetch for the first call to GetCandidates.

It's best set to (1+ (* zero-input-candidates-per-page N)) where
N is number of pages you want to fetch in initial fetch.")
257
;; zero-input-fetch-size is reset to 0 when preedit-str changes.
258 259
;; zero-input-fetch-size is set to fetch-size in build-candidates-async
;; complete-func lambda.
260
(defvar-local zero-input-fetch-size 0 "Last GetCandidates call's fetch-size.")
261 262 263 264 265 266 267 268 269 270 271 272 273 274
(defvar zero-input-previous-page-key ?\- "Previous page key.")
(defvar zero-input-next-page-key ?\= "Next page key.")

;;; concrete input method should define these functions and set them in the
;;; corresponding *-func variable.
(defun zero-input-build-candidates-default (_preedit-str _fetch-size)
  "Default implementation for `zero-input-build-candidates-func'."
  nil)
(defun zero-input-can-start-sequence-default (_ch)
  "Default implementation for `zero-input-can-start-sequence-func'."
  nil)
(defun zero-input-get-preedit-str-for-panel-default ()
  "Default implementation for `zero-input-get-preedit-str-for-panel-func'."
  zero-input-preedit-str)
275 276
(defvar-local zero-input-build-candidates-func
  'zero-input-build-candidates-default
277
  "Contains a function to build candidates from preedit-str.  The function accepts param preedit-str, fetch-size, returns candidate list.")
278 279
(defvar-local zero-input-build-candidates-async-func
  'zero-input-build-candidates-async-default
280
  "Contains a function to build candidates from preedit-str.  The function accepts param preedit-str, fetch-size, and a complete-func that should be called on returned candidate list.")
281 282
(defvar-local zero-input-can-start-sequence-func
  'zero-input-can-start-sequence-default
283
  "Contains a function to decide whether a char can start a preedit sequence.")
284 285
(defvar-local zero-input-handle-preedit-char-func
  'zero-input-handle-preedit-char-default
286 287 288
  "Contains a function to handle IM-PREEDITING state char insert.
The function should return t if char is handled.
This allow input method to override default logic.")
289 290
(defvar-local zero-input-get-preedit-str-for-panel-func
  'zero-input-get-preedit-str-for-panel-default
291
  "Contains a function that return preedit-str to show in zero-input-panel.")
292 293
(defvar-local zero-input-backspace-func
  'zero-input-backspace-default
294
  "Contains a function to handle <backward> char.")
295 296
(defvar-local zero-input-handle-preedit-char-func
  'zero-input-handle-preedit-char-default
297
  "Hanlde character insert in `zero-input--state-im-preediting' mode.")
298
(defvar-local zero-input-preedit-start-func 'nil
299
  "Called when enter `zero-input--state-im-preediting' state.")
300
(defvar-local zero-input-preedit-end-func 'nil
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
  "Called when leave `zero-input--state-im-preediting' state.")

(defvar zero-input-enable-debug nil
  "Whether to enable debug.
if t, `zero-input-debug' will output debug msg in *zero-input-debug* buffer")
(defvar zero-input-debug-buffer-max-size 30000
  "Max characters in *zero-input-debug* buffer.  If reached, first half data will be deleted.")

(defun zero-input-debug (string &rest objects)
  "Log debug message in *zero-input-debug* buffer.

STRING and OBJECTS are passed to `format'"
  (if zero-input-enable-debug
      (with-current-buffer (get-buffer-create "*zero-input-debug*")
	(goto-char (point-max))
	(insert (apply 'format string objects))
	(when (> (point) zero-input-debug-buffer-max-size)
	  (insert "removing old data\n")
	  (delete-region (point-min) (/ zero-input-debug-buffer-max-size 2))))))

;; (zero-input-debug "msg1\n")
;; (zero-input-debug "msg2: %s\n" "some obj")
;; (zero-input-debug "msg3: %s\n" 24)
;; (zero-input-debug "msg4: %s %s\n" 24 1)

326 327 328 329 330 331
(defun zero-input-add-recent-insert-char (ch)
  "Insert CH to `zero-input-recent-insert-chars'."
  ;; (cl-assert (and (characterp ch) (not (stringp ch))))
  (zero-input-debug "add char to recent chars ring: %s\n" ch)
  (ring-insert zero-input-recent-insert-chars ch))

332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
(defun zero-input-enter-preedit-state ()
  "Config keymap when enter preedit state."
  (zero-input-enable-preediting-map)
  (if (functionp zero-input-preedit-start-func)
      (funcall zero-input-preedit-start-func)))

(defun zero-input-leave-preedit-state ()
  "Config keymap when leave preedit state."
  (zero-input-disable-preediting-map)
  (if (functionp zero-input-preedit-end-func)
      (funcall zero-input-preedit-end-func)))

(defun zero-input-set-state (state)
  "Set zero state to given STATE."
  (zero-input-debug "set state to %s\n" state)
  (setq zero-input-state state)
  (if (eq state zero-input--state-im-preediting)
      (zero-input-enter-preedit-state)
    (zero-input-leave-preedit-state)))

(defun zero-input-candidates-on-page (candidates)
  "Return candidates on current page for given CANDIDATES list."
  (cl-flet ((take (n lst)
	       "take the first n element from lst. if there is not
enough elements, return lst as it is."
	       (cl-loop
		for lst* = lst then (cdr lst*)
		for n* = n then (1- n*)
		until (or (zerop n*) (null lst*))
		collect (car lst*)))
	    (drop (n lst)
	       "drop the first n elements from lst"
	       (cl-loop
		for lst* = lst then (cdr lst*)
		for n* = n then (1- n*)
		until (or (zerop n*) (null lst*))
		finally (return lst*))))
    (take zero-input-candidates-per-page
	  (drop (* zero-input-candidates-per-page zero-input-current-page) candidates))))

(defun zero-input-show-candidates (&optional candidates)
  "Show CANDIDATES using zero-input-panel via IPC/RPC."
374 375 376
  (let ((candidates-on-page
	 (zero-input-candidates-on-page (or candidates
					    zero-input-candidates))))
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
    (cl-destructuring-bind (x y) (zero-input-get-point-position)
      (zero-input-panel-show-candidates
       (funcall zero-input-get-preedit-str-for-panel-func)
       (length candidates-on-page)
       candidates-on-page
       `(("in_emacs" t)
	 ("filename" ,(or (buffer-file-name) ""))
	 ("page_number" ,(1+ zero-input-current-page))
	 ("has_next_page" ,(or (> (length (or candidates zero-input-candidates)) (* zero-input-candidates-per-page (1+ zero-input-current-page))) (< zero-input-fetch-size (* zero-input-candidates-per-page (+ 2 zero-input-current-page)))))
	 ("has_previous_page" ,(> zero-input-current-page 0))
	 ("move_x" :int32 ,x)
	 ("move_y" :int32 ,y)))
      (zero-input-debug "candidates: %s\n" (s-join ", " candidates-on-page)))))

(defun zero-input-build-candidates (preedit-str fetch-size)
  "Build candidates list synchronously.

394 395
Try to find at least FETCH-SIZE number of candidates for PREEDIT-STR.
Return a list of candidates."
396 397 398
  ;; (zero-input-debug "zero-input-build-candidates\n")
  (unless (functionp zero-input-build-candidates-func)
    (signal 'wrong-type-argument (list 'functionp zero-input-build-candidates-func)))
399 400 401 402
  ;; Note that zero-input-candidates and zero-input-fetch-size is updated in
  ;; async complete callback. This function only care about building the
  ;; candidates.
  (funcall zero-input-build-candidates-func preedit-str fetch-size))
403 404 405 406 407 408 409 410

(defun zero-input-build-candidates-async-default (preedit-str fetch-size complete-func)
  "Build candidate list, when done show it via `zero-input-show-candidates'.

PREEDIT-STR the preedit-str.
FETCH-SIZE try to find at least this many candidates for preedit-str.
COMPLETE-FUNC the function to call when build candidates completes."
  ;; (zero-input-debug "zero-input-build-candidates-async-default\n")
411
  ;; default implementation just call sync version `zero-input-build-candidates'.
412 413 414 415
  (let ((candidates (zero-input-build-candidates preedit-str fetch-size)))
    ;; update cache to make SPC and digit key selection possible.
    (funcall complete-func candidates)))

416
(defvar zero-input-full-width-char-map nil
417
  "An alist that map half-width char to full-width char.")
418 419 420 421 422 423 424 425 426
(setq zero-input-full-width-char-map
      (cons
       ;; ascii 32 -> unicode 3000
       (cons ?\s ?\u3000)
       ;; ascii [33, 126] -> unicode [FF01, FF5E]
       (cl-loop
	for i from 33 to 126
	collect (cons (make-char 'ascii i)
		      (make-char 'unicode 0 255 (- i 32))))))
427 428 429 430 431 432 433 434 435 436 437 438 439

(defun zero-input-convert-ch-to-full-width (ch)
  "Convert half-width char CH to full-width.

If there is no full-width char for CH, return it unchanged."
  (let ((pair (assoc ch zero-input-full-width-char-map)))
    (if pair (cdr pair) ch)))

(defun zero-input-convert-str-to-full-width (s)
  "Convert each char in S to their full-width char if there is one."
  (concat (mapcar 'zero-input-convert-ch-to-full-width s)))

(defun zero-input-convert-str-to-full-width-maybe (s)
440 441
  "If in `zero-input-full-width-p', convert char in S to their full-width char; otherwise, return s unchanged."
  (if zero-input-full-width-p (zero-input-convert-str-to-full-width s) s))
442 443

(defun zero-input-insert-full-width-char (ch)
444 445
  "If in `zero-input-full-width-p', insert full-width char for given CH and return true, otherwise just return nil."
  (when zero-input-full-width-p
446 447
    (let ((full-width-ch (zero-input-convert-ch-to-full-width ch)))
      (insert full-width-ch)
448
      (zero-input-add-recent-insert-char full-width-ch)
449 450 451 452 453 454
      full-width-ch)))

(defun zero-input-convert-punctuation-basic (ch)
  "Convert punctuation for `zero-input-punctuation-level-basic'.

Return CH's Chinese punctuation if CH is converted.  Return nil otherwise."
455
  (cadr (assq ch zero-input-punctuation-basic-map)))
456 457 458 459 460

(defun zero-input-convert-punctuation-full (ch)
  "Convert punctuation for `zero-input-punctuation-level-full'.

Return CH's Chinese punctuation if CH is converted.  Return nil otherwise"
461 462 463 464 465 466 467
  (or (zero-input-convert-punctuation-basic ch)
      (cadr (assq ch zero-input-punctuation-full-map))
      (cl-case ch
	(?\" (setq zero-input-double-quote-flag (not zero-input-double-quote-flag))
	     (if zero-input-double-quote-flag "“" "”"))
	(?\' (setq zero-input-single-quote-flag (not zero-input-single-quote-flag))
	     (if zero-input-single-quote-flag "‘" "’")))))
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483

(defun zero-input-convert-punctuation (ch)
  "Convert punctuation based on `zero-input-punctuation-level'.
Return CH's Chinese punctuation if CH is converted.  Return nil otherwise."
  (cond
   ((eq zero-input-punctuation-level zero-input-punctuation-level-basic)
    (zero-input-convert-punctuation-basic ch))
   ((eq zero-input-punctuation-level zero-input-punctuation-level-full)
    (zero-input-convert-punctuation-full ch))
   (t nil)))

(defun zero-input-handle-punctuation (ch)
  "If CH is a punctuation character, insert mapped Chinese punctuation and return true; otherwise, return false."
  (let ((str (zero-input-convert-punctuation ch)))
    (when str
      (insert str)
484
      (mapc #'zero-input-add-recent-insert-char str)
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
      t)))

(defun zero-input-append-char-to-preedit-str (ch)
  "Append char CH to preedit str, update and show candidate list."
  (setq zero-input-preedit-str
	(concat zero-input-preedit-str (make-string 1 ch)))
  (zero-input-debug "appended %c, preedit str is: %s\n" ch zero-input-preedit-str)
  (zero-input-preedit-str-changed))

(defun zero-input-can-start-sequence (ch)
  "Return t if char CH can start a preedit sequence."
  (if (functionp zero-input-can-start-sequence-func)
      (funcall zero-input-can-start-sequence-func ch)
    (error "`zero-input-can-start-sequence-func' is not a function")))

(defun zero-input-page-up ()
  "If not at first page, show candidates on previous page."
  (interactive)
  (when (> zero-input-current-page 0)
    (setq zero-input-current-page (1- zero-input-current-page))
    (zero-input-show-candidates)))

(defun zero-input-just-page-down ()
  "Just page down using existing candidates."
  (let ((len (length zero-input-candidates)))
    (when (> len (* zero-input-candidates-per-page (1+ zero-input-current-page)))
      (setq zero-input-current-page (1+ zero-input-current-page))
512
      (zero-input-debug "showing candidates on page %s\n" zero-input-current-page)
513 514 515 516 517 518
      (zero-input-show-candidates))))

(defun zero-input-page-down ()
  "If there is still candidates to be displayed, show candidates on next page."
  (interactive)
  (let ((len (length zero-input-candidates))
519 520
	(new-fetch-size (1+ (* zero-input-candidates-per-page (+ 2 zero-input-current-page)))))
    (zero-input-debug "decide whether to fetch more candidates, has %s candidates, last fetch size=%s, new-fetch-size=%s\n" len zero-input-fetch-size new-fetch-size)
521 522
    (if (and (< len new-fetch-size)
	     (< zero-input-fetch-size new-fetch-size))
523 524 525 526 527
	(progn
	  (zero-input-debug "will fetch more candidates")
	  (funcall zero-input-build-candidates-async-func
		   zero-input-preedit-str
		   new-fetch-size
528 529 530 531 532
		   #'(lambda (candidates)
		       (setq zero-input-candidates candidates)
		       (setq zero-input-fetch-size (max new-fetch-size
							(length candidates)))
		       (zero-input-just-page-down))))
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
      (zero-input-just-page-down))))

(defun zero-input-handle-preedit-char-default (ch)
  "Hanlde character insert in `zero-input--state-im-preediting' state.

CH is the char user has typed."
  (cond
   ((= ch ?\s)
    (zero-input-commit-first-candidate-or-preedit-str))
   ((and (>= ch ?0) (<= ch ?9))
    ;; 1 commit the 0th candidate
    ;; 2 commit the 1st candidate
    ;; ...
    ;; 0 commit the 9th candidate
    (unless (zero-input-commit-nth-candidate (mod (- (- ch ?0) 1) 10))
      (zero-input-append-char-to-preedit-str ch)))
   ((= ch zero-input-previous-page-key)
    (zero-input-page-up))
   ((= ch zero-input-next-page-key)
    (zero-input-page-down))
   (t (let ((str (zero-input-convert-punctuation ch)))
	(if str
	    (progn
	      (zero-input-set-state zero-input--state-im-waiting-input)
	      (zero-input-commit-first-candidate-or-preedit-str)
	      (insert str))
	  (zero-input-append-char-to-preedit-str ch))))))

(defun zero-input-self-insert-command (n)
  "Handle character `self-insert-command'.  This includes characters and digits.

N is the argument passed to `self-insert-command'."
  (interactive "p")
  (let ((ch (elt (this-command-keys-vector) 0)))
    (zero-input-debug "user typed: %c\n" ch)
    (cond
     ((eq zero-input-state zero-input--state-im-waiting-input)
      (if (zero-input-can-start-sequence ch)
	  (progn
	    (zero-input-debug "can start sequence, state=IM_PREEDITING\n")
	    (zero-input-set-state zero-input--state-im-preediting)
	    (zero-input-append-char-to-preedit-str ch))
	(zero-input-debug "cannot start sequence, state=IM_WAITING_INPUT\n")
	(unless (zero-input-handle-punctuation ch)
	  (unless (zero-input-insert-full-width-char ch)
	    (self-insert-command n)))))
     ((eq zero-input-state zero-input--state-im-preediting)
      (zero-input-debug "still preediting\n")
      (funcall zero-input-handle-preedit-char-func ch))
     (t
      (zero-input-debug "unexpected state: %s\n" zero-input-state)
      (self-insert-command n)))))

586
(defun zero-input-get-initial-fetch-size ()
587
  "Return initial fetch size."
588 589 590 591 592 593 594
  (cond
   ((<= zero-input-initial-fetch-size zero-input-candidates-per-page)
    (1+ zero-input-candidates-per-page))
   ((zerop (mod zero-input-initial-fetch-size zero-input-candidates-per-page))
    (1+ zero-input-initial-fetch-size))
   (t zero-input-initial-fetch-size)))

595 596 597 598
(defun zero-input-preedit-str-changed ()
  "Called when preedit str is changed and not empty.  Update and show candidate list."
  (setq zero-input-fetch-size 0)
  (setq zero-input-current-page 0)
599 600 601
  (let ((new-fetch-size (zero-input-get-initial-fetch-size)))
    (funcall zero-input-build-candidates-async-func
	     zero-input-preedit-str new-fetch-size
602 603 604 605
	     #'(lambda (candidates)
		 (setq zero-input-candidates candidates)
		 (setq zero-input-fetch-size (max new-fetch-size (length candidates)))
		 (zero-input-show-candidates candidates)))))
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629

(defun zero-input-backspace-default ()
  "Handle backspace key in `zero-input--state-im-preediting' state."
  (let ((len (length zero-input-preedit-str)))
    (if (> len 1)
	(progn
	  (setq zero-input-preedit-str
		(substring zero-input-preedit-str 0 (1- len)))
	  (zero-input-preedit-str-changed))
      (zero-input-set-state zero-input--state-im-waiting-input)
      (zero-input-reset))))

(defun zero-input-backspace ()
  "Handle backspace key in `zero-input--state-im-preediting' state."
  (interactive)
  (unless (eq zero-input-state zero-input--state-im-preediting)
    (error "Error: zero-input-backspace called in non preediting state"))
  (zero-input-debug "zero-input-backspace\n")
  (funcall zero-input-backspace-func))

(defun zero-input-commit-text (text)
  "Commit given TEXT, reset preedit str, hide candidate list."
  (zero-input-debug "commit text: %s\n" text)
  (insert text)
630 631 632
  ;; insert last 3 characters (if possible) to zero-input-recent-insert-chars
  (mapc #'zero-input-add-recent-insert-char
	(if (>= (length text) 3) (substring text -3) text))
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
  (setq zero-input-preedit-str "")
  (setq zero-input-candidates nil)
  (setq zero-input-current-page 0)
  (zero-input-hide-candidate-list))

(defun zero-input-return ()
  "Handle RET key press in `zero-input--state-im-preediting' state."
  (interactive)
  (unless (eq zero-input-state zero-input--state-im-preediting)
    (error "Error: zero-input-return called in non preediting state"))
  (zero-input-debug "zero-input-return\n")
  (zero-input-set-state zero-input--state-im-waiting-input)
  (zero-input-commit-text (zero-input-convert-str-to-full-width-maybe zero-input-preedit-str)))

(defun zero-input-commit-nth-candidate (n)
  "Commit Nth candidate and return true if it exists; otherwise, return false."
  (let ((candidate (nth n (zero-input-candidates-on-page zero-input-candidates))))
    (if candidate
	(progn
	  (zero-input-set-state zero-input--state-im-waiting-input)
	  (zero-input-commit-text candidate)
	  t)
      nil)))

(defun zero-input-commit-preedit-str ()
  "Commit current preedit-str."
  (zero-input-set-state zero-input--state-im-waiting-input)
  (zero-input-commit-text (zero-input-convert-str-to-full-width-maybe zero-input-preedit-str)))

(defun zero-input-commit-first-candidate-or-preedit-str ()
  "Commit first candidate if there is one, otherwise commit preedit str."
  (unless (zero-input-commit-nth-candidate 0)
    (zero-input-commit-preedit-str)))

(defun zero-input-hide-candidate-list ()
  "Hide candidate list."
  (zero-input-panel-hide)
  (zero-input-debug "hide candidate list\n"))

(defun zero-input-reset ()
  "Reset zero states."
  (interactive)
  (zero-input-debug "zero-input-reset\n")
  (zero-input-set-state zero-input--state-im-waiting-input)
  (setq zero-input-preedit-str "")
  (setq zero-input-candidates nil)
  (setq zero-input-current-page 0)
680 681
  (while (not (ring-empty-p zero-input-recent-insert-chars))
    (ring-remove zero-input-recent-insert-chars))
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
  (zero-input-hide-candidate-list))

(defun zero-input-focus-in ()
  "A hook function, run when focus in a buffer."
  (when (eq zero-input-state zero-input--state-im-preediting)
    (zero-input-show-candidates zero-input-candidates)
    (zero-input-enter-preedit-state)))

(defun zero-input-focus-out ()
  "A hook function, run when focus out a buffer."
  (when (eq zero-input-state zero-input--state-im-preediting)
    (zero-input-hide-candidate-list)
    (zero-input-leave-preedit-state)))

(defun zero-input-buffer-list-changed ()
  "A hook function, run when buffer list has changed.  This includes user has switched buffer."
  (if (eq (car (buffer-list)) zero-input-buffer)
      (zero-input-focus-in)))

;;============
;; minor mode
;;============

(defvar zero-input-mode-map
  (let ((map (make-sparse-keymap)))
    ;; build zero-input-prefix-map
    (defvar zero-input-prefix-map (define-prefix-command 'zero-input-prefix-map))
    (let ((bindings '(("," zero-input-cycle-punctuation-level)
710
		      ("." zero-input-toggle-full-width))))
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
      (dolist (b bindings)
	(define-key zero-input-prefix-map (car b) (cadr b))))
    ;; mount zero-input-prefix-map in C-c , prefix key.
    (define-key map (kbd "C-c ,") zero-input-prefix-map)

    ;; other keybindings
    (define-key map [remap self-insert-command]
      'zero-input-self-insert-command)
    map)
  "Keymap for `zero-input-mode'.")

(defun zero-input-enable-preediting-map ()
  "Enable preediting keymap in `zero-input-mode-map'."
  (zero-input-debug "zero-input-enable-preediting-map\n")
  (define-key zero-input-mode-map (kbd "<backspace>") 'zero-input-backspace)
  (define-key zero-input-mode-map (kbd "RET") 'zero-input-return)
  (define-key zero-input-mode-map (kbd "<escape>") 'zero-input-reset))

(defun zero-input-disable-preediting-map ()
  "Disable preediting keymap in `zero-input-mode-map'."
  (zero-input-debug "zero-input-disable-preediting-map\n")
  (define-key zero-input-mode-map (kbd "<backspace>") nil)
  (define-key zero-input-mode-map (kbd "RET") nil)
  (define-key zero-input-mode-map (kbd "<escape>") nil))

(defun zero-input-modeline-string ()
  "Build `zero-input-mode' modeline string aka lighter.

If full-width mode is enabled, show ZeroF;
Otherwise, show Zero."
741
  (if zero-input-full-width-p " ZeroF" " Zero"))
742

743
;;;###autoload
744 745 746 747 748 749 750 751 752
(define-minor-mode zero-input-mode
  "a Chinese input method framework written as an emacs minor mode.

\\{zero-input-mode-map}"
  nil
  (:eval (zero-input-modeline-string))
  zero-input-mode-map
  ;; local variables and variable init
  (make-local-variable 'zero-input-candidates-per-page)
753 754
  (make-local-variable 'zero-input-full-width-mode)
  (zero-input-reset)
755 756 757 758
  (zero-input-set-im zero-input-im)
  ;; hooks
  (add-hook 'focus-in-hook 'zero-input-focus-in)
  (add-hook 'focus-out-hook 'zero-input-focus-out)
759
  (setq zero-input-buffer (current-buffer))
760
  (add-hook 'post-self-insert-hook #'zero-input-post-self-insert-command nil t)
761 762
  (add-hook 'buffer-list-update-hook 'zero-input-buffer-list-changed))

763 764 765 766 767 768 769 770 771 772
(defun zero-input-post-self-insert-command (&optional ch)
  "Run after a regular `self-insert-command' is run by zero-input.

Argument CH the character that was inserted."
  ;; `zero-input-auto-fix-dot-between-numbers' is the only feature that
  ;; requires this ring, so for now if it is nil, no need to maintain the ring
  ;; for `self-insert-command'.
  (if (and zero-input-mode zero-input-auto-fix-dot-between-numbers)
      (let ((ch (or ch (elt (this-command-keys-vector) 0))))
	(zero-input-add-recent-insert-char ch)
773 774 775 776 777 778 779
	;; if user typed "[0-9A-Z]。[0-9]", auto convert “。” to “.”
	(cl-flet ((my-digit-char-p (ch) (and (>= ch ?0) (<= ch ?9)))
		  (my-capital-letter-p (ch) (and (>= ch ?A) (<= ch ?Z))))
	  ;; ring-ref index 2 is least recent inserted char.
	  (when (and (let ((ch (ring-ref zero-input-recent-insert-chars 2)))
		       (or (my-digit-char-p ch)
			   (my-capital-letter-p ch)))
780
		     (equal ? (ring-ref zero-input-recent-insert-chars 1))
781
		     (my-digit-char-p (ring-ref zero-input-recent-insert-chars 0)))
782 783 784
	    (delete-char -2)
	    (insert "." (car (ring-elements zero-input-recent-insert-chars))))))))

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
;;==================
;; IM developer API
;;==================

(defun zero-input-register-im (im-name im-functions-alist)
  "(Re)register an input method in zero.

After registration, you can use `zero-input-set-default-im' and
`zero-input-set-im' to select input method to use.

IM-NAME should be a symbol.
IM-FUNCTIONS-ALIST should be a list of form
  '((:virtual-function-name . implementation-function-name))

virtual functions                   corresponding variable
===========================================================================
:build-candidates                   `zero-input-build-candidates-func'
:can-start-sequence                 `zero-input-can-start-sequence-func'
:handle-preedit-char                `zero-input-handle-preedit-char-func'
:get-preedit-str-for-panel          `zero-input-get-preedit-str-for-panel-func'
:handle-backspace                   `zero-input-backspace-func'
:init                               nil
:shutdown                           nil
:preedit-start                      `zero-input-preedit-start-func'
:preedit-end                        `zero-input-preedit-end-func'

registered input method is saved in `zero-input-ims'"
  ;; add or replace entry in `zero-input-ims'
813 814 815
  (unless (stringp im-name)
    (signal 'wrong-type-argument (list 'stringp im-name)))
  (setq zero-input-ims (delq (assoc im-name zero-input-ims) zero-input-ims))
816 817
  (setq zero-input-ims (push (cons im-name im-functions-alist) zero-input-ims)))

818 819 820
;; Built-in empty input method. It only handles Chinese punctuation.
(zero-input-register-im "empty" nil)

821 822 823 824
;;============
;; public API
;;============

825 826
(defun zero-input-toggle-full-width ()
  "Toggle `zero-input-full-width-p' on/off."
827
  (interactive)
828 829
  (setq zero-input-full-width-p (not zero-input-full-width-p))
  (message (if zero-input-full-width-p
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
	       "Enabled full-width mode"
	     "Enabled half-width mode")))

(defun zero-input-set-punctuation-level (level)
  "Set `zero-input-punctuation-level'.

LEVEL the level to set to."
  (interactive)
  (if (not (member level (list zero-input-punctuation-level-basic
			       zero-input-punctuation-level-full
			       zero-input-punctuation-level-none)))
      (error "Level not supported: %s" level)
    (setq zero-input-punctuation-level level)))

(defun zero-input-set-punctuation-levels (levels)
  "Set `zero-input-punctuation-levels'.

`zero-input-cycle-punctuation-level' will cycle current
`zero-input-punctuation-level' among defined LEVELS."
  (dolist (level levels)
    (if (not (member level (list zero-input-punctuation-level-basic
				 zero-input-punctuation-level-full
				 zero-input-punctuation-level-none)))
	(error "Level not supported: %s" level)))
  (setq zero-input-punctuation-levels levels))

(defun zero-input-cycle-punctuation-level ()
  "Cycle `zero-input-punctuation-level' among `zero-input-punctuation-levels'."
  (interactive)
  (setq zero-input-punctuation-level
	(zero-input-cycle-list zero-input-punctuation-levels zero-input-punctuation-level))
  (message "punctuation level set to %s" zero-input-punctuation-level))

;;;###autoload
864
(defun zero-input-set-im (&optional im-name)
865 866
  "Select zero input method for current buffer.

867 868
IM-NAME (a string) should be a registered input method in zero-input."
  (interactive)
869 870
  ;; when switch away from an IM, run last IM's :shutdown function.
  (if zero-input-im
871
      (let ((shutdown-func (cdr (assq :shutdown (cdr (assoc zero-input-im zero-input-ims))))))
872 873
	(if (functionp shutdown-func)
	    (funcall shutdown-func))))
874 875 876 877 878 879 880 881 882
  (cond
   ((null im-name)
    ;; TODO is there an easier way to provide auto complete in mini buffer?
    ;; I used a recursive call to the same function.
    (let ((im-name-str (completing-read "Set input method to: " zero-input-ims)))
      (if (s-blank? im-name-str)
	  (error "Input method name is required")
	(zero-input-set-im im-name-str))))
   ((symbolp im-name)
883
    ;; symbol is allowed for backward compatibility.
884 885 886 887
    (zero-input-set-im (symbol-name im-name)))
   (t (let* ((im-slot (assoc im-name zero-input-ims))
	     (im-functions (cdr im-slot)))
	(if im-slot
888
	    (progn
889
	      (zero-input-debug "switching to %s input method" im-name)
890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
	      ;; TODO create a macro to reduce code duplication and human
	      ;; error.
	      ;;
	      ;; TODO do some functionp check for the slot functions. if check
	      ;; fail, keep (or revert to) the old IM.
	      (setq zero-input-build-candidates-func
		    (or (cdr (assq :build-candidates im-functions))
			'zero-input-build-candidates-default))
	      (setq zero-input-build-candidates-async-func
		    (or (cdr (assq :build-candidates-async im-functions))
			'zero-input-build-candidates-async-default))
	      (setq zero-input-can-start-sequence-func
		    (or (cdr (assq :can-start-sequence im-functions))
			'zero-input-can-start-sequence-default))
	      (setq zero-input-handle-preedit-char-func
		    (or (cdr (assq :handle-preedit-char im-functions))
			'zero-input-handle-preedit-char-default))
	      (setq zero-input-get-preedit-str-for-panel-func
		    (or (cdr (assq :get-preedit-str-for-panel im-functions))
			'zero-input-get-preedit-str-for-panel-default))
	      (setq zero-input-backspace-func
		    (or (cdr (assq :handle-backspace im-functions))
			'zero-input-backspace-default))
	      (setq zero-input-preedit-start-func
		    (cdr (assq :preedit-start im-functions)))
	      (setq zero-input-preedit-end-func
		    (cdr (assq :preedit-end im-functions)))
	      (unless (functionp zero-input-backspace-func)
		(signal 'wrong-type-argument
			(list 'functionp zero-input-backspace-func)))
	      ;; when switch to a IM, run its :init function
	      (let ((init-func (cdr (assq :init im-functions))))
		(if (functionp init-func)
		    (funcall init-func)))
924
	      (setq zero-input-im im-name))
925
	  (error "Input method %S not registered in zero" im-name))))))
926 927 928 929

;;;###autoload
(defun zero-input-set-default-im (im-name)
  "Set given IM-NAME as default zero input method."
930 931 932 933 934 935 936
  ;; symbol is allowed for backward compatibility.
  (unless (or (stringp im-name) (symbolp im-name))
    (signal 'wrong-type-argument (list 'string-or-symbolp im-name)))
  (let ((im-name-str (if (symbolp im-name) (symbol-name im-name) im-name)))
    (setq-default zero-input-im im-name-str)
    (unless (assoc im-name-str zero-input-ims)
      (warn "Input method %s is not registered with zero-input" im-name-str))))
937 938 939 940 941

;;;###autoload
(defun zero-input-on ()
  "Turn on `zero-input-mode'."
  (interactive)
942
  (zero-input-mode 1))
943 944 945 946

(defun zero-input-off ()
  "Turn off `zero-input-mode'."
  (interactive)
947
  (zero-input-mode -1))
948

949
;;;###autoload
950 951
(define-obsolete-function-alias 'zero-input-toggle 'zero-input-mode
  "Zero-input v2.0.2" "Toggle `zero-input-mode'.")
952 953 954 955

(provide 'zero-input-framework)

;;; zero-input-framework.el ends here