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