1 ;;; mule-util.el --- utility functions for multilingual environment (mule) -*- lexical-binding:t -*-
3 ;; Copyright (C) 1997-1998, 2000-2016 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
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/>.
33 ;;; String manipulations while paying attention to multibyte characters.
36 (defsubst string-to-list
(string)
37 "Return a list of characters in STRING."
41 (defsubst string-to-vector
(string)
42 "Return a vector of characters in STRING."
46 (defun store-substring (string idx obj
)
47 "Embed OBJ (string or character) at index IDX of STRING."
50 (let ((len1 (length obj
))
53 (aset string
(+ idx i
) (aref obj i
))
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'.")
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'."
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))
95 (head-padding "") (tail-padding "")
96 ch last-column last-idx from-idx
)
98 (while (< column start-column
)
99 (setq ch
(aref str idx
)
100 column
(+ column
(char-width ch
))
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
)))
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
))
114 (while (< column end-column
)
115 (setq last-column column
118 column
(+ column
(char-width ch
))
120 (args-out-of-range (setq idx str-len
)))
121 (when (> column end-column
)
122 (setq column last-column
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.
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
))))
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
151 Optional 5th argument BRANCHES if non-nil is branches for a 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
)))
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
)))
166 (setq slot
(cons key-elt
(list t
)))
167 (setcdr alist
(cons slot
(cdr alist
))))
168 (setq alist
(cdr slot
))
172 (setcdr (last alist
) branches
))))
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
))
189 (setq len
(length keyseq
)))
190 (let ((i (or start
0)))
191 (if (catch 'lookup-nested-alist-tag
194 (if (setq alist
(cdr (assoc (nth i keyseq
) (cdr alist
))))
196 (throw 'lookup-nested-alist-tag t
))))
198 (if (setq alist
(cdr (assoc (aref keyseq i
) (cdr alist
))))
200 (throw 'lookup-nested-alist-tag t
))))
201 ;; KEYSEQ is too long.
202 (if nil-for-too-long nil i
)
206 ;; Coding system related functions.
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
))
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
))
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
))
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
))
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
)
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
)
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
)))
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
)))
259 (with-coding-priority coding-priority
260 (detect-coding-region from to
)))))
262 (declare-function internal-char-font
"font.c" (position &optional ch
))
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."
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.
278 (let ((font-glyph (internal-char-font nil char
)))
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.
285 ;; On a text terminal supporting glyph codes, CHAR is
286 ;; displayable if its glyph code is nonnegative.
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)))
292 (let ((cs-list (coding-system-get coding
:charset-list
)))
296 (mapc #'(lambda (charset)
297 (if (encode-char char charset
)
298 (throw 'tag charset
)))
301 ((eq cs-list
'iso-2022
)
303 (mapc #'(lambda (charset)
304 (if (and (plist-get (charset-plist charset
)
306 (encode-char char charset
))
307 (throw 'tag2 charset
)))
310 ((eq cs-list
'emacs-mule
)
312 (mapc #'(lambda (charset)
313 (if (and (plist-get (charset-plist charset
)
315 (encode-char char charset
))
316 (throw 'tag3 charset
)))
320 (defun filepos-to-bufferpos--dos (byte f
)
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
)
328 (setq pos
(funcall f
(- byte eol-offset
)))
329 ;; Protect against accidental values of BYTE outside of the
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
)
341 (setq omin
(max (1+ omin
) lines
)
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'.
352 `approximate', in which case we may cut some corners to avoid
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
))
376 (when (coding-system-get coding-system
:bom
)
377 (setq byte
(max 0 (- byte
3))))
379 (filepos-to-bufferpos--dos (+ pm byte
) #'byte-to-position
)
380 (byte-to-position (+ pm byte
))))
383 (filepos-to-bufferpos--dos (+ pm byte
) #'identity
)
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
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))
397 (filepos-to-bufferpos--dos (+ pm byte
) #'identity
)
401 (`approximate
(byte-to-position (+ pm byte
)))
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)))
407 (set-buffer-multibyte nil
)
408 (let ((tmp-buf (current-buffer)))
409 (with-current-buffer buf
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
)))
418 (decode-coding-region (point-min)
419 (min (point-max) (+ pm byte
))
420 coding-system t
))))))))))))
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'.
428 `approximate', in which case we may cut some corners to avoid
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
))
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
))
453 (setq byte
(position-bytes position
))
457 (setq byte
(position-bytes (point-max)))))
458 (setq byte
(1- byte
))
460 ;; Account for BOM, if any.
461 (if (coding-system-get coding-system
:bom
) 3 0)
462 ;; Account for CR in CRLF pairs.
465 (+ position -
1 lineno
))
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
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.
480 (`approximate
(+ (position-bytes position
) -
1 lineno
))
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)))
486 (set-buffer-multibyte nil
)
487 (let ((tmp-buf (current-buffer)))
488 (with-current-buffer buf
491 (encode-coding-region (point-min) (min (point-max) position
)
492 coding-system tmp-buf
)))
493 (1- (point-max)))))))))))
501 ;;; mule-util.el ends here