Update copyright notices for 2013.
[bpt/emacs.git] / lisp / international / mule.el
CommitLineData
07513d64 1;;; mule.el --- basic commands for multilingual environment
4ed46869 2
ab422c4d 3;; Copyright (C) 1997-2013 Free Software Foundation, Inc.
7976eda0 4;; Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
5df4f04c 5;; 2005, 2006, 2007, 2008, 2009, 2010, 2011
2fd125a3
KH
6;; National Institute of Advanced Industrial Science and Technology (AIST)
7;; Registration Number H14PRO021
8f924df7 8;; Copyright (C) 2003
c1841772
KH
9;; National Institute of Advanced Industrial Science and Technology (AIST)
10;; Registration Number H13PRO009
4ed46869
KH
11
12;; Keywords: mule, multilingual, character set, coding system
13
14;; This file is part of GNU Emacs.
15
4936186e 16;; GNU Emacs is free software: you can redistribute it and/or modify
4ed46869 17;; it under the terms of the GNU General Public License as published by
4936186e
GM
18;; the Free Software Foundation, either version 3 of the License, or
19;; (at your option) any later version.
4ed46869
KH
20
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.
25
26;; You should have received a copy of the GNU General Public License
4936186e 27;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
4ed46869 28
60370d40
PJ
29;;; Commentary:
30
4ed46869
KH
31;;; Code:
32
03794570 33;; FIXME? Are these still relevant? Nothing uses them AFAICS.
8f924df7 34(defconst mule-version "6.0 (HANACHIRUSATO)" "\
4ed46869
KH
35Version number and name of this version of MULE (multilingual environment).")
36
8f924df7 37(defconst mule-version-date "2003.9.1" "\
4ed46869
KH
38Distribution date of this version of MULE (multilingual environment).")
39
c1841772
KH
40\f
41;;; CHARSET
42
6d2b6635
KH
43;; Backward compatibility code for handling emacs-mule charsets.
44(defvar private-char-area-1-min #xF0000)
45(defvar private-char-area-1-max #xFFFFE)
46(defvar private-char-area-2-min #x100000)
47(defvar private-char-area-2-max #x10FFFE)
48
49;; Table of emacs-mule charsets indexed by their emacs-mule ID.
50(defvar emacs-mule-charset-table (make-vector 256 nil))
51(aset emacs-mule-charset-table 0 'ascii)
52
3dabda23 53;; Convert the argument of old-style call of define-charset to a
6d2b6635
KH
54;; property list used by the new-style.
55;; INFO-VECTOR is a vector of the format:
56;; [DIMENSION CHARS WIDTH DIRECTION ISO-FINAL-CHAR ISO-GRAPHIC-PLANE
57;; SHORT-NAME LONG-NAME DESCRIPTION]
58
59(defun convert-define-charset-argument (emacs-mule-id info-vector)
60 (let* ((dim (aref info-vector 0))
61 (chars (aref info-vector 1))
62 (total (if (= dim 1) chars (* chars chars)))
63 (code-space (if (= dim 1) (if (= chars 96) [32 127] [33 126])
64 (if (= chars 96) [32 127 32 127] [33 126 33 126])))
65 code-offset)
66 (if (integerp emacs-mule-id)
67 (or (= emacs-mule-id 0)
68 (and (>= emacs-mule-id 129) (< emacs-mule-id 256))
69 (error "Invalid CHARSET-ID: %d" emacs-mule-id))
70 (let (from-id to-id)
71 (if (= dim 1) (setq from-id 160 to-id 224)
72 (setq from-id 224 to-id 255))
73 (while (and (< from-id to-id)
74 (not (aref emacs-mule-charset-table from-id)))
75 (setq from-id (1+ from-id)))
76 (if (= from-id to-id)
77 (error "No more room for the new Emacs-mule charset"))
78 (setq emacs-mule-id from-id)))
79 (if (> (- private-char-area-1-max private-char-area-1-min) total)
80 (setq code-offset private-char-area-1-min
81 private-char-area-1-min (+ private-char-area-1-min total))
82 (if (> (- private-char-area-2-max private-char-area-2-min) total)
83 (setq code-offset private-char-area-2-min
84 private-char-area-2-min (+ private-char-area-2-min total))
d660b68f 85 (error "No more space for a new charset")))
6d2b6635
KH
86 (list :dimension dim
87 :code-space code-space
88 :iso-final-char (aref info-vector 4)
89 :code-offset code-offset
90 :emacs-mule-id emacs-mule-id)))
91
c1841772
KH
92(defun define-charset (name docstring &rest props)
93 "Define NAME (symbol) as a charset with DOCSTRING.
94The remaining arguments must come in pairs ATTRIBUTE VALUE. ATTRIBUTE
07513d64 95may be any symbol. The following have special meanings, and one of
bec25acc 96`:code-offset', `:map', `:subset', `:superset' must be specified.
c1841772
KH
97
98`:short-name'
99
100VALUE must be a short string to identify the charset. If omitted,
101NAME is used.
102
103`:long-name'
104
105VALUE must be a string longer than `:short-name' to identify the
07513d64 106charset. If omitted, the value of the `:short-name' attribute is used.
c1841772
KH
107
108`:dimension'
109
110VALUE must be an integer 0, 1, 2, or 3, specifying the dimension of
07513d64
DL
111code-points of the charsets. If omitted, it is calculated from the
112value of the `:code-space' attribute.
c1841772
KH
113
114`:code-space'
115
116VALUE must be a vector of length at most 8 specifying the byte code
117range of each dimension in this format:
118 [ MIN-1 MAX-1 MIN-2 MAX-2 ... ]
07513d64 119where MIN-N is the minimum byte value of Nth dimension of code-point,
c1841772
KH
120MAX-N is the maximum byte value of that.
121
b1a79461
KH
122`:min-code'
123
0b381c7e 124VALUE must be an integer specifying the minimum code point of the
b1a79461
KH
125charset. If omitted, it is calculated from `:code-space'. VALUE may
126be a cons (HIGH . LOW), where HIGH is the most significant 16 bits of
127the code point and LOW is the least significant 16 bits.
128
1f32125f 129`:max-code'
b1a79461 130
0b381c7e 131VALUE must be an integer specifying the maximum code point of the
b1a79461
KH
132charset. If omitted, it is calculated from `:code-space'. VALUE may
133be a cons (HIGH . LOW), where HIGH is the most significant 16 bits of
134the code point and LOW is the least significant 16 bits.
135
c1841772
KH
136`:iso-final-char'
137
138VALUE must be a character in the range 32 to 127 (inclusive)
139specifying the final char of the charset for ISO-2022 encoding. If
140omitted, the charset can't be encoded by ISO-2022 based
141coding-systems.
142
143`:iso-revision-number'
144
145VALUE must be an integer in the range 0..63, specifying the revision
146number of the charset for ISO-2022 encoding.
147
148`:emacs-mule-id'
149
6d2b6635 150VALUE must be an integer of 0, 129..255. If omitted, the charset
c1841772
KH
151can't be encoded by coding-systems of type `emacs-mule'.
152
153`:ascii-compatible-p'
154
07513d64
DL
155VALUE must be nil or t (default nil). If VALUE is t, the charset is
156compatible with ASCII, i.e. the first 128 code points map to ASCII.
c1841772
KH
157
158`:supplementary-p'
159
160VALUE must be nil or t. If the VALUE is t, the charset is
1376eeae
KH
161supplementary, which means it is used only as a parent or a
162subset of some other charset, or it is provided just for backward
163compatibility.
c1841772
KH
164
165`:invalid-code'
166
167VALUE must be a nonnegative integer that can be used as an invalid
168code point of the charset. If the minimum code is 0 and the maximum
44e97401 169code is greater than Emacs's maximum integer value, `:invalid-code'
c1841772
KH
170should not be omitted.
171
172`:code-offset'
173
07513d64
DL
174VALUE must be an integer added to the index number of a character to
175get the corresponding character code.
c1841772
KH
176
177`:map'
178
179VALUE must be vector or string.
180
181If it is a vector, the format is [ CODE-1 CHAR-1 CODE-2 CHAR-2 ... ],
182where CODE-n is a code-point of the charset, and CHAR-n is the
07513d64 183corresponding character code.
c1841772
KH
184
185If it is a string, it is a name of file that contains the above
3e4abc9e
KH
186information. Each line of the file must be this format:
187 0xXXX 0xYYY
188where XXX is a hexadecimal representation of CODE-n and YYY is a
189hexadecimal representation of CHAR-n. A line starting with `#' is a
190comment line.
c1841772 191
2c2a254f
KH
192`:subset'
193
194VALUE must be a list:
195 ( PARENT MIN-CODE MAX-CODE OFFSET )
196PARENT is a parent charset. MIN-CODE and MAX-CODE specify the range
197of characters inherited from the parent. OFFSET is an integer value
198to add to a code point of the parent charset to get the corresponding
199code point of this charset.
200
201`:superset'
c1841772
KH
202
203VALUE must be a list of parent charsets. The charset inherits
204characters from them. Each element of the list may be a cons (PARENT
205. OFFSET), where PARENT is a parent charset, and OFFSET is an offset
2c2a254f
KH
206value to add to a code point of PARENT to get the corresponding code
207point of this charset.
c1841772
KH
208
209`:unify-map'
210
211VALUE must be vector or string.
212
213If it is a vector, the format is [ CODE-1 CHAR-1 CODE-2 CHAR-2 ... ],
214where CODE-n is a code-point of the charset, and CHAR-n is the
07513d64 215corresponding Unicode character code.
c1841772
KH
216
217If it is a string, it is a name of file that contains the above
3e4abc9e
KH
218information. The file format is the same as what described for `:map'
219attribute."
6d2b6635
KH
220 (when (vectorp (car props))
221 ;; Old style code:
222 ;; (define-charset CHARSET-ID CHARSET-SYMBOL INFO-VECTOR)
223 ;; Convert the argument to make it fit with the current style.
224 (let ((vec (car props)))
225 (setq props (convert-define-charset-argument name vec)
226 name docstring
227 docstring (aref vec 8))))
c1841772
KH
228 (let ((attrs (mapcar 'list '(:dimension
229 :code-space
b1a79461
KH
230 :min-code
231 :max-code
c1841772
KH
232 :iso-final-char
233 :iso-revision-number
234 :emacs-mule-id
235 :ascii-compatible-p
236 :supplementary-p
237 :invalid-code
238 :code-offset
239 :map
2c2a254f
KH
240 :subset
241 :superset
c1841772
KH
242 :unify-map
243 :plist))))
244
245 ;; If :dimension is omitted, get the dimension from :code-space.
246 (let ((dimension (plist-get props :dimension)))
247 (or dimension
c04e918c
KH
248 (let ((code-space (plist-get props :code-space)))
249 (setq dimension (if code-space (/ (length code-space) 2) 4))
c1841772
KH
250 (setq props (plist-put props :dimension dimension)))))
251
c04e918c
KH
252 (let ((code-space (plist-get props :code-space)))
253 (or code-space
254 (let ((dimension (plist-get props :dimension)))
255 (setq code-space (make-vector 8 0))
256 (dotimes (i dimension)
257 (aset code-space (1+ (* i 2)) #xFF))
258 (setq props (plist-put props :code-space code-space)))))
259
6d2b6635
KH
260 ;; If :emacs-mule-id is specified, update emacs-mule-charset-table.
261 (let ((emacs-mule-id (plist-get props :emacs-mule-id)))
262 (if (integerp emacs-mule-id)
263 (aset emacs-mule-charset-table emacs-mule-id name)))
264
c1841772 265 (dolist (slot attrs)
3b6acc72 266 (setcdr slot (purecopy (plist-get props (car slot)))))
c1841772
KH
267
268 ;; Make sure that the value of :code-space is a vector of 8
269 ;; elements.
270 (let* ((slot (assq :code-space attrs))
271 (val (cdr slot))
272 (len (length val)))
273 (if (< len 8)
274 (setcdr slot
275 (vconcat val (make-vector (- 8 len) 0)))))
276
277 ;; Add :name and :docstring properties to PROPS.
278 (setq props
3b6acc72 279 (cons :name (cons name (cons :docstring (cons (purecopy docstring) props)))))
c1841772
KH
280 (or (plist-get props :short-name)
281 (plist-put props :short-name (symbol-name name)))
282 (or (plist-get props :long-name)
283 (plist-put props :long-name (plist-get props :short-name)))
7a84eee5 284 (plist-put props :base name)
e1e529fa
DL
285 ;; We can probably get a worthwhile amount in purespace.
286 (setq props
287 (mapcar (lambda (elt)
288 (if (stringp elt)
289 (purecopy elt)
290 elt))
291 props))
c1841772
KH
292 (setcdr (assq :plist attrs) props)
293
294 (apply 'define-charset-internal name (mapcar 'cdr attrs))))
295
296
4ed46869 297(defun load-with-code-conversion (fullname file &optional noerror nomessage)
0f69cb38
KH
298 "Execute a file of Lisp code named FILE whose absolute name is FULLNAME.
299The file contents are decoded before evaluation if necessary.
5dd1c041 300If optional third arg NOERROR is non-nil,
4ed46869
KH
301 report no error if FILE doesn't exist.
302Print messages at start and end of loading unless
5dd1c041 303 optional fourth arg NOMESSAGE is non-nil.
4ed46869
KH
304Return t if file exists."
305 (if (null (file-readable-p fullname))
306 (and (null noerror)
307 (signal 'file-error (list "Cannot open load file" file)))
308 ;; Read file with code conversion, and then eval.
309 (let* ((buffer
72f16325
SM
310 ;; We can't use `generate-new-buffer' because files.el
311 ;; is not yet loaded.
312 (get-buffer-create (generate-new-buffer-name " *load*")))
db5cae4b
SM
313 (load-in-progress t)
314 (source (save-match-data (string-match "\\.el\\'" fullname))))
315 (unless nomessage
316 (if source
317 (message "Loading %s (source)..." file)
318 (message "Loading %s..." file)))
319 (when purify-flag
3b6acc72 320 (push (purecopy file) preloaded-file-list))
4ed46869 321 (unwind-protect
a6acd8a2 322 (let ((load-file-name fullname)
1c4cc63a 323 (set-auto-coding-for-load t)
a6acd8a2 324 (inhibit-file-name-operation nil))
053f45dd 325 (with-current-buffer buffer
00fc37d1
SM
326 ;; So that we don't get completely screwed if the
327 ;; file is encoded in some complicated character set,
198a7a97 328 ;; read it with real decoding, as a multibyte buffer.
00fc37d1 329 (set-buffer-multibyte t)
9fe1108c
RS
330 ;; Don't let deactivate-mark remain set.
331 (let (deactivate-mark)
332 (insert-file-contents fullname))
7d276780
EZ
333 ;; If the loaded file was inserted with no-conversion or
334 ;; raw-text coding system, make the buffer unibyte.
335 ;; Otherwise, eval-buffer might try to interpret random
336 ;; binary junk as multibyte characters.
337 (if (and enable-multibyte-characters
8f924df7
KH
338 (or (eq (coding-system-type last-coding-system-used)
339 'raw-text)))
7d276780 340 (set-buffer-multibyte nil))
4ed46869
KH
341 ;; Make `kill-buffer' quiet.
342 (set-buffer-modified-p nil))
0f69cb38 343 ;; Have the original buffer current while we eval.
01ae35c1
RS
344 (eval-buffer buffer nil
345 ;; This is compatible with what `load' does.
346 (if purify-flag file fullname)
198a7a97 347 nil t))
cfc70cdf
RS
348 (let (kill-buffer-hook kill-buffer-query-functions)
349 (kill-buffer buffer)))
eb6f577b 350 (do-after-load-evaluation fullname)
5dd1c041 351
db5cae4b
SM
352 (unless (or nomessage noninteractive)
353 (if source
354 (message "Loading %s (source)...done" file)
355 (message "Loading %s...done" file)))
4ed46869
KH
356 t)))
357
8f924df7 358(defun charset-info (charset)
4ed46869 359 "Return a vector of information of CHARSET.
8f924df7 360This function is provided for backward compatibility.
4ed46869 361
4ed46869
KH
362The elements of the vector are:
363 CHARSET-ID, BYTES, DIMENSION, CHARS, WIDTH, DIRECTION,
364 LEADING-CODE-BASE, LEADING-CODE-EXT,
365 ISO-FINAL-CHAR, ISO-GRAPHIC-PLANE,
366 REVERSE-CHARSET, SHORT-NAME, LONG-NAME, DESCRIPTION,
8f924df7 367 PLIST.
4ed46869 368where
8f924df7
KH
369CHARSET-ID is always 0.
370BYTES is always 0.
371DIMENSION is the number of bytes of a code-point of the charset:
372 1, 2, 3, or 4.
373CHARS is the number of characters in a dimension:
374 94, 96, 128, or 256.
375WIDTH is always 0.
376DIRECTION is always 0.
377LEADING-CODE-BASE is always 0.
378LEADING-CODE-EXT is always 0.
4ed46869 379ISO-FINAL-CHAR (character) is the final character of the
7dd4c92d
KH
380 corresponding ISO 2022 charset. If the charset is not assigned
381 any final character, the value is -1.
8f924df7
KH
382ISO-GRAPHIC-PLANE is always 0.
383REVERSE-CHARSET is always -1.
4ed46869
KH
384SHORT-NAME (string) is the short name to refer to the charset.
385LONG-NAME (string) is the long name to refer to the charset
386DESCRIPTION (string) is the description string of the charset.
387PLIST (property list) may contain any type of information a user
388 want to put and get by functions `put-charset-property' and
389 `get-charset-property' respectively."
8f924df7
KH
390 (vector 0
391 0
392 (charset-dimension charset)
393 (charset-chars charset)
394 0
395 0
396 0
397 0
398 (charset-iso-final-char charset)
399 0
400 -1
401 (get-charset-property charset :short-name)
402 (get-charset-property charset :short-name)
403 (charset-description charset)
404 (charset-plist charset)))
4ed46869 405
40c81f74
PE
406;; It is better not to use backquote in this file,
407;; because that makes a bootstrapping problem
408;; if you need to recompile all the Lisp files using interpreted code.
409
8f924df7
KH
410(defun charset-id (charset)
411 "Always return 0. This is provided for backward compatibility."
a5f2b6ec 412 (declare (obsolete nil "23.1"))
8f924df7 413 0)
4ed46869
KH
414
415(defmacro charset-bytes (charset)
8f924df7 416 "Always return 0. This is provided for backward compatibility."
a5f2b6ec 417 (declare (obsolete nil "23.1"))
8f924df7 418 0)
c1841772
KH
419
420(defun get-charset-property (charset propname)
421 "Return the value of CHARSET's PROPNAME property.
422This is the last value stored with
423 (put-charset-property CHARSET PROPNAME VALUE)."
424 (plist-get (charset-plist charset) propname))
425
426(defun put-charset-property (charset propname value)
1f32125f 427 "Set CHARSETS's PROPNAME property to value VALUE.
c1841772
KH
428It can be retrieved with `(get-charset-property CHARSET PROPNAME)'."
429 (set-charset-plist charset
3b6acc72
DN
430 (plist-put (charset-plist charset) propname
431 (if (stringp value)
432 (purecopy value)
433 value))))
c1841772 434
c1841772
KH
435(defun charset-description (charset)
436 "Return description string of CHARSET."
437 (plist-get (charset-plist charset) :docstring))
438
439(defun charset-dimension (charset)
12504f57 440 "Return dimension of CHARSET."
c1841772
KH
441 (plist-get (charset-plist charset) :dimension))
442
346a8d64 443(defun charset-chars (charset &optional dimension)
12504f57 444 "Return number of characters contained in DIMENSION of CHARSET.
346a8d64
DL
445DIMENSION defaults to the first dimension."
446 (unless dimension (setq dimension 1))
103cc921 447 (let ((code-space (plist-get (charset-plist charset) :code-space)))
346a8d64
DL
448 (1+ (- (aref code-space (1- (* 2 dimension)))
449 (aref code-space (- (* 2 dimension) 2))))))
c1841772
KH
450
451(defun charset-iso-final-char (charset)
1d839a14
DL
452 "Return ISO-2022 final character of CHARSET.
453Return -1 if charset isn't an ISO 2022 one."
c1841772
KH
454 (or (plist-get (charset-plist charset) :iso-final-char)
455 -1))
4ed46869
KH
456
457(defmacro charset-short-name (charset)
c1841772
KH
458 "Return short name of CHARSET."
459 (plist-get (charset-plist charset) :short-name))
4ed46869
KH
460
461(defmacro charset-long-name (charset)
c1841772
KH
462 "Return long name of CHARSET."
463 (plist-get (charset-plist charset) :long-name))
4ed46869 464
d3675a42 465(defun charset-list ()
f81b2db1 466 "Return list of all charsets ever defined."
a5f2b6ec 467 (declare (obsolete charset-list "23.1"))
d3675a42
KH
468 charset-list)
469
6d2b6635
KH
470\f
471;;; CHARACTER
f81b2db1 472(define-obsolete-function-alias 'char-valid-p 'characterp "23.1")
6d2b6635 473
c1841772 474(defun generic-char-p (char)
8f924df7 475 "Always return nil. This is provided for backward compatibility."
a5f2b6ec 476 (declare (obsolete nil "23.1"))
c1841772 477 nil)
6d2b6635
KH
478
479(defun make-char-internal (charset-id &optional code1 code2)
480 (let ((charset (aref emacs-mule-charset-table charset-id)))
481 (or charset
482 (error "Invalid Emacs-mule charset ID: %d" charset-id))
483 (make-char charset code1 code2)))
0269ddfb 484\f
bd72e34f
CY
485;; Save the ASCII case table in case we need it later. Some locales
486;; (such as Turkish) modify the case behavior of ASCII characters,
487;; which can interfere with networking code that uses ASCII strings.
488
489(defvar ascii-case-table
490 ;; Code copied from copy-case-table to avoid requiring case-table.el
491 (let ((tbl (copy-sequence (standard-case-table)))
492 (up (char-table-extra-slot (standard-case-table) 0)))
493 (if up (set-char-table-extra-slot tbl 0 (copy-sequence up)))
494 (set-char-table-extra-slot tbl 1 nil)
495 (set-char-table-extra-slot tbl 2 nil)
496 tbl)
497 "Case table for the ASCII character set.")
498\f
e76938e7 499;; Coding system stuff
4ed46869 500
c1841772
KH
501;; Coding system is a symbol that has been defined by the function
502;; `define-coding-system'.
4ed46869 503
c1841772
KH
504(defconst coding-system-iso-2022-flags
505 '(long-form
506 ascii-at-eol
507 ascii-at-cntl
508 7-bit
509 locking-shift
510 single-shift
511 designation
512 revision
513 direction
514 init-at-bol
515 designate-at-bol
516 safe
517 latin-extra
518 composition
3ed58a15
KH
519 euc-tw-shift
520 use-roman
521 use-oldjis)
c1841772 522 "List of symbols that control ISO-2022 encoder/decoder.
4ed46869 523
12504f57 524The value of the `:flags' attribute in the argument of the function
caa7db3a 525`define-coding-system' must be one of them.
4ed46869 526
c1841772
KH
527If `long-form' is specified, use a long designation sequence on
528encoding for the charsets `japanese-jisx0208-1978', `chinese-gb2312',
529and `japanese-jisx0208'. The long designation sequence doesn't
12504f57 530conform to ISO 2022, but is used by such coding systems as
c1841772
KH
531`compound-text'.
532
533If `ascii-at-eol' is specified, designate ASCII to g0 at end of line
534on encoding.
535
536If `ascii-at-cntl' is specified, designate ASCII to g0 before control
537codes and SPC on encoding.
538
539If `7-bit' is specified, use 7-bit code only on encoding.
540
541If `locking-shift' is specified, decode locking-shift code correctly
542on decoding, and use locking-shift to invoke a graphic element on
543encoding.
544
545If `single-shift' is specified, decode single-shift code correctly on
546decoding, and use single-shift to invoke a graphic element on encoding.
547
548If `designation' is specified, decode designation code correctly on
549decoding, and use designation to designate a charset to a graphic
550element on encoding.
551
552If `revision' is specified, produce an escape sequence to specify
553revision number of a charset on encoding. Such an escape sequence is
554always correctly decoded on decoding.
555
556If `direction' is specified, decode ISO6429's code for specifying
12504f57 557direction correctly, and produce the code on encoding.
c1841772
KH
558
559If `init-at-bol' is specified, on encoding, it is assumed that
560invocation and designation statuses are reset at each beginning of
12504f57 561line even if `ascii-at-eol' is not specified; thus no codes for
c1841772
KH
562resetting them are produced.
563
564If `safe' is specified, on encoding, characters not supported by a
565coding are replaced with `?'.
566
12504f57 567If `latin-extra' is specified, the code-detection routine assumes that a
c1841772
KH
568code specified in `latin-extra-code-table' (which see) is valid.
569
570If `composition' is specified, an escape sequence to specify
12504f57 571composition sequence is correctly decoded on decoding, and is produced
c1841772
KH
572on encoding.
573
574If `euc-tw-shift' is specified, the EUC-TW specific shifting code is
12504f57 575correctly decoded on decoding, and is produced on encoding.
c1841772 576
12504f57
DL
577If `use-roman' is specified, JIS0201-1976-Roman is designated instead
578of ASCII.
579
580If `use-oldjis' is specified, JIS0208-1976 is designated instead of
581JIS0208-1983.")
582
c1841772 583(defun define-coding-system (name docstring &rest props)
12504f57 584 "Define NAME (a symbol) as a coding system with DOCSTRING and attributes.
c1841772
KH
585The remaining arguments must come in pairs ATTRIBUTE VALUE. ATTRIBUTE
586may be any symbol.
587
12504f57 588The following attributes have special meanings. Those labeled as
ed039e6c 589\"(required)\" should not be omitted.
c1841772
KH
590
591`:mnemonic' (required)
592
593VALUE is a character to display on mode line for the coding system.
594
595`:coding-type' (required)
596
597VALUE must be one of `charset', `utf-8', `utf-16', `iso-2022',
1bfd603c 598`emacs-mule', `shift-jis', `ccl', `raw-text', `undecided'.
c1841772 599
12504f57 600`:eol-type'
c1841772 601
12504f57 602VALUE is the EOL (end-of-line) format of the coding system. It must be
c1841772
KH
603one of `unix', `dos', `mac'. The symbol `unix' means Unix-like EOL
604\(i.e. single LF), `dos' means DOS-like EOL \(i.e. sequence of CR LF),
9e8014c6
EZ
605and `mac' means Mac-like EOL \(i.e. single CR). If omitted, Emacs
606detects the EOL format automatically when decoding.
c1841772 607
736345cb 608`:charset-list'
c1841772
KH
609
610VALUE must be a list of charsets supported by the coding system. On
611encoding by the coding system, if a character belongs to multiple
612charsets in the list, a charset that comes earlier in the list is
736345cb
KH
613selected. If `:coding-type' is `iso-2022', VALUE may be `iso-2022',
614which indicates that the coding system supports all ISO-2022 based
615charsets. If `:coding-type' is `emacs-mule', VALUE may be
616`emacs-mule', which indicates that the coding system supports all
1d839a14 617charsets that have the `:emacs-mule-id' property.
c1841772 618
12504f57 619`:ascii-compatible-p'
c1841772
KH
620
621If VALUE is non-nil, the coding system decodes all 7-bit bytes into
07513d64 622the corresponding ASCII characters, and encodes all ASCII characters
12504f57 623back to the corresponding 7-bit bytes. VALUE defaults to nil.
c1841772 624
12504f57 625`:decode-translation-table'
c1841772
KH
626
627VALUE must be a translation table to use on decoding.
628
12504f57 629`:encode-translation-table'
c1841772
KH
630
631VALUE must be a translation table to use on encoding.
632
12504f57 633`:post-read-conversion'
c1841772
KH
634
635VALUE must be a function to call after some text is inserted and
636decoded by the coding system itself and before any functions in
368b3544
KH
637`after-insert-functions' are called. This function is passed one
638argument; the number of characters in the text to convert, with
639point at the start of the text. The function should leave point
640the same, and return the new character count.
c1841772
KH
641
642`:pre-write-conversion'
643
644VALUE must be a function to call after all functions in
368b3544
KH
645`write-region-annotate-functions' and `buffer-file-format' are
646called, and before the text is encoded by the coding system
647itself. This function should convert the whole text in the
c0943d3d 648current buffer. For backward compatibility, this function is
368b3544 649passed two arguments which can be ignored.
c1841772
KH
650
651`:default-char'
652
653VALUE must be a character. On encoding, a character not supported by
654the coding system is replaced with VALUE.
655
8f924df7
KH
656`:for-unibyte'
657
658VALUE non-nil means that visiting a file with the coding system
659results in a unibyte buffer.
660
c1841772
KH
661`:mime-charset'
662
12504f57
DL
663VALUE must be a symbol whose name is that of a MIME charset converted
664to lower case.
c1841772 665
1bfd603c
DL
666`:mime-text-unsuitable'
667
668VALUE non-nil means the `:mime-charset' property names a charset which
1894d108 669is unsuitable for the top-level media type \"text\".
1bfd603c 670
c1841772
KH
671`:flags'
672
12504f57
DL
673VALUE must be a list of symbols that control the ISO-2022 converter.
674Each must be a member of the list `coding-system-iso-2022-flags'
c1841772
KH
675\(which see). This attribute has a meaning only when `:coding-type'
676is `iso-2022'.
677
678`:designation'
679
12504f57 680VALUE must be a vector [G0-USAGE G1-USAGE G2-USAGE G3-USAGE].
c1841772
KH
681GN-USAGE specifies the usage of graphic register GN as follows.
682
683If it is nil, no charset can be designated to GN.
684
07513d64 685If it is a charset, the charset is initially designated to GN, and
c1841772
KH
686never used by the other charsets.
687
688If it is a list, the elements must be charsets, nil, 94, or 96. GN
12504f57
DL
689can be used by all the listed charsets. If the list contains 94, any
690iso-2022 charset whose code-space ranges are 94 long can be designated
691to GN. If the list contains 96, any charsets whose whose ranges are
69296 long can be designated to GN. If the first element is a charset,
693that charset is initially designated to GN.
c1841772
KH
694
695This attribute has a meaning only when `:coding-type' is `iso-2022'.
696
697`:bom'
698
12504f57 699This attributes specifies whether the coding system uses a `byte order
ed039e6c 700mark'. VALUE must be nil, t, or cons of coding systems whose
e4821482 701`:coding-type' is `utf-16' or `utf-8'.
c1841772 702
0ea1a6ca
KH
703If the value is nil, on decoding, don't treat the first two-byte as
704BOM, and on encoding, don't produce BOM bytes.
705
706If the value is t, on decoding, skip the first two-byte as BOM, and on
e4920bc9 707encoding, produce BOM bytes according to the value of `:endian'.
0ea1a6ca 708
3dabda23 709If the value is cons, on decoding, check the first two-byte. If they
0ea1a6ca 710are 0xFE 0xFF, use the car part coding system of the value. If they
3dabda23 711are 0xFF 0xFE, use the cdr part coding system of the value.
0ea1a6ca 712Otherwise, treat them as bytes for a normal character. On encoding,
e4920bc9 713produce BOM bytes according to the value of `:endian'.
0ea1a6ca 714
ed039e6c
JB
715This attribute has a meaning only when `:coding-type' is `utf-16' or
716`utf-8'.
c1841772
KH
717
718`:endian'
719
0ea1a6ca
KH
720VALUE must be `big' or `little' specifying big-endian and
721little-endian respectively. The default value is `big'.
c1841772
KH
722
723This attribute has a meaning only when `:coding-type' is `utf-16'.
724
725`:ccl-decoder'
726
12504f57
DL
727VALUE is a symbol representing the registered CCL program used for
728decoding. This attribute has a meaning only when `:coding-type' is
729`ccl'.
c1841772
KH
730
731`:ccl-encoder'
732
12504f57
DL
733VALUE is a symbol representing the registered CCL program used for
734encoding. This attribute has a meaning only when `:coding-type' is
735`ccl'."
c1841772
KH
736 (let* ((common-attrs (mapcar 'list
737 '(:mnemonic
738 :coding-type
739 :charset-list
740 :ascii-compatible-p
1a9db556 741 :decode-translation-table
c1841772
KH
742 :encode-translation-table
743 :post-read-conversion
744 :pre-write-conversion
745 :default-char
7e742024 746 :for-unibyte
c1841772
KH
747 :plist
748 :eol-type)))
749 (coding-type (plist-get props :coding-type))
750 (spec-attrs (mapcar 'list
751 (cond ((eq coding-type 'iso-2022)
752 '(:initial
753 :reg-usage
754 :request
755 :flags))
736c9276
KH
756 ((eq coding-type 'utf-8)
757 '(:bom))
c1841772
KH
758 ((eq coding-type 'utf-16)
759 '(:bom
760 :endian))
761 ((eq coding-type 'ccl)
762 '(:ccl-decoder
763 :ccl-encoder
764 :valids))))))
765
766 (dolist (slot common-attrs)
767 (setcdr slot (plist-get props (car slot))))
768
769 (dolist (slot spec-attrs)
770 (setcdr slot (plist-get props (car slot))))
771
772 (if (eq coding-type 'iso-2022)
773 (let ((designation (plist-get props :designation))
774 (flags (plist-get props :flags))
775 (initial (make-vector 4 nil))
776 (reg-usage (cons 4 4))
777 request elt)
778 (dotimes (i 4)
779 (setq elt (aref designation i))
780 (cond ((charsetp elt)
781 (aset initial i elt)
782 (setq request (cons (cons elt i) request)))
783 ((consp elt)
784 (aset initial i (car elt))
785 (if (charsetp (car elt))
786 (setq request (cons (cons (car elt) i) request)))
787 (dolist (e (cdr elt))
788 (cond ((charsetp e)
789 (setq request (cons (cons e i) request)))
790 ((eq e 94)
791 (setcar reg-usage i))
792 ((eq e 96)
793 (setcdr reg-usage i))
794 ((eq e t)
795 (setcar reg-usage i)
796 (setcdr reg-usage i)))))))
797 (setcdr (assq :initial spec-attrs) initial)
798 (setcdr (assq :reg-usage spec-attrs) reg-usage)
799 (setcdr (assq :request spec-attrs) request)
800
801 ;; Change :flags value from a list to a bit-mask.
802 (let ((bits 0)
803 (i 0))
804 (dolist (elt coding-system-iso-2022-flags)
805 (if (memq elt flags)
806 (setq bits (logior bits (lsh 1 i))))
807 (setq i (1+ i)))
808 (setcdr (assq :flags spec-attrs) bits))))
809
810 ;; Add :name and :docstring properties to PROPS.
811 (setq props
e1e529fa
DL
812 (cons :name (cons name (cons :docstring (cons (purecopy docstring)
813 props)))))
c1841772 814 (setcdr (assq :plist common-attrs) props)
f5d3a630 815 (apply 'define-coding-system-internal
c1841772 816 name (mapcar 'cdr (append common-attrs spec-attrs)))))
4ed46869 817
8057896b 818(defun coding-system-doc-string (coding-system)
0269ddfb 819 "Return the documentation string for CODING-SYSTEM."
c1841772 820 (plist-get (coding-system-plist coding-system) :docstring))
4ed46869 821
4ed46869 822(defun coding-system-mnemonic (coding-system)
0269ddfb 823 "Return the mnemonic character of CODING-SYSTEM.
12504f57 824The mnemonic character of a coding system is used in mode line to
d660b68f 825indicate the coding system. If CODING-SYSTEM is nil, return ?=."
c1841772 826 (plist-get (coding-system-plist coding-system) :mnemonic))
4ed46869 827
c1841772
KH
828(defun coding-system-type (coding-system)
829 "Return the coding type of CODING-SYSTEM.
830A coding type is a symbol indicating the encoding method of CODING-SYSTEM.
831See the function `define-coding-system' for more detail."
832 (plist-get (coding-system-plist coding-system) :coding-type))
d3675a42 833
c1841772 834(defun coding-system-charset-list (coding-system)
07513d64 835 "Return list of charsets supported by CODING-SYSTEM.
c1841772
KH
836If CODING-SYSTEM supports all ISO-2022 charsets, return `iso-2022'.
837If CODING-SYSTEM supports all emacs-mule charsets, return `emacs-mule'."
838 (plist-get (coding-system-plist coding-system) :charset-list))
0269ddfb 839
2f1e746b
KH
840(defun coding-system-category (coding-system)
841 "Return a category symbol of CODING-SYSTEM."
842 (plist-get (coding-system-plist coding-system) :category))
0269ddfb
KH
843
844(defun coding-system-get (coding-system prop)
07513d64
DL
845 "Extract a value from CODING-SYSTEM's property list for property PROP.
846For compatibility with Emacs 20/21, this accepts old-style symbols
847like `mime-charset' as well as the current style like `:mime-charset'."
848 (or (plist-get (coding-system-plist coding-system) prop)
849 (if (not (keywordp prop))
057bce6f 850 ;; For backward compatibility.
356384dc
KH
851 (if (eq prop 'ascii-incompatible)
852 (not (plist-get (coding-system-plist coding-system)
853 :ascii-compatible-p))
854 (plist-get (coding-system-plist coding-system)
855 (intern (concat ":" (symbol-name prop))))))))
0269ddfb 856
2e729bfa
JB
857(defun coding-system-eol-type-mnemonic (coding-system)
858 "Return the string indicating end-of-line format of CODING-SYSTEM."
859 (let* ((eol-type (coding-system-eol-type coding-system))
f4f00827 860 (val (cond ((eq eol-type 0) eol-mnemonic-unix)
2e729bfa
JB
861 ((eq eol-type 1) eol-mnemonic-dos)
862 ((eq eol-type 2) eol-mnemonic-mac)
f4f00827 863 (t eol-mnemonic-undecided))))
2e729bfa
JB
864 (if (stringp val)
865 val
866 (char-to-string val))))
867
857ea15c
AS
868(defun coding-system-lessp (x y)
869 (cond ((eq x 'no-conversion) t)
870 ((eq y 'no-conversion) nil)
871 ((eq x 'emacs-mule) t)
872 ((eq y 'emacs-mule) nil)
873 ((eq x 'undecided) t)
874 ((eq y 'undecided) nil)
875 (t (let ((c1 (coding-system-mnemonic x))
876 (c2 (coding-system-mnemonic y)))
877 (or (< (downcase c1) (downcase c2))
878 (and (not (> (downcase c1) (downcase c2)))
879 (< c1 c2)))))))
880
5e2e859a
KH
881(defun coding-system-equal (coding-system-1 coding-system-2)
882 "Return t if and only if CODING-SYSTEM-1 and CODING-SYSTEM-2 are identical.
f81b2db1 883Two coding systems are identical if both symbols are equal
5e2e859a
KH
884or one is an alias of the other."
885 (or (eq coding-system-1 coding-system-2)
daff7d74
KH
886 (and (equal (coding-system-plist coding-system-1)
887 (coding-system-plist coding-system-2))
5e2e859a
KH
888 (let ((eol-type-1 (coding-system-eol-type coding-system-1))
889 (eol-type-2 (coding-system-eol-type coding-system-2)))
890 (or (eq eol-type-1 eol-type-2)
891 (and (vectorp eol-type-1) (vectorp eol-type-2)))))))
892
857ea15c 893(defun add-to-coding-system-list (coding-system)
521d4010 894 "Add CODING-SYSTEM to `coding-system-list' while keeping it sorted."
857ea15c
AS
895 (if (or (null coding-system-list)
896 (coding-system-lessp coding-system (car coding-system-list)))
897 (setq coding-system-list (cons coding-system coding-system-list))
898 (let ((len (length coding-system-list))
899 mid (tem coding-system-list))
900 (while (> len 1)
901 (setq mid (nthcdr (/ len 2) tem))
902 (if (coding-system-lessp (car mid) coding-system)
903 (setq tem mid
904 len (- len (/ len 2)))
905 (setq len (/ len 2))))
906 (setcdr tem (cons coding-system (cdr tem))))))
907
80a7463d 908(defun coding-system-list (&optional base-only)
c11a8f77 909 "Return a list of all existing non-subsidiary coding systems.
12504f57
DL
910If optional arg BASE-ONLY is non-nil, only base coding systems are
911listed. The value doesn't include subsidiary coding systems which are
c11a8f77
KH
912made from bases and aliases automatically for various end-of-line
913formats (e.g. iso-latin-1-unix, koi8-r-dos)."
4f06ffe1
KH
914 (let ((codings nil))
915 (dolist (coding coding-system-list)
916 (if (eq (coding-system-base coding) coding)
917 (if base-only
918 (setq codings (cons coding codings))
919 (dolist (alias (coding-system-aliases coding))
920 (setq codings (cons alias codings))))))
80a7463d
KH
921 codings))
922
620956ca 923(defconst char-coding-system-table nil
f5d3a630
JB
924 "It exists just for backward compatibility, and the value is always nil.")
925(make-obsolete-variable 'char-coding-system-table nil "23.1")
c11a8f77 926
50c29104
KH
927(defun transform-make-coding-system-args (name type &optional doc-string props)
928 "For internal use only.
929Transform XEmacs style args for `make-coding-system' to Emacs style.
930Value is a list of transformed arguments."
931 (let ((mnemonic (string-to-char (or (plist-get props 'mnemonic) "?")))
932 (eol-type (plist-get props 'eol-type))
933 properties tmp)
934 (cond
935 ((eq eol-type 'lf) (setq eol-type 'unix))
936 ((eq eol-type 'crlf) (setq eol-type 'dos))
937 ((eq eol-type 'cr) (setq eol-type 'mac)))
938 (if (setq tmp (plist-get props 'post-read-conversion))
939 (setq properties (plist-put properties 'post-read-conversion tmp)))
940 (if (setq tmp (plist-get props 'pre-write-conversion))
941 (setq properties (plist-put properties 'pre-write-conversion tmp)))
942 (cond
f4a012a6
KH
943 ((eq type 'shift-jis)
944 `(,name 1 ,mnemonic ,doc-string () ,properties ,eol-type))
945 ((eq type 'iso2022) ; This is not perfect.
946 (if (plist-get props 'escape-quoted)
947 (error "escape-quoted is not supported: %S"
948 `(,name ,type ,doc-string ,props)))
949 (let ((g0 (plist-get props 'charset-g0))
950 (g1 (plist-get props 'charset-g1))
951 (g2 (plist-get props 'charset-g2))
952 (g3 (plist-get props 'charset-g3))
953 (use-roman
954 (and
955 (eq (cadr (assoc 'latin-jisx0201
956 (plist-get props 'input-charset-conversion)))
957 'ascii)
958 (eq (cadr (assoc 'ascii
959 (plist-get props 'output-charset-conversion)))
960 'latin-jisx0201)))
961 (use-oldjis
962 (and
963 (eq (cadr (assoc 'japanese-jisx0208-1978
964 (plist-get props 'input-charset-conversion)))
965 'japanese-jisx0208)
966 (eq (cadr (assoc 'japanese-jisx0208
967 (plist-get props 'output-charset-conversion)))
968 'japanese-jisx0208-1978))))
969 (if (charsetp g0)
970 (if (plist-get props 'force-g0-on-output)
971 (setq g0 `(nil ,g0))
972 (setq g0 `(,g0 t))))
973 (if (charsetp g1)
974 (if (plist-get props 'force-g1-on-output)
975 (setq g1 `(nil ,g1))
976 (setq g1 `(,g1 t))))
977 (if (charsetp g2)
978 (if (plist-get props 'force-g2-on-output)
979 (setq g2 `(nil ,g2))
980 (setq g2 `(,g2 t))))
981 (if (charsetp g3)
982 (if (plist-get props 'force-g3-on-output)
983 (setq g3 `(nil ,g3))
984 (setq g3 `(,g3 t))))
985 `(,name 2 ,mnemonic ,doc-string
986 (,g0 ,g1 ,g2 ,g3
987 ,(plist-get props 'short)
988 ,(not (plist-get props 'no-ascii-eol))
989 ,(not (plist-get props 'no-ascii-cntl))
990 ,(plist-get props 'seven)
991 t
992 ,(not (plist-get props 'lock-shift))
993 ,use-roman
994 ,use-oldjis
995 ,(plist-get props 'no-iso6429)
996 nil nil nil nil)
997 ,properties ,eol-type)))
998 ((eq type 'big5)
999 `(,name 3 ,mnemonic ,doc-string () ,properties ,eol-type))
50c29104 1000 ((eq type 'ccl)
f4a012a6 1001 `(,name 4 ,mnemonic ,doc-string
50c29104 1002 (,(plist-get props 'decode) . ,(plist-get props 'encode))
f4a012a6 1003 ,properties ,eol-type))
50c29104 1004 (t
f4a012a6 1005 (error "unsupported XEmacs style make-coding-style arguments: %S"
50c29104
KH
1006 `(,name ,type ,doc-string ,props))))))
1007
8057896b 1008(defun make-coding-system (coding-system type mnemonic doc-string
1b46a680
KH
1009 &optional
1010 flags
1011 properties
1012 eol-type)
3bb1accb 1013 "Define a new coding system CODING-SYSTEM (symbol).
f81b2db1 1014This function is provided for backward compatibility."
a5f2b6ec 1015 (declare (obsolete define-coding-system "23.1"))
057bce6f 1016 ;; For compatibility with XEmacs, we check the type of TYPE. If it
c3d0ee51
EZ
1017 ;; is a symbol, perhaps, this function is called with XEmacs-style
1018 ;; arguments. Here, try to transform that kind of arguments to
50c29104
KH
1019 ;; Emacs style.
1020 (if (symbolp type)
1021 (let ((args (transform-make-coding-system-args coding-system type
1022 mnemonic doc-string)))
1023 (setq coding-system (car args)
1053cc93 1024 type (nth 1 args)
50c29104
KH
1025 mnemonic (nth 2 args)
1026 doc-string (nth 3 args)
1027 flags (nth 4 args)
1028 properties (nth 5 args)
1029 eol-type (nth 6 args))))
1030
8f924df7
KH
1031 (setq type
1032 (cond ((eq type 0) 'emacs-mule)
1033 ((eq type 1) 'shift-jis)
1034 ((eq type 2) 'iso2022)
1035 ((eq type 3) 'big5)
1036 ((eq type 4) 'ccl)
1037 ((eq type 5) 'raw-text)
1b46a680 1038 (t
8f924df7
KH
1039 (error "Invalid coding system type: %s" type))))
1040
1041 (setq properties
1042 (let ((plist nil) key)
1043 (dolist (elt properties)
1044 (setq key (car elt))
1045 (cond ((eq key 'post-read-conversion)
1046 (setq key :post-read-conversion))
1047 ((eq key 'pre-write-conversion)
1048 (setq key :pre-write-conversion))
1049 ((eq key 'translation-table-for-decode)
1050 (setq key :decode-translation-table))
1051 ((eq key 'translation-table-for-encode)
1052 (setq key :encode-translation-table))
1053 ((eq key 'safe-charsets)
1054 (setq key :charset-list))
1055 ((eq key 'mime-charset)
1056 (setq key :mime-charset))
1057 ((eq key 'valid-codes)
1058 (setq key :valids)))
1059 (setq plist (plist-put plist key (cdr elt))))
1060 plist))
28380f17 1061 (setq properties (plist-put properties :mnemonic mnemonic))
8f924df7
KH
1062 (plist-put properties :coding-type type)
1063 (cond ((eq eol-type 0) (setq eol-type 'unix))
1064 ((eq eol-type 1) (setq eol-type 'dos))
1065 ((eq eol-type 2) (setq eol-type 'mac))
1066 ((vectorp eol-type) (setq eol-type nil)))
1067 (plist-put properties :eol-type eol-type)
1068
1069 (cond
1070 ((eq type 'iso2022)
1071 (plist-put properties :flags
1072 (list (and (or (consp (nth 0 flags))
1073 (consp (nth 1 flags))
1074 (consp (nth 2 flags))
1075 (consp (nth 3 flags))) 'designation)
1076 (or (nth 4 flags) 'long-form)
1077 (and (nth 5 flags) 'ascii-at-eol)
1078 (and (nth 6 flags) 'ascii-at-cntl)
1079 (and (nth 7 flags) '7-bit)
1080 (and (nth 8 flags) 'locking-shift)
1081 (and (nth 9 flags) 'single-shift)
1082 (and (nth 10 flags) 'use-roman)
1083 (and (nth 11 flags) 'use-oldjis)
1084 (or (nth 12 flags) 'direction)
1085 (and (nth 13 flags) 'init-at-bol)
1086 (and (nth 14 flags) 'designate-at-bol)
1087 (and (nth 15 flags) 'safe)
1088 (and (nth 16 flags) 'latin-extra)))
1089 (plist-put properties :designation
1090 (let ((vec (make-vector 4 nil)))
1091 (dotimes (i 4)
1092 (let ((spec (nth i flags)))
1093 (if (eq spec t)
1094 (aset vec i '(94 96))
1095 (if (consp spec)
1096 (progn
1097 (if (memq t spec)
1098 (setq spec (append (delq t spec) '(94 96))))
1099 (aset vec i spec))))))
1100 vec)))
1101
1102 ((eq type 'ccl)
1103 (plist-put properties :ccl-decoder (car flags))
1104 (plist-put properties :ccl-encoder (cdr flags))))
1105
1106 (apply 'define-coding-system coding-system doc-string properties))
4ed46869 1107
bbdea948
RS
1108(defun merge-coding-systems (first second)
1109 "Fill in any unspecified aspects of coding system FIRST from SECOND.
1110Return the resulting coding system."
1111 (let ((base (coding-system-base second))
1112 (eol (coding-system-eol-type second)))
1113 ;; If FIRST doesn't specify text conversion, merge with that of SECOND.
1114 (if (eq (coding-system-base first) 'undecided)
1115 (setq first (coding-system-change-text-conversion first base)))
1116 ;; If FIRST doesn't specify eol conversion, merge with that of SECOND.
1117 (if (and (vectorp (coding-system-eol-type first))
1118 (numberp eol) (>= eol 0) (<= eol 2))
1119 (setq first (coding-system-change-eol-conversion
1120 first eol)))
1121 first))
1122
2da14137
KH
1123(defun autoload-coding-system (symbol form)
1124 "Define SYMBOL as a coding-system that is defined on demand.
1125
f81b2db1 1126FORM is a form to evaluate to define the coding-system."
2da14137
KH
1127 (put symbol 'coding-system-define-form form)
1128 (setq coding-system-alist (cons (list (symbol-name symbol))
1129 coding-system-alist))
1130 (dolist (elt '("-unix" "-dos" "-mac"))
1131 (let ((name (concat (symbol-name symbol) elt)))
1132 (put (intern name) 'coding-system-define-form form)
1133 (setq coding-system-alist (cons (list name) coding-system-alist)))))
1134
4c549102
KH
1135;; This variable is set in these three cases:
1136;; (1) A file is read by a coding system specified explicitly.
1137;; after-insert-file-set-coding sets the car of this value to
1138;; coding-system-for-read, and sets the cdr to nil.
1139;; (2) A buffer is saved.
1140;; After writing, basic-save-buffer-1 sets the car of this value
1141;; to last-coding-system-used.
1142;; (3) set-buffer-file-coding-system is called.
1143;; The cdr of this value is set to the specified coding system.
1144;; This variable is used for decoding in revert-buffer and encoding in
1145;; select-safe-coding-system.
1146(defvar buffer-file-coding-system-explicit nil
1147 "The file coding system explicitly specified for the current buffer.
1148The value is a cons of coding systems for reading (decoding) and
1149writing (encoding).
1150Internal use only.")
1151(make-variable-buffer-local 'buffer-file-coding-system-explicit)
1152(put 'buffer-file-coding-system-explicit 'permanent-local t)
1153
87926e02
SM
1154(defun read-buffer-file-coding-system ()
1155 (let* ((bcss (find-coding-systems-region (point-min) (point-max)))
1156 (css-table
1157 (unless (equal bcss '(undecided))
1158 (append '("dos" "unix" "mac")
1159 (delq nil (mapcar (lambda (cs)
1160 (if (memq (coding-system-base cs) bcss)
1161 (symbol-name cs)))
1162 coding-system-list)))))
1163 (combined-table
1164 (if css-table
1165 (completion-table-in-turn css-table coding-system-alist)
1166 coding-system-alist))
1167 (auto-cs
1168 (unless find-file-literally
1169 (save-excursion
1170 (save-restriction
1171 (widen)
1172 (goto-char (point-min))
1173 (funcall set-auto-coding-function
1174 (or buffer-file-name "") (buffer-size))))))
1175 (preferred
1176 (let ((bfcs (default-value 'buffer-file-coding-system)))
1177 (cons (and (or (equal bcss '(undecided))
1178 (memq (coding-system-base bfcs) bcss))
1179 bfcs)
1180 (mapcar (lambda (cs)
1181 (and (coding-system-p cs)
1182 (coding-system-get cs :mime-charset)
1183 (or (equal bcss '(undecided))
1184 (memq (coding-system-base cs) bcss))
1185 cs))
1186 (coding-system-priority-list)))))
1187 (default
1188 (let ((current (coding-system-base buffer-file-coding-system)))
1189 ;; Generally use as a default the first preferred coding-system
1190 ;; different from the current coding-system, except for
1191 ;; the case of auto-cs since choosing anything else is asking
1192 ;; for trouble (would lead to using a different coding
1193 ;; system than specified in the coding tag).
1194 (or auto-cs
1195 (car (delq nil
1196 (mapcar (lambda (cs)
1197 (if (eq current (coding-system-base cs))
1198 nil
1199 cs))
1200 preferred))))))
1201 (completion-ignore-case t)
1202 (completion-pcm--delim-wild-regex ; Let "u8" complete to "utf-8".
1203 (concat completion-pcm--delim-wild-regex
1204 "\\|\\([[:alpha:]]\\)[[:digit:]]"))
1205 (cs (completing-read
1206 (format "Coding system for saving file (default %s): " default)
1207 combined-table
1208 nil t nil 'coding-system-history
1209 (if default (symbol-name default)))))
1210 (unless (zerop (length cs)) (intern cs))))
1211
14b3fa07 1212(defun set-buffer-file-coding-system (coding-system &optional force nomodify)
358d28fb
RS
1213 "Set the file coding-system of the current buffer to CODING-SYSTEM.
1214This means that when you save the buffer, it will be converted
f81b2db1
JB
1215according to CODING-SYSTEM. For a list of possible values of
1216CODING-SYSTEM, use \\[list-coding-systems].
358d28fb 1217
f81b2db1
JB
1218If CODING-SYSTEM leaves the text conversion unspecified, or if it leaves
1219the end-of-line conversion unspecified, FORCE controls what to do.
1220If FORCE is nil, get the unspecified aspect (or aspects) from the buffer's
1221previous `buffer-file-coding-system' value (if it is specified there).
1222Otherwise, leave it unspecified.
aeef8f07
KH
1223
1224This marks the buffer modified so that the succeeding \\[save-buffer]
1225surely saves the buffer with CODING-SYSTEM. From a program, if you
14b3fa07
RS
1226don't want to mark the buffer modified, specify t for NOMODIFY.
1227If you know exactly what coding system you want to use,
1228just set the variable `buffer-file-coding-system' directly."
87926e02
SM
1229 (interactive
1230 (list (read-buffer-file-coding-system)
1231 current-prefix-arg))
4ed46869 1232 (check-coding-system coding-system)
36d455c4 1233 (if (and coding-system buffer-file-coding-system (null force))
bbdea948
RS
1234 (setq coding-system
1235 (merge-coding-systems coding-system buffer-file-coding-system)))
87926e02
SM
1236 (when (called-interactively-p 'interactive)
1237 ;; Check whether save would succeed, and jump to the offending char(s)
1238 ;; if not.
1239 (let ((css (find-coding-systems-region (point-min) (point-max))))
1240 (unless (or (eq (car css) 'undecided)
1241 (memq (coding-system-base coding-system) css))
1242 (setq coding-system (select-safe-coding-system-interactively
1243 (point-min) (point-max) css
1244 (list coding-system))))))
4ed46869 1245 (setq buffer-file-coding-system coding-system)
4c549102
KH
1246 (if buffer-file-coding-system-explicit
1247 (setcdr buffer-file-coding-system-explicit coding-system)
1248 (setq buffer-file-coding-system-explicit (cons nil coding-system)))
de5ffead
RS
1249 (unless nomodify
1250 (set-buffer-modified-p t))
4ed46869
KH
1251 (force-mode-line-update))
1252
bbdea948
RS
1253(defun revert-buffer-with-coding-system (coding-system &optional force)
1254 "Visit the current buffer's file again using coding system CODING-SYSTEM.
1255For a list of possible values of CODING-SYSTEM, use \\[list-coding-systems].
1256
f81b2db1
JB
1257If CODING-SYSTEM leaves the text conversion unspecified, or if it leaves
1258the end-of-line conversion unspecified, FORCE controls what to do.
1259If FORCE is nil, get the unspecified aspect (or aspects) from the buffer's
1260previous `buffer-file-coding-system' value (if it is specified there).
1261Otherwise, determine it from the file contents as usual for visiting a file."
5b76833f 1262 (interactive "zCoding system for visited file (default nil): \nP")
bbdea948
RS
1263 (check-coding-system coding-system)
1264 (if (and coding-system buffer-file-coding-system (null force))
1265 (setq coding-system
1266 (merge-coding-systems coding-system buffer-file-coding-system)))
1267 (let ((coding-system-for-read coding-system))
1268 (revert-buffer)))
1269
701414e3
KH
1270(defun set-file-name-coding-system (coding-system)
1271 "Set coding system for decoding and encoding file names to CODING-SYSTEM.
f81b2db1
JB
1272It actually just set the variable `file-name-coding-system' (which see)
1273to CODING-SYSTEM."
5b76833f 1274 (interactive "zCoding system for file names (default nil): ")
701414e3 1275 (check-coding-system coding-system)
356384dc
KH
1276 (if (and coding-system
1277 (not (coding-system-get coding-system :ascii-compatible-p))
1278 (not (coding-system-get coding-system :suitable-for-file-name)))
1279 (error "%s is not suitable for file names" coding-system))
701414e3
KH
1280 (setq file-name-coding-system coding-system))
1281
358d28fb
RS
1282(defvar default-terminal-coding-system nil
1283 "Default value for the terminal coding system.
1284This is normally set according to the selected language environment.
1285See also the command `set-terminal-coding-system'.")
1286
4b77f8a3 1287(defun set-terminal-coding-system (coding-system &optional terminal)
68bba4e4 1288 "Set coding system of terminal output to CODING-SYSTEM.
4b77f8a3 1289All text output to TERMINAL will be encoded
358d28fb 1290with the specified coding system.
68bba4e4 1291
358d28fb
RS
1292For a list of possible values of CODING-SYSTEM, use \\[list-coding-systems].
1293The default is determined by the selected language environment
68bba4e4
KL
1294or by the previous use of this command.
1295
4b77f8a3
CY
1296TERMINAL may be a terminal object, a frame, or nil for the
1297selected frame's terminal. The setting has no effect on
1298graphical terminals."
358d28fb 1299 (interactive
2e02a76f
RS
1300 (list (let ((default (if (and (not (terminal-coding-system))
1301 default-terminal-coding-system)
1302 default-terminal-coding-system)))
1303 (read-coding-system
5b76833f 1304 (format "Coding system for terminal display (default %s): "
2e02a76f
RS
1305 default)
1306 default))))
358d28fb
RS
1307 (if (and (not coding-system)
1308 (not (terminal-coding-system)))
1309 (setq coding-system default-terminal-coding-system))
1310 (if coding-system
521d4010 1311 (setq default-terminal-coding-system coding-system))
4b77f8a3 1312 (set-terminal-coding-system-internal coding-system terminal)
df100398
KH
1313 (redraw-frame (selected-frame)))
1314
358d28fb
RS
1315(defvar default-keyboard-coding-system nil
1316 "Default value of the keyboard coding system.
1317This is normally set according to the selected language environment.
1318See also the command `set-keyboard-coding-system'.")
1319
4b77f8a3
CY
1320(defun set-keyboard-coding-system (coding-system &optional terminal)
1321 "Set coding system for keyboard input on TERMINAL to CODING-SYSTEM.
68bba4e4 1322
358d28fb
RS
1323For a list of possible values of CODING-SYSTEM, use \\[list-coding-systems].
1324The default is determined by the selected language environment
68bba4e4
KL
1325or by the previous use of this command.
1326
3dcad254
KH
1327If CODING-SYSTEM is nil or the coding-type of CODING-SYSTEM is
1328`raw-text', the decoding of keyboard input is disabled.
1329
4b77f8a3
CY
1330TERMINAL may be a terminal object, a frame, or nil for the
1331selected frame's terminal. The setting has no effect on
1332graphical terminals."
358d28fb 1333 (interactive
3dcad254
KH
1334 (list (let* ((coding (keyboard-coding-system nil))
1335 (default (if (eq (coding-system-type coding) 'raw-text)
1336 default-keyboard-coding-system)))
2e02a76f 1337 (read-coding-system
5b76833f 1338 (format "Coding system for keyboard input (default %s): "
2e02a76f
RS
1339 default)
1340 default))))
3dcad254
KH
1341 (let ((coding-type (coding-system-type coding-system))
1342 (saved-meta-mode
1343 (terminal-parameter terminal 'keyboard-coding-saved-meta-mode)))
1344 (if (not (eq coding-type 'raw-text))
1345 (let (accept-8-bit)
1346 (if (not (or (coding-system-get coding-system :suitable-for-keyboard)
1347 (coding-system-get coding-system :ascii-compatible-p)))
1348 (error "Unsuitable coding system for keyboard: %s" coding-system))
1349 (cond ((memq coding-type '(charset utf-8 shift-jis big5 ccl))
1350 (setq accept-8-bit t))
1351 ((eq coding-type 'iso-2022)
1352 (let ((flags (coding-system-get coding-system :flags)))
1353 (or (memq '7-bit flags)
1354 (setq accept-8-bit t))))
1355 (t
1356 (error "Unsupported coding system for keyboard: %s"
1357 coding-system)))
b278604e
KH
1358 (if accept-8-bit
1359 (progn
1360 (or saved-meta-mode
1361 (set-terminal-parameter terminal
1362 'keyboard-coding-saved-meta-mode
1363 (cons (nth 2 (current-input-mode))
1364 nil)))
1365 (set-input-meta-mode 8 terminal))
1366 (when saved-meta-mode
1367 (set-input-meta-mode (car saved-meta-mode) terminal)
1368 (set-terminal-parameter terminal
1369 'keyboard-coding-saved-meta-mode
1370 nil)))
af0403e0
KH
1371 ;; Avoid end-of-line conversion.
1372 (setq coding-system
1373 (coding-system-change-eol-conversion coding-system 'unix)))
3dcad254
KH
1374
1375 (when saved-meta-mode
b278604e 1376 (set-input-meta-mode (car saved-meta-mode) terminal)
3dcad254
KH
1377 (set-terminal-parameter terminal
1378 'keyboard-coding-saved-meta-mode
1379 nil))))
4b77f8a3 1380 (set-keyboard-coding-system-internal coding-system terminal)
3dcad254 1381 (setq keyboard-coding-system coding-system))
df100398 1382
6d34f495
DL
1383(defcustom keyboard-coding-system nil
1384 "Specify coding system for keyboard input.
1385If you set this on a terminal which can't distinguish Meta keys from
13868-bit characters, you will have to use ESC to type Meta characters.
50e5c885 1387See Info node `Terminal Coding' and Info node `Unibyte Mode'.
6d34f495 1388
237e5993
DL
1389On non-windowing terminals, this is set from the locale by default.
1390
6d34f495 1391Setting this variable directly does not take effect;
6b61353c 1392use either \\[customize] or \\[set-keyboard-coding-system]."
6d34f495 1393 :type '(coding-system :tag "Coding system")
50e5c885
EZ
1394 :link '(info-link "(emacs)Terminal Coding")
1395 :link '(info-link "(emacs)Unibyte Mode")
6d34f495 1396 :set (lambda (symbol value)
2a42d440
KL
1397 ;; Don't load encoded-kb unnecessarily.
1398 (if (or value (boundp 'encoded-kbd-setup-display))
6d34f495
DL
1399 (set-keyboard-coding-system value)
1400 (set-default 'keyboard-coding-system nil))) ; must initialize
bf247b6e 1401 :version "22.1"
6d34f495
DL
1402 :group 'keyboard
1403 :group 'mule)
1404
df100398 1405(defun set-buffer-process-coding-system (decoding encoding)
358d28fb 1406 "Set coding systems for the process associated with the current buffer.
df100398 1407DECODING is the coding system to be used to decode input from the process,
358d28fb
RS
1408ENCODING is the coding system to be used to encode output to the process.
1409
f81b2db1 1410For a list of possible coding systems, use \\[list-coding-systems]."
4ed46869 1411 (interactive
83911021 1412 "zCoding-system for output from the process: \nzCoding-system for input to the process: ")
4ed46869
KH
1413 (let ((proc (get-buffer-process (current-buffer))))
1414 (if (null proc)
521d4010 1415 (error "No process")
df100398
KH
1416 (check-coding-system decoding)
1417 (check-coding-system encoding)
1418 (set-process-coding-system proc decoding encoding)))
4ed46869
KH
1419 (force-mode-line-update))
1420
d0b99881
RS
1421(defalias 'set-clipboard-coding-system 'set-selection-coding-system)
1422
14915c37 1423(defun set-selection-coding-system (coding-system)
8c52d564 1424 "Make CODING-SYSTEM used for communicating with other X clients.
b25eef20
KH
1425When sending or receiving text via cut_buffer, selection, and clipboard,
1426the text is encoded or decoded by CODING-SYSTEM."
a03b3ce1 1427 (interactive "zCoding system for X selection: ")
b25eef20 1428 (check-coding-system coding-system)
14915c37 1429 (setq selection-coding-system coding-system))
b25eef20 1430
e8dd0160 1431;; Coding system lastly specified by the command
a03b3ce1
KH
1432;; set-next-selection-coding-system.
1433(defvar last-next-selection-coding-system nil)
1434
1435(defun set-next-selection-coding-system (coding-system)
12504f57 1436 "Use CODING-SYSTEM for next communication with other window system clients.
a03b3ce1
KH
1437This setting is effective for the next communication only."
1438 (interactive
1439 (list (read-coding-system
1440 (if last-next-selection-coding-system
7b9dc9af 1441 (format "Coding system for the next selection (default %S): "
a03b3ce1 1442 last-next-selection-coding-system)
12504f57 1443 "Coding system for the next selection: ")
a03b3ce1
KH
1444 last-next-selection-coding-system)))
1445 (if coding-system
1446 (setq last-next-selection-coding-system coding-system)
1447 (setq coding-system last-next-selection-coding-system))
1448 (check-coding-system coding-system)
1449
1450 (setq next-selection-coding-system coding-system))
1451
4ed46869 1452(defun set-coding-priority (arg)
521d4010 1453 "Set priority of coding categories according to ARG.
c1841772
KH
1454ARG is a list of coding categories ordered by priority.
1455
f81b2db1 1456This function is provided for backward compatibility."
a5f2b6ec 1457 (declare (obsolete set-coding-system-priority "23.1"))
5d75f46f
KH
1458 (apply 'set-coding-system-priority
1459 (mapcar #'(lambda (x) (symbol-value x)) arg)))
4ed46869 1460
835cbadb
EZ
1461;;; X selections
1462
cc926903 1463(defvar ctext-non-standard-encodings-alist
6d341a2a 1464 (mapcar 'purecopy
e0bd7bb9 1465 '(("big5-0" big5 2 big5)
6b61353c 1466 ("ISO8859-14" iso-8859-14 1 latin-iso8859-14)
e0bd7bb9 1467 ("ISO8859-15" iso-8859-15 1 latin-iso8859-15)
6b4d96c2
KH
1468 ("gbk-0" gbk 2 chinese-gbk)
1469 ("koi8-r" koi8-r 1 koi8-r)
1470 ("microsoft-cp1251" windows-1251 1 windows-1251)))
6b61353c
KH
1471 "Alist of non-standard encoding names vs the corresponding usages in CTEXT.
1472
1473It controls how extended segments of a compound text are handled
1474by the coding system `compound-text-with-extensions'.
1475
1476Each element has the form (ENCODING-NAME CODING-SYSTEM N-OCTET CHARSET).
1477
f81b2db1 1478ENCODING-NAME is an encoding name of an \"extended segment\".
6b61353c
KH
1479
1480CODING-SYSTEM is the coding-system to encode (or decode) the
1481characters into (or from) the extended segment.
1482
1483N-OCTET is the number of octets (bytes) that encodes a character
1484in the segment. It can be 0 (meaning the number of octets per
1485character is variable), 1, 2, 3, or 4.
1486
f81b2db1 1487CHARSET is a character set containing characters that are encoded
e0bd7bb9 1488in the segment. It can be a list of character sets.
6b61353c
KH
1489
1490On decoding CTEXT, all encoding names listed here are recognized.
1491
1492On encoding CTEXT, encoding names in the variable
1493`ctext-non-standard-encodings' (which see) and in the information
1494listed for the current language environment under the key
1495`ctext-non-standard-encodings' are used.")
1496
e0bd7bb9 1497(defvar ctext-non-standard-encodings nil
6b61353c
KH
1498 "List of non-standard encoding names used in extended segments of CTEXT.
1499Each element must be one of the names listed in the variable
1500`ctext-non-standard-encodings-alist' (which see).")
cc926903
KH
1501
1502(defvar ctext-non-standard-encodings-regexp
6d341a2a 1503 (purecopy
cc926903
KH
1504 (string-to-multibyte
1505 (concat
1506 ;; For non-standard encodings.
1507 "\\(\e%/[0-4][\200-\377][\200-\377]\\([^\002]+\\)\002\\)"
1508 "\\|"
1509 ;; For UTF-8 encoding.
6d341a2a 1510 "\\(\e%G[^\e]*\e%@\\)"))))
835cbadb
EZ
1511
1512;; Functions to support "Non-Standard Character Set Encodings" defined
6b61353c
KH
1513;; by the COMPOUND-TEXT spec. They also support "The UTF-8 encoding"
1514;; described in the section 7 of the documentation of COMPOUND-TEXT
1515;; distributed with XFree86.
5c88a01e 1516
835cbadb
EZ
1517(defun ctext-post-read-conversion (len)
1518 "Decode LEN characters encoded as Compound Text with Extended Segments."
1894d108
KH
1519 ;; We don't need the following because it is expected that this
1520 ;; function is mainly used for decoding X selection which is not
1521 ;; that big data.
1522 ;;(buffer-disable-undo) ; minimize consing due to insertions and deletions
835cbadb 1523 (save-match-data
cc926903 1524 (save-restriction
1894d108 1525 (narrow-to-region (point) (+ (point) len))
cc926903 1526 (let ((case-fold-search nil)
cc926903
KH
1527 last-coding-system-used
1528 pos bytes)
cc926903 1529 (decode-coding-region (point-min) (point-max) 'ctext)
cc926903
KH
1530 (while (re-search-forward ctext-non-standard-encodings-regexp
1531 nil 'move)
1532 (setq pos (match-beginning 0))
1533 (if (match-beginning 1)
1534 ;; ESC % / [0-4] M L --ENCODING-NAME-- \002 --BYTES--
e0bd7bb9
KH
1535 (let* ((M (multibyte-char-to-unibyte (char-after (+ pos 4))))
1536 (L (multibyte-char-to-unibyte (char-after (+ pos 5))))
cc926903 1537 (encoding (match-string 2))
9857367f 1538 (encoding-info (assoc-string
6b61353c 1539 encoding
c12bc1fb 1540 ctext-non-standard-encodings-alist t))
6b61353c
KH
1541 (coding (if encoding-info
1542 (nth 1 encoding-info)
1543 (setq encoding (intern (downcase encoding)))
1544 (and (coding-system-p encoding)
1545 encoding))))
cc926903
KH
1546 (setq bytes (- (+ (* (- M 128) 128) (- L 128))
1547 (- (point) (+ pos 6))))
1548 (when coding
1549 (delete-region pos (point))
1550 (forward-char bytes)
1551 (decode-coding-region (- (point) bytes) (point) coding)))
1552 ;; ESC % G --UTF-8-BYTES-- ESC % @
6b61353c
KH
1553 (delete-char -3)
1554 (delete-region pos (+ pos 3))
1555 (decode-coding-region pos (point) 'utf-8))))
cc926903
KH
1556 (goto-char (point-min))
1557 (- (point-max) (point)))))
835cbadb 1558
6b4d96c2
KH
1559(defvar ctext-standard-encodings
1560 '(ascii latin-jisx0201 katakana-jisx0201
1561 latin-iso8859-1 latin-iso8859-2 latin-iso8859-3 latin-iso8859-4
1562 greek-iso8859-7 arabic-iso8859-6 hebrew-iso8859-8 cyrillic-iso8859-5
1563 latin-iso8859-9
1564 chinese-gb2312 japanese-jisx0208 korean-ksc5601)
1565 "List of approved standard encodings (i.e. charsets) of X's Compound Text.
1566Coding-system `compound-text-with-extensions' encodes a character
1567belonging to any of those charsets using the normal ISO2022
1568designation sequence unless the current language environment or
1569the variable `ctext-non-standard-encodings' decide to use an extended
1570segment of CTEXT for that character. See also the documentation
1571of `ctext-non-standard-encodings-alist'.")
1572
e0bd7bb9
KH
1573;; Return an alist of CHARSET vs CTEXT-USAGE-INFO generated from
1574;; `ctext-non-standard-encodings' and a list specified by the key
c7015153 1575;; `ctext-non-standard-encodings' for the current language
e0bd7bb9
KH
1576;; environment. CTEXT-USAGE-INFO is one of the element of
1577;; `ctext-non-standard-encodings-alist' or nil. In the former case, a
1578;; character in CHARSET is encoded using extended segment. In the
1579;; latter case, a character in CHARSET is encoded using normal ISO2022
1580;; designation sequence. If a character is not in any of CHARSETs, it
cd1181db 1581;; is encoded using UTF-8 encoding extension.
6b61353c
KH
1582
1583(defun ctext-non-standard-encodings-table ()
6b4d96c2
KH
1584 (let* ((table (append ctext-non-standard-encodings
1585 (copy-sequence
1586 (get-language-info current-language-environment
1587 'ctext-non-standard-encodings))))
1588 (tail table)
1589 elt)
1590 (while tail
1591 (setq elt (car tail))
1592 (let* ((slot (assoc elt ctext-non-standard-encodings-alist))
6b61353c 1593 (charset (nth 3 slot)))
e0bd7bb9 1594 (if (charsetp charset)
7a84eee5
KH
1595 (setcar tail
1596 (cons (plist-get (charset-plist charset) :base) slot))
6b4d96c2
KH
1597 (setcar tail (cons (car charset) slot))
1598 (dolist (cs (cdr charset))
1599 (setcdr tail
7a84eee5
KH
1600 (cons (cons (plist-get (charset-plist (car cs)) :base) slot)
1601 (cdr tail)))
6b4d96c2
KH
1602 (setq tail (cdr tail))))
1603 (setq tail (cdr tail))))
1604 table))
835cbadb
EZ
1605
1606(defun ctext-pre-write-conversion (from to)
5dde3c71
EZ
1607 "Encode characters between FROM and TO as Compound Text w/Extended Segments.
1608
6b4d96c2
KH
1609If FROM is a string, generate a new temp buffer, insert the text,
1610and convert it in the temporary buffer. Otherwise, convert
1611in-place."
835cbadb 1612 (save-match-data
cc926903 1613 ;; Setup a working buffer if necessary.
f1beb0e0
KH
1614 (when (stringp from)
1615 (set-buffer (generate-new-buffer " *temp"))
1616 (set-buffer-multibyte (multibyte-string-p from))
6b4d96c2 1617 (insert from)
8dabbfd6 1618 (setq from (point-min) to (point-max)))
6b4d96c2
KH
1619 (save-restriction
1620 (narrow-to-region from to)
7a84eee5 1621 (goto-char from)
6b4d96c2 1622 (let ((encoding-table (ctext-non-standard-encodings-table))
7a84eee5
KH
1623 (charset-list (sort-charsets
1624 (copy-sequence ctext-standard-encodings)))
1625 (end-pos (make-marker))
6b4d96c2 1626 last-coding-system-used
7a84eee5 1627 last-pos charset encoding-info)
6b4d96c2
KH
1628 (dolist (elt encoding-table)
1629 (push (car elt) charset-list))
6b4d96c2 1630 (setq end-pos (point-marker))
7a84eee5 1631 (while (re-search-forward "[^\0-\177]+" nil t)
6b4d96c2 1632 ;; Found a sequence of non-ASCII characters.
6b4d96c2 1633 (set-marker end-pos (match-end 0))
7a84eee5
KH
1634 (goto-char (match-beginning 0))
1635 (setq last-pos (point)
1636 charset (char-charset (following-char) charset-list))
1637 (forward-char 1)
1638 (while (and (< (point) end-pos)
1639 (eq charset (char-charset (following-char) charset-list)))
1640 (forward-char 1))
1641 (if charset
1642 (if (setq encoding-info (cdr (assq charset encoding-table)))
1643 ;; Encode this range using an extended segment.
1644 (let ((encoding-name (car encoding-info))
1645 (coding-system (nth 1 encoding-info))
1646 (noctets (nth 2 encoding-info))
1647 len)
1648 (encode-coding-region last-pos (point) coding-system)
1649 (setq len (+ (length encoding-name) 1
1650 (- (point) last-pos)))
1651 ;; According to the spec of CTEXT, it is not
1652 ;; necessary to produce this extra designation
1653 ;; sequence, but some buggy application
1654 ;; (e.g. crxvt-gb) requires it.
1655 (insert "\e(B")
1656 (save-excursion
1657 (goto-char last-pos)
1658 (insert (format "\e%%/%d" noctets))
1659 (insert-byte (+ (/ len 128) 128) 1)
1660 (insert-byte (+ (% len 128) 128) 1)
1661 (insert encoding-name)
1662 (insert 2)))
1663 ;; Encode this range as characters in CHARSET.
1664 (put-text-property last-pos (point) 'charset charset))
cd1181db 1665 ;; Encode this range using UTF-8 encoding extension.
7a84eee5
KH
1666 (encode-coding-region last-pos (point) 'mule-utf-8)
1667 (save-excursion
1668 (goto-char last-pos)
1669 (insert "\e%G"))
1670 (insert "\e%@")))
6b4d96c2 1671 (goto-char (point-min)))))
5dde3c71 1672 ;; Must return nil, as build_annotations_2 expects that.
835cbadb
EZ
1673 nil)
1674
4ed46869
KH
1675;;; FILE I/O
1676
117a9ea1 1677;; TODO many elements of this list are also in inhibit-local-variables-regexps.
e76938e7 1678(defcustom auto-coding-alist
3a6a5981
CY
1679 ;; .exe and .EXE are added to support archive-mode looking at DOS
1680 ;; self-extracting exe archives.
e8e4d5c8
SS
1681 (mapcar (lambda (arg) (cons (purecopy (car arg)) (cdr arg)))
1682 '(("\\.\\(\
b3671a51
JL
1683arc\\|zip\\|lzh\\|lha\\|zoo\\|[jew]ar\\|xpi\\|rar\\|7z\\|\
1684ARC\\|ZIP\\|LZH\\|LHA\\|ZOO\\|[JEW]AR\\|XPI\\|RAR\\|7Z\\)\\'"
e8e4d5c8 1685 . no-conversion-multibyte)
03f244e2 1686 ("\\.\\(exe\\|EXE\\)\\'" . no-conversion)
117a9ea1 1687 ("\\.\\(sx[dmicw]\\|odt\\|tar\\|t[bg]z\\)\\'" . no-conversion)
4c964351 1688 ("\\.\\(gz\\|Z\\|bz\\|bz2\\|xz\\|gpg\\)\\'" . no-conversion)
ba40634b 1689 ("\\.\\(jpe?g\\|png\\|gif\\|tiff?\\|p[bpgn]m\\)\\'" . no-conversion)
6f37a576 1690 ("\\.pdf\\'" . no-conversion)
3b6acc72 1691 ("/#[^/]+#\\'" . emacs-mule)))
835f49b8
KH
1692 "Alist of filename patterns vs corresponding coding systems.
1693Each element looks like (REGEXP . CODING-SYSTEM).
558b0c86 1694A file whose name matches REGEXP is decoded by CODING-SYSTEM on reading.
835f49b8 1695
7fed493a
RS
1696The settings in this alist take priority over `coding:' tags
1697in the file (see the function `set-auto-coding')
e76938e7 1698and the contents of `file-coding-system-alist'."
4c964351 1699 :version "24.1" ; added xz
e76938e7
DL
1700 :group 'files
1701 :group 'mule
1702 :type '(repeat (cons (regexp :tag "File name regexp")
1703 (symbol :tag "Coding system"))))
835f49b8 1704
502522b2 1705(defcustom auto-coding-regexp-alist
e8e4d5c8 1706 (mapcar (lambda (arg) (cons (purecopy (car arg)) (cdr arg)))
da332cfb 1707 '(("\\`BABYL OPTIONS:[ \t]*-\\*-[ \t]*rmail[ \t]*-\\*-" . no-conversion)
dc5c3489
KH
1708 ("\\`\xFE\xFF" . utf-16be-with-signature)
1709 ("\\`\xFF\xFE" . utf-16le-with-signature)
c855d682 1710 ("\\`\xEF\xBB\xBF" . utf-8-with-signature)
3b6acc72 1711 ("\\`;ELC\024\0\0\0" . emacs-mule))) ; Emacs 20-compiled
502522b2
GM
1712 "Alist of patterns vs corresponding coding systems.
1713Each element looks like (REGEXP . CODING-SYSTEM).
1714A file whose first bytes match REGEXP is decoded by CODING-SYSTEM on reading.
1715
1716The settings in this alist take priority over `coding:' tags
1717in the file (see the function `set-auto-coding')
1718and the contents of `file-coding-system-alist'."
1719 :group 'files
1720 :group 'mule
1721 :type '(repeat (cons (regexp :tag "Regexp")
1722 (symbol :tag "Coding system"))))
1723
0814ca04
KH
1724(defun auto-coding-regexp-alist-lookup (from to)
1725 "Lookup `auto-coding-regexp-alist' for the contents of the current buffer.
1726The value is a coding system is specified for the region FROM and TO,
1727or nil."
1728 (save-excursion
1729 (goto-char from)
1730 (let ((alist auto-coding-regexp-alist)
1731 coding-system)
1732 (while (and alist (not coding-system))
1733 (let ((regexp (car (car alist))))
1734 (if enable-multibyte-characters
1735 (setq regexp (string-to-multibyte regexp)))
1736 (if (re-search-forward regexp to t)
1737 (setq coding-system (cdr (car alist)))
1738 (setq alist (cdr alist)))))
1739 coding-system)))
1740
d9f6dfe6 1741;; See the bottom of this file for built-in auto coding functions.
447404a3
CW
1742(defcustom auto-coding-functions '(sgml-xml-auto-coding-function
1743 sgml-html-meta-auto-coding-function)
d9f6dfe6
CW
1744 "A list of functions which attempt to determine a coding system.
1745
66643502
RS
1746Each function in this list should be written to operate on the
1747current buffer, but should not modify it in any way. The buffer
1748will contain undecoded text of parts of the file. Each function
f81b2db1
JB
1749should take one argument, SIZE, which says how many characters
1750\(starting from point) it should look at.
66643502
RS
1751
1752If one of these functions succeeds in determining a coding
1753system, it should return that coding system. Otherwise, it
1754should return nil.
1755
1756If a file has a `coding:' tag, that takes precedence over these
1757functions, so they won't be called at all."
d9f6dfe6
CW
1758 :group 'files
1759 :group 'mule
1760 :type '(repeat function))
1761
1c4cc63a 1762(defvar set-auto-coding-for-load nil
8edb942b
GM
1763 "Non-nil means respect a \"unibyte: t\" entry in file local variables.
1764Emacs binds this variable to t when loading or byte-compiling Emacs Lisp
1765files.")
1c4cc63a 1766
8a592131
RS
1767(defun auto-coding-alist-lookup (filename)
1768 "Return the coding system specified by `auto-coding-alist' for FILENAME."
1769 (let ((alist auto-coding-alist)
7c2fb837 1770 (case-fold-search (memq system-type '(windows-nt ms-dos cygwin)))
8a592131
RS
1771 coding-system)
1772 (while (and alist (not coding-system))
1773 (if (string-match (car (car alist)) filename)
1774 (setq coding-system (cdr (car alist)))
1775 (setq alist (cdr alist))))
1776 coding-system))
1777
09e5712d
KH
1778(put 'enable-character-translation 'permanent-local t)
1779(put 'enable-character-translation 'safe-local-variable 'booleanp)
1780
e9b01d1f
KH
1781(defun find-auto-coding (filename size)
1782 "Find a coding system for a file FILENAME of which SIZE bytes follow point.
1c4cc63a
KH
1783These bytes should include at least the first 1k of the file
1784and the last 3k of the file, but the middle may be omitted.
63561304 1785
d21ba5e0
DL
1786The function checks FILENAME against the variable `auto-coding-alist'.
1787If FILENAME doesn't match any entries in the variable, it checks the
502522b2 1788contents of the current buffer following point against
447404a3 1789`auto-coding-regexp-alist'. If no match is found, it checks for a
502522b2 1790`coding:' tag in the first one or two lines following point. If no
d21ba5e0 1791`coding:' tag is found, it checks any local variables list in the last
447404a3 17923K bytes out of the SIZE bytes. Finally, if none of these methods
d21ba5e0
DL
1793succeed, it checks to see if any function in `auto-coding-functions'
1794gives a match.
63561304 1795
c80e3b4a 1796If a coding system is specified, the return value is a cons
f81b2db1
JB
1797\(CODING . SOURCE), where CODING is the specified coding system and
1798SOURCE is a symbol `auto-coding-alist', `auto-coding-regexp-alist',
d5c78b09 1799`:coding', or `auto-coding-functions' indicating by what CODING is
f81b2db1
JB
1800specified. Note that the validity of CODING is not checked;
1801it's the caller's responsibility to check it.
e9b01d1f 1802
0814ca04 1803If nothing is specified, the return value is nil."
e9b01d1f
KH
1804 (or (let ((coding-system (auto-coding-alist-lookup filename)))
1805 (if coding-system
1806 (cons coding-system 'auto-coding-alist)))
447404a3 1807 ;; Try using `auto-coding-regexp-alist'.
0814ca04
KH
1808 (let ((coding-system (auto-coding-regexp-alist-lookup (point)
1809 (+ (point) size))))
1810 (if coding-system
1811 (cons coding-system 'auto-coding-regexp-alist)))
502522b2
GM
1812 (let* ((case-fold-search t)
1813 (head-start (point))
1814 (head-end (+ head-start (min size 1024)))
1815 (tail-start (+ head-start (max (- size 3072) 0)))
1816 (tail-end (+ head-start size))
09e5712d 1817 coding-system head-found tail-found pos char-trans)
502522b2
GM
1818 ;; Try a short cut by searching for the string "coding:"
1819 ;; and for "unibyte:" at the head and tail of SIZE bytes.
1820 (setq head-found (or (search-forward "coding:" head-end t)
09e5712d 1821 (search-forward "unibyte:" head-end t)
5dd1c041 1822 (search-forward "enable-character-translation:"
36e02850 1823 head-end t)))
502522b2
GM
1824 (if (and head-found (> head-found tail-start))
1825 ;; Head and tail are overlapped.
1826 (setq tail-found head-found)
1827 (goto-char tail-start)
1828 (setq tail-found (or (search-forward "coding:" tail-end t)
09e5712d
KH
1829 (search-forward "unibyte:" tail-end t)
1830 (search-forward "enable-character-translation:"
1831 tail-end t))))
502522b2
GM
1832
1833 ;; At first check the head.
1834 (when head-found
1835 (goto-char head-start)
6b66d028
RS
1836 (setq head-end (set-auto-mode-1))
1837 (setq head-start (point))
1d8e9a7c 1838 (when (and head-end (< head-found head-end))
835f49b8 1839 (goto-char head-start)
502522b2
GM
1840 (when (and set-auto-coding-for-load
1841 (re-search-forward
6b66d028 1842 "\\(.*;\\)?[ \t]*unibyte:[ \t]*\\([^ ;]+\\)"
502522b2 1843 head-end t))
03794570
GM
1844 (display-warning 'mule "`unibyte: t' is obsolete; \
1845use \"coding: 'raw-text\" instead." :warning)
502522b2
GM
1846 (setq coding-system 'raw-text))
1847 (when (and (not coding-system)
1848 (re-search-forward
6b66d028 1849 "\\(.*;\\)?[ \t]*coding:[ \t]*\\([^ ;]+\\)"
502522b2 1850 head-end t))
09e5712d
KH
1851 (setq coding-system (intern (match-string 2))))
1852 (when (re-search-forward
36e02850 1853 "\\(.*;\\)?[ \t]*enable-character-translation:[ \t]*\\([^ ;]+\\)"
09e5712d 1854 head-end t)
36e02850 1855 (setq char-trans (match-string 2)))))
502522b2
GM
1856
1857 ;; If no coding: tag in the head, check the tail.
6b61353c
KH
1858 ;; Here we must pay attention to the case that the end-of-line
1859 ;; is just "\r" and we can't use "^" nor "$" in regexp.
09e5712d 1860 (when (and tail-found (or (not coding-system) (not char-trans)))
502522b2 1861 (goto-char tail-start)
df94067b 1862 (re-search-forward "[\r\n]\^L" tail-end t)
502522b2 1863 (if (re-search-forward
9857367f 1864 "[\r\n]\\([^[\r\n]*\\)[ \t]*Local Variables:[ \t]*\\([^\r\n]*\\)[\r\n]"
6b61353c
KH
1865 tail-end t)
1866 ;; The prefix is what comes before "local variables:" in its
1867 ;; line. The suffix is what comes after "local variables:"
502522b2
GM
1868 ;; in its line.
1869 (let* ((prefix (regexp-quote (match-string 1)))
1870 (suffix (regexp-quote (match-string 2)))
1871 (re-coding
1872 (concat
6b61353c 1873 "[\r\n]" prefix
cfe98f50
GM
1874 ;; N.B. without the \n below, the regexp can
1875 ;; eat newlines.
6b61353c
KH
1876 "[ \t]*coding[ \t]*:[ \t]*\\([^ \t\r\n]+\\)[ \t]*"
1877 suffix "[\r\n]"))
502522b2
GM
1878 (re-unibyte
1879 (concat
6b61353c
KH
1880 "[\r\n]" prefix
1881 "[ \t]*unibyte[ \t]*:[ \t]*\\([^ \t\r\n]+\\)[ \t]*"
1882 suffix "[\r\n]"))
09e5712d
KH
1883 (re-char-trans
1884 (concat
1885 "[\r\n]" prefix
36e02850 1886 "[ \t]*enable-character-translation[ \t]*:[ \t]*\\([^ \t\r\n]+\\)[ \t]*"
09e5712d 1887 suffix "[\r\n]"))
502522b2 1888 (re-end
9857367f 1889 (concat "[\r\n]" prefix "[ \t]*End *:[ \t]*" suffix
6b61353c
KH
1890 "[\r\n]?"))
1891 (pos (1- (point))))
1892 (forward-char -1) ; skip back \r or \n.
502522b2
GM
1893 (re-search-forward re-end tail-end 'move)
1894 (setq tail-end (point))
1895 (goto-char pos)
1896 (when (and set-auto-coding-for-load
1897 (re-search-forward re-unibyte tail-end t))
fdcbcff2
GM
1898 (display-warning 'mule "`unibyte: t' is obsolete; \
1899use \"coding: 'raw-text\" instead." :warning)
502522b2
GM
1900 (setq coding-system 'raw-text))
1901 (when (and (not coding-system)
1902 (re-search-forward re-coding tail-end t))
09e5712d
KH
1903 (setq coding-system (intern (match-string 1))))
1904 (when (and (not char-trans)
1905 (re-search-forward re-char-trans tail-end t))
36e02850 1906 (setq char-trans (match-string 1))))))
09e5712d
KH
1907 (if coding-system
1908 ;; If the coding-system name ends with "!", remove it and
1909 ;; set char-trans to "nil".
1910 (let ((name (symbol-name coding-system)))
1911 (if (= (aref name (1- (length name))) ?!)
1912 (setq coding-system (intern (substring name 0 -1))
1913 char-trans "nil"))))
1914 (when (and char-trans
1915 (not (setq char-trans (intern char-trans))))
1916 (make-local-variable 'enable-character-translation)
1917 (setq enable-character-translation nil))
e9b01d1f
KH
1918 (if coding-system
1919 (cons coding-system :coding)))
447404a3
CW
1920 ;; Finally, try all the `auto-coding-functions'.
1921 (let ((funcs auto-coding-functions)
1922 (coding-system nil))
1923 (while (and funcs (not coding-system))
1924 (setq coding-system (condition-case e
1925 (save-excursion
1926 (goto-char (point-min))
1927 (funcall (pop funcs) size))
1928 (error nil))))
e9b01d1f
KH
1929 (if coding-system
1930 (cons coding-system 'auto-coding-functions)))))
1931
1932(defun set-auto-coding (filename size)
1933 "Return coding system for a file FILENAME of which SIZE bytes follow point.
1934See `find-auto-coding' for how the coding system is found.
0814ca04
KH
1935Return nil if an invalid coding system is found.
1936
1937The variable `set-auto-coding-function' (which see) is set to this
1938function by default."
e9b01d1f
KH
1939 (let ((found (find-auto-coding filename size)))
1940 (if (and found (coding-system-p (car found)))
1941 (car found))))
63561304
KH
1942
1943(setq set-auto-coding-function 'set-auto-coding)
87aba788 1944
0436cc1b 1945(defun after-insert-file-set-coding (inserted &optional visit)
872a0a6f
RS
1946 "Set `buffer-file-coding-system' of current buffer after text is inserted.
1947INSERTED is the number of characters that were inserted, as figured
1948in the situation before this function. Return the number of characters
1949inserted, as figured in the situation after. The two numbers can be
0436cc1b
KH
1950different if the buffer has become unibyte.
1951The optional second arg VISIT non-nil means that we are visiting a file."
1952 (if (and visit
1953 coding-system-for-read
1954 (not (eq coding-system-for-read 'auto-save-coding)))
4c549102
KH
1955 (setq buffer-file-coding-system-explicit
1956 (cons coding-system-for-read nil)))
4ed46869
KH
1957 (if last-coding-system-used
1958 (let ((coding-system
14839656 1959 (find-new-buffer-file-coding-system last-coding-system-used)))
a04f3650
KH
1960 (if coding-system
1961 (setq buffer-file-coding-system coding-system))))
d0c26c63 1962 inserted)
4ed46869 1963
8057896b 1964;; The coding-spec and eol-type of coding-system returned is decided
4ed46869
KH
1965;; independently in the following order.
1966;; 1. That of buffer-file-coding-system locally bound.
1967;; 2. That of CODING.
1968
1969(defun find-new-buffer-file-coding-system (coding)
1970 "Return a coding system for a buffer when a file of CODING is inserted.
a73a8c89
KH
1971The local variable `buffer-file-coding-system' of the current buffer
1972is set to the returned value.
509064c5 1973Return nil if there's no need to set `buffer-file-coding-system'."
4ed46869 1974 (let (local-coding local-eol
b685f8d6 1975 found-coding found-eol
4ed46869
KH
1976 new-coding new-eol)
1977 (if (null coding)
1978 ;; Nothing found about coding.
1979 nil
1980
b685f8d6
RS
1981 ;; Get information of `buffer-file-coding-system' in LOCAL-EOL
1982 ;; and LOCAL-CODING.
1983 (setq local-eol (coding-system-eol-type buffer-file-coding-system))
1984 (if (null (numberp local-eol))
1985 ;; But eol-type is not yet set.
1986 (setq local-eol nil))
0269ddfb 1987 (if (and buffer-file-coding-system
c1841772
KH
1988 (not (eq (coding-system-type buffer-file-coding-system)
1989 'undecided)))
0269ddfb 1990 (setq local-coding (coding-system-base buffer-file-coding-system)))
b685f8d6
RS
1991
1992 (if (and (local-variable-p 'buffer-file-coding-system)
1993 local-eol local-coding)
4ed46869
KH
1994 ;; The current buffer has already set full coding-system, we
1995 ;; had better not change it.
1996 nil
1997
8057896b 1998 (setq found-eol (coding-system-eol-type coding))
4ed46869 1999 (if (null (numberp found-eol))
be02cd54
EZ
2000 ;; But eol-type is not found.
2001 ;; If EOL conversions are inhibited, force unix eol-type.
2002 (setq found-eol (if inhibit-eol-conversion 0)))
c1841772 2003 (setq found-coding (coding-system-base coding))
c76b5c99
KH
2004
2005 (if (and (not found-eol) (eq found-coding 'undecided))
2006 ;; No valid coding information found.
2007 nil
2008
2009 ;; Some coding information (eol or text) found.
2010
2011 ;; The local setting takes precedence over the found one.
2012 (setq new-coding (if (local-variable-p 'buffer-file-coding-system)
2013 (or local-coding found-coding)
2014 (or found-coding local-coding)))
2015 (setq new-eol (if (local-variable-p 'buffer-file-coding-system)
2016 (or local-eol found-eol)
2017 (or found-eol local-eol)))
2018
2019 (let ((eol-type (coding-system-eol-type new-coding)))
2020 (if (and (numberp new-eol) (vectorp eol-type))
2021 (aref eol-type new-eol)
2022 new-coding)))))))
4ed46869 2023
fe831d33
GV
2024(defun modify-coding-system-alist (target-type regexp coding-system)
2025 "Modify one of look up tables for finding a coding system on I/O operation.
8c453b46
RS
2026There are three of such tables, `file-coding-system-alist',
2027`process-coding-system-alist', and `network-coding-system-alist'.
fe831d33
GV
2028
2029TARGET-TYPE specifies which of them to modify.
8c453b46
RS
2030If it is `file', it affects `file-coding-system-alist' (which see).
2031If it is `process', it affects `process-coding-system-alist' (which see).
e8dd0160 2032If it is `network', it affects `network-coding-system-alist' (which see).
fe831d33
GV
2033
2034REGEXP is a regular expression matching a target of I/O operation.
2035The target is a file name if TARGET-TYPE is `file', a program name if
2036TARGET-TYPE is `process', or a network service name or a port number
2037to connect to if TARGET-TYPE is `network'.
2038
2039CODING-SYSTEM is a coding system to perform code conversion on the I/O
f81b2db1
JB
2040operation, or a cons cell (DECODING . ENCODING) specifying the coding
2041systems for decoding and encoding respectively, or a function symbol
2042which, when called, returns such a cons cell."
fe831d33
GV
2043 (or (memq target-type '(file process network))
2044 (error "Invalid target type: %s" target-type))
2045 (or (stringp regexp)
2046 (and (eq target-type 'network) (integerp regexp))
2047 (error "Invalid regular expression: %s" regexp))
2048 (if (symbolp coding-system)
2049 (if (not (fboundp coding-system))
2050 (progn
2051 (check-coding-system coding-system)
2052 (setq coding-system (cons coding-system coding-system))))
2053 (check-coding-system (car coding-system))
2054 (check-coding-system (cdr coding-system)))
2055 (cond ((eq target-type 'file)
2056 (let ((slot (assoc regexp file-coding-system-alist)))
2057 (if slot
2058 (setcdr slot coding-system)
2059 (setq file-coding-system-alist
2060 (cons (cons regexp coding-system)
2061 file-coding-system-alist)))))
2062 ((eq target-type 'process)
2063 (let ((slot (assoc regexp process-coding-system-alist)))
2064 (if slot
2065 (setcdr slot coding-system)
2066 (setq process-coding-system-alist
2067 (cons (cons regexp coding-system)
2068 process-coding-system-alist)))))
2069 (t
2070 (let ((slot (assoc regexp network-coding-system-alist)))
2071 (if slot
2072 (setcdr slot coding-system)
2073 (setq network-coding-system-alist
2074 (cons (cons regexp coding-system)
2075 network-coding-system-alist)))))))
2076
db046b7d
KH
2077(defun decode-coding-inserted-region (from to filename
2078 &optional visit beg end replace)
f29387e8 2079 "Decode the region between FROM and TO as if it is read from file FILENAME.
9c848353 2080The idea is that the text between FROM and TO was just inserted somehow.
f29387e8 2081Optional arguments VISIT, BEG, END, and REPLACE are the same as those
9c848353
RS
2082of the function `insert-file-contents'.
2083Part of the job of this function is setting `buffer-undo-list' appropriately."
f29387e8
KH
2084 (save-excursion
2085 (save-restriction
9c848353
RS
2086 (let ((coding coding-system-for-read)
2087 undo-list-saved)
2088 (if visit
2089 ;; Temporarily turn off undo recording, if we're decoding the
2090 ;; text of a visited file.
2091 (setq buffer-undo-list t)
2092 ;; Otherwise, if we can recognize the undo elt for the insertion,
2093 ;; remove it and get ready to replace it later.
2094 ;; In the mean time, turn off undo recording.
bf247b6e 2095 (let ((last (car-safe buffer-undo-list)))
9c848353
RS
2096 (if (and (consp last) (eql (car last) from) (eql (cdr last) to))
2097 (setq undo-list-saved (cdr buffer-undo-list)
2098 buffer-undo-list t))))
2099 (narrow-to-region from to)
2100 (goto-char (point-min))
f29387e8
KH
2101 (or coding
2102 (setq coding (funcall set-auto-coding-function
2103 filename (- (point-max) (point-min)))))
2104 (or coding
6b61353c
KH
2105 (setq coding (car (find-operation-coding-system
2106 'insert-file-contents
47a355de
KH
2107 (cons filename (current-buffer))
2108 visit beg end replace))))
f29387e8
KH
2109 (if (coding-system-p coding)
2110 (or enable-multibyte-characters
2111 (setq coding
2112 (coding-system-change-text-conversion coding 'raw-text)))
2113 (setq coding nil))
2114 (if coding
b12e19b2 2115 (decode-coding-region (point-min) (point-max) coding)
9c848353
RS
2116 (setq last-coding-system-used coding))
2117 ;; If we're decoding the text of a visited file,
2118 ;; the undo list should start out empty.
2119 (if visit
2120 (setq buffer-undo-list nil)
2121 ;; If we decided to replace the undo entry for the insertion,
2122 ;; do so now.
2123 (if undo-list-saved
2124 (setq buffer-undo-list
2125 (cons (cons from (point-max)) undo-list-saved))))))))
f29387e8 2126
27a91cf7
KH
2127(defun recode-region (start end new-coding coding)
2128 "Re-decode the region (previously decoded by CODING) by NEW-CODING."
2129 (interactive
2130 (list (region-beginning) (region-end)
2131 (read-coding-system "Text was really in: ")
2132 (let ((coding (or buffer-file-coding-system last-coding-system-used)))
2133 (read-coding-system
2134 (concat "But was interpreted as"
2135 (if coding (format " (default %S): " coding) ": "))
2136 coding))))
2137 (or (and new-coding coding)
2138 (error "Coding system not specified"))
2139 ;; Check it before we encode the region.
2140 (check-coding-system new-coding)
2141 (save-restriction
2142 (narrow-to-region start end)
2143 (encode-coding-region (point-min) (point-max) coding)
98c51a88
CY
2144 (decode-coding-region (point-min) (point-max) new-coding))
2145 (if (region-active-p)
2146 (deactivate-mark)))
f29387e8 2147
b25eef20 2148(defun make-translation-table (&rest args)
a284eea3 2149 "Make a translation table from arguments.
d38b07f9 2150A translation table is a char table intended for character
a284eea3
DL
2151translation in CCL programs.
2152
d38b07f9 2153Each argument is a list of elements of the form (FROM . TO), where FROM
a284eea3 2154is a character to be translated to TO.
13d5617d 2155
4e003d37
KH
2156The arguments and forms in each argument are processed in the given
2157order, and if a previous form already translates TO to some other
2158character, say TO-ALT, FROM is also translated to TO-ALT."
f967223b 2159 (let ((table (make-char-table 'translation-table))
a73a8c89 2160 revlist)
5d75f46f
KH
2161 (dolist (elts args)
2162 (dolist (elt elts)
2163 (let ((from (car elt))
2164 (to (cdr elt))
2165 to-alt rev-from rev-to)
2166 ;; If we have already translated TO to TO-ALT, FROM should
2167 ;; also be translated to TO-ALT.
2168 (if (setq to-alt (aref table to))
2169 (setq to to-alt))
2170 (aset table from to)
2171 ;; If we have already translated some chars to FROM, they
2172 ;; should also be translated to TO.
2173 (when (setq rev-from (assq from revlist))
2174 (dolist (elt (cdr rev-from))
2175 (aset table elt to))
2176 (setq revlist (delq rev-from revlist)
2177 rev-from (cdr rev-from)))
2178 ;; Now update REVLIST.
2179 (setq rev-to (assq to revlist))
2180 (if rev-to
2181 (setcdr rev-to (cons from (cdr rev-to)))
2182 (setq rev-to (list to from)
2183 revlist (cons rev-to revlist)))
2184 (if rev-from
2185 (setcdr rev-to (append rev-from (cdr rev-to)))))))
a73a8c89 2186 ;; Return TABLE just created.
350cd166 2187 (set-char-table-extra-slot table 1 1)
a73a8c89
KH
2188 table))
2189
c76b5c99
KH
2190(defun make-translation-table-from-vector (vec)
2191 "Make translation table from decoding vector VEC.
9e3b6057 2192VEC is an array of 256 elements to map unibyte codes to multibyte
18ccd78a 2193characters. Elements may be nil for undefined code points."
c76b5c99
KH
2194 (let ((table (make-char-table 'translation-table))
2195 (rev-table (make-char-table 'translation-table))
c76b5c99 2196 ch)
9e3b6057 2197 (dotimes (i 256)
c76b5c99 2198 (setq ch (aref vec i))
9e3b6057
DL
2199 (when ch
2200 (aset table i ch)
2201 (if (>= ch 256)
2202 (aset rev-table ch i))))
c76b5c99 2203 (set-char-table-extra-slot table 0 rev-table)
350cd166
KH
2204 (set-char-table-extra-slot table 1 1)
2205 (set-char-table-extra-slot rev-table 1 1)
c76b5c99
KH
2206 table))
2207
a6d1872e
KH
2208(defun make-translation-table-from-alist (alist)
2209 "Make translation table from N<->M mapping in ALIST.
2210ALIST is an alist, each element has the form (FROM . TO).
2211FROM and TO are a character or a vector of characters.
2212If FROM is a character, that character is translated to TO.
2213If FROM is a vector of characters, that sequence is translated to TO.
350cd166
KH
2214The first extra-slot of the value is a translation table for reverse mapping."
2215 (let ((tables (vector (make-char-table 'translation-table)
2216 (make-char-table 'translation-table)))
2217 table max-lookup from to idx val)
2218 (dotimes (i 2)
2219 (setq table (aref tables i))
2220 (setq max-lookup 1)
2221 (dolist (elt alist)
2222 (if (= i 0)
2223 (setq from (car elt) to (cdr elt))
2224 (setq from (cdr elt) to (car elt)))
2225 (if (characterp from)
2226 (setq idx from)
2227 (setq idx (aref from 0)
2228 max-lookup (max max-lookup (length from))))
2229 (setq val (aref table idx))
2230 (if val
2231 (progn
2232 (or (consp val)
2233 (setq val (list (cons (vector idx) val))))
2234 (if (characterp from)
2235 (setq from (vector from)))
2236 (setq val (nconc val (list (cons from to)))))
2237 (if (characterp from)
2238 (setq val to)
2239 (setq val (list (cons from to)))))
2240 (aset table idx val))
2241 (set-char-table-extra-slot table 1 max-lookup))
2242 (set-char-table-extra-slot (aref tables 0) 0 (aref tables 1))
2243 (aref tables 0)))
a6d1872e 2244
f967223b 2245(defun define-translation-table (symbol &rest args)
a284eea3
DL
2246 "Define SYMBOL as the name of translation table made by ARGS.
2247This sets up information so that the table can be used for
2248translations in a CCL program.
b25eef20 2249
a284eea3
DL
2250If the first element of ARGS is a char-table whose purpose is
2251`translation-table', just define SYMBOL to name it. (Note that this
2252function does not bind SYMBOL.)
007c79c8 2253
a284eea3 2254Any other ARGS should be suitable as arguments of the function
007c79c8 2255`make-translation-table' (which see).
b25eef20 2256
452fdb31 2257This function sets properties `translation-table' and
521d4010
DL
2258`translation-table-id' of SYMBOL to the created table itself and the
2259identification number of the table respectively. It also registers
2260the table in `translation-table-vector'."
007c79c8
KH
2261 (let ((table (if (and (char-table-p (car args))
2262 (eq (char-table-subtype (car args))
2263 'translation-table))
2264 (car args)
2265 (apply 'make-translation-table args)))
f967223b 2266 (len (length translation-table-vector))
d9e3229d 2267 (id 0)
b25eef20 2268 (done nil))
f967223b 2269 (put symbol 'translation-table table)
b25eef20
KH
2270 (while (not done)
2271 (if (>= id len)
f967223b
KH
2272 (setq translation-table-vector
2273 (vconcat translation-table-vector (make-vector len nil))))
2274 (let ((slot (aref translation-table-vector id)))
b25eef20
KH
2275 (if (or (not slot)
2276 (eq (car slot) symbol))
2277 (progn
f967223b 2278 (aset translation-table-vector id (cons symbol table))
007c79c8
KH
2279 (setq done t))
2280 (setq id (1+ id)))))
f967223b 2281 (put symbol 'translation-table-id id)
d9e3229d
KH
2282 id))
2283
16431d3c
KH
2284(defun translate-region (start end table)
2285 "From START to END, translate characters according to TABLE.
2286TABLE is a string or a char-table.
2287If TABLE is a string, the Nth character in it is the mapping
2288for the character with code N.
2289If TABLE is a char-table, the element for character N is the mapping
2290for the character with code N.
2291It returns the number of characters changed."
2292 (interactive
2293 (list (region-beginning)
2294 (region-end)
2295 (let (table l)
2296 (dotimes (i (length translation-table-vector))
2297 (if (consp (aref translation-table-vector i))
2298 (push (list (symbol-name
2299 (car (aref translation-table-vector i)))) l)))
2300 (if (not l)
2301 (error "No translation table defined"))
2302 (while (not table)
2303 (setq table (completing-read "Translation table: " l nil t)))
2304 (intern table))))
2305 (if (symbolp table)
2306 (let ((val (get table 'translation-table)))
2307 (or (char-table-p val)
2308 (error "Invalid translation table name: %s" table))
2309 (setq table val)))
2310 (translate-region-internal start end table))
2311
ef6e365d 2312(defmacro with-category-table (table &rest body)
f81b2db1 2313 "Execute BODY like `progn' with TABLE the current category table.
ef6e365d
JPW
2314The category table of the current buffer is saved, BODY is evaluated,
2315then the saved table is restored, even in case of an abnormal exit.
2316Value is what BODY returns."
f291fe60 2317 (declare (indent 1) (debug t))
ef6e365d
JPW
2318 (let ((old-table (make-symbol "old-table"))
2319 (old-buffer (make-symbol "old-buffer")))
2320 `(let ((,old-table (category-table))
2321 (,old-buffer (current-buffer)))
2322 (unwind-protect
2323 (progn
2324 (set-category-table ,table)
2325 ,@body)
053f45dd 2326 (with-current-buffer ,old-buffer
ef6e365d 2327 (set-category-table ,old-table))))))
35554641 2328
394e4eb0
DL
2329(defun define-translation-hash-table (symbol table)
2330 "Define SYMBOL as the name of the hash translation TABLE for use in CCL.
2331
2332Analogous to `define-translation-table', but updates
2333`translation-hash-table-vector' and the table is for use in the CCL
2334`lookup-integer' and `lookup-character' functions."
2335 (unless (and (symbolp symbol)
2336 (hash-table-p table))
2337 (error "Bad args to define-translation-hash-table"))
2338 (let ((len (length translation-hash-table-vector))
2339 (id 0)
2340 done)
2341 (put symbol 'translation-hash-table table)
2342 (while (not done)
2343 (if (>= id len)
2344 (setq translation-hash-table-vector
2345 (vconcat translation-hash-table-vector [nil])))
2346 (let ((slot (aref translation-hash-table-vector id)))
2347 (if (or (not slot)
2348 (eq (car slot) symbol))
2349 (progn
2350 (aset translation-hash-table-vector id (cons symbol table))
2351 (setq done t))
2352 (setq id (1+ id)))))
2353 (put symbol 'translation-hash-table-id id)
2354 id))
2355
69eba008
KH
2356;;; Initialize some variables.
2357
2358(put 'use-default-ascent 'char-table-extra-slots 0)
2359(setq use-default-ascent (make-char-table 'use-default-ascent))
d6d6d592
KH
2360(put 'ignore-relative-composition 'char-table-extra-slots 0)
2361(setq ignore-relative-composition
2362 (make-char-table 'ignore-relative-composition))
69eba008 2363
d9f6dfe6
CW
2364;;; Built-in auto-coding-functions:
2365
2366(defun sgml-xml-auto-coding-function (size)
2367 "Determine whether the buffer is XML, and if so, its encoding.
2368This function is intended to be added to `auto-coding-functions'."
c069d3ac
SM
2369 (setq size (+ (point) size))
2370 (when (re-search-forward "\\`[[:space:]\n]*<\\?xml" size t)
d9f6dfe6
CW
2371 (let ((end (save-excursion
2372 ;; This is a hack.
c2c51a11 2373 (re-search-forward "[\"']\\s-*\\?>" size t))))
d9f6dfe6 2374 (when end
c2c51a11 2375 (if (re-search-forward "encoding=[\"']\\(.+?\\)[\"']" end t)
447404a3
CW
2376 (let* ((match (match-string 1))
2377 (sym (intern (downcase match))))
2378 (if (coding-system-p sym)
2379 sym
2380 (message "Warning: unknown coding system \"%s\"" match)
2381 nil))
c6578617
JR
2382 ;; Files without an encoding tag should be UTF-8. But users
2383 ;; may be naive about encodings, and have saved the file from
2384 ;; another editor that does not help them get the encoding right.
2385 ;; Detect the encoding and warn the user if it is detected as
2386 ;; something other than UTF-8.
2387 (let ((detected
2388 (with-coding-priority '(utf-8)
2389 (coding-system-base
2390 (detect-coding-region (point-min) size t)))))
2391 ;; Pure ASCII always comes back as undecided.
2392 (if (memq detected '(utf-8 undecided))
2393 'utf-8
2394 (warn "File contents detected as %s.
2395 Consider adding an encoding attribute to the xml declaration,
2396 or saving as utf-8, as mandated by the xml specification." detected)
2397 detected)))))))
d9f6dfe6 2398
447404a3
CW
2399(defun sgml-html-meta-auto-coding-function (size)
2400 "If the buffer has an HTML meta tag, use it to determine encoding.
2401This function is intended to be added to `auto-coding-functions'."
df3c9fe7
GM
2402 (let ((case-fold-search t))
2403 (setq size (min (+ (point) size)
2404 (save-excursion
2405 ;; Limit the search by the end of the HTML header.
9e5e233a 2406 (or (search-forward "</head>" (+ (point) size) t)
df3c9fe7
GM
2407 ;; In case of no header, search only 10 lines.
2408 (forward-line 10))
2409 (point))))
2410 ;; Make sure that the buffer really contains an HTML document, by
2411 ;; checking that it starts with a doctype or a <HTML> start tag
2412 ;; (allowing for whitespace at bob). Note: 'DOCTYPE NETSCAPE' is
2413 ;; useful for Mozilla bookmark files.
2414 (when (and (re-search-forward "\\`[[:space:]\n]*\\(<!doctype[[:space:]\n]+\\(html\\|netscape\\)\\|<html\\)" size t)
b31a5677
JK
2415 (re-search-forward "<meta\\s-+\\(http-equiv=[\"']?content-type[\"']?\\s-+content=[\"']text/\\sw+;\\s-*\\)?charset=[\"']?\\(.+?\\)[\"'\\s-/>]" size t))
2416 (let* ((match (match-string 2))
df3c9fe7
GM
2417 (sym (intern (downcase match))))
2418 (if (coding-system-p sym)
2419 sym
2420 (message "Warning: unknown coding system \"%s\"" match)
2421 nil)))))
0bca779a 2422
c6578617
JR
2423(defun xml-find-file-coding-system (args)
2424 "Determine the coding system of an XML file without a declaration.
2425Strictly speaking, the file should be utf-8, but mistakes are
2426made, and there are genuine cases where XML fragments are saved,
2427with the encoding properly specified in a master document, or
2428added by processing software."
2429 (if (eq (car args) 'insert-file-contents)
2430 (let ((detected
2431 (with-coding-priority '(utf-8)
2432 (coding-system-base
2433 (detect-coding-region (point-min) (point-max) t)))))
2434 ;; Pure ASCII always comes back as undecided.
228de8de
JR
2435 (cond
2436 ((memq detected '(utf-8 undecided))
2437 'utf-8)
2438 ((eq detected 'utf-16le-with-signature) 'utf-16le-with-signature)
2439 ((eq detected 'utf-16be-with-signature) 'utf-16be-with-signature)
2440 (t
c6578617
JR
2441 (warn "File contents detected as %s.
2442 Consider adding an xml declaration with the encoding specified,
2443 or saving as utf-8, as mandated by the xml specification." detected)
228de8de 2444 detected)))
c6578617
JR
2445 ;; Don't interfere with the user's wishes for saving the buffer.
2446 ;; We did what we could when the buffer was created to ensure the
2447 ;; correct encoding was used, or the user was warned, so any
2448 ;; non-conformity here is deliberate on the part of the user.
2449 'undecided))
2450
69eba008 2451;;;
4ed46869
KH
2452(provide 'mule)
2453
2454;;; mule.el ends here