Fix typo in comment.
[bpt/emacs.git] / src / coding.c
1 /* Coding system handler (conversion, detection, and etc).
2 Copyright (C) 1995, 1997, 1998, 2002 Electrotechnical Laboratory, JAPAN.
3 Licensed to the Free Software Foundation.
4 Copyright (C) 2001 Free Software Foundation, Inc.
5
6 This file is part of GNU Emacs.
7
8 GNU Emacs is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2, or (at your option)
11 any later version.
12
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs; see the file COPYING. If not, write to
20 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 Boston, MA 02111-1307, USA. */
22
23 /*** TABLE OF CONTENTS ***
24
25 0. General comments
26 1. Preamble
27 2. Emacs' internal format (emacs-mule) handlers
28 3. ISO2022 handlers
29 4. Shift-JIS and BIG5 handlers
30 5. CCL handlers
31 6. End-of-line handlers
32 7. C library functions
33 8. Emacs Lisp library functions
34 9. Post-amble
35
36 */
37
38 /*** 0. General comments ***/
39
40
41 /*** GENERAL NOTE on CODING SYSTEMS ***
42
43 A coding system is an encoding mechanism for one or more character
44 sets. Here's a list of coding systems which Emacs can handle. When
45 we say "decode", it means converting some other coding system to
46 Emacs' internal format (emacs-mule), and when we say "encode",
47 it means converting the coding system emacs-mule to some other
48 coding system.
49
50 0. Emacs' internal format (emacs-mule)
51
52 Emacs itself holds a multi-lingual character in buffers and strings
53 in a special format. Details are described in section 2.
54
55 1. ISO2022
56
57 The most famous coding system for multiple character sets. X's
58 Compound Text, various EUCs (Extended Unix Code), and coding
59 systems used in Internet communication such as ISO-2022-JP are
60 all variants of ISO2022. Details are described in section 3.
61
62 2. SJIS (or Shift-JIS or MS-Kanji-Code)
63
64 A coding system to encode character sets: ASCII, JISX0201, and
65 JISX0208. Widely used for PC's in Japan. Details are described in
66 section 4.
67
68 3. BIG5
69
70 A coding system to encode the character sets ASCII and Big5. Widely
71 used for Chinese (mainly in Taiwan and Hong Kong). Details are
72 described in section 4. In this file, when we write "BIG5"
73 (all uppercase), we mean the coding system, and when we write
74 "Big5" (capitalized), we mean the character set.
75
76 4. Raw text
77
78 A coding system for text containing random 8-bit code. Emacs does
79 no code conversion on such text except for end-of-line format.
80
81 5. Other
82
83 If a user wants to read/write text encoded in a coding system not
84 listed above, he can supply a decoder and an encoder for it as CCL
85 (Code Conversion Language) programs. Emacs executes the CCL program
86 while reading/writing.
87
88 Emacs represents a coding system by a Lisp symbol that has a property
89 `coding-system'. But, before actually using the coding system, the
90 information about it is set in a structure of type `struct
91 coding_system' for rapid processing. See section 6 for more details.
92
93 */
94
95 /*** GENERAL NOTES on END-OF-LINE FORMAT ***
96
97 How end-of-line of text is encoded depends on the operating system.
98 For instance, Unix's format is just one byte of `line-feed' code,
99 whereas DOS's format is two-byte sequence of `carriage-return' and
100 `line-feed' codes. MacOS's format is usually one byte of
101 `carriage-return'.
102
103 Since text character encoding and end-of-line encoding are
104 independent, any coding system described above can have any
105 end-of-line format. So Emacs has information about end-of-line
106 format in each coding-system. See section 6 for more details.
107
108 */
109
110 /*** GENERAL NOTES on `detect_coding_XXX ()' functions ***
111
112 These functions check if a text between SRC and SRC_END is encoded
113 in the coding system category XXX. Each returns an integer value in
114 which appropriate flag bits for the category XXX are set. The flag
115 bits are defined in macros CODING_CATEGORY_MASK_XXX. Below is the
116 template for these functions. If MULTIBYTEP is nonzero, 8-bit codes
117 of the range 0x80..0x9F are in multibyte form. */
118 #if 0
119 int
120 detect_coding_emacs_mule (src, src_end, multibytep)
121 unsigned char *src, *src_end;
122 int multibytep;
123 {
124 ...
125 }
126 #endif
127
128 /*** GENERAL NOTES on `decode_coding_XXX ()' functions ***
129
130 These functions decode SRC_BYTES length of unibyte text at SOURCE
131 encoded in CODING to Emacs' internal format. The resulting
132 multibyte text goes to a place pointed to by DESTINATION, the length
133 of which should not exceed DST_BYTES.
134
135 These functions set the information about original and decoded texts
136 in the members `produced', `produced_char', `consumed', and
137 `consumed_char' of the structure *CODING. They also set the member
138 `result' to one of CODING_FINISH_XXX indicating how the decoding
139 finished.
140
141 DST_BYTES zero means that the source area and destination area are
142 overlapped, which means that we can produce a decoded text until it
143 reaches the head of the not-yet-decoded source text.
144
145 Below is a template for these functions. */
146 #if 0
147 static void
148 decode_coding_XXX (coding, source, destination, src_bytes, dst_bytes)
149 struct coding_system *coding;
150 unsigned char *source, *destination;
151 int src_bytes, dst_bytes;
152 {
153 ...
154 }
155 #endif
156
157 /*** GENERAL NOTES on `encode_coding_XXX ()' functions ***
158
159 These functions encode SRC_BYTES length text at SOURCE from Emacs'
160 internal multibyte format to CODING. The resulting unibyte text
161 goes to a place pointed to by DESTINATION, the length of which
162 should not exceed DST_BYTES.
163
164 These functions set the information about original and encoded texts
165 in the members `produced', `produced_char', `consumed', and
166 `consumed_char' of the structure *CODING. They also set the member
167 `result' to one of CODING_FINISH_XXX indicating how the encoding
168 finished.
169
170 DST_BYTES zero means that the source area and destination area are
171 overlapped, which means that we can produce encoded text until it
172 reaches at the head of the not-yet-encoded source text.
173
174 Below is a template for these functions. */
175 #if 0
176 static void
177 encode_coding_XXX (coding, source, destination, src_bytes, dst_bytes)
178 struct coding_system *coding;
179 unsigned char *source, *destination;
180 int src_bytes, dst_bytes;
181 {
182 ...
183 }
184 #endif
185
186 /*** COMMONLY USED MACROS ***/
187
188 /* The following two macros ONE_MORE_BYTE and TWO_MORE_BYTES safely
189 get one, two, and three bytes from the source text respectively.
190 If there are not enough bytes in the source, they jump to
191 `label_end_of_loop'. The caller should set variables `coding',
192 `src' and `src_end' to appropriate pointer in advance. These
193 macros are called from decoding routines `decode_coding_XXX', thus
194 it is assumed that the source text is unibyte. */
195
196 #define ONE_MORE_BYTE(c1) \
197 do { \
198 if (src >= src_end) \
199 { \
200 coding->result = CODING_FINISH_INSUFFICIENT_SRC; \
201 goto label_end_of_loop; \
202 } \
203 c1 = *src++; \
204 } while (0)
205
206 #define TWO_MORE_BYTES(c1, c2) \
207 do { \
208 if (src + 1 >= src_end) \
209 { \
210 coding->result = CODING_FINISH_INSUFFICIENT_SRC; \
211 goto label_end_of_loop; \
212 } \
213 c1 = *src++; \
214 c2 = *src++; \
215 } while (0)
216
217
218 /* Like ONE_MORE_BYTE, but 8-bit bytes of data at SRC are in multibyte
219 form if MULTIBYTEP is nonzero. */
220
221 #define ONE_MORE_BYTE_CHECK_MULTIBYTE(c1, multibytep) \
222 do { \
223 if (src >= src_end) \
224 { \
225 coding->result = CODING_FINISH_INSUFFICIENT_SRC; \
226 goto label_end_of_loop; \
227 } \
228 c1 = *src++; \
229 if (multibytep && c1 == LEADING_CODE_8_BIT_CONTROL) \
230 c1 = *src++ - 0x20; \
231 } while (0)
232
233 /* Set C to the next character at the source text pointed by `src'.
234 If there are not enough characters in the source, jump to
235 `label_end_of_loop'. The caller should set variables `coding'
236 `src', `src_end', and `translation_table' to appropriate pointers
237 in advance. This macro is used in encoding routines
238 `encode_coding_XXX', thus it assumes that the source text is in
239 multibyte form except for 8-bit characters. 8-bit characters are
240 in multibyte form if coding->src_multibyte is nonzero, else they
241 are represented by a single byte. */
242
243 #define ONE_MORE_CHAR(c) \
244 do { \
245 int len = src_end - src; \
246 int bytes; \
247 if (len <= 0) \
248 { \
249 coding->result = CODING_FINISH_INSUFFICIENT_SRC; \
250 goto label_end_of_loop; \
251 } \
252 if (coding->src_multibyte \
253 || UNIBYTE_STR_AS_MULTIBYTE_P (src, len, bytes)) \
254 c = STRING_CHAR_AND_LENGTH (src, len, bytes); \
255 else \
256 c = *src, bytes = 1; \
257 if (!NILP (translation_table)) \
258 c = translate_char (translation_table, c, -1, 0, 0); \
259 src += bytes; \
260 } while (0)
261
262
263 /* Produce a multibyte form of character C to `dst'. Jump to
264 `label_end_of_loop' if there's not enough space at `dst'.
265
266 If we are now in the middle of a composition sequence, the decoded
267 character may be ALTCHAR (for the current composition). In that
268 case, the character goes to coding->cmp_data->data instead of
269 `dst'.
270
271 This macro is used in decoding routines. */
272
273 #define EMIT_CHAR(c) \
274 do { \
275 if (! COMPOSING_P (coding) \
276 || coding->composing == COMPOSITION_RELATIVE \
277 || coding->composing == COMPOSITION_WITH_RULE) \
278 { \
279 int bytes = CHAR_BYTES (c); \
280 if ((dst + bytes) > (dst_bytes ? dst_end : src)) \
281 { \
282 coding->result = CODING_FINISH_INSUFFICIENT_DST; \
283 goto label_end_of_loop; \
284 } \
285 dst += CHAR_STRING (c, dst); \
286 coding->produced_char++; \
287 } \
288 \
289 if (COMPOSING_P (coding) \
290 && coding->composing != COMPOSITION_RELATIVE) \
291 { \
292 CODING_ADD_COMPOSITION_COMPONENT (coding, c); \
293 coding->composition_rule_follows \
294 = coding->composing != COMPOSITION_WITH_ALTCHARS; \
295 } \
296 } while (0)
297
298
299 #define EMIT_ONE_BYTE(c) \
300 do { \
301 if (dst >= (dst_bytes ? dst_end : src)) \
302 { \
303 coding->result = CODING_FINISH_INSUFFICIENT_DST; \
304 goto label_end_of_loop; \
305 } \
306 *dst++ = c; \
307 } while (0)
308
309 #define EMIT_TWO_BYTES(c1, c2) \
310 do { \
311 if (dst + 2 > (dst_bytes ? dst_end : src)) \
312 { \
313 coding->result = CODING_FINISH_INSUFFICIENT_DST; \
314 goto label_end_of_loop; \
315 } \
316 *dst++ = c1, *dst++ = c2; \
317 } while (0)
318
319 #define EMIT_BYTES(from, to) \
320 do { \
321 if (dst + (to - from) > (dst_bytes ? dst_end : src)) \
322 { \
323 coding->result = CODING_FINISH_INSUFFICIENT_DST; \
324 goto label_end_of_loop; \
325 } \
326 while (from < to) \
327 *dst++ = *from++; \
328 } while (0)
329
330 \f
331 /*** 1. Preamble ***/
332
333 #ifdef emacs
334 #include <config.h>
335 #endif
336
337 #include <stdio.h>
338
339 #ifdef emacs
340
341 #include "lisp.h"
342 #include "buffer.h"
343 #include "charset.h"
344 #include "composite.h"
345 #include "ccl.h"
346 #include "coding.h"
347 #include "window.h"
348
349 #else /* not emacs */
350
351 #include "mulelib.h"
352
353 #endif /* not emacs */
354
355 Lisp_Object Qcoding_system, Qeol_type;
356 Lisp_Object Qbuffer_file_coding_system;
357 Lisp_Object Qpost_read_conversion, Qpre_write_conversion;
358 Lisp_Object Qno_conversion, Qundecided;
359 Lisp_Object Qcoding_system_history;
360 Lisp_Object Qsafe_chars;
361 Lisp_Object Qvalid_codes;
362
363 extern Lisp_Object Qinsert_file_contents, Qwrite_region;
364 Lisp_Object Qcall_process, Qcall_process_region, Qprocess_argument;
365 Lisp_Object Qstart_process, Qopen_network_stream;
366 Lisp_Object Qtarget_idx;
367
368 Lisp_Object Vselect_safe_coding_system_function;
369
370 /* Mnemonic string for each format of end-of-line. */
371 Lisp_Object eol_mnemonic_unix, eol_mnemonic_dos, eol_mnemonic_mac;
372 /* Mnemonic string to indicate format of end-of-line is not yet
373 decided. */
374 Lisp_Object eol_mnemonic_undecided;
375
376 /* Format of end-of-line decided by system. This is CODING_EOL_LF on
377 Unix, CODING_EOL_CRLF on DOS/Windows, and CODING_EOL_CR on Mac. */
378 int system_eol_type;
379
380 #ifdef emacs
381
382 Lisp_Object Vcoding_system_list, Vcoding_system_alist;
383
384 Lisp_Object Qcoding_system_p, Qcoding_system_error;
385
386 /* Coding system emacs-mule and raw-text are for converting only
387 end-of-line format. */
388 Lisp_Object Qemacs_mule, Qraw_text;
389
390 /* Coding-systems are handed between Emacs Lisp programs and C internal
391 routines by the following three variables. */
392 /* Coding-system for reading files and receiving data from process. */
393 Lisp_Object Vcoding_system_for_read;
394 /* Coding-system for writing files and sending data to process. */
395 Lisp_Object Vcoding_system_for_write;
396 /* Coding-system actually used in the latest I/O. */
397 Lisp_Object Vlast_coding_system_used;
398
399 /* A vector of length 256 which contains information about special
400 Latin codes (especially for dealing with Microsoft codes). */
401 Lisp_Object Vlatin_extra_code_table;
402
403 /* Flag to inhibit code conversion of end-of-line format. */
404 int inhibit_eol_conversion;
405
406 /* Flag to inhibit ISO2022 escape sequence detection. */
407 int inhibit_iso_escape_detection;
408
409 /* Flag to make buffer-file-coding-system inherit from process-coding. */
410 int inherit_process_coding_system;
411
412 /* Coding system to be used to encode text for terminal display. */
413 struct coding_system terminal_coding;
414
415 /* Coding system to be used to encode text for terminal display when
416 terminal coding system is nil. */
417 struct coding_system safe_terminal_coding;
418
419 /* Coding system of what is sent from terminal keyboard. */
420 struct coding_system keyboard_coding;
421
422 /* Default coding system to be used to write a file. */
423 struct coding_system default_buffer_file_coding;
424
425 Lisp_Object Vfile_coding_system_alist;
426 Lisp_Object Vprocess_coding_system_alist;
427 Lisp_Object Vnetwork_coding_system_alist;
428
429 Lisp_Object Vlocale_coding_system;
430
431 #endif /* emacs */
432
433 Lisp_Object Qcoding_category, Qcoding_category_index;
434
435 /* List of symbols `coding-category-xxx' ordered by priority. */
436 Lisp_Object Vcoding_category_list;
437
438 /* Table of coding categories (Lisp symbols). */
439 Lisp_Object Vcoding_category_table;
440
441 /* Table of names of symbol for each coding-category. */
442 char *coding_category_name[CODING_CATEGORY_IDX_MAX] = {
443 "coding-category-emacs-mule",
444 "coding-category-sjis",
445 "coding-category-iso-7",
446 "coding-category-iso-7-tight",
447 "coding-category-iso-8-1",
448 "coding-category-iso-8-2",
449 "coding-category-iso-7-else",
450 "coding-category-iso-8-else",
451 "coding-category-ccl",
452 "coding-category-big5",
453 "coding-category-utf-8",
454 "coding-category-utf-16-be",
455 "coding-category-utf-16-le",
456 "coding-category-raw-text",
457 "coding-category-binary"
458 };
459
460 /* Table of pointers to coding systems corresponding to each coding
461 categories. */
462 struct coding_system *coding_system_table[CODING_CATEGORY_IDX_MAX];
463
464 /* Table of coding category masks. Nth element is a mask for a coding
465 category of which priority is Nth. */
466 static
467 int coding_priorities[CODING_CATEGORY_IDX_MAX];
468
469 /* Flag to tell if we look up translation table on character code
470 conversion. */
471 Lisp_Object Venable_character_translation;
472 /* Standard translation table to look up on decoding (reading). */
473 Lisp_Object Vstandard_translation_table_for_decode;
474 /* Standard translation table to look up on encoding (writing). */
475 Lisp_Object Vstandard_translation_table_for_encode;
476
477 Lisp_Object Qtranslation_table;
478 Lisp_Object Qtranslation_table_id;
479 Lisp_Object Qtranslation_table_for_decode;
480 Lisp_Object Qtranslation_table_for_encode;
481
482 /* Alist of charsets vs revision number. */
483 Lisp_Object Vcharset_revision_alist;
484
485 /* Default coding systems used for process I/O. */
486 Lisp_Object Vdefault_process_coding_system;
487
488 /* Global flag to tell that we can't call post-read-conversion and
489 pre-write-conversion functions. Usually the value is zero, but it
490 is set to 1 temporarily while such functions are running. This is
491 to avoid infinite recursive call. */
492 static int inhibit_pre_post_conversion;
493
494 /* Char-table containing safe coding systems of each character. */
495 Lisp_Object Vchar_coding_system_table;
496 Lisp_Object Qchar_coding_system;
497
498 /* Return `safe-chars' property of coding system CODING. Don't check
499 validity of CODING. */
500
501 Lisp_Object
502 coding_safe_chars (coding)
503 struct coding_system *coding;
504 {
505 Lisp_Object coding_spec, plist, safe_chars;
506
507 coding_spec = Fget (coding->symbol, Qcoding_system);
508 plist = XVECTOR (coding_spec)->contents[3];
509 safe_chars = Fplist_get (XVECTOR (coding_spec)->contents[3], Qsafe_chars);
510 return (CHAR_TABLE_P (safe_chars) ? safe_chars : Qt);
511 }
512
513 #define CODING_SAFE_CHAR_P(safe_chars, c) \
514 (EQ (safe_chars, Qt) || !NILP (CHAR_TABLE_REF (safe_chars, c)))
515
516 \f
517 /*** 2. Emacs internal format (emacs-mule) handlers ***/
518
519 /* Emacs' internal format for representation of multiple character
520 sets is a kind of multi-byte encoding, i.e. characters are
521 represented by variable-length sequences of one-byte codes.
522
523 ASCII characters and control characters (e.g. `tab', `newline') are
524 represented by one-byte sequences which are their ASCII codes, in
525 the range 0x00 through 0x7F.
526
527 8-bit characters of the range 0x80..0x9F are represented by
528 two-byte sequences of LEADING_CODE_8_BIT_CONTROL and (their 8-bit
529 code + 0x20).
530
531 8-bit characters of the range 0xA0..0xFF are represented by
532 one-byte sequences which are their 8-bit code.
533
534 The other characters are represented by a sequence of `base
535 leading-code', optional `extended leading-code', and one or two
536 `position-code's. The length of the sequence is determined by the
537 base leading-code. Leading-code takes the range 0x81 through 0x9D,
538 whereas extended leading-code and position-code take the range 0xA0
539 through 0xFF. See `charset.h' for more details about leading-code
540 and position-code.
541
542 --- CODE RANGE of Emacs' internal format ---
543 character set range
544 ------------- -----
545 ascii 0x00..0x7F
546 eight-bit-control LEADING_CODE_8_BIT_CONTROL + 0xA0..0xBF
547 eight-bit-graphic 0xA0..0xBF
548 ELSE 0x81..0x9D + [0xA0..0xFF]+
549 ---------------------------------------------
550
551 As this is the internal character representation, the format is
552 usually not used externally (i.e. in a file or in a data sent to a
553 process). But, it is possible to have a text externally in this
554 format (i.e. by encoding by the coding system `emacs-mule').
555
556 In that case, a sequence of one-byte codes has a slightly different
557 form.
558
559 Firstly, all characters in eight-bit-control are represented by
560 one-byte sequences which are their 8-bit code.
561
562 Next, character composition data are represented by the byte
563 sequence of the form: 0x80 METHOD BYTES CHARS COMPONENT ...,
564 where,
565 METHOD is 0xF0 plus one of composition method (enum
566 composition_method),
567
568 BYTES is 0xA0 plus the byte length of these composition data,
569
570 CHARS is 0xA0 plus the number of characters composed by these
571 data,
572
573 COMPONENTs are characters of multibyte form or composition
574 rules encoded by two-byte of ASCII codes.
575
576 In addition, for backward compatibility, the following formats are
577 also recognized as composition data on decoding.
578
579 0x80 MSEQ ...
580 0x80 0xFF MSEQ RULE MSEQ RULE ... MSEQ
581
582 Here,
583 MSEQ is a multibyte form but in these special format:
584 ASCII: 0xA0 ASCII_CODE+0x80,
585 other: LEADING_CODE+0x20 FOLLOWING-BYTE ...,
586 RULE is a one byte code of the range 0xA0..0xF0 that
587 represents a composition rule.
588 */
589
590 enum emacs_code_class_type emacs_code_class[256];
591
592 /* See the above "GENERAL NOTES on `detect_coding_XXX ()' functions".
593 Check if a text is encoded in Emacs' internal format. If it is,
594 return CODING_CATEGORY_MASK_EMACS_MULE, else return 0. */
595
596 static int
597 detect_coding_emacs_mule (src, src_end, multibytep)
598 unsigned char *src, *src_end;
599 int multibytep;
600 {
601 unsigned char c;
602 int composing = 0;
603 /* Dummy for ONE_MORE_BYTE. */
604 struct coding_system dummy_coding;
605 struct coding_system *coding = &dummy_coding;
606
607 while (1)
608 {
609 ONE_MORE_BYTE_CHECK_MULTIBYTE (c, multibytep);
610
611 if (composing)
612 {
613 if (c < 0xA0)
614 composing = 0;
615 else if (c == 0xA0)
616 {
617 ONE_MORE_BYTE_CHECK_MULTIBYTE (c, multibytep);
618 c &= 0x7F;
619 }
620 else
621 c -= 0x20;
622 }
623
624 if (c < 0x20)
625 {
626 if (c == ISO_CODE_ESC || c == ISO_CODE_SI || c == ISO_CODE_SO)
627 return 0;
628 }
629 else if (c >= 0x80 && c < 0xA0)
630 {
631 if (c == 0x80)
632 /* Old leading code for a composite character. */
633 composing = 1;
634 else
635 {
636 unsigned char *src_base = src - 1;
637 int bytes;
638
639 if (!UNIBYTE_STR_AS_MULTIBYTE_P (src_base, src_end - src_base,
640 bytes))
641 return 0;
642 src = src_base + bytes;
643 }
644 }
645 }
646 label_end_of_loop:
647 return CODING_CATEGORY_MASK_EMACS_MULE;
648 }
649
650
651 /* Record the starting position START and METHOD of one composition. */
652
653 #define CODING_ADD_COMPOSITION_START(coding, start, method) \
654 do { \
655 struct composition_data *cmp_data = coding->cmp_data; \
656 int *data = cmp_data->data + cmp_data->used; \
657 coding->cmp_data_start = cmp_data->used; \
658 data[0] = -1; \
659 data[1] = cmp_data->char_offset + start; \
660 data[3] = (int) method; \
661 cmp_data->used += 4; \
662 } while (0)
663
664 /* Record the ending position END of the current composition. */
665
666 #define CODING_ADD_COMPOSITION_END(coding, end) \
667 do { \
668 struct composition_data *cmp_data = coding->cmp_data; \
669 int *data = cmp_data->data + coding->cmp_data_start; \
670 data[0] = cmp_data->used - coding->cmp_data_start; \
671 data[2] = cmp_data->char_offset + end; \
672 } while (0)
673
674 /* Record one COMPONENT (alternate character or composition rule). */
675
676 #define CODING_ADD_COMPOSITION_COMPONENT(coding, component) \
677 (coding->cmp_data->data[coding->cmp_data->used++] = component)
678
679
680 /* Get one byte from a data pointed by SRC and increment SRC. If SRC
681 is not less than SRC_END, return -1 without incrementing Src. */
682
683 #define SAFE_ONE_MORE_BYTE() (src >= src_end ? -1 : *src++)
684
685
686 /* Decode a character represented as a component of composition
687 sequence of Emacs 20 style at SRC. Set C to that character, store
688 its multibyte form sequence at P, and set P to the end of that
689 sequence. If no valid character is found, set C to -1. */
690
691 #define DECODE_EMACS_MULE_COMPOSITION_CHAR(c, p) \
692 do { \
693 int bytes; \
694 \
695 c = SAFE_ONE_MORE_BYTE (); \
696 if (c < 0) \
697 break; \
698 if (CHAR_HEAD_P (c)) \
699 c = -1; \
700 else if (c == 0xA0) \
701 { \
702 c = SAFE_ONE_MORE_BYTE (); \
703 if (c < 0xA0) \
704 c = -1; \
705 else \
706 { \
707 c -= 0xA0; \
708 *p++ = c; \
709 } \
710 } \
711 else if (BASE_LEADING_CODE_P (c - 0x20)) \
712 { \
713 unsigned char *p0 = p; \
714 \
715 c -= 0x20; \
716 *p++ = c; \
717 bytes = BYTES_BY_CHAR_HEAD (c); \
718 while (--bytes) \
719 { \
720 c = SAFE_ONE_MORE_BYTE (); \
721 if (c < 0) \
722 break; \
723 *p++ = c; \
724 } \
725 if (UNIBYTE_STR_AS_MULTIBYTE_P (p0, p - p0, bytes)) \
726 c = STRING_CHAR (p0, bytes); \
727 else \
728 c = -1; \
729 } \
730 else \
731 c = -1; \
732 } while (0)
733
734
735 /* Decode a composition rule represented as a component of composition
736 sequence of Emacs 20 style at SRC. Set C to the rule. If not
737 valid rule is found, set C to -1. */
738
739 #define DECODE_EMACS_MULE_COMPOSITION_RULE(c) \
740 do { \
741 c = SAFE_ONE_MORE_BYTE (); \
742 c -= 0xA0; \
743 if (c < 0 || c >= 81) \
744 c = -1; \
745 else \
746 { \
747 gref = c / 9, nref = c % 9; \
748 c = COMPOSITION_ENCODE_RULE (gref, nref); \
749 } \
750 } while (0)
751
752
753 /* Decode composition sequence encoded by `emacs-mule' at the source
754 pointed by SRC. SRC_END is the end of source. Store information
755 of the composition in CODING->cmp_data.
756
757 For backward compatibility, decode also a composition sequence of
758 Emacs 20 style. In that case, the composition sequence contains
759 characters that should be extracted into a buffer or string. Store
760 those characters at *DESTINATION in multibyte form.
761
762 If we encounter an invalid byte sequence, return 0.
763 If we encounter an insufficient source or destination, or
764 insufficient space in CODING->cmp_data, return 1.
765 Otherwise, return consumed bytes in the source.
766
767 */
768 static INLINE int
769 decode_composition_emacs_mule (coding, src, src_end,
770 destination, dst_end, dst_bytes)
771 struct coding_system *coding;
772 unsigned char *src, *src_end, **destination, *dst_end;
773 int dst_bytes;
774 {
775 unsigned char *dst = *destination;
776 int method, data_len, nchars;
777 unsigned char *src_base = src++;
778 /* Store components of composition. */
779 int component[COMPOSITION_DATA_MAX_BUNCH_LENGTH];
780 int ncomponent;
781 /* Store multibyte form of characters to be composed. This is for
782 Emacs 20 style composition sequence. */
783 unsigned char buf[MAX_COMPOSITION_COMPONENTS * MAX_MULTIBYTE_LENGTH];
784 unsigned char *bufp = buf;
785 int c, i, gref, nref;
786
787 if (coding->cmp_data->used + COMPOSITION_DATA_MAX_BUNCH_LENGTH
788 >= COMPOSITION_DATA_SIZE)
789 {
790 coding->result = CODING_FINISH_INSUFFICIENT_CMP;
791 return -1;
792 }
793
794 ONE_MORE_BYTE (c);
795 if (c - 0xF0 >= COMPOSITION_RELATIVE
796 && c - 0xF0 <= COMPOSITION_WITH_RULE_ALTCHARS)
797 {
798 int with_rule;
799
800 method = c - 0xF0;
801 with_rule = (method == COMPOSITION_WITH_RULE
802 || method == COMPOSITION_WITH_RULE_ALTCHARS);
803 ONE_MORE_BYTE (c);
804 data_len = c - 0xA0;
805 if (data_len < 4
806 || src_base + data_len > src_end)
807 return 0;
808 ONE_MORE_BYTE (c);
809 nchars = c - 0xA0;
810 if (c < 1)
811 return 0;
812 for (ncomponent = 0; src < src_base + data_len; ncomponent++)
813 {
814 /* If it is longer than this, it can't be valid. */
815 if (ncomponent >= COMPOSITION_DATA_MAX_BUNCH_LENGTH)
816 return 0;
817
818 if (ncomponent % 2 && with_rule)
819 {
820 ONE_MORE_BYTE (gref);
821 gref -= 32;
822 ONE_MORE_BYTE (nref);
823 nref -= 32;
824 c = COMPOSITION_ENCODE_RULE (gref, nref);
825 }
826 else
827 {
828 int bytes;
829 if (UNIBYTE_STR_AS_MULTIBYTE_P (src, src_end - src, bytes))
830 c = STRING_CHAR (src, bytes);
831 else
832 c = *src, bytes = 1;
833 src += bytes;
834 }
835 component[ncomponent] = c;
836 }
837 }
838 else
839 {
840 /* This may be an old Emacs 20 style format. See the comment at
841 the section 2 of this file. */
842 while (src < src_end && !CHAR_HEAD_P (*src)) src++;
843 if (src == src_end
844 && !(coding->mode & CODING_MODE_LAST_BLOCK))
845 goto label_end_of_loop;
846
847 src_end = src;
848 src = src_base + 1;
849 if (c < 0xC0)
850 {
851 method = COMPOSITION_RELATIVE;
852 for (ncomponent = 0; ncomponent < MAX_COMPOSITION_COMPONENTS;)
853 {
854 DECODE_EMACS_MULE_COMPOSITION_CHAR (c, bufp);
855 if (c < 0)
856 break;
857 component[ncomponent++] = c;
858 }
859 if (ncomponent < 2)
860 return 0;
861 nchars = ncomponent;
862 }
863 else if (c == 0xFF)
864 {
865 method = COMPOSITION_WITH_RULE;
866 src++;
867 DECODE_EMACS_MULE_COMPOSITION_CHAR (c, bufp);
868 if (c < 0)
869 return 0;
870 component[0] = c;
871 for (ncomponent = 1;
872 ncomponent < MAX_COMPOSITION_COMPONENTS * 2 - 1;)
873 {
874 DECODE_EMACS_MULE_COMPOSITION_RULE (c);
875 if (c < 0)
876 break;
877 component[ncomponent++] = c;
878 DECODE_EMACS_MULE_COMPOSITION_CHAR (c, bufp);
879 if (c < 0)
880 break;
881 component[ncomponent++] = c;
882 }
883 if (ncomponent < 3)
884 return 0;
885 nchars = (ncomponent + 1) / 2;
886 }
887 else
888 return 0;
889 }
890
891 if (buf == bufp || dst + (bufp - buf) <= (dst_bytes ? dst_end : src))
892 {
893 CODING_ADD_COMPOSITION_START (coding, coding->produced_char, method);
894 for (i = 0; i < ncomponent; i++)
895 CODING_ADD_COMPOSITION_COMPONENT (coding, component[i]);
896 CODING_ADD_COMPOSITION_END (coding, coding->produced_char + nchars);
897 if (buf < bufp)
898 {
899 unsigned char *p = buf;
900 EMIT_BYTES (p, bufp);
901 *destination += bufp - buf;
902 coding->produced_char += nchars;
903 }
904 return (src - src_base);
905 }
906 label_end_of_loop:
907 return -1;
908 }
909
910 /* See the above "GENERAL NOTES on `decode_coding_XXX ()' functions". */
911
912 static void
913 decode_coding_emacs_mule (coding, source, destination, src_bytes, dst_bytes)
914 struct coding_system *coding;
915 unsigned char *source, *destination;
916 int src_bytes, dst_bytes;
917 {
918 unsigned char *src = source;
919 unsigned char *src_end = source + src_bytes;
920 unsigned char *dst = destination;
921 unsigned char *dst_end = destination + dst_bytes;
922 /* SRC_BASE remembers the start position in source in each loop.
923 The loop will be exited when there's not enough source code, or
924 when there's not enough destination area to produce a
925 character. */
926 unsigned char *src_base;
927
928 coding->produced_char = 0;
929 while ((src_base = src) < src_end)
930 {
931 unsigned char tmp[MAX_MULTIBYTE_LENGTH], *p;
932 int bytes;
933
934 if (*src == '\r')
935 {
936 int c = *src++;
937
938 if (coding->eol_type == CODING_EOL_CR)
939 c = '\n';
940 else if (coding->eol_type == CODING_EOL_CRLF)
941 {
942 ONE_MORE_BYTE (c);
943 if (c != '\n')
944 {
945 if (coding->mode & CODING_MODE_INHIBIT_INCONSISTENT_EOL)
946 {
947 coding->result = CODING_FINISH_INCONSISTENT_EOL;
948 goto label_end_of_loop;
949 }
950 src--;
951 c = '\r';
952 }
953 }
954 *dst++ = c;
955 coding->produced_char++;
956 continue;
957 }
958 else if (*src == '\n')
959 {
960 if ((coding->eol_type == CODING_EOL_CR
961 || coding->eol_type == CODING_EOL_CRLF)
962 && coding->mode & CODING_MODE_INHIBIT_INCONSISTENT_EOL)
963 {
964 coding->result = CODING_FINISH_INCONSISTENT_EOL;
965 goto label_end_of_loop;
966 }
967 *dst++ = *src++;
968 coding->produced_char++;
969 continue;
970 }
971 else if (*src == 0x80 && coding->cmp_data)
972 {
973 /* Start of composition data. */
974 int consumed = decode_composition_emacs_mule (coding, src, src_end,
975 &dst, dst_end,
976 dst_bytes);
977 if (consumed < 0)
978 goto label_end_of_loop;
979 else if (consumed > 0)
980 {
981 src += consumed;
982 continue;
983 }
984 bytes = CHAR_STRING (*src, tmp);
985 p = tmp;
986 src++;
987 }
988 else if (UNIBYTE_STR_AS_MULTIBYTE_P (src, src_end - src, bytes))
989 {
990 p = src;
991 src += bytes;
992 }
993 else
994 {
995 bytes = CHAR_STRING (*src, tmp);
996 p = tmp;
997 src++;
998 }
999 if (dst + bytes >= (dst_bytes ? dst_end : src))
1000 {
1001 coding->result = CODING_FINISH_INSUFFICIENT_DST;
1002 break;
1003 }
1004 while (bytes--) *dst++ = *p++;
1005 coding->produced_char++;
1006 }
1007 label_end_of_loop:
1008 coding->consumed = coding->consumed_char = src_base - source;
1009 coding->produced = dst - destination;
1010 }
1011
1012
1013 /* Encode composition data stored at DATA into a special byte sequence
1014 starting by 0x80. Update CODING->cmp_data_start and maybe
1015 CODING->cmp_data for the next call. */
1016
1017 #define ENCODE_COMPOSITION_EMACS_MULE(coding, data) \
1018 do { \
1019 unsigned char buf[1024], *p0 = buf, *p; \
1020 int len = data[0]; \
1021 int i; \
1022 \
1023 buf[0] = 0x80; \
1024 buf[1] = 0xF0 + data[3]; /* METHOD */ \
1025 buf[3] = 0xA0 + (data[2] - data[1]); /* COMPOSED-CHARS */ \
1026 p = buf + 4; \
1027 if (data[3] == COMPOSITION_WITH_RULE \
1028 || data[3] == COMPOSITION_WITH_RULE_ALTCHARS) \
1029 { \
1030 p += CHAR_STRING (data[4], p); \
1031 for (i = 5; i < len; i += 2) \
1032 { \
1033 int gref, nref; \
1034 COMPOSITION_DECODE_RULE (data[i], gref, nref); \
1035 *p++ = 0x20 + gref; \
1036 *p++ = 0x20 + nref; \
1037 p += CHAR_STRING (data[i + 1], p); \
1038 } \
1039 } \
1040 else \
1041 { \
1042 for (i = 4; i < len; i++) \
1043 p += CHAR_STRING (data[i], p); \
1044 } \
1045 buf[2] = 0xA0 + (p - buf); /* COMPONENTS-BYTES */ \
1046 \
1047 if (dst + (p - buf) + 4 > (dst_bytes ? dst_end : src)) \
1048 { \
1049 coding->result = CODING_FINISH_INSUFFICIENT_DST; \
1050 goto label_end_of_loop; \
1051 } \
1052 while (p0 < p) \
1053 *dst++ = *p0++; \
1054 coding->cmp_data_start += data[0]; \
1055 if (coding->cmp_data_start == coding->cmp_data->used \
1056 && coding->cmp_data->next) \
1057 { \
1058 coding->cmp_data = coding->cmp_data->next; \
1059 coding->cmp_data_start = 0; \
1060 } \
1061 } while (0)
1062
1063
1064 static void encode_eol P_ ((struct coding_system *, const unsigned char *,
1065 unsigned char *, int, int));
1066
1067 static void
1068 encode_coding_emacs_mule (coding, source, destination, src_bytes, dst_bytes)
1069 struct coding_system *coding;
1070 unsigned char *source, *destination;
1071 int src_bytes, dst_bytes;
1072 {
1073 unsigned char *src = source;
1074 unsigned char *src_end = source + src_bytes;
1075 unsigned char *dst = destination;
1076 unsigned char *dst_end = destination + dst_bytes;
1077 unsigned char *src_base;
1078 int c;
1079 int char_offset;
1080 int *data;
1081
1082 Lisp_Object translation_table;
1083
1084 translation_table = Qnil;
1085
1086 /* Optimization for the case that there's no composition. */
1087 if (!coding->cmp_data || coding->cmp_data->used == 0)
1088 {
1089 encode_eol (coding, source, destination, src_bytes, dst_bytes);
1090 return;
1091 }
1092
1093 char_offset = coding->cmp_data->char_offset;
1094 data = coding->cmp_data->data + coding->cmp_data_start;
1095 while (1)
1096 {
1097 src_base = src;
1098
1099 /* If SRC starts a composition, encode the information about the
1100 composition in advance. */
1101 if (coding->cmp_data_start < coding->cmp_data->used
1102 && char_offset + coding->consumed_char == data[1])
1103 {
1104 ENCODE_COMPOSITION_EMACS_MULE (coding, data);
1105 char_offset = coding->cmp_data->char_offset;
1106 data = coding->cmp_data->data + coding->cmp_data_start;
1107 }
1108
1109 ONE_MORE_CHAR (c);
1110 if (c == '\n' && (coding->eol_type == CODING_EOL_CRLF
1111 || coding->eol_type == CODING_EOL_CR))
1112 {
1113 if (coding->eol_type == CODING_EOL_CRLF)
1114 EMIT_TWO_BYTES ('\r', c);
1115 else
1116 EMIT_ONE_BYTE ('\r');
1117 }
1118 else if (SINGLE_BYTE_CHAR_P (c))
1119 EMIT_ONE_BYTE (c);
1120 else
1121 EMIT_BYTES (src_base, src);
1122 coding->consumed_char++;
1123 }
1124 label_end_of_loop:
1125 coding->consumed = src_base - source;
1126 coding->produced = coding->produced_char = dst - destination;
1127 return;
1128 }
1129
1130 \f
1131 /*** 3. ISO2022 handlers ***/
1132
1133 /* The following note describes the coding system ISO2022 briefly.
1134 Since the intention of this note is to help understand the
1135 functions in this file, some parts are NOT ACCURATE or are OVERLY
1136 SIMPLIFIED. For thorough understanding, please refer to the
1137 original document of ISO2022. This is equivalent to the standard
1138 ECMA-35, obtainable from <URL:http://www.ecma.ch/> (*).
1139
1140 ISO2022 provides many mechanisms to encode several character sets
1141 in 7-bit and 8-bit environments. For 7-bit environments, all text
1142 is encoded using bytes less than 128. This may make the encoded
1143 text a little bit longer, but the text passes more easily through
1144 several types of gateway, some of which strip off the MSB (Most
1145 Significant Bit).
1146
1147 There are two kinds of character sets: control character sets and
1148 graphic character sets. The former contain control characters such
1149 as `newline' and `escape' to provide control functions (control
1150 functions are also provided by escape sequences). The latter
1151 contain graphic characters such as 'A' and '-'. Emacs recognizes
1152 two control character sets and many graphic character sets.
1153
1154 Graphic character sets are classified into one of the following
1155 four classes, according to the number of bytes (DIMENSION) and
1156 number of characters in one dimension (CHARS) of the set:
1157 - DIMENSION1_CHARS94
1158 - DIMENSION1_CHARS96
1159 - DIMENSION2_CHARS94
1160 - DIMENSION2_CHARS96
1161
1162 In addition, each character set is assigned an identification tag,
1163 unique for each set, called the "final character" (denoted as <F>
1164 hereafter). The <F> of each character set is decided by ECMA(*)
1165 when it is registered in ISO. The code range of <F> is 0x30..0x7F
1166 (0x30..0x3F are for private use only).
1167
1168 Note (*): ECMA = European Computer Manufacturers Association
1169
1170 Here are examples of graphic character sets [NAME(<F>)]:
1171 o DIMENSION1_CHARS94 -- ASCII('B'), right-half-of-JISX0201('I'), ...
1172 o DIMENSION1_CHARS96 -- right-half-of-ISO8859-1('A'), ...
1173 o DIMENSION2_CHARS94 -- GB2312('A'), JISX0208('B'), ...
1174 o DIMENSION2_CHARS96 -- none for the moment
1175
1176 A code area (1 byte=8 bits) is divided into 4 areas, C0, GL, C1, and GR.
1177 C0 [0x00..0x1F] -- control character plane 0
1178 GL [0x20..0x7F] -- graphic character plane 0
1179 C1 [0x80..0x9F] -- control character plane 1
1180 GR [0xA0..0xFF] -- graphic character plane 1
1181
1182 A control character set is directly designated and invoked to C0 or
1183 C1 by an escape sequence. The most common case is that:
1184 - ISO646's control character set is designated/invoked to C0, and
1185 - ISO6429's control character set is designated/invoked to C1,
1186 and usually these designations/invocations are omitted in encoded
1187 text. In a 7-bit environment, only C0 can be used, and a control
1188 character for C1 is encoded by an appropriate escape sequence to
1189 fit into the environment. All control characters for C1 are
1190 defined to have corresponding escape sequences.
1191
1192 A graphic character set is at first designated to one of four
1193 graphic registers (G0 through G3), then these graphic registers are
1194 invoked to GL or GR. These designations and invocations can be
1195 done independently. The most common case is that G0 is invoked to
1196 GL, G1 is invoked to GR, and ASCII is designated to G0. Usually
1197 these invocations and designations are omitted in encoded text.
1198 In a 7-bit environment, only GL can be used.
1199
1200 When a graphic character set of CHARS94 is invoked to GL, codes
1201 0x20 and 0x7F of the GL area work as control characters SPACE and
1202 DEL respectively, and codes 0xA0 and 0xFF of the GR area should not
1203 be used.
1204
1205 There are two ways of invocation: locking-shift and single-shift.
1206 With locking-shift, the invocation lasts until the next different
1207 invocation, whereas with single-shift, the invocation affects the
1208 following character only and doesn't affect the locking-shift
1209 state. Invocations are done by the following control characters or
1210 escape sequences:
1211
1212 ----------------------------------------------------------------------
1213 abbrev function cntrl escape seq description
1214 ----------------------------------------------------------------------
1215 SI/LS0 (shift-in) 0x0F none invoke G0 into GL
1216 SO/LS1 (shift-out) 0x0E none invoke G1 into GL
1217 LS2 (locking-shift-2) none ESC 'n' invoke G2 into GL
1218 LS3 (locking-shift-3) none ESC 'o' invoke G3 into GL
1219 LS1R (locking-shift-1 right) none ESC '~' invoke G1 into GR (*)
1220 LS2R (locking-shift-2 right) none ESC '}' invoke G2 into GR (*)
1221 LS3R (locking-shift 3 right) none ESC '|' invoke G3 into GR (*)
1222 SS2 (single-shift-2) 0x8E ESC 'N' invoke G2 for one char
1223 SS3 (single-shift-3) 0x8F ESC 'O' invoke G3 for one char
1224 ----------------------------------------------------------------------
1225 (*) These are not used by any known coding system.
1226
1227 Control characters for these functions are defined by macros
1228 ISO_CODE_XXX in `coding.h'.
1229
1230 Designations are done by the following escape sequences:
1231 ----------------------------------------------------------------------
1232 escape sequence description
1233 ----------------------------------------------------------------------
1234 ESC '(' <F> designate DIMENSION1_CHARS94<F> to G0
1235 ESC ')' <F> designate DIMENSION1_CHARS94<F> to G1
1236 ESC '*' <F> designate DIMENSION1_CHARS94<F> to G2
1237 ESC '+' <F> designate DIMENSION1_CHARS94<F> to G3
1238 ESC ',' <F> designate DIMENSION1_CHARS96<F> to G0 (*)
1239 ESC '-' <F> designate DIMENSION1_CHARS96<F> to G1
1240 ESC '.' <F> designate DIMENSION1_CHARS96<F> to G2
1241 ESC '/' <F> designate DIMENSION1_CHARS96<F> to G3
1242 ESC '$' '(' <F> designate DIMENSION2_CHARS94<F> to G0 (**)
1243 ESC '$' ')' <F> designate DIMENSION2_CHARS94<F> to G1
1244 ESC '$' '*' <F> designate DIMENSION2_CHARS94<F> to G2
1245 ESC '$' '+' <F> designate DIMENSION2_CHARS94<F> to G3
1246 ESC '$' ',' <F> designate DIMENSION2_CHARS96<F> to G0 (*)
1247 ESC '$' '-' <F> designate DIMENSION2_CHARS96<F> to G1
1248 ESC '$' '.' <F> designate DIMENSION2_CHARS96<F> to G2
1249 ESC '$' '/' <F> designate DIMENSION2_CHARS96<F> to G3
1250 ----------------------------------------------------------------------
1251
1252 In this list, "DIMENSION1_CHARS94<F>" means a graphic character set
1253 of dimension 1, chars 94, and final character <F>, etc...
1254
1255 Note (*): Although these designations are not allowed in ISO2022,
1256 Emacs accepts them on decoding, and produces them on encoding
1257 CHARS96 character sets in a coding system which is characterized as
1258 7-bit environment, non-locking-shift, and non-single-shift.
1259
1260 Note (**): If <F> is '@', 'A', or 'B', the intermediate character
1261 '(' can be omitted. We refer to this as "short-form" hereafter.
1262
1263 Now you may notice that there are a lot of ways of encoding the
1264 same multilingual text in ISO2022. Actually, there exist many
1265 coding systems such as Compound Text (used in X11's inter client
1266 communication, ISO-2022-JP (used in Japanese Internet), ISO-2022-KR
1267 (used in Korean Internet), EUC (Extended UNIX Code, used in Asian
1268 localized platforms), and all of these are variants of ISO2022.
1269
1270 In addition to the above, Emacs handles two more kinds of escape
1271 sequences: ISO6429's direction specification and Emacs' private
1272 sequence for specifying character composition.
1273
1274 ISO6429's direction specification takes the following form:
1275 o CSI ']' -- end of the current direction
1276 o CSI '0' ']' -- end of the current direction
1277 o CSI '1' ']' -- start of left-to-right text
1278 o CSI '2' ']' -- start of right-to-left text
1279 The control character CSI (0x9B: control sequence introducer) is
1280 abbreviated to the escape sequence ESC '[' in a 7-bit environment.
1281
1282 Character composition specification takes the following form:
1283 o ESC '0' -- start relative composition
1284 o ESC '1' -- end composition
1285 o ESC '2' -- start rule-base composition (*)
1286 o ESC '3' -- start relative composition with alternate chars (**)
1287 o ESC '4' -- start rule-base composition with alternate chars (**)
1288 Since these are not standard escape sequences of any ISO standard,
1289 the use of them with these meanings is restricted to Emacs only.
1290
1291 (*) This form is used only in Emacs 20.5 and older versions,
1292 but the newer versions can safely decode it.
1293 (**) This form is used only in Emacs 21.1 and newer versions,
1294 and the older versions can't decode it.
1295
1296 Here's a list of example usages of these composition escape
1297 sequences (categorized by `enum composition_method').
1298
1299 COMPOSITION_RELATIVE:
1300 ESC 0 CHAR [ CHAR ] ESC 1
1301 COMPOSITION_WITH_RULE:
1302 ESC 2 CHAR [ RULE CHAR ] ESC 1
1303 COMPOSITION_WITH_ALTCHARS:
1304 ESC 3 ALTCHAR [ ALTCHAR ] ESC 0 CHAR [ CHAR ] ESC 1
1305 COMPOSITION_WITH_RULE_ALTCHARS:
1306 ESC 4 ALTCHAR [ RULE ALTCHAR ] ESC 0 CHAR [ CHAR ] ESC 1 */
1307
1308 enum iso_code_class_type iso_code_class[256];
1309
1310 #define CHARSET_OK(idx, charset, c) \
1311 (coding_system_table[idx] \
1312 && (charset == CHARSET_ASCII \
1313 || (safe_chars = coding_safe_chars (coding_system_table[idx]), \
1314 CODING_SAFE_CHAR_P (safe_chars, c))) \
1315 && (CODING_SPEC_ISO_REQUESTED_DESIGNATION (coding_system_table[idx], \
1316 charset) \
1317 != CODING_SPEC_ISO_NO_REQUESTED_DESIGNATION))
1318
1319 #define SHIFT_OUT_OK(idx) \
1320 (CODING_SPEC_ISO_INITIAL_DESIGNATION (coding_system_table[idx], 1) >= 0)
1321
1322 /* See the above "GENERAL NOTES on `detect_coding_XXX ()' functions".
1323 Check if a text is encoded in ISO2022. If it is, return an
1324 integer in which appropriate flag bits any of:
1325 CODING_CATEGORY_MASK_ISO_7
1326 CODING_CATEGORY_MASK_ISO_7_TIGHT
1327 CODING_CATEGORY_MASK_ISO_8_1
1328 CODING_CATEGORY_MASK_ISO_8_2
1329 CODING_CATEGORY_MASK_ISO_7_ELSE
1330 CODING_CATEGORY_MASK_ISO_8_ELSE
1331 are set. If a code which should never appear in ISO2022 is found,
1332 returns 0. */
1333
1334 static int
1335 detect_coding_iso2022 (src, src_end, multibytep)
1336 unsigned char *src, *src_end;
1337 int multibytep;
1338 {
1339 int mask = CODING_CATEGORY_MASK_ISO;
1340 int mask_found = 0;
1341 int reg[4], shift_out = 0, single_shifting = 0;
1342 int c, c1, charset;
1343 /* Dummy for ONE_MORE_BYTE. */
1344 struct coding_system dummy_coding;
1345 struct coding_system *coding = &dummy_coding;
1346 Lisp_Object safe_chars;
1347
1348 reg[0] = CHARSET_ASCII, reg[1] = reg[2] = reg[3] = -1;
1349 while (mask && src < src_end)
1350 {
1351 ONE_MORE_BYTE_CHECK_MULTIBYTE (c, multibytep);
1352 retry:
1353 switch (c)
1354 {
1355 case ISO_CODE_ESC:
1356 if (inhibit_iso_escape_detection)
1357 break;
1358 single_shifting = 0;
1359 ONE_MORE_BYTE_CHECK_MULTIBYTE (c, multibytep);
1360 if (c >= '(' && c <= '/')
1361 {
1362 /* Designation sequence for a charset of dimension 1. */
1363 ONE_MORE_BYTE_CHECK_MULTIBYTE (c1, multibytep);
1364 if (c1 < ' ' || c1 >= 0x80
1365 || (charset = iso_charset_table[0][c >= ','][c1]) < 0)
1366 /* Invalid designation sequence. Just ignore. */
1367 break;
1368 reg[(c - '(') % 4] = charset;
1369 }
1370 else if (c == '$')
1371 {
1372 /* Designation sequence for a charset of dimension 2. */
1373 ONE_MORE_BYTE_CHECK_MULTIBYTE (c, multibytep);
1374 if (c >= '@' && c <= 'B')
1375 /* Designation for JISX0208.1978, GB2312, or JISX0208. */
1376 reg[0] = charset = iso_charset_table[1][0][c];
1377 else if (c >= '(' && c <= '/')
1378 {
1379 ONE_MORE_BYTE_CHECK_MULTIBYTE (c1, multibytep);
1380 if (c1 < ' ' || c1 >= 0x80
1381 || (charset = iso_charset_table[1][c >= ','][c1]) < 0)
1382 /* Invalid designation sequence. Just ignore. */
1383 break;
1384 reg[(c - '(') % 4] = charset;
1385 }
1386 else
1387 /* Invalid designation sequence. Just ignore. */
1388 break;
1389 }
1390 else if (c == 'N' || c == 'O')
1391 {
1392 /* ESC <Fe> for SS2 or SS3. */
1393 mask &= CODING_CATEGORY_MASK_ISO_7_ELSE;
1394 break;
1395 }
1396 else if (c >= '0' && c <= '4')
1397 {
1398 /* ESC <Fp> for start/end composition. */
1399 mask_found |= CODING_CATEGORY_MASK_ISO;
1400 break;
1401 }
1402 else
1403 /* Invalid escape sequence. Just ignore. */
1404 break;
1405
1406 /* We found a valid designation sequence for CHARSET. */
1407 mask &= ~CODING_CATEGORY_MASK_ISO_8BIT;
1408 c = MAKE_CHAR (charset, 0, 0);
1409 if (CHARSET_OK (CODING_CATEGORY_IDX_ISO_7, charset, c))
1410 mask_found |= CODING_CATEGORY_MASK_ISO_7;
1411 else
1412 mask &= ~CODING_CATEGORY_MASK_ISO_7;
1413 if (CHARSET_OK (CODING_CATEGORY_IDX_ISO_7_TIGHT, charset, c))
1414 mask_found |= CODING_CATEGORY_MASK_ISO_7_TIGHT;
1415 else
1416 mask &= ~CODING_CATEGORY_MASK_ISO_7_TIGHT;
1417 if (CHARSET_OK (CODING_CATEGORY_IDX_ISO_7_ELSE, charset, c))
1418 mask_found |= CODING_CATEGORY_MASK_ISO_7_ELSE;
1419 else
1420 mask &= ~CODING_CATEGORY_MASK_ISO_7_ELSE;
1421 if (CHARSET_OK (CODING_CATEGORY_IDX_ISO_8_ELSE, charset, c))
1422 mask_found |= CODING_CATEGORY_MASK_ISO_8_ELSE;
1423 else
1424 mask &= ~CODING_CATEGORY_MASK_ISO_8_ELSE;
1425 break;
1426
1427 case ISO_CODE_SO:
1428 if (inhibit_iso_escape_detection)
1429 break;
1430 single_shifting = 0;
1431 if (shift_out == 0
1432 && (reg[1] >= 0
1433 || SHIFT_OUT_OK (CODING_CATEGORY_IDX_ISO_7_ELSE)
1434 || SHIFT_OUT_OK (CODING_CATEGORY_IDX_ISO_8_ELSE)))
1435 {
1436 /* Locking shift out. */
1437 mask &= ~CODING_CATEGORY_MASK_ISO_7BIT;
1438 mask_found |= CODING_CATEGORY_MASK_ISO_SHIFT;
1439 }
1440 break;
1441
1442 case ISO_CODE_SI:
1443 if (inhibit_iso_escape_detection)
1444 break;
1445 single_shifting = 0;
1446 if (shift_out == 1)
1447 {
1448 /* Locking shift in. */
1449 mask &= ~CODING_CATEGORY_MASK_ISO_7BIT;
1450 mask_found |= CODING_CATEGORY_MASK_ISO_SHIFT;
1451 }
1452 break;
1453
1454 case ISO_CODE_CSI:
1455 single_shifting = 0;
1456 case ISO_CODE_SS2:
1457 case ISO_CODE_SS3:
1458 {
1459 int newmask = CODING_CATEGORY_MASK_ISO_8_ELSE;
1460
1461 if (inhibit_iso_escape_detection)
1462 break;
1463 if (c != ISO_CODE_CSI)
1464 {
1465 if (coding_system_table[CODING_CATEGORY_IDX_ISO_8_1]->flags
1466 & CODING_FLAG_ISO_SINGLE_SHIFT)
1467 newmask |= CODING_CATEGORY_MASK_ISO_8_1;
1468 if (coding_system_table[CODING_CATEGORY_IDX_ISO_8_2]->flags
1469 & CODING_FLAG_ISO_SINGLE_SHIFT)
1470 newmask |= CODING_CATEGORY_MASK_ISO_8_2;
1471 single_shifting = 1;
1472 }
1473 if (VECTORP (Vlatin_extra_code_table)
1474 && !NILP (XVECTOR (Vlatin_extra_code_table)->contents[c]))
1475 {
1476 if (coding_system_table[CODING_CATEGORY_IDX_ISO_8_1]->flags
1477 & CODING_FLAG_ISO_LATIN_EXTRA)
1478 newmask |= CODING_CATEGORY_MASK_ISO_8_1;
1479 if (coding_system_table[CODING_CATEGORY_IDX_ISO_8_2]->flags
1480 & CODING_FLAG_ISO_LATIN_EXTRA)
1481 newmask |= CODING_CATEGORY_MASK_ISO_8_2;
1482 }
1483 mask &= newmask;
1484 mask_found |= newmask;
1485 }
1486 break;
1487
1488 default:
1489 if (c < 0x80)
1490 {
1491 single_shifting = 0;
1492 break;
1493 }
1494 else if (c < 0xA0)
1495 {
1496 single_shifting = 0;
1497 if (VECTORP (Vlatin_extra_code_table)
1498 && !NILP (XVECTOR (Vlatin_extra_code_table)->contents[c]))
1499 {
1500 int newmask = 0;
1501
1502 if (coding_system_table[CODING_CATEGORY_IDX_ISO_8_1]->flags
1503 & CODING_FLAG_ISO_LATIN_EXTRA)
1504 newmask |= CODING_CATEGORY_MASK_ISO_8_1;
1505 if (coding_system_table[CODING_CATEGORY_IDX_ISO_8_2]->flags
1506 & CODING_FLAG_ISO_LATIN_EXTRA)
1507 newmask |= CODING_CATEGORY_MASK_ISO_8_2;
1508 mask &= newmask;
1509 mask_found |= newmask;
1510 }
1511 else
1512 return 0;
1513 }
1514 else
1515 {
1516 mask &= ~(CODING_CATEGORY_MASK_ISO_7BIT
1517 | CODING_CATEGORY_MASK_ISO_7_ELSE);
1518 mask_found |= CODING_CATEGORY_MASK_ISO_8_1;
1519 /* Check the length of succeeding codes of the range
1520 0xA0..0FF. If the byte length is odd, we exclude
1521 CODING_CATEGORY_MASK_ISO_8_2. We can check this only
1522 when we are not single shifting. */
1523 if (!single_shifting
1524 && mask & CODING_CATEGORY_MASK_ISO_8_2)
1525 {
1526 int i = 1;
1527
1528 c = -1;
1529 while (src < src_end)
1530 {
1531 ONE_MORE_BYTE_CHECK_MULTIBYTE (c, multibytep);
1532 if (c < 0xA0)
1533 break;
1534 i++;
1535 }
1536
1537 if (i & 1 && src < src_end)
1538 mask &= ~CODING_CATEGORY_MASK_ISO_8_2;
1539 else
1540 mask_found |= CODING_CATEGORY_MASK_ISO_8_2;
1541 if (c >= 0)
1542 /* This means that we have read one extra byte. */
1543 goto retry;
1544 }
1545 }
1546 break;
1547 }
1548 }
1549 label_end_of_loop:
1550 return (mask & mask_found);
1551 }
1552
1553 /* Decode a character of which charset is CHARSET, the 1st position
1554 code is C1, the 2nd position code is C2, and return the decoded
1555 character code. If the variable `translation_table' is non-nil,
1556 returned the translated code. */
1557
1558 #define DECODE_ISO_CHARACTER(charset, c1, c2) \
1559 (NILP (translation_table) \
1560 ? MAKE_CHAR (charset, c1, c2) \
1561 : translate_char (translation_table, -1, charset, c1, c2))
1562
1563 /* Set designation state into CODING. */
1564 #define DECODE_DESIGNATION(reg, dimension, chars, final_char) \
1565 do { \
1566 int charset, c; \
1567 \
1568 if (final_char < '0' || final_char >= 128) \
1569 goto label_invalid_code; \
1570 charset = ISO_CHARSET_TABLE (make_number (dimension), \
1571 make_number (chars), \
1572 make_number (final_char)); \
1573 c = MAKE_CHAR (charset, 0, 0); \
1574 if (charset >= 0 \
1575 && (CODING_SPEC_ISO_REQUESTED_DESIGNATION (coding, charset) == reg \
1576 || CODING_SAFE_CHAR_P (safe_chars, c))) \
1577 { \
1578 if (coding->spec.iso2022.last_invalid_designation_register == 0 \
1579 && reg == 0 \
1580 && charset == CHARSET_ASCII) \
1581 { \
1582 /* We should insert this designation sequence as is so \
1583 that it is surely written back to a file. */ \
1584 coding->spec.iso2022.last_invalid_designation_register = -1; \
1585 goto label_invalid_code; \
1586 } \
1587 coding->spec.iso2022.last_invalid_designation_register = -1; \
1588 if ((coding->mode & CODING_MODE_DIRECTION) \
1589 && CHARSET_REVERSE_CHARSET (charset) >= 0) \
1590 charset = CHARSET_REVERSE_CHARSET (charset); \
1591 CODING_SPEC_ISO_DESIGNATION (coding, reg) = charset; \
1592 } \
1593 else \
1594 { \
1595 coding->spec.iso2022.last_invalid_designation_register = reg; \
1596 goto label_invalid_code; \
1597 } \
1598 } while (0)
1599
1600 /* Allocate a memory block for storing information about compositions.
1601 The block is chained to the already allocated blocks. */
1602
1603 void
1604 coding_allocate_composition_data (coding, char_offset)
1605 struct coding_system *coding;
1606 int char_offset;
1607 {
1608 struct composition_data *cmp_data
1609 = (struct composition_data *) xmalloc (sizeof *cmp_data);
1610
1611 cmp_data->char_offset = char_offset;
1612 cmp_data->used = 0;
1613 cmp_data->prev = coding->cmp_data;
1614 cmp_data->next = NULL;
1615 if (coding->cmp_data)
1616 coding->cmp_data->next = cmp_data;
1617 coding->cmp_data = cmp_data;
1618 coding->cmp_data_start = 0;
1619 }
1620
1621 /* Handle composition start sequence ESC 0, ESC 2, ESC 3, or ESC 4.
1622 ESC 0 : relative composition : ESC 0 CHAR ... ESC 1
1623 ESC 2 : rulebase composition : ESC 2 CHAR RULE CHAR RULE ... CHAR ESC 1
1624 ESC 3 : altchar composition : ESC 3 ALT ... ESC 0 CHAR ... ESC 1
1625 ESC 4 : alt&rule composition : ESC 4 ALT RULE .. ALT ESC 0 CHAR ... ESC 1
1626 */
1627
1628 #define DECODE_COMPOSITION_START(c1) \
1629 do { \
1630 if (coding->composing == COMPOSITION_DISABLED) \
1631 { \
1632 *dst++ = ISO_CODE_ESC; \
1633 *dst++ = c1 & 0x7f; \
1634 coding->produced_char += 2; \
1635 } \
1636 else if (!COMPOSING_P (coding)) \
1637 { \
1638 /* This is surely the start of a composition. We must be sure \
1639 that coding->cmp_data has enough space to store the \
1640 information about the composition. If not, terminate the \
1641 current decoding loop, allocate one more memory block for \
1642 coding->cmp_data in the caller, then start the decoding \
1643 loop again. We can't allocate memory here directly because \
1644 it may cause buffer/string relocation. */ \
1645 if (!coding->cmp_data \
1646 || (coding->cmp_data->used + COMPOSITION_DATA_MAX_BUNCH_LENGTH \
1647 >= COMPOSITION_DATA_SIZE)) \
1648 { \
1649 coding->result = CODING_FINISH_INSUFFICIENT_CMP; \
1650 goto label_end_of_loop; \
1651 } \
1652 coding->composing = (c1 == '0' ? COMPOSITION_RELATIVE \
1653 : c1 == '2' ? COMPOSITION_WITH_RULE \
1654 : c1 == '3' ? COMPOSITION_WITH_ALTCHARS \
1655 : COMPOSITION_WITH_RULE_ALTCHARS); \
1656 CODING_ADD_COMPOSITION_START (coding, coding->produced_char, \
1657 coding->composing); \
1658 coding->composition_rule_follows = 0; \
1659 } \
1660 else \
1661 { \
1662 /* We are already handling a composition. If the method is \
1663 the following two, the codes following the current escape \
1664 sequence are actual characters stored in a buffer. */ \
1665 if (coding->composing == COMPOSITION_WITH_ALTCHARS \
1666 || coding->composing == COMPOSITION_WITH_RULE_ALTCHARS) \
1667 { \
1668 coding->composing = COMPOSITION_RELATIVE; \
1669 coding->composition_rule_follows = 0; \
1670 } \
1671 } \
1672 } while (0)
1673
1674 /* Handle composition end sequence ESC 1. */
1675
1676 #define DECODE_COMPOSITION_END(c1) \
1677 do { \
1678 if (! COMPOSING_P (coding)) \
1679 { \
1680 *dst++ = ISO_CODE_ESC; \
1681 *dst++ = c1; \
1682 coding->produced_char += 2; \
1683 } \
1684 else \
1685 { \
1686 CODING_ADD_COMPOSITION_END (coding, coding->produced_char); \
1687 coding->composing = COMPOSITION_NO; \
1688 } \
1689 } while (0)
1690
1691 /* Decode a composition rule from the byte C1 (and maybe one more byte
1692 from SRC) and store one encoded composition rule in
1693 coding->cmp_data. */
1694
1695 #define DECODE_COMPOSITION_RULE(c1) \
1696 do { \
1697 int rule = 0; \
1698 (c1) -= 32; \
1699 if (c1 < 81) /* old format (before ver.21) */ \
1700 { \
1701 int gref = (c1) / 9; \
1702 int nref = (c1) % 9; \
1703 if (gref == 4) gref = 10; \
1704 if (nref == 4) nref = 10; \
1705 rule = COMPOSITION_ENCODE_RULE (gref, nref); \
1706 } \
1707 else if (c1 < 93) /* new format (after ver.21) */ \
1708 { \
1709 ONE_MORE_BYTE (c2); \
1710 rule = COMPOSITION_ENCODE_RULE (c1 - 81, c2 - 32); \
1711 } \
1712 CODING_ADD_COMPOSITION_COMPONENT (coding, rule); \
1713 coding->composition_rule_follows = 0; \
1714 } while (0)
1715
1716
1717 /* See the above "GENERAL NOTES on `decode_coding_XXX ()' functions". */
1718
1719 static void
1720 decode_coding_iso2022 (coding, source, destination, src_bytes, dst_bytes)
1721 struct coding_system *coding;
1722 unsigned char *source, *destination;
1723 int src_bytes, dst_bytes;
1724 {
1725 unsigned char *src = source;
1726 unsigned char *src_end = source + src_bytes;
1727 unsigned char *dst = destination;
1728 unsigned char *dst_end = destination + dst_bytes;
1729 /* Charsets invoked to graphic plane 0 and 1 respectively. */
1730 int charset0 = CODING_SPEC_ISO_PLANE_CHARSET (coding, 0);
1731 int charset1 = CODING_SPEC_ISO_PLANE_CHARSET (coding, 1);
1732 /* SRC_BASE remembers the start position in source in each loop.
1733 The loop will be exited when there's not enough source code
1734 (within macro ONE_MORE_BYTE), or when there's not enough
1735 destination area to produce a character (within macro
1736 EMIT_CHAR). */
1737 unsigned char *src_base;
1738 int c, charset;
1739 Lisp_Object translation_table;
1740 Lisp_Object safe_chars;
1741
1742 safe_chars = coding_safe_chars (coding);
1743
1744 if (NILP (Venable_character_translation))
1745 translation_table = Qnil;
1746 else
1747 {
1748 translation_table = coding->translation_table_for_decode;
1749 if (NILP (translation_table))
1750 translation_table = Vstandard_translation_table_for_decode;
1751 }
1752
1753 coding->result = CODING_FINISH_NORMAL;
1754
1755 while (1)
1756 {
1757 int c1, c2;
1758
1759 src_base = src;
1760 ONE_MORE_BYTE (c1);
1761
1762 /* We produce no character or one character. */
1763 switch (iso_code_class [c1])
1764 {
1765 case ISO_0x20_or_0x7F:
1766 if (COMPOSING_P (coding) && coding->composition_rule_follows)
1767 {
1768 DECODE_COMPOSITION_RULE (c1);
1769 continue;
1770 }
1771 if (charset0 < 0 || CHARSET_CHARS (charset0) == 94)
1772 {
1773 /* This is SPACE or DEL. */
1774 charset = CHARSET_ASCII;
1775 break;
1776 }
1777 /* This is a graphic character, we fall down ... */
1778
1779 case ISO_graphic_plane_0:
1780 if (COMPOSING_P (coding) && coding->composition_rule_follows)
1781 {
1782 DECODE_COMPOSITION_RULE (c1);
1783 continue;
1784 }
1785 charset = charset0;
1786 break;
1787
1788 case ISO_0xA0_or_0xFF:
1789 if (charset1 < 0 || CHARSET_CHARS (charset1) == 94
1790 || coding->flags & CODING_FLAG_ISO_SEVEN_BITS)
1791 goto label_invalid_code;
1792 /* This is a graphic character, we fall down ... */
1793
1794 case ISO_graphic_plane_1:
1795 if (charset1 < 0)
1796 goto label_invalid_code;
1797 charset = charset1;
1798 break;
1799
1800 case ISO_control_0:
1801 if (COMPOSING_P (coding))
1802 DECODE_COMPOSITION_END ('1');
1803
1804 /* All ISO2022 control characters in this class have the
1805 same representation in Emacs internal format. */
1806 if (c1 == '\n'
1807 && (coding->mode & CODING_MODE_INHIBIT_INCONSISTENT_EOL)
1808 && (coding->eol_type == CODING_EOL_CR
1809 || coding->eol_type == CODING_EOL_CRLF))
1810 {
1811 coding->result = CODING_FINISH_INCONSISTENT_EOL;
1812 goto label_end_of_loop;
1813 }
1814 charset = CHARSET_ASCII;
1815 break;
1816
1817 case ISO_control_1:
1818 if (COMPOSING_P (coding))
1819 DECODE_COMPOSITION_END ('1');
1820 goto label_invalid_code;
1821
1822 case ISO_carriage_return:
1823 if (COMPOSING_P (coding))
1824 DECODE_COMPOSITION_END ('1');
1825
1826 if (coding->eol_type == CODING_EOL_CR)
1827 c1 = '\n';
1828 else if (coding->eol_type == CODING_EOL_CRLF)
1829 {
1830 ONE_MORE_BYTE (c1);
1831 if (c1 != ISO_CODE_LF)
1832 {
1833 if (coding->mode & CODING_MODE_INHIBIT_INCONSISTENT_EOL)
1834 {
1835 coding->result = CODING_FINISH_INCONSISTENT_EOL;
1836 goto label_end_of_loop;
1837 }
1838 src--;
1839 c1 = '\r';
1840 }
1841 }
1842 charset = CHARSET_ASCII;
1843 break;
1844
1845 case ISO_shift_out:
1846 if (! (coding->flags & CODING_FLAG_ISO_LOCKING_SHIFT)
1847 || CODING_SPEC_ISO_DESIGNATION (coding, 1) < 0)
1848 goto label_invalid_code;
1849 CODING_SPEC_ISO_INVOCATION (coding, 0) = 1;
1850 charset0 = CODING_SPEC_ISO_PLANE_CHARSET (coding, 0);
1851 continue;
1852
1853 case ISO_shift_in:
1854 if (! (coding->flags & CODING_FLAG_ISO_LOCKING_SHIFT))
1855 goto label_invalid_code;
1856 CODING_SPEC_ISO_INVOCATION (coding, 0) = 0;
1857 charset0 = CODING_SPEC_ISO_PLANE_CHARSET (coding, 0);
1858 continue;
1859
1860 case ISO_single_shift_2_7:
1861 case ISO_single_shift_2:
1862 if (! (coding->flags & CODING_FLAG_ISO_SINGLE_SHIFT))
1863 goto label_invalid_code;
1864 /* SS2 is handled as an escape sequence of ESC 'N' */
1865 c1 = 'N';
1866 goto label_escape_sequence;
1867
1868 case ISO_single_shift_3:
1869 if (! (coding->flags & CODING_FLAG_ISO_SINGLE_SHIFT))
1870 goto label_invalid_code;
1871 /* SS2 is handled as an escape sequence of ESC 'O' */
1872 c1 = 'O';
1873 goto label_escape_sequence;
1874
1875 case ISO_control_sequence_introducer:
1876 /* CSI is handled as an escape sequence of ESC '[' ... */
1877 c1 = '[';
1878 goto label_escape_sequence;
1879
1880 case ISO_escape:
1881 ONE_MORE_BYTE (c1);
1882 label_escape_sequence:
1883 /* Escape sequences handled by Emacs are invocation,
1884 designation, direction specification, and character
1885 composition specification. */
1886 switch (c1)
1887 {
1888 case '&': /* revision of following character set */
1889 ONE_MORE_BYTE (c1);
1890 if (!(c1 >= '@' && c1 <= '~'))
1891 goto label_invalid_code;
1892 ONE_MORE_BYTE (c1);
1893 if (c1 != ISO_CODE_ESC)
1894 goto label_invalid_code;
1895 ONE_MORE_BYTE (c1);
1896 goto label_escape_sequence;
1897
1898 case '$': /* designation of 2-byte character set */
1899 if (! (coding->flags & CODING_FLAG_ISO_DESIGNATION))
1900 goto label_invalid_code;
1901 ONE_MORE_BYTE (c1);
1902 if (c1 >= '@' && c1 <= 'B')
1903 { /* designation of JISX0208.1978, GB2312.1980,
1904 or JISX0208.1980 */
1905 DECODE_DESIGNATION (0, 2, 94, c1);
1906 }
1907 else if (c1 >= 0x28 && c1 <= 0x2B)
1908 { /* designation of DIMENSION2_CHARS94 character set */
1909 ONE_MORE_BYTE (c2);
1910 DECODE_DESIGNATION (c1 - 0x28, 2, 94, c2);
1911 }
1912 else if (c1 >= 0x2C && c1 <= 0x2F)
1913 { /* designation of DIMENSION2_CHARS96 character set */
1914 ONE_MORE_BYTE (c2);
1915 DECODE_DESIGNATION (c1 - 0x2C, 2, 96, c2);
1916 }
1917 else
1918 goto label_invalid_code;
1919 /* We must update these variables now. */
1920 charset0 = CODING_SPEC_ISO_PLANE_CHARSET (coding, 0);
1921 charset1 = CODING_SPEC_ISO_PLANE_CHARSET (coding, 1);
1922 continue;
1923
1924 case 'n': /* invocation of locking-shift-2 */
1925 if (! (coding->flags & CODING_FLAG_ISO_LOCKING_SHIFT)
1926 || CODING_SPEC_ISO_DESIGNATION (coding, 2) < 0)
1927 goto label_invalid_code;
1928 CODING_SPEC_ISO_INVOCATION (coding, 0) = 2;
1929 charset0 = CODING_SPEC_ISO_PLANE_CHARSET (coding, 0);
1930 continue;
1931
1932 case 'o': /* invocation of locking-shift-3 */
1933 if (! (coding->flags & CODING_FLAG_ISO_LOCKING_SHIFT)
1934 || CODING_SPEC_ISO_DESIGNATION (coding, 3) < 0)
1935 goto label_invalid_code;
1936 CODING_SPEC_ISO_INVOCATION (coding, 0) = 3;
1937 charset0 = CODING_SPEC_ISO_PLANE_CHARSET (coding, 0);
1938 continue;
1939
1940 case 'N': /* invocation of single-shift-2 */
1941 if (! (coding->flags & CODING_FLAG_ISO_SINGLE_SHIFT)
1942 || CODING_SPEC_ISO_DESIGNATION (coding, 2) < 0)
1943 goto label_invalid_code;
1944 charset = CODING_SPEC_ISO_DESIGNATION (coding, 2);
1945 ONE_MORE_BYTE (c1);
1946 if (c1 < 0x20 || (c1 >= 0x80 && c1 < 0xA0))
1947 goto label_invalid_code;
1948 break;
1949
1950 case 'O': /* invocation of single-shift-3 */
1951 if (! (coding->flags & CODING_FLAG_ISO_SINGLE_SHIFT)
1952 || CODING_SPEC_ISO_DESIGNATION (coding, 3) < 0)
1953 goto label_invalid_code;
1954 charset = CODING_SPEC_ISO_DESIGNATION (coding, 3);
1955 ONE_MORE_BYTE (c1);
1956 if (c1 < 0x20 || (c1 >= 0x80 && c1 < 0xA0))
1957 goto label_invalid_code;
1958 break;
1959
1960 case '0': case '2': case '3': case '4': /* start composition */
1961 DECODE_COMPOSITION_START (c1);
1962 continue;
1963
1964 case '1': /* end composition */
1965 DECODE_COMPOSITION_END (c1);
1966 continue;
1967
1968 case '[': /* specification of direction */
1969 if (coding->flags & CODING_FLAG_ISO_NO_DIRECTION)
1970 goto label_invalid_code;
1971 /* For the moment, nested direction is not supported.
1972 So, `coding->mode & CODING_MODE_DIRECTION' zero means
1973 left-to-right, and nonzero means right-to-left. */
1974 ONE_MORE_BYTE (c1);
1975 switch (c1)
1976 {
1977 case ']': /* end of the current direction */
1978 coding->mode &= ~CODING_MODE_DIRECTION;
1979
1980 case '0': /* end of the current direction */
1981 case '1': /* start of left-to-right direction */
1982 ONE_MORE_BYTE (c1);
1983 if (c1 == ']')
1984 coding->mode &= ~CODING_MODE_DIRECTION;
1985 else
1986 goto label_invalid_code;
1987 break;
1988
1989 case '2': /* start of right-to-left direction */
1990 ONE_MORE_BYTE (c1);
1991 if (c1 == ']')
1992 coding->mode |= CODING_MODE_DIRECTION;
1993 else
1994 goto label_invalid_code;
1995 break;
1996
1997 default:
1998 goto label_invalid_code;
1999 }
2000 continue;
2001
2002 default:
2003 if (! (coding->flags & CODING_FLAG_ISO_DESIGNATION))
2004 goto label_invalid_code;
2005 if (c1 >= 0x28 && c1 <= 0x2B)
2006 { /* designation of DIMENSION1_CHARS94 character set */
2007 ONE_MORE_BYTE (c2);
2008 DECODE_DESIGNATION (c1 - 0x28, 1, 94, c2);
2009 }
2010 else if (c1 >= 0x2C && c1 <= 0x2F)
2011 { /* designation of DIMENSION1_CHARS96 character set */
2012 ONE_MORE_BYTE (c2);
2013 DECODE_DESIGNATION (c1 - 0x2C, 1, 96, c2);
2014 }
2015 else
2016 goto label_invalid_code;
2017 /* We must update these variables now. */
2018 charset0 = CODING_SPEC_ISO_PLANE_CHARSET (coding, 0);
2019 charset1 = CODING_SPEC_ISO_PLANE_CHARSET (coding, 1);
2020 continue;
2021 }
2022 }
2023
2024 /* Now we know CHARSET and 1st position code C1 of a character.
2025 Produce a multibyte sequence for that character while getting
2026 2nd position code C2 if necessary. */
2027 if (CHARSET_DIMENSION (charset) == 2)
2028 {
2029 ONE_MORE_BYTE (c2);
2030 if (c1 < 0x80 ? c2 < 0x20 || c2 >= 0x80 : c2 < 0xA0)
2031 /* C2 is not in a valid range. */
2032 goto label_invalid_code;
2033 }
2034 c = DECODE_ISO_CHARACTER (charset, c1, c2);
2035 EMIT_CHAR (c);
2036 continue;
2037
2038 label_invalid_code:
2039 coding->errors++;
2040 if (COMPOSING_P (coding))
2041 DECODE_COMPOSITION_END ('1');
2042 src = src_base;
2043 c = *src++;
2044 EMIT_CHAR (c);
2045 }
2046
2047 label_end_of_loop:
2048 coding->consumed = coding->consumed_char = src_base - source;
2049 coding->produced = dst - destination;
2050 return;
2051 }
2052
2053
2054 /* ISO2022 encoding stuff. */
2055
2056 /*
2057 It is not enough to say just "ISO2022" on encoding, we have to
2058 specify more details. In Emacs, each ISO2022 coding system
2059 variant has the following specifications:
2060 1. Initial designation to G0 through G3.
2061 2. Allows short-form designation?
2062 3. ASCII should be designated to G0 before control characters?
2063 4. ASCII should be designated to G0 at end of line?
2064 5. 7-bit environment or 8-bit environment?
2065 6. Use locking-shift?
2066 7. Use Single-shift?
2067 And the following two are only for Japanese:
2068 8. Use ASCII in place of JIS0201-1976-Roman?
2069 9. Use JISX0208-1983 in place of JISX0208-1978?
2070 These specifications are encoded in `coding->flags' as flag bits
2071 defined by macros CODING_FLAG_ISO_XXX. See `coding.h' for more
2072 details.
2073 */
2074
2075 /* Produce codes (escape sequence) for designating CHARSET to graphic
2076 register REG at DST, and increment DST. If <final-char> of CHARSET is
2077 '@', 'A', or 'B' and the coding system CODING allows, produce
2078 designation sequence of short-form. */
2079
2080 #define ENCODE_DESIGNATION(charset, reg, coding) \
2081 do { \
2082 unsigned char final_char = CHARSET_ISO_FINAL_CHAR (charset); \
2083 char *intermediate_char_94 = "()*+"; \
2084 char *intermediate_char_96 = ",-./"; \
2085 int revision = CODING_SPEC_ISO_REVISION_NUMBER(coding, charset); \
2086 \
2087 if (revision < 255) \
2088 { \
2089 *dst++ = ISO_CODE_ESC; \
2090 *dst++ = '&'; \
2091 *dst++ = '@' + revision; \
2092 } \
2093 *dst++ = ISO_CODE_ESC; \
2094 if (CHARSET_DIMENSION (charset) == 1) \
2095 { \
2096 if (CHARSET_CHARS (charset) == 94) \
2097 *dst++ = (unsigned char) (intermediate_char_94[reg]); \
2098 else \
2099 *dst++ = (unsigned char) (intermediate_char_96[reg]); \
2100 } \
2101 else \
2102 { \
2103 *dst++ = '$'; \
2104 if (CHARSET_CHARS (charset) == 94) \
2105 { \
2106 if (! (coding->flags & CODING_FLAG_ISO_SHORT_FORM) \
2107 || reg != 0 \
2108 || final_char < '@' || final_char > 'B') \
2109 *dst++ = (unsigned char) (intermediate_char_94[reg]); \
2110 } \
2111 else \
2112 *dst++ = (unsigned char) (intermediate_char_96[reg]); \
2113 } \
2114 *dst++ = final_char; \
2115 CODING_SPEC_ISO_DESIGNATION (coding, reg) = charset; \
2116 } while (0)
2117
2118 /* The following two macros produce codes (control character or escape
2119 sequence) for ISO2022 single-shift functions (single-shift-2 and
2120 single-shift-3). */
2121
2122 #define ENCODE_SINGLE_SHIFT_2 \
2123 do { \
2124 if (coding->flags & CODING_FLAG_ISO_SEVEN_BITS) \
2125 *dst++ = ISO_CODE_ESC, *dst++ = 'N'; \
2126 else \
2127 *dst++ = ISO_CODE_SS2; \
2128 CODING_SPEC_ISO_SINGLE_SHIFTING (coding) = 1; \
2129 } while (0)
2130
2131 #define ENCODE_SINGLE_SHIFT_3 \
2132 do { \
2133 if (coding->flags & CODING_FLAG_ISO_SEVEN_BITS) \
2134 *dst++ = ISO_CODE_ESC, *dst++ = 'O'; \
2135 else \
2136 *dst++ = ISO_CODE_SS3; \
2137 CODING_SPEC_ISO_SINGLE_SHIFTING (coding) = 1; \
2138 } while (0)
2139
2140 /* The following four macros produce codes (control character or
2141 escape sequence) for ISO2022 locking-shift functions (shift-in,
2142 shift-out, locking-shift-2, and locking-shift-3). */
2143
2144 #define ENCODE_SHIFT_IN \
2145 do { \
2146 *dst++ = ISO_CODE_SI; \
2147 CODING_SPEC_ISO_INVOCATION (coding, 0) = 0; \
2148 } while (0)
2149
2150 #define ENCODE_SHIFT_OUT \
2151 do { \
2152 *dst++ = ISO_CODE_SO; \
2153 CODING_SPEC_ISO_INVOCATION (coding, 0) = 1; \
2154 } while (0)
2155
2156 #define ENCODE_LOCKING_SHIFT_2 \
2157 do { \
2158 *dst++ = ISO_CODE_ESC, *dst++ = 'n'; \
2159 CODING_SPEC_ISO_INVOCATION (coding, 0) = 2; \
2160 } while (0)
2161
2162 #define ENCODE_LOCKING_SHIFT_3 \
2163 do { \
2164 *dst++ = ISO_CODE_ESC, *dst++ = 'o'; \
2165 CODING_SPEC_ISO_INVOCATION (coding, 0) = 3; \
2166 } while (0)
2167
2168 /* Produce codes for a DIMENSION1 character whose character set is
2169 CHARSET and whose position-code is C1. Designation and invocation
2170 sequences are also produced in advance if necessary. */
2171
2172 #define ENCODE_ISO_CHARACTER_DIMENSION1(charset, c1) \
2173 do { \
2174 if (CODING_SPEC_ISO_SINGLE_SHIFTING (coding)) \
2175 { \
2176 if (coding->flags & CODING_FLAG_ISO_SEVEN_BITS) \
2177 *dst++ = c1 & 0x7F; \
2178 else \
2179 *dst++ = c1 | 0x80; \
2180 CODING_SPEC_ISO_SINGLE_SHIFTING (coding) = 0; \
2181 break; \
2182 } \
2183 else if (charset == CODING_SPEC_ISO_PLANE_CHARSET (coding, 0)) \
2184 { \
2185 *dst++ = c1 & 0x7F; \
2186 break; \
2187 } \
2188 else if (charset == CODING_SPEC_ISO_PLANE_CHARSET (coding, 1)) \
2189 { \
2190 *dst++ = c1 | 0x80; \
2191 break; \
2192 } \
2193 else \
2194 /* Since CHARSET is not yet invoked to any graphic planes, we \
2195 must invoke it, or, at first, designate it to some graphic \
2196 register. Then repeat the loop to actually produce the \
2197 character. */ \
2198 dst = encode_invocation_designation (charset, coding, dst); \
2199 } while (1)
2200
2201 /* Produce codes for a DIMENSION2 character whose character set is
2202 CHARSET and whose position-codes are C1 and C2. Designation and
2203 invocation codes are also produced in advance if necessary. */
2204
2205 #define ENCODE_ISO_CHARACTER_DIMENSION2(charset, c1, c2) \
2206 do { \
2207 if (CODING_SPEC_ISO_SINGLE_SHIFTING (coding)) \
2208 { \
2209 if (coding->flags & CODING_FLAG_ISO_SEVEN_BITS) \
2210 *dst++ = c1 & 0x7F, *dst++ = c2 & 0x7F; \
2211 else \
2212 *dst++ = c1 | 0x80, *dst++ = c2 | 0x80; \
2213 CODING_SPEC_ISO_SINGLE_SHIFTING (coding) = 0; \
2214 break; \
2215 } \
2216 else if (charset == CODING_SPEC_ISO_PLANE_CHARSET (coding, 0)) \
2217 { \
2218 *dst++ = c1 & 0x7F, *dst++= c2 & 0x7F; \
2219 break; \
2220 } \
2221 else if (charset == CODING_SPEC_ISO_PLANE_CHARSET (coding, 1)) \
2222 { \
2223 *dst++ = c1 | 0x80, *dst++= c2 | 0x80; \
2224 break; \
2225 } \
2226 else \
2227 /* Since CHARSET is not yet invoked to any graphic planes, we \
2228 must invoke it, or, at first, designate it to some graphic \
2229 register. Then repeat the loop to actually produce the \
2230 character. */ \
2231 dst = encode_invocation_designation (charset, coding, dst); \
2232 } while (1)
2233
2234 #define ENCODE_ISO_CHARACTER(c) \
2235 do { \
2236 int charset, c1, c2; \
2237 \
2238 SPLIT_CHAR (c, charset, c1, c2); \
2239 if (CHARSET_DEFINED_P (charset)) \
2240 { \
2241 if (CHARSET_DIMENSION (charset) == 1) \
2242 { \
2243 if (charset == CHARSET_ASCII \
2244 && coding->flags & CODING_FLAG_ISO_USE_ROMAN) \
2245 charset = charset_latin_jisx0201; \
2246 ENCODE_ISO_CHARACTER_DIMENSION1 (charset, c1); \
2247 } \
2248 else \
2249 { \
2250 if (charset == charset_jisx0208 \
2251 && coding->flags & CODING_FLAG_ISO_USE_OLDJIS) \
2252 charset = charset_jisx0208_1978; \
2253 ENCODE_ISO_CHARACTER_DIMENSION2 (charset, c1, c2); \
2254 } \
2255 } \
2256 else \
2257 { \
2258 *dst++ = c1; \
2259 if (c2 >= 0) \
2260 *dst++ = c2; \
2261 } \
2262 } while (0)
2263
2264
2265 /* Instead of encoding character C, produce one or two `?'s. */
2266
2267 #define ENCODE_UNSAFE_CHARACTER(c) \
2268 do { \
2269 ENCODE_ISO_CHARACTER (CODING_INHIBIT_CHARACTER_SUBSTITUTION); \
2270 if (CHARSET_WIDTH (CHAR_CHARSET (c)) > 1) \
2271 ENCODE_ISO_CHARACTER (CODING_INHIBIT_CHARACTER_SUBSTITUTION); \
2272 } while (0)
2273
2274
2275 /* Produce designation and invocation codes at a place pointed by DST
2276 to use CHARSET. The element `spec.iso2022' of *CODING is updated.
2277 Return new DST. */
2278
2279 unsigned char *
2280 encode_invocation_designation (charset, coding, dst)
2281 int charset;
2282 struct coding_system *coding;
2283 unsigned char *dst;
2284 {
2285 int reg; /* graphic register number */
2286
2287 /* At first, check designations. */
2288 for (reg = 0; reg < 4; reg++)
2289 if (charset == CODING_SPEC_ISO_DESIGNATION (coding, reg))
2290 break;
2291
2292 if (reg >= 4)
2293 {
2294 /* CHARSET is not yet designated to any graphic registers. */
2295 /* At first check the requested designation. */
2296 reg = CODING_SPEC_ISO_REQUESTED_DESIGNATION (coding, charset);
2297 if (reg == CODING_SPEC_ISO_NO_REQUESTED_DESIGNATION)
2298 /* Since CHARSET requests no special designation, designate it
2299 to graphic register 0. */
2300 reg = 0;
2301
2302 ENCODE_DESIGNATION (charset, reg, coding);
2303 }
2304
2305 if (CODING_SPEC_ISO_INVOCATION (coding, 0) != reg
2306 && CODING_SPEC_ISO_INVOCATION (coding, 1) != reg)
2307 {
2308 /* Since the graphic register REG is not invoked to any graphic
2309 planes, invoke it to graphic plane 0. */
2310 switch (reg)
2311 {
2312 case 0: /* graphic register 0 */
2313 ENCODE_SHIFT_IN;
2314 break;
2315
2316 case 1: /* graphic register 1 */
2317 ENCODE_SHIFT_OUT;
2318 break;
2319
2320 case 2: /* graphic register 2 */
2321 if (coding->flags & CODING_FLAG_ISO_SINGLE_SHIFT)
2322 ENCODE_SINGLE_SHIFT_2;
2323 else
2324 ENCODE_LOCKING_SHIFT_2;
2325 break;
2326
2327 case 3: /* graphic register 3 */
2328 if (coding->flags & CODING_FLAG_ISO_SINGLE_SHIFT)
2329 ENCODE_SINGLE_SHIFT_3;
2330 else
2331 ENCODE_LOCKING_SHIFT_3;
2332 break;
2333 }
2334 }
2335
2336 return dst;
2337 }
2338
2339 /* Produce 2-byte codes for encoded composition rule RULE. */
2340
2341 #define ENCODE_COMPOSITION_RULE(rule) \
2342 do { \
2343 int gref, nref; \
2344 COMPOSITION_DECODE_RULE (rule, gref, nref); \
2345 *dst++ = 32 + 81 + gref; \
2346 *dst++ = 32 + nref; \
2347 } while (0)
2348
2349 /* Produce codes for indicating the start of a composition sequence
2350 (ESC 0, ESC 3, or ESC 4). DATA points to an array of integers
2351 which specify information about the composition. See the comment
2352 in coding.h for the format of DATA. */
2353
2354 #define ENCODE_COMPOSITION_START(coding, data) \
2355 do { \
2356 coding->composing = data[3]; \
2357 *dst++ = ISO_CODE_ESC; \
2358 if (coding->composing == COMPOSITION_RELATIVE) \
2359 *dst++ = '0'; \
2360 else \
2361 { \
2362 *dst++ = (coding->composing == COMPOSITION_WITH_ALTCHARS \
2363 ? '3' : '4'); \
2364 coding->cmp_data_index = coding->cmp_data_start + 4; \
2365 coding->composition_rule_follows = 0; \
2366 } \
2367 } while (0)
2368
2369 /* Produce codes for indicating the end of the current composition. */
2370
2371 #define ENCODE_COMPOSITION_END(coding, data) \
2372 do { \
2373 *dst++ = ISO_CODE_ESC; \
2374 *dst++ = '1'; \
2375 coding->cmp_data_start += data[0]; \
2376 coding->composing = COMPOSITION_NO; \
2377 if (coding->cmp_data_start == coding->cmp_data->used \
2378 && coding->cmp_data->next) \
2379 { \
2380 coding->cmp_data = coding->cmp_data->next; \
2381 coding->cmp_data_start = 0; \
2382 } \
2383 } while (0)
2384
2385 /* Produce composition start sequence ESC 0. Here, this sequence
2386 doesn't mean the start of a new composition but means that we have
2387 just produced components (alternate chars and composition rules) of
2388 the composition and the actual text follows in SRC. */
2389
2390 #define ENCODE_COMPOSITION_FAKE_START(coding) \
2391 do { \
2392 *dst++ = ISO_CODE_ESC; \
2393 *dst++ = '0'; \
2394 coding->composing = COMPOSITION_RELATIVE; \
2395 } while (0)
2396
2397 /* The following three macros produce codes for indicating direction
2398 of text. */
2399 #define ENCODE_CONTROL_SEQUENCE_INTRODUCER \
2400 do { \
2401 if (coding->flags == CODING_FLAG_ISO_SEVEN_BITS) \
2402 *dst++ = ISO_CODE_ESC, *dst++ = '['; \
2403 else \
2404 *dst++ = ISO_CODE_CSI; \
2405 } while (0)
2406
2407 #define ENCODE_DIRECTION_R2L \
2408 ENCODE_CONTROL_SEQUENCE_INTRODUCER (dst), *dst++ = '2', *dst++ = ']'
2409
2410 #define ENCODE_DIRECTION_L2R \
2411 ENCODE_CONTROL_SEQUENCE_INTRODUCER (dst), *dst++ = '0', *dst++ = ']'
2412
2413 /* Produce codes for designation and invocation to reset the graphic
2414 planes and registers to initial state. */
2415 #define ENCODE_RESET_PLANE_AND_REGISTER \
2416 do { \
2417 int reg; \
2418 if (CODING_SPEC_ISO_INVOCATION (coding, 0) != 0) \
2419 ENCODE_SHIFT_IN; \
2420 for (reg = 0; reg < 4; reg++) \
2421 if (CODING_SPEC_ISO_INITIAL_DESIGNATION (coding, reg) >= 0 \
2422 && (CODING_SPEC_ISO_DESIGNATION (coding, reg) \
2423 != CODING_SPEC_ISO_INITIAL_DESIGNATION (coding, reg))) \
2424 ENCODE_DESIGNATION \
2425 (CODING_SPEC_ISO_INITIAL_DESIGNATION (coding, reg), reg, coding); \
2426 } while (0)
2427
2428 /* Produce designation sequences of charsets in the line started from
2429 SRC to a place pointed by DST, and return updated DST.
2430
2431 If the current block ends before any end-of-line, we may fail to
2432 find all the necessary designations. */
2433
2434 static unsigned char *
2435 encode_designation_at_bol (coding, translation_table, src, src_end, dst)
2436 struct coding_system *coding;
2437 Lisp_Object translation_table;
2438 unsigned char *src, *src_end, *dst;
2439 {
2440 int charset, c, found = 0, reg;
2441 /* Table of charsets to be designated to each graphic register. */
2442 int r[4];
2443
2444 for (reg = 0; reg < 4; reg++)
2445 r[reg] = -1;
2446
2447 while (found < 4)
2448 {
2449 ONE_MORE_CHAR (c);
2450 if (c == '\n')
2451 break;
2452
2453 charset = CHAR_CHARSET (c);
2454 reg = CODING_SPEC_ISO_REQUESTED_DESIGNATION (coding, charset);
2455 if (reg != CODING_SPEC_ISO_NO_REQUESTED_DESIGNATION && r[reg] < 0)
2456 {
2457 found++;
2458 r[reg] = charset;
2459 }
2460 }
2461
2462 label_end_of_loop:
2463 if (found)
2464 {
2465 for (reg = 0; reg < 4; reg++)
2466 if (r[reg] >= 0
2467 && CODING_SPEC_ISO_DESIGNATION (coding, reg) != r[reg])
2468 ENCODE_DESIGNATION (r[reg], reg, coding);
2469 }
2470
2471 return dst;
2472 }
2473
2474 /* See the above "GENERAL NOTES on `encode_coding_XXX ()' functions". */
2475
2476 static void
2477 encode_coding_iso2022 (coding, source, destination, src_bytes, dst_bytes)
2478 struct coding_system *coding;
2479 unsigned char *source, *destination;
2480 int src_bytes, dst_bytes;
2481 {
2482 unsigned char *src = source;
2483 unsigned char *src_end = source + src_bytes;
2484 unsigned char *dst = destination;
2485 unsigned char *dst_end = destination + dst_bytes;
2486 /* Since the maximum bytes produced by each loop is 20, we subtract 19
2487 from DST_END to assure overflow checking is necessary only at the
2488 head of loop. */
2489 unsigned char *adjusted_dst_end = dst_end - 19;
2490 /* SRC_BASE remembers the start position in source in each loop.
2491 The loop will be exited when there's not enough source text to
2492 analyze multi-byte codes (within macro ONE_MORE_CHAR), or when
2493 there's not enough destination area to produce encoded codes
2494 (within macro EMIT_BYTES). */
2495 unsigned char *src_base;
2496 int c;
2497 Lisp_Object translation_table;
2498 Lisp_Object safe_chars;
2499
2500 safe_chars = coding_safe_chars (coding);
2501
2502 if (NILP (Venable_character_translation))
2503 translation_table = Qnil;
2504 else
2505 {
2506 translation_table = coding->translation_table_for_encode;
2507 if (NILP (translation_table))
2508 translation_table = Vstandard_translation_table_for_encode;
2509 }
2510
2511 coding->consumed_char = 0;
2512 coding->errors = 0;
2513 while (1)
2514 {
2515 src_base = src;
2516
2517 if (dst >= (dst_bytes ? adjusted_dst_end : (src - 19)))
2518 {
2519 coding->result = CODING_FINISH_INSUFFICIENT_DST;
2520 break;
2521 }
2522
2523 if (coding->flags & CODING_FLAG_ISO_DESIGNATE_AT_BOL
2524 && CODING_SPEC_ISO_BOL (coding))
2525 {
2526 /* We have to produce designation sequences if any now. */
2527 dst = encode_designation_at_bol (coding, translation_table,
2528 src, src_end, dst);
2529 CODING_SPEC_ISO_BOL (coding) = 0;
2530 }
2531
2532 /* Check composition start and end. */
2533 if (coding->composing != COMPOSITION_DISABLED
2534 && coding->cmp_data_start < coding->cmp_data->used)
2535 {
2536 struct composition_data *cmp_data = coding->cmp_data;
2537 int *data = cmp_data->data + coding->cmp_data_start;
2538 int this_pos = cmp_data->char_offset + coding->consumed_char;
2539
2540 if (coding->composing == COMPOSITION_RELATIVE)
2541 {
2542 if (this_pos == data[2])
2543 {
2544 ENCODE_COMPOSITION_END (coding, data);
2545 cmp_data = coding->cmp_data;
2546 data = cmp_data->data + coding->cmp_data_start;
2547 }
2548 }
2549 else if (COMPOSING_P (coding))
2550 {
2551 /* COMPOSITION_WITH_ALTCHARS or COMPOSITION_WITH_RULE_ALTCHAR */
2552 if (coding->cmp_data_index == coding->cmp_data_start + data[0])
2553 /* We have consumed components of the composition.
2554 What follows in SRC is the composition's base
2555 text. */
2556 ENCODE_COMPOSITION_FAKE_START (coding);
2557 else
2558 {
2559 int c = cmp_data->data[coding->cmp_data_index++];
2560 if (coding->composition_rule_follows)
2561 {
2562 ENCODE_COMPOSITION_RULE (c);
2563 coding->composition_rule_follows = 0;
2564 }
2565 else
2566 {
2567 if (coding->flags & CODING_FLAG_ISO_SAFE
2568 && ! CODING_SAFE_CHAR_P (safe_chars, c))
2569 ENCODE_UNSAFE_CHARACTER (c);
2570 else
2571 ENCODE_ISO_CHARACTER (c);
2572 if (coding->composing == COMPOSITION_WITH_RULE_ALTCHARS)
2573 coding->composition_rule_follows = 1;
2574 }
2575 continue;
2576 }
2577 }
2578 if (!COMPOSING_P (coding))
2579 {
2580 if (this_pos == data[1])
2581 {
2582 ENCODE_COMPOSITION_START (coding, data);
2583 continue;
2584 }
2585 }
2586 }
2587
2588 ONE_MORE_CHAR (c);
2589
2590 /* Now encode the character C. */
2591 if (c < 0x20 || c == 0x7F)
2592 {
2593 if (c == '\r')
2594 {
2595 if (! (coding->mode & CODING_MODE_SELECTIVE_DISPLAY))
2596 {
2597 if (coding->flags & CODING_FLAG_ISO_RESET_AT_CNTL)
2598 ENCODE_RESET_PLANE_AND_REGISTER;
2599 *dst++ = c;
2600 continue;
2601 }
2602 /* fall down to treat '\r' as '\n' ... */
2603 c = '\n';
2604 }
2605 if (c == '\n')
2606 {
2607 if (coding->flags & CODING_FLAG_ISO_RESET_AT_EOL)
2608 ENCODE_RESET_PLANE_AND_REGISTER;
2609 if (coding->flags & CODING_FLAG_ISO_INIT_AT_BOL)
2610 bcopy (coding->spec.iso2022.initial_designation,
2611 coding->spec.iso2022.current_designation,
2612 sizeof coding->spec.iso2022.initial_designation);
2613 if (coding->eol_type == CODING_EOL_LF
2614 || coding->eol_type == CODING_EOL_UNDECIDED)
2615 *dst++ = ISO_CODE_LF;
2616 else if (coding->eol_type == CODING_EOL_CRLF)
2617 *dst++ = ISO_CODE_CR, *dst++ = ISO_CODE_LF;
2618 else
2619 *dst++ = ISO_CODE_CR;
2620 CODING_SPEC_ISO_BOL (coding) = 1;
2621 }
2622 else
2623 {
2624 if (coding->flags & CODING_FLAG_ISO_RESET_AT_CNTL)
2625 ENCODE_RESET_PLANE_AND_REGISTER;
2626 *dst++ = c;
2627 }
2628 }
2629 else if (ASCII_BYTE_P (c))
2630 ENCODE_ISO_CHARACTER (c);
2631 else if (SINGLE_BYTE_CHAR_P (c))
2632 {
2633 *dst++ = c;
2634 coding->errors++;
2635 }
2636 else if (coding->flags & CODING_FLAG_ISO_SAFE
2637 && ! CODING_SAFE_CHAR_P (safe_chars, c))
2638 ENCODE_UNSAFE_CHARACTER (c);
2639 else
2640 ENCODE_ISO_CHARACTER (c);
2641
2642 coding->consumed_char++;
2643 }
2644
2645 label_end_of_loop:
2646 coding->consumed = src_base - source;
2647 coding->produced = coding->produced_char = dst - destination;
2648 }
2649
2650 \f
2651 /*** 4. SJIS and BIG5 handlers ***/
2652
2653 /* Although SJIS and BIG5 are not ISO coding systems, they are used
2654 quite widely. So, for the moment, Emacs supports them in the bare
2655 C code. But, in the future, they may be supported only by CCL. */
2656
2657 /* SJIS is a coding system encoding three character sets: ASCII, right
2658 half of JISX0201-Kana, and JISX0208. An ASCII character is encoded
2659 as is. A character of charset katakana-jisx0201 is encoded by
2660 "position-code + 0x80". A character of charset japanese-jisx0208
2661 is encoded in 2-byte but two position-codes are divided and shifted
2662 so that it fits in the range below.
2663
2664 --- CODE RANGE of SJIS ---
2665 (character set) (range)
2666 ASCII 0x00 .. 0x7F
2667 KATAKANA-JISX0201 0xA1 .. 0xDF
2668 JISX0208 (1st byte) 0x81 .. 0x9F and 0xE0 .. 0xEF
2669 (2nd byte) 0x40 .. 0x7E and 0x80 .. 0xFC
2670 -------------------------------
2671
2672 */
2673
2674 /* BIG5 is a coding system encoding two character sets: ASCII and
2675 Big5. An ASCII character is encoded as is. Big5 is a two-byte
2676 character set and is encoded in two bytes.
2677
2678 --- CODE RANGE of BIG5 ---
2679 (character set) (range)
2680 ASCII 0x00 .. 0x7F
2681 Big5 (1st byte) 0xA1 .. 0xFE
2682 (2nd byte) 0x40 .. 0x7E and 0xA1 .. 0xFE
2683 --------------------------
2684
2685 Since the number of characters in Big5 is larger than maximum
2686 characters in Emacs' charset (96x96), it can't be handled as one
2687 charset. So, in Emacs, Big5 is divided into two: `charset-big5-1'
2688 and `charset-big5-2'. Both are DIMENSION2 and CHARS94. The former
2689 contains frequently used characters and the latter contains less
2690 frequently used characters. */
2691
2692 /* Macros to decode or encode a character of Big5 in BIG5. B1 and B2
2693 are the 1st and 2nd position-codes of Big5 in BIG5 coding system.
2694 C1 and C2 are the 1st and 2nd position-codes of Emacs' internal
2695 format. CHARSET is `charset_big5_1' or `charset_big5_2'. */
2696
2697 /* Number of Big5 characters which have the same code in 1st byte. */
2698 #define BIG5_SAME_ROW (0xFF - 0xA1 + 0x7F - 0x40)
2699
2700 #define DECODE_BIG5(b1, b2, charset, c1, c2) \
2701 do { \
2702 unsigned int temp \
2703 = (b1 - 0xA1) * BIG5_SAME_ROW + b2 - (b2 < 0x7F ? 0x40 : 0x62); \
2704 if (b1 < 0xC9) \
2705 charset = charset_big5_1; \
2706 else \
2707 { \
2708 charset = charset_big5_2; \
2709 temp -= (0xC9 - 0xA1) * BIG5_SAME_ROW; \
2710 } \
2711 c1 = temp / (0xFF - 0xA1) + 0x21; \
2712 c2 = temp % (0xFF - 0xA1) + 0x21; \
2713 } while (0)
2714
2715 #define ENCODE_BIG5(charset, c1, c2, b1, b2) \
2716 do { \
2717 unsigned int temp = (c1 - 0x21) * (0xFF - 0xA1) + (c2 - 0x21); \
2718 if (charset == charset_big5_2) \
2719 temp += BIG5_SAME_ROW * (0xC9 - 0xA1); \
2720 b1 = temp / BIG5_SAME_ROW + 0xA1; \
2721 b2 = temp % BIG5_SAME_ROW; \
2722 b2 += b2 < 0x3F ? 0x40 : 0x62; \
2723 } while (0)
2724
2725 /* See the above "GENERAL NOTES on `detect_coding_XXX ()' functions".
2726 Check if a text is encoded in SJIS. If it is, return
2727 CODING_CATEGORY_MASK_SJIS, else return 0. */
2728
2729 static int
2730 detect_coding_sjis (src, src_end, multibytep)
2731 unsigned char *src, *src_end;
2732 int multibytep;
2733 {
2734 int c;
2735 /* Dummy for ONE_MORE_BYTE. */
2736 struct coding_system dummy_coding;
2737 struct coding_system *coding = &dummy_coding;
2738
2739 while (1)
2740 {
2741 ONE_MORE_BYTE_CHECK_MULTIBYTE (c, multibytep);
2742 if (c < 0x80)
2743 continue;
2744 if (c == 0x80 || c == 0xA0 || c > 0xEF)
2745 return 0;
2746 if (c <= 0x9F || c >= 0xE0)
2747 {
2748 ONE_MORE_BYTE_CHECK_MULTIBYTE (c, multibytep);
2749 if (c < 0x40 || c == 0x7F || c > 0xFC)
2750 return 0;
2751 }
2752 }
2753 label_end_of_loop:
2754 return CODING_CATEGORY_MASK_SJIS;
2755 }
2756
2757 /* See the above "GENERAL NOTES on `detect_coding_XXX ()' functions".
2758 Check if a text is encoded in BIG5. If it is, return
2759 CODING_CATEGORY_MASK_BIG5, else return 0. */
2760
2761 static int
2762 detect_coding_big5 (src, src_end, multibytep)
2763 unsigned char *src, *src_end;
2764 int multibytep;
2765 {
2766 int c;
2767 /* Dummy for ONE_MORE_BYTE. */
2768 struct coding_system dummy_coding;
2769 struct coding_system *coding = &dummy_coding;
2770
2771 while (1)
2772 {
2773 ONE_MORE_BYTE_CHECK_MULTIBYTE (c, multibytep);
2774 if (c < 0x80)
2775 continue;
2776 if (c < 0xA1 || c > 0xFE)
2777 return 0;
2778 ONE_MORE_BYTE_CHECK_MULTIBYTE (c, multibytep);
2779 if (c < 0x40 || (c > 0x7F && c < 0xA1) || c > 0xFE)
2780 return 0;
2781 }
2782 label_end_of_loop:
2783 return CODING_CATEGORY_MASK_BIG5;
2784 }
2785
2786 /* See the above "GENERAL NOTES on `detect_coding_XXX ()' functions".
2787 Check if a text is encoded in UTF-8. If it is, return
2788 CODING_CATEGORY_MASK_UTF_8, else return 0. */
2789
2790 #define UTF_8_1_OCTET_P(c) ((c) < 0x80)
2791 #define UTF_8_EXTRA_OCTET_P(c) (((c) & 0xC0) == 0x80)
2792 #define UTF_8_2_OCTET_LEADING_P(c) (((c) & 0xE0) == 0xC0)
2793 #define UTF_8_3_OCTET_LEADING_P(c) (((c) & 0xF0) == 0xE0)
2794 #define UTF_8_4_OCTET_LEADING_P(c) (((c) & 0xF8) == 0xF0)
2795 #define UTF_8_5_OCTET_LEADING_P(c) (((c) & 0xFC) == 0xF8)
2796 #define UTF_8_6_OCTET_LEADING_P(c) (((c) & 0xFE) == 0xFC)
2797
2798 static int
2799 detect_coding_utf_8 (src, src_end, multibytep)
2800 unsigned char *src, *src_end;
2801 int multibytep;
2802 {
2803 unsigned char c;
2804 int seq_maybe_bytes;
2805 /* Dummy for ONE_MORE_BYTE. */
2806 struct coding_system dummy_coding;
2807 struct coding_system *coding = &dummy_coding;
2808
2809 while (1)
2810 {
2811 ONE_MORE_BYTE_CHECK_MULTIBYTE (c, multibytep);
2812 if (UTF_8_1_OCTET_P (c))
2813 continue;
2814 else if (UTF_8_2_OCTET_LEADING_P (c))
2815 seq_maybe_bytes = 1;
2816 else if (UTF_8_3_OCTET_LEADING_P (c))
2817 seq_maybe_bytes = 2;
2818 else if (UTF_8_4_OCTET_LEADING_P (c))
2819 seq_maybe_bytes = 3;
2820 else if (UTF_8_5_OCTET_LEADING_P (c))
2821 seq_maybe_bytes = 4;
2822 else if (UTF_8_6_OCTET_LEADING_P (c))
2823 seq_maybe_bytes = 5;
2824 else
2825 return 0;
2826
2827 do
2828 {
2829 ONE_MORE_BYTE_CHECK_MULTIBYTE (c, multibytep);
2830 if (!UTF_8_EXTRA_OCTET_P (c))
2831 return 0;
2832 seq_maybe_bytes--;
2833 }
2834 while (seq_maybe_bytes > 0);
2835 }
2836
2837 label_end_of_loop:
2838 return CODING_CATEGORY_MASK_UTF_8;
2839 }
2840
2841 /* See the above "GENERAL NOTES on `detect_coding_XXX ()' functions".
2842 Check if a text is encoded in UTF-16 Big Endian (endian == 1) or
2843 Little Endian (otherwise). If it is, return
2844 CODING_CATEGORY_MASK_UTF_16_BE or CODING_CATEGORY_MASK_UTF_16_LE,
2845 else return 0. */
2846
2847 #define UTF_16_INVALID_P(val) \
2848 (((val) == 0xFFFE) \
2849 || ((val) == 0xFFFF))
2850
2851 #define UTF_16_HIGH_SURROGATE_P(val) \
2852 (((val) & 0xD800) == 0xD800)
2853
2854 #define UTF_16_LOW_SURROGATE_P(val) \
2855 (((val) & 0xDC00) == 0xDC00)
2856
2857 static int
2858 detect_coding_utf_16 (src, src_end, multibytep)
2859 unsigned char *src, *src_end;
2860 int multibytep;
2861 {
2862 unsigned char c1, c2;
2863 /* Dummy for TWO_MORE_BYTES. */
2864 struct coding_system dummy_coding;
2865 struct coding_system *coding = &dummy_coding;
2866
2867 ONE_MORE_BYTE_CHECK_MULTIBYTE (c1, multibytep);
2868 ONE_MORE_BYTE_CHECK_MULTIBYTE (c2, multibytep);
2869
2870 if ((c1 == 0xFF) && (c2 == 0xFE))
2871 return CODING_CATEGORY_MASK_UTF_16_LE;
2872 else if ((c1 == 0xFE) && (c2 == 0xFF))
2873 return CODING_CATEGORY_MASK_UTF_16_BE;
2874
2875 label_end_of_loop:
2876 return 0;
2877 }
2878
2879 /* See the above "GENERAL NOTES on `decode_coding_XXX ()' functions".
2880 If SJIS_P is 1, decode SJIS text, else decode BIG5 test. */
2881
2882 static void
2883 decode_coding_sjis_big5 (coding, source, destination,
2884 src_bytes, dst_bytes, sjis_p)
2885 struct coding_system *coding;
2886 unsigned char *source, *destination;
2887 int src_bytes, dst_bytes;
2888 int sjis_p;
2889 {
2890 unsigned char *src = source;
2891 unsigned char *src_end = source + src_bytes;
2892 unsigned char *dst = destination;
2893 unsigned char *dst_end = destination + dst_bytes;
2894 /* SRC_BASE remembers the start position in source in each loop.
2895 The loop will be exited when there's not enough source code
2896 (within macro ONE_MORE_BYTE), or when there's not enough
2897 destination area to produce a character (within macro
2898 EMIT_CHAR). */
2899 unsigned char *src_base;
2900 Lisp_Object translation_table;
2901
2902 if (NILP (Venable_character_translation))
2903 translation_table = Qnil;
2904 else
2905 {
2906 translation_table = coding->translation_table_for_decode;
2907 if (NILP (translation_table))
2908 translation_table = Vstandard_translation_table_for_decode;
2909 }
2910
2911 coding->produced_char = 0;
2912 while (1)
2913 {
2914 int c, charset, c1, c2;
2915
2916 src_base = src;
2917 ONE_MORE_BYTE (c1);
2918
2919 if (c1 < 0x80)
2920 {
2921 charset = CHARSET_ASCII;
2922 if (c1 < 0x20)
2923 {
2924 if (c1 == '\r')
2925 {
2926 if (coding->eol_type == CODING_EOL_CRLF)
2927 {
2928 ONE_MORE_BYTE (c2);
2929 if (c2 == '\n')
2930 c1 = c2;
2931 else if (coding->mode
2932 & CODING_MODE_INHIBIT_INCONSISTENT_EOL)
2933 {
2934 coding->result = CODING_FINISH_INCONSISTENT_EOL;
2935 goto label_end_of_loop;
2936 }
2937 else
2938 /* To process C2 again, SRC is subtracted by 1. */
2939 src--;
2940 }
2941 else if (coding->eol_type == CODING_EOL_CR)
2942 c1 = '\n';
2943 }
2944 else if (c1 == '\n'
2945 && (coding->mode & CODING_MODE_INHIBIT_INCONSISTENT_EOL)
2946 && (coding->eol_type == CODING_EOL_CR
2947 || coding->eol_type == CODING_EOL_CRLF))
2948 {
2949 coding->result = CODING_FINISH_INCONSISTENT_EOL;
2950 goto label_end_of_loop;
2951 }
2952 }
2953 }
2954 else
2955 {
2956 if (sjis_p)
2957 {
2958 if (c1 == 0x80 || c1 == 0xA0 || c1 > 0xEF)
2959 goto label_invalid_code;
2960 if (c1 <= 0x9F || c1 >= 0xE0)
2961 {
2962 /* SJIS -> JISX0208 */
2963 ONE_MORE_BYTE (c2);
2964 if (c2 < 0x40 || c2 == 0x7F || c2 > 0xFC)
2965 goto label_invalid_code;
2966 DECODE_SJIS (c1, c2, c1, c2);
2967 charset = charset_jisx0208;
2968 }
2969 else
2970 /* SJIS -> JISX0201-Kana */
2971 charset = charset_katakana_jisx0201;
2972 }
2973 else
2974 {
2975 /* BIG5 -> Big5 */
2976 if (c1 < 0xA0 || c1 > 0xFE)
2977 goto label_invalid_code;
2978 ONE_MORE_BYTE (c2);
2979 if (c2 < 0x40 || (c2 > 0x7E && c2 < 0xA1) || c2 > 0xFE)
2980 goto label_invalid_code;
2981 DECODE_BIG5 (c1, c2, charset, c1, c2);
2982 }
2983 }
2984
2985 c = DECODE_ISO_CHARACTER (charset, c1, c2);
2986 EMIT_CHAR (c);
2987 continue;
2988
2989 label_invalid_code:
2990 coding->errors++;
2991 src = src_base;
2992 c = *src++;
2993 EMIT_CHAR (c);
2994 }
2995
2996 label_end_of_loop:
2997 coding->consumed = coding->consumed_char = src_base - source;
2998 coding->produced = dst - destination;
2999 return;
3000 }
3001
3002 /* See the above "GENERAL NOTES on `encode_coding_XXX ()' functions".
3003 This function can encode charsets `ascii', `katakana-jisx0201',
3004 `japanese-jisx0208', `chinese-big5-1', and `chinese-big5-2'. We
3005 are sure that all these charsets are registered as official charset
3006 (i.e. do not have extended leading-codes). Characters of other
3007 charsets are produced without any encoding. If SJIS_P is 1, encode
3008 SJIS text, else encode BIG5 text. */
3009
3010 static void
3011 encode_coding_sjis_big5 (coding, source, destination,
3012 src_bytes, dst_bytes, sjis_p)
3013 struct coding_system *coding;
3014 unsigned char *source, *destination;
3015 int src_bytes, dst_bytes;
3016 int sjis_p;
3017 {
3018 unsigned char *src = source;
3019 unsigned char *src_end = source + src_bytes;
3020 unsigned char *dst = destination;
3021 unsigned char *dst_end = destination + dst_bytes;
3022 /* SRC_BASE remembers the start position in source in each loop.
3023 The loop will be exited when there's not enough source text to
3024 analyze multi-byte codes (within macro ONE_MORE_CHAR), or when
3025 there's not enough destination area to produce encoded codes
3026 (within macro EMIT_BYTES). */
3027 unsigned char *src_base;
3028 Lisp_Object translation_table;
3029
3030 if (NILP (Venable_character_translation))
3031 translation_table = Qnil;
3032 else
3033 {
3034 translation_table = coding->translation_table_for_encode;
3035 if (NILP (translation_table))
3036 translation_table = Vstandard_translation_table_for_encode;
3037 }
3038
3039 while (1)
3040 {
3041 int c, charset, c1, c2;
3042
3043 src_base = src;
3044 ONE_MORE_CHAR (c);
3045
3046 /* Now encode the character C. */
3047 if (SINGLE_BYTE_CHAR_P (c))
3048 {
3049 switch (c)
3050 {
3051 case '\r':
3052 if (!(coding->mode & CODING_MODE_SELECTIVE_DISPLAY))
3053 {
3054 EMIT_ONE_BYTE (c);
3055 break;
3056 }
3057 c = '\n';
3058 case '\n':
3059 if (coding->eol_type == CODING_EOL_CRLF)
3060 {
3061 EMIT_TWO_BYTES ('\r', c);
3062 break;
3063 }
3064 else if (coding->eol_type == CODING_EOL_CR)
3065 c = '\r';
3066 default:
3067 EMIT_ONE_BYTE (c);
3068 }
3069 }
3070 else
3071 {
3072 SPLIT_CHAR (c, charset, c1, c2);
3073 if (sjis_p)
3074 {
3075 if (charset == charset_jisx0208
3076 || charset == charset_jisx0208_1978)
3077 {
3078 ENCODE_SJIS (c1, c2, c1, c2);
3079 EMIT_TWO_BYTES (c1, c2);
3080 }
3081 else if (charset == charset_katakana_jisx0201)
3082 EMIT_ONE_BYTE (c1 | 0x80);
3083 else if (charset == charset_latin_jisx0201)
3084 EMIT_ONE_BYTE (c1);
3085 else
3086 /* There's no way other than producing the internal
3087 codes as is. */
3088 EMIT_BYTES (src_base, src);
3089 }
3090 else
3091 {
3092 if (charset == charset_big5_1 || charset == charset_big5_2)
3093 {
3094 ENCODE_BIG5 (charset, c1, c2, c1, c2);
3095 EMIT_TWO_BYTES (c1, c2);
3096 }
3097 else
3098 /* There's no way other than producing the internal
3099 codes as is. */
3100 EMIT_BYTES (src_base, src);
3101 }
3102 }
3103 coding->consumed_char++;
3104 }
3105
3106 label_end_of_loop:
3107 coding->consumed = src_base - source;
3108 coding->produced = coding->produced_char = dst - destination;
3109 }
3110
3111 \f
3112 /*** 5. CCL handlers ***/
3113
3114 /* See the above "GENERAL NOTES on `detect_coding_XXX ()' functions".
3115 Check if a text is encoded in a coding system of which
3116 encoder/decoder are written in CCL program. If it is, return
3117 CODING_CATEGORY_MASK_CCL, else return 0. */
3118
3119 static int
3120 detect_coding_ccl (src, src_end, multibytep)
3121 unsigned char *src, *src_end;
3122 int multibytep;
3123 {
3124 unsigned char *valid;
3125 int c;
3126 /* Dummy for ONE_MORE_BYTE. */
3127 struct coding_system dummy_coding;
3128 struct coding_system *coding = &dummy_coding;
3129
3130 /* No coding system is assigned to coding-category-ccl. */
3131 if (!coding_system_table[CODING_CATEGORY_IDX_CCL])
3132 return 0;
3133
3134 valid = coding_system_table[CODING_CATEGORY_IDX_CCL]->spec.ccl.valid_codes;
3135 while (1)
3136 {
3137 ONE_MORE_BYTE_CHECK_MULTIBYTE (c, multibytep);
3138 if (! valid[c])
3139 return 0;
3140 }
3141 label_end_of_loop:
3142 return CODING_CATEGORY_MASK_CCL;
3143 }
3144
3145 \f
3146 /*** 6. End-of-line handlers ***/
3147
3148 /* See the above "GENERAL NOTES on `decode_coding_XXX ()' functions". */
3149
3150 static void
3151 decode_eol (coding, source, destination, src_bytes, dst_bytes)
3152 struct coding_system *coding;
3153 unsigned char *source, *destination;
3154 int src_bytes, dst_bytes;
3155 {
3156 unsigned char *src = source;
3157 unsigned char *dst = destination;
3158 unsigned char *src_end = src + src_bytes;
3159 unsigned char *dst_end = dst + dst_bytes;
3160 Lisp_Object translation_table;
3161 /* SRC_BASE remembers the start position in source in each loop.
3162 The loop will be exited when there's not enough source code
3163 (within macro ONE_MORE_BYTE), or when there's not enough
3164 destination area to produce a character (within macro
3165 EMIT_CHAR). */
3166 unsigned char *src_base;
3167 int c;
3168
3169 translation_table = Qnil;
3170 switch (coding->eol_type)
3171 {
3172 case CODING_EOL_CRLF:
3173 while (1)
3174 {
3175 src_base = src;
3176 ONE_MORE_BYTE (c);
3177 if (c == '\r')
3178 {
3179 ONE_MORE_BYTE (c);
3180 if (c != '\n')
3181 {
3182 if (coding->mode & CODING_MODE_INHIBIT_INCONSISTENT_EOL)
3183 {
3184 coding->result = CODING_FINISH_INCONSISTENT_EOL;
3185 goto label_end_of_loop;
3186 }
3187 src--;
3188 c = '\r';
3189 }
3190 }
3191 else if (c == '\n'
3192 && (coding->mode & CODING_MODE_INHIBIT_INCONSISTENT_EOL))
3193 {
3194 coding->result = CODING_FINISH_INCONSISTENT_EOL;
3195 goto label_end_of_loop;
3196 }
3197 EMIT_CHAR (c);
3198 }
3199 break;
3200
3201 case CODING_EOL_CR:
3202 while (1)
3203 {
3204 src_base = src;
3205 ONE_MORE_BYTE (c);
3206 if (c == '\n')
3207 {
3208 if (coding->mode & CODING_MODE_INHIBIT_INCONSISTENT_EOL)
3209 {
3210 coding->result = CODING_FINISH_INCONSISTENT_EOL;
3211 goto label_end_of_loop;
3212 }
3213 }
3214 else if (c == '\r')
3215 c = '\n';
3216 EMIT_CHAR (c);
3217 }
3218 break;
3219
3220 default: /* no need for EOL handling */
3221 while (1)
3222 {
3223 src_base = src;
3224 ONE_MORE_BYTE (c);
3225 EMIT_CHAR (c);
3226 }
3227 }
3228
3229 label_end_of_loop:
3230 coding->consumed = coding->consumed_char = src_base - source;
3231 coding->produced = dst - destination;
3232 return;
3233 }
3234
3235 /* See "GENERAL NOTES about `encode_coding_XXX ()' functions". Encode
3236 format of end-of-line according to `coding->eol_type'. It also
3237 convert multibyte form 8-bit characters to unibyte if
3238 CODING->src_multibyte is nonzero. If `coding->mode &
3239 CODING_MODE_SELECTIVE_DISPLAY' is nonzero, code '\r' in source text
3240 also means end-of-line. */
3241
3242 static void
3243 encode_eol (coding, source, destination, src_bytes, dst_bytes)
3244 struct coding_system *coding;
3245 const unsigned char *source;
3246 unsigned char *destination;
3247 int src_bytes, dst_bytes;
3248 {
3249 const unsigned char *src = source;
3250 unsigned char *dst = destination;
3251 const unsigned char *src_end = src + src_bytes;
3252 unsigned char *dst_end = dst + dst_bytes;
3253 Lisp_Object translation_table;
3254 /* SRC_BASE remembers the start position in source in each loop.
3255 The loop will be exited when there's not enough source text to
3256 analyze multi-byte codes (within macro ONE_MORE_CHAR), or when
3257 there's not enough destination area to produce encoded codes
3258 (within macro EMIT_BYTES). */
3259 const unsigned char *src_base;
3260 unsigned char *tmp;
3261 int c;
3262 int selective_display = coding->mode & CODING_MODE_SELECTIVE_DISPLAY;
3263
3264 translation_table = Qnil;
3265 if (coding->src_multibyte
3266 && *(src_end - 1) == LEADING_CODE_8_BIT_CONTROL)
3267 {
3268 src_end--;
3269 src_bytes--;
3270 coding->result = CODING_FINISH_INSUFFICIENT_SRC;
3271 }
3272
3273 if (coding->eol_type == CODING_EOL_CRLF)
3274 {
3275 while (src < src_end)
3276 {
3277 src_base = src;
3278 c = *src++;
3279 if (c >= 0x20)
3280 EMIT_ONE_BYTE (c);
3281 else if (c == '\n' || (c == '\r' && selective_display))
3282 EMIT_TWO_BYTES ('\r', '\n');
3283 else
3284 EMIT_ONE_BYTE (c);
3285 }
3286 src_base = src;
3287 label_end_of_loop:
3288 ;
3289 }
3290 else
3291 {
3292 if (!dst_bytes || src_bytes <= dst_bytes)
3293 {
3294 safe_bcopy (src, dst, src_bytes);
3295 src_base = src_end;
3296 dst += src_bytes;
3297 }
3298 else
3299 {
3300 if (coding->src_multibyte
3301 && *(src + dst_bytes - 1) == LEADING_CODE_8_BIT_CONTROL)
3302 dst_bytes--;
3303 safe_bcopy (src, dst, dst_bytes);
3304 src_base = src + dst_bytes;
3305 dst = destination + dst_bytes;
3306 coding->result = CODING_FINISH_INSUFFICIENT_DST;
3307 }
3308 if (coding->eol_type == CODING_EOL_CR)
3309 {
3310 for (tmp = destination; tmp < dst; tmp++)
3311 if (*tmp == '\n') *tmp = '\r';
3312 }
3313 else if (selective_display)
3314 {
3315 for (tmp = destination; tmp < dst; tmp++)
3316 if (*tmp == '\r') *tmp = '\n';
3317 }
3318 }
3319 if (coding->src_multibyte)
3320 dst = destination + str_as_unibyte (destination, dst - destination);
3321
3322 coding->consumed = src_base - source;
3323 coding->produced = dst - destination;
3324 coding->produced_char = coding->produced;
3325 }
3326
3327 \f
3328 /*** 7. C library functions ***/
3329
3330 /* In Emacs Lisp, a coding system is represented by a Lisp symbol which
3331 has a property `coding-system'. The value of this property is a
3332 vector of length 5 (called the coding-vector). Among elements of
3333 this vector, the first (element[0]) and the fifth (element[4])
3334 carry important information for decoding/encoding. Before
3335 decoding/encoding, this information should be set in fields of a
3336 structure of type `coding_system'.
3337
3338 The value of the property `coding-system' can be a symbol of another
3339 subsidiary coding-system. In that case, Emacs gets coding-vector
3340 from that symbol.
3341
3342 `element[0]' contains information to be set in `coding->type'. The
3343 value and its meaning is as follows:
3344
3345 0 -- coding_type_emacs_mule
3346 1 -- coding_type_sjis
3347 2 -- coding_type_iso2022
3348 3 -- coding_type_big5
3349 4 -- coding_type_ccl encoder/decoder written in CCL
3350 nil -- coding_type_no_conversion
3351 t -- coding_type_undecided (automatic conversion on decoding,
3352 no-conversion on encoding)
3353
3354 `element[4]' contains information to be set in `coding->flags' and
3355 `coding->spec'. The meaning varies by `coding->type'.
3356
3357 If `coding->type' is `coding_type_iso2022', element[4] is a vector
3358 of length 32 (of which the first 13 sub-elements are used now).
3359 Meanings of these sub-elements are:
3360
3361 sub-element[N] where N is 0 through 3: to be set in `coding->spec.iso2022'
3362 If the value is an integer of valid charset, the charset is
3363 assumed to be designated to graphic register N initially.
3364
3365 If the value is minus, it is a minus value of charset which
3366 reserves graphic register N, which means that the charset is
3367 not designated initially but should be designated to graphic
3368 register N just before encoding a character in that charset.
3369
3370 If the value is nil, graphic register N is never used on
3371 encoding.
3372
3373 sub-element[N] where N is 4 through 11: to be set in `coding->flags'
3374 Each value takes t or nil. See the section ISO2022 of
3375 `coding.h' for more information.
3376
3377 If `coding->type' is `coding_type_big5', element[4] is t to denote
3378 BIG5-ETen or nil to denote BIG5-HKU.
3379
3380 If `coding->type' takes the other value, element[4] is ignored.
3381
3382 Emacs Lisp's coding systems also carry information about format of
3383 end-of-line in a value of property `eol-type'. If the value is
3384 integer, 0 means CODING_EOL_LF, 1 means CODING_EOL_CRLF, and 2
3385 means CODING_EOL_CR. If it is not integer, it should be a vector
3386 of subsidiary coding systems of which property `eol-type' has one
3387 of the above values.
3388
3389 */
3390
3391 /* Extract information for decoding/encoding from CODING_SYSTEM_SYMBOL
3392 and set it in CODING. If CODING_SYSTEM_SYMBOL is invalid, CODING
3393 is setup so that no conversion is necessary and return -1, else
3394 return 0. */
3395
3396 int
3397 setup_coding_system (coding_system, coding)
3398 Lisp_Object coding_system;
3399 struct coding_system *coding;
3400 {
3401 Lisp_Object coding_spec, coding_type, eol_type, plist;
3402 Lisp_Object val;
3403
3404 /* At first, zero clear all members. */
3405 bzero (coding, sizeof (struct coding_system));
3406
3407 /* Initialize some fields required for all kinds of coding systems. */
3408 coding->symbol = coding_system;
3409 coding->heading_ascii = -1;
3410 coding->post_read_conversion = coding->pre_write_conversion = Qnil;
3411 coding->composing = COMPOSITION_DISABLED;
3412 coding->cmp_data = NULL;
3413
3414 if (NILP (coding_system))
3415 goto label_invalid_coding_system;
3416
3417 coding_spec = Fget (coding_system, Qcoding_system);
3418
3419 if (!VECTORP (coding_spec)
3420 || XVECTOR (coding_spec)->size != 5
3421 || !CONSP (XVECTOR (coding_spec)->contents[3]))
3422 goto label_invalid_coding_system;
3423
3424 eol_type = inhibit_eol_conversion ? Qnil : Fget (coding_system, Qeol_type);
3425 if (VECTORP (eol_type))
3426 {
3427 coding->eol_type = CODING_EOL_UNDECIDED;
3428 coding->common_flags = CODING_REQUIRE_DETECTION_MASK;
3429 }
3430 else if (XFASTINT (eol_type) == 1)
3431 {
3432 coding->eol_type = CODING_EOL_CRLF;
3433 coding->common_flags
3434 = CODING_REQUIRE_DECODING_MASK | CODING_REQUIRE_ENCODING_MASK;
3435 }
3436 else if (XFASTINT (eol_type) == 2)
3437 {
3438 coding->eol_type = CODING_EOL_CR;
3439 coding->common_flags
3440 = CODING_REQUIRE_DECODING_MASK | CODING_REQUIRE_ENCODING_MASK;
3441 }
3442 else
3443 coding->eol_type = CODING_EOL_LF;
3444
3445 coding_type = XVECTOR (coding_spec)->contents[0];
3446 /* Try short cut. */
3447 if (SYMBOLP (coding_type))
3448 {
3449 if (EQ (coding_type, Qt))
3450 {
3451 coding->type = coding_type_undecided;
3452 coding->common_flags |= CODING_REQUIRE_DETECTION_MASK;
3453 }
3454 else
3455 coding->type = coding_type_no_conversion;
3456 /* Initialize this member. Any thing other than
3457 CODING_CATEGORY_IDX_UTF_16_BE and
3458 CODING_CATEGORY_IDX_UTF_16_LE are ok because they have
3459 special treatment in detect_eol. */
3460 coding->category_idx = CODING_CATEGORY_IDX_EMACS_MULE;
3461
3462 return 0;
3463 }
3464
3465 /* Get values of coding system properties:
3466 `post-read-conversion', `pre-write-conversion',
3467 `translation-table-for-decode', `translation-table-for-encode'. */
3468 plist = XVECTOR (coding_spec)->contents[3];
3469 /* Pre & post conversion functions should be disabled if
3470 inhibit_eol_conversion is nonzero. This is the case that a code
3471 conversion function is called while those functions are running. */
3472 if (! inhibit_pre_post_conversion)
3473 {
3474 coding->post_read_conversion = Fplist_get (plist, Qpost_read_conversion);
3475 coding->pre_write_conversion = Fplist_get (plist, Qpre_write_conversion);
3476 }
3477 val = Fplist_get (plist, Qtranslation_table_for_decode);
3478 if (SYMBOLP (val))
3479 val = Fget (val, Qtranslation_table_for_decode);
3480 coding->translation_table_for_decode = CHAR_TABLE_P (val) ? val : Qnil;
3481 val = Fplist_get (plist, Qtranslation_table_for_encode);
3482 if (SYMBOLP (val))
3483 val = Fget (val, Qtranslation_table_for_encode);
3484 coding->translation_table_for_encode = CHAR_TABLE_P (val) ? val : Qnil;
3485 val = Fplist_get (plist, Qcoding_category);
3486 if (!NILP (val))
3487 {
3488 val = Fget (val, Qcoding_category_index);
3489 if (INTEGERP (val))
3490 coding->category_idx = XINT (val);
3491 else
3492 goto label_invalid_coding_system;
3493 }
3494 else
3495 goto label_invalid_coding_system;
3496
3497 /* If the coding system has non-nil `composition' property, enable
3498 composition handling. */
3499 val = Fplist_get (plist, Qcomposition);
3500 if (!NILP (val))
3501 coding->composing = COMPOSITION_NO;
3502
3503 switch (XFASTINT (coding_type))
3504 {
3505 case 0:
3506 coding->type = coding_type_emacs_mule;
3507 coding->common_flags
3508 |= CODING_REQUIRE_DECODING_MASK | CODING_REQUIRE_ENCODING_MASK;
3509 if (!NILP (coding->post_read_conversion))
3510 coding->common_flags |= CODING_REQUIRE_DECODING_MASK;
3511 if (!NILP (coding->pre_write_conversion))
3512 coding->common_flags |= CODING_REQUIRE_ENCODING_MASK;
3513 break;
3514
3515 case 1:
3516 coding->type = coding_type_sjis;
3517 coding->common_flags
3518 |= CODING_REQUIRE_DECODING_MASK | CODING_REQUIRE_ENCODING_MASK;
3519 break;
3520
3521 case 2:
3522 coding->type = coding_type_iso2022;
3523 coding->common_flags
3524 |= CODING_REQUIRE_DECODING_MASK | CODING_REQUIRE_ENCODING_MASK;
3525 {
3526 Lisp_Object val, temp;
3527 Lisp_Object *flags;
3528 int i, charset, reg_bits = 0;
3529
3530 val = XVECTOR (coding_spec)->contents[4];
3531
3532 if (!VECTORP (val) || XVECTOR (val)->size != 32)
3533 goto label_invalid_coding_system;
3534
3535 flags = XVECTOR (val)->contents;
3536 coding->flags
3537 = ((NILP (flags[4]) ? 0 : CODING_FLAG_ISO_SHORT_FORM)
3538 | (NILP (flags[5]) ? 0 : CODING_FLAG_ISO_RESET_AT_EOL)
3539 | (NILP (flags[6]) ? 0 : CODING_FLAG_ISO_RESET_AT_CNTL)
3540 | (NILP (flags[7]) ? 0 : CODING_FLAG_ISO_SEVEN_BITS)
3541 | (NILP (flags[8]) ? 0 : CODING_FLAG_ISO_LOCKING_SHIFT)
3542 | (NILP (flags[9]) ? 0 : CODING_FLAG_ISO_SINGLE_SHIFT)
3543 | (NILP (flags[10]) ? 0 : CODING_FLAG_ISO_USE_ROMAN)
3544 | (NILP (flags[11]) ? 0 : CODING_FLAG_ISO_USE_OLDJIS)
3545 | (NILP (flags[12]) ? 0 : CODING_FLAG_ISO_NO_DIRECTION)
3546 | (NILP (flags[13]) ? 0 : CODING_FLAG_ISO_INIT_AT_BOL)
3547 | (NILP (flags[14]) ? 0 : CODING_FLAG_ISO_DESIGNATE_AT_BOL)
3548 | (NILP (flags[15]) ? 0 : CODING_FLAG_ISO_SAFE)
3549 | (NILP (flags[16]) ? 0 : CODING_FLAG_ISO_LATIN_EXTRA)
3550 );
3551
3552 /* Invoke graphic register 0 to plane 0. */
3553 CODING_SPEC_ISO_INVOCATION (coding, 0) = 0;
3554 /* Invoke graphic register 1 to plane 1 if we can use full 8-bit. */
3555 CODING_SPEC_ISO_INVOCATION (coding, 1)
3556 = (coding->flags & CODING_FLAG_ISO_SEVEN_BITS ? -1 : 1);
3557 /* Not single shifting at first. */
3558 CODING_SPEC_ISO_SINGLE_SHIFTING (coding) = 0;
3559 /* Beginning of buffer should also be regarded as bol. */
3560 CODING_SPEC_ISO_BOL (coding) = 1;
3561
3562 for (charset = 0; charset <= MAX_CHARSET; charset++)
3563 CODING_SPEC_ISO_REVISION_NUMBER (coding, charset) = 255;
3564 val = Vcharset_revision_alist;
3565 while (CONSP (val))
3566 {
3567 charset = get_charset_id (Fcar_safe (XCAR (val)));
3568 if (charset >= 0
3569 && (temp = Fcdr_safe (XCAR (val)), INTEGERP (temp))
3570 && (i = XINT (temp), (i >= 0 && (i + '@') < 128)))
3571 CODING_SPEC_ISO_REVISION_NUMBER (coding, charset) = i;
3572 val = XCDR (val);
3573 }
3574
3575 /* Checks FLAGS[REG] (REG = 0, 1, 2 3) and decide designations.
3576 FLAGS[REG] can be one of below:
3577 integer CHARSET: CHARSET occupies register I,
3578 t: designate nothing to REG initially, but can be used
3579 by any charsets,
3580 list of integer, nil, or t: designate the first
3581 element (if integer) to REG initially, the remaining
3582 elements (if integer) is designated to REG on request,
3583 if an element is t, REG can be used by any charsets,
3584 nil: REG is never used. */
3585 for (charset = 0; charset <= MAX_CHARSET; charset++)
3586 CODING_SPEC_ISO_REQUESTED_DESIGNATION (coding, charset)
3587 = CODING_SPEC_ISO_NO_REQUESTED_DESIGNATION;
3588 for (i = 0; i < 4; i++)
3589 {
3590 if ((INTEGERP (flags[i])
3591 && (charset = XINT (flags[i]), CHARSET_VALID_P (charset)))
3592 || (charset = get_charset_id (flags[i])) >= 0)
3593 {
3594 CODING_SPEC_ISO_INITIAL_DESIGNATION (coding, i) = charset;
3595 CODING_SPEC_ISO_REQUESTED_DESIGNATION (coding, charset) = i;
3596 }
3597 else if (EQ (flags[i], Qt))
3598 {
3599 CODING_SPEC_ISO_INITIAL_DESIGNATION (coding, i) = -1;
3600 reg_bits |= 1 << i;
3601 coding->flags |= CODING_FLAG_ISO_DESIGNATION;
3602 }
3603 else if (CONSP (flags[i]))
3604 {
3605 Lisp_Object tail;
3606 tail = flags[i];
3607
3608 coding->flags |= CODING_FLAG_ISO_DESIGNATION;
3609 if ((INTEGERP (XCAR (tail))
3610 && (charset = XINT (XCAR (tail)),
3611 CHARSET_VALID_P (charset)))
3612 || (charset = get_charset_id (XCAR (tail))) >= 0)
3613 {
3614 CODING_SPEC_ISO_INITIAL_DESIGNATION (coding, i) = charset;
3615 CODING_SPEC_ISO_REQUESTED_DESIGNATION (coding, charset) =i;
3616 }
3617 else
3618 CODING_SPEC_ISO_INITIAL_DESIGNATION (coding, i) = -1;
3619 tail = XCDR (tail);
3620 while (CONSP (tail))
3621 {
3622 if ((INTEGERP (XCAR (tail))
3623 && (charset = XINT (XCAR (tail)),
3624 CHARSET_VALID_P (charset)))
3625 || (charset = get_charset_id (XCAR (tail))) >= 0)
3626 CODING_SPEC_ISO_REQUESTED_DESIGNATION (coding, charset)
3627 = i;
3628 else if (EQ (XCAR (tail), Qt))
3629 reg_bits |= 1 << i;
3630 tail = XCDR (tail);
3631 }
3632 }
3633 else
3634 CODING_SPEC_ISO_INITIAL_DESIGNATION (coding, i) = -1;
3635
3636 CODING_SPEC_ISO_DESIGNATION (coding, i)
3637 = CODING_SPEC_ISO_INITIAL_DESIGNATION (coding, i);
3638 }
3639
3640 if (reg_bits && ! (coding->flags & CODING_FLAG_ISO_LOCKING_SHIFT))
3641 {
3642 /* REG 1 can be used only by locking shift in 7-bit env. */
3643 if (coding->flags & CODING_FLAG_ISO_SEVEN_BITS)
3644 reg_bits &= ~2;
3645 if (! (coding->flags & CODING_FLAG_ISO_SINGLE_SHIFT))
3646 /* Without any shifting, only REG 0 and 1 can be used. */
3647 reg_bits &= 3;
3648 }
3649
3650 if (reg_bits)
3651 for (charset = 0; charset <= MAX_CHARSET; charset++)
3652 {
3653 if (CHARSET_DEFINED_P (charset)
3654 && (CODING_SPEC_ISO_REQUESTED_DESIGNATION (coding, charset)
3655 == CODING_SPEC_ISO_NO_REQUESTED_DESIGNATION))
3656 {
3657 /* There exist some default graphic registers to be
3658 used by CHARSET. */
3659
3660 /* We had better avoid designating a charset of
3661 CHARS96 to REG 0 as far as possible. */
3662 if (CHARSET_CHARS (charset) == 96)
3663 CODING_SPEC_ISO_REQUESTED_DESIGNATION (coding, charset)
3664 = (reg_bits & 2
3665 ? 1 : (reg_bits & 4 ? 2 : (reg_bits & 8 ? 3 : 0)));
3666 else
3667 CODING_SPEC_ISO_REQUESTED_DESIGNATION (coding, charset)
3668 = (reg_bits & 1
3669 ? 0 : (reg_bits & 2 ? 1 : (reg_bits & 4 ? 2 : 3)));
3670 }
3671 }
3672 }
3673 coding->common_flags |= CODING_REQUIRE_FLUSHING_MASK;
3674 coding->spec.iso2022.last_invalid_designation_register = -1;
3675 break;
3676
3677 case 3:
3678 coding->type = coding_type_big5;
3679 coding->common_flags
3680 |= CODING_REQUIRE_DECODING_MASK | CODING_REQUIRE_ENCODING_MASK;
3681 coding->flags
3682 = (NILP (XVECTOR (coding_spec)->contents[4])
3683 ? CODING_FLAG_BIG5_HKU
3684 : CODING_FLAG_BIG5_ETEN);
3685 break;
3686
3687 case 4:
3688 coding->type = coding_type_ccl;
3689 coding->common_flags
3690 |= CODING_REQUIRE_DECODING_MASK | CODING_REQUIRE_ENCODING_MASK;
3691 {
3692 val = XVECTOR (coding_spec)->contents[4];
3693 if (! CONSP (val)
3694 || setup_ccl_program (&(coding->spec.ccl.decoder),
3695 XCAR (val)) < 0
3696 || setup_ccl_program (&(coding->spec.ccl.encoder),
3697 XCDR (val)) < 0)
3698 goto label_invalid_coding_system;
3699
3700 bzero (coding->spec.ccl.valid_codes, 256);
3701 val = Fplist_get (plist, Qvalid_codes);
3702 if (CONSP (val))
3703 {
3704 Lisp_Object this;
3705
3706 for (; CONSP (val); val = XCDR (val))
3707 {
3708 this = XCAR (val);
3709 if (INTEGERP (this)
3710 && XINT (this) >= 0 && XINT (this) < 256)
3711 coding->spec.ccl.valid_codes[XINT (this)] = 1;
3712 else if (CONSP (this)
3713 && INTEGERP (XCAR (this))
3714 && INTEGERP (XCDR (this)))
3715 {
3716 int start = XINT (XCAR (this));
3717 int end = XINT (XCDR (this));
3718
3719 if (start >= 0 && start <= end && end < 256)
3720 while (start <= end)
3721 coding->spec.ccl.valid_codes[start++] = 1;
3722 }
3723 }
3724 }
3725 }
3726 coding->common_flags |= CODING_REQUIRE_FLUSHING_MASK;
3727 coding->spec.ccl.cr_carryover = 0;
3728 coding->spec.ccl.eight_bit_carryover[0] = 0;
3729 break;
3730
3731 case 5:
3732 coding->type = coding_type_raw_text;
3733 break;
3734
3735 default:
3736 goto label_invalid_coding_system;
3737 }
3738 return 0;
3739
3740 label_invalid_coding_system:
3741 coding->type = coding_type_no_conversion;
3742 coding->category_idx = CODING_CATEGORY_IDX_BINARY;
3743 coding->common_flags = 0;
3744 coding->eol_type = CODING_EOL_LF;
3745 coding->pre_write_conversion = coding->post_read_conversion = Qnil;
3746 return -1;
3747 }
3748
3749 /* Free memory blocks allocated for storing composition information. */
3750
3751 void
3752 coding_free_composition_data (coding)
3753 struct coding_system *coding;
3754 {
3755 struct composition_data *cmp_data = coding->cmp_data, *next;
3756
3757 if (!cmp_data)
3758 return;
3759 /* Memory blocks are chained. At first, rewind to the first, then,
3760 free blocks one by one. */
3761 while (cmp_data->prev)
3762 cmp_data = cmp_data->prev;
3763 while (cmp_data)
3764 {
3765 next = cmp_data->next;
3766 xfree (cmp_data);
3767 cmp_data = next;
3768 }
3769 coding->cmp_data = NULL;
3770 }
3771
3772 /* Set `char_offset' member of all memory blocks pointed by
3773 coding->cmp_data to POS. */
3774
3775 void
3776 coding_adjust_composition_offset (coding, pos)
3777 struct coding_system *coding;
3778 int pos;
3779 {
3780 struct composition_data *cmp_data;
3781
3782 for (cmp_data = coding->cmp_data; cmp_data; cmp_data = cmp_data->next)
3783 cmp_data->char_offset = pos;
3784 }
3785
3786 /* Setup raw-text or one of its subsidiaries in the structure
3787 coding_system CODING according to the already setup value eol_type
3788 in CODING. CODING should be setup for some coding system in
3789 advance. */
3790
3791 void
3792 setup_raw_text_coding_system (coding)
3793 struct coding_system *coding;
3794 {
3795 if (coding->type != coding_type_raw_text)
3796 {
3797 coding->symbol = Qraw_text;
3798 coding->type = coding_type_raw_text;
3799 if (coding->eol_type != CODING_EOL_UNDECIDED)
3800 {
3801 Lisp_Object subsidiaries;
3802 subsidiaries = Fget (Qraw_text, Qeol_type);
3803
3804 if (VECTORP (subsidiaries)
3805 && XVECTOR (subsidiaries)->size == 3)
3806 coding->symbol
3807 = XVECTOR (subsidiaries)->contents[coding->eol_type];
3808 }
3809 setup_coding_system (coding->symbol, coding);
3810 }
3811 return;
3812 }
3813
3814 /* Emacs has a mechanism to automatically detect a coding system if it
3815 is one of Emacs' internal format, ISO2022, SJIS, and BIG5. But,
3816 it's impossible to distinguish some coding systems accurately
3817 because they use the same range of codes. So, at first, coding
3818 systems are categorized into 7, those are:
3819
3820 o coding-category-emacs-mule
3821
3822 The category for a coding system which has the same code range
3823 as Emacs' internal format. Assigned the coding-system (Lisp
3824 symbol) `emacs-mule' by default.
3825
3826 o coding-category-sjis
3827
3828 The category for a coding system which has the same code range
3829 as SJIS. Assigned the coding-system (Lisp
3830 symbol) `japanese-shift-jis' by default.
3831
3832 o coding-category-iso-7
3833
3834 The category for a coding system which has the same code range
3835 as ISO2022 of 7-bit environment. This doesn't use any locking
3836 shift and single shift functions. This can encode/decode all
3837 charsets. Assigned the coding-system (Lisp symbol)
3838 `iso-2022-7bit' by default.
3839
3840 o coding-category-iso-7-tight
3841
3842 Same as coding-category-iso-7 except that this can
3843 encode/decode only the specified charsets.
3844
3845 o coding-category-iso-8-1
3846
3847 The category for a coding system which has the same code range
3848 as ISO2022 of 8-bit environment and graphic plane 1 used only
3849 for DIMENSION1 charset. This doesn't use any locking shift
3850 and single shift functions. Assigned the coding-system (Lisp
3851 symbol) `iso-latin-1' by default.
3852
3853 o coding-category-iso-8-2
3854
3855 The category for a coding system which has the same code range
3856 as ISO2022 of 8-bit environment and graphic plane 1 used only
3857 for DIMENSION2 charset. This doesn't use any locking shift
3858 and single shift functions. Assigned the coding-system (Lisp
3859 symbol) `japanese-iso-8bit' by default.
3860
3861 o coding-category-iso-7-else
3862
3863 The category for a coding system which has the same code range
3864 as ISO2022 of 7-bit environment but uses locking shift or
3865 single shift functions. Assigned the coding-system (Lisp
3866 symbol) `iso-2022-7bit-lock' by default.
3867
3868 o coding-category-iso-8-else
3869
3870 The category for a coding system which has the same code range
3871 as ISO2022 of 8-bit environment but uses locking shift or
3872 single shift functions. Assigned the coding-system (Lisp
3873 symbol) `iso-2022-8bit-ss2' by default.
3874
3875 o coding-category-big5
3876
3877 The category for a coding system which has the same code range
3878 as BIG5. Assigned the coding-system (Lisp symbol)
3879 `cn-big5' by default.
3880
3881 o coding-category-utf-8
3882
3883 The category for a coding system which has the same code range
3884 as UTF-8 (cf. RFC2279). Assigned the coding-system (Lisp
3885 symbol) `utf-8' by default.
3886
3887 o coding-category-utf-16-be
3888
3889 The category for a coding system in which a text has an
3890 Unicode signature (cf. Unicode Standard) in the order of BIG
3891 endian at the head. Assigned the coding-system (Lisp symbol)
3892 `utf-16-be' by default.
3893
3894 o coding-category-utf-16-le
3895
3896 The category for a coding system in which a text has an
3897 Unicode signature (cf. Unicode Standard) in the order of
3898 LITTLE endian at the head. Assigned the coding-system (Lisp
3899 symbol) `utf-16-le' by default.
3900
3901 o coding-category-ccl
3902
3903 The category for a coding system of which encoder/decoder is
3904 written in CCL programs. The default value is nil, i.e., no
3905 coding system is assigned.
3906
3907 o coding-category-binary
3908
3909 The category for a coding system not categorized in any of the
3910 above. Assigned the coding-system (Lisp symbol)
3911 `no-conversion' by default.
3912
3913 Each of them is a Lisp symbol and the value is an actual
3914 `coding-system' (this is also a Lisp symbol) assigned by a user.
3915 What Emacs does actually is to detect a category of coding system.
3916 Then, it uses a `coding-system' assigned to it. If Emacs can't
3917 decide a single possible category, it selects a category of the
3918 highest priority. Priorities of categories are also specified by a
3919 user in a Lisp variable `coding-category-list'.
3920
3921 */
3922
3923 static
3924 int ascii_skip_code[256];
3925
3926 /* Detect how a text of length SRC_BYTES pointed by SOURCE is encoded.
3927 If it detects possible coding systems, return an integer in which
3928 appropriate flag bits are set. Flag bits are defined by macros
3929 CODING_CATEGORY_MASK_XXX in `coding.h'. If PRIORITIES is non-NULL,
3930 it should point the table `coding_priorities'. In that case, only
3931 the flag bit for a coding system of the highest priority is set in
3932 the returned value. If MULTIBYTEP is nonzero, 8-bit codes of the
3933 range 0x80..0x9F are in multibyte form.
3934
3935 How many ASCII characters are at the head is returned as *SKIP. */
3936
3937 static int
3938 detect_coding_mask (source, src_bytes, priorities, skip, multibytep)
3939 unsigned char *source;
3940 int src_bytes, *priorities, *skip;
3941 int multibytep;
3942 {
3943 register unsigned char c;
3944 unsigned char *src = source, *src_end = source + src_bytes;
3945 unsigned int mask, utf16_examined_p, iso2022_examined_p;
3946 int i;
3947
3948 /* At first, skip all ASCII characters and control characters except
3949 for three ISO2022 specific control characters. */
3950 ascii_skip_code[ISO_CODE_SO] = 0;
3951 ascii_skip_code[ISO_CODE_SI] = 0;
3952 ascii_skip_code[ISO_CODE_ESC] = 0;
3953
3954 label_loop_detect_coding:
3955 while (src < src_end && ascii_skip_code[*src]) src++;
3956 *skip = src - source;
3957
3958 if (src >= src_end)
3959 /* We found nothing other than ASCII. There's nothing to do. */
3960 return 0;
3961
3962 c = *src;
3963 /* The text seems to be encoded in some multilingual coding system.
3964 Now, try to find in which coding system the text is encoded. */
3965 if (c < 0x80)
3966 {
3967 /* i.e. (c == ISO_CODE_ESC || c == ISO_CODE_SI || c == ISO_CODE_SO) */
3968 /* C is an ISO2022 specific control code of C0. */
3969 mask = detect_coding_iso2022 (src, src_end, multibytep);
3970 if (mask == 0)
3971 {
3972 /* No valid ISO2022 code follows C. Try again. */
3973 src++;
3974 if (c == ISO_CODE_ESC)
3975 ascii_skip_code[ISO_CODE_ESC] = 1;
3976 else
3977 ascii_skip_code[ISO_CODE_SO] = ascii_skip_code[ISO_CODE_SI] = 1;
3978 goto label_loop_detect_coding;
3979 }
3980 if (priorities)
3981 {
3982 for (i = 0; i < CODING_CATEGORY_IDX_MAX; i++)
3983 {
3984 if (mask & priorities[i])
3985 return priorities[i];
3986 }
3987 return CODING_CATEGORY_MASK_RAW_TEXT;
3988 }
3989 }
3990 else
3991 {
3992 int try;
3993
3994 if (multibytep && c == LEADING_CODE_8_BIT_CONTROL)
3995 c = src[1] - 0x20;
3996
3997 if (c < 0xA0)
3998 {
3999 /* C is the first byte of SJIS character code,
4000 or a leading-code of Emacs' internal format (emacs-mule),
4001 or the first byte of UTF-16. */
4002 try = (CODING_CATEGORY_MASK_SJIS
4003 | CODING_CATEGORY_MASK_EMACS_MULE
4004 | CODING_CATEGORY_MASK_UTF_16_BE
4005 | CODING_CATEGORY_MASK_UTF_16_LE);
4006
4007 /* Or, if C is a special latin extra code,
4008 or is an ISO2022 specific control code of C1 (SS2 or SS3),
4009 or is an ISO2022 control-sequence-introducer (CSI),
4010 we should also consider the possibility of ISO2022 codings. */
4011 if ((VECTORP (Vlatin_extra_code_table)
4012 && !NILP (XVECTOR (Vlatin_extra_code_table)->contents[c]))
4013 || (c == ISO_CODE_SS2 || c == ISO_CODE_SS3)
4014 || (c == ISO_CODE_CSI
4015 && (src < src_end
4016 && (*src == ']'
4017 || ((*src == '0' || *src == '1' || *src == '2')
4018 && src + 1 < src_end
4019 && src[1] == ']')))))
4020 try |= (CODING_CATEGORY_MASK_ISO_8_ELSE
4021 | CODING_CATEGORY_MASK_ISO_8BIT);
4022 }
4023 else
4024 /* C is a character of ISO2022 in graphic plane right,
4025 or a SJIS's 1-byte character code (i.e. JISX0201),
4026 or the first byte of BIG5's 2-byte code,
4027 or the first byte of UTF-8/16. */
4028 try = (CODING_CATEGORY_MASK_ISO_8_ELSE
4029 | CODING_CATEGORY_MASK_ISO_8BIT
4030 | CODING_CATEGORY_MASK_SJIS
4031 | CODING_CATEGORY_MASK_BIG5
4032 | CODING_CATEGORY_MASK_UTF_8
4033 | CODING_CATEGORY_MASK_UTF_16_BE
4034 | CODING_CATEGORY_MASK_UTF_16_LE);
4035
4036 /* Or, we may have to consider the possibility of CCL. */
4037 if (coding_system_table[CODING_CATEGORY_IDX_CCL]
4038 && (coding_system_table[CODING_CATEGORY_IDX_CCL]
4039 ->spec.ccl.valid_codes)[c])
4040 try |= CODING_CATEGORY_MASK_CCL;
4041
4042 mask = 0;
4043 utf16_examined_p = iso2022_examined_p = 0;
4044 if (priorities)
4045 {
4046 for (i = 0; i < CODING_CATEGORY_IDX_MAX; i++)
4047 {
4048 if (!iso2022_examined_p
4049 && (priorities[i] & try & CODING_CATEGORY_MASK_ISO))
4050 {
4051 mask |= detect_coding_iso2022 (src, src_end, multibytep);
4052 iso2022_examined_p = 1;
4053 }
4054 else if (priorities[i] & try & CODING_CATEGORY_MASK_SJIS)
4055 mask |= detect_coding_sjis (src, src_end, multibytep);
4056 else if (priorities[i] & try & CODING_CATEGORY_MASK_UTF_8)
4057 mask |= detect_coding_utf_8 (src, src_end, multibytep);
4058 else if (!utf16_examined_p
4059 && (priorities[i] & try &
4060 CODING_CATEGORY_MASK_UTF_16_BE_LE))
4061 {
4062 mask |= detect_coding_utf_16 (src, src_end, multibytep);
4063 utf16_examined_p = 1;
4064 }
4065 else if (priorities[i] & try & CODING_CATEGORY_MASK_BIG5)
4066 mask |= detect_coding_big5 (src, src_end, multibytep);
4067 else if (priorities[i] & try & CODING_CATEGORY_MASK_EMACS_MULE)
4068 mask |= detect_coding_emacs_mule (src, src_end, multibytep);
4069 else if (priorities[i] & try & CODING_CATEGORY_MASK_CCL)
4070 mask |= detect_coding_ccl (src, src_end, multibytep);
4071 else if (priorities[i] & CODING_CATEGORY_MASK_RAW_TEXT)
4072 mask |= CODING_CATEGORY_MASK_RAW_TEXT;
4073 else if (priorities[i] & CODING_CATEGORY_MASK_BINARY)
4074 mask |= CODING_CATEGORY_MASK_BINARY;
4075 if (mask & priorities[i])
4076 return priorities[i];
4077 }
4078 return CODING_CATEGORY_MASK_RAW_TEXT;
4079 }
4080 if (try & CODING_CATEGORY_MASK_ISO)
4081 mask |= detect_coding_iso2022 (src, src_end, multibytep);
4082 if (try & CODING_CATEGORY_MASK_SJIS)
4083 mask |= detect_coding_sjis (src, src_end, multibytep);
4084 if (try & CODING_CATEGORY_MASK_BIG5)
4085 mask |= detect_coding_big5 (src, src_end, multibytep);
4086 if (try & CODING_CATEGORY_MASK_UTF_8)
4087 mask |= detect_coding_utf_8 (src, src_end, multibytep);
4088 if (try & CODING_CATEGORY_MASK_UTF_16_BE_LE)
4089 mask |= detect_coding_utf_16 (src, src_end, multibytep);
4090 if (try & CODING_CATEGORY_MASK_EMACS_MULE)
4091 mask |= detect_coding_emacs_mule (src, src_end, multibytep);
4092 if (try & CODING_CATEGORY_MASK_CCL)
4093 mask |= detect_coding_ccl (src, src_end, multibytep);
4094 }
4095 return (mask | CODING_CATEGORY_MASK_RAW_TEXT | CODING_CATEGORY_MASK_BINARY);
4096 }
4097
4098 /* Detect how a text of length SRC_BYTES pointed by SRC is encoded.
4099 The information of the detected coding system is set in CODING. */
4100
4101 void
4102 detect_coding (coding, src, src_bytes)
4103 struct coding_system *coding;
4104 const unsigned char *src;
4105 int src_bytes;
4106 {
4107 unsigned int idx;
4108 int skip, mask;
4109 Lisp_Object val;
4110
4111 val = Vcoding_category_list;
4112 mask = detect_coding_mask (src, src_bytes, coding_priorities, &skip,
4113 coding->src_multibyte);
4114 coding->heading_ascii = skip;
4115
4116 if (!mask) return;
4117
4118 /* We found a single coding system of the highest priority in MASK. */
4119 idx = 0;
4120 while (mask && ! (mask & 1)) mask >>= 1, idx++;
4121 if (! mask)
4122 idx = CODING_CATEGORY_IDX_RAW_TEXT;
4123
4124 val = SYMBOL_VALUE (XVECTOR (Vcoding_category_table)->contents[idx]);
4125
4126 if (coding->eol_type != CODING_EOL_UNDECIDED)
4127 {
4128 Lisp_Object tmp;
4129
4130 tmp = Fget (val, Qeol_type);
4131 if (VECTORP (tmp))
4132 val = XVECTOR (tmp)->contents[coding->eol_type];
4133 }
4134
4135 /* Setup this new coding system while preserving some slots. */
4136 {
4137 int src_multibyte = coding->src_multibyte;
4138 int dst_multibyte = coding->dst_multibyte;
4139
4140 setup_coding_system (val, coding);
4141 coding->src_multibyte = src_multibyte;
4142 coding->dst_multibyte = dst_multibyte;
4143 coding->heading_ascii = skip;
4144 }
4145 }
4146
4147 /* Detect how end-of-line of a text of length SRC_BYTES pointed by
4148 SOURCE is encoded. Return one of CODING_EOL_LF, CODING_EOL_CRLF,
4149 CODING_EOL_CR, and CODING_EOL_UNDECIDED.
4150
4151 How many non-eol characters are at the head is returned as *SKIP. */
4152
4153 #define MAX_EOL_CHECK_COUNT 3
4154
4155 static int
4156 detect_eol_type (source, src_bytes, skip)
4157 unsigned char *source;
4158 int src_bytes, *skip;
4159 {
4160 unsigned char *src = source, *src_end = src + src_bytes;
4161 unsigned char c;
4162 int total = 0; /* How many end-of-lines are found so far. */
4163 int eol_type = CODING_EOL_UNDECIDED;
4164 int this_eol_type;
4165
4166 *skip = 0;
4167
4168 while (src < src_end && total < MAX_EOL_CHECK_COUNT)
4169 {
4170 c = *src++;
4171 if (c == '\n' || c == '\r')
4172 {
4173 if (*skip == 0)
4174 *skip = src - 1 - source;
4175 total++;
4176 if (c == '\n')
4177 this_eol_type = CODING_EOL_LF;
4178 else if (src >= src_end || *src != '\n')
4179 this_eol_type = CODING_EOL_CR;
4180 else
4181 this_eol_type = CODING_EOL_CRLF, src++;
4182
4183 if (eol_type == CODING_EOL_UNDECIDED)
4184 /* This is the first end-of-line. */
4185 eol_type = this_eol_type;
4186 else if (eol_type != this_eol_type)
4187 {
4188 /* The found type is different from what found before. */
4189 eol_type = CODING_EOL_INCONSISTENT;
4190 break;
4191 }
4192 }
4193 }
4194
4195 if (*skip == 0)
4196 *skip = src_end - source;
4197 return eol_type;
4198 }
4199
4200 /* Like detect_eol_type, but detect EOL type in 2-octet
4201 big-endian/little-endian format for coding systems utf-16-be and
4202 utf-16-le. */
4203
4204 static int
4205 detect_eol_type_in_2_octet_form (source, src_bytes, skip, big_endian_p)
4206 unsigned char *source;
4207 int src_bytes, *skip, big_endian_p;
4208 {
4209 unsigned char *src = source, *src_end = src + src_bytes;
4210 unsigned int c1, c2;
4211 int total = 0; /* How many end-of-lines are found so far. */
4212 int eol_type = CODING_EOL_UNDECIDED;
4213 int this_eol_type;
4214 int msb, lsb;
4215
4216 if (big_endian_p)
4217 msb = 0, lsb = 1;
4218 else
4219 msb = 1, lsb = 0;
4220
4221 *skip = 0;
4222
4223 while ((src + 1) < src_end && total < MAX_EOL_CHECK_COUNT)
4224 {
4225 c1 = (src[msb] << 8) | (src[lsb]);
4226 src += 2;
4227
4228 if (c1 == '\n' || c1 == '\r')
4229 {
4230 if (*skip == 0)
4231 *skip = src - 2 - source;
4232 total++;
4233 if (c1 == '\n')
4234 {
4235 this_eol_type = CODING_EOL_LF;
4236 }
4237 else
4238 {
4239 if ((src + 1) >= src_end)
4240 {
4241 this_eol_type = CODING_EOL_CR;
4242 }
4243 else
4244 {
4245 c2 = (src[msb] << 8) | (src[lsb]);
4246 if (c2 == '\n')
4247 this_eol_type = CODING_EOL_CRLF, src += 2;
4248 else
4249 this_eol_type = CODING_EOL_CR;
4250 }
4251 }
4252
4253 if (eol_type == CODING_EOL_UNDECIDED)
4254 /* This is the first end-of-line. */
4255 eol_type = this_eol_type;
4256 else if (eol_type != this_eol_type)
4257 {
4258 /* The found type is different from what found before. */
4259 eol_type = CODING_EOL_INCONSISTENT;
4260 break;
4261 }
4262 }
4263 }
4264
4265 if (*skip == 0)
4266 *skip = src_end - source;
4267 return eol_type;
4268 }
4269
4270 /* Detect how end-of-line of a text of length SRC_BYTES pointed by SRC
4271 is encoded. If it detects an appropriate format of end-of-line, it
4272 sets the information in *CODING. */
4273
4274 void
4275 detect_eol (coding, src, src_bytes)
4276 struct coding_system *coding;
4277 const unsigned char *src;
4278 int src_bytes;
4279 {
4280 Lisp_Object val;
4281 int skip;
4282 int eol_type;
4283
4284 switch (coding->category_idx)
4285 {
4286 case CODING_CATEGORY_IDX_UTF_16_BE:
4287 eol_type = detect_eol_type_in_2_octet_form (src, src_bytes, &skip, 1);
4288 break;
4289 case CODING_CATEGORY_IDX_UTF_16_LE:
4290 eol_type = detect_eol_type_in_2_octet_form (src, src_bytes, &skip, 0);
4291 break;
4292 default:
4293 eol_type = detect_eol_type (src, src_bytes, &skip);
4294 break;
4295 }
4296
4297 if (coding->heading_ascii > skip)
4298 coding->heading_ascii = skip;
4299 else
4300 skip = coding->heading_ascii;
4301
4302 if (eol_type == CODING_EOL_UNDECIDED)
4303 return;
4304 if (eol_type == CODING_EOL_INCONSISTENT)
4305 {
4306 #if 0
4307 /* This code is suppressed until we find a better way to
4308 distinguish raw text file and binary file. */
4309
4310 /* If we have already detected that the coding is raw-text, the
4311 coding should actually be no-conversion. */
4312 if (coding->type == coding_type_raw_text)
4313 {
4314 setup_coding_system (Qno_conversion, coding);
4315 return;
4316 }
4317 /* Else, let's decode only text code anyway. */
4318 #endif /* 0 */
4319 eol_type = CODING_EOL_LF;
4320 }
4321
4322 val = Fget (coding->symbol, Qeol_type);
4323 if (VECTORP (val) && XVECTOR (val)->size == 3)
4324 {
4325 int src_multibyte = coding->src_multibyte;
4326 int dst_multibyte = coding->dst_multibyte;
4327 struct composition_data *cmp_data = coding->cmp_data;
4328
4329 setup_coding_system (XVECTOR (val)->contents[eol_type], coding);
4330 coding->src_multibyte = src_multibyte;
4331 coding->dst_multibyte = dst_multibyte;
4332 coding->heading_ascii = skip;
4333 coding->cmp_data = cmp_data;
4334 }
4335 }
4336
4337 #define CONVERSION_BUFFER_EXTRA_ROOM 256
4338
4339 #define DECODING_BUFFER_MAG(coding) \
4340 (coding->type == coding_type_iso2022 \
4341 ? 3 \
4342 : (coding->type == coding_type_ccl \
4343 ? coding->spec.ccl.decoder.buf_magnification \
4344 : 2))
4345
4346 /* Return maximum size (bytes) of a buffer enough for decoding
4347 SRC_BYTES of text encoded in CODING. */
4348
4349 int
4350 decoding_buffer_size (coding, src_bytes)
4351 struct coding_system *coding;
4352 int src_bytes;
4353 {
4354 return (src_bytes * DECODING_BUFFER_MAG (coding)
4355 + CONVERSION_BUFFER_EXTRA_ROOM);
4356 }
4357
4358 /* Return maximum size (bytes) of a buffer enough for encoding
4359 SRC_BYTES of text to CODING. */
4360
4361 int
4362 encoding_buffer_size (coding, src_bytes)
4363 struct coding_system *coding;
4364 int src_bytes;
4365 {
4366 int magnification;
4367
4368 if (coding->type == coding_type_ccl)
4369 magnification = coding->spec.ccl.encoder.buf_magnification;
4370 else if (CODING_REQUIRE_ENCODING (coding))
4371 magnification = 3;
4372 else
4373 magnification = 1;
4374
4375 return (src_bytes * magnification + CONVERSION_BUFFER_EXTRA_ROOM);
4376 }
4377
4378 /* Working buffer for code conversion. */
4379 struct conversion_buffer
4380 {
4381 int size; /* size of data. */
4382 int on_stack; /* 1 if allocated by alloca. */
4383 unsigned char *data;
4384 };
4385
4386 /* Don't use alloca for allocating memory space larger than this, lest
4387 we overflow their stack. */
4388 #define MAX_ALLOCA 16*1024
4389
4390 /* Allocate LEN bytes of memory for BUF (struct conversion_buffer). */
4391 #define allocate_conversion_buffer(buf, len) \
4392 do { \
4393 if (len < MAX_ALLOCA) \
4394 { \
4395 buf.data = (unsigned char *) alloca (len); \
4396 buf.on_stack = 1; \
4397 } \
4398 else \
4399 { \
4400 buf.data = (unsigned char *) xmalloc (len); \
4401 buf.on_stack = 0; \
4402 } \
4403 buf.size = len; \
4404 } while (0)
4405
4406 /* Double the allocated memory for *BUF. */
4407 static void
4408 extend_conversion_buffer (buf)
4409 struct conversion_buffer *buf;
4410 {
4411 if (buf->on_stack)
4412 {
4413 unsigned char *save = buf->data;
4414 buf->data = (unsigned char *) xmalloc (buf->size * 2);
4415 bcopy (save, buf->data, buf->size);
4416 buf->on_stack = 0;
4417 }
4418 else
4419 {
4420 buf->data = (unsigned char *) xrealloc (buf->data, buf->size * 2);
4421 }
4422 buf->size *= 2;
4423 }
4424
4425 /* Free the allocated memory for BUF if it is not on stack. */
4426 static void
4427 free_conversion_buffer (buf)
4428 struct conversion_buffer *buf;
4429 {
4430 if (!buf->on_stack)
4431 xfree (buf->data);
4432 }
4433
4434 int
4435 ccl_coding_driver (coding, source, destination, src_bytes, dst_bytes, encodep)
4436 struct coding_system *coding;
4437 unsigned char *source, *destination;
4438 int src_bytes, dst_bytes, encodep;
4439 {
4440 struct ccl_program *ccl
4441 = encodep ? &coding->spec.ccl.encoder : &coding->spec.ccl.decoder;
4442 unsigned char *dst = destination;
4443
4444 ccl->suppress_error = coding->suppress_error;
4445 ccl->last_block = coding->mode & CODING_MODE_LAST_BLOCK;
4446 if (encodep)
4447 {
4448 /* On encoding, EOL format is converted within ccl_driver. For
4449 that, setup proper information in the structure CCL. */
4450 ccl->eol_type = coding->eol_type;
4451 if (ccl->eol_type ==CODING_EOL_UNDECIDED)
4452 ccl->eol_type = CODING_EOL_LF;
4453 ccl->cr_consumed = coding->spec.ccl.cr_carryover;
4454 }
4455 ccl->multibyte = coding->src_multibyte;
4456 if (coding->spec.ccl.eight_bit_carryover[0] != 0)
4457 {
4458 /* Move carryover bytes to DESTINATION. */
4459 unsigned char *p = coding->spec.ccl.eight_bit_carryover;
4460 while (*p)
4461 *dst++ = *p++;
4462 coding->spec.ccl.eight_bit_carryover[0] = 0;
4463 if (dst_bytes)
4464 dst_bytes -= dst - destination;
4465 }
4466
4467 coding->produced = (ccl_driver (ccl, source, dst, src_bytes, dst_bytes,
4468 &(coding->consumed))
4469 + dst - destination);
4470
4471 if (encodep)
4472 {
4473 coding->produced_char = coding->produced;
4474 coding->spec.ccl.cr_carryover = ccl->cr_consumed;
4475 }
4476 else if (!ccl->eight_bit_control)
4477 {
4478 /* The produced bytes forms a valid multibyte sequence. */
4479 coding->produced_char
4480 = multibyte_chars_in_text (destination, coding->produced);
4481 coding->spec.ccl.eight_bit_carryover[0] = 0;
4482 }
4483 else
4484 {
4485 /* On decoding, the destination should always multibyte. But,
4486 CCL program might have been generated an invalid multibyte
4487 sequence. Here we make such a sequence valid as
4488 multibyte. */
4489 int bytes
4490 = dst_bytes ? dst_bytes : source + coding->consumed - destination;
4491
4492 if ((coding->consumed < src_bytes
4493 || !ccl->last_block)
4494 && coding->produced >= 1
4495 && destination[coding->produced - 1] >= 0x80)
4496 {
4497 /* We should not convert the tailing 8-bit codes to
4498 multibyte form even if they doesn't form a valid
4499 multibyte sequence. They may form a valid sequence in
4500 the next call. */
4501 int carryover = 0;
4502
4503 if (destination[coding->produced - 1] < 0xA0)
4504 carryover = 1;
4505 else if (coding->produced >= 2)
4506 {
4507 if (destination[coding->produced - 2] >= 0x80)
4508 {
4509 if (destination[coding->produced - 2] < 0xA0)
4510 carryover = 2;
4511 else if (coding->produced >= 3
4512 && destination[coding->produced - 3] >= 0x80
4513 && destination[coding->produced - 3] < 0xA0)
4514 carryover = 3;
4515 }
4516 }
4517 if (carryover > 0)
4518 {
4519 BCOPY_SHORT (destination + coding->produced - carryover,
4520 coding->spec.ccl.eight_bit_carryover,
4521 carryover);
4522 coding->spec.ccl.eight_bit_carryover[carryover] = 0;
4523 coding->produced -= carryover;
4524 }
4525 }
4526 coding->produced = str_as_multibyte (destination, bytes,
4527 coding->produced,
4528 &(coding->produced_char));
4529 }
4530
4531 switch (ccl->status)
4532 {
4533 case CCL_STAT_SUSPEND_BY_SRC:
4534 coding->result = CODING_FINISH_INSUFFICIENT_SRC;
4535 break;
4536 case CCL_STAT_SUSPEND_BY_DST:
4537 coding->result = CODING_FINISH_INSUFFICIENT_DST;
4538 break;
4539 case CCL_STAT_QUIT:
4540 case CCL_STAT_INVALID_CMD:
4541 coding->result = CODING_FINISH_INTERRUPT;
4542 break;
4543 default:
4544 coding->result = CODING_FINISH_NORMAL;
4545 break;
4546 }
4547 return coding->result;
4548 }
4549
4550 /* Decode EOL format of the text at PTR of BYTES length destructively
4551 according to CODING->eol_type. This is called after the CCL
4552 program produced a decoded text at PTR. If we do CRLF->LF
4553 conversion, update CODING->produced and CODING->produced_char. */
4554
4555 static void
4556 decode_eol_post_ccl (coding, ptr, bytes)
4557 struct coding_system *coding;
4558 unsigned char *ptr;
4559 int bytes;
4560 {
4561 Lisp_Object val, saved_coding_symbol;
4562 unsigned char *pend = ptr + bytes;
4563 int dummy;
4564
4565 /* Remember the current coding system symbol. We set it back when
4566 an inconsistent EOL is found so that `last-coding-system-used' is
4567 set to the coding system that doesn't specify EOL conversion. */
4568 saved_coding_symbol = coding->symbol;
4569
4570 coding->spec.ccl.cr_carryover = 0;
4571 if (coding->eol_type == CODING_EOL_UNDECIDED)
4572 {
4573 /* Here, to avoid the call of setup_coding_system, we directly
4574 call detect_eol_type. */
4575 coding->eol_type = detect_eol_type (ptr, bytes, &dummy);
4576 if (coding->eol_type == CODING_EOL_INCONSISTENT)
4577 coding->eol_type = CODING_EOL_LF;
4578 if (coding->eol_type != CODING_EOL_UNDECIDED)
4579 {
4580 val = Fget (coding->symbol, Qeol_type);
4581 if (VECTORP (val) && XVECTOR (val)->size == 3)
4582 coding->symbol = XVECTOR (val)->contents[coding->eol_type];
4583 }
4584 coding->mode |= CODING_MODE_INHIBIT_INCONSISTENT_EOL;
4585 }
4586
4587 if (coding->eol_type == CODING_EOL_LF
4588 || coding->eol_type == CODING_EOL_UNDECIDED)
4589 {
4590 /* We have nothing to do. */
4591 ptr = pend;
4592 }
4593 else if (coding->eol_type == CODING_EOL_CRLF)
4594 {
4595 unsigned char *pstart = ptr, *p = ptr;
4596
4597 if (! (coding->mode & CODING_MODE_LAST_BLOCK)
4598 && *(pend - 1) == '\r')
4599 {
4600 /* If the last character is CR, we can't handle it here
4601 because LF will be in the not-yet-decoded source text.
4602 Record that the CR is not yet processed. */
4603 coding->spec.ccl.cr_carryover = 1;
4604 coding->produced--;
4605 coding->produced_char--;
4606 pend--;
4607 }
4608 while (ptr < pend)
4609 {
4610 if (*ptr == '\r')
4611 {
4612 if (ptr + 1 < pend && *(ptr + 1) == '\n')
4613 {
4614 *p++ = '\n';
4615 ptr += 2;
4616 }
4617 else
4618 {
4619 if (coding->mode & CODING_MODE_INHIBIT_INCONSISTENT_EOL)
4620 goto undo_eol_conversion;
4621 *p++ = *ptr++;
4622 }
4623 }
4624 else if (*ptr == '\n'
4625 && coding->mode & CODING_MODE_INHIBIT_INCONSISTENT_EOL)
4626 goto undo_eol_conversion;
4627 else
4628 *p++ = *ptr++;
4629 continue;
4630
4631 undo_eol_conversion:
4632 /* We have faced with inconsistent EOL format at PTR.
4633 Convert all LFs before PTR back to CRLFs. */
4634 for (p--, ptr--; p >= pstart; p--)
4635 {
4636 if (*p == '\n')
4637 *ptr-- = '\n', *ptr-- = '\r';
4638 else
4639 *ptr-- = *p;
4640 }
4641 /* If carryover is recorded, cancel it because we don't
4642 convert CRLF anymore. */
4643 if (coding->spec.ccl.cr_carryover)
4644 {
4645 coding->spec.ccl.cr_carryover = 0;
4646 coding->produced++;
4647 coding->produced_char++;
4648 pend++;
4649 }
4650 p = ptr = pend;
4651 coding->eol_type = CODING_EOL_LF;
4652 coding->symbol = saved_coding_symbol;
4653 }
4654 if (p < pend)
4655 {
4656 /* As each two-byte sequence CRLF was converted to LF, (PEND
4657 - P) is the number of deleted characters. */
4658 coding->produced -= pend - p;
4659 coding->produced_char -= pend - p;
4660 }
4661 }
4662 else /* i.e. coding->eol_type == CODING_EOL_CR */
4663 {
4664 unsigned char *p = ptr;
4665
4666 for (; ptr < pend; ptr++)
4667 {
4668 if (*ptr == '\r')
4669 *ptr = '\n';
4670 else if (*ptr == '\n'
4671 && coding->mode & CODING_MODE_INHIBIT_INCONSISTENT_EOL)
4672 {
4673 for (; p < ptr; p++)
4674 {
4675 if (*p == '\n')
4676 *p = '\r';
4677 }
4678 ptr = pend;
4679 coding->eol_type = CODING_EOL_LF;
4680 coding->symbol = saved_coding_symbol;
4681 }
4682 }
4683 }
4684 }
4685
4686 /* See "GENERAL NOTES about `decode_coding_XXX ()' functions". Before
4687 decoding, it may detect coding system and format of end-of-line if
4688 those are not yet decided. The source should be unibyte, the
4689 result is multibyte if CODING->dst_multibyte is nonzero, else
4690 unibyte. */
4691
4692 int
4693 decode_coding (coding, source, destination, src_bytes, dst_bytes)
4694 struct coding_system *coding;
4695 const unsigned char *source;
4696 unsigned char *destination;
4697 int src_bytes, dst_bytes;
4698 {
4699 int extra = 0;
4700
4701 if (coding->type == coding_type_undecided)
4702 detect_coding (coding, source, src_bytes);
4703
4704 if (coding->eol_type == CODING_EOL_UNDECIDED
4705 && coding->type != coding_type_ccl)
4706 {
4707 detect_eol (coding, source, src_bytes);
4708 /* We had better recover the original eol format if we
4709 encounter an inconsistent eol format while decoding. */
4710 coding->mode |= CODING_MODE_INHIBIT_INCONSISTENT_EOL;
4711 }
4712
4713 coding->produced = coding->produced_char = 0;
4714 coding->consumed = coding->consumed_char = 0;
4715 coding->errors = 0;
4716 coding->result = CODING_FINISH_NORMAL;
4717
4718 switch (coding->type)
4719 {
4720 case coding_type_sjis:
4721 decode_coding_sjis_big5 (coding, source, destination,
4722 src_bytes, dst_bytes, 1);
4723 break;
4724
4725 case coding_type_iso2022:
4726 decode_coding_iso2022 (coding, source, destination,
4727 src_bytes, dst_bytes);
4728 break;
4729
4730 case coding_type_big5:
4731 decode_coding_sjis_big5 (coding, source, destination,
4732 src_bytes, dst_bytes, 0);
4733 break;
4734
4735 case coding_type_emacs_mule:
4736 decode_coding_emacs_mule (coding, source, destination,
4737 src_bytes, dst_bytes);
4738 break;
4739
4740 case coding_type_ccl:
4741 if (coding->spec.ccl.cr_carryover)
4742 {
4743 /* Put the CR which was not processed by the previous call
4744 of decode_eol_post_ccl in DESTINATION. It will be
4745 decoded together with the following LF by the call to
4746 decode_eol_post_ccl below. */
4747 *destination = '\r';
4748 coding->produced++;
4749 coding->produced_char++;
4750 dst_bytes--;
4751 extra = coding->spec.ccl.cr_carryover;
4752 }
4753 ccl_coding_driver (coding, source, destination + extra,
4754 src_bytes, dst_bytes, 0);
4755 if (coding->eol_type != CODING_EOL_LF)
4756 {
4757 coding->produced += extra;
4758 coding->produced_char += extra;
4759 decode_eol_post_ccl (coding, destination, coding->produced);
4760 }
4761 break;
4762
4763 default:
4764 decode_eol (coding, source, destination, src_bytes, dst_bytes);
4765 }
4766
4767 if (coding->result == CODING_FINISH_INSUFFICIENT_SRC
4768 && coding->mode & CODING_MODE_LAST_BLOCK
4769 && coding->consumed == src_bytes)
4770 coding->result = CODING_FINISH_NORMAL;
4771
4772 if (coding->mode & CODING_MODE_LAST_BLOCK
4773 && coding->result == CODING_FINISH_INSUFFICIENT_SRC)
4774 {
4775 const unsigned char *src = source + coding->consumed;
4776 unsigned char *dst = destination + coding->produced;
4777
4778 src_bytes -= coding->consumed;
4779 coding->errors++;
4780 if (COMPOSING_P (coding))
4781 DECODE_COMPOSITION_END ('1');
4782 while (src_bytes--)
4783 {
4784 int c = *src++;
4785 dst += CHAR_STRING (c, dst);
4786 coding->produced_char++;
4787 }
4788 coding->consumed = coding->consumed_char = src - source;
4789 coding->produced = dst - destination;
4790 coding->result = CODING_FINISH_NORMAL;
4791 }
4792
4793 if (!coding->dst_multibyte)
4794 {
4795 coding->produced = str_as_unibyte (destination, coding->produced);
4796 coding->produced_char = coding->produced;
4797 }
4798
4799 return coding->result;
4800 }
4801
4802 /* See "GENERAL NOTES about `encode_coding_XXX ()' functions". The
4803 multibyteness of the source is CODING->src_multibyte, the
4804 multibyteness of the result is always unibyte. */
4805
4806 int
4807 encode_coding (coding, source, destination, src_bytes, dst_bytes)
4808 struct coding_system *coding;
4809 const unsigned char *source;
4810 unsigned char *destination;
4811 int src_bytes, dst_bytes;
4812 {
4813 coding->produced = coding->produced_char = 0;
4814 coding->consumed = coding->consumed_char = 0;
4815 coding->errors = 0;
4816 coding->result = CODING_FINISH_NORMAL;
4817
4818 switch (coding->type)
4819 {
4820 case coding_type_sjis:
4821 encode_coding_sjis_big5 (coding, source, destination,
4822 src_bytes, dst_bytes, 1);
4823 break;
4824
4825 case coding_type_iso2022:
4826 encode_coding_iso2022 (coding, source, destination,
4827 src_bytes, dst_bytes);
4828 break;
4829
4830 case coding_type_big5:
4831 encode_coding_sjis_big5 (coding, source, destination,
4832 src_bytes, dst_bytes, 0);
4833 break;
4834
4835 case coding_type_emacs_mule:
4836 encode_coding_emacs_mule (coding, source, destination,
4837 src_bytes, dst_bytes);
4838 break;
4839
4840 case coding_type_ccl:
4841 ccl_coding_driver (coding, source, destination,
4842 src_bytes, dst_bytes, 1);
4843 break;
4844
4845 default:
4846 encode_eol (coding, source, destination, src_bytes, dst_bytes);
4847 }
4848
4849 if (coding->mode & CODING_MODE_LAST_BLOCK
4850 && coding->result == CODING_FINISH_INSUFFICIENT_SRC)
4851 {
4852 const unsigned char *src = source + coding->consumed;
4853 unsigned char *dst = destination + coding->produced;
4854
4855 if (coding->type == coding_type_iso2022)
4856 ENCODE_RESET_PLANE_AND_REGISTER;
4857 if (COMPOSING_P (coding))
4858 *dst++ = ISO_CODE_ESC, *dst++ = '1';
4859 if (coding->consumed < src_bytes)
4860 {
4861 int len = src_bytes - coding->consumed;
4862
4863 BCOPY_SHORT (src, dst, len);
4864 if (coding->src_multibyte)
4865 len = str_as_unibyte (dst, len);
4866 dst += len;
4867 coding->consumed = src_bytes;
4868 }
4869 coding->produced = coding->produced_char = dst - destination;
4870 coding->result = CODING_FINISH_NORMAL;
4871 }
4872
4873 if (coding->result == CODING_FINISH_INSUFFICIENT_SRC
4874 && coding->consumed == src_bytes)
4875 coding->result = CODING_FINISH_NORMAL;
4876
4877 return coding->result;
4878 }
4879
4880 /* Scan text in the region between *BEG and *END (byte positions),
4881 skip characters which we don't have to decode by coding system
4882 CODING at the head and tail, then set *BEG and *END to the region
4883 of the text we actually have to convert. The caller should move
4884 the gap out of the region in advance if the region is from a
4885 buffer.
4886
4887 If STR is not NULL, *BEG and *END are indices into STR. */
4888
4889 static void
4890 shrink_decoding_region (beg, end, coding, str)
4891 int *beg, *end;
4892 struct coding_system *coding;
4893 unsigned char *str;
4894 {
4895 unsigned char *begp_orig, *begp, *endp_orig, *endp, c;
4896 int eol_conversion;
4897 Lisp_Object translation_table;
4898
4899 if (coding->type == coding_type_ccl
4900 || coding->type == coding_type_undecided
4901 || coding->eol_type != CODING_EOL_LF
4902 || !NILP (coding->post_read_conversion)
4903 || coding->composing != COMPOSITION_DISABLED)
4904 {
4905 /* We can't skip any data. */
4906 return;
4907 }
4908 if (coding->type == coding_type_no_conversion
4909 || coding->type == coding_type_raw_text
4910 || coding->type == coding_type_emacs_mule)
4911 {
4912 /* We need no conversion, but don't have to skip any data here.
4913 Decoding routine handles them effectively anyway. */
4914 return;
4915 }
4916
4917 translation_table = coding->translation_table_for_decode;
4918 if (NILP (translation_table) && !NILP (Venable_character_translation))
4919 translation_table = Vstandard_translation_table_for_decode;
4920 if (CHAR_TABLE_P (translation_table))
4921 {
4922 int i;
4923 for (i = 0; i < 128; i++)
4924 if (!NILP (CHAR_TABLE_REF (translation_table, i)))
4925 break;
4926 if (i < 128)
4927 /* Some ASCII character should be translated. We give up
4928 shrinking. */
4929 return;
4930 }
4931
4932 if (coding->heading_ascii >= 0)
4933 /* Detection routine has already found how much we can skip at the
4934 head. */
4935 *beg += coding->heading_ascii;
4936
4937 if (str)
4938 {
4939 begp_orig = begp = str + *beg;
4940 endp_orig = endp = str + *end;
4941 }
4942 else
4943 {
4944 begp_orig = begp = BYTE_POS_ADDR (*beg);
4945 endp_orig = endp = begp + *end - *beg;
4946 }
4947
4948 eol_conversion = (coding->eol_type == CODING_EOL_CR
4949 || coding->eol_type == CODING_EOL_CRLF);
4950
4951 switch (coding->type)
4952 {
4953 case coding_type_sjis:
4954 case coding_type_big5:
4955 /* We can skip all ASCII characters at the head. */
4956 if (coding->heading_ascii < 0)
4957 {
4958 if (eol_conversion)
4959 while (begp < endp && *begp < 0x80 && *begp != '\r') begp++;
4960 else
4961 while (begp < endp && *begp < 0x80) begp++;
4962 }
4963 /* We can skip all ASCII characters at the tail except for the
4964 second byte of SJIS or BIG5 code. */
4965 if (eol_conversion)
4966 while (begp < endp && endp[-1] < 0x80 && endp[-1] != '\r') endp--;
4967 else
4968 while (begp < endp && endp[-1] < 0x80) endp--;
4969 /* Do not consider LF as ascii if preceded by CR, since that
4970 confuses eol decoding. */
4971 if (begp < endp && endp < endp_orig && endp[-1] == '\r' && endp[0] == '\n')
4972 endp++;
4973 if (begp < endp && endp < endp_orig && endp[-1] >= 0x80)
4974 endp++;
4975 break;
4976
4977 case coding_type_iso2022:
4978 if (CODING_SPEC_ISO_INITIAL_DESIGNATION (coding, 0) != CHARSET_ASCII)
4979 /* We can't skip any data. */
4980 break;
4981 if (coding->heading_ascii < 0)
4982 {
4983 /* We can skip all ASCII characters at the head except for a
4984 few control codes. */
4985 while (begp < endp && (c = *begp) < 0x80
4986 && c != ISO_CODE_CR && c != ISO_CODE_SO
4987 && c != ISO_CODE_SI && c != ISO_CODE_ESC
4988 && (!eol_conversion || c != ISO_CODE_LF))
4989 begp++;
4990 }
4991 switch (coding->category_idx)
4992 {
4993 case CODING_CATEGORY_IDX_ISO_8_1:
4994 case CODING_CATEGORY_IDX_ISO_8_2:
4995 /* We can skip all ASCII characters at the tail. */
4996 if (eol_conversion)
4997 while (begp < endp && (c = endp[-1]) < 0x80 && c != '\r') endp--;
4998 else
4999 while (begp < endp && endp[-1] < 0x80) endp--;
5000 /* Do not consider LF as ascii if preceded by CR, since that
5001 confuses eol decoding. */
5002 if (begp < endp && endp < endp_orig && endp[-1] == '\r' && endp[0] == '\n')
5003 endp++;
5004 break;
5005
5006 case CODING_CATEGORY_IDX_ISO_7:
5007 case CODING_CATEGORY_IDX_ISO_7_TIGHT:
5008 {
5009 /* We can skip all characters at the tail except for 8-bit
5010 codes and ESC and the following 2-byte at the tail. */
5011 unsigned char *eight_bit = NULL;
5012
5013 if (eol_conversion)
5014 while (begp < endp
5015 && (c = endp[-1]) != ISO_CODE_ESC && c != '\r')
5016 {
5017 if (!eight_bit && c & 0x80) eight_bit = endp;
5018 endp--;
5019 }
5020 else
5021 while (begp < endp
5022 && (c = endp[-1]) != ISO_CODE_ESC)
5023 {
5024 if (!eight_bit && c & 0x80) eight_bit = endp;
5025 endp--;
5026 }
5027 /* Do not consider LF as ascii if preceded by CR, since that
5028 confuses eol decoding. */
5029 if (begp < endp && endp < endp_orig
5030 && endp[-1] == '\r' && endp[0] == '\n')
5031 endp++;
5032 if (begp < endp && endp[-1] == ISO_CODE_ESC)
5033 {
5034 if (endp + 1 < endp_orig && end[0] == '(' && end[1] == 'B')
5035 /* This is an ASCII designation sequence. We can
5036 surely skip the tail. But, if we have
5037 encountered an 8-bit code, skip only the codes
5038 after that. */
5039 endp = eight_bit ? eight_bit : endp + 2;
5040 else
5041 /* Hmmm, we can't skip the tail. */
5042 endp = endp_orig;
5043 }
5044 else if (eight_bit)
5045 endp = eight_bit;
5046 }
5047 }
5048 break;
5049
5050 default:
5051 abort ();
5052 }
5053 *beg += begp - begp_orig;
5054 *end += endp - endp_orig;
5055 return;
5056 }
5057
5058 /* Like shrink_decoding_region but for encoding. */
5059
5060 static void
5061 shrink_encoding_region (beg, end, coding, str)
5062 int *beg, *end;
5063 struct coding_system *coding;
5064 unsigned char *str;
5065 {
5066 unsigned char *begp_orig, *begp, *endp_orig, *endp;
5067 int eol_conversion;
5068 Lisp_Object translation_table;
5069
5070 if (coding->type == coding_type_ccl
5071 || coding->eol_type == CODING_EOL_CRLF
5072 || coding->eol_type == CODING_EOL_CR
5073 || (coding->cmp_data && coding->cmp_data->used > 0))
5074 {
5075 /* We can't skip any data. */
5076 return;
5077 }
5078 if (coding->type == coding_type_no_conversion
5079 || coding->type == coding_type_raw_text
5080 || coding->type == coding_type_emacs_mule
5081 || coding->type == coding_type_undecided)
5082 {
5083 /* We need no conversion, but don't have to skip any data here.
5084 Encoding routine handles them effectively anyway. */
5085 return;
5086 }
5087
5088 translation_table = coding->translation_table_for_encode;
5089 if (NILP (translation_table) && !NILP (Venable_character_translation))
5090 translation_table = Vstandard_translation_table_for_encode;
5091 if (CHAR_TABLE_P (translation_table))
5092 {
5093 int i;
5094 for (i = 0; i < 128; i++)
5095 if (!NILP (CHAR_TABLE_REF (translation_table, i)))
5096 break;
5097 if (i < 128)
5098 /* Some ASCII character should be translated. We give up
5099 shrinking. */
5100 return;
5101 }
5102
5103 if (str)
5104 {
5105 begp_orig = begp = str + *beg;
5106 endp_orig = endp = str + *end;
5107 }
5108 else
5109 {
5110 begp_orig = begp = BYTE_POS_ADDR (*beg);
5111 endp_orig = endp = begp + *end - *beg;
5112 }
5113
5114 eol_conversion = (coding->eol_type == CODING_EOL_CR
5115 || coding->eol_type == CODING_EOL_CRLF);
5116
5117 /* Here, we don't have to check coding->pre_write_conversion because
5118 the caller is expected to have handled it already. */
5119 switch (coding->type)
5120 {
5121 case coding_type_iso2022:
5122 if (CODING_SPEC_ISO_INITIAL_DESIGNATION (coding, 0) != CHARSET_ASCII)
5123 /* We can't skip any data. */
5124 break;
5125 if (coding->flags & CODING_FLAG_ISO_DESIGNATE_AT_BOL)
5126 {
5127 unsigned char *bol = begp;
5128 while (begp < endp && *begp < 0x80)
5129 {
5130 begp++;
5131 if (begp[-1] == '\n')
5132 bol = begp;
5133 }
5134 begp = bol;
5135 goto label_skip_tail;
5136 }
5137 /* fall down ... */
5138
5139 case coding_type_sjis:
5140 case coding_type_big5:
5141 /* We can skip all ASCII characters at the head and tail. */
5142 if (eol_conversion)
5143 while (begp < endp && *begp < 0x80 && *begp != '\n') begp++;
5144 else
5145 while (begp < endp && *begp < 0x80) begp++;
5146 label_skip_tail:
5147 if (eol_conversion)
5148 while (begp < endp && endp[-1] < 0x80 && endp[-1] != '\n') endp--;
5149 else
5150 while (begp < endp && *(endp - 1) < 0x80) endp--;
5151 break;
5152
5153 default:
5154 abort ();
5155 }
5156
5157 *beg += begp - begp_orig;
5158 *end += endp - endp_orig;
5159 return;
5160 }
5161
5162 /* As shrinking conversion region requires some overhead, we don't try
5163 shrinking if the length of conversion region is less than this
5164 value. */
5165 static int shrink_conversion_region_threshhold = 1024;
5166
5167 #define SHRINK_CONVERSION_REGION(beg, end, coding, str, encodep) \
5168 do { \
5169 if (*(end) - *(beg) > shrink_conversion_region_threshhold) \
5170 { \
5171 if (encodep) shrink_encoding_region (beg, end, coding, str); \
5172 else shrink_decoding_region (beg, end, coding, str); \
5173 } \
5174 } while (0)
5175
5176 static Lisp_Object
5177 code_convert_region_unwind (dummy)
5178 Lisp_Object dummy;
5179 {
5180 inhibit_pre_post_conversion = 0;
5181 return Qnil;
5182 }
5183
5184 /* Store information about all compositions in the range FROM and TO
5185 of OBJ in memory blocks pointed by CODING->cmp_data. OBJ is a
5186 buffer or a string, defaults to the current buffer. */
5187
5188 void
5189 coding_save_composition (coding, from, to, obj)
5190 struct coding_system *coding;
5191 int from, to;
5192 Lisp_Object obj;
5193 {
5194 Lisp_Object prop;
5195 int start, end;
5196
5197 if (coding->composing == COMPOSITION_DISABLED)
5198 return;
5199 if (!coding->cmp_data)
5200 coding_allocate_composition_data (coding, from);
5201 if (!find_composition (from, to, &start, &end, &prop, obj)
5202 || end > to)
5203 return;
5204 if (start < from
5205 && (!find_composition (end, to, &start, &end, &prop, obj)
5206 || end > to))
5207 return;
5208 coding->composing = COMPOSITION_NO;
5209 do
5210 {
5211 if (COMPOSITION_VALID_P (start, end, prop))
5212 {
5213 enum composition_method method = COMPOSITION_METHOD (prop);
5214 if (coding->cmp_data->used + COMPOSITION_DATA_MAX_BUNCH_LENGTH
5215 >= COMPOSITION_DATA_SIZE)
5216 coding_allocate_composition_data (coding, from);
5217 /* For relative composition, we remember start and end
5218 positions, for the other compositions, we also remember
5219 components. */
5220 CODING_ADD_COMPOSITION_START (coding, start - from, method);
5221 if (method != COMPOSITION_RELATIVE)
5222 {
5223 /* We must store a*/
5224 Lisp_Object val, ch;
5225
5226 val = COMPOSITION_COMPONENTS (prop);
5227 if (CONSP (val))
5228 while (CONSP (val))
5229 {
5230 ch = XCAR (val), val = XCDR (val);
5231 CODING_ADD_COMPOSITION_COMPONENT (coding, XINT (ch));
5232 }
5233 else if (VECTORP (val) || STRINGP (val))
5234 {
5235 int len = (VECTORP (val)
5236 ? XVECTOR (val)->size : SCHARS (val));
5237 int i;
5238 for (i = 0; i < len; i++)
5239 {
5240 ch = (STRINGP (val)
5241 ? Faref (val, make_number (i))
5242 : XVECTOR (val)->contents[i]);
5243 CODING_ADD_COMPOSITION_COMPONENT (coding, XINT (ch));
5244 }
5245 }
5246 else /* INTEGERP (val) */
5247 CODING_ADD_COMPOSITION_COMPONENT (coding, XINT (val));
5248 }
5249 CODING_ADD_COMPOSITION_END (coding, end - from);
5250 }
5251 start = end;
5252 }
5253 while (start < to
5254 && find_composition (start, to, &start, &end, &prop, obj)
5255 && end <= to);
5256
5257 /* Make coding->cmp_data point to the first memory block. */
5258 while (coding->cmp_data->prev)
5259 coding->cmp_data = coding->cmp_data->prev;
5260 coding->cmp_data_start = 0;
5261 }
5262
5263 /* Reflect the saved information about compositions to OBJ.
5264 CODING->cmp_data points to a memory block for the information. OBJ
5265 is a buffer or a string, defaults to the current buffer. */
5266
5267 void
5268 coding_restore_composition (coding, obj)
5269 struct coding_system *coding;
5270 Lisp_Object obj;
5271 {
5272 struct composition_data *cmp_data = coding->cmp_data;
5273
5274 if (!cmp_data)
5275 return;
5276
5277 while (cmp_data->prev)
5278 cmp_data = cmp_data->prev;
5279
5280 while (cmp_data)
5281 {
5282 int i;
5283
5284 for (i = 0; i < cmp_data->used && cmp_data->data[i] > 0;
5285 i += cmp_data->data[i])
5286 {
5287 int *data = cmp_data->data + i;
5288 enum composition_method method = (enum composition_method) data[3];
5289 Lisp_Object components;
5290
5291 if (method == COMPOSITION_RELATIVE)
5292 components = Qnil;
5293 else
5294 {
5295 int len = data[0] - 4, j;
5296 Lisp_Object args[MAX_COMPOSITION_COMPONENTS * 2 - 1];
5297
5298 for (j = 0; j < len; j++)
5299 args[j] = make_number (data[4 + j]);
5300 components = (method == COMPOSITION_WITH_ALTCHARS
5301 ? Fstring (len, args) : Fvector (len, args));
5302 }
5303 compose_text (data[1], data[2], components, Qnil, obj);
5304 }
5305 cmp_data = cmp_data->next;
5306 }
5307 }
5308
5309 /* Decode (if ENCODEP is zero) or encode (if ENCODEP is nonzero) the
5310 text from FROM to TO (byte positions are FROM_BYTE and TO_BYTE) by
5311 coding system CODING, and return the status code of code conversion
5312 (currently, this value has no meaning).
5313
5314 How many characters (and bytes) are converted to how many
5315 characters (and bytes) are recorded in members of the structure
5316 CODING.
5317
5318 If REPLACE is nonzero, we do various things as if the original text
5319 is deleted and a new text is inserted. See the comments in
5320 replace_range (insdel.c) to know what we are doing.
5321
5322 If REPLACE is zero, it is assumed that the source text is unibyte.
5323 Otherwise, it is assumed that the source text is multibyte. */
5324
5325 int
5326 code_convert_region (from, from_byte, to, to_byte, coding, encodep, replace)
5327 int from, from_byte, to, to_byte, encodep, replace;
5328 struct coding_system *coding;
5329 {
5330 int len = to - from, len_byte = to_byte - from_byte;
5331 int nchars_del = 0, nbytes_del = 0;
5332 int require, inserted, inserted_byte;
5333 int head_skip, tail_skip, total_skip = 0;
5334 Lisp_Object saved_coding_symbol;
5335 int first = 1;
5336 unsigned char *src, *dst;
5337 Lisp_Object deletion;
5338 int orig_point = PT, orig_len = len;
5339 int prev_Z;
5340 int multibyte_p = !NILP (current_buffer->enable_multibyte_characters);
5341
5342 deletion = Qnil;
5343 saved_coding_symbol = coding->symbol;
5344
5345 if (from < PT && PT < to)
5346 {
5347 TEMP_SET_PT_BOTH (from, from_byte);
5348 orig_point = from;
5349 }
5350
5351 if (replace)
5352 {
5353 int saved_from = from;
5354 int saved_inhibit_modification_hooks;
5355
5356 prepare_to_modify_buffer (from, to, &from);
5357 if (saved_from != from)
5358 {
5359 to = from + len;
5360 from_byte = CHAR_TO_BYTE (from), to_byte = CHAR_TO_BYTE (to);
5361 len_byte = to_byte - from_byte;
5362 }
5363
5364 /* The code conversion routine can not preserve text properties
5365 for now. So, we must remove all text properties in the
5366 region. Here, we must suppress all modification hooks. */
5367 saved_inhibit_modification_hooks = inhibit_modification_hooks;
5368 inhibit_modification_hooks = 1;
5369 Fset_text_properties (make_number (from), make_number (to), Qnil, Qnil);
5370 inhibit_modification_hooks = saved_inhibit_modification_hooks;
5371 }
5372
5373 if (! encodep && CODING_REQUIRE_DETECTION (coding))
5374 {
5375 /* We must detect encoding of text and eol format. */
5376
5377 if (from < GPT && to > GPT)
5378 move_gap_both (from, from_byte);
5379 if (coding->type == coding_type_undecided)
5380 {
5381 detect_coding (coding, BYTE_POS_ADDR (from_byte), len_byte);
5382 if (coding->type == coding_type_undecided)
5383 {
5384 /* It seems that the text contains only ASCII, but we
5385 should not leave it undecided because the deeper
5386 decoding routine (decode_coding) tries to detect the
5387 encodings again in vain. */
5388 coding->type = coding_type_emacs_mule;
5389 coding->category_idx = CODING_CATEGORY_IDX_EMACS_MULE;
5390 /* As emacs-mule decoder will handle composition, we
5391 need this setting to allocate coding->cmp_data
5392 later. */
5393 coding->composing = COMPOSITION_NO;
5394 }
5395 }
5396 if (coding->eol_type == CODING_EOL_UNDECIDED
5397 && coding->type != coding_type_ccl)
5398 {
5399 detect_eol (coding, BYTE_POS_ADDR (from_byte), len_byte);
5400 if (coding->eol_type == CODING_EOL_UNDECIDED)
5401 coding->eol_type = CODING_EOL_LF;
5402 /* We had better recover the original eol format if we
5403 encounter an inconsistent eol format while decoding. */
5404 coding->mode |= CODING_MODE_INHIBIT_INCONSISTENT_EOL;
5405 }
5406 }
5407
5408 /* Now we convert the text. */
5409
5410 /* For encoding, we must process pre-write-conversion in advance. */
5411 if (! inhibit_pre_post_conversion
5412 && encodep
5413 && SYMBOLP (coding->pre_write_conversion)
5414 && ! NILP (Ffboundp (coding->pre_write_conversion)))
5415 {
5416 /* The function in pre-write-conversion may put a new text in a
5417 new buffer. */
5418 struct buffer *prev = current_buffer;
5419 Lisp_Object new;
5420
5421 record_unwind_protect (code_convert_region_unwind, Qnil);
5422 /* We should not call any more pre-write/post-read-conversion
5423 functions while this pre-write-conversion is running. */
5424 inhibit_pre_post_conversion = 1;
5425 call2 (coding->pre_write_conversion,
5426 make_number (from), make_number (to));
5427 inhibit_pre_post_conversion = 0;
5428 /* Discard the unwind protect. */
5429 specpdl_ptr--;
5430
5431 if (current_buffer != prev)
5432 {
5433 len = ZV - BEGV;
5434 new = Fcurrent_buffer ();
5435 set_buffer_internal_1 (prev);
5436 del_range_2 (from, from_byte, to, to_byte, 0);
5437 TEMP_SET_PT_BOTH (from, from_byte);
5438 insert_from_buffer (XBUFFER (new), 1, len, 0);
5439 Fkill_buffer (new);
5440 if (orig_point >= to)
5441 orig_point += len - orig_len;
5442 else if (orig_point > from)
5443 orig_point = from;
5444 orig_len = len;
5445 to = from + len;
5446 from_byte = CHAR_TO_BYTE (from);
5447 to_byte = CHAR_TO_BYTE (to);
5448 len_byte = to_byte - from_byte;
5449 TEMP_SET_PT_BOTH (from, from_byte);
5450 }
5451 }
5452
5453 if (replace)
5454 {
5455 if (! EQ (current_buffer->undo_list, Qt))
5456 deletion = make_buffer_string_both (from, from_byte, to, to_byte, 1);
5457 else
5458 {
5459 nchars_del = to - from;
5460 nbytes_del = to_byte - from_byte;
5461 }
5462 }
5463
5464 if (coding->composing != COMPOSITION_DISABLED)
5465 {
5466 if (encodep)
5467 coding_save_composition (coding, from, to, Fcurrent_buffer ());
5468 else
5469 coding_allocate_composition_data (coding, from);
5470 }
5471
5472 /* Try to skip the heading and tailing ASCIIs. */
5473 if (coding->type != coding_type_ccl)
5474 {
5475 int from_byte_orig = from_byte, to_byte_orig = to_byte;
5476
5477 if (from < GPT && GPT < to)
5478 move_gap_both (from, from_byte);
5479 SHRINK_CONVERSION_REGION (&from_byte, &to_byte, coding, NULL, encodep);
5480 if (from_byte == to_byte
5481 && (encodep || NILP (coding->post_read_conversion))
5482 && ! CODING_REQUIRE_FLUSHING (coding))
5483 {
5484 coding->produced = len_byte;
5485 coding->produced_char = len;
5486 if (!replace)
5487 /* We must record and adjust for this new text now. */
5488 adjust_after_insert (from, from_byte_orig, to, to_byte_orig, len);
5489 return 0;
5490 }
5491
5492 head_skip = from_byte - from_byte_orig;
5493 tail_skip = to_byte_orig - to_byte;
5494 total_skip = head_skip + tail_skip;
5495 from += head_skip;
5496 to -= tail_skip;
5497 len -= total_skip; len_byte -= total_skip;
5498 }
5499
5500 /* For conversion, we must put the gap before the text in addition to
5501 making the gap larger for efficient decoding. The required gap
5502 size starts from 2000 which is the magic number used in make_gap.
5503 But, after one batch of conversion, it will be incremented if we
5504 find that it is not enough . */
5505 require = 2000;
5506
5507 if (GAP_SIZE < require)
5508 make_gap (require - GAP_SIZE);
5509 move_gap_both (from, from_byte);
5510
5511 inserted = inserted_byte = 0;
5512
5513 GAP_SIZE += len_byte;
5514 ZV -= len;
5515 Z -= len;
5516 ZV_BYTE -= len_byte;
5517 Z_BYTE -= len_byte;
5518
5519 if (GPT - BEG < BEG_UNCHANGED)
5520 BEG_UNCHANGED = GPT - BEG;
5521 if (Z - GPT < END_UNCHANGED)
5522 END_UNCHANGED = Z - GPT;
5523
5524 if (!encodep && coding->src_multibyte)
5525 {
5526 /* Decoding routines expects that the source text is unibyte.
5527 We must convert 8-bit characters of multibyte form to
5528 unibyte. */
5529 int len_byte_orig = len_byte;
5530 len_byte = str_as_unibyte (GAP_END_ADDR - len_byte, len_byte);
5531 if (len_byte < len_byte_orig)
5532 safe_bcopy (GAP_END_ADDR - len_byte_orig, GAP_END_ADDR - len_byte,
5533 len_byte);
5534 coding->src_multibyte = 0;
5535 }
5536
5537 for (;;)
5538 {
5539 int result;
5540
5541 /* The buffer memory is now:
5542 +--------+converted-text+---------+-------original-text-------+---+
5543 |<-from->|<--inserted-->|---------|<--------len_byte--------->|---|
5544 |<---------------------- GAP ----------------------->| */
5545 src = GAP_END_ADDR - len_byte;
5546 dst = GPT_ADDR + inserted_byte;
5547
5548 if (encodep)
5549 result = encode_coding (coding, src, dst, len_byte, 0);
5550 else
5551 {
5552 if (coding->composing != COMPOSITION_DISABLED)
5553 coding->cmp_data->char_offset = from + inserted;
5554 result = decode_coding (coding, src, dst, len_byte, 0);
5555 }
5556
5557 /* The buffer memory is now:
5558 +--------+-------converted-text----+--+------original-text----+---+
5559 |<-from->|<-inserted->|<-produced->|--|<-(len_byte-consumed)->|---|
5560 |<---------------------- GAP ----------------------->| */
5561
5562 inserted += coding->produced_char;
5563 inserted_byte += coding->produced;
5564 len_byte -= coding->consumed;
5565
5566 if (result == CODING_FINISH_INSUFFICIENT_CMP)
5567 {
5568 coding_allocate_composition_data (coding, from + inserted);
5569 continue;
5570 }
5571
5572 src += coding->consumed;
5573 dst += coding->produced;
5574
5575 if (result == CODING_FINISH_NORMAL)
5576 {
5577 src += len_byte;
5578 break;
5579 }
5580 if (! encodep && result == CODING_FINISH_INCONSISTENT_EOL)
5581 {
5582 unsigned char *pend = dst, *p = pend - inserted_byte;
5583 Lisp_Object eol_type;
5584
5585 /* Encode LFs back to the original eol format (CR or CRLF). */
5586 if (coding->eol_type == CODING_EOL_CR)
5587 {
5588 while (p < pend) if (*p++ == '\n') p[-1] = '\r';
5589 }
5590 else
5591 {
5592 int count = 0;
5593
5594 while (p < pend) if (*p++ == '\n') count++;
5595 if (src - dst < count)
5596 {
5597 /* We don't have sufficient room for encoding LFs
5598 back to CRLF. We must record converted and
5599 not-yet-converted text back to the buffer
5600 content, enlarge the gap, then record them out of
5601 the buffer contents again. */
5602 int add = len_byte + inserted_byte;
5603
5604 GAP_SIZE -= add;
5605 ZV += add; Z += add; ZV_BYTE += add; Z_BYTE += add;
5606 GPT += inserted_byte; GPT_BYTE += inserted_byte;
5607 make_gap (count - GAP_SIZE);
5608 GAP_SIZE += add;
5609 ZV -= add; Z -= add; ZV_BYTE -= add; Z_BYTE -= add;
5610 GPT -= inserted_byte; GPT_BYTE -= inserted_byte;
5611 /* Don't forget to update SRC, DST, and PEND. */
5612 src = GAP_END_ADDR - len_byte;
5613 dst = GPT_ADDR + inserted_byte;
5614 pend = dst;
5615 }
5616 inserted += count;
5617 inserted_byte += count;
5618 coding->produced += count;
5619 p = dst = pend + count;
5620 while (count)
5621 {
5622 *--p = *--pend;
5623 if (*p == '\n') count--, *--p = '\r';
5624 }
5625 }
5626
5627 /* Suppress eol-format conversion in the further conversion. */
5628 coding->eol_type = CODING_EOL_LF;
5629
5630 /* Set the coding system symbol to that for Unix-like EOL. */
5631 eol_type = Fget (saved_coding_symbol, Qeol_type);
5632 if (VECTORP (eol_type)
5633 && XVECTOR (eol_type)->size == 3
5634 && SYMBOLP (XVECTOR (eol_type)->contents[CODING_EOL_LF]))
5635 coding->symbol = XVECTOR (eol_type)->contents[CODING_EOL_LF];
5636 else
5637 coding->symbol = saved_coding_symbol;
5638
5639 continue;
5640 }
5641 if (len_byte <= 0)
5642 {
5643 if (coding->type != coding_type_ccl
5644 || coding->mode & CODING_MODE_LAST_BLOCK)
5645 break;
5646 coding->mode |= CODING_MODE_LAST_BLOCK;
5647 continue;
5648 }
5649 if (result == CODING_FINISH_INSUFFICIENT_SRC)
5650 {
5651 /* The source text ends in invalid codes. Let's just
5652 make them valid buffer contents, and finish conversion. */
5653 if (multibyte_p)
5654 {
5655 unsigned char *start = dst;
5656
5657 inserted += len_byte;
5658 while (len_byte--)
5659 {
5660 int c = *src++;
5661 dst += CHAR_STRING (c, dst);
5662 }
5663
5664 inserted_byte += dst - start;
5665 }
5666 else
5667 {
5668 inserted += len_byte;
5669 inserted_byte += len_byte;
5670 while (len_byte--)
5671 *dst++ = *src++;
5672 }
5673 break;
5674 }
5675 if (result == CODING_FINISH_INTERRUPT)
5676 {
5677 /* The conversion procedure was interrupted by a user. */
5678 break;
5679 }
5680 /* Now RESULT == CODING_FINISH_INSUFFICIENT_DST */
5681 if (coding->consumed < 1)
5682 {
5683 /* It's quite strange to require more memory without
5684 consuming any bytes. Perhaps CCL program bug. */
5685 break;
5686 }
5687 if (first)
5688 {
5689 /* We have just done the first batch of conversion which was
5690 stopped because of insufficient gap. Let's reconsider the
5691 required gap size (i.e. SRT - DST) now.
5692
5693 We have converted ORIG bytes (== coding->consumed) into
5694 NEW bytes (coding->produced). To convert the remaining
5695 LEN bytes, we may need REQUIRE bytes of gap, where:
5696 REQUIRE + LEN_BYTE = LEN_BYTE * (NEW / ORIG)
5697 REQUIRE = LEN_BYTE * (NEW - ORIG) / ORIG
5698 Here, we are sure that NEW >= ORIG. */
5699 float ratio;
5700
5701 if (coding->produced <= coding->consumed)
5702 {
5703 /* This happens because of CCL-based coding system with
5704 eol-type CRLF. */
5705 require = 0;
5706 }
5707 else
5708 {
5709 ratio = (coding->produced - coding->consumed) / coding->consumed;
5710 require = len_byte * ratio;
5711 }
5712 first = 0;
5713 }
5714 if ((src - dst) < (require + 2000))
5715 {
5716 /* See the comment above the previous call of make_gap. */
5717 int add = len_byte + inserted_byte;
5718
5719 GAP_SIZE -= add;
5720 ZV += add; Z += add; ZV_BYTE += add; Z_BYTE += add;
5721 GPT += inserted_byte; GPT_BYTE += inserted_byte;
5722 make_gap (require + 2000);
5723 GAP_SIZE += add;
5724 ZV -= add; Z -= add; ZV_BYTE -= add; Z_BYTE -= add;
5725 GPT -= inserted_byte; GPT_BYTE -= inserted_byte;
5726 }
5727 }
5728 if (src - dst > 0) *dst = 0; /* Put an anchor. */
5729
5730 if (encodep && coding->dst_multibyte)
5731 {
5732 /* The output is unibyte. We must convert 8-bit characters to
5733 multibyte form. */
5734 if (inserted_byte * 2 > GAP_SIZE)
5735 {
5736 GAP_SIZE -= inserted_byte;
5737 ZV += inserted_byte; Z += inserted_byte;
5738 ZV_BYTE += inserted_byte; Z_BYTE += inserted_byte;
5739 GPT += inserted_byte; GPT_BYTE += inserted_byte;
5740 make_gap (inserted_byte - GAP_SIZE);
5741 GAP_SIZE += inserted_byte;
5742 ZV -= inserted_byte; Z -= inserted_byte;
5743 ZV_BYTE -= inserted_byte; Z_BYTE -= inserted_byte;
5744 GPT -= inserted_byte; GPT_BYTE -= inserted_byte;
5745 }
5746 inserted_byte = str_to_multibyte (GPT_ADDR, GAP_SIZE, inserted_byte);
5747 }
5748
5749 /* If we shrank the conversion area, adjust it now. */
5750 if (total_skip > 0)
5751 {
5752 if (tail_skip > 0)
5753 safe_bcopy (GAP_END_ADDR, GPT_ADDR + inserted_byte, tail_skip);
5754 inserted += total_skip; inserted_byte += total_skip;
5755 GAP_SIZE += total_skip;
5756 GPT -= head_skip; GPT_BYTE -= head_skip;
5757 ZV -= total_skip; ZV_BYTE -= total_skip;
5758 Z -= total_skip; Z_BYTE -= total_skip;
5759 from -= head_skip; from_byte -= head_skip;
5760 to += tail_skip; to_byte += tail_skip;
5761 }
5762
5763 prev_Z = Z;
5764 if (! EQ (current_buffer->undo_list, Qt))
5765 adjust_after_replace (from, from_byte, deletion, inserted, inserted_byte);
5766 else
5767 adjust_after_replace_noundo (from, from_byte, nchars_del, nbytes_del,
5768 inserted, inserted_byte);
5769 inserted = Z - prev_Z;
5770
5771 if (!encodep && coding->cmp_data && coding->cmp_data->used)
5772 coding_restore_composition (coding, Fcurrent_buffer ());
5773 coding_free_composition_data (coding);
5774
5775 if (! inhibit_pre_post_conversion
5776 && ! encodep && ! NILP (coding->post_read_conversion))
5777 {
5778 Lisp_Object val;
5779
5780 if (from != PT)
5781 TEMP_SET_PT_BOTH (from, from_byte);
5782 prev_Z = Z;
5783 record_unwind_protect (code_convert_region_unwind, Qnil);
5784 /* We should not call any more pre-write/post-read-conversion
5785 functions while this post-read-conversion is running. */
5786 inhibit_pre_post_conversion = 1;
5787 val = call1 (coding->post_read_conversion, make_number (inserted));
5788 inhibit_pre_post_conversion = 0;
5789 /* Discard the unwind protect. */
5790 specpdl_ptr--;
5791 CHECK_NUMBER (val);
5792 inserted += Z - prev_Z;
5793 }
5794
5795 if (orig_point >= from)
5796 {
5797 if (orig_point >= from + orig_len)
5798 orig_point += inserted - orig_len;
5799 else
5800 orig_point = from;
5801 TEMP_SET_PT (orig_point);
5802 }
5803
5804 if (replace)
5805 {
5806 signal_after_change (from, to - from, inserted);
5807 update_compositions (from, from + inserted, CHECK_BORDER);
5808 }
5809
5810 {
5811 coding->consumed = to_byte - from_byte;
5812 coding->consumed_char = to - from;
5813 coding->produced = inserted_byte;
5814 coding->produced_char = inserted;
5815 }
5816
5817 return 0;
5818 }
5819
5820 Lisp_Object
5821 run_pre_post_conversion_on_str (str, coding, encodep)
5822 Lisp_Object str;
5823 struct coding_system *coding;
5824 int encodep;
5825 {
5826 int count = SPECPDL_INDEX ();
5827 struct gcpro gcpro1, gcpro2;
5828 int multibyte = STRING_MULTIBYTE (str);
5829 Lisp_Object buffer;
5830 struct buffer *buf;
5831 Lisp_Object old_deactivate_mark;
5832
5833 record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
5834 record_unwind_protect (code_convert_region_unwind, Qnil);
5835 /* It is not crucial to specbind this. */
5836 old_deactivate_mark = Vdeactivate_mark;
5837 GCPRO2 (str, old_deactivate_mark);
5838
5839 buffer = Fget_buffer_create (build_string (" *code-converting-work*"));
5840 buf = XBUFFER (buffer);
5841
5842 buf->directory = current_buffer->directory;
5843 buf->read_only = Qnil;
5844 buf->filename = Qnil;
5845 buf->undo_list = Qt;
5846 buf->overlays_before = Qnil;
5847 buf->overlays_after = Qnil;
5848
5849 set_buffer_internal (buf);
5850 /* We must insert the contents of STR as is without
5851 unibyte<->multibyte conversion. For that, we adjust the
5852 multibyteness of the working buffer to that of STR. */
5853 Ferase_buffer ();
5854 buf->enable_multibyte_characters = multibyte ? Qt : Qnil;
5855
5856 insert_from_string (str, 0, 0,
5857 SCHARS (str), SBYTES (str), 0);
5858 UNGCPRO;
5859 inhibit_pre_post_conversion = 1;
5860 if (encodep)
5861 call2 (coding->pre_write_conversion, make_number (BEG), make_number (Z));
5862 else
5863 {
5864 TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
5865 call1 (coding->post_read_conversion, make_number (Z - BEG));
5866 }
5867 inhibit_pre_post_conversion = 0;
5868 Vdeactivate_mark = old_deactivate_mark;
5869 str = make_buffer_string (BEG, Z, 1);
5870 return unbind_to (count, str);
5871 }
5872
5873 Lisp_Object
5874 decode_coding_string (str, coding, nocopy)
5875 Lisp_Object str;
5876 struct coding_system *coding;
5877 int nocopy;
5878 {
5879 int len;
5880 struct conversion_buffer buf;
5881 int from, to_byte;
5882 Lisp_Object saved_coding_symbol;
5883 int result;
5884 int require_decoding;
5885 int shrinked_bytes = 0;
5886 Lisp_Object newstr;
5887 int consumed, consumed_char, produced, produced_char;
5888
5889 from = 0;
5890 to_byte = SBYTES (str);
5891
5892 saved_coding_symbol = coding->symbol;
5893 coding->src_multibyte = STRING_MULTIBYTE (str);
5894 coding->dst_multibyte = 1;
5895 if (CODING_REQUIRE_DETECTION (coding))
5896 {
5897 /* See the comments in code_convert_region. */
5898 if (coding->type == coding_type_undecided)
5899 {
5900 detect_coding (coding, SDATA (str), to_byte);
5901 if (coding->type == coding_type_undecided)
5902 {
5903 coding->type = coding_type_emacs_mule;
5904 coding->category_idx = CODING_CATEGORY_IDX_EMACS_MULE;
5905 /* As emacs-mule decoder will handle composition, we
5906 need this setting to allocate coding->cmp_data
5907 later. */
5908 coding->composing = COMPOSITION_NO;
5909 }
5910 }
5911 if (coding->eol_type == CODING_EOL_UNDECIDED
5912 && coding->type != coding_type_ccl)
5913 {
5914 saved_coding_symbol = coding->symbol;
5915 detect_eol (coding, SDATA (str), to_byte);
5916 if (coding->eol_type == CODING_EOL_UNDECIDED)
5917 coding->eol_type = CODING_EOL_LF;
5918 /* We had better recover the original eol format if we
5919 encounter an inconsistent eol format while decoding. */
5920 coding->mode |= CODING_MODE_INHIBIT_INCONSISTENT_EOL;
5921 }
5922 }
5923
5924 if (coding->type == coding_type_no_conversion
5925 || coding->type == coding_type_raw_text)
5926 coding->dst_multibyte = 0;
5927
5928 require_decoding = CODING_REQUIRE_DECODING (coding);
5929
5930 if (STRING_MULTIBYTE (str))
5931 {
5932 /* Decoding routines expect the source text to be unibyte. */
5933 str = Fstring_as_unibyte (str);
5934 to_byte = SBYTES (str);
5935 nocopy = 1;
5936 coding->src_multibyte = 0;
5937 }
5938
5939 /* Try to skip the heading and tailing ASCIIs. */
5940 if (require_decoding && coding->type != coding_type_ccl)
5941 {
5942 SHRINK_CONVERSION_REGION (&from, &to_byte, coding, SDATA (str),
5943 0);
5944 if (from == to_byte)
5945 require_decoding = 0;
5946 shrinked_bytes = from + (SBYTES (str) - to_byte);
5947 }
5948
5949 if (!require_decoding)
5950 {
5951 coding->consumed = SBYTES (str);
5952 coding->consumed_char = SCHARS (str);
5953 if (coding->dst_multibyte)
5954 {
5955 str = Fstring_as_multibyte (str);
5956 nocopy = 1;
5957 }
5958 coding->produced = SBYTES (str);
5959 coding->produced_char = SCHARS (str);
5960 return (nocopy ? str : Fcopy_sequence (str));
5961 }
5962
5963 if (coding->composing != COMPOSITION_DISABLED)
5964 coding_allocate_composition_data (coding, from);
5965 len = decoding_buffer_size (coding, to_byte - from);
5966 allocate_conversion_buffer (buf, len);
5967
5968 consumed = consumed_char = produced = produced_char = 0;
5969 while (1)
5970 {
5971 result = decode_coding (coding, SDATA (str) + from + consumed,
5972 buf.data + produced, to_byte - from - consumed,
5973 buf.size - produced);
5974 consumed += coding->consumed;
5975 consumed_char += coding->consumed_char;
5976 produced += coding->produced;
5977 produced_char += coding->produced_char;
5978 if (result == CODING_FINISH_NORMAL
5979 || (result == CODING_FINISH_INSUFFICIENT_SRC
5980 && coding->consumed == 0))
5981 break;
5982 if (result == CODING_FINISH_INSUFFICIENT_CMP)
5983 coding_allocate_composition_data (coding, from + produced_char);
5984 else if (result == CODING_FINISH_INSUFFICIENT_DST)
5985 extend_conversion_buffer (&buf);
5986 else if (result == CODING_FINISH_INCONSISTENT_EOL)
5987 {
5988 Lisp_Object eol_type;
5989
5990 /* Recover the original EOL format. */
5991 if (coding->eol_type == CODING_EOL_CR)
5992 {
5993 unsigned char *p;
5994 for (p = buf.data; p < buf.data + produced; p++)
5995 if (*p == '\n') *p = '\r';
5996 }
5997 else if (coding->eol_type == CODING_EOL_CRLF)
5998 {
5999 int num_eol = 0;
6000 unsigned char *p0, *p1;
6001 for (p0 = buf.data, p1 = p0 + produced; p0 < p1; p0++)
6002 if (*p0 == '\n') num_eol++;
6003 if (produced + num_eol >= buf.size)
6004 extend_conversion_buffer (&buf);
6005 for (p0 = buf.data + produced, p1 = p0 + num_eol; p0 > buf.data;)
6006 {
6007 *--p1 = *--p0;
6008 if (*p0 == '\n') *--p1 = '\r';
6009 }
6010 produced += num_eol;
6011 produced_char += num_eol;
6012 }
6013 /* Suppress eol-format conversion in the further conversion. */
6014 coding->eol_type = CODING_EOL_LF;
6015
6016 /* Set the coding system symbol to that for Unix-like EOL. */
6017 eol_type = Fget (saved_coding_symbol, Qeol_type);
6018 if (VECTORP (eol_type)
6019 && XVECTOR (eol_type)->size == 3
6020 && SYMBOLP (XVECTOR (eol_type)->contents[CODING_EOL_LF]))
6021 coding->symbol = XVECTOR (eol_type)->contents[CODING_EOL_LF];
6022 else
6023 coding->symbol = saved_coding_symbol;
6024
6025
6026 }
6027 }
6028
6029 coding->consumed = consumed;
6030 coding->consumed_char = consumed_char;
6031 coding->produced = produced;
6032 coding->produced_char = produced_char;
6033
6034 if (coding->dst_multibyte)
6035 newstr = make_uninit_multibyte_string (produced_char + shrinked_bytes,
6036 produced + shrinked_bytes);
6037 else
6038 newstr = make_uninit_string (produced + shrinked_bytes);
6039 if (from > 0)
6040 STRING_COPYIN (newstr, 0, SDATA (str), from);
6041 STRING_COPYIN (newstr, from, buf.data, produced);
6042 if (shrinked_bytes > from)
6043 STRING_COPYIN (newstr, from + produced,
6044 SDATA (str) + to_byte,
6045 shrinked_bytes - from);
6046 free_conversion_buffer (&buf);
6047
6048 if (coding->cmp_data && coding->cmp_data->used)
6049 coding_restore_composition (coding, newstr);
6050 coding_free_composition_data (coding);
6051
6052 if (SYMBOLP (coding->post_read_conversion)
6053 && !NILP (Ffboundp (coding->post_read_conversion)))
6054 newstr = run_pre_post_conversion_on_str (newstr, coding, 0);
6055
6056 return newstr;
6057 }
6058
6059 Lisp_Object
6060 encode_coding_string (str, coding, nocopy)
6061 Lisp_Object str;
6062 struct coding_system *coding;
6063 int nocopy;
6064 {
6065 int len;
6066 struct conversion_buffer buf;
6067 int from, to, to_byte;
6068 int result;
6069 int shrinked_bytes = 0;
6070 Lisp_Object newstr;
6071 int consumed, consumed_char, produced, produced_char;
6072
6073 if (SYMBOLP (coding->pre_write_conversion)
6074 && !NILP (Ffboundp (coding->pre_write_conversion)))
6075 str = run_pre_post_conversion_on_str (str, coding, 1);
6076
6077 from = 0;
6078 to = SCHARS (str);
6079 to_byte = SBYTES (str);
6080
6081 /* Encoding routines determine the multibyteness of the source text
6082 by coding->src_multibyte. */
6083 coding->src_multibyte = STRING_MULTIBYTE (str);
6084 coding->dst_multibyte = 0;
6085 if (! CODING_REQUIRE_ENCODING (coding))
6086 {
6087 coding->consumed = SBYTES (str);
6088 coding->consumed_char = SCHARS (str);
6089 if (STRING_MULTIBYTE (str))
6090 {
6091 str = Fstring_as_unibyte (str);
6092 nocopy = 1;
6093 }
6094 coding->produced = SBYTES (str);
6095 coding->produced_char = SCHARS (str);
6096 return (nocopy ? str : Fcopy_sequence (str));
6097 }
6098
6099 if (coding->composing != COMPOSITION_DISABLED)
6100 coding_save_composition (coding, from, to, str);
6101
6102 /* Try to skip the heading and tailing ASCIIs. */
6103 if (coding->type != coding_type_ccl)
6104 {
6105 SHRINK_CONVERSION_REGION (&from, &to_byte, coding, SDATA (str),
6106 1);
6107 if (from == to_byte)
6108 return (nocopy ? str : Fcopy_sequence (str));
6109 shrinked_bytes = from + (SBYTES (str) - to_byte);
6110 }
6111
6112 len = encoding_buffer_size (coding, to_byte - from);
6113 allocate_conversion_buffer (buf, len);
6114
6115 consumed = consumed_char = produced = produced_char = 0;
6116 while (1)
6117 {
6118 result = encode_coding (coding, SDATA (str) + from + consumed,
6119 buf.data + produced, to_byte - from - consumed,
6120 buf.size - produced);
6121 consumed += coding->consumed;
6122 consumed_char += coding->consumed_char;
6123 produced += coding->produced;
6124 produced_char += coding->produced_char;
6125 if (result == CODING_FINISH_NORMAL
6126 || (result == CODING_FINISH_INSUFFICIENT_SRC
6127 && coding->consumed == 0))
6128 break;
6129 /* Now result should be CODING_FINISH_INSUFFICIENT_DST. */
6130 extend_conversion_buffer (&buf);
6131 }
6132
6133 coding->consumed = consumed;
6134 coding->consumed_char = consumed_char;
6135 coding->produced = produced;
6136 coding->produced_char = produced_char;
6137
6138 newstr = make_uninit_string (produced + shrinked_bytes);
6139 if (from > 0)
6140 STRING_COPYIN (newstr, 0, SDATA (str), from);
6141 STRING_COPYIN (newstr, from, buf.data, produced);
6142 if (shrinked_bytes > from)
6143 STRING_COPYIN (newstr, from + produced,
6144 SDATA (str) + to_byte,
6145 shrinked_bytes - from);
6146
6147 free_conversion_buffer (&buf);
6148 coding_free_composition_data (coding);
6149
6150 return newstr;
6151 }
6152
6153 \f
6154 #ifdef emacs
6155 /*** 8. Emacs Lisp library functions ***/
6156
6157 DEFUN ("coding-system-p", Fcoding_system_p, Scoding_system_p, 1, 1, 0,
6158 doc: /* Return t if OBJECT is nil or a coding-system.
6159 See the documentation of `make-coding-system' for information
6160 about coding-system objects. */)
6161 (obj)
6162 Lisp_Object obj;
6163 {
6164 if (NILP (obj))
6165 return Qt;
6166 if (!SYMBOLP (obj))
6167 return Qnil;
6168 /* Get coding-spec vector for OBJ. */
6169 obj = Fget (obj, Qcoding_system);
6170 return ((VECTORP (obj) && XVECTOR (obj)->size == 5)
6171 ? Qt : Qnil);
6172 }
6173
6174 DEFUN ("read-non-nil-coding-system", Fread_non_nil_coding_system,
6175 Sread_non_nil_coding_system, 1, 1, 0,
6176 doc: /* Read a coding system from the minibuffer, prompting with string PROMPT. */)
6177 (prompt)
6178 Lisp_Object prompt;
6179 {
6180 Lisp_Object val;
6181 do
6182 {
6183 val = Fcompleting_read (prompt, Vcoding_system_alist, Qnil,
6184 Qt, Qnil, Qcoding_system_history, Qnil, Qnil);
6185 }
6186 while (SCHARS (val) == 0);
6187 return (Fintern (val, Qnil));
6188 }
6189
6190 DEFUN ("read-coding-system", Fread_coding_system, Sread_coding_system, 1, 2, 0,
6191 doc: /* Read a coding system from the minibuffer, prompting with string PROMPT.
6192 If the user enters null input, return second argument DEFAULT-CODING-SYSTEM. */)
6193 (prompt, default_coding_system)
6194 Lisp_Object prompt, default_coding_system;
6195 {
6196 Lisp_Object val;
6197 if (SYMBOLP (default_coding_system))
6198 default_coding_system = SYMBOL_NAME (default_coding_system);
6199 val = Fcompleting_read (prompt, Vcoding_system_alist, Qnil,
6200 Qt, Qnil, Qcoding_system_history,
6201 default_coding_system, Qnil);
6202 return (SCHARS (val) == 0 ? Qnil : Fintern (val, Qnil));
6203 }
6204
6205 DEFUN ("check-coding-system", Fcheck_coding_system, Scheck_coding_system,
6206 1, 1, 0,
6207 doc: /* Check validity of CODING-SYSTEM.
6208 If valid, return CODING-SYSTEM, else signal a `coding-system-error' error.
6209 It is valid if it is a symbol with a non-nil `coding-system' property.
6210 The value of property should be a vector of length 5. */)
6211 (coding_system)
6212 Lisp_Object coding_system;
6213 {
6214 CHECK_SYMBOL (coding_system);
6215 if (!NILP (Fcoding_system_p (coding_system)))
6216 return coding_system;
6217 while (1)
6218 Fsignal (Qcoding_system_error, Fcons (coding_system, Qnil));
6219 }
6220 \f
6221 Lisp_Object
6222 detect_coding_system (src, src_bytes, highest, multibytep)
6223 const unsigned char *src;
6224 int src_bytes, highest;
6225 int multibytep;
6226 {
6227 int coding_mask, eol_type;
6228 Lisp_Object val, tmp;
6229 int dummy;
6230
6231 coding_mask = detect_coding_mask (src, src_bytes, NULL, &dummy, multibytep);
6232 eol_type = detect_eol_type (src, src_bytes, &dummy);
6233 if (eol_type == CODING_EOL_INCONSISTENT)
6234 eol_type = CODING_EOL_UNDECIDED;
6235
6236 if (!coding_mask)
6237 {
6238 val = Qundecided;
6239 if (eol_type != CODING_EOL_UNDECIDED)
6240 {
6241 Lisp_Object val2;
6242 val2 = Fget (Qundecided, Qeol_type);
6243 if (VECTORP (val2))
6244 val = XVECTOR (val2)->contents[eol_type];
6245 }
6246 return (highest ? val : Fcons (val, Qnil));
6247 }
6248
6249 /* At first, gather possible coding systems in VAL. */
6250 val = Qnil;
6251 for (tmp = Vcoding_category_list; CONSP (tmp); tmp = XCDR (tmp))
6252 {
6253 Lisp_Object category_val, category_index;
6254
6255 category_index = Fget (XCAR (tmp), Qcoding_category_index);
6256 category_val = Fsymbol_value (XCAR (tmp));
6257 if (!NILP (category_val)
6258 && NATNUMP (category_index)
6259 && (coding_mask & (1 << XFASTINT (category_index))))
6260 {
6261 val = Fcons (category_val, val);
6262 if (highest)
6263 break;
6264 }
6265 }
6266 if (!highest)
6267 val = Fnreverse (val);
6268
6269 /* Then, replace the elements with subsidiary coding systems. */
6270 for (tmp = val; CONSP (tmp); tmp = XCDR (tmp))
6271 {
6272 if (eol_type != CODING_EOL_UNDECIDED
6273 && eol_type != CODING_EOL_INCONSISTENT)
6274 {
6275 Lisp_Object eol;
6276 eol = Fget (XCAR (tmp), Qeol_type);
6277 if (VECTORP (eol))
6278 XSETCAR (tmp, XVECTOR (eol)->contents[eol_type]);
6279 }
6280 }
6281 return (highest ? XCAR (val) : val);
6282 }
6283
6284 DEFUN ("detect-coding-region", Fdetect_coding_region, Sdetect_coding_region,
6285 2, 3, 0,
6286 doc: /* Detect coding system of the text in the region between START and END.
6287 Return a list of possible coding systems ordered by priority.
6288
6289 If only ASCII characters are found, it returns a list of single element
6290 `undecided' or its subsidiary coding system according to a detected
6291 end-of-line format.
6292
6293 If optional argument HIGHEST is non-nil, return the coding system of
6294 highest priority. */)
6295 (start, end, highest)
6296 Lisp_Object start, end, highest;
6297 {
6298 int from, to;
6299 int from_byte, to_byte;
6300 int include_anchor_byte = 0;
6301
6302 CHECK_NUMBER_COERCE_MARKER (start);
6303 CHECK_NUMBER_COERCE_MARKER (end);
6304
6305 validate_region (&start, &end);
6306 from = XINT (start), to = XINT (end);
6307 from_byte = CHAR_TO_BYTE (from);
6308 to_byte = CHAR_TO_BYTE (to);
6309
6310 if (from < GPT && to >= GPT)
6311 move_gap_both (to, to_byte);
6312 /* If we an anchor byte `\0' follows the region, we include it in
6313 the detecting source. Then code detectors can handle the tailing
6314 byte sequence more accurately.
6315
6316 Fix me: This is not a perfect solution. It is better that we
6317 add one more argument, say LAST_BLOCK, to all detect_coding_XXX.
6318 */
6319 if (to == Z || (to == GPT && GAP_SIZE > 0))
6320 include_anchor_byte = 1;
6321 return detect_coding_system (BYTE_POS_ADDR (from_byte),
6322 to_byte - from_byte + include_anchor_byte,
6323 !NILP (highest),
6324 !NILP (current_buffer
6325 ->enable_multibyte_characters));
6326 }
6327
6328 DEFUN ("detect-coding-string", Fdetect_coding_string, Sdetect_coding_string,
6329 1, 2, 0,
6330 doc: /* Detect coding system of the text in STRING.
6331 Return a list of possible coding systems ordered by priority.
6332
6333 If only ASCII characters are found, it returns a list of single element
6334 `undecided' or its subsidiary coding system according to a detected
6335 end-of-line format.
6336
6337 If optional argument HIGHEST is non-nil, return the coding system of
6338 highest priority. */)
6339 (string, highest)
6340 Lisp_Object string, highest;
6341 {
6342 CHECK_STRING (string);
6343
6344 return detect_coding_system (SDATA (string),
6345 /* "+ 1" is to include the anchor byte
6346 `\0'. With this, code detectors can
6347 handle the tailing bytes more
6348 accurately. */
6349 SBYTES (string) + 1,
6350 !NILP (highest),
6351 STRING_MULTIBYTE (string));
6352 }
6353
6354 /* Return an intersection of lists L1 and L2. */
6355
6356 static Lisp_Object
6357 intersection (l1, l2)
6358 Lisp_Object l1, l2;
6359 {
6360 Lisp_Object val = Fcons (Qnil, Qnil), tail;
6361
6362 for (tail = val; CONSP (l1); l1 = XCDR (l1))
6363 {
6364 if (!NILP (Fmemq (XCAR (l1), l2)))
6365 {
6366 XSETCDR (tail, Fcons (XCAR (l1), Qnil));
6367 tail = XCDR (tail);
6368 }
6369 }
6370 return XCDR (val);
6371 }
6372
6373
6374 /* Subroutine for Fsafe_coding_systems_region_internal.
6375
6376 Return a list of coding systems that safely encode the multibyte
6377 text between P and PEND. SAFE_CODINGS, if non-nil, is a list of
6378 possible coding systems. If it is nil, it means that we have not
6379 yet found any coding systems.
6380
6381 WORK_TABLE is a copy of the char-table Vchar_coding_system_table. An
6382 element of WORK_TABLE is set to t once the element is looked up.
6383
6384 If a non-ASCII single byte char is found, set
6385 *single_byte_char_found to 1. */
6386
6387 static Lisp_Object
6388 find_safe_codings (p, pend, safe_codings, work_table, single_byte_char_found)
6389 unsigned char *p, *pend;
6390 Lisp_Object safe_codings, work_table;
6391 int *single_byte_char_found;
6392 {
6393 int c, len, idx;
6394 Lisp_Object val;
6395
6396 while (p < pend)
6397 {
6398 c = STRING_CHAR_AND_LENGTH (p, pend - p, len);
6399 p += len;
6400 if (ASCII_BYTE_P (c))
6401 /* We can ignore ASCII characters here. */
6402 continue;
6403 if (SINGLE_BYTE_CHAR_P (c))
6404 *single_byte_char_found = 1;
6405 if (NILP (safe_codings))
6406 continue;
6407 /* Check the safe coding systems for C. */
6408 val = char_table_ref_and_index (work_table, c, &idx);
6409 if (EQ (val, Qt))
6410 /* This element was already checked. Ignore it. */
6411 continue;
6412 /* Remember that we checked this element. */
6413 CHAR_TABLE_SET (work_table, make_number (idx), Qt);
6414
6415 /* If there are some safe coding systems for C and we have
6416 already found the other set of coding systems for the
6417 different characters, get the intersection of them. */
6418 if (!EQ (safe_codings, Qt) && !NILP (val))
6419 val = intersection (safe_codings, val);
6420 safe_codings = val;
6421 }
6422 return safe_codings;
6423 }
6424
6425
6426 /* Return a list of coding systems that safely encode the text between
6427 START and END. If the text contains only ASCII or is unibyte,
6428 return t. */
6429
6430 DEFUN ("find-coding-systems-region-internal",
6431 Ffind_coding_systems_region_internal,
6432 Sfind_coding_systems_region_internal, 2, 2, 0,
6433 doc: /* Internal use only. */)
6434 (start, end)
6435 Lisp_Object start, end;
6436 {
6437 Lisp_Object work_table, safe_codings;
6438 int non_ascii_p = 0;
6439 int single_byte_char_found = 0;
6440 const unsigned char *p1, *p1end, *p2, *p2end, *p;
6441
6442 if (STRINGP (start))
6443 {
6444 if (!STRING_MULTIBYTE (start))
6445 return Qt;
6446 p1 = SDATA (start), p1end = p1 + SBYTES (start);
6447 p2 = p2end = p1end;
6448 if (SCHARS (start) != SBYTES (start))
6449 non_ascii_p = 1;
6450 }
6451 else
6452 {
6453 int from, to, stop;
6454
6455 CHECK_NUMBER_COERCE_MARKER (start);
6456 CHECK_NUMBER_COERCE_MARKER (end);
6457 if (XINT (start) < BEG || XINT (end) > Z || XINT (start) > XINT (end))
6458 args_out_of_range (start, end);
6459 if (NILP (current_buffer->enable_multibyte_characters))
6460 return Qt;
6461 from = CHAR_TO_BYTE (XINT (start));
6462 to = CHAR_TO_BYTE (XINT (end));
6463 stop = from < GPT_BYTE && GPT_BYTE < to ? GPT_BYTE : to;
6464 p1 = BYTE_POS_ADDR (from), p1end = p1 + (stop - from);
6465 if (stop == to)
6466 p2 = p2end = p1end;
6467 else
6468 p2 = BYTE_POS_ADDR (stop), p2end = p2 + (to - stop);
6469 if (XINT (end) - XINT (start) != to - from)
6470 non_ascii_p = 1;
6471 }
6472
6473 if (!non_ascii_p)
6474 {
6475 /* We are sure that the text contains no multibyte character.
6476 Check if it contains eight-bit-graphic. */
6477 p = p1;
6478 for (p = p1; p < p1end && ASCII_BYTE_P (*p); p++);
6479 if (p == p1end)
6480 {
6481 for (p = p2; p < p2end && ASCII_BYTE_P (*p); p++);
6482 if (p == p2end)
6483 return Qt;
6484 }
6485 }
6486
6487 /* The text contains non-ASCII characters. */
6488 work_table = Fcopy_sequence (Vchar_coding_system_table);
6489 safe_codings = find_safe_codings (p1, p1end, Qt, work_table,
6490 &single_byte_char_found);
6491 if (p2 < p2end)
6492 safe_codings = find_safe_codings (p2, p2end, safe_codings, work_table,
6493 &single_byte_char_found);
6494
6495 if (EQ (safe_codings, Qt))
6496 ; /* Nothing to be done. */
6497 else if (!single_byte_char_found)
6498 {
6499 /* Append generic coding systems. */
6500 Lisp_Object args[2];
6501 args[0] = safe_codings;
6502 args[1] = Fchar_table_extra_slot (Vchar_coding_system_table,
6503 make_number (0));
6504 safe_codings = Fappend (2, args);
6505 }
6506 else
6507 safe_codings = Fcons (Qraw_text,
6508 Fcons (Qemacs_mule,
6509 Fcons (Qno_conversion, safe_codings)));
6510 return safe_codings;
6511 }
6512
6513
6514 /* Search from position POS for such characters that are unencodable
6515 accoding to SAFE_CHARS, and return a list of their positions. P
6516 points where in the memory the character at POS exists. Limit the
6517 search at PEND or when Nth unencodable characters are found.
6518
6519 If SAFE_CHARS is a char table, an element for an unencodable
6520 character is nil.
6521
6522 If SAFE_CHARS is nil, all non-ASCII characters are unencodable.
6523
6524 Otherwise, SAFE_CHARS is t, and only eight-bit-contrl and
6525 eight-bit-graphic characters are unencodable. */
6526
6527 static Lisp_Object
6528 unencodable_char_position (safe_chars, pos, p, pend, n)
6529 Lisp_Object safe_chars;
6530 int pos;
6531 unsigned char *p, *pend;
6532 int n;
6533 {
6534 Lisp_Object pos_list;
6535
6536 pos_list = Qnil;
6537 while (p < pend)
6538 {
6539 int len;
6540 int c = STRING_CHAR_AND_LENGTH (p, MAX_MULTIBYTE_LENGTH, len);
6541
6542 if (c >= 128
6543 && (CHAR_TABLE_P (safe_chars)
6544 ? NILP (CHAR_TABLE_REF (safe_chars, c))
6545 : (NILP (safe_chars) || c < 256)))
6546 {
6547 pos_list = Fcons (make_number (pos), pos_list);
6548 if (--n <= 0)
6549 break;
6550 }
6551 pos++;
6552 p += len;
6553 }
6554 return Fnreverse (pos_list);
6555 }
6556
6557
6558 DEFUN ("unencodable-char-position", Funencodable_char_position,
6559 Sunencodable_char_position, 3, 5, 0,
6560 doc: /*
6561 Return position of first un-encodable character in a region.
6562 START and END specfiy the region and CODING-SYSTEM specifies the
6563 encoding to check. Return nil if CODING-SYSTEM does encode the region.
6564
6565 If optional 4th argument COUNT is non-nil, it specifies at most how
6566 many un-encodable characters to search. In this case, the value is a
6567 list of positions.
6568
6569 If optional 5th argument STRING is non-nil, it is a string to search
6570 for un-encodable characters. In that case, START and END are indexes
6571 to the string. */)
6572 (start, end, coding_system, count, string)
6573 Lisp_Object start, end, coding_system, count, string;
6574 {
6575 int n;
6576 Lisp_Object safe_chars;
6577 struct coding_system coding;
6578 Lisp_Object positions;
6579 int from, to;
6580 unsigned char *p, *pend;
6581
6582 if (NILP (string))
6583 {
6584 validate_region (&start, &end);
6585 from = XINT (start);
6586 to = XINT (end);
6587 if (NILP (current_buffer->enable_multibyte_characters))
6588 return Qnil;
6589 p = CHAR_POS_ADDR (from);
6590 pend = CHAR_POS_ADDR (to);
6591 }
6592 else
6593 {
6594 CHECK_STRING (string);
6595 CHECK_NATNUM (start);
6596 CHECK_NATNUM (end);
6597 from = XINT (start);
6598 to = XINT (end);
6599 if (from > to
6600 || to > SCHARS (string))
6601 args_out_of_range_3 (string, start, end);
6602 if (! STRING_MULTIBYTE (string))
6603 return Qnil;
6604 p = SDATA (string) + string_char_to_byte (string, from);
6605 pend = SDATA (string) + string_char_to_byte (string, to);
6606 }
6607
6608 setup_coding_system (Fcheck_coding_system (coding_system), &coding);
6609
6610 if (NILP (count))
6611 n = 1;
6612 else
6613 {
6614 CHECK_NATNUM (count);
6615 n = XINT (count);
6616 }
6617
6618 if (coding.type == coding_type_no_conversion
6619 || coding.type == coding_type_raw_text)
6620 return Qnil;
6621
6622 if (coding.type == coding_type_undecided)
6623 safe_chars = Qnil;
6624 else
6625 safe_chars = coding_safe_chars (&coding);
6626
6627 if (STRINGP (string)
6628 || from >= GPT || to <= GPT)
6629 positions = unencodable_char_position (safe_chars, from, p, pend, n);
6630 else
6631 {
6632 Lisp_Object args[2];
6633
6634 args[0] = unencodable_char_position (safe_chars, from, p, GPT_ADDR, n);
6635 n -= XINT (Flength (args[0]));
6636 if (n <= 0)
6637 positions = args[0];
6638 else
6639 {
6640 args[1] = unencodable_char_position (safe_chars, GPT, GAP_END_ADDR,
6641 pend, n);
6642 positions = Fappend (2, args);
6643 }
6644 }
6645
6646 return (NILP (count) ? Fcar (positions) : positions);
6647 }
6648
6649
6650 Lisp_Object
6651 code_convert_region1 (start, end, coding_system, encodep)
6652 Lisp_Object start, end, coding_system;
6653 int encodep;
6654 {
6655 struct coding_system coding;
6656 int from, to;
6657
6658 CHECK_NUMBER_COERCE_MARKER (start);
6659 CHECK_NUMBER_COERCE_MARKER (end);
6660 CHECK_SYMBOL (coding_system);
6661
6662 validate_region (&start, &end);
6663 from = XFASTINT (start);
6664 to = XFASTINT (end);
6665
6666 if (NILP (coding_system))
6667 return make_number (to - from);
6668
6669 if (setup_coding_system (Fcheck_coding_system (coding_system), &coding) < 0)
6670 error ("Invalid coding system: %s", SDATA (SYMBOL_NAME (coding_system)));
6671
6672 coding.mode |= CODING_MODE_LAST_BLOCK;
6673 coding.src_multibyte = coding.dst_multibyte
6674 = !NILP (current_buffer->enable_multibyte_characters);
6675 code_convert_region (from, CHAR_TO_BYTE (from), to, CHAR_TO_BYTE (to),
6676 &coding, encodep, 1);
6677 Vlast_coding_system_used = coding.symbol;
6678 return make_number (coding.produced_char);
6679 }
6680
6681 DEFUN ("decode-coding-region", Fdecode_coding_region, Sdecode_coding_region,
6682 3, 3, "r\nzCoding system: ",
6683 doc: /* Decode the current region from the specified coding system.
6684 When called from a program, takes three arguments:
6685 START, END, and CODING-SYSTEM. START and END are buffer positions.
6686 This function sets `last-coding-system-used' to the precise coding system
6687 used (which may be different from CODING-SYSTEM if CODING-SYSTEM is
6688 not fully specified.)
6689 It returns the length of the decoded text. */)
6690 (start, end, coding_system)
6691 Lisp_Object start, end, coding_system;
6692 {
6693 return code_convert_region1 (start, end, coding_system, 0);
6694 }
6695
6696 DEFUN ("encode-coding-region", Fencode_coding_region, Sencode_coding_region,
6697 3, 3, "r\nzCoding system: ",
6698 doc: /* Encode the current region into the specified coding system.
6699 When called from a program, takes three arguments:
6700 START, END, and CODING-SYSTEM. START and END are buffer positions.
6701 This function sets `last-coding-system-used' to the precise coding system
6702 used (which may be different from CODING-SYSTEM if CODING-SYSTEM is
6703 not fully specified.)
6704 It returns the length of the encoded text. */)
6705 (start, end, coding_system)
6706 Lisp_Object start, end, coding_system;
6707 {
6708 return code_convert_region1 (start, end, coding_system, 1);
6709 }
6710
6711 Lisp_Object
6712 code_convert_string1 (string, coding_system, nocopy, encodep)
6713 Lisp_Object string, coding_system, nocopy;
6714 int encodep;
6715 {
6716 struct coding_system coding;
6717
6718 CHECK_STRING (string);
6719 CHECK_SYMBOL (coding_system);
6720
6721 if (NILP (coding_system))
6722 return (NILP (nocopy) ? Fcopy_sequence (string) : string);
6723
6724 if (setup_coding_system (Fcheck_coding_system (coding_system), &coding) < 0)
6725 error ("Invalid coding system: %s", SDATA (SYMBOL_NAME (coding_system)));
6726
6727 coding.mode |= CODING_MODE_LAST_BLOCK;
6728 string = (encodep
6729 ? encode_coding_string (string, &coding, !NILP (nocopy))
6730 : decode_coding_string (string, &coding, !NILP (nocopy)));
6731 Vlast_coding_system_used = coding.symbol;
6732
6733 return string;
6734 }
6735
6736 DEFUN ("decode-coding-string", Fdecode_coding_string, Sdecode_coding_string,
6737 2, 3, 0,
6738 doc: /* Decode STRING which is encoded in CODING-SYSTEM, and return the result.
6739 Optional arg NOCOPY non-nil means it is OK to return STRING itself
6740 if the decoding operation is trivial.
6741 This function sets `last-coding-system-used' to the precise coding system
6742 used (which may be different from CODING-SYSTEM if CODING-SYSTEM is
6743 not fully specified.) */)
6744 (string, coding_system, nocopy)
6745 Lisp_Object string, coding_system, nocopy;
6746 {
6747 return code_convert_string1 (string, coding_system, nocopy, 0);
6748 }
6749
6750 DEFUN ("encode-coding-string", Fencode_coding_string, Sencode_coding_string,
6751 2, 3, 0,
6752 doc: /* Encode STRING to CODING-SYSTEM, and return the result.
6753 Optional arg NOCOPY non-nil means it is OK to return STRING itself
6754 if the encoding operation is trivial.
6755 This function sets `last-coding-system-used' to the precise coding system
6756 used (which may be different from CODING-SYSTEM if CODING-SYSTEM is
6757 not fully specified.) */)
6758 (string, coding_system, nocopy)
6759 Lisp_Object string, coding_system, nocopy;
6760 {
6761 return code_convert_string1 (string, coding_system, nocopy, 1);
6762 }
6763
6764 /* Encode or decode STRING according to CODING_SYSTEM.
6765 Do not set Vlast_coding_system_used.
6766
6767 This function is called only from macros DECODE_FILE and
6768 ENCODE_FILE, thus we ignore character composition. */
6769
6770 Lisp_Object
6771 code_convert_string_norecord (string, coding_system, encodep)
6772 Lisp_Object string, coding_system;
6773 int encodep;
6774 {
6775 struct coding_system coding;
6776
6777 CHECK_STRING (string);
6778 CHECK_SYMBOL (coding_system);
6779
6780 if (NILP (coding_system))
6781 return string;
6782
6783 if (setup_coding_system (Fcheck_coding_system (coding_system), &coding) < 0)
6784 error ("Invalid coding system: %s", SDATA (SYMBOL_NAME (coding_system)));
6785
6786 coding.composing = COMPOSITION_DISABLED;
6787 coding.mode |= CODING_MODE_LAST_BLOCK;
6788 return (encodep
6789 ? encode_coding_string (string, &coding, 1)
6790 : decode_coding_string (string, &coding, 1));
6791 }
6792 \f
6793 DEFUN ("decode-sjis-char", Fdecode_sjis_char, Sdecode_sjis_char, 1, 1, 0,
6794 doc: /* Decode a Japanese character which has CODE in shift_jis encoding.
6795 Return the corresponding character. */)
6796 (code)
6797 Lisp_Object code;
6798 {
6799 unsigned char c1, c2, s1, s2;
6800 Lisp_Object val;
6801
6802 CHECK_NUMBER (code);
6803 s1 = (XFASTINT (code)) >> 8, s2 = (XFASTINT (code)) & 0xFF;
6804 if (s1 == 0)
6805 {
6806 if (s2 < 0x80)
6807 XSETFASTINT (val, s2);
6808 else if (s2 >= 0xA0 || s2 <= 0xDF)
6809 XSETFASTINT (val, MAKE_CHAR (charset_katakana_jisx0201, s2, 0));
6810 else
6811 error ("Invalid Shift JIS code: %x", XFASTINT (code));
6812 }
6813 else
6814 {
6815 if ((s1 < 0x80 || (s1 > 0x9F && s1 < 0xE0) || s1 > 0xEF)
6816 || (s2 < 0x40 || s2 == 0x7F || s2 > 0xFC))
6817 error ("Invalid Shift JIS code: %x", XFASTINT (code));
6818 DECODE_SJIS (s1, s2, c1, c2);
6819 XSETFASTINT (val, MAKE_CHAR (charset_jisx0208, c1, c2));
6820 }
6821 return val;
6822 }
6823
6824 DEFUN ("encode-sjis-char", Fencode_sjis_char, Sencode_sjis_char, 1, 1, 0,
6825 doc: /* Encode a Japanese character CHAR to shift_jis encoding.
6826 Return the corresponding code in SJIS. */)
6827 (ch)
6828 Lisp_Object ch;
6829 {
6830 int charset, c1, c2, s1, s2;
6831 Lisp_Object val;
6832
6833 CHECK_NUMBER (ch);
6834 SPLIT_CHAR (XFASTINT (ch), charset, c1, c2);
6835 if (charset == CHARSET_ASCII)
6836 {
6837 val = ch;
6838 }
6839 else if (charset == charset_jisx0208
6840 && c1 > 0x20 && c1 < 0x7F && c2 > 0x20 && c2 < 0x7F)
6841 {
6842 ENCODE_SJIS (c1, c2, s1, s2);
6843 XSETFASTINT (val, (s1 << 8) | s2);
6844 }
6845 else if (charset == charset_katakana_jisx0201
6846 && c1 > 0x20 && c2 < 0xE0)
6847 {
6848 XSETFASTINT (val, c1 | 0x80);
6849 }
6850 else
6851 error ("Can't encode to shift_jis: %d", XFASTINT (ch));
6852 return val;
6853 }
6854
6855 DEFUN ("decode-big5-char", Fdecode_big5_char, Sdecode_big5_char, 1, 1, 0,
6856 doc: /* Decode a Big5 character which has CODE in BIG5 coding system.
6857 Return the corresponding character. */)
6858 (code)
6859 Lisp_Object code;
6860 {
6861 int charset;
6862 unsigned char b1, b2, c1, c2;
6863 Lisp_Object val;
6864
6865 CHECK_NUMBER (code);
6866 b1 = (XFASTINT (code)) >> 8, b2 = (XFASTINT (code)) & 0xFF;
6867 if (b1 == 0)
6868 {
6869 if (b2 >= 0x80)
6870 error ("Invalid BIG5 code: %x", XFASTINT (code));
6871 val = code;
6872 }
6873 else
6874 {
6875 if ((b1 < 0xA1 || b1 > 0xFE)
6876 || (b2 < 0x40 || (b2 > 0x7E && b2 < 0xA1) || b2 > 0xFE))
6877 error ("Invalid BIG5 code: %x", XFASTINT (code));
6878 DECODE_BIG5 (b1, b2, charset, c1, c2);
6879 XSETFASTINT (val, MAKE_CHAR (charset, c1, c2));
6880 }
6881 return val;
6882 }
6883
6884 DEFUN ("encode-big5-char", Fencode_big5_char, Sencode_big5_char, 1, 1, 0,
6885 doc: /* Encode the Big5 character CHAR to BIG5 coding system.
6886 Return the corresponding character code in Big5. */)
6887 (ch)
6888 Lisp_Object ch;
6889 {
6890 int charset, c1, c2, b1, b2;
6891 Lisp_Object val;
6892
6893 CHECK_NUMBER (ch);
6894 SPLIT_CHAR (XFASTINT (ch), charset, c1, c2);
6895 if (charset == CHARSET_ASCII)
6896 {
6897 val = ch;
6898 }
6899 else if ((charset == charset_big5_1
6900 && (XFASTINT (ch) >= 0x250a1 && XFASTINT (ch) <= 0x271ec))
6901 || (charset == charset_big5_2
6902 && XFASTINT (ch) >= 0x290a1 && XFASTINT (ch) <= 0x2bdb2))
6903 {
6904 ENCODE_BIG5 (charset, c1, c2, b1, b2);
6905 XSETFASTINT (val, (b1 << 8) | b2);
6906 }
6907 else
6908 error ("Can't encode to Big5: %d", XFASTINT (ch));
6909 return val;
6910 }
6911 \f
6912 DEFUN ("set-terminal-coding-system-internal",
6913 Fset_terminal_coding_system_internal,
6914 Sset_terminal_coding_system_internal, 1, 1, 0,
6915 doc: /* Internal use only. */)
6916 (coding_system)
6917 Lisp_Object coding_system;
6918 {
6919 CHECK_SYMBOL (coding_system);
6920 setup_coding_system (Fcheck_coding_system (coding_system), &terminal_coding);
6921 /* We had better not send unsafe characters to terminal. */
6922 terminal_coding.flags |= CODING_FLAG_ISO_SAFE;
6923 /* Character composition should be disabled. */
6924 terminal_coding.composing = COMPOSITION_DISABLED;
6925 /* Error notification should be suppressed. */
6926 terminal_coding.suppress_error = 1;
6927 terminal_coding.src_multibyte = 1;
6928 terminal_coding.dst_multibyte = 0;
6929 return Qnil;
6930 }
6931
6932 DEFUN ("set-safe-terminal-coding-system-internal",
6933 Fset_safe_terminal_coding_system_internal,
6934 Sset_safe_terminal_coding_system_internal, 1, 1, 0,
6935 doc: /* Internal use only. */)
6936 (coding_system)
6937 Lisp_Object coding_system;
6938 {
6939 CHECK_SYMBOL (coding_system);
6940 setup_coding_system (Fcheck_coding_system (coding_system),
6941 &safe_terminal_coding);
6942 /* Character composition should be disabled. */
6943 safe_terminal_coding.composing = COMPOSITION_DISABLED;
6944 /* Error notification should be suppressed. */
6945 terminal_coding.suppress_error = 1;
6946 safe_terminal_coding.src_multibyte = 1;
6947 safe_terminal_coding.dst_multibyte = 0;
6948 return Qnil;
6949 }
6950
6951 DEFUN ("terminal-coding-system",
6952 Fterminal_coding_system, Sterminal_coding_system, 0, 0, 0,
6953 doc: /* Return coding system specified for terminal output. */)
6954 ()
6955 {
6956 return terminal_coding.symbol;
6957 }
6958
6959 DEFUN ("set-keyboard-coding-system-internal",
6960 Fset_keyboard_coding_system_internal,
6961 Sset_keyboard_coding_system_internal, 1, 1, 0,
6962 doc: /* Internal use only. */)
6963 (coding_system)
6964 Lisp_Object coding_system;
6965 {
6966 CHECK_SYMBOL (coding_system);
6967 setup_coding_system (Fcheck_coding_system (coding_system), &keyboard_coding);
6968 /* Character composition should be disabled. */
6969 keyboard_coding.composing = COMPOSITION_DISABLED;
6970 return Qnil;
6971 }
6972
6973 DEFUN ("keyboard-coding-system",
6974 Fkeyboard_coding_system, Skeyboard_coding_system, 0, 0, 0,
6975 doc: /* Return coding system specified for decoding keyboard input. */)
6976 ()
6977 {
6978 return keyboard_coding.symbol;
6979 }
6980
6981 \f
6982 DEFUN ("find-operation-coding-system", Ffind_operation_coding_system,
6983 Sfind_operation_coding_system, 1, MANY, 0,
6984 doc: /* Choose a coding system for an operation based on the target name.
6985 The value names a pair of coding systems: (DECODING-SYSTEM . ENCODING-SYSTEM).
6986 DECODING-SYSTEM is the coding system to use for decoding
6987 \(in case OPERATION does decoding), and ENCODING-SYSTEM is the coding system
6988 for encoding (in case OPERATION does encoding).
6989
6990 The first argument OPERATION specifies an I/O primitive:
6991 For file I/O, `insert-file-contents' or `write-region'.
6992 For process I/O, `call-process', `call-process-region', or `start-process'.
6993 For network I/O, `open-network-stream'.
6994
6995 The remaining arguments should be the same arguments that were passed
6996 to the primitive. Depending on which primitive, one of those arguments
6997 is selected as the TARGET. For example, if OPERATION does file I/O,
6998 whichever argument specifies the file name is TARGET.
6999
7000 TARGET has a meaning which depends on OPERATION:
7001 For file I/O, TARGET is a file name.
7002 For process I/O, TARGET is a process name.
7003 For network I/O, TARGET is a service name or a port number
7004
7005 This function looks up what specified for TARGET in,
7006 `file-coding-system-alist', `process-coding-system-alist',
7007 or `network-coding-system-alist' depending on OPERATION.
7008 They may specify a coding system, a cons of coding systems,
7009 or a function symbol to call.
7010 In the last case, we call the function with one argument,
7011 which is a list of all the arguments given to this function.
7012
7013 usage: (find-operation-coding-system OPERATION ARGUMENTS ...) */)
7014 (nargs, args)
7015 int nargs;
7016 Lisp_Object *args;
7017 {
7018 Lisp_Object operation, target_idx, target, val;
7019 register Lisp_Object chain;
7020
7021 if (nargs < 2)
7022 error ("Too few arguments");
7023 operation = args[0];
7024 if (!SYMBOLP (operation)
7025 || !INTEGERP (target_idx = Fget (operation, Qtarget_idx)))
7026 error ("Invalid first argument");
7027 if (nargs < 1 + XINT (target_idx))
7028 error ("Too few arguments for operation: %s",
7029 SDATA (SYMBOL_NAME (operation)));
7030 /* For write-region, if the 6th argument (i.e. VISIT, the 5th
7031 argument to write-region) is string, it must be treated as a
7032 target file name. */
7033 if (EQ (operation, Qwrite_region)
7034 && nargs > 5
7035 && STRINGP (args[5]))
7036 target_idx = make_number (4);
7037 target = args[XINT (target_idx) + 1];
7038 if (!(STRINGP (target)
7039 || (EQ (operation, Qopen_network_stream) && INTEGERP (target))))
7040 error ("Invalid argument %d", XINT (target_idx) + 1);
7041
7042 chain = ((EQ (operation, Qinsert_file_contents)
7043 || EQ (operation, Qwrite_region))
7044 ? Vfile_coding_system_alist
7045 : (EQ (operation, Qopen_network_stream)
7046 ? Vnetwork_coding_system_alist
7047 : Vprocess_coding_system_alist));
7048 if (NILP (chain))
7049 return Qnil;
7050
7051 for (; CONSP (chain); chain = XCDR (chain))
7052 {
7053 Lisp_Object elt;
7054 elt = XCAR (chain);
7055
7056 if (CONSP (elt)
7057 && ((STRINGP (target)
7058 && STRINGP (XCAR (elt))
7059 && fast_string_match (XCAR (elt), target) >= 0)
7060 || (INTEGERP (target) && EQ (target, XCAR (elt)))))
7061 {
7062 val = XCDR (elt);
7063 /* Here, if VAL is both a valid coding system and a valid
7064 function symbol, we return VAL as a coding system. */
7065 if (CONSP (val))
7066 return val;
7067 if (! SYMBOLP (val))
7068 return Qnil;
7069 if (! NILP (Fcoding_system_p (val)))
7070 return Fcons (val, val);
7071 if (! NILP (Ffboundp (val)))
7072 {
7073 val = call1 (val, Flist (nargs, args));
7074 if (CONSP (val))
7075 return val;
7076 if (SYMBOLP (val) && ! NILP (Fcoding_system_p (val)))
7077 return Fcons (val, val);
7078 }
7079 return Qnil;
7080 }
7081 }
7082 return Qnil;
7083 }
7084
7085 DEFUN ("update-coding-systems-internal", Fupdate_coding_systems_internal,
7086 Supdate_coding_systems_internal, 0, 0, 0,
7087 doc: /* Update internal database for ISO2022 and CCL based coding systems.
7088 When values of any coding categories are changed, you must
7089 call this function. */)
7090 ()
7091 {
7092 int i;
7093
7094 for (i = CODING_CATEGORY_IDX_EMACS_MULE; i < CODING_CATEGORY_IDX_MAX; i++)
7095 {
7096 Lisp_Object val;
7097
7098 val = SYMBOL_VALUE (XVECTOR (Vcoding_category_table)->contents[i]);
7099 if (!NILP (val))
7100 {
7101 if (! coding_system_table[i])
7102 coding_system_table[i] = ((struct coding_system *)
7103 xmalloc (sizeof (struct coding_system)));
7104 setup_coding_system (val, coding_system_table[i]);
7105 }
7106 else if (coding_system_table[i])
7107 {
7108 xfree (coding_system_table[i]);
7109 coding_system_table[i] = NULL;
7110 }
7111 }
7112
7113 return Qnil;
7114 }
7115
7116 DEFUN ("set-coding-priority-internal", Fset_coding_priority_internal,
7117 Sset_coding_priority_internal, 0, 0, 0,
7118 doc: /* Update internal database for the current value of `coding-category-list'.
7119 This function is internal use only. */)
7120 ()
7121 {
7122 int i = 0, idx;
7123 Lisp_Object val;
7124
7125 val = Vcoding_category_list;
7126
7127 while (CONSP (val) && i < CODING_CATEGORY_IDX_MAX)
7128 {
7129 if (! SYMBOLP (XCAR (val)))
7130 break;
7131 idx = XFASTINT (Fget (XCAR (val), Qcoding_category_index));
7132 if (idx >= CODING_CATEGORY_IDX_MAX)
7133 break;
7134 coding_priorities[i++] = (1 << idx);
7135 val = XCDR (val);
7136 }
7137 /* If coding-category-list is valid and contains all coding
7138 categories, `i' should be CODING_CATEGORY_IDX_MAX now. If not,
7139 the following code saves Emacs from crashing. */
7140 while (i < CODING_CATEGORY_IDX_MAX)
7141 coding_priorities[i++] = CODING_CATEGORY_MASK_RAW_TEXT;
7142
7143 return Qnil;
7144 }
7145
7146 #endif /* emacs */
7147
7148 \f
7149 /*** 9. Post-amble ***/
7150
7151 void
7152 init_coding_once ()
7153 {
7154 int i;
7155
7156 /* Emacs' internal format specific initialize routine. */
7157 for (i = 0; i <= 0x20; i++)
7158 emacs_code_class[i] = EMACS_control_code;
7159 emacs_code_class[0x0A] = EMACS_linefeed_code;
7160 emacs_code_class[0x0D] = EMACS_carriage_return_code;
7161 for (i = 0x21 ; i < 0x7F; i++)
7162 emacs_code_class[i] = EMACS_ascii_code;
7163 emacs_code_class[0x7F] = EMACS_control_code;
7164 for (i = 0x80; i < 0xFF; i++)
7165 emacs_code_class[i] = EMACS_invalid_code;
7166 emacs_code_class[LEADING_CODE_PRIVATE_11] = EMACS_leading_code_3;
7167 emacs_code_class[LEADING_CODE_PRIVATE_12] = EMACS_leading_code_3;
7168 emacs_code_class[LEADING_CODE_PRIVATE_21] = EMACS_leading_code_4;
7169 emacs_code_class[LEADING_CODE_PRIVATE_22] = EMACS_leading_code_4;
7170
7171 /* ISO2022 specific initialize routine. */
7172 for (i = 0; i < 0x20; i++)
7173 iso_code_class[i] = ISO_control_0;
7174 for (i = 0x21; i < 0x7F; i++)
7175 iso_code_class[i] = ISO_graphic_plane_0;
7176 for (i = 0x80; i < 0xA0; i++)
7177 iso_code_class[i] = ISO_control_1;
7178 for (i = 0xA1; i < 0xFF; i++)
7179 iso_code_class[i] = ISO_graphic_plane_1;
7180 iso_code_class[0x20] = iso_code_class[0x7F] = ISO_0x20_or_0x7F;
7181 iso_code_class[0xA0] = iso_code_class[0xFF] = ISO_0xA0_or_0xFF;
7182 iso_code_class[ISO_CODE_CR] = ISO_carriage_return;
7183 iso_code_class[ISO_CODE_SO] = ISO_shift_out;
7184 iso_code_class[ISO_CODE_SI] = ISO_shift_in;
7185 iso_code_class[ISO_CODE_SS2_7] = ISO_single_shift_2_7;
7186 iso_code_class[ISO_CODE_ESC] = ISO_escape;
7187 iso_code_class[ISO_CODE_SS2] = ISO_single_shift_2;
7188 iso_code_class[ISO_CODE_SS3] = ISO_single_shift_3;
7189 iso_code_class[ISO_CODE_CSI] = ISO_control_sequence_introducer;
7190
7191 setup_coding_system (Qnil, &keyboard_coding);
7192 setup_coding_system (Qnil, &terminal_coding);
7193 setup_coding_system (Qnil, &safe_terminal_coding);
7194 setup_coding_system (Qnil, &default_buffer_file_coding);
7195
7196 bzero (coding_system_table, sizeof coding_system_table);
7197
7198 bzero (ascii_skip_code, sizeof ascii_skip_code);
7199 for (i = 0; i < 128; i++)
7200 ascii_skip_code[i] = 1;
7201
7202 #if defined (MSDOS) || defined (WINDOWSNT)
7203 system_eol_type = CODING_EOL_CRLF;
7204 #else
7205 system_eol_type = CODING_EOL_LF;
7206 #endif
7207
7208 inhibit_pre_post_conversion = 0;
7209 }
7210
7211 #ifdef emacs
7212
7213 void
7214 syms_of_coding ()
7215 {
7216 Qtarget_idx = intern ("target-idx");
7217 staticpro (&Qtarget_idx);
7218
7219 Qcoding_system_history = intern ("coding-system-history");
7220 staticpro (&Qcoding_system_history);
7221 Fset (Qcoding_system_history, Qnil);
7222
7223 /* Target FILENAME is the first argument. */
7224 Fput (Qinsert_file_contents, Qtarget_idx, make_number (0));
7225 /* Target FILENAME is the third argument. */
7226 Fput (Qwrite_region, Qtarget_idx, make_number (2));
7227
7228 Qcall_process = intern ("call-process");
7229 staticpro (&Qcall_process);
7230 /* Target PROGRAM is the first argument. */
7231 Fput (Qcall_process, Qtarget_idx, make_number (0));
7232
7233 Qcall_process_region = intern ("call-process-region");
7234 staticpro (&Qcall_process_region);
7235 /* Target PROGRAM is the third argument. */
7236 Fput (Qcall_process_region, Qtarget_idx, make_number (2));
7237
7238 Qstart_process = intern ("start-process");
7239 staticpro (&Qstart_process);
7240 /* Target PROGRAM is the third argument. */
7241 Fput (Qstart_process, Qtarget_idx, make_number (2));
7242
7243 Qopen_network_stream = intern ("open-network-stream");
7244 staticpro (&Qopen_network_stream);
7245 /* Target SERVICE is the fourth argument. */
7246 Fput (Qopen_network_stream, Qtarget_idx, make_number (3));
7247
7248 Qcoding_system = intern ("coding-system");
7249 staticpro (&Qcoding_system);
7250
7251 Qeol_type = intern ("eol-type");
7252 staticpro (&Qeol_type);
7253
7254 Qbuffer_file_coding_system = intern ("buffer-file-coding-system");
7255 staticpro (&Qbuffer_file_coding_system);
7256
7257 Qpost_read_conversion = intern ("post-read-conversion");
7258 staticpro (&Qpost_read_conversion);
7259
7260 Qpre_write_conversion = intern ("pre-write-conversion");
7261 staticpro (&Qpre_write_conversion);
7262
7263 Qno_conversion = intern ("no-conversion");
7264 staticpro (&Qno_conversion);
7265
7266 Qundecided = intern ("undecided");
7267 staticpro (&Qundecided);
7268
7269 Qcoding_system_p = intern ("coding-system-p");
7270 staticpro (&Qcoding_system_p);
7271
7272 Qcoding_system_error = intern ("coding-system-error");
7273 staticpro (&Qcoding_system_error);
7274
7275 Fput (Qcoding_system_error, Qerror_conditions,
7276 Fcons (Qcoding_system_error, Fcons (Qerror, Qnil)));
7277 Fput (Qcoding_system_error, Qerror_message,
7278 build_string ("Invalid coding system"));
7279
7280 Qcoding_category = intern ("coding-category");
7281 staticpro (&Qcoding_category);
7282 Qcoding_category_index = intern ("coding-category-index");
7283 staticpro (&Qcoding_category_index);
7284
7285 Vcoding_category_table
7286 = Fmake_vector (make_number (CODING_CATEGORY_IDX_MAX), Qnil);
7287 staticpro (&Vcoding_category_table);
7288 {
7289 int i;
7290 for (i = 0; i < CODING_CATEGORY_IDX_MAX; i++)
7291 {
7292 XVECTOR (Vcoding_category_table)->contents[i]
7293 = intern (coding_category_name[i]);
7294 Fput (XVECTOR (Vcoding_category_table)->contents[i],
7295 Qcoding_category_index, make_number (i));
7296 }
7297 }
7298
7299 Qtranslation_table = intern ("translation-table");
7300 staticpro (&Qtranslation_table);
7301 Fput (Qtranslation_table, Qchar_table_extra_slots, make_number (1));
7302
7303 Qtranslation_table_id = intern ("translation-table-id");
7304 staticpro (&Qtranslation_table_id);
7305
7306 Qtranslation_table_for_decode = intern ("translation-table-for-decode");
7307 staticpro (&Qtranslation_table_for_decode);
7308
7309 Qtranslation_table_for_encode = intern ("translation-table-for-encode");
7310 staticpro (&Qtranslation_table_for_encode);
7311
7312 Qsafe_chars = intern ("safe-chars");
7313 staticpro (&Qsafe_chars);
7314
7315 Qchar_coding_system = intern ("char-coding-system");
7316 staticpro (&Qchar_coding_system);
7317
7318 /* Intern this now in case it isn't already done.
7319 Setting this variable twice is harmless.
7320 But don't staticpro it here--that is done in alloc.c. */
7321 Qchar_table_extra_slots = intern ("char-table-extra-slots");
7322 Fput (Qsafe_chars, Qchar_table_extra_slots, make_number (0));
7323 Fput (Qchar_coding_system, Qchar_table_extra_slots, make_number (2));
7324
7325 Qvalid_codes = intern ("valid-codes");
7326 staticpro (&Qvalid_codes);
7327
7328 Qemacs_mule = intern ("emacs-mule");
7329 staticpro (&Qemacs_mule);
7330
7331 Qraw_text = intern ("raw-text");
7332 staticpro (&Qraw_text);
7333
7334 defsubr (&Scoding_system_p);
7335 defsubr (&Sread_coding_system);
7336 defsubr (&Sread_non_nil_coding_system);
7337 defsubr (&Scheck_coding_system);
7338 defsubr (&Sdetect_coding_region);
7339 defsubr (&Sdetect_coding_string);
7340 defsubr (&Sfind_coding_systems_region_internal);
7341 defsubr (&Sunencodable_char_position);
7342 defsubr (&Sdecode_coding_region);
7343 defsubr (&Sencode_coding_region);
7344 defsubr (&Sdecode_coding_string);
7345 defsubr (&Sencode_coding_string);
7346 defsubr (&Sdecode_sjis_char);
7347 defsubr (&Sencode_sjis_char);
7348 defsubr (&Sdecode_big5_char);
7349 defsubr (&Sencode_big5_char);
7350 defsubr (&Sset_terminal_coding_system_internal);
7351 defsubr (&Sset_safe_terminal_coding_system_internal);
7352 defsubr (&Sterminal_coding_system);
7353 defsubr (&Sset_keyboard_coding_system_internal);
7354 defsubr (&Skeyboard_coding_system);
7355 defsubr (&Sfind_operation_coding_system);
7356 defsubr (&Supdate_coding_systems_internal);
7357 defsubr (&Sset_coding_priority_internal);
7358
7359 DEFVAR_LISP ("coding-system-list", &Vcoding_system_list,
7360 doc: /* List of coding systems.
7361
7362 Do not alter the value of this variable manually. This variable should be
7363 updated by the functions `make-coding-system' and
7364 `define-coding-system-alias'. */);
7365 Vcoding_system_list = Qnil;
7366
7367 DEFVAR_LISP ("coding-system-alist", &Vcoding_system_alist,
7368 doc: /* Alist of coding system names.
7369 Each element is one element list of coding system name.
7370 This variable is given to `completing-read' as TABLE argument.
7371
7372 Do not alter the value of this variable manually. This variable should be
7373 updated by the functions `make-coding-system' and
7374 `define-coding-system-alias'. */);
7375 Vcoding_system_alist = Qnil;
7376
7377 DEFVAR_LISP ("coding-category-list", &Vcoding_category_list,
7378 doc: /* List of coding-categories (symbols) ordered by priority.
7379
7380 On detecting a coding system, Emacs tries code detection algorithms
7381 associated with each coding-category one by one in this order. When
7382 one algorithm agrees with a byte sequence of source text, the coding
7383 system bound to the corresponding coding-category is selected. */);
7384 {
7385 int i;
7386
7387 Vcoding_category_list = Qnil;
7388 for (i = CODING_CATEGORY_IDX_MAX - 1; i >= 0; i--)
7389 Vcoding_category_list
7390 = Fcons (XVECTOR (Vcoding_category_table)->contents[i],
7391 Vcoding_category_list);
7392 }
7393
7394 DEFVAR_LISP ("coding-system-for-read", &Vcoding_system_for_read,
7395 doc: /* Specify the coding system for read operations.
7396 It is useful to bind this variable with `let', but do not set it globally.
7397 If the value is a coding system, it is used for decoding on read operation.
7398 If not, an appropriate element is used from one of the coding system alists:
7399 There are three such tables, `file-coding-system-alist',
7400 `process-coding-system-alist', and `network-coding-system-alist'. */);
7401 Vcoding_system_for_read = Qnil;
7402
7403 DEFVAR_LISP ("coding-system-for-write", &Vcoding_system_for_write,
7404 doc: /* Specify the coding system for write operations.
7405 Programs bind this variable with `let', but you should not set it globally.
7406 If the value is a coding system, it is used for encoding of output,
7407 when writing it to a file and when sending it to a file or subprocess.
7408
7409 If this does not specify a coding system, an appropriate element
7410 is used from one of the coding system alists:
7411 There are three such tables, `file-coding-system-alist',
7412 `process-coding-system-alist', and `network-coding-system-alist'.
7413 For output to files, if the above procedure does not specify a coding system,
7414 the value of `buffer-file-coding-system' is used. */);
7415 Vcoding_system_for_write = Qnil;
7416
7417 DEFVAR_LISP ("last-coding-system-used", &Vlast_coding_system_used,
7418 doc: /* Coding system used in the latest file or process I/O. */);
7419 Vlast_coding_system_used = Qnil;
7420
7421 DEFVAR_BOOL ("inhibit-eol-conversion", &inhibit_eol_conversion,
7422 doc: /* *Non-nil means always inhibit code conversion of end-of-line format.
7423 See info node `Coding Systems' and info node `Text and Binary' concerning
7424 such conversion. */);
7425 inhibit_eol_conversion = 0;
7426
7427 DEFVAR_BOOL ("inherit-process-coding-system", &inherit_process_coding_system,
7428 doc: /* Non-nil means process buffer inherits coding system of process output.
7429 Bind it to t if the process output is to be treated as if it were a file
7430 read from some filesystem. */);
7431 inherit_process_coding_system = 0;
7432
7433 DEFVAR_LISP ("file-coding-system-alist", &Vfile_coding_system_alist,
7434 doc: /* Alist to decide a coding system to use for a file I/O operation.
7435 The format is ((PATTERN . VAL) ...),
7436 where PATTERN is a regular expression matching a file name,
7437 VAL is a coding system, a cons of coding systems, or a function symbol.
7438 If VAL is a coding system, it is used for both decoding and encoding
7439 the file contents.
7440 If VAL is a cons of coding systems, the car part is used for decoding,
7441 and the cdr part is used for encoding.
7442 If VAL is a function symbol, the function must return a coding system
7443 or a cons of coding systems which are used as above. The function gets
7444 the arguments with which `find-operation-coding-system' was called.
7445
7446 See also the function `find-operation-coding-system'
7447 and the variable `auto-coding-alist'. */);
7448 Vfile_coding_system_alist = Qnil;
7449
7450 DEFVAR_LISP ("process-coding-system-alist", &Vprocess_coding_system_alist,
7451 doc: /* Alist to decide a coding system to use for a process I/O operation.
7452 The format is ((PATTERN . VAL) ...),
7453 where PATTERN is a regular expression matching a program name,
7454 VAL is a coding system, a cons of coding systems, or a function symbol.
7455 If VAL is a coding system, it is used for both decoding what received
7456 from the program and encoding what sent to the program.
7457 If VAL is a cons of coding systems, the car part is used for decoding,
7458 and the cdr part is used for encoding.
7459 If VAL is a function symbol, the function must return a coding system
7460 or a cons of coding systems which are used as above.
7461
7462 See also the function `find-operation-coding-system'. */);
7463 Vprocess_coding_system_alist = Qnil;
7464
7465 DEFVAR_LISP ("network-coding-system-alist", &Vnetwork_coding_system_alist,
7466 doc: /* Alist to decide a coding system to use for a network I/O operation.
7467 The format is ((PATTERN . VAL) ...),
7468 where PATTERN is a regular expression matching a network service name
7469 or is a port number to connect to,
7470 VAL is a coding system, a cons of coding systems, or a function symbol.
7471 If VAL is a coding system, it is used for both decoding what received
7472 from the network stream and encoding what sent to the network stream.
7473 If VAL is a cons of coding systems, the car part is used for decoding,
7474 and the cdr part is used for encoding.
7475 If VAL is a function symbol, the function must return a coding system
7476 or a cons of coding systems which are used as above.
7477
7478 See also the function `find-operation-coding-system'. */);
7479 Vnetwork_coding_system_alist = Qnil;
7480
7481 DEFVAR_LISP ("locale-coding-system", &Vlocale_coding_system,
7482 doc: /* Coding system to use with system messages.
7483 Also used for decoding keyboard input on X Window system. */);
7484 Vlocale_coding_system = Qnil;
7485
7486 /* The eol mnemonics are reset in startup.el system-dependently. */
7487 DEFVAR_LISP ("eol-mnemonic-unix", &eol_mnemonic_unix,
7488 doc: /* *String displayed in mode line for UNIX-like (LF) end-of-line format. */);
7489 eol_mnemonic_unix = build_string (":");
7490
7491 DEFVAR_LISP ("eol-mnemonic-dos", &eol_mnemonic_dos,
7492 doc: /* *String displayed in mode line for DOS-like (CRLF) end-of-line format. */);
7493 eol_mnemonic_dos = build_string ("\\");
7494
7495 DEFVAR_LISP ("eol-mnemonic-mac", &eol_mnemonic_mac,
7496 doc: /* *String displayed in mode line for MAC-like (CR) end-of-line format. */);
7497 eol_mnemonic_mac = build_string ("/");
7498
7499 DEFVAR_LISP ("eol-mnemonic-undecided", &eol_mnemonic_undecided,
7500 doc: /* *String displayed in mode line when end-of-line format is not yet determined. */);
7501 eol_mnemonic_undecided = build_string (":");
7502
7503 DEFVAR_LISP ("enable-character-translation", &Venable_character_translation,
7504 doc: /* *Non-nil enables character translation while encoding and decoding. */);
7505 Venable_character_translation = Qt;
7506
7507 DEFVAR_LISP ("standard-translation-table-for-decode",
7508 &Vstandard_translation_table_for_decode,
7509 doc: /* Table for translating characters while decoding. */);
7510 Vstandard_translation_table_for_decode = Qnil;
7511
7512 DEFVAR_LISP ("standard-translation-table-for-encode",
7513 &Vstandard_translation_table_for_encode,
7514 doc: /* Table for translating characters while encoding. */);
7515 Vstandard_translation_table_for_encode = Qnil;
7516
7517 DEFVAR_LISP ("charset-revision-table", &Vcharset_revision_alist,
7518 doc: /* Alist of charsets vs revision numbers.
7519 While encoding, if a charset (car part of an element) is found,
7520 designate it with the escape sequence identifying revision (cdr part of the element). */);
7521 Vcharset_revision_alist = Qnil;
7522
7523 DEFVAR_LISP ("default-process-coding-system",
7524 &Vdefault_process_coding_system,
7525 doc: /* Cons of coding systems used for process I/O by default.
7526 The car part is used for decoding a process output,
7527 the cdr part is used for encoding a text to be sent to a process. */);
7528 Vdefault_process_coding_system = Qnil;
7529
7530 DEFVAR_LISP ("latin-extra-code-table", &Vlatin_extra_code_table,
7531 doc: /* Table of extra Latin codes in the range 128..159 (inclusive).
7532 This is a vector of length 256.
7533 If Nth element is non-nil, the existence of code N in a file
7534 \(or output of subprocess) doesn't prevent it to be detected as
7535 a coding system of ISO 2022 variant which has a flag
7536 `accept-latin-extra-code' t (e.g. iso-latin-1) on reading a file
7537 or reading output of a subprocess.
7538 Only 128th through 159th elements has a meaning. */);
7539 Vlatin_extra_code_table = Fmake_vector (make_number (256), Qnil);
7540
7541 DEFVAR_LISP ("select-safe-coding-system-function",
7542 &Vselect_safe_coding_system_function,
7543 doc: /* Function to call to select safe coding system for encoding a text.
7544
7545 If set, this function is called to force a user to select a proper
7546 coding system which can encode the text in the case that a default
7547 coding system used in each operation can't encode the text.
7548
7549 The default value is `select-safe-coding-system' (which see). */);
7550 Vselect_safe_coding_system_function = Qnil;
7551
7552 DEFVAR_LISP ("char-coding-system-table", &Vchar_coding_system_table,
7553 doc: /* Char-table containing safe coding systems of each characters.
7554 Each element doesn't include such generic coding systems that can
7555 encode any characters. They are in the first extra slot. */);
7556 Vchar_coding_system_table = Fmake_char_table (Qchar_coding_system, Qnil);
7557
7558 DEFVAR_BOOL ("inhibit-iso-escape-detection",
7559 &inhibit_iso_escape_detection,
7560 doc: /* If non-nil, Emacs ignores ISO2022's escape sequence on code detection.
7561
7562 By default, on reading a file, Emacs tries to detect how the text is
7563 encoded. This code detection is sensitive to escape sequences. If
7564 the sequence is valid as ISO2022, the code is determined as one of
7565 the ISO2022 encodings, and the file is decoded by the corresponding
7566 coding system (e.g. `iso-2022-7bit').
7567
7568 However, there may be a case that you want to read escape sequences in
7569 a file as is. In such a case, you can set this variable to non-nil.
7570 Then, as the code detection ignores any escape sequences, no file is
7571 detected as encoded in some ISO2022 encoding. The result is that all
7572 escape sequences become visible in a buffer.
7573
7574 The default value is nil, and it is strongly recommended not to change
7575 it. That is because many Emacs Lisp source files that contain
7576 non-ASCII characters are encoded by the coding system `iso-2022-7bit'
7577 in Emacs's distribution, and they won't be decoded correctly on
7578 reading if you suppress escape sequence detection.
7579
7580 The other way to read escape sequences in a file without decoding is
7581 to explicitly specify some coding system that doesn't use ISO2022's
7582 escape sequence (e.g `latin-1') on reading by \\[universal-coding-system-argument]. */);
7583 inhibit_iso_escape_detection = 0;
7584 }
7585
7586 char *
7587 emacs_strerror (error_number)
7588 int error_number;
7589 {
7590 char *str;
7591
7592 synchronize_system_messages_locale ();
7593 str = strerror (error_number);
7594
7595 if (! NILP (Vlocale_coding_system))
7596 {
7597 Lisp_Object dec = code_convert_string_norecord (build_string (str),
7598 Vlocale_coding_system,
7599 0);
7600 str = (char *) SDATA (dec);
7601 }
7602
7603 return str;
7604 }
7605
7606 #endif /* emacs */
7607