; Spelling fix
[emacs.git] / lisp / international / mule-util.el
blobb575c2b7db396f6cfe27c316d837540b1d91f222
1 ;;; mule-util.el --- utility functions for multilingual environment (mule) -*- lexical-binding:t -*-
3 ;; Copyright (C) 1997-1998, 2000-2015 Free Software Foundation, Inc.
4 ;; Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
5 ;; 2005, 2006, 2007, 2008, 2009, 2010, 2011
6 ;; National Institute of Advanced Industrial Science and Technology (AIST)
7 ;; Registration Number H14PRO021
8 ;; Copyright (C) 2003
9 ;; National Institute of Advanced Industrial Science and Technology (AIST)
10 ;; Registration Number H13PRO009
12 ;; Keywords: mule, multilingual
14 ;; This file is part of GNU Emacs.
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
29 ;;; Commentary:
31 ;;; Code:
33 ;;; String manipulations while paying attention to multibyte characters.
35 ;;;###autoload
36 (defsubst string-to-list (string)
37 "Return a list of characters in STRING."
38 (append string nil))
40 ;;;###autoload
41 (defsubst string-to-vector (string)
42 "Return a vector of characters in STRING."
43 (vconcat string))
45 ;;;###autoload
46 (defun store-substring (string idx obj)
47 "Embed OBJ (string or character) at index IDX of STRING."
48 (if (integerp obj)
49 (aset string idx obj)
50 (let ((len1 (length obj))
51 (i 0))
52 (while (< i len1)
53 (aset string (+ idx i) (aref obj i))
54 (setq i (1+ i)))))
55 string)
57 (defvar truncate-string-ellipsis "..." ;"…"
58 "String to use to indicate truncation.")
60 ;;;###autoload
61 (defun truncate-string-to-width (str end-column
62 &optional start-column padding ellipsis)
63 "Truncate string STR to end at column END-COLUMN.
64 The optional 3rd arg START-COLUMN, if non-nil, specifies the starting
65 column; that means to return the characters occupying columns
66 START-COLUMN ... END-COLUMN of STR. Both END-COLUMN and START-COLUMN
67 are specified in terms of character display width in the current
68 buffer; see also `char-width'.
70 The optional 4th arg PADDING, if non-nil, specifies a padding
71 character (which should have a display width of 1) to add at the end
72 of the result if STR doesn't reach column END-COLUMN, or if END-COLUMN
73 comes in the middle of a character in STR. PADDING is also added at
74 the beginning of the result if column START-COLUMN appears in the
75 middle of a character in STR.
77 If PADDING is nil, no padding is added in these cases, so
78 the resulting string may be narrower than END-COLUMN.
80 If ELLIPSIS is non-nil, it should be a string which will replace the
81 end of STR (including any padding) if it extends beyond END-COLUMN,
82 unless the display width of STR is equal to or less than the display
83 width of ELLIPSIS. If it is non-nil and not a string, then ELLIPSIS
84 defaults to `truncate-string-ellipsis'."
85 (or start-column
86 (setq start-column 0))
87 (when (and ellipsis (not (stringp ellipsis)))
88 (setq ellipsis truncate-string-ellipsis))
89 (let ((str-len (length str))
90 (str-width (string-width str))
91 (ellipsis-width (if ellipsis (string-width ellipsis) 0))
92 (idx 0)
93 (column 0)
94 (head-padding "") (tail-padding "")
95 ch last-column last-idx from-idx)
96 (condition-case nil
97 (while (< column start-column)
98 (setq ch (aref str idx)
99 column (+ column (char-width ch))
100 idx (1+ idx)))
101 (args-out-of-range (setq idx str-len)))
102 (if (< column start-column)
103 (if padding (make-string end-column padding) "")
104 (when (and padding (> column start-column))
105 (setq head-padding (make-string (- column start-column) padding)))
106 (setq from-idx idx)
107 (when (>= end-column column)
108 (if (and (< end-column str-width)
109 (> str-width ellipsis-width))
110 (setq end-column (- end-column ellipsis-width))
111 (setq ellipsis ""))
112 (condition-case nil
113 (while (< column end-column)
114 (setq last-column column
115 last-idx idx
116 ch (aref str idx)
117 column (+ column (char-width ch))
118 idx (1+ idx)))
119 (args-out-of-range (setq idx str-len)))
120 (when (> column end-column)
121 (setq column last-column
122 idx last-idx))
123 (when (and padding (< column end-column))
124 (setq tail-padding (make-string (- end-column column) padding))))
125 (concat head-padding (substring str from-idx idx)
126 tail-padding ellipsis))))
129 ;;; Nested alist handler.
130 ;; Nested alist is alist whose elements are also nested alist.
132 ;;;###autoload
133 (defsubst nested-alist-p (obj)
134 "Return t if OBJ is a nested alist.
136 Nested alist is a list of the form (ENTRY . BRANCHES), where ENTRY is
137 any Lisp object, and BRANCHES is a list of cons cells of the form
138 \(KEY-ELEMENT . NESTED-ALIST).
140 You can use a nested alist to store any Lisp object (ENTRY) for a key
141 sequence KEYSEQ, where KEYSEQ is a sequence of KEY-ELEMENT. KEYSEQ
142 can be a string, a vector, or a list."
143 (and obj (listp obj) (listp (cdr obj))))
145 ;;;###autoload
146 (defun set-nested-alist (keyseq entry alist &optional len branches)
147 "Set ENTRY for KEYSEQ in a nested alist ALIST.
148 Optional 4th arg LEN non-nil means the first LEN elements in KEYSEQ
149 are considered.
150 Optional 5th argument BRANCHES if non-nil is branches for a keyseq
151 longer than KEYSEQ.
152 See the documentation of `nested-alist-p' for more detail."
153 (or (nested-alist-p alist)
154 (error "Invalid argument %s" alist))
155 (let ((islist (listp keyseq))
156 (len (or len (length keyseq)))
157 (i 0)
158 key-elt slot)
159 (while (< i len)
160 (if (null (nested-alist-p alist))
161 (error "Keyseq %s is too long for this nested alist" keyseq))
162 (setq key-elt (if islist (nth i keyseq) (aref keyseq i)))
163 (setq slot (assoc key-elt (cdr alist)))
164 (unless slot
165 (setq slot (cons key-elt (list t)))
166 (setcdr alist (cons slot (cdr alist))))
167 (setq alist (cdr slot))
168 (setq i (1+ i)))
169 (setcar alist entry)
170 (if branches
171 (setcdr (last alist) branches))))
173 ;;;###autoload
174 (defun lookup-nested-alist (keyseq alist &optional len start nil-for-too-long)
175 "Look up key sequence KEYSEQ in nested alist ALIST. Return the definition.
176 Optional 3rd argument LEN specifies the length of KEYSEQ.
177 Optional 4th argument START specifies index of the starting key.
178 The returned value is normally a nested alist of which
179 car part is the entry for KEYSEQ.
180 If ALIST is not deep enough for KEYSEQ, return number which is
181 how many key elements at the front of KEYSEQ it takes
182 to reach a leaf in ALIST.
183 Optional 5th argument NIL-FOR-TOO-LONG non-nil means return nil
184 even if ALIST is not deep enough."
185 (or (nested-alist-p alist)
186 (error "Invalid argument %s" alist))
187 (or len
188 (setq len (length keyseq)))
189 (let ((i (or start 0)))
190 (if (catch 'lookup-nested-alist-tag
191 (if (listp keyseq)
192 (while (< i len)
193 (if (setq alist (cdr (assoc (nth i keyseq) (cdr alist))))
194 (setq i (1+ i))
195 (throw 'lookup-nested-alist-tag t))))
196 (while (< i len)
197 (if (setq alist (cdr (assoc (aref keyseq i) (cdr alist))))
198 (setq i (1+ i))
199 (throw 'lookup-nested-alist-tag t))))
200 ;; KEYSEQ is too long.
201 (if nil-for-too-long nil i)
202 alist)))
205 ;; Coding system related functions.
207 ;;;###autoload
208 (defun coding-system-post-read-conversion (coding-system)
209 "Return the value of CODING-SYSTEM's `post-read-conversion' property."
210 (coding-system-get coding-system :post-read-conversion))
212 ;;;###autoload
213 (defun coding-system-pre-write-conversion (coding-system)
214 "Return the value of CODING-SYSTEM's `pre-write-conversion' property."
215 (coding-system-get coding-system :pre-write-conversion))
217 ;;;###autoload
218 (defun coding-system-translation-table-for-decode (coding-system)
219 "Return the value of CODING-SYSTEM's `decode-translation-table' property."
220 (coding-system-get coding-system :decode-translation-table))
222 ;;;###autoload
223 (defun coding-system-translation-table-for-encode (coding-system)
224 "Return the value of CODING-SYSTEM's `encode-translation-table' property."
225 (coding-system-get coding-system :encode-translation-table))
227 ;;;###autoload
228 (defmacro with-coding-priority (coding-systems &rest body)
229 "Execute BODY like `progn' with CODING-SYSTEMS at the front of priority list.
230 CODING-SYSTEMS is a list of coding systems. See `set-coding-system-priority'.
231 This affects the implicit sorting of lists of coding systems returned by
232 operations such as `find-coding-systems-region'."
233 (let ((current (make-symbol "current")))
234 `(let ((,current (coding-system-priority-list)))
235 (apply #'set-coding-system-priority ,coding-systems)
236 (unwind-protect
237 (progn ,@body)
238 (apply #'set-coding-system-priority ,current)))))
239 ;;;###autoload(put 'with-coding-priority 'lisp-indent-function 1)
240 (put 'with-coding-priority 'edebug-form-spec t)
242 ;;;###autoload
243 (defmacro detect-coding-with-priority (from to priority-list)
244 "Detect a coding system of the text between FROM and TO with PRIORITY-LIST.
245 PRIORITY-LIST is an alist of coding categories vs the corresponding
246 coding systems ordered by priority."
247 (declare (obsolete with-coding-priority "23.1"))
248 `(with-coding-priority (mapcar #'cdr ,priority-list)
249 (detect-coding-region ,from ,to)))
251 ;;;###autoload
252 (defun detect-coding-with-language-environment (from to lang-env)
253 "Detect a coding system for the text between FROM and TO with LANG-ENV.
254 The detection takes into account the coding system priorities for the
255 language environment LANG-ENV."
256 (let ((coding-priority (get-language-info lang-env 'coding-priority)))
257 (if coding-priority
258 (with-coding-priority coding-priority
259 (detect-coding-region from to)))))
261 (declare-function internal-char-font "fontset.c" (position &optional ch))
263 ;;;###autoload
264 (defun char-displayable-p (char)
265 "Return non-nil if we should be able to display CHAR.
266 On a multi-font display, the test is only whether there is an
267 appropriate font from the selected frame's fontset to display
268 CHAR's charset in general. Since fonts may be specified on a
269 per-character basis, this may not be accurate."
270 (cond ((< char 128)
271 ;; ASCII characters are always displayable.
273 ((not enable-multibyte-characters)
274 ;; Maybe there's a font for it, but we can't put it in the buffer.
275 nil)
277 (let ((font-glyph (internal-char-font nil char)))
278 (if font-glyph
279 (if (consp font-glyph)
280 ;; On a window system, a character is displayable
281 ;; if a font for that character is in the default
282 ;; face of the currently selected frame.
283 (car font-glyph)
284 ;; On a text terminal supporting glyph codes, CHAR is
285 ;; displayable if its glyph code is nonnegative.
286 (<= 0 font-glyph))
287 ;; On a text terminal without glyph codes, CHAR is displayable
288 ;; if the coding system for the terminal can encode it.
289 (let ((coding (terminal-coding-system)))
290 (when coding
291 (let ((cs-list (coding-system-get coding :charset-list)))
292 (cond
293 ((listp cs-list)
294 (catch 'tag
295 (mapc #'(lambda (charset)
296 (if (encode-char char charset)
297 (throw 'tag charset)))
298 cs-list)
299 nil))
300 ((eq cs-list 'iso-2022)
301 (catch 'tag2
302 (mapc #'(lambda (charset)
303 (if (and (plist-get (charset-plist charset)
304 :iso-final-char)
305 (encode-char char charset))
306 (throw 'tag2 charset)))
307 charset-list)
308 nil))
309 ((eq cs-list 'emacs-mule)
310 (catch 'tag3
311 (mapc #'(lambda (charset)
312 (if (and (plist-get (charset-plist charset)
313 :emacs-mule-id)
314 (encode-char char charset))
315 (throw 'tag3 charset)))
316 charset-list)
317 nil)))))))))))
319 (defun filepos-to-bufferpos--dos (byte f)
320 (let ((eol-offset 0)
321 ;; Make sure we terminate, even if BYTE falls right in the middle
322 ;; of a CRLF or some other weird corner case.
323 (omin 0) (omax most-positive-fixnum)
324 pos lines)
325 (while
326 (progn
327 (setq pos (funcall f (- byte eol-offset)))
328 ;; Protect against accidental values of BYTE outside of the
329 ;; valid region.
330 (when (null pos)
331 (if (<= byte eol-offset)
332 (setq pos (point-min))
333 (setq pos (point-max))))
334 ;; Adjust POS for DOS EOL format.
335 (setq lines (1- (line-number-at-pos pos)))
336 (and (not (= lines eol-offset)) (> omax omin)))
337 (if (> lines eol-offset)
338 (setq omax (min (1- omax) lines)
339 eol-offset omax)
340 (setq omin (max (1+ omin) lines)
341 eol-offset omin)))
342 pos))
344 ;;;###autoload
345 (defun filepos-to-bufferpos (byte &optional quality coding-system)
346 "Try to return the buffer position corresponding to a particular file position.
347 The file position is given as a (0-based) BYTE count.
348 The function presumes the file is encoded with CODING-SYSTEM, which defaults
349 to `buffer-file-coding-system'.
350 QUALITY can be:
351 `approximate', in which case we may cut some corners to avoid
352 excessive work.
353 `exact', in which case we may end up re-(en/de)coding a large
354 part of the file/buffer.
355 nil, in which case we may return nil rather than an approximation."
356 (unless coding-system (setq coding-system buffer-file-coding-system))
357 (let ((eol (coding-system-eol-type coding-system))
358 (type (coding-system-type coding-system))
359 (base (coding-system-base coding-system))
360 (pm (save-restriction (widen) (point-min))))
361 (and (eq type 'utf-8)
362 ;; Any post-read/pre-write conversions mean it's not really UTF-8.
363 (not (null (coding-system-get coding-system :post-read-conversion)))
364 (setq type 'not-utf-8))
365 (and (memq type '(charset raw-text undecided))
366 ;; The following are all of type 'charset', but they are
367 ;; actually variable-width encodings.
368 (not (memq base '(chinese-gbk chinese-gb18030 euc-tw euc-jis-2004
369 korean-iso-8bit chinese-iso-8bit
370 japanese-iso-8bit chinese-big5-hkscs
371 japanese-cp932 korean-cp949)))
372 (setq type 'single-byte))
373 (pcase type
374 (`utf-8
375 (when (coding-system-get coding-system :bom)
376 (setq byte (max 0 (- byte 3))))
377 (if (= eol 1)
378 (filepos-to-bufferpos--dos (+ pm byte) #'byte-to-position)
379 (byte-to-position (+ pm byte))))
380 (`single-byte
381 (if (= eol 1)
382 (filepos-to-bufferpos--dos (+ pm byte) #'identity)
383 (+ pm byte)))
384 ((and `utf-16
385 ;; FIXME: For utf-16, we could use the same approach as used for
386 ;; dos EOLs (counting the number of non-BMP chars instead of the
387 ;; number of lines).
388 (guard (not (eq quality 'exact))))
389 ;; Account for BOM, which is always 2 bytes in UTF-16.
390 (when (coding-system-get coding-system :bom)
391 (setq byte (max 0 (- byte 2))))
392 ;; In approximate mode, assume all characters are within the
393 ;; BMP, i.e. take up 2 bytes.
394 (setq byte (/ byte 2))
395 (if (= eol 1)
396 (filepos-to-bufferpos--dos (+ pm byte) #'identity)
397 (+ pm byte)))
399 (pcase quality
400 (`approximate (byte-to-position (+ pm byte)))
401 (`exact
402 ;; Rather than assume that the file exists and still holds the right
403 ;; data, we reconstruct it based on the buffer's content.
404 (let ((buf (current-buffer)))
405 (with-temp-buffer
406 (set-buffer-multibyte nil)
407 (let ((tmp-buf (current-buffer)))
408 (with-current-buffer buf
409 (save-restriction
410 (widen)
411 ;; Since encoding should always return more bytes than
412 ;; there were chars, encoding all chars up to (+ byte pm)
413 ;; guarantees the encoded result has at least `byte' bytes.
414 (encode-coding-region pm (min (point-max) (+ pm byte))
415 coding-system tmp-buf)))
416 (+ pm (length
417 (decode-coding-region (point-min)
418 (min (point-max) (+ pm byte))
419 coding-system t))))))))))))
420 ;;;###autoload
421 (defun bufferpos-to-filepos (position &optional quality coding-system)
422 "Try to return the file byte corresponding to a particular buffer POSITION.
423 Value is the file position given as a (0-based) byte count.
424 The function presumes the file is encoded with CODING-SYSTEM, which defaults
425 to `buffer-file-coding-system'.
426 QUALITY can be:
427 `approximate', in which case we may cut some corners to avoid
428 excessive work.
429 `exact', in which case we may end up re-(en/de)coding a large
430 part of the file/buffer.
431 nil, in which case we may return nil rather than an approximation."
432 (unless coding-system (setq coding-system buffer-file-coding-system))
433 (let* ((eol (coding-system-eol-type coding-system))
434 (lineno (if (= eol 1) (1- (line-number-at-pos position)) 0))
435 (type (coding-system-type coding-system))
436 (base (coding-system-base coding-system))
437 byte)
438 (and (eq type 'utf-8)
439 ;; Any post-read/pre-write conversions mean it's not really UTF-8.
440 (not (null (coding-system-get coding-system :post-read-conversion)))
441 (setq type 'not-utf-8))
442 (and (memq type '(charset raw-text undecided))
443 ;; The following are all of type 'charset', but they are
444 ;; actually variable-width encodings.
445 (not (memq base '(chinese-gbk chinese-gb18030 euc-tw euc-jis-2004
446 korean-iso-8bit chinese-iso-8bit
447 japanese-iso-8bit chinese-big5-hkscs
448 japanese-cp932 korean-cp949)))
449 (setq type 'single-byte))
450 (pcase type
451 (`utf-8
452 (setq byte (position-bytes position))
453 (when (null byte)
454 (if (<= position 0)
455 (setq byte 1)
456 (setq byte (position-bytes (point-max)))))
457 (setq byte (1- byte))
458 (+ byte
459 ;; Account for BOM, if any.
460 (if (coding-system-get coding-system :bom) 3 0)
461 ;; Account for CR in CRLF pairs.
462 lineno))
463 (`single-byte
464 (+ position -1 lineno))
465 ((and `utf-16
466 ;; FIXME: For utf-16, we could use the same approach as used for
467 ;; dos EOLs (counting the number of non-BMP chars instead of the
468 ;; number of lines).
469 (guard (not (eq quality 'exact))))
470 ;; In approximate mode, assume all characters are within the
471 ;; BMP, i.e. each one takes up 2 bytes.
472 (+ (* (1- position) 2)
473 ;; Account for BOM, if any.
474 (if (coding-system-get coding-system :bom) 2 0)
475 ;; Account for CR in CRLF pairs.
476 lineno))
478 (pcase quality
479 (`approximate (+ (position-bytes position) -1 lineno))
480 (`exact
481 ;; Rather than assume that the file exists and still holds the right
482 ;; data, we reconstruct its relevant portion.
483 (let ((buf (current-buffer)))
484 (with-temp-buffer
485 (set-buffer-multibyte nil)
486 (let ((tmp-buf (current-buffer)))
487 (with-current-buffer buf
488 (save-restriction
489 (widen)
490 (encode-coding-region (point-min) (min (point-max) position)
491 coding-system tmp-buf)))
492 (1- (point-max)))))))))))
494 (provide 'mule-util)
496 ;; Local Variables:
497 ;; coding: utf-8
498 ;; End:
500 ;;; mule-util.el ends here