(ER_BUF_SIZE): New macro.
[chise/xemacs-chise.git.1] / src / text-coding.c
1 /* Code conversion functions.
2    Copyright (C) 1991, 1995 Free Software Foundation, Inc.
3    Copyright (C) 1995 Sun Microsystems, Inc.
4    Copyright (C) 1999,2000,2001,2002,2003,2004 MORIOKA Tomohiko
5
6 This file is part of XEmacs.
7
8 XEmacs is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation; either version 2, or (at your option) any
11 later version.
12
13 XEmacs is distributed in the hope that it will be useful, but WITHOUT
14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with XEmacs; 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 /* Synched up with: Mule 2.3.   Not in FSF. */
24
25 /* Rewritten by Ben Wing <ben@xemacs.org>. */
26 /* Rewritten by MORIOKA Tomohiko <tomo@m17n.org> for XEmacs CHISE. */
27
28 #include <config.h>
29 #include "lisp.h"
30
31 #include "buffer.h"
32 #include "elhash.h"
33 #include "insdel.h"
34 #include "lstream.h"
35 #include "opaque.h"
36 #ifdef MULE
37 #include "mule-ccl.h"
38 #include "chartab.h"
39 #endif
40 #include "file-coding.h"
41
42 Lisp_Object Qcoding_system_error;
43
44 Lisp_Object Vkeyboard_coding_system;
45 Lisp_Object Vterminal_coding_system;
46 Lisp_Object Vcoding_system_for_read;
47 Lisp_Object Vcoding_system_for_write;
48 Lisp_Object Vfile_name_coding_system;
49
50 Lisp_Object Vcoded_charset_entity_reference_alist;
51
52 /* Table of symbols identifying each coding category. */
53 Lisp_Object coding_category_symbol[CODING_CATEGORY_LAST];
54
55
56
57 struct file_coding_dump {
58   /* Coding system currently associated with each coding category. */
59   Lisp_Object coding_category_system[CODING_CATEGORY_LAST];
60
61   /* Table of all coding categories in decreasing order of priority.
62      This describes a permutation of the possible coding categories. */
63   int coding_category_by_priority[CODING_CATEGORY_LAST];
64
65 #if defined(MULE) && !defined(UTF2000)
66   Lisp_Object ucs_to_mule_table[65536];
67 #endif
68 } *fcd;
69
70 static const struct lrecord_description fcd_description_1[] = {
71   { XD_LISP_OBJECT_ARRAY, offsetof (struct file_coding_dump, coding_category_system), CODING_CATEGORY_LAST },
72 #if defined(MULE) && !defined(UTF2000)
73   { XD_LISP_OBJECT_ARRAY, offsetof (struct file_coding_dump, ucs_to_mule_table), countof (fcd->ucs_to_mule_table) },
74 #endif
75   { XD_END }
76 };
77
78 static const struct struct_description fcd_description = {
79   sizeof (struct file_coding_dump),
80   fcd_description_1
81 };
82
83 Lisp_Object mule_to_ucs_table;
84
85 Lisp_Object Qcoding_systemp;
86
87 Lisp_Object Qraw_text, Qno_conversion, Qccl, Qiso2022;
88 /* Qinternal in general.c */
89
90 Lisp_Object Qmnemonic, Qeol_type;
91 Lisp_Object Qcr, Qcrlf, Qlf;
92 Lisp_Object Qeol_cr, Qeol_crlf, Qeol_lf;
93 Lisp_Object Qpost_read_conversion;
94 Lisp_Object Qpre_write_conversion;
95
96 #ifdef MULE
97 Lisp_Object Qucs4, Qutf16, Qutf8;
98 Lisp_Object Qbig5, Qshift_jis;
99 Lisp_Object Qcharset_g0, Qcharset_g1, Qcharset_g2, Qcharset_g3;
100 Lisp_Object Qforce_g0_on_output, Qforce_g1_on_output;
101 Lisp_Object Qforce_g2_on_output, Qforce_g3_on_output;
102 Lisp_Object Qno_iso6429;
103 Lisp_Object Qinput_charset_conversion, Qoutput_charset_conversion;
104 Lisp_Object Qescape_quoted;
105 Lisp_Object Qshort, Qno_ascii_eol, Qno_ascii_cntl, Qseven, Qlock_shift;
106 #endif
107 #ifdef UTF2000
108 Lisp_Object Qutf_8_mcs;
109 Lisp_Object Qdisable_composition;
110 Lisp_Object Quse_entity_reference;
111 Lisp_Object Qd, Qx, QX;
112 #endif
113 Lisp_Object Qencode, Qdecode;
114
115 Lisp_Object Vcoding_system_hash_table;
116
117 int enable_multibyte_characters;
118
119 #ifdef MULE
120 /* Additional information used by the ISO2022 decoder and detector. */
121 struct iso2022_decoder
122 {
123   /* CHARSET holds the character sets currently assigned to the G0
124      through G3 variables.  It is initialized from the array
125      INITIAL_CHARSET in CODESYS. */
126   Lisp_Object charset[4];
127
128   /* Which registers are currently invoked into the left (GL) and
129      right (GR) halves of the 8-bit encoding space? */
130   int register_left, register_right;
131
132   /* ISO_ESC holds a value indicating part of an escape sequence
133      that has already been seen. */
134   enum iso_esc_flag esc;
135
136   /* This records the bytes we've seen so far in an escape sequence,
137      in case the sequence is invalid (we spit out the bytes unchanged). */
138   unsigned char esc_bytes[8];
139
140   /* Index for next byte to store in ISO escape sequence. */
141   int esc_bytes_index;
142
143 #ifdef ENABLE_COMPOSITE_CHARS
144   /* Stuff seen so far when composing a string. */
145   unsigned_char_dynarr *composite_chars;
146 #endif
147
148   /* If we saw an invalid designation sequence for a particular
149      register, we flag it here and switch to ASCII.  The next time we
150      see a valid designation for this register, we turn off the flag
151      and do the designation normally, but pretend the sequence was
152      invalid.  The effect of all this is that (most of the time) the
153      escape sequences for both the switch to the unknown charset, and
154      the switch back to the known charset, get inserted literally into
155      the buffer and saved out as such.  The hope is that we can
156      preserve the escape sequences so that the resulting written out
157      file makes sense.  If we don't do any of this, the designation
158      to the invalid charset will be preserved but that switch back
159      to the known charset will probably get eaten because it was
160      the same charset that was already present in the register. */
161   unsigned char invalid_designated[4];
162
163   /* We try to do similar things as above for direction-switching
164      sequences.  If we encountered a direction switch while an
165      invalid designation was present, or an invalid designation
166      just after a direction switch (i.e. no valid designation
167      encountered yet), we insert the direction-switch escape
168      sequence literally into the output stream, and later on
169      insert the corresponding direction-restoring escape sequence
170      literally also. */
171   unsigned int switched_dir_and_no_valid_charset_yet :1;
172   unsigned int invalid_switch_dir :1;
173
174   /* Tells the decoder to output the escape sequence literally
175      even though it was valid.  Used in the games we play to
176      avoid lossage when we encounter invalid designations. */
177   unsigned int output_literally :1;
178   /* We encountered a direction switch followed by an invalid
179      designation.  We didn't output the direction switch
180      literally because we didn't know about the invalid designation;
181      but we have to do so now. */
182   unsigned int output_direction_sequence :1;
183 };
184 #endif /* MULE */
185 EXFUN (Fcopy_coding_system, 2);
186 #ifdef MULE
187 struct detection_state;
188
189 static void
190 text_encode_generic (Lstream *encoding, const Bufbyte *src,
191                      unsigned_char_dynarr *dst, Lstream_data_count n);
192
193 static int detect_coding_sjis (struct detection_state *st,
194                                const Extbyte *src, Lstream_data_count n);
195 static void decode_coding_sjis (Lstream *decoding, const Extbyte *src,
196                                 unsigned_char_dynarr *dst, Lstream_data_count n);
197 void char_encode_shift_jis (struct encoding_stream *str, Emchar c,
198                             unsigned_char_dynarr *dst, unsigned int *flags);
199 void char_finish_shift_jis (struct encoding_stream *str,
200                             unsigned_char_dynarr *dst, unsigned int *flags);
201
202 static int detect_coding_big5 (struct detection_state *st,
203                                const Extbyte *src, Lstream_data_count n);
204 static void decode_coding_big5 (Lstream *decoding, const Extbyte *src,
205                                 unsigned_char_dynarr *dst, Lstream_data_count n);
206 void char_encode_big5 (struct encoding_stream *str, Emchar c,
207                        unsigned_char_dynarr *dst, unsigned int *flags);
208 void char_finish_big5 (struct encoding_stream *str,
209                        unsigned_char_dynarr *dst, unsigned int *flags);
210
211 static int detect_coding_ucs4 (struct detection_state *st,
212                                const Extbyte *src, Lstream_data_count n);
213 static void decode_coding_ucs4 (Lstream *decoding, const Extbyte *src,
214                                 unsigned_char_dynarr *dst, Lstream_data_count n);
215 void char_encode_ucs4 (struct encoding_stream *str, Emchar c,
216                        unsigned_char_dynarr *dst, unsigned int *flags);
217 void char_finish_ucs4 (struct encoding_stream *str,
218                        unsigned_char_dynarr *dst, unsigned int *flags);
219
220 static int detect_coding_utf16 (struct detection_state *st,
221                                const Extbyte *src, Lstream_data_count n);
222 static void decode_coding_utf16 (Lstream *decoding, const Extbyte *src,
223                                 unsigned_char_dynarr *dst, Lstream_data_count n);
224 void char_encode_utf16 (struct encoding_stream *str, Emchar c,
225                        unsigned_char_dynarr *dst, unsigned int *flags);
226 void char_finish_utf16 (struct encoding_stream *str,
227                        unsigned_char_dynarr *dst, unsigned int *flags);
228
229 static int detect_coding_utf8 (struct detection_state *st,
230                                const Extbyte *src, Lstream_data_count n);
231 static void decode_coding_utf8 (Lstream *decoding, const Extbyte *src,
232                                 unsigned_char_dynarr *dst, Lstream_data_count n);
233 void char_encode_utf8 (struct encoding_stream *str, Emchar c,
234                        unsigned_char_dynarr *dst, unsigned int *flags);
235 void char_finish_utf8 (struct encoding_stream *str,
236                        unsigned_char_dynarr *dst, unsigned int *flags);
237
238 static int postprocess_iso2022_mask (int mask);
239 static void reset_iso2022 (Lisp_Object coding_system,
240                            struct iso2022_decoder *iso);
241 static int detect_coding_iso2022 (struct detection_state *st,
242                                   const Extbyte *src, Lstream_data_count n);
243 static void decode_coding_iso2022 (Lstream *decoding, const Extbyte *src,
244                                    unsigned_char_dynarr *dst, Lstream_data_count n);
245 void char_encode_iso2022 (struct encoding_stream *str, Emchar c,
246                           unsigned_char_dynarr *dst, unsigned int *flags);
247 void char_finish_iso2022 (struct encoding_stream *str,
248                           unsigned_char_dynarr *dst, unsigned int *flags);
249 #endif /* MULE */
250 static void decode_coding_no_conversion (Lstream *decoding, const Extbyte *src,
251                                          unsigned_char_dynarr *dst, Lstream_data_count n);
252 static void encode_coding_no_conversion (Lstream *encoding, const Bufbyte *src,
253                                          unsigned_char_dynarr *dst, Lstream_data_count n);
254 static void mule_decode (Lstream *decoding, const Extbyte *src,
255                          unsigned_char_dynarr *dst, Lstream_data_count n);
256 static void mule_encode (Lstream *encoding, const Bufbyte *src,
257                          unsigned_char_dynarr *dst, Lstream_data_count n);
258
259 typedef struct codesys_prop codesys_prop;
260 struct codesys_prop
261 {
262   Lisp_Object sym;
263   int prop_type;
264 };
265
266 typedef struct
267 {
268   Dynarr_declare (codesys_prop);
269 } codesys_prop_dynarr;
270
271 static const struct lrecord_description codesys_prop_description_1[] = {
272   { XD_LISP_OBJECT, offsetof (codesys_prop, sym) },
273   { XD_END }
274 };
275
276 static const struct struct_description codesys_prop_description = {
277   sizeof (codesys_prop),
278   codesys_prop_description_1
279 };
280
281 static const struct lrecord_description codesys_prop_dynarr_description_1[] = {
282   XD_DYNARR_DESC (codesys_prop_dynarr, &codesys_prop_description),
283   { XD_END }
284 };
285
286 static const struct struct_description codesys_prop_dynarr_description = {
287   sizeof (codesys_prop_dynarr),
288   codesys_prop_dynarr_description_1
289 };
290
291 codesys_prop_dynarr *the_codesys_prop_dynarr;
292
293 enum codesys_prop_enum
294 {
295   CODESYS_PROP_ALL_OK,
296   CODESYS_PROP_ISO2022,
297   CODESYS_PROP_CCL
298 };
299
300 \f
301 /************************************************************************/
302 /*                       Coding system functions                        */
303 /************************************************************************/
304
305 static Lisp_Object mark_coding_system (Lisp_Object);
306 static void print_coding_system (Lisp_Object, Lisp_Object, int);
307 static void finalize_coding_system (void *header, int for_disksave);
308
309 #ifdef MULE
310 static const struct lrecord_description ccs_description_1[] = {
311   { XD_LISP_OBJECT, offsetof (charset_conversion_spec, from_charset) },
312   { XD_LISP_OBJECT, offsetof (charset_conversion_spec, to_charset) },
313   { XD_END }
314 };
315
316 static const struct struct_description ccs_description = {
317   sizeof (charset_conversion_spec),
318   ccs_description_1
319 };
320
321 static const struct lrecord_description ccsd_description_1[] = {
322   XD_DYNARR_DESC (charset_conversion_spec_dynarr, &ccs_description),
323   { XD_END }
324 };
325
326 static const struct struct_description ccsd_description = {
327   sizeof (charset_conversion_spec_dynarr),
328   ccsd_description_1
329 };
330 #endif
331
332 static const struct lrecord_description coding_system_description[] = {
333   { XD_LISP_OBJECT, offsetof (Lisp_Coding_System, name) },
334   { XD_LISP_OBJECT, offsetof (Lisp_Coding_System, doc_string) },
335   { XD_LISP_OBJECT, offsetof (Lisp_Coding_System, mnemonic) },
336   { XD_LISP_OBJECT, offsetof (Lisp_Coding_System, post_read_conversion) },
337   { XD_LISP_OBJECT, offsetof (Lisp_Coding_System, pre_write_conversion) },
338   { XD_LISP_OBJECT, offsetof (Lisp_Coding_System, eol_lf) },
339   { XD_LISP_OBJECT, offsetof (Lisp_Coding_System, eol_crlf) },
340   { XD_LISP_OBJECT, offsetof (Lisp_Coding_System, eol_cr) },
341 #ifdef MULE
342   { XD_LISP_OBJECT_ARRAY, offsetof (Lisp_Coding_System, iso2022.initial_charset), 4 },
343   { XD_STRUCT_PTR,  offsetof (Lisp_Coding_System, iso2022.input_conv),  1, &ccsd_description },
344   { XD_STRUCT_PTR,  offsetof (Lisp_Coding_System, iso2022.output_conv), 1, &ccsd_description },
345   { XD_LISP_OBJECT, offsetof (Lisp_Coding_System, ccl.decode) },
346   { XD_LISP_OBJECT, offsetof (Lisp_Coding_System, ccl.encode) },
347 #ifdef UTF2000
348   { XD_LISP_OBJECT, offsetof (Lisp_Coding_System, ccs_priority_list) },
349 #endif
350 #endif
351   { XD_END }
352 };
353
354 DEFINE_LRECORD_IMPLEMENTATION ("coding-system", coding_system,
355                                mark_coding_system, print_coding_system,
356                                finalize_coding_system,
357                                0, 0, coding_system_description,
358                                Lisp_Coding_System);
359
360 static Lisp_Object
361 mark_coding_system (Lisp_Object obj)
362 {
363   Lisp_Coding_System *codesys = XCODING_SYSTEM (obj);
364
365   mark_object (CODING_SYSTEM_NAME (codesys));
366   mark_object (CODING_SYSTEM_DOC_STRING (codesys));
367   mark_object (CODING_SYSTEM_MNEMONIC (codesys));
368   mark_object (CODING_SYSTEM_EOL_LF (codesys));
369   mark_object (CODING_SYSTEM_EOL_CRLF (codesys));
370   mark_object (CODING_SYSTEM_EOL_CR (codesys));
371
372   switch (CODING_SYSTEM_TYPE (codesys))
373     {
374 #ifdef MULE
375       int i;
376     case CODESYS_ISO2022:
377       for (i = 0; i < 4; i++)
378         mark_object (CODING_SYSTEM_ISO2022_INITIAL_CHARSET (codesys, i));
379       if (codesys->iso2022.input_conv)
380         {
381           for (i = 0; i < Dynarr_length (codesys->iso2022.input_conv); i++)
382             {
383               struct charset_conversion_spec *ccs =
384                 Dynarr_atp (codesys->iso2022.input_conv, i);
385               mark_object (ccs->from_charset);
386               mark_object (ccs->to_charset);
387             }
388         }
389       if (codesys->iso2022.output_conv)
390         {
391           for (i = 0; i < Dynarr_length (codesys->iso2022.output_conv); i++)
392             {
393               struct charset_conversion_spec *ccs =
394                 Dynarr_atp (codesys->iso2022.output_conv, i);
395               mark_object (ccs->from_charset);
396               mark_object (ccs->to_charset);
397             }
398         }
399       break;
400 #ifdef UTF2000
401
402     case CODESYS_BIG5:
403       mark_object (CODING_SYSTEM_ISO2022_INITIAL_CHARSET (codesys, 0));
404       mark_object (CODING_SYSTEM_ISO2022_INITIAL_CHARSET (codesys, 1));
405       break;
406 #endif
407
408     case CODESYS_CCL:
409       mark_object (CODING_SYSTEM_CCL_DECODE (codesys));
410       mark_object (CODING_SYSTEM_CCL_ENCODE (codesys));
411       break;
412 #endif /* MULE */
413     default:
414       break;
415     }
416
417   mark_object (CODING_SYSTEM_PRE_WRITE_CONVERSION (codesys));
418 #ifdef UTF2000
419   mark_object (CODING_SYSTEM_CCS_PRIORITY_LIST (codesys));
420 #endif
421   return CODING_SYSTEM_POST_READ_CONVERSION (codesys);
422 }
423
424 static void
425 print_coding_system (Lisp_Object obj, Lisp_Object printcharfun,
426                      int escapeflag)
427 {
428   Lisp_Coding_System *c = XCODING_SYSTEM (obj);
429   if (print_readably)
430     error ("printing unreadable object #<coding_system 0x%x>",
431            c->header.uid);
432
433   write_c_string ("#<coding_system ", printcharfun);
434   print_internal (c->name, printcharfun, 1);
435   write_c_string (">", printcharfun);
436 }
437
438 static void
439 finalize_coding_system (void *header, int for_disksave)
440 {
441   Lisp_Coding_System *c = (Lisp_Coding_System *) header;
442   /* Since coding systems never go away, this function is not
443      necessary.  But it would be necessary if we changed things
444      so that coding systems could go away. */
445   if (!for_disksave) /* see comment in lstream.c */
446     {
447       switch (CODING_SYSTEM_TYPE (c))
448         {
449 #ifdef MULE
450         case CODESYS_ISO2022:
451           if (c->iso2022.input_conv)
452             {
453               Dynarr_free (c->iso2022.input_conv);
454               c->iso2022.input_conv = 0;
455             }
456           if (c->iso2022.output_conv)
457             {
458               Dynarr_free (c->iso2022.output_conv);
459               c->iso2022.output_conv = 0;
460             }
461           break;
462 #endif /* MULE */
463         default:
464           break;
465         }
466     }
467 }
468
469 static eol_type_t
470 symbol_to_eol_type (Lisp_Object symbol)
471 {
472   CHECK_SYMBOL (symbol);
473   if (NILP (symbol))      return EOL_AUTODETECT;
474   if (EQ (symbol, Qlf))   return EOL_LF;
475   if (EQ (symbol, Qcrlf)) return EOL_CRLF;
476   if (EQ (symbol, Qcr))   return EOL_CR;
477
478   signal_simple_error ("Unrecognized eol type", symbol);
479   return EOL_AUTODETECT; /* not reached */
480 }
481
482 static Lisp_Object
483 eol_type_to_symbol (eol_type_t type)
484 {
485   switch (type)
486     {
487     default: abort ();
488     case EOL_LF:         return Qlf;
489     case EOL_CRLF:       return Qcrlf;
490     case EOL_CR:         return Qcr;
491     case EOL_AUTODETECT: return Qnil;
492     }
493 }
494
495 static void
496 setup_eol_coding_systems (Lisp_Coding_System *codesys)
497 {
498   Lisp_Object codesys_obj;
499   int len = string_length (XSYMBOL (CODING_SYSTEM_NAME (codesys))->name);
500   char *codesys_name = (char *) alloca (len + 7);
501   int mlen = -1;
502   char *codesys_mnemonic=0;
503
504   Lisp_Object codesys_name_sym, sub_codesys_obj;
505
506   /* kludge */
507
508   XSETCODING_SYSTEM (codesys_obj, codesys);
509
510   memcpy (codesys_name,
511           string_data (XSYMBOL (CODING_SYSTEM_NAME (codesys))->name), len);
512
513   if (STRINGP (CODING_SYSTEM_MNEMONIC (codesys)))
514     {
515       mlen = XSTRING_LENGTH (CODING_SYSTEM_MNEMONIC (codesys));
516       codesys_mnemonic = (char *) alloca (mlen + 7);
517       memcpy (codesys_mnemonic,
518               XSTRING_DATA (CODING_SYSTEM_MNEMONIC (codesys)), mlen);
519     }
520
521 #define DEFINE_SUB_CODESYS(op_sys, op_sys_abbr, Type) do {                      \
522   strcpy (codesys_name + len, "-" op_sys);                                      \
523   if (mlen != -1)                                                               \
524     strcpy (codesys_mnemonic + mlen, op_sys_abbr);                              \
525   codesys_name_sym = intern (codesys_name);                                     \
526   sub_codesys_obj = Fcopy_coding_system (codesys_obj, codesys_name_sym);        \
527   XCODING_SYSTEM_EOL_TYPE (sub_codesys_obj) = Type;                             \
528   if (mlen != -1)                                                               \
529     XCODING_SYSTEM_MNEMONIC(sub_codesys_obj) =                                  \
530       build_string (codesys_mnemonic);                                          \
531   CODING_SYSTEM_##Type (codesys) = sub_codesys_obj;                             \
532 } while (0)
533
534   DEFINE_SUB_CODESYS("unix", "", EOL_LF);
535   DEFINE_SUB_CODESYS("dos",  ":T", EOL_CRLF);
536   DEFINE_SUB_CODESYS("mac",  ":t", EOL_CR);
537 }
538
539 DEFUN ("coding-system-p", Fcoding_system_p, 1, 1, 0, /*
540 Return t if OBJECT is a coding system.
541 A coding system is an object that defines how text containing multiple
542 character sets is encoded into a stream of (typically 8-bit) bytes.
543 The coding system is used to decode the stream into a series of
544 characters (which may be from multiple charsets) when the text is read
545 from a file or process, and is used to encode the text back into the
546 same format when it is written out to a file or process.
547
548 For example, many ISO2022-compliant coding systems (such as Compound
549 Text, which is used for inter-client data under the X Window System)
550 use escape sequences to switch between different charsets -- Japanese
551 Kanji, for example, is invoked with "ESC $ ( B"; ASCII is invoked
552 with "ESC ( B"; and Cyrillic is invoked with "ESC - L".  See
553 `make-coding-system' for more information.
554
555 Coding systems are normally identified using a symbol, and the
556 symbol is accepted in place of the actual coding system object whenever
557 a coding system is called for. (This is similar to how faces work.)
558 */
559        (object))
560 {
561   return CODING_SYSTEMP (object) ? Qt : Qnil;
562 }
563
564 DEFUN ("find-coding-system", Ffind_coding_system, 1, 1, 0, /*
565 Retrieve the coding system of the given name.
566
567 If CODING-SYSTEM-OR-NAME is a coding-system object, it is simply
568 returned.  Otherwise, CODING-SYSTEM-OR-NAME should be a symbol.
569 If there is no such coding system, nil is returned.  Otherwise the
570 associated coding system object is returned.
571 */
572        (coding_system_or_name))
573 {
574   if (NILP (coding_system_or_name))
575     coding_system_or_name = Qbinary;
576   else if (CODING_SYSTEMP (coding_system_or_name))
577     return coding_system_or_name;
578   else
579     CHECK_SYMBOL (coding_system_or_name);
580
581   while (1)
582     {
583       coding_system_or_name =
584         Fgethash (coding_system_or_name, Vcoding_system_hash_table, Qnil);
585
586       if (CODING_SYSTEMP (coding_system_or_name) || NILP (coding_system_or_name))
587         return coding_system_or_name;
588     }
589 }
590
591 DEFUN ("get-coding-system", Fget_coding_system, 1, 1, 0, /*
592 Retrieve the coding system of the given name.
593 Same as `find-coding-system' except that if there is no such
594 coding system, an error is signaled instead of returning nil.
595 */
596        (name))
597 {
598   Lisp_Object coding_system = Ffind_coding_system (name);
599
600   if (NILP (coding_system))
601     signal_simple_error ("No such coding system", name);
602   return coding_system;
603 }
604
605 /* We store the coding systems in hash tables with the names as the key and the
606    actual coding system object as the value.  Occasionally we need to use them
607    in a list format.  These routines provide us with that. */
608 struct coding_system_list_closure
609 {
610   Lisp_Object *coding_system_list;
611 };
612
613 static int
614 add_coding_system_to_list_mapper (Lisp_Object key, Lisp_Object value,
615                                   void *coding_system_list_closure)
616 {
617   /* This function can GC */
618   struct coding_system_list_closure *cscl =
619     (struct coding_system_list_closure *) coding_system_list_closure;
620   Lisp_Object *coding_system_list = cscl->coding_system_list;
621
622   *coding_system_list = Fcons (key, *coding_system_list);
623   return 0;
624 }
625
626 DEFUN ("coding-system-list", Fcoding_system_list, 0, 0, 0, /*
627 Return a list of the names of all defined coding systems.
628 */
629        ())
630 {
631   Lisp_Object coding_system_list = Qnil;
632   struct gcpro gcpro1;
633   struct coding_system_list_closure coding_system_list_closure;
634
635   GCPRO1 (coding_system_list);
636   coding_system_list_closure.coding_system_list = &coding_system_list;
637   elisp_maphash (add_coding_system_to_list_mapper, Vcoding_system_hash_table,
638                  &coding_system_list_closure);
639   UNGCPRO;
640
641   return coding_system_list;
642 }
643
644 DEFUN ("coding-system-name", Fcoding_system_name, 1, 1, 0, /*
645 Return the name of the given coding system.
646 */
647        (coding_system))
648 {
649   coding_system = Fget_coding_system (coding_system);
650   return XCODING_SYSTEM_NAME (coding_system);
651 }
652
653 static Lisp_Coding_System *
654 allocate_coding_system (enum coding_system_type type, Lisp_Object name)
655 {
656   Lisp_Coding_System *codesys =
657     alloc_lcrecord_type (Lisp_Coding_System, &lrecord_coding_system);
658
659   zero_lcrecord (codesys);
660   CODING_SYSTEM_PRE_WRITE_CONVERSION (codesys) = Qnil;
661   CODING_SYSTEM_POST_READ_CONVERSION (codesys) = Qnil;
662   CODING_SYSTEM_EOL_TYPE (codesys) = EOL_AUTODETECT;
663   CODING_SYSTEM_EOL_CRLF (codesys) = Qnil;
664   CODING_SYSTEM_EOL_CR   (codesys) = Qnil;
665   CODING_SYSTEM_EOL_LF   (codesys) = Qnil;
666   CODING_SYSTEM_TYPE     (codesys) = type;
667   CODING_SYSTEM_MNEMONIC (codesys) = Qnil;
668 #ifdef MULE
669 #ifdef UTF2000
670   CODING_SYSTEM_CCS_PRIORITY_LIST (codesys) = Qnil;
671 #endif
672   if (type == CODESYS_ISO2022)
673     {
674       int i;
675       for (i = 0; i < 4; i++)
676         CODING_SYSTEM_ISO2022_INITIAL_CHARSET (codesys, i) = Qnil;
677     }
678 #ifdef UTF2000
679   if (type == CODESYS_UTF8)
680     {
681       CODING_SYSTEM_ISO2022_INITIAL_CHARSET (codesys, 0)
682         = Vcharset_ucs;
683       CODING_SYSTEM_ISO2022_INITIAL_CHARSET (codesys, 1)
684         = Qnil;
685       CODING_SYSTEM_ISO2022_INITIAL_CHARSET (codesys, 2)
686         = Qnil;
687       CODING_SYSTEM_ISO2022_INITIAL_CHARSET (codesys, 3)
688         = Qnil;
689     }
690   else if (type == CODESYS_BIG5)
691     {
692       CODING_SYSTEM_ISO2022_INITIAL_CHARSET (codesys, 0)
693         = Vcharset_ascii;
694       CODING_SYSTEM_ISO2022_INITIAL_CHARSET (codesys, 1)
695         = Vcharset_chinese_big5;
696       CODING_SYSTEM_ISO2022_INITIAL_CHARSET (codesys, 2)
697         = Qnil;
698       CODING_SYSTEM_ISO2022_INITIAL_CHARSET (codesys, 3)
699         = Qnil;
700     }
701 #endif
702   else if (type == CODESYS_CCL)
703     {
704       CODING_SYSTEM_CCL_DECODE (codesys) = Qnil;
705       CODING_SYSTEM_CCL_ENCODE (codesys) = Qnil;
706     }
707 #endif /* MULE */
708   CODING_SYSTEM_NAME (codesys) = name;
709
710   return codesys;
711 }
712
713 #ifdef MULE
714 /* Given a list of charset conversion specs as specified in a Lisp
715    program, parse it into STORE_HERE. */
716
717 static void
718 parse_charset_conversion_specs (charset_conversion_spec_dynarr *store_here,
719                                 Lisp_Object spec_list)
720 {
721   Lisp_Object rest;
722
723   EXTERNAL_LIST_LOOP (rest, spec_list)
724     {
725       Lisp_Object car = XCAR (rest);
726       Lisp_Object from, to;
727       struct charset_conversion_spec spec;
728
729       if (!CONSP (car) || !CONSP (XCDR (car)) || !NILP (XCDR (XCDR (car))))
730         signal_simple_error ("Invalid charset conversion spec", car);
731       from = Fget_charset (XCAR (car));
732       to = Fget_charset (XCAR (XCDR (car)));
733       if ( (XCHARSET_CHARS (from) != XCHARSET_CHARS (to)) ||
734            (XCHARSET_DIMENSION (from) != XCHARSET_DIMENSION (to)) )
735         signal_simple_error_2
736           ("Attempted conversion between different charset types",
737            from, to);
738       spec.from_charset = from;
739       spec.to_charset = to;
740
741       Dynarr_add (store_here, spec);
742     }
743 }
744
745 /* Given a dynarr LOAD_HERE of internally-stored charset conversion
746    specs, return the equivalent as the Lisp programmer would see it.
747
748    If LOAD_HERE is 0, return Qnil. */
749
750 static Lisp_Object
751 unparse_charset_conversion_specs (charset_conversion_spec_dynarr *load_here)
752 {
753   int i;
754   Lisp_Object result;
755
756   if (!load_here)
757     return Qnil;
758   for (i = 0, result = Qnil; i < Dynarr_length (load_here); i++)
759     {
760       struct charset_conversion_spec *ccs = Dynarr_atp (load_here, i);
761       result = Fcons (list2 (ccs->from_charset, ccs->to_charset), result);
762     }
763
764   return Fnreverse (result);
765 }
766
767 #endif /* MULE */
768
769 DEFUN ("make-coding-system", Fmake_coding_system, 2, 4, 0, /*
770 Register symbol NAME as a coding system.
771
772 TYPE describes the conversion method used and should be one of
773
774 nil or 'undecided
775      Automatic conversion.  XEmacs attempts to detect the coding system
776      used in the file.
777 'no-conversion
778      No conversion.  Use this for binary files and such.  On output,
779      graphic characters that are not in ASCII or Latin-1 will be
780      replaced by a ?. (For a no-conversion-encoded buffer, these
781      characters will only be present if you explicitly insert them.)
782 'shift-jis
783      Shift-JIS (a Japanese encoding commonly used in PC operating systems).
784 'ucs-4
785      ISO 10646 UCS-4 encoding.
786 'utf-8
787      ISO 10646 UTF-8 encoding.
788 'iso2022
789      Any ISO2022-compliant encoding.  Among other things, this includes
790      JIS (the Japanese encoding commonly used for e-mail), EUC (the
791      standard Unix encoding for Japanese and other languages), and
792      Compound Text (the encoding used in X11).  You can specify more
793      specific information about the conversion with the PROPS argument.
794 'big5
795      Big5 (the encoding commonly used for Taiwanese).
796 'ccl
797      The conversion is performed using a user-written pseudo-code
798      program.  CCL (Code Conversion Language) is the name of this
799      pseudo-code.
800 'internal
801      Write out or read in the raw contents of the memory representing
802      the buffer's text.  This is primarily useful for debugging
803      purposes, and is only enabled when XEmacs has been compiled with
804      DEBUG_XEMACS defined (via the --debug configure option).
805      WARNING: Reading in a file using 'internal conversion can result
806      in an internal inconsistency in the memory representing a
807      buffer's text, which will produce unpredictable results and may
808      cause XEmacs to crash.  Under normal circumstances you should
809      never use 'internal conversion.
810
811 DOC-STRING is a string describing the coding system.
812
813 PROPS is a property list, describing the specific nature of the
814 character set.  Recognized properties are:
815
816 'mnemonic
817      String to be displayed in the modeline when this coding system is
818      active.
819
820 'eol-type
821      End-of-line conversion to be used.  It should be one of
822
823         nil
824                 Automatically detect the end-of-line type (LF, CRLF,
825                 or CR).  Also generate subsidiary coding systems named
826                 `NAME-unix', `NAME-dos', and `NAME-mac', that are
827                 identical to this coding system but have an EOL-TYPE
828                 value of 'lf, 'crlf, and 'cr, respectively.
829         'lf
830                 The end of a line is marked externally using ASCII LF.
831                 Since this is also the way that XEmacs represents an
832                 end-of-line internally, specifying this option results
833                 in no end-of-line conversion.  This is the standard
834                 format for Unix text files.
835         'crlf
836                 The end of a line is marked externally using ASCII
837                 CRLF.  This is the standard format for MS-DOS text
838                 files.
839         'cr
840                 The end of a line is marked externally using ASCII CR.
841                 This is the standard format for Macintosh text files.
842         t
843                 Automatically detect the end-of-line type but do not
844                 generate subsidiary coding systems.  (This value is
845                 converted to nil when stored internally, and
846                 `coding-system-property' will return nil.)
847
848 'disable-composition
849      If non-nil, composition/decomposition for combining characters
850      are disabled.
851
852 'use-entity-reference
853      If non-nil, SGML style entity-reference is used for non-system-characters.
854
855 'post-read-conversion
856      Function called after a file has been read in, to perform the
857      decoding.  Called with two arguments, START and END, denoting
858      a region of the current buffer to be decoded.
859
860 'pre-write-conversion
861      Function called before a file is written out, to perform the
862      encoding.  Called with two arguments, START and END, denoting
863      a region of the current buffer to be encoded.
864
865
866 The following additional properties are recognized if TYPE is 'iso2022:
867
868 'charset-g0
869 'charset-g1
870 'charset-g2
871 'charset-g3
872      The character set initially designated to the G0 - G3 registers.
873      The value should be one of
874
875           -- A charset object (designate that character set)
876           -- nil (do not ever use this register)
877           -- t (no character set is initially designated to
878                 the register, but may be later on; this automatically
879                 sets the corresponding `force-g*-on-output' property)
880
881 'force-g0-on-output
882 'force-g1-on-output
883 'force-g2-on-output
884 'force-g2-on-output
885      If non-nil, send an explicit designation sequence on output before
886      using the specified register.
887
888 'short
889      If non-nil, use the short forms "ESC $ @", "ESC $ A", and
890      "ESC $ B" on output in place of the full designation sequences
891      "ESC $ ( @", "ESC $ ( A", and "ESC $ ( B".
892
893 'no-ascii-eol
894      If non-nil, don't designate ASCII to G0 at each end of line on output.
895      Setting this to non-nil also suppresses other state-resetting that
896      normally happens at the end of a line.
897
898 'no-ascii-cntl
899      If non-nil, don't designate ASCII to G0 before control chars on output.
900
901 'seven
902      If non-nil, use 7-bit environment on output.  Otherwise, use 8-bit
903      environment.
904
905 'lock-shift
906      If non-nil, use locking-shift (SO/SI) instead of single-shift
907      or designation by escape sequence.
908
909 'no-iso6429
910      If non-nil, don't use ISO6429's direction specification.
911
912 'escape-quoted
913      If non-nil, literal control characters that are the same as
914      the beginning of a recognized ISO2022 or ISO6429 escape sequence
915      (in particular, ESC (0x1B), SO (0x0E), SI (0x0F), SS2 (0x8E),
916      SS3 (0x8F), and CSI (0x9B)) are "quoted" with an escape character
917      so that they can be properly distinguished from an escape sequence.
918      (Note that doing this results in a non-portable encoding.) This
919      encoding flag is used for byte-compiled files.  Note that ESC
920      is a good choice for a quoting character because there are no
921      escape sequences whose second byte is a character from the Control-0
922      or Control-1 character sets; this is explicitly disallowed by the
923      ISO2022 standard.
924
925 'input-charset-conversion
926      A list of conversion specifications, specifying conversion of
927      characters in one charset to another when decoding is performed.
928      Each specification is a list of two elements: the source charset,
929      and the destination charset.
930
931 'output-charset-conversion
932      A list of conversion specifications, specifying conversion of
933      characters in one charset to another when encoding is performed.
934      The form of each specification is the same as for
935      'input-charset-conversion.
936
937
938 The following additional properties are recognized (and required)
939 if TYPE is 'ccl:
940
941 'decode
942      CCL program used for decoding (converting to internal format).
943
944 'encode
945      CCL program used for encoding (converting to external format).
946 */
947        (name, type, doc_string, props))
948 {
949   Lisp_Coding_System *codesys;
950   enum coding_system_type ty;
951   int need_to_setup_eol_systems = 1;
952
953   /* Convert type to constant */
954   if (NILP (type) || EQ (type, Qundecided))
955                                       { ty = CODESYS_AUTODETECT; }
956 #ifdef MULE
957   else if (EQ (type, Qshift_jis))     { ty = CODESYS_SHIFT_JIS; }
958   else if (EQ (type, Qiso2022))       { ty = CODESYS_ISO2022; }
959   else if (EQ (type, Qbig5))          { ty = CODESYS_BIG5; }
960   else if (EQ (type, Qucs4))          { ty = CODESYS_UCS4; }
961   else if (EQ (type, Qutf16))         { ty = CODESYS_UTF16; }
962   else if (EQ (type, Qutf8))          { ty = CODESYS_UTF8; }
963   else if (EQ (type, Qccl))           { ty = CODESYS_CCL; }
964 #endif
965   else if (EQ (type, Qno_conversion)) { ty = CODESYS_NO_CONVERSION; }
966 #ifdef DEBUG_XEMACS
967   else if (EQ (type, Qinternal))      { ty = CODESYS_INTERNAL; }
968 #endif
969   else
970     signal_simple_error ("Invalid coding system type", type);
971
972   CHECK_SYMBOL (name);
973
974   codesys = allocate_coding_system (ty, name);
975
976   if (NILP (doc_string))
977     doc_string = build_string ("");
978   else
979     CHECK_STRING (doc_string);
980   CODING_SYSTEM_DOC_STRING (codesys) = doc_string;
981
982   {
983     EXTERNAL_PROPERTY_LIST_LOOP_3 (key, value, props)
984       {
985         if (EQ (key, Qmnemonic))
986           {
987             if (!NILP (value))
988               CHECK_STRING (value);
989             CODING_SYSTEM_MNEMONIC (codesys) = value;
990           }
991
992         else if (EQ (key, Qeol_type))
993           {
994             need_to_setup_eol_systems = NILP (value);
995             if (EQ (value, Qt))
996               value = Qnil;
997             CODING_SYSTEM_EOL_TYPE (codesys) = symbol_to_eol_type (value);
998           }
999
1000         else if (EQ (key, Qpost_read_conversion))
1001           CODING_SYSTEM_POST_READ_CONVERSION (codesys) = value;
1002         else if (EQ (key, Qpre_write_conversion))
1003           CODING_SYSTEM_PRE_WRITE_CONVERSION (codesys) = value;
1004 #ifdef UTF2000
1005         else if (EQ (key, Qdisable_composition))
1006           CODING_SYSTEM_DISABLE_COMPOSITION (codesys) = !NILP (value);
1007         else if (EQ (key, Quse_entity_reference))
1008           CODING_SYSTEM_USE_ENTITY_REFERENCE (codesys) = !NILP (value);
1009 #endif
1010 #ifdef MULE
1011         else if (ty == CODESYS_ISO2022)
1012           {
1013 #define FROB_INITIAL_CHARSET(charset_num) \
1014   CODING_SYSTEM_ISO2022_INITIAL_CHARSET (codesys, charset_num) = \
1015     ((EQ (value, Qt) || EQ (value, Qnil)) ? value : Fget_charset (value))
1016
1017             if      (EQ (key, Qcharset_g0)) FROB_INITIAL_CHARSET (0);
1018             else if (EQ (key, Qcharset_g1)) FROB_INITIAL_CHARSET (1);
1019             else if (EQ (key, Qcharset_g2)) FROB_INITIAL_CHARSET (2);
1020             else if (EQ (key, Qcharset_g3)) FROB_INITIAL_CHARSET (3);
1021
1022 #define FROB_FORCE_CHARSET(charset_num) \
1023   CODING_SYSTEM_ISO2022_FORCE_CHARSET_ON_OUTPUT (codesys, charset_num) = !NILP (value)
1024
1025             else if (EQ (key, Qforce_g0_on_output)) FROB_FORCE_CHARSET (0);
1026             else if (EQ (key, Qforce_g1_on_output)) FROB_FORCE_CHARSET (1);
1027             else if (EQ (key, Qforce_g2_on_output)) FROB_FORCE_CHARSET (2);
1028             else if (EQ (key, Qforce_g3_on_output)) FROB_FORCE_CHARSET (3);
1029
1030 #define FROB_BOOLEAN_PROPERTY(prop) \
1031   CODING_SYSTEM_ISO2022_##prop (codesys) = !NILP (value)
1032
1033             else if (EQ (key, Qshort))         FROB_BOOLEAN_PROPERTY (SHORT);
1034             else if (EQ (key, Qno_ascii_eol))  FROB_BOOLEAN_PROPERTY (NO_ASCII_EOL);
1035             else if (EQ (key, Qno_ascii_cntl)) FROB_BOOLEAN_PROPERTY (NO_ASCII_CNTL);
1036             else if (EQ (key, Qseven))         FROB_BOOLEAN_PROPERTY (SEVEN);
1037             else if (EQ (key, Qlock_shift))    FROB_BOOLEAN_PROPERTY (LOCK_SHIFT);
1038             else if (EQ (key, Qno_iso6429))    FROB_BOOLEAN_PROPERTY (NO_ISO6429);
1039             else if (EQ (key, Qescape_quoted)) FROB_BOOLEAN_PROPERTY (ESCAPE_QUOTED);
1040
1041             else if (EQ (key, Qinput_charset_conversion))
1042               {
1043                 codesys->iso2022.input_conv =
1044                   Dynarr_new (charset_conversion_spec);
1045                 parse_charset_conversion_specs (codesys->iso2022.input_conv,
1046                                                 value);
1047               }
1048             else if (EQ (key, Qoutput_charset_conversion))
1049               {
1050                 codesys->iso2022.output_conv =
1051                   Dynarr_new (charset_conversion_spec);
1052                 parse_charset_conversion_specs (codesys->iso2022.output_conv,
1053                                                 value);
1054               }
1055             else
1056               signal_simple_error ("Unrecognized property", key);
1057           }
1058 #ifdef UTF2000
1059         else if (ty == CODESYS_UTF8)
1060           {
1061             if      (EQ (key, Qcharset_g0)) FROB_INITIAL_CHARSET (0);
1062             else if (EQ (key, Qcharset_g1))
1063               CODING_SYSTEM_ISO2022_INITIAL_CHARSET (codesys, 1) = value;
1064             else if (EQ (key, Qcharset_g2))
1065               CODING_SYSTEM_ISO2022_INITIAL_CHARSET (codesys, 2) = value;
1066             else
1067               signal_simple_error ("Unrecognized property", key);
1068           }
1069         else if (ty == CODESYS_BIG5)
1070           {
1071             if      (EQ (key, Qcharset_g0)) FROB_INITIAL_CHARSET (0);
1072             else if (EQ (key, Qcharset_g1)) FROB_INITIAL_CHARSET (1);
1073             else
1074               signal_simple_error ("Unrecognized property", key);
1075           }
1076 #endif
1077         else if (EQ (type, Qccl))
1078           {
1079             Lisp_Object sym;
1080             struct ccl_program test_ccl;
1081             Extbyte *suffix;
1082
1083             /* Check key first.  */
1084             if (EQ (key, Qdecode))
1085               suffix = "-ccl-decode";
1086             else if (EQ (key, Qencode))
1087               suffix = "-ccl-encode";
1088             else
1089               signal_simple_error ("Unrecognized property", key);
1090
1091             /* If value is vector, register it as a ccl program
1092                associated with an newly created symbol for
1093                backward compatibility.  */
1094             if (VECTORP (value))
1095               {
1096                 sym = Fintern (concat2 (Fsymbol_name (name),
1097                                         build_string (suffix)),
1098                                Qnil);
1099                 Fregister_ccl_program (sym, value);
1100               }
1101             else
1102               {
1103                 CHECK_SYMBOL (value);
1104                 sym = value;
1105               }
1106             /* check if the given ccl programs are valid.  */
1107             if (setup_ccl_program (&test_ccl, sym) < 0)
1108               signal_simple_error ("Invalid CCL program", value);
1109
1110             if (EQ (key, Qdecode))
1111               CODING_SYSTEM_CCL_DECODE (codesys) = sym;
1112             else if (EQ (key, Qencode))
1113               CODING_SYSTEM_CCL_ENCODE (codesys) = sym;
1114
1115           }
1116 #endif /* MULE */
1117         else
1118           signal_simple_error ("Unrecognized property", key);
1119       }
1120   }
1121
1122   if (need_to_setup_eol_systems)
1123     setup_eol_coding_systems (codesys);
1124
1125   {
1126     Lisp_Object codesys_obj;
1127     XSETCODING_SYSTEM (codesys_obj, codesys);
1128     Fputhash (name, codesys_obj, Vcoding_system_hash_table);
1129     return codesys_obj;
1130   }
1131 }
1132
1133 DEFUN ("copy-coding-system", Fcopy_coding_system, 2, 2, 0, /*
1134 Copy OLD-CODING-SYSTEM to NEW-NAME.
1135 If NEW-NAME does not name an existing coding system, a new one will
1136 be created.
1137 */
1138        (old_coding_system, new_name))
1139 {
1140   Lisp_Object new_coding_system;
1141   old_coding_system = Fget_coding_system (old_coding_system);
1142   new_coding_system = Ffind_coding_system (new_name);
1143   if (NILP (new_coding_system))
1144     {
1145       XSETCODING_SYSTEM (new_coding_system,
1146                          allocate_coding_system
1147                          (XCODING_SYSTEM_TYPE (old_coding_system),
1148                           new_name));
1149       Fputhash (new_name, new_coding_system, Vcoding_system_hash_table);
1150     }
1151
1152   {
1153     Lisp_Coding_System *to = XCODING_SYSTEM (new_coding_system);
1154     Lisp_Coding_System *from = XCODING_SYSTEM (old_coding_system);
1155     memcpy (((char *) to  ) + sizeof (to->header),
1156             ((char *) from) + sizeof (from->header),
1157             sizeof (*from) - sizeof (from->header));
1158     to->name = new_name;
1159   }
1160   return new_coding_system;
1161 }
1162
1163 DEFUN ("coding-system-canonical-name-p", Fcoding_system_canonical_name_p, 1, 1, 0, /*
1164 Return t if OBJECT names a coding system, and is not a coding system alias.
1165 */
1166        (object))
1167 {
1168   return CODING_SYSTEMP (Fgethash (object, Vcoding_system_hash_table, Qnil))
1169     ? Qt : Qnil;
1170 }
1171
1172 DEFUN ("coding-system-alias-p", Fcoding_system_alias_p, 1, 1, 0, /*
1173 Return t if OBJECT is a coding system alias.
1174 All coding system aliases are created by `define-coding-system-alias'.
1175 */
1176        (object))
1177 {
1178   return SYMBOLP (Fgethash (object, Vcoding_system_hash_table, Qzero))
1179     ? Qt : Qnil;
1180 }
1181
1182 DEFUN ("coding-system-aliasee", Fcoding_system_aliasee, 1, 1, 0, /*
1183 Return the coding-system symbol for which symbol ALIAS is an alias.
1184 */
1185        (alias))
1186 {
1187   Lisp_Object aliasee = Fgethash (alias, Vcoding_system_hash_table, Qnil);
1188   if (SYMBOLP (aliasee))
1189     return aliasee;
1190   else
1191     signal_simple_error ("Symbol is not a coding system alias", alias);
1192   return Qnil;          /* To keep the compiler happy */
1193 }
1194
1195 static Lisp_Object
1196 append_suffix_to_symbol (Lisp_Object symbol, const char *ascii_string)
1197 {
1198   return Fintern (concat2 (Fsymbol_name (symbol), build_string (ascii_string)),
1199                   Qnil);
1200 }
1201
1202 /* A maphash function, for removing dangling coding system aliases. */
1203 static int
1204 dangling_coding_system_alias_p (Lisp_Object alias,
1205                                 Lisp_Object aliasee,
1206                                 void *dangling_aliases)
1207 {
1208   if (SYMBOLP (aliasee)
1209       && NILP (Fgethash (aliasee, Vcoding_system_hash_table, Qnil)))
1210     {
1211       (*(int *) dangling_aliases)++;
1212       return 1;
1213     }
1214   else
1215     return 0;
1216 }
1217
1218 DEFUN ("define-coding-system-alias", Fdefine_coding_system_alias, 2, 2, 0, /*
1219 Define symbol ALIAS as an alias for coding system ALIASEE.
1220
1221 You can use this function to redefine an alias that has already been defined,
1222 but you cannot redefine a name which is the canonical name for a coding system.
1223 \(a canonical name of a coding system is what is returned when you call
1224 `coding-system-name' on a coding system).
1225
1226 ALIASEE itself can be an alias, which allows you to define nested aliases.
1227
1228 You are forbidden, however, from creating alias loops or `dangling' aliases.
1229 These will be detected, and an error will be signaled if you attempt to do so.
1230
1231 If ALIASEE is nil, then ALIAS will simply be undefined.
1232
1233 See also `coding-system-alias-p', `coding-system-aliasee',
1234 and `coding-system-canonical-name-p'.
1235 */
1236        (alias, aliasee))
1237 {
1238   Lisp_Object real_coding_system, probe;
1239
1240   CHECK_SYMBOL (alias);
1241
1242   if (!NILP (Fcoding_system_canonical_name_p (alias)))
1243     signal_simple_error
1244       ("Symbol is the canonical name of a coding system and cannot be redefined",
1245        alias);
1246
1247   if (NILP (aliasee))
1248     {
1249       Lisp_Object subsidiary_unix = append_suffix_to_symbol (alias, "-unix");
1250       Lisp_Object subsidiary_dos  = append_suffix_to_symbol (alias, "-dos");
1251       Lisp_Object subsidiary_mac  = append_suffix_to_symbol (alias, "-mac");
1252
1253       Fremhash (alias, Vcoding_system_hash_table);
1254
1255       /* Undefine subsidiary aliases,
1256          presumably created by a previous call to this function */
1257       if (! NILP (Fcoding_system_alias_p (subsidiary_unix)) &&
1258           ! NILP (Fcoding_system_alias_p (subsidiary_dos))  &&
1259           ! NILP (Fcoding_system_alias_p (subsidiary_mac)))
1260         {
1261           Fdefine_coding_system_alias (subsidiary_unix, Qnil);
1262           Fdefine_coding_system_alias (subsidiary_dos,  Qnil);
1263           Fdefine_coding_system_alias (subsidiary_mac,  Qnil);
1264         }
1265
1266       /* Undefine dangling coding system aliases. */
1267       {
1268         int dangling_aliases;
1269
1270         do {
1271           dangling_aliases = 0;
1272           elisp_map_remhash (dangling_coding_system_alias_p,
1273                              Vcoding_system_hash_table,
1274                              &dangling_aliases);
1275         } while (dangling_aliases > 0);
1276       }
1277
1278       return Qnil;
1279     }
1280
1281   if (CODING_SYSTEMP (aliasee))
1282     aliasee = XCODING_SYSTEM_NAME (aliasee);
1283
1284   /* Checks that aliasee names a coding-system */
1285   real_coding_system = Fget_coding_system (aliasee);
1286
1287   /* Check for coding system alias loops */
1288   if (EQ (alias, aliasee))
1289     alias_loop: signal_simple_error_2
1290       ("Attempt to create a coding system alias loop", alias, aliasee);
1291
1292   for (probe = aliasee;
1293        SYMBOLP (probe);
1294        probe = Fgethash (probe, Vcoding_system_hash_table, Qzero))
1295     {
1296       if (EQ (probe, alias))
1297         goto alias_loop;
1298     }
1299
1300   Fputhash (alias, aliasee, Vcoding_system_hash_table);
1301
1302   /* Set up aliases for subsidiaries.
1303      #### There must be a better way to handle subsidiary coding systems. */
1304   {
1305     static const char *suffixes[] = { "-unix", "-dos", "-mac" };
1306     int i;
1307     for (i = 0; i < countof (suffixes); i++)
1308       {
1309         Lisp_Object alias_subsidiary =
1310           append_suffix_to_symbol (alias, suffixes[i]);
1311         Lisp_Object aliasee_subsidiary =
1312           append_suffix_to_symbol (aliasee, suffixes[i]);
1313
1314         if (! NILP (Ffind_coding_system (aliasee_subsidiary)))
1315           Fdefine_coding_system_alias (alias_subsidiary, aliasee_subsidiary);
1316       }
1317   }
1318   /* FSF return value is a vector of [ALIAS-unix ALIAS-dos ALIAS-mac],
1319      but it doesn't look intentional, so I'd rather return something
1320      meaningful or nothing at all. */
1321   return Qnil;
1322 }
1323
1324 static Lisp_Object
1325 subsidiary_coding_system (Lisp_Object coding_system, eol_type_t type)
1326 {
1327   Lisp_Coding_System *cs = XCODING_SYSTEM (coding_system);
1328   Lisp_Object new_coding_system;
1329
1330   if (CODING_SYSTEM_EOL_TYPE (cs) != EOL_AUTODETECT)
1331     return coding_system;
1332
1333   switch (type)
1334     {
1335     case EOL_AUTODETECT: return coding_system;
1336     case EOL_LF:   new_coding_system = CODING_SYSTEM_EOL_LF   (cs); break;
1337     case EOL_CR:   new_coding_system = CODING_SYSTEM_EOL_CR   (cs); break;
1338     case EOL_CRLF: new_coding_system = CODING_SYSTEM_EOL_CRLF (cs); break;
1339     default:       abort (); return Qnil;
1340     }
1341
1342   return NILP (new_coding_system) ? coding_system : new_coding_system;
1343 }
1344
1345 DEFUN ("subsidiary-coding-system", Fsubsidiary_coding_system, 2, 2, 0, /*
1346 Return the subsidiary coding system of CODING-SYSTEM with eol type EOL-TYPE.
1347 */
1348        (coding_system, eol_type))
1349 {
1350   coding_system = Fget_coding_system (coding_system);
1351
1352   return subsidiary_coding_system (coding_system,
1353                                    symbol_to_eol_type (eol_type));
1354 }
1355
1356 \f
1357 /************************************************************************/
1358 /*                         Coding system accessors                      */
1359 /************************************************************************/
1360
1361 DEFUN ("coding-system-doc-string", Fcoding_system_doc_string, 1, 1, 0, /*
1362 Return the doc string for CODING-SYSTEM.
1363 */
1364        (coding_system))
1365 {
1366   coding_system = Fget_coding_system (coding_system);
1367   return XCODING_SYSTEM_DOC_STRING (coding_system);
1368 }
1369
1370 DEFUN ("coding-system-type", Fcoding_system_type, 1, 1, 0, /*
1371 Return the type of CODING-SYSTEM.
1372 */
1373        (coding_system))
1374 {
1375   switch (XCODING_SYSTEM_TYPE (Fget_coding_system (coding_system)))
1376     {
1377     default: abort ();
1378     case CODESYS_AUTODETECT:    return Qundecided;
1379 #ifdef MULE
1380     case CODESYS_SHIFT_JIS:     return Qshift_jis;
1381     case CODESYS_ISO2022:       return Qiso2022;
1382     case CODESYS_BIG5:          return Qbig5;
1383     case CODESYS_UCS4:          return Qucs4;
1384     case CODESYS_UTF16:         return Qutf16;
1385     case CODESYS_UTF8:          return Qutf8;
1386     case CODESYS_CCL:           return Qccl;
1387 #endif
1388     case CODESYS_NO_CONVERSION: return Qno_conversion;
1389 #ifdef DEBUG_XEMACS
1390     case CODESYS_INTERNAL:      return Qinternal;
1391 #endif
1392     }
1393 }
1394
1395 #ifdef MULE
1396 static
1397 Lisp_Object coding_system_charset (Lisp_Object coding_system, int gnum)
1398 {
1399   Lisp_Object cs
1400     = XCODING_SYSTEM_ISO2022_INITIAL_CHARSET (coding_system, gnum);
1401
1402   return CHARSETP (cs) ? XCHARSET_NAME (cs) : Qnil;
1403 }
1404
1405 DEFUN ("coding-system-charset", Fcoding_system_charset, 2, 2, 0, /*
1406 Return initial charset of CODING-SYSTEM designated to GNUM.
1407 GNUM allows 0 .. 3.
1408 */
1409        (coding_system, gnum))
1410 {
1411   coding_system = Fget_coding_system (coding_system);
1412   CHECK_INT (gnum);
1413
1414   return coding_system_charset (coding_system, XINT (gnum));
1415 }
1416 #endif /* MULE */
1417
1418 DEFUN ("coding-system-property", Fcoding_system_property, 2, 2, 0, /*
1419 Return the PROP property of CODING-SYSTEM.
1420 */
1421        (coding_system, prop))
1422 {
1423   int i, ok = 0;
1424   enum coding_system_type type;
1425
1426   coding_system = Fget_coding_system (coding_system);
1427   CHECK_SYMBOL (prop);
1428   type = XCODING_SYSTEM_TYPE (coding_system);
1429
1430   for (i = 0; !ok && i < Dynarr_length (the_codesys_prop_dynarr); i++)
1431     if (EQ (Dynarr_at (the_codesys_prop_dynarr, i).sym, prop))
1432       {
1433         ok = 1;
1434         switch (Dynarr_at (the_codesys_prop_dynarr, i).prop_type)
1435           {
1436           case CODESYS_PROP_ALL_OK:
1437             break;
1438 #ifdef MULE
1439           case CODESYS_PROP_ISO2022:
1440             if (type != CODESYS_ISO2022)
1441               signal_simple_error
1442                 ("Property only valid in ISO2022 coding systems",
1443                  prop);
1444             break;
1445
1446           case CODESYS_PROP_CCL:
1447             if (type != CODESYS_CCL)
1448               signal_simple_error
1449                 ("Property only valid in CCL coding systems",
1450                  prop);
1451             break;
1452 #endif /* MULE */
1453           default:
1454             abort ();
1455           }
1456       }
1457
1458   if (!ok)
1459     signal_simple_error ("Unrecognized property", prop);
1460
1461   if (EQ (prop, Qname))
1462     return XCODING_SYSTEM_NAME (coding_system);
1463   else if (EQ (prop, Qtype))
1464     return Fcoding_system_type (coding_system);
1465   else if (EQ (prop, Qdoc_string))
1466     return XCODING_SYSTEM_DOC_STRING (coding_system);
1467   else if (EQ (prop, Qmnemonic))
1468     return XCODING_SYSTEM_MNEMONIC (coding_system);
1469   else if (EQ (prop, Qeol_type))
1470     return eol_type_to_symbol (XCODING_SYSTEM_EOL_TYPE (coding_system));
1471   else if (EQ (prop, Qeol_lf))
1472     return XCODING_SYSTEM_EOL_LF (coding_system);
1473   else if (EQ (prop, Qeol_crlf))
1474     return XCODING_SYSTEM_EOL_CRLF (coding_system);
1475   else if (EQ (prop, Qeol_cr))
1476     return XCODING_SYSTEM_EOL_CR (coding_system);
1477   else if (EQ (prop, Qpost_read_conversion))
1478     return XCODING_SYSTEM_POST_READ_CONVERSION (coding_system);
1479   else if (EQ (prop, Qpre_write_conversion))
1480     return XCODING_SYSTEM_PRE_WRITE_CONVERSION (coding_system);
1481 #ifdef MULE
1482 #ifdef UTF2000
1483   else if (EQ (prop, Qdisable_composition))
1484     return XCODING_SYSTEM_DISABLE_COMPOSITION (coding_system) ? Qt : Qnil;
1485   else if (EQ (prop, Quse_entity_reference))
1486     return XCODING_SYSTEM_USE_ENTITY_REFERENCE (coding_system) ? Qt : Qnil;
1487 #endif
1488   else if (type == CODESYS_ISO2022)
1489     {
1490       if (EQ (prop, Qcharset_g0))
1491         return coding_system_charset (coding_system, 0);
1492       else if (EQ (prop, Qcharset_g1))
1493         return coding_system_charset (coding_system, 1);
1494       else if (EQ (prop, Qcharset_g2))
1495         return coding_system_charset (coding_system, 2);
1496       else if (EQ (prop, Qcharset_g3))
1497         return coding_system_charset (coding_system, 3);
1498
1499 #define FORCE_CHARSET(charset_num) \
1500   (XCODING_SYSTEM_ISO2022_FORCE_CHARSET_ON_OUTPUT \
1501    (coding_system, charset_num) ? Qt : Qnil)
1502
1503       else if (EQ (prop, Qforce_g0_on_output)) return FORCE_CHARSET (0);
1504       else if (EQ (prop, Qforce_g1_on_output)) return FORCE_CHARSET (1);
1505       else if (EQ (prop, Qforce_g2_on_output)) return FORCE_CHARSET (2);
1506       else if (EQ (prop, Qforce_g3_on_output)) return FORCE_CHARSET (3);
1507
1508 #define LISP_BOOLEAN(prop) \
1509   (XCODING_SYSTEM_ISO2022_##prop (coding_system) ? Qt : Qnil)
1510
1511       else if (EQ (prop, Qshort))         return LISP_BOOLEAN (SHORT);
1512       else if (EQ (prop, Qno_ascii_eol))  return LISP_BOOLEAN (NO_ASCII_EOL);
1513       else if (EQ (prop, Qno_ascii_cntl)) return LISP_BOOLEAN (NO_ASCII_CNTL);
1514       else if (EQ (prop, Qseven))         return LISP_BOOLEAN (SEVEN);
1515       else if (EQ (prop, Qlock_shift))    return LISP_BOOLEAN (LOCK_SHIFT);
1516       else if (EQ (prop, Qno_iso6429))    return LISP_BOOLEAN (NO_ISO6429);
1517       else if (EQ (prop, Qescape_quoted)) return LISP_BOOLEAN (ESCAPE_QUOTED);
1518
1519       else if (EQ (prop, Qinput_charset_conversion))
1520         return
1521           unparse_charset_conversion_specs
1522             (XCODING_SYSTEM (coding_system)->iso2022.input_conv);
1523       else if (EQ (prop, Qoutput_charset_conversion))
1524         return
1525           unparse_charset_conversion_specs
1526             (XCODING_SYSTEM (coding_system)->iso2022.output_conv);
1527       else
1528         abort ();
1529     }
1530   else if (type == CODESYS_CCL)
1531     {
1532       if (EQ (prop, Qdecode))
1533         return XCODING_SYSTEM_CCL_DECODE (coding_system);
1534       else if (EQ (prop, Qencode))
1535         return XCODING_SYSTEM_CCL_ENCODE (coding_system);
1536       else
1537         abort ();
1538     }
1539 #endif /* MULE */
1540   else
1541     abort ();
1542
1543   return Qnil; /* not reached */
1544 }
1545
1546 \f
1547 /************************************************************************/
1548 /*                       Coding category functions                      */
1549 /************************************************************************/
1550
1551 static int
1552 decode_coding_category (Lisp_Object symbol)
1553 {
1554   int i;
1555
1556   CHECK_SYMBOL (symbol);
1557   for (i = 0; i < CODING_CATEGORY_LAST; i++)
1558     if (EQ (coding_category_symbol[i], symbol))
1559       return i;
1560
1561   signal_simple_error ("Unrecognized coding category", symbol);
1562   return 0; /* not reached */
1563 }
1564
1565 DEFUN ("coding-category-list", Fcoding_category_list, 0, 0, 0, /*
1566 Return a list of all recognized coding categories.
1567 */
1568        ())
1569 {
1570   int i;
1571   Lisp_Object list = Qnil;
1572
1573   for (i = CODING_CATEGORY_LAST - 1; i >= 0; i--)
1574     list = Fcons (coding_category_symbol[i], list);
1575   return list;
1576 }
1577
1578 DEFUN ("set-coding-priority-list", Fset_coding_priority_list, 1, 1, 0, /*
1579 Change the priority order of the coding categories.
1580 LIST should be list of coding categories, in descending order of
1581 priority.  Unspecified coding categories will be lower in priority
1582 than all specified ones, in the same relative order they were in
1583 previously.
1584 */
1585        (list))
1586 {
1587   int category_to_priority[CODING_CATEGORY_LAST];
1588   int i, j;
1589   Lisp_Object rest;
1590
1591   /* First generate a list that maps coding categories to priorities. */
1592
1593   for (i = 0; i < CODING_CATEGORY_LAST; i++)
1594     category_to_priority[i] = -1;
1595
1596   /* Highest priority comes from the specified list. */
1597   i = 0;
1598   EXTERNAL_LIST_LOOP (rest, list)
1599     {
1600       int cat = decode_coding_category (XCAR (rest));
1601
1602       if (category_to_priority[cat] >= 0)
1603         signal_simple_error ("Duplicate coding category in list", XCAR (rest));
1604       category_to_priority[cat] = i++;
1605     }
1606
1607   /* Now go through the existing categories by priority to retrieve
1608      the categories not yet specified and preserve their priority
1609      order. */
1610   for (j = 0; j < CODING_CATEGORY_LAST; j++)
1611     {
1612       int cat = fcd->coding_category_by_priority[j];
1613       if (category_to_priority[cat] < 0)
1614         category_to_priority[cat] = i++;
1615     }
1616
1617   /* Now we need to construct the inverse of the mapping we just
1618      constructed. */
1619
1620   for (i = 0; i < CODING_CATEGORY_LAST; i++)
1621     fcd->coding_category_by_priority[category_to_priority[i]] = i;
1622
1623   /* Phew!  That was confusing. */
1624   return Qnil;
1625 }
1626
1627 DEFUN ("coding-priority-list", Fcoding_priority_list, 0, 0, 0, /*
1628 Return a list of coding categories in descending order of priority.
1629 */
1630        ())
1631 {
1632   int i;
1633   Lisp_Object list = Qnil;
1634
1635   for (i = CODING_CATEGORY_LAST - 1; i >= 0; i--)
1636     list = Fcons (coding_category_symbol[fcd->coding_category_by_priority[i]],
1637                   list);
1638   return list;
1639 }
1640
1641 DEFUN ("set-coding-category-system", Fset_coding_category_system, 2, 2, 0, /*
1642 Change the coding system associated with a coding category.
1643 */
1644        (coding_category, coding_system))
1645 {
1646   int cat = decode_coding_category (coding_category);
1647
1648   coding_system = Fget_coding_system (coding_system);
1649   fcd->coding_category_system[cat] = coding_system;
1650   return Qnil;
1651 }
1652
1653 DEFUN ("coding-category-system", Fcoding_category_system, 1, 1, 0, /*
1654 Return the coding system associated with a coding category.
1655 */
1656        (coding_category))
1657 {
1658   int cat = decode_coding_category (coding_category);
1659   Lisp_Object sys = fcd->coding_category_system[cat];
1660
1661   if (!NILP (sys))
1662     return XCODING_SYSTEM_NAME (sys);
1663   return Qnil;
1664 }
1665
1666 \f
1667 /************************************************************************/
1668 /*                     Detecting the encoding of data                   */
1669 /************************************************************************/
1670
1671 struct detection_state
1672 {
1673   eol_type_t eol_type;
1674   int seen_non_ascii;
1675   int mask;
1676 #ifdef MULE
1677   struct
1678     {
1679       int mask;
1680       int in_second_byte;
1681     }
1682   big5;
1683
1684   struct
1685     {
1686       int mask;
1687       int in_second_byte;
1688     }
1689   shift_jis;
1690
1691   struct
1692     {
1693       int mask;
1694       int in_byte;
1695   }
1696   ucs4;
1697
1698   struct
1699     {
1700       int mask;
1701       int in_byte;
1702     }
1703   utf16;
1704
1705   struct
1706     {
1707       int mask;
1708       int in_byte;
1709     }
1710   utf8;
1711
1712   struct
1713     {
1714       int mask;
1715       int initted;
1716       struct iso2022_decoder iso;
1717       unsigned int flags;
1718       int high_byte_count;
1719       unsigned int saw_single_shift:1;
1720     }
1721   iso2022;
1722 #endif
1723   struct
1724     {
1725       int seen_anything;
1726       int just_saw_cr;
1727     }
1728   eol;
1729 };
1730
1731 static int
1732 acceptable_control_char_p (int c)
1733 {
1734   switch (c)
1735     {
1736       /* Allow and ignore control characters that you might
1737          reasonably see in a text file */
1738     case '\r':
1739     case '\n':
1740     case '\t':
1741     case  7: /* bell */
1742     case  8: /* backspace */
1743     case 11: /* vertical tab */
1744     case 12: /* form feed */
1745     case 26: /* MS-DOS C-z junk */
1746     case 31: /* '^_' -- for info */
1747       return 1;
1748     default:
1749       return 0;
1750     }
1751 }
1752
1753 static int
1754 mask_has_at_most_one_bit_p (int mask)
1755 {
1756   /* Perhaps the only thing useful you learn from intensive Microsoft
1757      technical interviews */
1758   return (mask & (mask - 1)) == 0;
1759 }
1760
1761 static eol_type_t
1762 detect_eol_type (struct detection_state *st, const Extbyte *src,
1763                  Lstream_data_count n)
1764 {
1765   while (n--)
1766     {
1767       unsigned char c = *(unsigned char *)src++;
1768       if (c == '\n')
1769         {
1770           if (st->eol.just_saw_cr)
1771             return EOL_CRLF;
1772           else if (st->eol.seen_anything)
1773             return EOL_LF;
1774         }
1775       else if (st->eol.just_saw_cr)
1776         return EOL_CR;
1777       else if (c == '\r')
1778         st->eol.just_saw_cr = 1;
1779       else
1780         st->eol.just_saw_cr = 0;
1781       st->eol.seen_anything = 1;
1782     }
1783
1784   return EOL_AUTODETECT;
1785 }
1786
1787 /* Attempt to determine the encoding and EOL type of the given text.
1788    Before calling this function for the first type, you must initialize
1789    st->eol_type as appropriate and initialize st->mask to ~0.
1790
1791    st->eol_type holds the determined EOL type, or EOL_AUTODETECT if
1792    not yet known.
1793
1794    st->mask holds the determined coding category mask, or ~0 if only
1795    ASCII has been seen so far.
1796
1797    Returns:
1798
1799    0 == st->eol_type is EOL_AUTODETECT and/or more than coding category
1800         is present in st->mask
1801    1 == definitive answers are here for both st->eol_type and st->mask
1802 */
1803
1804 static int
1805 detect_coding_type (struct detection_state *st, const Extbyte *src,
1806                     Lstream_data_count n, int just_do_eol)
1807 {
1808   if (st->eol_type == EOL_AUTODETECT)
1809     st->eol_type = detect_eol_type (st, src, n);
1810
1811   if (just_do_eol)
1812     return st->eol_type != EOL_AUTODETECT;
1813
1814   if (!st->seen_non_ascii)
1815     {
1816       for (; n; n--, src++)
1817         {
1818           unsigned char c = *(unsigned char *) src;
1819           if ((c < 0x20 && !acceptable_control_char_p (c)) || c >= 0x80)
1820             {
1821               st->seen_non_ascii = 1;
1822 #ifdef MULE
1823               st->shift_jis.mask = ~0;
1824               st->big5.mask = ~0;
1825               st->ucs4.mask = ~0;
1826               st->utf16.mask = ~0;
1827               st->utf8.mask = ~0;
1828               st->iso2022.mask = ~0;
1829 #endif
1830               break;
1831             }
1832         }
1833     }
1834
1835   if (!n)
1836     return 0;
1837 #ifdef MULE
1838   if (!mask_has_at_most_one_bit_p (st->iso2022.mask))
1839     st->iso2022.mask = detect_coding_iso2022 (st, src, n);
1840   if (!mask_has_at_most_one_bit_p (st->shift_jis.mask))
1841     st->shift_jis.mask = detect_coding_sjis (st, src, n);
1842   if (!mask_has_at_most_one_bit_p (st->big5.mask))
1843     st->big5.mask = detect_coding_big5 (st, src, n);
1844   if (!mask_has_at_most_one_bit_p (st->utf8.mask))
1845     st->utf8.mask = detect_coding_utf8 (st, src, n);
1846   if (!mask_has_at_most_one_bit_p (st->utf16.mask))
1847     st->utf16.mask = detect_coding_utf16 (st, src, n);
1848   if (!mask_has_at_most_one_bit_p (st->ucs4.mask))
1849     st->ucs4.mask = detect_coding_ucs4 (st, src, n);
1850
1851   st->mask
1852     = st->iso2022.mask | st->shift_jis.mask | st->big5.mask
1853     | st->utf8.mask | st->ucs4.mask;
1854 #endif
1855   {
1856     int retval = mask_has_at_most_one_bit_p (st->mask);
1857     st->mask |= CODING_CATEGORY_NO_CONVERSION_MASK;
1858     return retval && st->eol_type != EOL_AUTODETECT;
1859   }
1860 }
1861
1862 static Lisp_Object
1863 coding_system_from_mask (int mask)
1864 {
1865   if (mask == ~0)
1866     {
1867       /* If the file was entirely or basically ASCII, use the
1868          default value of `buffer-file-coding-system'. */
1869       Lisp_Object retval =
1870         XBUFFER (Vbuffer_defaults)->buffer_file_coding_system;
1871       if (!NILP (retval))
1872         {
1873           retval = Ffind_coding_system (retval);
1874           if (NILP (retval))
1875             {
1876               warn_when_safe
1877                 (Qbad_variable, Qwarning,
1878                  "Invalid `default-buffer-file-coding-system', set to nil");
1879               XBUFFER (Vbuffer_defaults)->buffer_file_coding_system = Qnil;
1880             }
1881         }
1882       if (NILP (retval))
1883         retval = Fget_coding_system (Qraw_text);
1884       return retval;
1885     }
1886   else
1887     {
1888       int i;
1889       int cat = -1;
1890 #ifdef MULE
1891       mask = postprocess_iso2022_mask (mask);
1892 #endif
1893       /* Look through the coding categories by priority and find
1894          the first one that is allowed. */
1895       for (i = 0; i < CODING_CATEGORY_LAST; i++)
1896         {
1897           cat = fcd->coding_category_by_priority[i];
1898           if ((mask & (1 << cat)) &&
1899               !NILP (fcd->coding_category_system[cat]))
1900             break;
1901         }
1902       if (cat >= 0)
1903         return fcd->coding_category_system[cat];
1904       else
1905         return Fget_coding_system (Qraw_text);
1906     }
1907 }
1908
1909 /* Given a seekable read stream and potential coding system and EOL type
1910    as specified, do any autodetection that is called for.  If the
1911    coding system and/or EOL type are not `autodetect', they will be left
1912    alone; but this function will never return an autodetect coding system
1913    or EOL type.
1914
1915    This function does not automatically fetch subsidiary coding systems;
1916    that should be unnecessary with the explicit eol-type argument. */
1917
1918 #define LENGTH(string_constant) (sizeof (string_constant) - 1)
1919 /* number of leading lines to check for a coding cookie */
1920 #define LINES_TO_CHECK 2
1921
1922 void
1923 determine_real_coding_system (Lstream *stream, Lisp_Object *codesys_in_out,
1924                               eol_type_t *eol_type_in_out)
1925 {
1926   struct detection_state decst;
1927
1928   if (*eol_type_in_out == EOL_AUTODETECT)
1929     *eol_type_in_out = XCODING_SYSTEM_EOL_TYPE (*codesys_in_out);
1930
1931   xzero (decst);
1932   decst.eol_type = *eol_type_in_out;
1933   decst.mask = ~0;
1934
1935   /* If autodetection is called for, do it now. */
1936   if (XCODING_SYSTEM_TYPE (*codesys_in_out) == CODESYS_AUTODETECT
1937       || *eol_type_in_out == EOL_AUTODETECT)
1938     {
1939       Extbyte buf[4096];
1940       Lisp_Object coding_system = Qnil;
1941       Extbyte *p;
1942       Lstream_data_count nread = Lstream_read (stream, buf, sizeof (buf));
1943       Extbyte *scan_end;
1944       int lines_checked = 0;
1945
1946       /* Look for initial "-*-"; mode line prefix */
1947       for (p = buf,
1948              scan_end = buf + nread - LENGTH ("-*-coding:?-*-");
1949            p <= scan_end
1950              && lines_checked < LINES_TO_CHECK;
1951            p++)
1952         if (*p == '-' && *(p+1) == '*' && *(p+2) == '-')
1953           {
1954             Extbyte *local_vars_beg = p + 3;
1955             /* Look for final "-*-"; mode line suffix */
1956             for (p = local_vars_beg,
1957                    scan_end = buf + nread - LENGTH ("-*-");
1958                  p <= scan_end
1959                    && lines_checked < LINES_TO_CHECK;
1960                  p++)
1961               if (*p == '-' && *(p+1) == '*' && *(p+2) == '-')
1962                 {
1963                   Extbyte *suffix = p;
1964                   /* Look for "coding:" */
1965                   for (p = local_vars_beg,
1966                          scan_end = suffix - LENGTH ("coding:?");
1967                        p <= scan_end;
1968                        p++)
1969                     if (memcmp ("coding:", p, LENGTH ("coding:")) == 0
1970                         && (p == local_vars_beg
1971                             || (*(p-1) == ' '  ||
1972                                 *(p-1) == '\t' ||
1973                                 *(p-1) == ';')))
1974                       {
1975                         Extbyte save;
1976                         int n;
1977                         p += LENGTH ("coding:");
1978                         while (*p == ' ' || *p == '\t') p++;
1979
1980                         /* Get coding system name */
1981                         save = *suffix; *suffix = '\0';
1982                         /* Characters valid in a MIME charset name (rfc 1521),
1983                            and in a Lisp symbol name. */
1984                         n = strspn ( (char *) p,
1985                                     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1986                                     "abcdefghijklmnopqrstuvwxyz"
1987                                     "0123456789"
1988                                     "!$%&*+-.^_{|}~");
1989                         *suffix = save;
1990                         if (n > 0)
1991                           {
1992                             save = p[n]; p[n] = '\0';
1993                             coding_system =
1994                               Ffind_coding_system (intern ((char *) p));
1995                             p[n] = save;
1996                           }
1997                         break;
1998                       }
1999                   break;
2000                 }
2001               /* #### file must use standard EOLs or we miss 2d line */
2002               /* #### not to mention this is broken for UTF-16 DOS files */
2003               else if (*p == '\n' || *p == '\r')
2004                 {
2005                   lines_checked++;
2006                   /* skip past multibyte (DOS) newline */
2007                   if (*p == '\r' && *(p+1) == '\n') p++;
2008                 }
2009             break;
2010           }
2011         /* #### file must use standard EOLs or we miss 2d line */
2012         /* #### not to mention this is broken for UTF-16 DOS files */
2013         else if (*p == '\n' || *p == '\r')
2014           {
2015             lines_checked++;
2016             /* skip past multibyte (DOS) newline */
2017             if (*p == '\r' && *(p+1) == '\n') p++;
2018           }
2019
2020       if (NILP (coding_system))
2021         do
2022           {
2023             if (detect_coding_type (&decst, buf, nread,
2024                                     XCODING_SYSTEM_TYPE (*codesys_in_out)
2025                                     != CODESYS_AUTODETECT))
2026               break;
2027             nread = Lstream_read (stream, buf, sizeof (buf));
2028             if (nread == 0)
2029               break;
2030           }
2031         while (1);
2032
2033       else if (XCODING_SYSTEM_TYPE (*codesys_in_out) == CODESYS_AUTODETECT
2034                && XCODING_SYSTEM_EOL_TYPE (coding_system) == EOL_AUTODETECT)
2035         do
2036           {
2037             if (detect_coding_type (&decst, buf, nread, 1))
2038               break;
2039             nread = Lstream_read (stream, buf, sizeof (buf));
2040             if (!nread)
2041               break;
2042           }
2043         while (1);
2044
2045       *eol_type_in_out = decst.eol_type;
2046       if (XCODING_SYSTEM_TYPE (*codesys_in_out) == CODESYS_AUTODETECT)
2047         {
2048           if (NILP (coding_system))
2049             *codesys_in_out = coding_system_from_mask (decst.mask);
2050           else
2051             *codesys_in_out = coding_system;
2052         }
2053     }
2054
2055   /* If we absolutely can't determine the EOL type, just assume LF. */
2056   if (*eol_type_in_out == EOL_AUTODETECT)
2057     *eol_type_in_out = EOL_LF;
2058
2059   Lstream_rewind (stream);
2060 }
2061
2062 DEFUN ("detect-coding-region", Fdetect_coding_region, 2, 3, 0, /*
2063 Detect coding system of the text in the region between START and END.
2064 Return a list of possible coding systems ordered by priority.
2065 If only ASCII characters are found, return 'undecided or one of
2066 its subsidiary coding systems according to a detected end-of-line
2067 type.  Optional arg BUFFER defaults to the current buffer.
2068 */
2069        (start, end, buffer))
2070 {
2071   Lisp_Object val = Qnil;
2072   struct buffer *buf = decode_buffer (buffer, 0);
2073   Bufpos b, e;
2074   Lisp_Object instream, lb_instream;
2075   Lstream *istr, *lb_istr;
2076   struct detection_state decst;
2077   struct gcpro gcpro1, gcpro2;
2078
2079   get_buffer_range_char (buf, start, end, &b, &e, 0);
2080   lb_instream = make_lisp_buffer_input_stream (buf, b, e, 0);
2081   lb_istr = XLSTREAM (lb_instream);
2082   instream = make_encoding_input_stream (lb_istr, Fget_coding_system (Qbinary));
2083   istr = XLSTREAM (instream);
2084   GCPRO2 (instream, lb_instream);
2085   xzero (decst);
2086   decst.eol_type = EOL_AUTODETECT;
2087   decst.mask = ~0;
2088   while (1)
2089     {
2090       Extbyte random_buffer[4096];
2091       Lstream_data_count nread = Lstream_read (istr, random_buffer, sizeof (random_buffer));
2092
2093       if (!nread)
2094         break;
2095       if (detect_coding_type (&decst, random_buffer, nread, 0))
2096         break;
2097     }
2098
2099   if (decst.mask == ~0)
2100     val = subsidiary_coding_system (Fget_coding_system (Qundecided),
2101                                     decst.eol_type);
2102   else
2103     {
2104       int i;
2105
2106       val = Qnil;
2107 #ifdef MULE
2108       decst.mask = postprocess_iso2022_mask (decst.mask);
2109 #endif
2110       for (i = CODING_CATEGORY_LAST - 1; i >= 0; i--)
2111         {
2112           int sys = fcd->coding_category_by_priority[i];
2113           if (decst.mask & (1 << sys))
2114             {
2115               Lisp_Object codesys = fcd->coding_category_system[sys];
2116               if (!NILP (codesys))
2117                 codesys = subsidiary_coding_system (codesys, decst.eol_type);
2118               val = Fcons (codesys, val);
2119             }
2120         }
2121     }
2122   Lstream_close (istr);
2123   UNGCPRO;
2124   Lstream_delete (istr);
2125   Lstream_delete (lb_istr);
2126   return val;
2127 }
2128
2129 \f
2130 /************************************************************************/
2131 /*           Converting to internal Mule format ("decoding")            */
2132 /************************************************************************/
2133
2134 /* A decoding stream is a stream used for decoding text (i.e.
2135    converting from some external format to internal format).
2136    The decoding-stream object keeps track of the actual coding
2137    stream, the stream that is at the other end, and data that
2138    needs to be persistent across the lifetime of the stream. */
2139
2140 /* Handle the EOL stuff related to just-read-in character C.
2141    EOL_TYPE is the EOL type of the coding stream.
2142    FLAGS is the current value of FLAGS in the coding stream, and may
2143    be modified by this macro.  (The macro only looks at the
2144    CODING_STATE_CR flag.)  DST is the Dynarr to which the decoded
2145    bytes are to be written.  You need to also define a local goto
2146    label "label_continue_loop" that is at the end of the main
2147    character-reading loop.
2148
2149    If C is a CR character, then this macro handles it entirely and
2150    jumps to label_continue_loop.  Otherwise, this macro does not add
2151    anything to DST, and continues normally.  You should continue
2152    processing C normally after this macro. */
2153
2154 #define DECODE_HANDLE_EOL_TYPE(eol_type, c, flags, dst)         \
2155 do {                                                            \
2156   if (c == '\r')                                                \
2157     {                                                           \
2158       if (eol_type == EOL_CR)                                   \
2159         Dynarr_add (dst, '\n');                                 \
2160       else if (eol_type != EOL_CRLF || flags & CODING_STATE_CR) \
2161         Dynarr_add (dst, c);                                    \
2162       else                                                      \
2163         flags |= CODING_STATE_CR;                               \
2164       goto label_continue_loop;                                 \
2165     }                                                           \
2166   else if (flags & CODING_STATE_CR)                             \
2167     {   /* eol_type == CODING_SYSTEM_EOL_CRLF */                \
2168       if (c != '\n')                                            \
2169         Dynarr_add (dst, '\r');                                 \
2170       flags &= ~CODING_STATE_CR;                                \
2171     }                                                           \
2172 } while (0)
2173
2174 /* C should be a binary character in the range 0 - 255; convert
2175    to internal format and add to Dynarr DST. */
2176
2177 #ifdef UTF2000
2178 #define DECODE_ADD_BINARY_CHAR(c, dst) \
2179 do {                                            \
2180   if (BYTE_ASCII_P (c))                         \
2181     Dynarr_add (dst, c);                        \
2182   else                                          \
2183     {                                           \
2184       Dynarr_add (dst, (c >> 6) | 0xc0);        \
2185       Dynarr_add (dst, (c & 0x3f) | 0x80);      \
2186     }                                           \
2187 } while (0)
2188
2189 INLINE_HEADER void DECODE_ADD_UCS_CHAR(Emchar c, unsigned_char_dynarr* dst);
2190 INLINE_HEADER void
2191 DECODE_ADD_UCS_CHAR(Emchar c, unsigned_char_dynarr* dst)
2192 {
2193   if ( c <= 0x7f )
2194     {
2195       Dynarr_add (dst, c);
2196     }
2197   else if ( c <= 0x7ff )
2198     {
2199       Dynarr_add (dst, (c >> 6) | 0xc0);
2200       Dynarr_add (dst, (c & 0x3f) | 0x80);
2201     }
2202   else if ( c <= 0xffff )
2203     {
2204       Dynarr_add (dst,  (c >> 12) | 0xe0);
2205       Dynarr_add (dst, ((c >>  6) & 0x3f) | 0x80);
2206       Dynarr_add (dst,  (c        & 0x3f) | 0x80);
2207     }
2208   else if ( c <= 0x1fffff )
2209     {
2210       Dynarr_add (dst,  (c >> 18) | 0xf0);
2211       Dynarr_add (dst, ((c >> 12) & 0x3f) | 0x80);
2212       Dynarr_add (dst, ((c >>  6) & 0x3f) | 0x80);
2213       Dynarr_add (dst,  (c        & 0x3f) | 0x80);
2214     }
2215   else if ( c <= 0x3ffffff )
2216     {
2217       Dynarr_add (dst,  (c >> 24) | 0xf8);
2218       Dynarr_add (dst, ((c >> 18) & 0x3f) | 0x80);
2219       Dynarr_add (dst, ((c >> 12) & 0x3f) | 0x80);
2220       Dynarr_add (dst, ((c >>  6) & 0x3f) | 0x80);
2221       Dynarr_add (dst,  (c        & 0x3f) | 0x80);
2222     }
2223   else
2224     {
2225       Dynarr_add (dst,  (c >> 30) | 0xfc);
2226       Dynarr_add (dst, ((c >> 24) & 0x3f) | 0x80);
2227       Dynarr_add (dst, ((c >> 18) & 0x3f) | 0x80);
2228       Dynarr_add (dst, ((c >> 12) & 0x3f) | 0x80);
2229       Dynarr_add (dst, ((c >>  6) & 0x3f) | 0x80);
2230       Dynarr_add (dst,  (c        & 0x3f) | 0x80);
2231     }
2232 }
2233 #else
2234 #define DECODE_ADD_BINARY_CHAR(c, dst)          \
2235 do {                                            \
2236   if (BYTE_ASCII_P (c))                         \
2237     Dynarr_add (dst, c);                        \
2238   else if (BYTE_C1_P (c))                       \
2239     {                                           \
2240       Dynarr_add (dst, LEADING_BYTE_CONTROL_1); \
2241       Dynarr_add (dst, c + 0x20);               \
2242     }                                           \
2243   else                                          \
2244     {                                           \
2245       Dynarr_add (dst, LEADING_BYTE_LATIN_ISO8859_1); \
2246       Dynarr_add (dst, c);                      \
2247     }                                           \
2248 } while (0)
2249 #endif
2250
2251 #define DECODE_OUTPUT_PARTIAL_CHAR(ch)  \
2252 do {                                    \
2253   if (ch)                               \
2254     {                                   \
2255       DECODE_ADD_BINARY_CHAR (ch, dst); \
2256       ch = 0;                           \
2257     }                                   \
2258 } while (0)
2259
2260 #define DECODE_HANDLE_END_OF_CONVERSION(flags, ch, dst) \
2261 do {                                    \
2262   if (flags & CODING_STATE_END)         \
2263     {                                   \
2264       DECODE_OUTPUT_PARTIAL_CHAR (ch);  \
2265       if (flags & CODING_STATE_CR)      \
2266         Dynarr_add (dst, '\r');         \
2267     }                                   \
2268 } while (0)
2269
2270 #define DECODING_STREAM_DATA(stream) LSTREAM_TYPE_DATA (stream, decoding)
2271
2272 #define ER_BUF_SIZE 24
2273
2274 struct decoding_stream
2275 {
2276   /* Coding system that governs the conversion. */
2277   Lisp_Coding_System *codesys;
2278
2279   /* Stream that we read the encoded data from or
2280      write the decoded data to. */
2281   Lstream *other_end;
2282
2283   /* If we are reading, then we can return only a fixed amount of
2284      data, so if the conversion resulted in too much data, we store it
2285      here for retrieval the next time around. */
2286   unsigned_char_dynarr *runoff;
2287
2288   /* FLAGS holds flags indicating the current state of the decoding.
2289      Some of these flags are dependent on the coding system. */
2290   unsigned int flags;
2291
2292   /* CPOS holds a partially built-up code-point of character. */
2293   unsigned int cpos;
2294
2295   /* EOL_TYPE specifies the type of end-of-line conversion that
2296      currently applies.  We need to keep this separate from the
2297      EOL type stored in CODESYS because the latter might indicate
2298      automatic EOL-type detection while the former will always
2299      indicate a particular EOL type. */
2300   eol_type_t eol_type;
2301 #ifdef MULE
2302   /* Additional ISO2022 information.  We define the structure above
2303      because it's also needed by the detection routines. */
2304   struct iso2022_decoder iso2022;
2305
2306   /* Additional information (the state of the running CCL program)
2307      used by the CCL decoder. */
2308   struct ccl_program ccl;
2309
2310   /* counter for UTF-8 or UCS-4 */
2311   unsigned char counter;
2312 #endif
2313 #ifdef UTF2000
2314   unsigned char er_counter;
2315   unsigned char er_buf[ER_BUF_SIZE];
2316
2317   unsigned combined_char_count;
2318   Emchar combined_chars[16];
2319   Lisp_Object combining_table;
2320 #endif
2321   struct detection_state decst;
2322 };
2323
2324 static Lstream_data_count decoding_reader (Lstream *stream,
2325                                 unsigned char *data, Lstream_data_count size);
2326 static Lstream_data_count decoding_writer (Lstream *stream,
2327                                 const unsigned char *data, Lstream_data_count size);
2328 static int decoding_rewinder   (Lstream *stream);
2329 static int decoding_seekable_p (Lstream *stream);
2330 static int decoding_flusher    (Lstream *stream);
2331 static int decoding_closer     (Lstream *stream);
2332
2333 static Lisp_Object decoding_marker (Lisp_Object stream);
2334
2335 DEFINE_LSTREAM_IMPLEMENTATION ("decoding", lstream_decoding,
2336                                sizeof (struct decoding_stream));
2337
2338 static Lisp_Object
2339 decoding_marker (Lisp_Object stream)
2340 {
2341   Lstream *str = DECODING_STREAM_DATA (XLSTREAM (stream))->other_end;
2342   Lisp_Object str_obj;
2343
2344   /* We do not need to mark the coding systems or charsets stored
2345      within the stream because they are stored in a global list
2346      and automatically marked. */
2347
2348   XSETLSTREAM (str_obj, str);
2349   mark_object (str_obj);
2350   if (str->imp->marker)
2351     return (str->imp->marker) (str_obj);
2352   else
2353     return Qnil;
2354 }
2355
2356 /* Read SIZE bytes of data and store it into DATA.  We are a decoding stream
2357    so we read data from the other end, decode it, and store it into DATA. */
2358
2359 static Lstream_data_count
2360 decoding_reader (Lstream *stream, unsigned char *data, Lstream_data_count size)
2361 {
2362   struct decoding_stream *str = DECODING_STREAM_DATA (stream);
2363   unsigned char *orig_data = data;
2364   Lstream_data_count read_size;
2365   int error_occurred = 0;
2366
2367   /* We need to interface to mule_decode(), which expects to take some
2368      amount of data and store the result into a Dynarr.  We have
2369      mule_decode() store into str->runoff, and take data from there
2370      as necessary. */
2371
2372   /* We loop until we have enough data, reading chunks from the other
2373      end and decoding it. */
2374   while (1)
2375     {
2376       /* Take data from the runoff if we can.  Make sure to take at
2377          most SIZE bytes, and delete the data from the runoff. */
2378       if (Dynarr_length (str->runoff) > 0)
2379         {
2380           Lstream_data_count chunk = min (size, (Lstream_data_count) Dynarr_length (str->runoff));
2381           memcpy (data, Dynarr_atp (str->runoff, 0), chunk);
2382           Dynarr_delete_many (str->runoff, 0, chunk);
2383           data += chunk;
2384           size -= chunk;
2385         }
2386
2387       if (size == 0)
2388         break; /* No more room for data */
2389
2390       if (str->flags & CODING_STATE_END)
2391         /* This means that on the previous iteration, we hit the EOF on
2392            the other end.  We loop once more so that mule_decode() can
2393            output any final stuff it may be holding, or any "go back
2394            to a sane state" escape sequences. (This latter makes sense
2395            during encoding.) */
2396         break;
2397
2398       /* Exhausted the runoff, so get some more.  DATA has at least
2399          SIZE bytes left of storage in it, so it's OK to read directly
2400          into it.  (We'll be overwriting above, after we've decoded it
2401          into the runoff.) */
2402       read_size = Lstream_read (str->other_end, data, size);
2403       if (read_size < 0)
2404         {
2405           error_occurred = 1;
2406           break;
2407         }
2408       if (read_size == 0)
2409         /* There might be some more end data produced in the translation.
2410            See the comment above. */
2411         str->flags |= CODING_STATE_END;
2412       mule_decode (stream, (Extbyte *) data, str->runoff, read_size);
2413     }
2414
2415   if (data - orig_data == 0)
2416     return error_occurred ? -1 : 0;
2417   else
2418     return data - orig_data;
2419 }
2420
2421 static Lstream_data_count
2422 decoding_writer (Lstream *stream, const unsigned char *data, Lstream_data_count size)
2423 {
2424   struct decoding_stream *str = DECODING_STREAM_DATA (stream);
2425   Lstream_data_count retval;
2426
2427   /* Decode all our data into the runoff, and then attempt to write
2428      it all out to the other end.  Remove whatever chunk we succeeded
2429      in writing. */
2430   mule_decode (stream, (Extbyte *) data, str->runoff, size);
2431   retval = Lstream_write (str->other_end, Dynarr_atp (str->runoff, 0),
2432                           Dynarr_length (str->runoff));
2433   if (retval > 0)
2434     Dynarr_delete_many (str->runoff, 0, retval);
2435   /* Do NOT return retval.  The return value indicates how much
2436      of the incoming data was written, not how many bytes were
2437      written. */
2438   return size;
2439 }
2440
2441 static void
2442 reset_decoding_stream (struct decoding_stream *str)
2443 {
2444 #ifdef MULE
2445   if (CODING_SYSTEM_TYPE (str->codesys) == CODESYS_ISO2022)
2446     {
2447       Lisp_Object coding_system;
2448       XSETCODING_SYSTEM (coding_system, str->codesys);
2449       reset_iso2022 (coding_system, &str->iso2022);
2450     }
2451   else if (CODING_SYSTEM_TYPE (str->codesys) == CODESYS_CCL)
2452     {
2453       setup_ccl_program (&str->ccl, CODING_SYSTEM_CCL_DECODE (str->codesys));
2454     }
2455   str->counter = 0;
2456 #endif /* MULE */
2457 #ifdef UTF2000
2458   str->er_counter = 0;
2459   str->combined_char_count = 0;
2460   str->combining_table = Qnil;
2461 #endif
2462   if (CODING_SYSTEM_TYPE (str->codesys) == CODESYS_AUTODETECT
2463       || CODING_SYSTEM_EOL_TYPE (str->codesys) == EOL_AUTODETECT)
2464     {
2465       xzero (str->decst);
2466       str->decst.eol_type = EOL_AUTODETECT;
2467       str->decst.mask = ~0;
2468     }
2469   str->flags = str->cpos = 0;
2470 }
2471
2472 static int
2473 decoding_rewinder (Lstream *stream)
2474 {
2475   struct decoding_stream *str = DECODING_STREAM_DATA (stream);
2476   reset_decoding_stream (str);
2477   Dynarr_reset (str->runoff);
2478   return Lstream_rewind (str->other_end);
2479 }
2480
2481 static int
2482 decoding_seekable_p (Lstream *stream)
2483 {
2484   struct decoding_stream *str = DECODING_STREAM_DATA (stream);
2485   return Lstream_seekable_p (str->other_end);
2486 }
2487
2488 static int
2489 decoding_flusher (Lstream *stream)
2490 {
2491   struct decoding_stream *str = DECODING_STREAM_DATA (stream);
2492   return Lstream_flush (str->other_end);
2493 }
2494
2495 static int
2496 decoding_closer (Lstream *stream)
2497 {
2498   struct decoding_stream *str = DECODING_STREAM_DATA (stream);
2499   if (stream->flags & LSTREAM_FL_WRITE)
2500     {
2501       str->flags |= CODING_STATE_END;
2502       decoding_writer (stream, 0, 0);
2503     }
2504   Dynarr_free (str->runoff);
2505 #ifdef MULE
2506 #ifdef ENABLE_COMPOSITE_CHARS
2507   if (str->iso2022.composite_chars)
2508     Dynarr_free (str->iso2022.composite_chars);
2509 #endif
2510 #endif
2511   return Lstream_close (str->other_end);
2512 }
2513
2514 Lisp_Object
2515 decoding_stream_coding_system (Lstream *stream)
2516 {
2517   Lisp_Object coding_system;
2518   struct decoding_stream *str = DECODING_STREAM_DATA (stream);
2519
2520   XSETCODING_SYSTEM (coding_system, str->codesys);
2521   return subsidiary_coding_system (coding_system, str->eol_type);
2522 }
2523
2524 void
2525 set_decoding_stream_coding_system (Lstream *lstr, Lisp_Object codesys)
2526 {
2527   Lisp_Coding_System *cs = XCODING_SYSTEM (codesys);
2528   struct decoding_stream *str = DECODING_STREAM_DATA (lstr);
2529   str->codesys = cs;
2530   if (CODING_SYSTEM_EOL_TYPE (cs) != EOL_AUTODETECT)
2531     str->eol_type = CODING_SYSTEM_EOL_TYPE (cs);
2532   reset_decoding_stream (str);
2533 }
2534
2535 /* WARNING WARNING WARNING WARNING!!!!!  If you open up a decoding
2536    stream for writing, no automatic code detection will be performed.
2537    The reason for this is that automatic code detection requires a
2538    seekable input.  Things will also fail if you open a decoding
2539    stream for reading using a non-fully-specified coding system and
2540    a non-seekable input stream. */
2541
2542 static Lisp_Object
2543 make_decoding_stream_1 (Lstream *stream, Lisp_Object codesys,
2544                         const char *mode)
2545 {
2546   Lstream *lstr = Lstream_new (lstream_decoding, mode);
2547   struct decoding_stream *str = DECODING_STREAM_DATA (lstr);
2548   Lisp_Object obj;
2549
2550   xzero (*str);
2551   str->other_end = stream;
2552   str->runoff = (unsigned_char_dynarr *) Dynarr_new (unsigned_char);
2553   str->eol_type = EOL_AUTODETECT;
2554   if (!strcmp (mode, "r")
2555       && Lstream_seekable_p (stream))
2556     /* We can determine the coding system now. */
2557     determine_real_coding_system (stream, &codesys, &str->eol_type);
2558   set_decoding_stream_coding_system (lstr, codesys);
2559   str->decst.eol_type = str->eol_type;
2560   str->decst.mask = ~0;
2561   XSETLSTREAM (obj, lstr);
2562   return obj;
2563 }
2564
2565 Lisp_Object
2566 make_decoding_input_stream (Lstream *stream, Lisp_Object codesys)
2567 {
2568   return make_decoding_stream_1 (stream, codesys, "r");
2569 }
2570
2571 Lisp_Object
2572 make_decoding_output_stream (Lstream *stream, Lisp_Object codesys)
2573 {
2574   return make_decoding_stream_1 (stream, codesys, "w");
2575 }
2576
2577 /* Note: the decode_coding_* functions all take the same
2578    arguments as mule_decode(), which is to say some SRC data of
2579    size N, which is to be stored into dynamic array DST.
2580    DECODING is the stream within which the decoding is
2581    taking place, but no data is actually read from or
2582    written to that stream; that is handled in decoding_reader()
2583    or decoding_writer().  This allows the same functions to
2584    be used for both reading and writing. */
2585
2586 static void
2587 mule_decode (Lstream *decoding, const Extbyte *src,
2588              unsigned_char_dynarr *dst, Lstream_data_count n)
2589 {
2590   struct decoding_stream *str = DECODING_STREAM_DATA (decoding);
2591
2592   /* If necessary, do encoding-detection now.  We do this when
2593      we're a writing stream or a non-seekable reading stream,
2594      meaning that we can't just process the whole input,
2595      rewind, and start over. */
2596
2597   if (CODING_SYSTEM_TYPE (str->codesys) == CODESYS_AUTODETECT ||
2598       str->eol_type == EOL_AUTODETECT)
2599     {
2600       Lisp_Object codesys;
2601
2602       XSETCODING_SYSTEM (codesys, str->codesys);
2603       detect_coding_type (&str->decst, src, n,
2604                           CODING_SYSTEM_TYPE (str->codesys) !=
2605                           CODESYS_AUTODETECT);
2606       if (CODING_SYSTEM_TYPE (str->codesys) == CODESYS_AUTODETECT &&
2607           str->decst.mask != ~0)
2608         /* #### This is cheesy.  What we really ought to do is
2609            buffer up a certain amount of data so as to get a
2610            less random result. */
2611         codesys = coding_system_from_mask (str->decst.mask);
2612       str->eol_type = str->decst.eol_type;
2613       if (XCODING_SYSTEM (codesys) != str->codesys)
2614         {
2615           /* Preserve the CODING_STATE_END flag in case it was set.
2616              If we erase it, bad things might happen. */
2617           int was_end = str->flags & CODING_STATE_END;
2618           set_decoding_stream_coding_system (decoding, codesys);
2619           if (was_end)
2620             str->flags |= CODING_STATE_END;
2621         }
2622     }
2623
2624   switch (CODING_SYSTEM_TYPE (str->codesys))
2625     {
2626 #ifdef DEBUG_XEMACS
2627     case CODESYS_INTERNAL:
2628       Dynarr_add_many (dst, src, n);
2629       break;
2630 #endif
2631     case CODESYS_AUTODETECT:
2632       /* If we got this far and still haven't decided on the coding
2633          system, then do no conversion. */
2634     case CODESYS_NO_CONVERSION:
2635       decode_coding_no_conversion (decoding, src, dst, n);
2636       break;
2637 #ifdef MULE
2638     case CODESYS_SHIFT_JIS:
2639       decode_coding_sjis (decoding, src, dst, n);
2640       break;
2641     case CODESYS_BIG5:
2642       decode_coding_big5 (decoding, src, dst, n);
2643       break;
2644     case CODESYS_UCS4:
2645       decode_coding_ucs4 (decoding, src, dst, n);
2646       break;
2647     case CODESYS_UTF16:
2648       decode_coding_utf16 (decoding, src, dst, n);
2649       break;
2650     case CODESYS_UTF8:
2651       decode_coding_utf8 (decoding, src, dst, n);
2652       break;
2653     case CODESYS_CCL:
2654       str->ccl.last_block = str->flags & CODING_STATE_END;
2655       /* When applying ccl program to stream, MUST NOT set NULL
2656          pointer to src.  */
2657       ccl_driver (&str->ccl, (src ? (unsigned char *)src : (unsigned char*)""),
2658                   dst, n, 0, CCL_MODE_DECODING);
2659       break;
2660     case CODESYS_ISO2022:
2661       decode_coding_iso2022 (decoding, src, dst, n);
2662       break;
2663 #endif /* MULE */
2664     default:
2665       abort ();
2666     }
2667 }
2668
2669 DEFUN ("decode-coding-region", Fdecode_coding_region, 3, 4, 0, /*
2670 Decode the text between START and END which is encoded in CODING-SYSTEM.
2671 This is useful if you've read in encoded text from a file without decoding
2672 it (e.g. you read in a JIS-formatted file but used the `binary' or
2673 `no-conversion' coding system, so that it shows up as "^[$B!<!+^[(B").
2674 Return length of decoded text.
2675 BUFFER defaults to the current buffer if unspecified.
2676 */
2677        (start, end, coding_system, buffer))
2678 {
2679   Bufpos b, e;
2680   struct buffer *buf = decode_buffer (buffer, 0);
2681   Lisp_Object instream, lb_outstream, de_outstream, outstream;
2682   Lstream *istr, *ostr;
2683   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2684
2685   get_buffer_range_char (buf, start, end, &b, &e, 0);
2686
2687   barf_if_buffer_read_only (buf, b, e);
2688
2689   coding_system = Fget_coding_system (coding_system);
2690   instream = make_lisp_buffer_input_stream  (buf, b, e, 0);
2691   lb_outstream = make_lisp_buffer_output_stream (buf, b, 0);
2692   de_outstream = make_decoding_output_stream (XLSTREAM (lb_outstream),
2693                                               coding_system);
2694   outstream = make_encoding_output_stream (XLSTREAM (de_outstream),
2695                                            Fget_coding_system (Qbinary));
2696   istr = XLSTREAM (instream);
2697   ostr = XLSTREAM (outstream);
2698   GCPRO4 (instream, lb_outstream, de_outstream, outstream);
2699
2700   /* The chain of streams looks like this:
2701
2702      [BUFFER] <----- send through
2703                      ------> [ENCODE AS BINARY]
2704                              ------> [DECODE AS SPECIFIED]
2705                                      ------> [BUFFER]
2706    */
2707
2708   while (1)
2709     {
2710       char tempbuf[1024]; /* some random amount */
2711       Bufpos newpos, even_newer_pos;
2712       Bufpos oldpos = lisp_buffer_stream_startpos (istr);
2713       Lstream_data_count size_in_bytes = Lstream_read (istr, tempbuf, sizeof (tempbuf));
2714
2715       if (!size_in_bytes)
2716         break;
2717       newpos = lisp_buffer_stream_startpos (istr);
2718       Lstream_write (ostr, tempbuf, size_in_bytes);
2719       even_newer_pos = lisp_buffer_stream_startpos (istr);
2720       buffer_delete_range (buf, even_newer_pos - (newpos - oldpos),
2721                            even_newer_pos, 0);
2722     }
2723   Lstream_close (istr);
2724   Lstream_close (ostr);
2725   UNGCPRO;
2726   Lstream_delete (istr);
2727   Lstream_delete (ostr);
2728   Lstream_delete (XLSTREAM (de_outstream));
2729   Lstream_delete (XLSTREAM (lb_outstream));
2730   return Qnil;
2731 }
2732
2733 \f
2734 /************************************************************************/
2735 /*           Converting to an external encoding ("encoding")            */
2736 /************************************************************************/
2737
2738 /* An encoding stream is an output stream.  When you create the
2739    stream, you specify the coding system that governs the encoding
2740    and another stream that the resulting encoded data is to be
2741    sent to, and then start sending data to it. */
2742
2743 #define ENCODING_STREAM_DATA(stream) LSTREAM_TYPE_DATA (stream, encoding)
2744
2745 struct encoding_stream
2746 {
2747   /* Coding system that governs the conversion. */
2748   Lisp_Coding_System *codesys;
2749
2750   /* Stream that we read the encoded data from or
2751      write the decoded data to. */
2752   Lstream *other_end;
2753
2754   /* If we are reading, then we can return only a fixed amount of
2755      data, so if the conversion resulted in too much data, we store it
2756      here for retrieval the next time around. */
2757   unsigned_char_dynarr *runoff;
2758
2759   /* FLAGS holds flags indicating the current state of the encoding.
2760      Some of these flags are dependent on the coding system. */
2761   unsigned int flags;
2762
2763   /* CH holds a partially built-up character.  Since we only deal
2764      with one- and two-byte characters at the moment, we only use
2765      this to store the first byte of a two-byte character. */
2766   unsigned int ch;
2767 #ifdef MULE
2768   /* Additional information used by the ISO2022 encoder. */
2769   struct
2770     {
2771       /* CHARSET holds the character sets currently assigned to the G0
2772          through G3 registers.  It is initialized from the array
2773          INITIAL_CHARSET in CODESYS. */
2774       Lisp_Object charset[4];
2775
2776       /* Which registers are currently invoked into the left (GL) and
2777          right (GR) halves of the 8-bit encoding space? */
2778       int register_left, register_right;
2779
2780       /* Whether we need to explicitly designate the charset in the
2781          G? register before using it.  It is initialized from the
2782          array FORCE_CHARSET_ON_OUTPUT in CODESYS. */
2783       unsigned char force_charset_on_output[4];
2784
2785       /* Other state variables that need to be preserved across
2786          invocations. */
2787       Lisp_Object current_charset;
2788       int current_half;
2789       int current_char_boundary;
2790     } iso2022;
2791
2792   void (*encode_char) (struct encoding_stream *str, Emchar c,
2793                        unsigned_char_dynarr *dst, unsigned int *flags);
2794   void (*finish) (struct encoding_stream *str,
2795                   unsigned_char_dynarr *dst, unsigned int *flags);
2796
2797   /* Additional information (the state of the running CCL program)
2798      used by the CCL encoder. */
2799   struct ccl_program ccl;
2800 #endif /* MULE */
2801 };
2802
2803 static Lstream_data_count encoding_reader (Lstream *stream, unsigned char *data, Lstream_data_count size);
2804 static Lstream_data_count encoding_writer (Lstream *stream, const unsigned char *data,
2805                                 Lstream_data_count size);
2806 static int encoding_rewinder   (Lstream *stream);
2807 static int encoding_seekable_p (Lstream *stream);
2808 static int encoding_flusher    (Lstream *stream);
2809 static int encoding_closer     (Lstream *stream);
2810
2811 static Lisp_Object encoding_marker (Lisp_Object stream);
2812
2813 DEFINE_LSTREAM_IMPLEMENTATION ("encoding", lstream_encoding,
2814                                sizeof (struct encoding_stream));
2815
2816 static Lisp_Object
2817 encoding_marker (Lisp_Object stream)
2818 {
2819   Lstream *str = ENCODING_STREAM_DATA (XLSTREAM (stream))->other_end;
2820   Lisp_Object str_obj;
2821
2822   /* We do not need to mark the coding systems or charsets stored
2823      within the stream because they are stored in a global list
2824      and automatically marked. */
2825
2826   XSETLSTREAM (str_obj, str);
2827   mark_object (str_obj);
2828   if (str->imp->marker)
2829     return (str->imp->marker) (str_obj);
2830   else
2831     return Qnil;
2832 }
2833
2834 /* Read SIZE bytes of data and store it into DATA.  We are a encoding stream
2835    so we read data from the other end, encode it, and store it into DATA. */
2836
2837 static Lstream_data_count
2838 encoding_reader (Lstream *stream, unsigned char *data, Lstream_data_count size)
2839 {
2840   struct encoding_stream *str = ENCODING_STREAM_DATA (stream);
2841   unsigned char *orig_data = data;
2842   Lstream_data_count read_size;
2843   int error_occurred = 0;
2844
2845   /* We need to interface to mule_encode(), which expects to take some
2846      amount of data and store the result into a Dynarr.  We have
2847      mule_encode() store into str->runoff, and take data from there
2848      as necessary. */
2849
2850   /* We loop until we have enough data, reading chunks from the other
2851      end and encoding it. */
2852   while (1)
2853     {
2854       /* Take data from the runoff if we can.  Make sure to take at
2855          most SIZE bytes, and delete the data from the runoff. */
2856       if (Dynarr_length (str->runoff) > 0)
2857         {
2858           int chunk = min ((int) size, Dynarr_length (str->runoff));
2859           memcpy (data, Dynarr_atp (str->runoff, 0), chunk);
2860           Dynarr_delete_many (str->runoff, 0, chunk);
2861           data += chunk;
2862           size -= chunk;
2863         }
2864
2865       if (size == 0)
2866         break; /* No more room for data */
2867
2868       if (str->flags & CODING_STATE_END)
2869         /* This means that on the previous iteration, we hit the EOF on
2870            the other end.  We loop once more so that mule_encode() can
2871            output any final stuff it may be holding, or any "go back
2872            to a sane state" escape sequences. (This latter makes sense
2873            during encoding.) */
2874         break;
2875
2876       /* Exhausted the runoff, so get some more.  DATA at least SIZE bytes
2877          left of storage in it, so it's OK to read directly into it.
2878          (We'll be overwriting above, after we've encoded it into the
2879          runoff.) */
2880       read_size = Lstream_read (str->other_end, data, size);
2881       if (read_size < 0)
2882         {
2883           error_occurred = 1;
2884           break;
2885         }
2886       if (read_size == 0)
2887         /* There might be some more end data produced in the translation.
2888            See the comment above. */
2889         str->flags |= CODING_STATE_END;
2890       mule_encode (stream, data, str->runoff, read_size);
2891     }
2892
2893   if (data == orig_data)
2894     return error_occurred ? -1 : 0;
2895   else
2896     return data - orig_data;
2897 }
2898
2899 static Lstream_data_count
2900 encoding_writer (Lstream *stream, const unsigned char *data, Lstream_data_count size)
2901 {
2902   struct encoding_stream *str = ENCODING_STREAM_DATA (stream);
2903   Lstream_data_count retval;
2904
2905   /* Encode all our data into the runoff, and then attempt to write
2906      it all out to the other end.  Remove whatever chunk we succeeded
2907      in writing. */
2908   mule_encode (stream, data, str->runoff, size);
2909   retval = Lstream_write (str->other_end, Dynarr_atp (str->runoff, 0),
2910                           Dynarr_length (str->runoff));
2911   if (retval > 0)
2912     Dynarr_delete_many (str->runoff, 0, retval);
2913   /* Do NOT return retval.  The return value indicates how much
2914      of the incoming data was written, not how many bytes were
2915      written. */
2916   return size;
2917 }
2918
2919 static void
2920 reset_encoding_stream (struct encoding_stream *str)
2921 {
2922 #ifdef MULE
2923   switch (CODING_SYSTEM_TYPE (str->codesys))
2924     {
2925     case CODESYS_ISO2022:
2926       {
2927         int i;
2928
2929         str->encode_char = &char_encode_iso2022;
2930         str->finish = &char_finish_iso2022;
2931         for (i = 0; i < 4; i++)
2932           {
2933             str->iso2022.charset[i] =
2934               CODING_SYSTEM_ISO2022_INITIAL_CHARSET (str->codesys, i);
2935             str->iso2022.force_charset_on_output[i] =
2936               CODING_SYSTEM_ISO2022_FORCE_CHARSET_ON_OUTPUT (str->codesys, i);
2937           }
2938         str->iso2022.register_left = 0;
2939         str->iso2022.register_right = 1;
2940         str->iso2022.current_charset = Qnil;
2941         str->iso2022.current_half = 0;
2942         break;
2943       }
2944     case CODESYS_CCL:
2945       setup_ccl_program (&str->ccl, CODING_SYSTEM_CCL_ENCODE (str->codesys));
2946       break;
2947     case CODESYS_UTF8:
2948       str->encode_char = &char_encode_utf8;
2949       str->finish = &char_finish_utf8;
2950       break;
2951     case CODESYS_UTF16:
2952       str->encode_char = &char_encode_utf16;
2953       str->finish = &char_finish_utf16;
2954       break;
2955     case CODESYS_UCS4:
2956       str->encode_char = &char_encode_ucs4;
2957       str->finish = &char_finish_ucs4;
2958       break;
2959     case CODESYS_SHIFT_JIS:
2960       str->encode_char = &char_encode_shift_jis;
2961       str->finish = &char_finish_shift_jis;
2962       break;
2963     case CODESYS_BIG5:
2964       str->encode_char = &char_encode_big5;
2965       str->finish = &char_finish_big5;
2966       break;
2967     default:
2968       break;
2969     }
2970 #endif /* MULE */
2971   str->iso2022.current_char_boundary = 0;
2972   str->flags = str->ch = 0;
2973 }
2974
2975 static int
2976 encoding_rewinder (Lstream *stream)
2977 {
2978   struct encoding_stream *str = ENCODING_STREAM_DATA (stream);
2979   reset_encoding_stream (str);
2980   Dynarr_reset (str->runoff);
2981   return Lstream_rewind (str->other_end);
2982 }
2983
2984 static int
2985 encoding_seekable_p (Lstream *stream)
2986 {
2987   struct encoding_stream *str = ENCODING_STREAM_DATA (stream);
2988   return Lstream_seekable_p (str->other_end);
2989 }
2990
2991 static int
2992 encoding_flusher (Lstream *stream)
2993 {
2994   struct encoding_stream *str = ENCODING_STREAM_DATA (stream);
2995   return Lstream_flush (str->other_end);
2996 }
2997
2998 static int
2999 encoding_closer (Lstream *stream)
3000 {
3001   struct encoding_stream *str = ENCODING_STREAM_DATA (stream);
3002   if (stream->flags & LSTREAM_FL_WRITE)
3003     {
3004       str->flags |= CODING_STATE_END;
3005       encoding_writer (stream, 0, 0);
3006     }
3007   Dynarr_free (str->runoff);
3008   return Lstream_close (str->other_end);
3009 }
3010
3011 Lisp_Object
3012 encoding_stream_coding_system (Lstream *stream)
3013 {
3014   Lisp_Object coding_system;
3015   struct encoding_stream *str = ENCODING_STREAM_DATA (stream);
3016
3017   XSETCODING_SYSTEM (coding_system, str->codesys);
3018   return coding_system;
3019 }
3020
3021 void
3022 set_encoding_stream_coding_system (Lstream *lstr, Lisp_Object codesys)
3023 {
3024   Lisp_Coding_System *cs = XCODING_SYSTEM (codesys);
3025   struct encoding_stream *str = ENCODING_STREAM_DATA (lstr);
3026   str->codesys = cs;
3027   reset_encoding_stream (str);
3028 }
3029
3030 static Lisp_Object
3031 make_encoding_stream_1 (Lstream *stream, Lisp_Object codesys,
3032                         const char *mode)
3033 {
3034   Lstream *lstr = Lstream_new (lstream_encoding, mode);
3035   struct encoding_stream *str = ENCODING_STREAM_DATA (lstr);
3036   Lisp_Object obj;
3037
3038   xzero (*str);
3039   str->runoff = Dynarr_new (unsigned_char);
3040   str->other_end = stream;
3041   set_encoding_stream_coding_system (lstr, codesys);
3042   XSETLSTREAM (obj, lstr);
3043   return obj;
3044 }
3045
3046 Lisp_Object
3047 make_encoding_input_stream (Lstream *stream, Lisp_Object codesys)
3048 {
3049   return make_encoding_stream_1 (stream, codesys, "r");
3050 }
3051
3052 Lisp_Object
3053 make_encoding_output_stream (Lstream *stream, Lisp_Object codesys)
3054 {
3055   return make_encoding_stream_1 (stream, codesys, "w");
3056 }
3057
3058 /* Convert N bytes of internally-formatted data stored in SRC to an
3059    external format, according to the encoding stream ENCODING.
3060    Store the encoded data into DST. */
3061
3062 static void
3063 mule_encode (Lstream *encoding, const Bufbyte *src,
3064              unsigned_char_dynarr *dst, Lstream_data_count n)
3065 {
3066   struct encoding_stream *str = ENCODING_STREAM_DATA (encoding);
3067
3068   switch (CODING_SYSTEM_TYPE (str->codesys))
3069     {
3070 #ifdef DEBUG_XEMACS
3071     case CODESYS_INTERNAL:
3072       Dynarr_add_many (dst, src, n);
3073       break;
3074 #endif
3075     case CODESYS_AUTODETECT:
3076       /* If we got this far and still haven't decided on the coding
3077          system, then do no conversion. */
3078     case CODESYS_NO_CONVERSION:
3079       encode_coding_no_conversion (encoding, src, dst, n);
3080       break;
3081 #ifdef MULE
3082     case CODESYS_CCL:
3083       str->ccl.last_block = str->flags & CODING_STATE_END;
3084       /* When applying ccl program to stream, MUST NOT set NULL
3085          pointer to src.  */
3086       ccl_driver (&str->ccl, ((src) ? src : (unsigned char*)""),
3087                   dst, n, 0, CCL_MODE_ENCODING);
3088       break;
3089 #endif /* MULE */
3090     default:
3091       text_encode_generic (encoding, src, dst, n);
3092     }
3093 }
3094
3095 DEFUN ("encode-coding-region", Fencode_coding_region, 3, 4, 0, /*
3096 Encode the text between START and END using CODING-SYSTEM.
3097 This will, for example, convert Japanese characters into stuff such as
3098 "^[$B!<!+^[(B" if you use the JIS encoding.  Return length of encoded
3099 text.  BUFFER defaults to the current buffer if unspecified.
3100 */
3101        (start, end, coding_system, buffer))
3102 {
3103   Bufpos b, e;
3104   struct buffer *buf = decode_buffer (buffer, 0);
3105   Lisp_Object instream, lb_outstream, de_outstream, outstream;
3106   Lstream *istr, *ostr;
3107   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
3108
3109   get_buffer_range_char (buf, start, end, &b, &e, 0);
3110
3111   barf_if_buffer_read_only (buf, b, e);
3112
3113   coding_system = Fget_coding_system (coding_system);
3114   instream  = make_lisp_buffer_input_stream  (buf, b, e, 0);
3115   lb_outstream = make_lisp_buffer_output_stream (buf, b, 0);
3116   de_outstream = make_decoding_output_stream (XLSTREAM (lb_outstream),
3117                                               Fget_coding_system (Qbinary));
3118   outstream = make_encoding_output_stream (XLSTREAM (de_outstream),
3119                                            coding_system);
3120   istr = XLSTREAM (instream);
3121   ostr = XLSTREAM (outstream);
3122   GCPRO4 (instream, outstream, de_outstream, lb_outstream);
3123   /* The chain of streams looks like this:
3124
3125      [BUFFER] <----- send through
3126                      ------> [ENCODE AS SPECIFIED]
3127                              ------> [DECODE AS BINARY]
3128                                      ------> [BUFFER]
3129    */
3130   while (1)
3131     {
3132       char tempbuf[1024]; /* some random amount */
3133       Bufpos newpos, even_newer_pos;
3134       Bufpos oldpos = lisp_buffer_stream_startpos (istr);
3135       Lstream_data_count size_in_bytes = Lstream_read (istr, tempbuf, sizeof (tempbuf));
3136
3137       if (!size_in_bytes)
3138         break;
3139       newpos = lisp_buffer_stream_startpos (istr);
3140       Lstream_write (ostr, tempbuf, size_in_bytes);
3141       even_newer_pos = lisp_buffer_stream_startpos (istr);
3142       buffer_delete_range (buf, even_newer_pos - (newpos - oldpos),
3143                            even_newer_pos, 0);
3144     }
3145
3146   {
3147     Charcount retlen =
3148       lisp_buffer_stream_startpos (XLSTREAM (instream)) - b;
3149     Lstream_close (istr);
3150     Lstream_close (ostr);
3151     UNGCPRO;
3152     Lstream_delete (istr);
3153     Lstream_delete (ostr);
3154     Lstream_delete (XLSTREAM (de_outstream));
3155     Lstream_delete (XLSTREAM (lb_outstream));
3156     return make_int (retlen);
3157   }
3158 }
3159
3160 #ifdef MULE
3161 \f
3162 static void
3163 text_encode_generic (Lstream *encoding, const Bufbyte *src,
3164                      unsigned_char_dynarr *dst, Lstream_data_count n)
3165 {
3166   unsigned char c;
3167   unsigned char char_boundary;
3168   struct encoding_stream *str = ENCODING_STREAM_DATA (encoding);
3169   unsigned int flags          = str->flags;
3170   Emchar ch                   = str->ch;
3171
3172   char_boundary = str->iso2022.current_char_boundary;
3173
3174   while (n--)
3175     {
3176       c = *src++;
3177
3178       if (char_boundary == 0)
3179         {
3180           if (c >= 0xfc)
3181             {
3182               ch = c & 0x01;
3183               char_boundary = 5;
3184             }
3185           else if (c >= 0xf8)
3186             {
3187               ch = c & 0x03;
3188               char_boundary = 4;
3189             }
3190           else if (c >= 0xf0)
3191             {
3192               ch = c & 0x07;
3193               char_boundary = 3;
3194             }
3195           else if (c >= 0xe0)
3196             {
3197               ch = c & 0x0f;
3198               char_boundary = 2;
3199             }
3200           else if (c >= 0xc0)
3201             {
3202               ch = c & 0x1f;
3203               char_boundary = 1;
3204             }
3205           else
3206             (*str->encode_char) (str, c, dst, &flags);
3207         }
3208       else if (char_boundary == 1)
3209         {
3210           (*str->encode_char) (str, (ch << 6) | (c & 0x3f), dst, &flags);
3211           ch =0;
3212           char_boundary = 0;
3213         }
3214       else
3215         {
3216           ch = (ch << 6) | (c & 0x3f);
3217           char_boundary--;
3218         }
3219     }
3220
3221   if ((char_boundary == 0) && (flags & CODING_STATE_END))
3222     {
3223       (*str->finish) (str, dst, &flags);
3224     }
3225
3226   str->flags = flags;
3227   str->ch    = ch;
3228   str->iso2022.current_char_boundary = char_boundary;
3229 }
3230
3231 \f
3232 #ifdef UTF2000
3233 /************************************************************************/
3234 /*                          entity reference                            */
3235 /************************************************************************/
3236
3237 INLINE_HEADER void
3238 decode_flush_er_chars (struct decoding_stream *str, unsigned_char_dynarr* dst);
3239 INLINE_HEADER void
3240 decode_flush_er_chars (struct decoding_stream *str, unsigned_char_dynarr* dst)
3241 {
3242   if ( str->er_counter > 0)
3243     {
3244       Dynarr_add_many (dst, str->er_buf, str->er_counter);
3245       str->er_counter = 0;
3246     }
3247 }
3248
3249 void decode_add_er_char (struct decoding_stream *str, Emchar character,
3250                          unsigned_char_dynarr* dst);
3251 void
3252 decode_add_er_char (struct decoding_stream *str, Emchar c,
3253                     unsigned_char_dynarr* dst)
3254 {
3255   if (str->er_counter == 0)
3256     {
3257       if (CODING_SYSTEM_USE_ENTITY_REFERENCE (str->codesys)
3258           && (c == '&') )
3259         {
3260           str->er_buf[0] = '&';
3261           str->er_counter++;
3262         }
3263       else
3264         DECODE_ADD_UCS_CHAR (c, dst);
3265     }
3266   else if (c == ';')
3267     {
3268       Lisp_Object string = make_string (str->er_buf,
3269                                         str->er_counter);
3270       Lisp_Object rest = Vcoded_charset_entity_reference_alist;
3271       Lisp_Object cell;
3272       Lisp_Object ret;
3273       Lisp_Object pat;
3274       Lisp_Object ccs;
3275       Lisp_Object char_type;
3276       int base;
3277
3278       while (!NILP (rest))
3279         {                     
3280           cell = Fcar (rest);
3281           ccs = Fcar (cell);
3282           if (CONSP (ccs))
3283             {
3284               char_type = XCDR (ccs);
3285               ccs = XCAR (ccs);
3286             }
3287           else
3288             char_type = Qnil;
3289           if (NILP (ccs = Ffind_charset (ccs)))
3290             continue;
3291
3292           cell = Fcdr (cell);
3293           ret = Fcar (cell);
3294           if (STRINGP (ret))
3295             pat = ret;
3296           else
3297             continue;
3298
3299           cell = Fcdr (cell);
3300           cell = Fcdr (cell);
3301           ret = Fcar (cell);
3302           if (EQ (ret, Qd))
3303             {
3304               pat = concat3 (build_string ("^&"),
3305                              pat, build_string ("\\([0-9]+\\)$"));
3306               base = 10;
3307             }
3308           else if (EQ (ret, Qx))
3309             {
3310               pat = concat3 (build_string ("^&"),
3311                              pat, build_string ("\\([0-9a-f]+\\)$"));
3312               base = 16;
3313             }
3314           else if (EQ (ret, QX))
3315             {
3316               pat = concat3 (build_string ("^&"),
3317                              pat, build_string ("\\([0-9A-F]+\\)$"));
3318               base = 16;
3319             }
3320           else
3321             continue;
3322
3323           if (!NILP (Fstring_match (pat, string, Qnil, Qnil)))
3324             {
3325               int code
3326                 = XINT (Fstring_to_number
3327                         (Fsubstring (string,
3328                                      Fmatch_beginning (make_int (1)),
3329                                      Fmatch_end (make_int (1))),
3330                          make_int (base)));
3331               Emchar chr
3332                 = NILP (char_type)
3333                 ? DECODE_CHAR (ccs, code, 0)
3334                 : decode_builtin_char (ccs, code);
3335
3336               DECODE_ADD_UCS_CHAR (chr, dst);
3337               goto decoded;
3338             }
3339           rest = Fcdr (rest);
3340         }
3341       if (!NILP (Fstring_match (build_string ("^&MCS-\\([0-9A-F]+\\)$"),
3342                                 string, Qnil, Qnil)))
3343         {
3344           int code
3345             = XUINT (Fstring_to_number
3346                      (Fsubstring (string,
3347                                   Fmatch_beginning (make_int (1)),
3348                                   Fmatch_end (make_int (1))),
3349                       make_int (16)));
3350
3351           DECODE_ADD_UCS_CHAR (code, dst);
3352         }
3353       else
3354         {
3355           Dynarr_add_many (dst, str->er_buf, str->er_counter);
3356           Dynarr_add (dst, ';');
3357         }
3358     decoded:
3359       str->er_counter = 0;
3360     }
3361   else if ( (str->er_counter >= ER_BUF_SIZE) || (c >= 0x7F) )
3362     {
3363       Dynarr_add_many (dst, str->er_buf, str->er_counter);
3364       str->er_counter = 0;
3365       DECODE_ADD_UCS_CHAR (c, dst);
3366     }
3367   else
3368     str->er_buf[str->er_counter++] = c;
3369 }
3370
3371 void char_encode_as_entity_reference (Emchar ch, char* buf);
3372 void
3373 char_encode_as_entity_reference (Emchar ch, char* buf)
3374 {
3375   Lisp_Object rest = Vcoded_charset_entity_reference_alist;
3376   Lisp_Object cell;
3377   Lisp_Object ccs;
3378   Lisp_Object char_type;
3379   int format_columns, idx;
3380   char format[ER_BUF_SIZE];
3381
3382   while (!NILP (rest))
3383     {
3384       cell = Fcar (rest);
3385       ccs = Fcar (cell);
3386       if (CONSP (ccs))
3387         {
3388           char_type = XCDR (ccs);
3389           ccs = XCAR (ccs);
3390         }
3391       else
3392         char_type = Qnil;
3393       if (!NILP (ccs = Ffind_charset (ccs)))
3394         {
3395           int code_point = charset_code_point (ccs, ch, 0);
3396
3397           if ( (code_point >= 0)
3398                && (NILP (char_type)
3399                    || DECODE_CHAR (ccs, code_point, 0) != ch) )
3400             {
3401               Lisp_Object ret;
3402
3403               cell = Fcdr (cell);
3404               ret = Fcar (cell);
3405               if ( STRINGP (ret) &&
3406                    ( (idx = XSTRING_LENGTH (ret)) <= (ER_BUF_SIZE - 4) ) )
3407                 {
3408                   format[0] = '&';
3409                   strncpy (&format[1], XSTRING_DATA (ret), idx);
3410                   idx++;
3411                 }
3412               else
3413                 goto try_next;
3414
3415               cell = Fcdr (cell);
3416               ret = Fcar (cell);
3417               if (INTP (ret))
3418                 {
3419                   format[idx++] = '%';
3420                   format_columns = XINT (ret);
3421                   if ( (2 <= format_columns) && (format_columns <= 8)
3422                        && (idx + format_columns <= ER_BUF_SIZE - 1) )
3423                     {
3424                       format [idx++] = '0';
3425                       format [idx++] = '0' + format_columns;
3426                     }
3427                 }
3428               else
3429                 goto try_next;
3430
3431               cell = Fcdr (cell);
3432               ret = Fcar (cell);
3433               if (EQ (ret, Qd))
3434                 format [idx++] = 'd';
3435               else if (EQ (ret, Qx))
3436                 format [idx++] = 'x';
3437               else if (EQ (ret, QX))
3438                 format [idx++] = 'X';
3439               else
3440                 goto try_next;
3441               format [idx++] = ';';
3442               format [idx++] = 0;
3443
3444               sprintf (buf, format, code_point);
3445               return;
3446             }
3447         }
3448     try_next:
3449       rest = Fcdr (rest);
3450     }
3451   sprintf (buf, "&MCS-%08X;", ch);
3452 }
3453
3454 \f
3455 /************************************************************************/
3456 /*                          character composition                       */
3457 /************************************************************************/
3458 extern Lisp_Object Qcomposition;
3459
3460 INLINE_HEADER void
3461 COMPOSE_FLUSH_CHARS (struct decoding_stream *str, unsigned_char_dynarr* dst);
3462 INLINE_HEADER void
3463 COMPOSE_FLUSH_CHARS (struct decoding_stream *str, unsigned_char_dynarr* dst)
3464 {
3465   unsigned i;
3466
3467   for (i = 0; i < str->combined_char_count; i++)
3468     decode_add_er_char (str, str->combined_chars[i], dst);
3469   str->combined_char_count = 0;
3470   str->combining_table = Qnil;
3471 }
3472
3473 void COMPOSE_ADD_CHAR (struct decoding_stream *str, Emchar character,
3474                        unsigned_char_dynarr* dst);
3475 void
3476 COMPOSE_ADD_CHAR (struct decoding_stream *str,
3477                   Emchar character, unsigned_char_dynarr* dst)
3478 {
3479   if (CODING_SYSTEM_DISABLE_COMPOSITION (str->codesys))
3480     decode_add_er_char (str, character, dst);
3481   else if (!CONSP (str->combining_table))
3482     {
3483       Lisp_Object ret
3484         = Fchar_feature (make_char (character), Qcomposition, Qnil,
3485                          Qnil, Qnil);
3486
3487       if (NILP (ret))
3488         decode_add_er_char (str, character, dst);
3489       else
3490         {
3491           str->combined_chars[0] = character;
3492           str->combined_char_count = 1;
3493           str->combining_table = ret;
3494         }
3495     }
3496   else
3497     {
3498       Lisp_Object ret
3499         = Fcdr (Fassq (make_char (character), str->combining_table));
3500
3501       if (CHARP (ret))
3502         {
3503           Emchar char2 = XCHARVAL (ret);
3504           Lisp_Object ret2 = Fchar_feature (ret, Qcomposition, Qnil,
3505                                             Qnil, Qnil);
3506
3507           if (NILP (ret2))
3508             {
3509               decode_add_er_char (str, char2, dst);
3510               str->combined_char_count = 0;
3511               str->combining_table = Qnil;
3512             }
3513           else
3514             {
3515               str->combined_chars[0] = char2;
3516               str->combined_char_count = 1;
3517               str->combining_table = ret2;
3518             }
3519         }
3520       else
3521         {
3522           ret = Fchar_feature (make_char (character), Qcomposition, Qnil,
3523                                Qnil, Qnil);
3524
3525           COMPOSE_FLUSH_CHARS (str, dst);
3526           if (NILP (ret))
3527             decode_add_er_char (str, character, dst);
3528           else
3529             {
3530               str->combined_chars[0] = character;
3531               str->combined_char_count = 1;
3532               str->combining_table = ret;
3533             }
3534         }
3535     }
3536 }
3537 #else /* not UTF2000 */
3538 #define COMPOSE_FLUSH_CHARS(str, dst)
3539 #define COMPOSE_ADD_CHAR(str, ch, dst) DECODE_ADD_UCS_CHAR (ch, dst)
3540 #endif /* UTF2000 */
3541
3542 \f
3543 /************************************************************************/
3544 /*                          Shift-JIS methods                           */
3545 /************************************************************************/
3546
3547 /* Shift-JIS is a coding system encoding three character sets: ASCII, right
3548    half of JISX0201-Kana, and JISX0208.  An ASCII character is encoded
3549    as is.  A character of JISX0201-Kana (DIMENSION1_CHARS94 character set) is
3550    encoded by "position-code + 0x80".  A character of JISX0208
3551    (DIMENSION2_CHARS94 character set) is encoded in 2-byte but two
3552    position-codes are divided and shifted so that it fit in the range
3553    below.
3554
3555    --- CODE RANGE of Shift-JIS ---
3556    (character set)      (range)
3557    ASCII                0x00 .. 0x7F
3558    JISX0201-Kana        0xA0 .. 0xDF
3559    JISX0208 (1st byte)  0x80 .. 0x9F and 0xE0 .. 0xEF
3560             (2nd byte)  0x40 .. 0x7E and 0x80 .. 0xFC
3561    -------------------------------
3562
3563 */
3564
3565 /* Is this the first byte of a Shift-JIS two-byte char? */
3566
3567 #define BYTE_SJIS_TWO_BYTE_1_P(c) \
3568   (((c) >= 0x81 && (c) <= 0x9F) || ((c) >= 0xE0 && (c) <= 0xEF))
3569
3570 /* Is this the second byte of a Shift-JIS two-byte char? */
3571
3572 #define BYTE_SJIS_TWO_BYTE_2_P(c) \
3573   (((c) >= 0x40 && (c) <= 0x7E) || ((c) >= 0x80 && (c) <= 0xFC))
3574
3575 #define BYTE_SJIS_KATAKANA_P(c) \
3576   ((c) >= 0xA1 && (c) <= 0xDF)
3577
3578 static int
3579 detect_coding_sjis (struct detection_state *st, const Extbyte *src, Lstream_data_count n)
3580 {
3581   while (n--)
3582     {
3583       unsigned char c = *(unsigned char *)src++;
3584       if (c == ISO_CODE_ESC || c == ISO_CODE_SI || c == ISO_CODE_SO)
3585         return 0;
3586       if (st->shift_jis.in_second_byte)
3587         {
3588           st->shift_jis.in_second_byte = 0;
3589           if (c < 0x40)
3590             return 0;
3591         }
3592       else if ((c >= 0x80 && c < 0xA0) || c >= 0xE0)
3593         st->shift_jis.in_second_byte = 1;
3594     }
3595   return CODING_CATEGORY_SHIFT_JIS_MASK;
3596 }
3597
3598 /* Convert Shift-JIS data to internal format. */
3599
3600 static void
3601 decode_coding_sjis (Lstream *decoding, const Extbyte *src,
3602                     unsigned_char_dynarr *dst, Lstream_data_count n)
3603 {
3604   struct decoding_stream *str = DECODING_STREAM_DATA (decoding);
3605   unsigned int flags  = str->flags;
3606   unsigned int cpos   = str->cpos;
3607   eol_type_t eol_type = str->eol_type;
3608
3609   while (n--)
3610     {
3611       unsigned char c = *(unsigned char *)src++;
3612
3613       if (cpos)
3614         {
3615           /* Previous character was first byte of Shift-JIS Kanji char. */
3616           if (BYTE_SJIS_TWO_BYTE_2_P (c))
3617             {
3618               unsigned char e1, e2;
3619
3620               DECODE_SJIS (cpos, c, e1, e2);
3621 #ifdef UTF2000
3622               DECODE_ADD_UCS_CHAR(MAKE_CHAR(Vcharset_japanese_jisx0208,
3623                                             e1 & 0x7F,
3624                                             e2 & 0x7F), dst);
3625 #else
3626               Dynarr_add (dst, LEADING_BYTE_JAPANESE_JISX0208);
3627               Dynarr_add (dst, e1);
3628               Dynarr_add (dst, e2);
3629 #endif
3630             }
3631           else
3632             {
3633               DECODE_ADD_BINARY_CHAR (cpos, dst);
3634               DECODE_ADD_BINARY_CHAR (c, dst);
3635             }
3636           cpos = 0;
3637         }
3638       else
3639         {
3640           DECODE_HANDLE_EOL_TYPE (eol_type, c, flags, dst);
3641           if (BYTE_SJIS_TWO_BYTE_1_P (c))
3642             cpos = c;
3643           else if (BYTE_SJIS_KATAKANA_P (c))
3644             {
3645 #ifdef UTF2000
3646               DECODE_ADD_UCS_CHAR(MAKE_CHAR(Vcharset_katakana_jisx0201,
3647                                             c & 0x7F, 0), dst);
3648 #else
3649               Dynarr_add (dst, LEADING_BYTE_KATAKANA_JISX0201);
3650               Dynarr_add (dst, c);
3651 #endif
3652             }
3653 #ifdef UTF2000
3654           else if (c > 32)
3655             DECODE_ADD_UCS_CHAR(MAKE_CHAR(Vcharset_latin_jisx0201,
3656                                           c, 0), dst);
3657 #endif
3658           else
3659             DECODE_ADD_BINARY_CHAR (c, dst);
3660         }
3661     label_continue_loop:;
3662     }
3663
3664   DECODE_HANDLE_END_OF_CONVERSION (flags, cpos, dst);
3665
3666   str->flags = flags;
3667   str->cpos  = cpos;
3668 }
3669
3670 /* Convert internal character representation to Shift_JIS. */
3671
3672 void
3673 char_encode_shift_jis (struct encoding_stream *str, Emchar ch,
3674                        unsigned_char_dynarr *dst, unsigned int *flags)
3675 {
3676   eol_type_t eol_type = CODING_SYSTEM_EOL_TYPE (str->codesys);
3677
3678   if (ch == '\n')
3679     {
3680       if (eol_type != EOL_LF && eol_type != EOL_AUTODETECT)
3681         Dynarr_add (dst, '\r');
3682       if (eol_type != EOL_CR)
3683         Dynarr_add (dst, ch);
3684     }
3685   else
3686     {
3687       unsigned int s1, s2;
3688 #ifdef UTF2000
3689       int code_point = charset_code_point (Vcharset_latin_jisx0201, ch, 0);
3690
3691       if (code_point >= 0)
3692         Dynarr_add (dst, code_point);
3693       else if ((code_point
3694                 = charset_code_point (Vcharset_japanese_jisx0208_1990, ch, 0))
3695                >= 0)
3696         {
3697           ENCODE_SJIS ((code_point >> 8) | 0x80,
3698                        (code_point & 0xFF) | 0x80, s1, s2);
3699           Dynarr_add (dst, s1);
3700           Dynarr_add (dst, s2);
3701         }
3702       else if ((code_point
3703                 = charset_code_point (Vcharset_katakana_jisx0201, ch, 0))
3704                >= 0)
3705         Dynarr_add (dst, code_point | 0x80);
3706       else if ((code_point
3707                 = charset_code_point (Vcharset_japanese_jisx0208, ch, 0))
3708                >= 0)
3709         {
3710           ENCODE_SJIS ((code_point >> 8) | 0x80,
3711                        (code_point & 0xFF) | 0x80, s1, s2);
3712           Dynarr_add (dst, s1);
3713           Dynarr_add (dst, s2);
3714         }
3715       else if ((code_point = charset_code_point (Vcharset_ascii, ch, 0))
3716                >= 0)
3717         Dynarr_add (dst, code_point);
3718       else
3719         Dynarr_add (dst, '?');
3720 #else
3721       Lisp_Object charset;
3722       unsigned int c1, c2;
3723
3724       BREAKUP_CHAR (ch, charset, c1, c2);
3725           
3726       if (EQ(charset, Vcharset_katakana_jisx0201))
3727         {
3728           Dynarr_add (dst, c1 | 0x80);
3729         }
3730       else if (c2 == 0)
3731         {
3732           Dynarr_add (dst, c1);
3733         }
3734       else if (EQ(charset, Vcharset_japanese_jisx0208))
3735         {
3736           ENCODE_SJIS (c1 | 0x80, c2 | 0x80, s1, s2);
3737           Dynarr_add (dst, s1);
3738           Dynarr_add (dst, s2);
3739         }
3740       else
3741         Dynarr_add (dst, '?');
3742 #endif
3743     }
3744 }
3745
3746 void
3747 char_finish_shift_jis (struct encoding_stream *str, unsigned_char_dynarr *dst,
3748                        unsigned int *flags)
3749 {
3750 }
3751
3752 DEFUN ("decode-shift-jis-char", Fdecode_shift_jis_char, 1, 1, 0, /*
3753 Decode a JISX0208 character of Shift-JIS coding-system.
3754 CODE is the character code in Shift-JIS as a cons of type bytes.
3755 Return the corresponding character.
3756 */
3757        (code))
3758 {
3759   unsigned char c1, c2, s1, s2;
3760
3761   CHECK_CONS (code);
3762   CHECK_INT (XCAR (code));
3763   CHECK_INT (XCDR (code));
3764   s1 = XINT (XCAR (code));
3765   s2 = XINT (XCDR (code));
3766   if (BYTE_SJIS_TWO_BYTE_1_P (s1) &&
3767       BYTE_SJIS_TWO_BYTE_2_P (s2))
3768     {
3769       DECODE_SJIS (s1, s2, c1, c2);
3770       return make_char (MAKE_CHAR (Vcharset_japanese_jisx0208,
3771                                    c1 & 0x7F, c2 & 0x7F));
3772     }
3773   else
3774     return Qnil;
3775 }
3776
3777 DEFUN ("encode-shift-jis-char", Fencode_shift_jis_char, 1, 1, 0, /*
3778 Encode a JISX0208 character CHARACTER to SHIFT-JIS coding-system.
3779 Return the corresponding character code in SHIFT-JIS as a cons of two bytes.
3780 */
3781        (character))
3782 {
3783   Lisp_Object charset;
3784   int c1, c2, s1, s2;
3785
3786   CHECK_CHAR_COERCE_INT (character);
3787   BREAKUP_CHAR (XCHAR (character), charset, c1, c2);
3788   if (EQ (charset, Vcharset_japanese_jisx0208))
3789     {
3790       ENCODE_SJIS (c1 | 0x80, c2 | 0x80, s1, s2);
3791       return Fcons (make_int (s1), make_int (s2));
3792     }
3793   else
3794     return Qnil;
3795 }
3796
3797 \f
3798 /************************************************************************/
3799 /*                            Big5 methods                              */
3800 /************************************************************************/
3801
3802 /* BIG5 is a coding system encoding two character sets: ASCII and
3803    Big5.  An ASCII character is encoded as is.  Big5 is a two-byte
3804    character set and is encoded in two-byte.
3805
3806    --- CODE RANGE of BIG5 ---
3807    (character set)      (range)
3808    ASCII                0x00 .. 0x7F
3809    Big5 (1st byte)      0xA1 .. 0xFE
3810         (2nd byte)      0x40 .. 0x7E and 0xA1 .. 0xFE
3811    --------------------------
3812
3813    Since the number of characters in Big5 is larger than maximum
3814    characters in Emacs' charset (96x96), it can't be handled as one
3815    charset.  So, in Emacs, Big5 is divided into two: `charset-big5-1'
3816    and `charset-big5-2'.  Both <type>s are DIMENSION2_CHARS94.  The former
3817    contains frequently used characters and the latter contains less
3818    frequently used characters.  */
3819
3820 #ifdef UTF2000
3821 #define BYTE_BIG5_TWO_BYTE_1_P(c) \
3822   ((c) >= 0x81 && (c) <= 0xFE)
3823 #else
3824 #define BYTE_BIG5_TWO_BYTE_1_P(c) \
3825   ((c) >= 0xA1 && (c) <= 0xFE)
3826 #endif
3827
3828 /* Is this the second byte of a Shift-JIS two-byte char? */
3829
3830 #define BYTE_BIG5_TWO_BYTE_2_P(c) \
3831   (((c) >= 0x40 && (c) <= 0x7E) || ((c) >= 0xA1 && (c) <= 0xFE))
3832
3833 /* Number of Big5 characters which have the same code in 1st byte.  */
3834
3835 #define BIG5_SAME_ROW (0xFF - 0xA1 + 0x7F - 0x40)
3836
3837 /* Code conversion macros.  These are macros because they are used in
3838    inner loops during code conversion.
3839
3840    Note that temporary variables in macros introduce the classic
3841    dynamic-scoping problems with variable names.  We use capital-
3842    lettered variables in the assumption that XEmacs does not use
3843    capital letters in variables except in a very formalized way
3844    (e.g. Qstring). */
3845
3846 /* Convert Big5 code (b1, b2) into its internal string representation
3847    (lb, c1, c2). */
3848
3849 /* There is a much simpler way to split the Big5 charset into two.
3850    For the moment I'm going to leave the algorithm as-is because it
3851    claims to separate out the most-used characters into a single
3852    charset, which perhaps will lead to optimizations in various
3853    places.
3854
3855    The way the algorithm works is something like this:
3856
3857    Big5 can be viewed as a 94x157 charset, where the row is
3858    encoded into the bytes 0xA1 .. 0xFE and the column is encoded
3859    into the bytes 0x40 .. 0x7E and 0xA1 .. 0xFE.  As for frequency,
3860    the split between low and high column numbers is apparently
3861    meaningless; ascending rows produce less and less frequent chars.
3862    Therefore, we assign the lower half of rows (0xA1 .. 0xC8) to
3863    the first charset, and the upper half (0xC9 .. 0xFE) to the
3864    second.  To do the conversion, we convert the character into
3865    a single number where 0 .. 156 is the first row, 157 .. 313
3866    is the second, etc.  That way, the characters are ordered by
3867    decreasing frequency.  Then we just chop the space in two
3868    and coerce the result into a 94x94 space.
3869    */
3870
3871 #define DECODE_BIG5(b1, b2, lb, c1, c2) do                              \
3872 {                                                                       \
3873   int B1 = b1, B2 = b2;                                                 \
3874   unsigned int I                                                        \
3875     = (B1 - 0xA1) * BIG5_SAME_ROW + B2 - (B2 < 0x7F ? 0x40 : 0x62);     \
3876                                                                         \
3877   if (B1 < 0xC9)                                                        \
3878     {                                                                   \
3879       lb = LEADING_BYTE_CHINESE_BIG5_1;                                 \
3880     }                                                                   \
3881   else                                                                  \
3882     {                                                                   \
3883       lb = LEADING_BYTE_CHINESE_BIG5_2;                                 \
3884       I -= (BIG5_SAME_ROW) * (0xC9 - 0xA1);                             \
3885     }                                                                   \
3886   c1 = I / (0xFF - 0xA1) + 0xA1;                                        \
3887   c2 = I % (0xFF - 0xA1) + 0xA1;                                        \
3888 } while (0)
3889
3890 /* Convert the internal string representation of a Big5 character
3891    (lb, c1, c2) into Big5 code (b1, b2). */
3892
3893 #define ENCODE_BIG5(lb, c1, c2, b1, b2) do                              \
3894 {                                                                       \
3895   unsigned int I = ((c1) - 0xA1) * (0xFF - 0xA1) + ((c2) - 0xA1);       \
3896                                                                         \
3897   if (lb == LEADING_BYTE_CHINESE_BIG5_2)                                \
3898     {                                                                   \
3899       I += BIG5_SAME_ROW * (0xC9 - 0xA1);                               \
3900     }                                                                   \
3901   b1 = I / BIG5_SAME_ROW + 0xA1;                                        \
3902   b2 = I % BIG5_SAME_ROW;                                               \
3903   b2 += b2 < 0x3F ? 0x40 : 0x62;                                        \
3904 } while (0)
3905
3906 static int
3907 detect_coding_big5 (struct detection_state *st, const Extbyte *src, Lstream_data_count n)
3908 {
3909   while (n--)
3910     {
3911       unsigned char c = *(unsigned char *)src++;
3912       if (c == ISO_CODE_ESC || c == ISO_CODE_SI || c == ISO_CODE_SO
3913 #ifndef UTF2000
3914           || (c >= 0x80 && c <= 0xA0)
3915 #endif
3916           )
3917         return 0;
3918       if (st->big5.in_second_byte)
3919         {
3920           st->big5.in_second_byte = 0;
3921           if (c < 0x40 || (c >= 0x80 && c <= 0xA0))
3922             return 0;
3923         }
3924       else if (
3925 #ifdef UTF2000
3926                c >= 0x81
3927 #else
3928                c >= 0xA1
3929 #endif
3930                )
3931         st->big5.in_second_byte = 1;
3932     }
3933   return CODING_CATEGORY_BIG5_MASK;
3934 }
3935
3936 /* Convert Big5 data to internal format. */
3937
3938 static void
3939 decode_coding_big5 (Lstream *decoding, const Extbyte *src,
3940                     unsigned_char_dynarr *dst, Lstream_data_count n)
3941 {
3942   struct decoding_stream *str = DECODING_STREAM_DATA (decoding);
3943   unsigned int flags  = str->flags;
3944   unsigned int cpos   = str->cpos;
3945   eol_type_t eol_type = str->eol_type;
3946 #ifdef UTF2000
3947   Lisp_Object ccs
3948     = CODING_SYSTEM_ISO2022_INITIAL_CHARSET (DECODING_STREAM_DATA
3949                                              (decoding)->codesys, 1);
3950 #endif
3951
3952   while (n--)
3953     {
3954       unsigned char c = *(unsigned char *)src++;
3955       if (cpos)
3956         {
3957           /* Previous character was first byte of Big5 char. */
3958           if (BYTE_BIG5_TWO_BYTE_2_P (c))
3959             {
3960 #ifdef UTF2000
3961               int code_point = (cpos << 8) | c;
3962               Emchar char_id = decode_defined_char (ccs, code_point, 0);
3963
3964               if (char_id < 0)
3965                 char_id
3966                   = DECODE_CHAR (Vcharset_chinese_big5, code_point, 0);
3967               DECODE_ADD_UCS_CHAR (char_id, dst);
3968 #else
3969               unsigned char b1, b2, b3;
3970               DECODE_BIG5 (cpos, c, b1, b2, b3);
3971               Dynarr_add (dst, b1);
3972               Dynarr_add (dst, b2);
3973               Dynarr_add (dst, b3);
3974 #endif
3975             }
3976           else
3977             {
3978               DECODE_ADD_BINARY_CHAR (cpos, dst);
3979               DECODE_ADD_BINARY_CHAR (c, dst);
3980             }
3981           cpos = 0;
3982         }
3983       else
3984         {
3985           DECODE_HANDLE_EOL_TYPE (eol_type, c, flags, dst);
3986           if (BYTE_BIG5_TWO_BYTE_1_P (c))
3987             {
3988               decode_flush_er_chars (str, dst);
3989               cpos = c;
3990             }
3991           else if ( c < ' ' )
3992             {
3993               decode_flush_er_chars (str, dst);
3994               DECODE_HANDLE_EOL_TYPE (eol_type, c, flags, dst);
3995               DECODE_ADD_BINARY_CHAR (c, dst);
3996             }
3997           else
3998             {
3999               /* DECODE_ADD_BINARY_CHAR (c, dst); */
4000               decode_add_er_char (str, c, dst);
4001             }
4002         }
4003     label_continue_loop:;
4004     }
4005
4006   /* DECODE_HANDLE_END_OF_CONVERSION (flags, cpos, dst); */
4007   if (flags & CODING_STATE_END)
4008     {
4009       decode_flush_er_chars (str, dst);
4010       DECODE_OUTPUT_PARTIAL_CHAR (cpos);
4011       if (flags & CODING_STATE_CR)
4012         Dynarr_add (dst, '\r');
4013     }
4014
4015   str->flags = flags;
4016   str->cpos  = cpos;
4017 }
4018
4019 /* Convert internally-formatted data to Big5. */
4020
4021 void
4022 char_encode_big5 (struct encoding_stream *str, Emchar ch,
4023                   unsigned_char_dynarr *dst, unsigned int *flags)
4024 {
4025   eol_type_t eol_type = CODING_SYSTEM_EOL_TYPE (str->codesys);
4026
4027   if (ch == '\n')
4028     {
4029       if (eol_type != EOL_LF && eol_type != EOL_AUTODETECT)
4030         Dynarr_add (dst, '\r');
4031       if (eol_type != EOL_CR)
4032         Dynarr_add (dst, ch);
4033     }
4034   else
4035     {
4036 #ifdef UTF2000
4037       int code_point;
4038       Lisp_Object ccs
4039         = CODING_SYSTEM_ISO2022_INITIAL_CHARSET (str->codesys, 1);
4040
4041       if ((code_point = charset_code_point (Vcharset_ascii, ch, 0)) >= 0)
4042         Dynarr_add (dst, code_point);
4043       else if ((code_point = charset_code_point (ccs, ch, 0)) >= 0)
4044         {
4045           Dynarr_add (dst, code_point >> 8);
4046           Dynarr_add (dst, code_point & 0xFF);
4047         }
4048       else if ((code_point
4049                 = charset_code_point (Vcharset_chinese_big5, ch, 0)) >= 0)
4050         {
4051           Dynarr_add (dst, code_point >> 8);
4052           Dynarr_add (dst, code_point & 0xFF);
4053         }
4054       else if ((code_point
4055                 = charset_code_point (Vcharset_chinese_big5_1, ch, 0)) >= 0)
4056         {
4057           unsigned int I
4058             = ((code_point >> 8) - 33) * (0xFF - 0xA1)
4059             + ((code_point & 0xFF) - 33);
4060           unsigned char b1 = I / BIG5_SAME_ROW + 0xA1;
4061           unsigned char b2 = I % BIG5_SAME_ROW;
4062
4063           b2 += b2 < 0x3F ? 0x40 : 0x62;
4064           Dynarr_add (dst, b1);
4065           Dynarr_add (dst, b2);
4066         }
4067       else if ((code_point
4068                 = charset_code_point (Vcharset_chinese_big5_2, ch, 0)) >= 0)
4069         {
4070           unsigned int I
4071             = ((code_point >> 8) - 33) * (0xFF - 0xA1)
4072             + ((code_point & 0xFF) - 33);
4073           unsigned char b1, b2;
4074
4075           I += BIG5_SAME_ROW * (0xC9 - 0xA1);
4076           b1 = I / BIG5_SAME_ROW + 0xA1;
4077           b2 = I % BIG5_SAME_ROW;
4078           b2 += b2 < 0x3F ? 0x40 : 0x62;
4079           Dynarr_add (dst, b1);
4080           Dynarr_add (dst, b2);
4081         }
4082       else if (CODING_SYSTEM_USE_ENTITY_REFERENCE (str->codesys))
4083         {
4084           char buf[18];
4085
4086           char_encode_as_entity_reference (ch, buf);
4087           Dynarr_add_many (dst, buf, strlen (buf));
4088         }
4089       else
4090         Dynarr_add (dst, '?');
4091 #else
4092 #endif
4093     }
4094 }
4095
4096 void
4097 char_finish_big5 (struct encoding_stream *str, unsigned_char_dynarr *dst,
4098                   unsigned int *flags)
4099 {
4100 }
4101
4102
4103 DEFUN ("decode-big5-char", Fdecode_big5_char, 1, 1, 0, /*
4104 Decode a Big5 character CODE of BIG5 coding-system.
4105 CODE is the character code in BIG5, a cons of two integers.
4106 Return the corresponding character.
4107 */
4108        (code))
4109 {
4110   unsigned char c1, c2, b1, b2;
4111
4112   CHECK_CONS (code);
4113   CHECK_INT (XCAR (code));
4114   CHECK_INT (XCDR (code));
4115   b1 = XINT (XCAR (code));
4116   b2 = XINT (XCDR (code));
4117   if (BYTE_BIG5_TWO_BYTE_1_P (b1) &&
4118       BYTE_BIG5_TWO_BYTE_2_P (b2))
4119     {
4120       Charset_ID leading_byte;
4121       Lisp_Object charset;
4122       DECODE_BIG5 (b1, b2, leading_byte, c1, c2);
4123       charset = CHARSET_BY_LEADING_BYTE (leading_byte);
4124       return make_char (MAKE_CHAR (charset, c1 & 0x7F, c2 & 0x7F));
4125     }
4126   else
4127     return Qnil;
4128 }
4129
4130 DEFUN ("encode-big5-char", Fencode_big5_char, 1, 1, 0, /*
4131 Encode the Big5 character CHARACTER in the BIG5 coding-system.
4132 Return the corresponding character code in Big5.
4133 */
4134        (character))
4135 {
4136   Lisp_Object charset;
4137   int c1, c2, b1, b2;
4138
4139   CHECK_CHAR_COERCE_INT (character);
4140   BREAKUP_CHAR (XCHAR (character), charset, c1, c2);
4141   if (EQ (charset, Vcharset_chinese_big5_1) ||
4142       EQ (charset, Vcharset_chinese_big5_2))
4143     {
4144       ENCODE_BIG5 (XCHARSET_LEADING_BYTE (charset), c1 | 0x80, c2 | 0x80,
4145                    b1, b2);
4146       return Fcons (make_int (b1), make_int (b2));
4147     }
4148   else
4149     return Qnil;
4150 }
4151
4152 \f
4153 /************************************************************************/
4154 /*                           UCS-4 methods                              */
4155 /************************************************************************/
4156
4157 static int
4158 detect_coding_ucs4 (struct detection_state *st, const Extbyte *src, Lstream_data_count n)
4159 {
4160   while (n--)
4161     {
4162       unsigned char c = *(unsigned char *)src++;
4163       switch (st->ucs4.in_byte)
4164         {
4165         case 0:
4166           if (c >= 128)
4167             return 0;
4168           else
4169             st->ucs4.in_byte++;
4170           break;
4171         case 3:
4172           st->ucs4.in_byte = 0;
4173           break;
4174         default:
4175           st->ucs4.in_byte++;
4176         }
4177     }
4178   return CODING_CATEGORY_UCS4_MASK;
4179 }
4180
4181 static void
4182 decode_coding_ucs4 (Lstream *decoding, const Extbyte *src,
4183                     unsigned_char_dynarr *dst, Lstream_data_count n)
4184 {
4185   struct decoding_stream *str = DECODING_STREAM_DATA (decoding);
4186   unsigned int flags = str->flags;
4187   unsigned int cpos  = str->cpos;
4188   unsigned char counter = str->counter;
4189
4190   while (n--)
4191     {
4192       unsigned char c = *(unsigned char *)src++;
4193       switch (counter)
4194         {
4195         case 0:
4196           cpos = c;
4197           counter = 3;
4198           break;
4199         case 1:
4200           DECODE_ADD_UCS_CHAR ((cpos << 8) | c, dst);
4201           cpos = 0;
4202           counter = 0;
4203           break;
4204         default:
4205           cpos = ( cpos << 8 ) | c;
4206           counter--;
4207         }
4208     }
4209   if (counter & CODING_STATE_END)
4210     DECODE_OUTPUT_PARTIAL_CHAR (cpos);
4211
4212   str->flags    = flags;
4213   str->cpos     = cpos;
4214   str->counter  = counter;
4215 }
4216
4217 void
4218 char_encode_ucs4 (struct encoding_stream *str, Emchar ch,
4219                   unsigned_char_dynarr *dst, unsigned int *flags)
4220 {
4221   Dynarr_add (dst, ch >> 24);
4222   Dynarr_add (dst, ch >> 16);
4223   Dynarr_add (dst, ch >>  8);
4224   Dynarr_add (dst, ch      );
4225 }
4226
4227 void
4228 char_finish_ucs4 (struct encoding_stream *str, unsigned_char_dynarr *dst,
4229                   unsigned int *flags)
4230 {
4231 }
4232
4233 \f
4234 /************************************************************************/
4235 /*                           UTF-16 methods                             */
4236 /************************************************************************/
4237
4238 static int
4239 detect_coding_utf16 (struct detection_state *st, const Extbyte *src, Lstream_data_count n)
4240 {
4241   return CODING_CATEGORY_UTF16_MASK;
4242 }
4243
4244 static void
4245 decode_coding_utf16 (Lstream *decoding, const Extbyte *src,
4246                     unsigned_char_dynarr *dst, Lstream_data_count n)
4247 {
4248   struct decoding_stream *str = DECODING_STREAM_DATA (decoding);
4249   unsigned int flags = str->flags;
4250   unsigned int cpos  = str->cpos;
4251   unsigned char counter = str->counter & 3;
4252   unsigned char byte_order = str->counter >> 2;
4253   eol_type_t eol_type = str->eol_type;
4254
4255   while (n--)
4256     {
4257       unsigned char c = *(unsigned char *)src++;
4258       if (counter == 0)
4259         {
4260           cpos = c;
4261           counter = 1;
4262         }
4263       else if (counter == 1)
4264         {
4265           int code;
4266
4267           if (byte_order == 0)
4268             code = (c << 8) | cpos;
4269           else
4270             code = (cpos << 8) | c;
4271           if (code == 0xFFFE)
4272             {
4273               code = ((code & 0xFF) << 8) | (code >> 8);
4274               if ( byte_order == 0 )
4275                 byte_order = 1;
4276               else
4277                 byte_order = 0;
4278             }
4279           if ( (0xD800 <= code) && (code <= 0xDBFF) )
4280             {
4281               counter = 2;
4282               cpos = code;
4283             }
4284           else
4285             {
4286               counter = 0;
4287               cpos = 0;
4288               if (code != 0xFEFF)
4289                 {
4290                   DECODE_HANDLE_EOL_TYPE (eol_type, code, flags, dst);
4291                   DECODE_ADD_UCS_CHAR (code, dst);
4292                 }
4293             }
4294         }
4295       else if (counter == 2)
4296         {
4297           cpos = (cpos << 8) | c;
4298           counter++;
4299         }
4300       else
4301         {
4302           int x = cpos >> 8;
4303           int y
4304             = (byte_order == 0)
4305             ? (c << 8) | (cpos & 0xFF)
4306             : ((cpos & 0xFF) << 8) | c;
4307
4308           DECODE_ADD_UCS_CHAR ((x - 0xD800) * 0x400 + (y - 0xDC00)
4309                                + 0x10000, dst);
4310           counter = 0;
4311           cpos = 0;
4312         }
4313     label_continue_loop:;
4314     }
4315   if (counter & CODING_STATE_END)
4316     DECODE_OUTPUT_PARTIAL_CHAR (cpos);
4317
4318   str->flags    = flags;
4319   str->cpos     = cpos;
4320   str->counter  = (byte_order << 2) | counter;
4321 }
4322
4323 void
4324 char_encode_utf16 (struct encoding_stream *str, Emchar ch,
4325                   unsigned_char_dynarr *dst, unsigned int *flags)
4326 {
4327   if (ch <= 0xFFFF)
4328     {
4329       Dynarr_add (dst, ch);
4330       Dynarr_add (dst, ch >> 8);
4331     }
4332   else
4333     {
4334       int y = ((ch - 0x10000) / 0x400) + 0xD800;
4335       int z = ((ch - 0x10000) % 0x400) + 0xDC00;
4336       
4337       Dynarr_add (dst, y);
4338       Dynarr_add (dst, y >> 8);
4339       Dynarr_add (dst, z);
4340       Dynarr_add (dst, z >> 8);
4341     }
4342 }
4343
4344 void
4345 char_finish_utf16 (struct encoding_stream *str, unsigned_char_dynarr *dst,
4346                   unsigned int *flags)
4347 {
4348 }
4349
4350 \f
4351 /************************************************************************/
4352 /*                           UTF-8 methods                              */
4353 /************************************************************************/
4354
4355 static int
4356 detect_coding_utf8 (struct detection_state *st, const Extbyte *src, Lstream_data_count n)
4357 {
4358   while (n--)
4359     {
4360       unsigned char c = *(unsigned char *)src++;
4361       switch (st->utf8.in_byte)
4362         {
4363         case 0:
4364           if (c == ISO_CODE_ESC || c == ISO_CODE_SI || c == ISO_CODE_SO)
4365             return 0;
4366           else if (c >= 0xfc)
4367             st->utf8.in_byte = 5;
4368           else if (c >= 0xf8)
4369             st->utf8.in_byte = 4;
4370           else if (c >= 0xf0)
4371             st->utf8.in_byte = 3;
4372           else if (c >= 0xe0)
4373             st->utf8.in_byte = 2;
4374           else if (c >= 0xc0)
4375             st->utf8.in_byte = 1;
4376           else if (c >= 0x80)
4377             return 0;
4378           break;
4379         default:
4380           if ((c & 0xc0) != 0x80)
4381             return 0;
4382           else
4383             st->utf8.in_byte--;
4384         }
4385     }
4386   return CODING_CATEGORY_UTF8_MASK;
4387 }
4388
4389 static void
4390 decode_output_utf8_partial_char (unsigned char counter,
4391                                  unsigned int cpos,
4392                                  unsigned_char_dynarr *dst)
4393 {
4394   if (counter == 5)
4395     DECODE_ADD_BINARY_CHAR ( (cpos|0xFC), dst);
4396   else if (counter == 4)
4397     {
4398       if (cpos < (1 << 6))
4399         DECODE_ADD_BINARY_CHAR ( (cpos|0xF8), dst);
4400       else
4401         {
4402           DECODE_ADD_BINARY_CHAR ( ((cpos >> 6)|0xFC), dst);
4403           DECODE_ADD_BINARY_CHAR ( ((cpos&0x3F)|0x80), dst);
4404         }
4405     }
4406   else if (counter == 3)
4407     {
4408       if (cpos < (1 << 6))
4409         DECODE_ADD_BINARY_CHAR ( (cpos|0xF0), dst);
4410       else if (cpos < (1 << 12))
4411         {
4412           DECODE_ADD_BINARY_CHAR ( ((cpos >> 6)|0xF8), dst);
4413           DECODE_ADD_BINARY_CHAR ( ((cpos&0x3F)|0x80), dst);
4414         }
4415       else
4416         {
4417           DECODE_ADD_BINARY_CHAR ( ( (cpos >> 12)|0xFC), dst);
4418           DECODE_ADD_BINARY_CHAR ( (((cpos >>  6)&0x3F)|0x80), dst);
4419           DECODE_ADD_BINARY_CHAR ( ( (cpos       &0x3F)|0x80), dst);
4420         }
4421     }
4422   else if (counter == 2)
4423     {
4424       if (cpos < (1 << 6))
4425         DECODE_ADD_BINARY_CHAR ( (cpos|0xE0), dst);
4426       else if (cpos < (1 << 12))
4427         {
4428           DECODE_ADD_BINARY_CHAR ( ((cpos >> 6)|0xF0), dst);
4429           DECODE_ADD_BINARY_CHAR ( ((cpos&0x3F)|0x80), dst);
4430         }
4431       else if (cpos < (1 << 18))
4432         {
4433           DECODE_ADD_BINARY_CHAR ( ( (cpos >> 12)|0xF8), dst);
4434           DECODE_ADD_BINARY_CHAR ( (((cpos >> 6)&0x3F)|0x80), dst);
4435           DECODE_ADD_BINARY_CHAR ( ( (cpos      &0x3F)|0x80), dst);
4436         }
4437       else
4438         {
4439           DECODE_ADD_BINARY_CHAR ( ( (cpos >> 18)|0xFC), dst);
4440           DECODE_ADD_BINARY_CHAR ( (((cpos >> 12)&0x3F)|0x80), dst);
4441           DECODE_ADD_BINARY_CHAR ( (((cpos >>  6)&0x3F)|0x80), dst);
4442           DECODE_ADD_BINARY_CHAR ( ( (cpos       &0x3F)|0x80), dst);
4443         }
4444     }
4445   else
4446     {
4447       if (cpos < (1 << 6))
4448         DECODE_ADD_BINARY_CHAR ( (cpos|0xC0), dst);
4449       else if (cpos < (1 << 12))
4450         {
4451           DECODE_ADD_BINARY_CHAR ( ((cpos >> 6)|0xE0), dst);
4452           DECODE_ADD_BINARY_CHAR ( ((cpos&0x3F)|0x80), dst);
4453         }
4454       else if (cpos < (1 << 18))
4455         {
4456           DECODE_ADD_BINARY_CHAR ( ( (cpos >> 12)|0xF0), dst);
4457           DECODE_ADD_BINARY_CHAR ( (((cpos >>  6)&0x3F)|0x80), dst);
4458           DECODE_ADD_BINARY_CHAR ( ( (cpos       &0x3F)|0x80), dst);
4459         }
4460       else if (cpos < (1 << 24))
4461         {
4462           DECODE_ADD_BINARY_CHAR ( ( (cpos >> 18)|0xF8), dst);
4463           DECODE_ADD_BINARY_CHAR ( (((cpos >> 12)&0x3F)|0x80), dst);
4464           DECODE_ADD_BINARY_CHAR ( (((cpos >>  6)&0x3F)|0x80), dst);
4465           DECODE_ADD_BINARY_CHAR ( ( (cpos       &0x3F)|0x80), dst);
4466         }
4467       else
4468         {
4469           DECODE_ADD_BINARY_CHAR ( ( (cpos >> 24)|0xFC), dst);
4470           DECODE_ADD_BINARY_CHAR ( (((cpos >> 18)&0x3F)|0x80), dst);
4471           DECODE_ADD_BINARY_CHAR ( (((cpos >> 12)&0x3F)|0x80), dst);
4472           DECODE_ADD_BINARY_CHAR ( (((cpos >>  6)&0x3F)|0x80), dst);
4473           DECODE_ADD_BINARY_CHAR ( ( (cpos       &0x3F)|0x80), dst);
4474         }
4475     }
4476 }
4477
4478 static void
4479 decode_coding_utf8 (Lstream *decoding, const Extbyte *src,
4480                     unsigned_char_dynarr *dst, Lstream_data_count n)
4481 {
4482   struct decoding_stream *str = DECODING_STREAM_DATA (decoding);
4483   unsigned int flags    = str->flags;
4484   unsigned int cpos     = str->cpos;
4485   eol_type_t eol_type   = str->eol_type;
4486   unsigned char counter = str->counter;
4487 #ifdef UTF2000
4488   Lisp_Object ccs
4489     = CODING_SYSTEM_ISO2022_INITIAL_CHARSET (DECODING_STREAM_DATA
4490                                              (decoding)->codesys, 0);
4491 #endif
4492
4493   while (n--)
4494     {
4495       unsigned char c = *(unsigned char *)src++;
4496       if (counter == 0)
4497         {
4498           if ( c < ' ' )
4499             {
4500               COMPOSE_FLUSH_CHARS (str, dst);
4501               decode_flush_er_chars (str, dst);
4502               DECODE_HANDLE_EOL_TYPE (eol_type, c, flags, dst);
4503               DECODE_ADD_UCS_CHAR (c, dst);
4504             }
4505           else if ( c < 0xC0 )
4506             /* decode_add_er_char (str, c, dst); */
4507             COMPOSE_ADD_CHAR (str, c, dst);
4508           else
4509             {
4510               /* decode_flush_er_chars (str, dst); */
4511               if ( c < 0xE0 )
4512                 {
4513                   cpos = c & 0x1f;
4514                   counter = 1;
4515                 }
4516               else if ( c < 0xF0 )
4517                 {
4518                   cpos = c & 0x0f;
4519                   counter = 2;
4520                 }
4521               else if ( c < 0xF8 )
4522                 {
4523                   cpos = c & 0x07;
4524                   counter = 3;
4525                 }
4526               else if ( c < 0xFC )
4527                 {
4528                   cpos = c & 0x03;
4529                   counter = 4;
4530                 }
4531               else
4532                 {
4533                   cpos = c & 0x01;
4534                   counter = 5;
4535                 }
4536             }
4537         }
4538       else if ( (c & 0xC0) == 0x80 )
4539         {
4540           cpos = ( cpos << 6 ) | ( c & 0x3f );
4541           if (counter == 1)
4542             {
4543               Emchar char_id;
4544
4545               if (!NILP (ccs))
4546                 {
4547                   char_id = decode_defined_char (ccs, cpos, 0);
4548
4549                   if (char_id < 0)
4550                     char_id = cpos;
4551                 }
4552               else
4553                 char_id = cpos;
4554               COMPOSE_ADD_CHAR (str, char_id, dst);
4555               cpos = 0;
4556               counter = 0;
4557             }
4558           else
4559             counter--;
4560         }
4561       else
4562         {
4563           COMPOSE_FLUSH_CHARS (str, dst);
4564           decode_flush_er_chars (str, dst);
4565           decode_output_utf8_partial_char (counter, cpos, dst);
4566           DECODE_ADD_BINARY_CHAR (c, dst);
4567           cpos = 0;
4568           counter = 0;
4569         }
4570     label_continue_loop:;
4571     }
4572
4573   if (flags & CODING_STATE_END)
4574     {
4575       COMPOSE_FLUSH_CHARS (str, dst);
4576       decode_flush_er_chars (str, dst);
4577       if (counter > 0)
4578         {
4579           decode_output_utf8_partial_char (counter, cpos, dst);
4580           cpos = 0;
4581           counter = 0;
4582         }
4583     }
4584   str->flags    = flags;
4585   str->cpos     = cpos;
4586   str->counter  = counter;
4587 }
4588
4589 void
4590 char_encode_utf8 (struct encoding_stream *str, Emchar ch,
4591                   unsigned_char_dynarr *dst, unsigned int *flags)
4592 {
4593   eol_type_t eol_type = CODING_SYSTEM_EOL_TYPE (str->codesys);
4594
4595   if (ch == '\n')
4596     {
4597       if (eol_type != EOL_LF && eol_type != EOL_AUTODETECT)
4598         Dynarr_add (dst, '\r');
4599       if (eol_type != EOL_CR)
4600         Dynarr_add (dst, ch);
4601     }
4602   else if (ch <= 0x7f)
4603     {
4604       Dynarr_add (dst, ch);
4605     }
4606   else
4607     {
4608       Lisp_Object ucs_ccs
4609         = CODING_SYSTEM_ISO2022_INITIAL_CHARSET (str->codesys, 0);
4610       int code_point = charset_code_point (ucs_ccs, ch, 0);
4611
4612       if ( (code_point < 0) || (code_point > 0x10FFFF) )
4613         {
4614           Lisp_Object map
4615             = CODING_SYSTEM_ISO2022_INITIAL_CHARSET (str->codesys, 1);
4616           Lisp_Object ret;
4617
4618           if ( !NILP (map)
4619                && INTP (ret = Fchar_feature (make_char (ch),
4620                                              map, Qnil,
4621                                              Qnil, Qnil)) )
4622             code_point = XINT (ret);
4623           else if ( !NILP (map =
4624                            CODING_SYSTEM_ISO2022_INITIAL_CHARSET
4625                            (str->codesys, 2))
4626                     && INTP (ret = Fchar_feature (make_char (ch),
4627                                                   map, Qnil,
4628                                                   Qnil, Qnil)) )
4629             code_point = XINT (ret);
4630           else if (CODING_SYSTEM_USE_ENTITY_REFERENCE (str->codesys))
4631             {
4632               char buf[18];
4633
4634               char_encode_as_entity_reference (ch, buf);
4635               Dynarr_add_many (dst, buf, strlen (buf));
4636               return;
4637             }
4638           else
4639             code_point = ch;
4640         }
4641       if (code_point <= 0x7ff)
4642         {
4643           Dynarr_add (dst, (code_point >> 6) | 0xc0);
4644           Dynarr_add (dst, (code_point & 0x3f) | 0x80);
4645         }
4646       else if (code_point <= 0xffff)
4647         {
4648           Dynarr_add (dst,  (code_point >> 12) | 0xe0);
4649           Dynarr_add (dst, ((code_point >>  6) & 0x3f) | 0x80);
4650           Dynarr_add (dst,  (code_point        & 0x3f) | 0x80);
4651         }
4652       else if (code_point <= 0x1fffff)
4653         {
4654           Dynarr_add (dst,  (code_point >> 18) | 0xf0);
4655           Dynarr_add (dst, ((code_point >> 12) & 0x3f) | 0x80);
4656           Dynarr_add (dst, ((code_point >>  6) & 0x3f) | 0x80);
4657           Dynarr_add (dst,  (code_point        & 0x3f) | 0x80);
4658         }
4659       else if (code_point <= 0x3ffffff)
4660         {
4661           Dynarr_add (dst,  (code_point >> 24) | 0xf8);
4662           Dynarr_add (dst, ((code_point >> 18) & 0x3f) | 0x80);
4663           Dynarr_add (dst, ((code_point >> 12) & 0x3f) | 0x80);
4664           Dynarr_add (dst, ((code_point >>  6) & 0x3f) | 0x80);
4665           Dynarr_add (dst,  (code_point        & 0x3f) | 0x80);
4666         }
4667       else
4668         {
4669           Dynarr_add (dst,  (code_point >> 30) | 0xfc);
4670           Dynarr_add (dst, ((code_point >> 24) & 0x3f) | 0x80);
4671           Dynarr_add (dst, ((code_point >> 18) & 0x3f) | 0x80);
4672           Dynarr_add (dst, ((code_point >> 12) & 0x3f) | 0x80);
4673           Dynarr_add (dst, ((code_point >>  6) & 0x3f) | 0x80);
4674           Dynarr_add (dst,  (code_point        & 0x3f) | 0x80);
4675         }
4676     }
4677 }
4678
4679 void
4680 char_finish_utf8 (struct encoding_stream *str, unsigned_char_dynarr *dst,
4681                   unsigned int *flags)
4682 {
4683 }
4684
4685 \f
4686 /************************************************************************/
4687 /*                           ISO2022 methods                            */
4688 /************************************************************************/
4689
4690 /* The following note describes the coding system ISO2022 briefly.
4691    Since the intention of this note is to help understand the
4692    functions in this file, some parts are NOT ACCURATE or OVERLY
4693    SIMPLIFIED.  For thorough understanding, please refer to the
4694    original document of ISO2022.
4695
4696    ISO2022 provides many mechanisms to encode several character sets
4697    in 7-bit and 8-bit environments.  For 7-bit environments, all text
4698    is encoded using bytes less than 128.  This may make the encoded
4699    text a little bit longer, but the text passes more easily through
4700    several gateways, some of which strip off MSB (Most Signigant Bit).
4701
4702    There are two kinds of character sets: control character set and
4703    graphic character set.  The former contains control characters such
4704    as `newline' and `escape' to provide control functions (control
4705    functions are also provided by escape sequences).  The latter
4706    contains graphic characters such as 'A' and '-'.  Emacs recognizes
4707    two control character sets and many graphic character sets.
4708
4709    Graphic character sets are classified into one of the following
4710    four classes, according to the number of bytes (DIMENSION) and
4711    number of characters in one dimension (CHARS) of the set:
4712    - DIMENSION1_CHARS94
4713    - DIMENSION1_CHARS96
4714    - DIMENSION2_CHARS94
4715    - DIMENSION2_CHARS96
4716
4717    In addition, each character set is assigned an identification tag,
4718    unique for each set, called "final character" (denoted as <F>
4719    hereafter).  The <F> of each character set is decided by ECMA(*)
4720    when it is registered in ISO.  The code range of <F> is 0x30..0x7F
4721    (0x30..0x3F are for private use only).
4722
4723    Note (*): ECMA = European Computer Manufacturers Association
4724
4725    Here are examples of graphic character set [NAME(<F>)]:
4726         o DIMENSION1_CHARS94 -- ASCII('B'), right-half-of-JISX0201('I'), ...
4727         o DIMENSION1_CHARS96 -- right-half-of-ISO8859-1('A'), ...
4728         o DIMENSION2_CHARS94 -- GB2312('A'), JISX0208('B'), ...
4729         o DIMENSION2_CHARS96 -- none for the moment
4730
4731    A code area (1 byte = 8 bits) is divided into 4 areas, C0, GL, C1, and GR.
4732         C0 [0x00..0x1F] -- control character plane 0
4733         GL [0x20..0x7F] -- graphic character plane 0
4734         C1 [0x80..0x9F] -- control character plane 1
4735         GR [0xA0..0xFF] -- graphic character plane 1
4736
4737    A control character set is directly designated and invoked to C0 or
4738    C1 by an escape sequence.  The most common case is that:
4739    - ISO646's  control character set is designated/invoked to C0, and
4740    - ISO6429's control character set is designated/invoked to C1,
4741    and usually these designations/invocations are omitted in encoded
4742    text.  In a 7-bit environment, only C0 can be used, and a control
4743    character for C1 is encoded by an appropriate escape sequence to
4744    fit into the environment.  All control characters for C1 are
4745    defined to have corresponding escape sequences.
4746
4747    A graphic character set is at first designated to one of four
4748    graphic registers (G0 through G3), then these graphic registers are
4749    invoked to GL or GR.  These designations and invocations can be
4750    done independently.  The most common case is that G0 is invoked to
4751    GL, G1 is invoked to GR, and ASCII is designated to G0.  Usually
4752    these invocations and designations are omitted in encoded text.
4753    In a 7-bit environment, only GL can be used.
4754
4755    When a graphic character set of CHARS94 is invoked to GL, codes
4756    0x20 and 0x7F of the GL area work as control characters SPACE and
4757    DEL respectively, and codes 0xA0 and 0xFF of the GR area should not
4758    be used.
4759
4760    There are two ways of invocation: locking-shift and single-shift.
4761    With locking-shift, the invocation lasts until the next different
4762    invocation, whereas with single-shift, the invocation affects the
4763    following character only and doesn't affect the locking-shift
4764    state.  Invocations are done by the following control characters or
4765    escape sequences:
4766
4767    ----------------------------------------------------------------------
4768    abbrev  function                  cntrl escape seq   description
4769    ----------------------------------------------------------------------
4770    SI/LS0  (shift-in)                0x0F  none         invoke G0 into GL
4771    SO/LS1  (shift-out)               0x0E  none         invoke G1 into GL
4772    LS2     (locking-shift-2)         none  ESC 'n'      invoke G2 into GL
4773    LS3     (locking-shift-3)         none  ESC 'o'      invoke G3 into GL
4774    LS1R    (locking-shift-1 right)   none  ESC '~'      invoke G1 into GR (*)
4775    LS2R    (locking-shift-2 right)   none  ESC '}'      invoke G2 into GR (*)
4776    LS3R    (locking-shift 3 right)   none  ESC '|'      invoke G3 into GR (*)
4777    SS2     (single-shift-2)          0x8E  ESC 'N'      invoke G2 for one char
4778    SS3     (single-shift-3)          0x8F  ESC 'O'      invoke G3 for one char
4779    ----------------------------------------------------------------------
4780    (*) These are not used by any known coding system.
4781
4782    Control characters for these functions are defined by macros
4783    ISO_CODE_XXX in `coding.h'.
4784
4785    Designations are done by the following escape sequences:
4786    ----------------------------------------------------------------------
4787    escape sequence      description
4788    ----------------------------------------------------------------------
4789    ESC '(' <F>          designate DIMENSION1_CHARS94<F> to G0
4790    ESC ')' <F>          designate DIMENSION1_CHARS94<F> to G1
4791    ESC '*' <F>          designate DIMENSION1_CHARS94<F> to G2
4792    ESC '+' <F>          designate DIMENSION1_CHARS94<F> to G3
4793    ESC ',' <F>          designate DIMENSION1_CHARS96<F> to G0 (*)
4794    ESC '-' <F>          designate DIMENSION1_CHARS96<F> to G1
4795    ESC '.' <F>          designate DIMENSION1_CHARS96<F> to G2
4796    ESC '/' <F>          designate DIMENSION1_CHARS96<F> to G3
4797    ESC '$' '(' <F>      designate DIMENSION2_CHARS94<F> to G0 (**)
4798    ESC '$' ')' <F>      designate DIMENSION2_CHARS94<F> to G1
4799    ESC '$' '*' <F>      designate DIMENSION2_CHARS94<F> to G2
4800    ESC '$' '+' <F>      designate DIMENSION2_CHARS94<F> to G3
4801    ESC '$' ',' <F>      designate DIMENSION2_CHARS96<F> to G0 (*)
4802    ESC '$' '-' <F>      designate DIMENSION2_CHARS96<F> to G1
4803    ESC '$' '.' <F>      designate DIMENSION2_CHARS96<F> to G2
4804    ESC '$' '/' <F>      designate DIMENSION2_CHARS96<F> to G3
4805    ----------------------------------------------------------------------
4806
4807    In this list, "DIMENSION1_CHARS94<F>" means a graphic character set
4808    of dimension 1, chars 94, and final character <F>, etc...
4809
4810    Note (*): Although these designations are not allowed in ISO2022,
4811    Emacs accepts them on decoding, and produces them on encoding
4812    CHARS96 character sets in a coding system which is characterized as
4813    7-bit environment, non-locking-shift, and non-single-shift.
4814
4815    Note (**): If <F> is '@', 'A', or 'B', the intermediate character
4816    '(' can be omitted.  We refer to this as "short-form" hereafter.
4817
4818    Now you may notice that there are a lot of ways for encoding the
4819    same multilingual text in ISO2022.  Actually, there exist many
4820    coding systems such as Compound Text (used in X11's inter client
4821    communication, ISO-2022-JP (used in Japanese internet), ISO-2022-KR
4822    (used in Korean internet), EUC (Extended UNIX Code, used in Asian
4823    localized platforms), and all of these are variants of ISO2022.
4824
4825    In addition to the above, Emacs handles two more kinds of escape
4826    sequences: ISO6429's direction specification and Emacs' private
4827    sequence for specifying character composition.
4828
4829    ISO6429's direction specification takes the following form:
4830         o CSI ']'      -- end of the current direction
4831         o CSI '0' ']'  -- end of the current direction
4832         o CSI '1' ']'  -- start of left-to-right text
4833         o CSI '2' ']'  -- start of right-to-left text
4834    The control character CSI (0x9B: control sequence introducer) is
4835    abbreviated to the escape sequence ESC '[' in a 7-bit environment.
4836
4837    Character composition specification takes the following form:
4838         o ESC '0' -- start character composition
4839         o ESC '1' -- end character composition
4840    Since these are not standard escape sequences of any ISO standard,
4841    their use with these meanings is restricted to Emacs only.  */
4842
4843 static void
4844 reset_iso2022 (Lisp_Object coding_system, struct iso2022_decoder *iso)
4845 {
4846   int i;
4847
4848   for (i = 0; i < 4; i++)
4849     {
4850       if (!NILP (coding_system))
4851         iso->charset[i] =
4852           XCODING_SYSTEM_ISO2022_INITIAL_CHARSET (coding_system, i);
4853       else
4854         iso->charset[i] = Qt;
4855       iso->invalid_designated[i] = 0;
4856     }
4857   iso->esc = ISO_ESC_NOTHING;
4858   iso->esc_bytes_index = 0;
4859   iso->register_left = 0;
4860   iso->register_right = 1;
4861   iso->switched_dir_and_no_valid_charset_yet = 0;
4862   iso->invalid_switch_dir = 0;
4863   iso->output_direction_sequence = 0;
4864   iso->output_literally = 0;
4865 #ifdef ENABLE_COMPOSITE_CHARS
4866   if (iso->composite_chars)
4867     Dynarr_reset (iso->composite_chars);
4868 #endif
4869 }
4870
4871 static int
4872 fit_to_be_escape_quoted (unsigned char c)
4873 {
4874   switch (c)
4875     {
4876     case ISO_CODE_ESC:
4877     case ISO_CODE_CSI:
4878     case ISO_CODE_SS2:
4879     case ISO_CODE_SS3:
4880     case ISO_CODE_SO:
4881     case ISO_CODE_SI:
4882       return 1;
4883
4884     default:
4885       return 0;
4886     }
4887 }
4888
4889 /* Parse one byte of an ISO2022 escape sequence.
4890    If the result is an invalid escape sequence, return 0 and
4891    do not change anything in STR.  Otherwise, if the result is
4892    an incomplete escape sequence, update ISO2022.ESC and
4893    ISO2022.ESC_BYTES and return -1.  Otherwise, update
4894    all the state variables (but not ISO2022.ESC_BYTES) and
4895    return 1.
4896
4897    If CHECK_INVALID_CHARSETS is non-zero, check for designation
4898    or invocation of an invalid character set and treat that as
4899    an unrecognized escape sequence. */
4900
4901 static int
4902 parse_iso2022_esc (Lisp_Object codesys, struct iso2022_decoder *iso,
4903                    unsigned char c, unsigned int *flags,
4904                    int check_invalid_charsets)
4905 {
4906   /* (1) If we're at the end of a designation sequence, CS is the
4907      charset being designated and REG is the register to designate
4908      it to.
4909
4910      (2) If we're at the end of a locking-shift sequence, REG is
4911      the register to invoke and HALF (0 == left, 1 == right) is
4912      the half to invoke it into.
4913
4914      (3) If we're at the end of a single-shift sequence, REG is
4915      the register to invoke. */
4916   Lisp_Object cs = Qnil;
4917   int reg, half;
4918
4919   /* NOTE: This code does goto's all over the fucking place.
4920      The reason for this is that we're basically implementing
4921      a state machine here, and hierarchical languages like C
4922      don't really provide a clean way of doing this. */
4923
4924   if (! (*flags & CODING_STATE_ESCAPE))
4925     /* At beginning of escape sequence; we need to reset our
4926        escape-state variables. */
4927     iso->esc = ISO_ESC_NOTHING;
4928
4929   iso->output_literally = 0;
4930   iso->output_direction_sequence = 0;
4931
4932   switch (iso->esc)
4933     {
4934     case ISO_ESC_NOTHING:
4935       iso->esc_bytes_index = 0;
4936       switch (c)
4937         {
4938         case ISO_CODE_ESC:      /* Start escape sequence */
4939           *flags |= CODING_STATE_ESCAPE;
4940           iso->esc = ISO_ESC;
4941           goto not_done;
4942
4943         case ISO_CODE_CSI:      /* ISO6429 (specifying directionality) */
4944           *flags |= CODING_STATE_ESCAPE;
4945           iso->esc = ISO_ESC_5_11;
4946           goto not_done;
4947
4948         case ISO_CODE_SO:       /* locking shift 1 */
4949           reg = 1; half = 0;
4950           goto locking_shift;
4951         case ISO_CODE_SI:       /* locking shift 0 */
4952           reg = 0; half = 0;
4953           goto locking_shift;
4954
4955         case ISO_CODE_SS2:      /* single shift */
4956           reg = 2;
4957           goto single_shift;
4958         case ISO_CODE_SS3:      /* single shift */
4959           reg = 3;
4960           goto single_shift;
4961
4962         default:                        /* Other control characters */
4963           return 0;
4964         }
4965
4966     case ISO_ESC:
4967       switch (c)
4968         {
4969           /**** single shift ****/
4970
4971         case 'N':       /* single shift 2 */
4972           reg = 2;
4973           goto single_shift;
4974         case 'O':       /* single shift 3 */
4975           reg = 3;
4976           goto single_shift;
4977
4978           /**** locking shift ****/
4979
4980         case '~':       /* locking shift 1 right */
4981           reg = 1; half = 1;
4982           goto locking_shift;
4983         case 'n':       /* locking shift 2 */
4984           reg = 2; half = 0;
4985           goto locking_shift;
4986         case '}':       /* locking shift 2 right */
4987           reg = 2; half = 1;
4988           goto locking_shift;
4989         case 'o':       /* locking shift 3 */
4990           reg = 3; half = 0;
4991           goto locking_shift;
4992         case '|':       /* locking shift 3 right */
4993           reg = 3; half = 1;
4994           goto locking_shift;
4995
4996 #ifdef ENABLE_COMPOSITE_CHARS
4997           /**** composite ****/
4998
4999         case '0':
5000           iso->esc = ISO_ESC_START_COMPOSITE;
5001           *flags = (*flags & CODING_STATE_ISO2022_LOCK) |
5002             CODING_STATE_COMPOSITE;
5003           return 1;
5004
5005         case '1':
5006           iso->esc = ISO_ESC_END_COMPOSITE;
5007           *flags = (*flags & CODING_STATE_ISO2022_LOCK) &
5008             ~CODING_STATE_COMPOSITE;
5009           return 1;
5010 #endif /* ENABLE_COMPOSITE_CHARS */
5011
5012           /**** directionality ****/
5013
5014         case '[':
5015           iso->esc = ISO_ESC_5_11;
5016           goto not_done;
5017
5018           /**** designation ****/
5019
5020         case '$':       /* multibyte charset prefix */
5021           iso->esc = ISO_ESC_2_4;
5022           goto not_done;
5023
5024         default:
5025           if (0x28 <= c && c <= 0x2F)
5026             {
5027               iso->esc = (enum iso_esc_flag) (c - 0x28 + ISO_ESC_2_8);
5028               goto not_done;
5029             }
5030
5031           /* This function is called with CODESYS equal to nil when
5032              doing coding-system detection. */
5033           if (!NILP (codesys)
5034               && XCODING_SYSTEM_ISO2022_ESCAPE_QUOTED (codesys)
5035               && fit_to_be_escape_quoted (c))
5036             {
5037               iso->esc = ISO_ESC_LITERAL;
5038               *flags &= CODING_STATE_ISO2022_LOCK;
5039               return 1;
5040             }
5041
5042           /* bzzzt! */
5043           return 0;
5044         }
5045
5046
5047
5048       /**** directionality ****/
5049
5050     case ISO_ESC_5_11:          /* ISO6429 direction control */
5051       if (c == ']')
5052         {
5053           *flags &= (CODING_STATE_ISO2022_LOCK & ~CODING_STATE_R2L);
5054           goto directionality;
5055         }
5056       if      (c == '0') iso->esc = ISO_ESC_5_11_0;
5057       else if (c == '1') iso->esc = ISO_ESC_5_11_1;
5058       else if (c == '2') iso->esc = ISO_ESC_5_11_2;
5059       else               return 0;
5060       goto not_done;
5061
5062     case ISO_ESC_5_11_0:
5063       if (c == ']')
5064         {
5065           *flags &= (CODING_STATE_ISO2022_LOCK & ~CODING_STATE_R2L);
5066           goto directionality;
5067         }
5068       return 0;
5069
5070     case ISO_ESC_5_11_1:
5071       if (c == ']')
5072         {
5073           *flags = (CODING_STATE_ISO2022_LOCK & ~CODING_STATE_R2L);
5074           goto directionality;
5075         }
5076       return 0;
5077
5078     case ISO_ESC_5_11_2:
5079       if (c == ']')
5080         {
5081           *flags = (*flags & CODING_STATE_ISO2022_LOCK) | CODING_STATE_R2L;
5082           goto directionality;
5083         }
5084       return 0;
5085
5086     directionality:
5087       iso->esc = ISO_ESC_DIRECTIONALITY;
5088       /* Various junk here to attempt to preserve the direction sequences
5089          literally in the text if they would otherwise be swallowed due
5090          to invalid designations that don't show up as actual charset
5091          changes in the text. */
5092       if (iso->invalid_switch_dir)
5093         {
5094           /* We already inserted a direction switch literally into the
5095              text.  We assume (#### this may not be right) that the
5096              next direction switch is the one going the other way,
5097              and we need to output that literally as well. */
5098           iso->output_literally = 1;
5099           iso->invalid_switch_dir = 0;
5100         }
5101       else
5102         {
5103           int jj;
5104
5105           /* If we are in the thrall of an invalid designation,
5106            then stick the directionality sequence literally into the
5107            output stream so it ends up in the original text again. */
5108           for (jj = 0; jj < 4; jj++)
5109             if (iso->invalid_designated[jj])
5110               break;
5111           if (jj < 4)
5112             {
5113               iso->output_literally = 1;
5114               iso->invalid_switch_dir = 1;
5115             }
5116           else
5117             /* Indicate that we haven't yet seen a valid designation,
5118                so that if a switch-dir is directly followed by an
5119                invalid designation, both get inserted literally. */
5120             iso->switched_dir_and_no_valid_charset_yet = 1;
5121         }
5122       return 1;
5123
5124
5125       /**** designation ****/
5126
5127     case ISO_ESC_2_4:
5128       if (0x28 <= c && c <= 0x2F)
5129         {
5130           iso->esc = (enum iso_esc_flag) (c - 0x28 + ISO_ESC_2_4_8);
5131           goto not_done;
5132         }
5133       if (0x40 <= c && c <= 0x42)
5134         {
5135           /* 94^n-set */
5136           cs = CHARSET_BY_ATTRIBUTES (94, -1, c,
5137                                       *flags & CODING_STATE_R2L ?
5138                                       CHARSET_RIGHT_TO_LEFT :
5139                                       CHARSET_LEFT_TO_RIGHT);
5140           reg = 0;
5141           goto designated;
5142         }
5143       return 0;
5144
5145     default:
5146       {
5147         int chars = 0;
5148         int single = 0;
5149
5150         if (c < '0' || c > '~')
5151           return 0; /* bad final byte */
5152
5153         if (iso->esc >= ISO_ESC_2_8 &&
5154             iso->esc <= ISO_ESC_2_15)
5155           {
5156             chars = (iso->esc >= ISO_ESC_2_12) ? 96 : 94;
5157             single = 1; /* single-byte */
5158             reg = (iso->esc - ISO_ESC_2_8) & 3;
5159           }
5160         else if (iso->esc >= ISO_ESC_2_4_8 &&
5161                  iso->esc <= ISO_ESC_2_4_15)
5162           {
5163             chars = (iso->esc >= ISO_ESC_2_4_12) ? 96 : 94;
5164             single = -1; /* multi-byte */
5165             reg = (iso->esc - ISO_ESC_2_4_8) & 3;
5166           }
5167         else
5168           {
5169             /* Can this ever be reached? -slb */
5170             abort();
5171           }
5172
5173         cs = CHARSET_BY_ATTRIBUTES (chars, single, c,
5174                                     *flags & CODING_STATE_R2L ?
5175                                     CHARSET_RIGHT_TO_LEFT :
5176                                     CHARSET_LEFT_TO_RIGHT);
5177         goto designated;
5178       }
5179     }
5180
5181  not_done:
5182   iso->esc_bytes[iso->esc_bytes_index++] = (unsigned char) c;
5183   return -1;
5184
5185  single_shift:
5186   if (check_invalid_charsets && !CHARSETP (iso->charset[reg]))
5187     /* can't invoke something that ain't there. */
5188     return 0;
5189   iso->esc = ISO_ESC_SINGLE_SHIFT;
5190   *flags &= CODING_STATE_ISO2022_LOCK;
5191   if (reg == 2)
5192     *flags |= CODING_STATE_SS2;
5193   else
5194     *flags |= CODING_STATE_SS3;
5195   return 1;
5196
5197  locking_shift:
5198   if (check_invalid_charsets &&
5199       !CHARSETP (iso->charset[reg]))
5200     /* can't invoke something that ain't there. */
5201     return 0;
5202   if (half)
5203     iso->register_right = reg;
5204   else
5205     iso->register_left = reg;
5206   *flags &= CODING_STATE_ISO2022_LOCK;
5207   iso->esc = ISO_ESC_LOCKING_SHIFT;
5208   return 1;
5209
5210  designated:
5211   if (NILP (cs) && check_invalid_charsets)
5212     {
5213       iso->invalid_designated[reg] = 1;
5214       iso->charset[reg] = Vcharset_ascii;
5215       iso->esc = ISO_ESC_DESIGNATE;
5216       *flags &= CODING_STATE_ISO2022_LOCK;
5217       iso->output_literally = 1;
5218       if (iso->switched_dir_and_no_valid_charset_yet)
5219         {
5220           /* We encountered a switch-direction followed by an
5221              invalid designation.  Ensure that the switch-direction
5222              gets outputted; otherwise it will probably get eaten
5223              when the text is written out again. */
5224           iso->switched_dir_and_no_valid_charset_yet = 0;
5225           iso->output_direction_sequence = 1;
5226           /* And make sure that the switch-dir going the other
5227              way gets outputted, as well. */
5228           iso->invalid_switch_dir = 1;
5229         }
5230       return 1;
5231     }
5232   /* This function is called with CODESYS equal to nil when
5233      doing coding-system detection. */
5234   if (!NILP (codesys))
5235     {
5236       charset_conversion_spec_dynarr *dyn =
5237         XCODING_SYSTEM (codesys)->iso2022.input_conv;
5238
5239       if (dyn)
5240         {
5241           int i;
5242
5243           for (i = 0; i < Dynarr_length (dyn); i++)
5244             {
5245               struct charset_conversion_spec *spec = Dynarr_atp (dyn, i);
5246               if (EQ (cs, spec->from_charset))
5247                 cs = spec->to_charset;
5248             }
5249         }
5250     }
5251
5252   iso->charset[reg] = cs;
5253   iso->esc = ISO_ESC_DESIGNATE;
5254   *flags &= CODING_STATE_ISO2022_LOCK;
5255   if (iso->invalid_designated[reg])
5256     {
5257       iso->invalid_designated[reg] = 0;
5258       iso->output_literally = 1;
5259     }
5260   if (iso->switched_dir_and_no_valid_charset_yet)
5261     iso->switched_dir_and_no_valid_charset_yet = 0;
5262   return 1;
5263 }
5264
5265 static int
5266 detect_coding_iso2022 (struct detection_state *st, const Extbyte *src, Lstream_data_count n)
5267 {
5268   int mask;
5269
5270   /* #### There are serious deficiencies in the recognition mechanism
5271      here.  This needs to be much smarter if it's going to cut it.
5272      The sequence "\xff\x0f" is currently detected as LOCK_SHIFT while
5273      it should be detected as Latin-1.
5274      All the ISO2022 stuff in this file should be synced up with the
5275      code from FSF Emacs-20.4, in which Mule should be more or less stable.
5276      Perhaps we should wait till R2L works in FSF Emacs? */
5277
5278   if (!st->iso2022.initted)
5279     {
5280       reset_iso2022 (Qnil, &st->iso2022.iso);
5281       st->iso2022.mask = (CODING_CATEGORY_ISO_7_MASK |
5282                           CODING_CATEGORY_ISO_8_DESIGNATE_MASK |
5283                           CODING_CATEGORY_ISO_8_1_MASK |
5284                           CODING_CATEGORY_ISO_8_2_MASK |
5285                           CODING_CATEGORY_ISO_LOCK_SHIFT_MASK);
5286       st->iso2022.flags = 0;
5287       st->iso2022.high_byte_count = 0;
5288       st->iso2022.saw_single_shift = 0;
5289       st->iso2022.initted = 1;
5290     }
5291
5292   mask = st->iso2022.mask;
5293
5294   while (n--)
5295     {
5296       unsigned char c = *(unsigned char *)src++;
5297       if (c >= 0xA0)
5298         {
5299           mask &= ~CODING_CATEGORY_ISO_7_MASK;
5300           st->iso2022.high_byte_count++;
5301         }
5302       else
5303         {
5304           if (st->iso2022.high_byte_count && !st->iso2022.saw_single_shift)
5305             {
5306               if (st->iso2022.high_byte_count & 1)
5307                 /* odd number of high bytes; assume not iso-8-2 */
5308                 mask &= ~CODING_CATEGORY_ISO_8_2_MASK;
5309             }
5310           st->iso2022.high_byte_count = 0;
5311           st->iso2022.saw_single_shift = 0;
5312           if (c > 0x80)
5313             mask &= ~CODING_CATEGORY_ISO_7_MASK;
5314         }
5315       if (!(st->iso2022.flags & CODING_STATE_ESCAPE)
5316           && (BYTE_C0_P (c) || BYTE_C1_P (c)))
5317         { /* control chars */
5318           switch (c)
5319             {
5320               /* Allow and ignore control characters that you might
5321                  reasonably see in a text file */
5322             case '\r':
5323             case '\n':
5324             case '\t':
5325             case  7: /* bell */
5326             case  8: /* backspace */
5327             case 11: /* vertical tab */
5328             case 12: /* form feed */
5329             case 26: /* MS-DOS C-z junk */
5330             case 31: /* '^_' -- for info */
5331               goto label_continue_loop;
5332
5333             default:
5334               break;
5335             }
5336         }
5337
5338       if ((st->iso2022.flags & CODING_STATE_ESCAPE) || BYTE_C0_P (c)
5339           || BYTE_C1_P (c))
5340         {
5341           if (parse_iso2022_esc (Qnil, &st->iso2022.iso, c,
5342                                  &st->iso2022.flags, 0))
5343             {
5344               switch (st->iso2022.iso.esc)
5345                 {
5346                 case ISO_ESC_DESIGNATE:
5347                   mask &= ~CODING_CATEGORY_ISO_8_1_MASK;
5348                   mask &= ~CODING_CATEGORY_ISO_8_2_MASK;
5349                   break;
5350                 case ISO_ESC_LOCKING_SHIFT:
5351                   mask = CODING_CATEGORY_ISO_LOCK_SHIFT_MASK;
5352                   goto ran_out_of_chars;
5353                 case ISO_ESC_SINGLE_SHIFT:
5354                   mask &= ~CODING_CATEGORY_ISO_8_DESIGNATE_MASK;
5355                   st->iso2022.saw_single_shift = 1;
5356                   break;
5357                 default:
5358                   break;
5359                 }
5360             }
5361           else
5362             {
5363               mask = 0;
5364               goto ran_out_of_chars;
5365             }
5366         }
5367     label_continue_loop:;
5368     }
5369
5370  ran_out_of_chars:
5371
5372   return mask;
5373 }
5374
5375 static int
5376 postprocess_iso2022_mask (int mask)
5377 {
5378   /* #### kind of cheesy */
5379   /* If seven-bit ISO is allowed, then assume that the encoding is
5380      entirely seven-bit and turn off the eight-bit ones. */
5381   if (mask & CODING_CATEGORY_ISO_7_MASK)
5382     mask &= ~ (CODING_CATEGORY_ISO_8_DESIGNATE_MASK |
5383                CODING_CATEGORY_ISO_8_1_MASK |
5384                CODING_CATEGORY_ISO_8_2_MASK);
5385   return mask;
5386 }
5387
5388 /* If FLAGS is a null pointer or specifies right-to-left motion,
5389    output a switch-dir-to-left-to-right sequence to DST.
5390    Also update FLAGS if it is not a null pointer.
5391    If INTERNAL_P is set, we are outputting in internal format and
5392    need to handle the CSI differently. */
5393
5394 static void
5395 restore_left_to_right_direction (Lisp_Coding_System *codesys,
5396                                  unsigned_char_dynarr *dst,
5397                                  unsigned int *flags,
5398                                  int internal_p)
5399 {
5400   if (!flags || (*flags & CODING_STATE_R2L))
5401     {
5402       if (CODING_SYSTEM_ISO2022_SEVEN (codesys))
5403         {
5404           Dynarr_add (dst, ISO_CODE_ESC);
5405           Dynarr_add (dst, '[');
5406         }
5407       else if (internal_p)
5408         DECODE_ADD_BINARY_CHAR (ISO_CODE_CSI, dst);
5409       else
5410         Dynarr_add (dst, ISO_CODE_CSI);
5411       Dynarr_add (dst, '0');
5412       Dynarr_add (dst, ']');
5413       if (flags)
5414         *flags &= ~CODING_STATE_R2L;
5415     }
5416 }
5417
5418 /* If FLAGS is a null pointer or specifies a direction different from
5419    DIRECTION (which should be either CHARSET_RIGHT_TO_LEFT or
5420    CHARSET_LEFT_TO_RIGHT), output the appropriate switch-dir escape
5421    sequence to DST.  Also update FLAGS if it is not a null pointer.
5422    If INTERNAL_P is set, we are outputting in internal format and
5423    need to handle the CSI differently. */
5424
5425 static void
5426 ensure_correct_direction (int direction, Lisp_Coding_System *codesys,
5427                           unsigned_char_dynarr *dst, unsigned int *flags,
5428                           int internal_p)
5429 {
5430   if ((!flags || (*flags & CODING_STATE_R2L)) &&
5431       direction == CHARSET_LEFT_TO_RIGHT)
5432     restore_left_to_right_direction (codesys, dst, flags, internal_p);
5433   else if (!CODING_SYSTEM_ISO2022_NO_ISO6429 (codesys)
5434            && (!flags || !(*flags & CODING_STATE_R2L)) &&
5435            direction == CHARSET_RIGHT_TO_LEFT)
5436     {
5437       if (CODING_SYSTEM_ISO2022_SEVEN (codesys))
5438         {
5439           Dynarr_add (dst, ISO_CODE_ESC);
5440           Dynarr_add (dst, '[');
5441         }
5442       else if (internal_p)
5443         DECODE_ADD_BINARY_CHAR (ISO_CODE_CSI, dst);
5444       else
5445         Dynarr_add (dst, ISO_CODE_CSI);
5446       Dynarr_add (dst, '2');
5447       Dynarr_add (dst, ']');
5448       if (flags)
5449         *flags |= CODING_STATE_R2L;
5450     }
5451 }
5452
5453 /* Convert ISO2022-format data to internal format. */
5454
5455 static void
5456 decode_coding_iso2022 (Lstream *decoding, const Extbyte *src,
5457                        unsigned_char_dynarr *dst, Lstream_data_count n)
5458 {
5459   struct decoding_stream *str = DECODING_STREAM_DATA (decoding);
5460   unsigned int flags    = str->flags;
5461   unsigned int cpos     = str->cpos;
5462   unsigned char counter = str->counter;
5463   eol_type_t eol_type   = str->eol_type;
5464 #ifdef ENABLE_COMPOSITE_CHARS
5465   unsigned_char_dynarr *real_dst = dst;
5466 #endif
5467   Lisp_Object coding_system;
5468
5469   XSETCODING_SYSTEM (coding_system, str->codesys);
5470
5471 #ifdef ENABLE_COMPOSITE_CHARS
5472   if (flags & CODING_STATE_COMPOSITE)
5473     dst = str->iso2022.composite_chars;
5474 #endif /* ENABLE_COMPOSITE_CHARS */
5475
5476   while (n--)
5477     {
5478       unsigned char c = *(unsigned char *)src++;
5479       if (flags & CODING_STATE_ESCAPE)
5480         {       /* Within ESC sequence */
5481           int retval = parse_iso2022_esc (coding_system, &str->iso2022,
5482                                           c, &flags, 1);
5483
5484           if (retval)
5485             {
5486               switch (str->iso2022.esc)
5487                 {
5488 #ifdef ENABLE_COMPOSITE_CHARS
5489                 case ISO_ESC_START_COMPOSITE:
5490                   if (str->iso2022.composite_chars)
5491                     Dynarr_reset (str->iso2022.composite_chars);
5492                   else
5493                     str->iso2022.composite_chars = Dynarr_new (unsigned_char);
5494                   dst = str->iso2022.composite_chars;
5495                   break;
5496                 case ISO_ESC_END_COMPOSITE:
5497                   {
5498                     Bufbyte comstr[MAX_EMCHAR_LEN];
5499                     Bytecount len;
5500                     Emchar emch = lookup_composite_char (Dynarr_atp (dst, 0),
5501                                                          Dynarr_length (dst));
5502                     dst = real_dst;
5503                     len = set_charptr_emchar (comstr, emch);
5504                     Dynarr_add_many (dst, comstr, len);
5505                     break;
5506                   }
5507 #endif /* ENABLE_COMPOSITE_CHARS */
5508
5509                 case ISO_ESC_LITERAL:
5510                   COMPOSE_FLUSH_CHARS (str, dst);
5511                   decode_flush_er_chars (str, dst);
5512                   DECODE_ADD_BINARY_CHAR (c, dst);
5513                   break;
5514
5515                 default:
5516                   /* Everything else handled already */
5517                   break;
5518                 }
5519             }
5520
5521           /* Attempted error recovery. */
5522           if (str->iso2022.output_direction_sequence)
5523             ensure_correct_direction (flags & CODING_STATE_R2L ?
5524                                       CHARSET_RIGHT_TO_LEFT :
5525                                       CHARSET_LEFT_TO_RIGHT,
5526                                       str->codesys, dst, 0, 1);
5527           /* More error recovery. */
5528           if (!retval || str->iso2022.output_literally)
5529             {
5530               /* Output the (possibly invalid) sequence */
5531               int i;
5532               COMPOSE_FLUSH_CHARS (str, dst);
5533               decode_flush_er_chars (str, dst);
5534               for (i = 0; i < str->iso2022.esc_bytes_index; i++)
5535                 DECODE_ADD_BINARY_CHAR (str->iso2022.esc_bytes[i], dst);
5536               flags &= CODING_STATE_ISO2022_LOCK;
5537               if (!retval)
5538                 n++, src--;/* Repeat the loop with the same character. */
5539               else
5540                 {
5541                   /* No sense in reprocessing the final byte of the
5542                      escape sequence; it could mess things up anyway.
5543                      Just add it now. */
5544                   COMPOSE_FLUSH_CHARS (str, dst);
5545                   decode_flush_er_chars (str, dst);
5546                   DECODE_ADD_BINARY_CHAR (c, dst);
5547                 }
5548             }
5549           cpos = 0;
5550           counter = 0;
5551         }
5552       else if (BYTE_C0_P (c) || BYTE_C1_P (c))
5553         { /* Control characters */
5554
5555           /***** Error-handling *****/
5556
5557           /* If we were in the middle of a character, dump out the
5558              partial character. */
5559           if (counter)
5560             {
5561               COMPOSE_FLUSH_CHARS (str, dst);
5562               decode_flush_er_chars (str, dst);
5563               while (counter > 0)
5564                 {
5565                   counter--;
5566                   DECODE_ADD_BINARY_CHAR
5567                     ((unsigned char)(cpos >> (counter * 8)), dst);
5568                 }
5569               cpos = 0;
5570             }
5571
5572           /* If we just saw a single-shift character, dump it out.
5573              This may dump out the wrong sort of single-shift character,
5574              but least it will give an indication that something went
5575              wrong. */
5576           if (flags & CODING_STATE_SS2)
5577             {
5578               COMPOSE_FLUSH_CHARS (str, dst);
5579               decode_flush_er_chars (str, dst);
5580               DECODE_ADD_BINARY_CHAR (ISO_CODE_SS2, dst);
5581               flags &= ~CODING_STATE_SS2;
5582             }
5583           if (flags & CODING_STATE_SS3)
5584             {
5585               COMPOSE_FLUSH_CHARS (str, dst);
5586               decode_flush_er_chars (str, dst);
5587               DECODE_ADD_BINARY_CHAR (ISO_CODE_SS3, dst);
5588               flags &= ~CODING_STATE_SS3;
5589             }
5590
5591           /***** Now handle the control characters. *****/
5592
5593           /* Handle CR/LF */
5594 #ifdef UTF2000
5595           if (c == '\r')
5596             {
5597               COMPOSE_FLUSH_CHARS (str, dst);
5598               decode_flush_er_chars (str, dst);
5599               if (eol_type == EOL_CR)
5600                 Dynarr_add (dst, '\n');
5601               else if (eol_type != EOL_CRLF || flags & CODING_STATE_CR)
5602                 Dynarr_add (dst, c);
5603               else
5604                 flags |= CODING_STATE_CR;
5605               goto label_continue_loop;
5606             }
5607           else if (flags & CODING_STATE_CR)
5608             {   /* eol_type == CODING_SYSTEM_EOL_CRLF */
5609               if (c != '\n')
5610                 Dynarr_add (dst, '\r');
5611               flags &= ~CODING_STATE_CR;
5612             }
5613 #else
5614           DECODE_HANDLE_EOL_TYPE (eol_type, c, flags, dst);
5615 #endif
5616
5617           flags &= CODING_STATE_ISO2022_LOCK;
5618
5619           if (!parse_iso2022_esc (coding_system, &str->iso2022, c, &flags, 1))
5620             {
5621               COMPOSE_FLUSH_CHARS (str, dst);
5622               decode_flush_er_chars (str, dst);
5623               DECODE_ADD_BINARY_CHAR (c, dst);
5624             }
5625         }
5626       else
5627         {                       /* Graphic characters */
5628           Lisp_Object charset;
5629 #ifndef UTF2000
5630           Charset_ID lb;
5631 #endif
5632           int reg;
5633
5634 #ifdef UTF2000
5635           if (c == '\r')
5636             {
5637               COMPOSE_FLUSH_CHARS (str, dst);
5638               decode_flush_er_chars (str, dst);
5639               if (eol_type == EOL_CR)
5640                 Dynarr_add (dst, '\n');
5641               else if (eol_type != EOL_CRLF || flags & CODING_STATE_CR)
5642                 Dynarr_add (dst, c);
5643               else
5644                 flags |= CODING_STATE_CR;
5645               goto label_continue_loop;
5646             }
5647           else if (flags & CODING_STATE_CR)
5648             {   /* eol_type == CODING_SYSTEM_EOL_CRLF */
5649               if (c != '\n')
5650                 Dynarr_add (dst, '\r');
5651               flags &= ~CODING_STATE_CR;
5652             }
5653 #else
5654           DECODE_HANDLE_EOL_TYPE (eol_type, c, flags, dst);
5655 #endif
5656
5657           /* Now determine the charset. */
5658           reg = ((flags & CODING_STATE_SS2) ? 2
5659                  : (flags & CODING_STATE_SS3) ? 3
5660                  : !BYTE_ASCII_P (c) ? str->iso2022.register_right
5661                  : str->iso2022.register_left);
5662           charset = str->iso2022.charset[reg];
5663
5664           /* Error checking: */
5665           if (! CHARSETP (charset)
5666               || str->iso2022.invalid_designated[reg]
5667               || (((c & 0x7F) == ' ' || (c & 0x7F) == ISO_CODE_DEL)
5668                   && XCHARSET_CHARS (charset) == 94))
5669             /* Mrmph.  We are trying to invoke a register that has no
5670                or an invalid charset in it, or trying to add a character
5671                outside the range of the charset.  Insert that char literally
5672                to preserve it for the output. */
5673             {
5674               COMPOSE_FLUSH_CHARS (str, dst);
5675               decode_flush_er_chars (str, dst);
5676               while (counter > 0)
5677                 {
5678                   counter--;
5679                   DECODE_ADD_BINARY_CHAR
5680                     ((unsigned char)(cpos >> (counter * 8)), dst);
5681                 }
5682               cpos = 0;
5683               DECODE_ADD_BINARY_CHAR (c, dst);
5684             }
5685
5686           else
5687             {
5688               /* Things are probably hunky-dorey. */
5689
5690               /* Fetch reverse charset, maybe. */
5691               if (((flags & CODING_STATE_R2L) &&
5692                    XCHARSET_DIRECTION (charset) == CHARSET_LEFT_TO_RIGHT)
5693                   ||
5694                   (!(flags & CODING_STATE_R2L) &&
5695                    XCHARSET_DIRECTION (charset) == CHARSET_RIGHT_TO_LEFT))
5696                 {
5697                   Lisp_Object new_charset =
5698                     XCHARSET_REVERSE_DIRECTION_CHARSET (charset);
5699                   if (!NILP (new_charset))
5700                     charset = new_charset;
5701                 }
5702
5703 #ifdef UTF2000
5704               counter++;
5705               if (XCHARSET_DIMENSION (charset) == counter)
5706                 {
5707                   COMPOSE_ADD_CHAR (str,
5708                                     DECODE_CHAR (charset,
5709                                                  ((cpos & 0x7F7F7F) << 8)
5710                                                  | (c & 0x7F), 0),
5711                                     dst);
5712                   cpos = 0;
5713                   counter = 0;
5714                 }
5715               else
5716                 cpos = (cpos << 8) | c;
5717 #else
5718               lb = XCHARSET_LEADING_BYTE (charset);
5719               switch (XCHARSET_REP_BYTES (charset))
5720                 {
5721                 case 1: /* ASCII */
5722                   DECODE_OUTPUT_PARTIAL_CHAR (ch);
5723                   Dynarr_add (dst, c & 0x7F);
5724                   break;
5725
5726                 case 2: /* one-byte official */
5727                   DECODE_OUTPUT_PARTIAL_CHAR (ch);
5728                   Dynarr_add (dst, lb);
5729                   Dynarr_add (dst, c | 0x80);
5730                   break;
5731
5732                 case 3: /* one-byte private or two-byte official */
5733                   if (XCHARSET_PRIVATE_P (charset))
5734                     {
5735                       DECODE_OUTPUT_PARTIAL_CHAR (ch);
5736                       Dynarr_add (dst, PRE_LEADING_BYTE_PRIVATE_1);
5737                       Dynarr_add (dst, lb);
5738                       Dynarr_add (dst, c | 0x80);
5739                     }
5740                   else
5741                     {
5742                       if (ch)
5743                         {
5744                           Dynarr_add (dst, lb);
5745                           Dynarr_add (dst, ch | 0x80);
5746                           Dynarr_add (dst, c | 0x80);
5747                           ch = 0;
5748                         }
5749                       else
5750                         ch = c;
5751                     }
5752                   break;
5753
5754                 default:        /* two-byte private */
5755                   if (ch)
5756                     {
5757                       Dynarr_add (dst, PRE_LEADING_BYTE_PRIVATE_2);
5758                       Dynarr_add (dst, lb);
5759                       Dynarr_add (dst, ch | 0x80);
5760                       Dynarr_add (dst, c | 0x80);
5761                       ch = 0;
5762                     }
5763                   else
5764                     ch = c;
5765                 }
5766 #endif
5767             }
5768
5769           if (!cpos)
5770             flags &= CODING_STATE_ISO2022_LOCK;
5771         }
5772
5773     label_continue_loop:;
5774     }
5775
5776   if (flags & CODING_STATE_END)
5777     {
5778       COMPOSE_FLUSH_CHARS (str, dst);
5779       decode_flush_er_chars (str, dst);
5780       DECODE_OUTPUT_PARTIAL_CHAR (cpos);
5781     }
5782   str->flags   = flags;
5783   str->cpos    = cpos;
5784   str->counter = counter;
5785 }
5786
5787
5788 /***** ISO2022 encoder *****/
5789
5790 /* Designate CHARSET into register REG. */
5791
5792 static void
5793 iso2022_designate (Lisp_Object charset, unsigned char reg,
5794                    struct encoding_stream *str, unsigned_char_dynarr *dst)
5795 {
5796   static const char inter94[] = "()*+";
5797   static const char inter96[] = ",-./";
5798   unsigned short chars;
5799   unsigned char dimension;
5800   unsigned char final;
5801   Lisp_Object old_charset = str->iso2022.charset[reg];
5802
5803   str->iso2022.charset[reg] = charset;
5804   if (!CHARSETP (charset))
5805     /* charset might be an initial nil or t. */
5806     return;
5807   chars = XCHARSET_CHARS (charset);
5808   dimension = XCHARSET_DIMENSION (charset);
5809   final = XCHARSET_FINAL (charset);
5810   if (!str->iso2022.force_charset_on_output[reg] &&
5811       CHARSETP (old_charset) &&
5812       XCHARSET_CHARS (old_charset) == chars &&
5813       XCHARSET_DIMENSION (old_charset) == dimension &&
5814       XCHARSET_FINAL (old_charset) == final)
5815     return;
5816
5817   str->iso2022.force_charset_on_output[reg] = 0;
5818
5819   {
5820     charset_conversion_spec_dynarr *dyn =
5821       str->codesys->iso2022.output_conv;
5822
5823     if (dyn)
5824       {
5825         int i;
5826
5827         for (i = 0; i < Dynarr_length (dyn); i++)
5828           {
5829             struct charset_conversion_spec *spec = Dynarr_atp (dyn, i);
5830             if (EQ (charset, spec->from_charset))
5831                 charset = spec->to_charset;
5832           }
5833       }
5834   }
5835
5836   Dynarr_add (dst, ISO_CODE_ESC);
5837   switch (chars)
5838     {
5839     case 94:
5840       if (dimension == 1)
5841         Dynarr_add (dst, inter94[reg]);
5842       else
5843         {
5844           Dynarr_add (dst, '$');
5845           if (reg != 0
5846               || !(CODING_SYSTEM_ISO2022_SHORT (str->codesys))
5847               || final < '@'
5848               || final > 'B')
5849             Dynarr_add (dst, inter94[reg]);
5850         }
5851       break;
5852     case 96:
5853       if (dimension == 1)
5854         Dynarr_add (dst, inter96[reg]);
5855       else
5856         {
5857           Dynarr_add (dst, '$');
5858           Dynarr_add (dst, inter96[reg]);
5859         }
5860       break;
5861     }
5862   Dynarr_add (dst, final);
5863 }
5864
5865 static void
5866 ensure_normal_shift (struct encoding_stream *str, unsigned_char_dynarr *dst)
5867 {
5868   if (str->iso2022.register_left != 0)
5869     {
5870       Dynarr_add (dst, ISO_CODE_SI);
5871       str->iso2022.register_left = 0;
5872     }
5873 }
5874
5875 static void
5876 ensure_shift_out (struct encoding_stream *str, unsigned_char_dynarr *dst)
5877 {
5878   if (str->iso2022.register_left != 1)
5879     {
5880       Dynarr_add (dst, ISO_CODE_SO);
5881       str->iso2022.register_left = 1;
5882     }
5883 }
5884
5885 void
5886 char_encode_iso2022 (struct encoding_stream *str, Emchar ch,
5887                      unsigned_char_dynarr *dst, unsigned int *flags)
5888 {
5889   unsigned char charmask;
5890   Lisp_Coding_System* codesys = str->codesys;
5891   eol_type_t eol_type         = CODING_SYSTEM_EOL_TYPE (str->codesys);
5892   int i;
5893   Lisp_Object charset = str->iso2022.current_charset;
5894   int half = str->iso2022.current_half;
5895   int code_point = -1;
5896
5897   if (ch <= 0x7F)
5898     {
5899       restore_left_to_right_direction (codesys, dst, flags, 0);
5900               
5901       /* Make sure G0 contains ASCII */
5902       if ((ch > ' ' && ch < ISO_CODE_DEL)
5903           || !CODING_SYSTEM_ISO2022_NO_ASCII_CNTL (codesys))
5904         {
5905           ensure_normal_shift (str, dst);
5906           iso2022_designate (Vcharset_ascii, 0, str, dst);
5907         }
5908               
5909       /* If necessary, restore everything to the default state
5910          at end-of-line */
5911       if (ch == '\n' && !(CODING_SYSTEM_ISO2022_NO_ASCII_EOL (codesys)))
5912         {
5913           restore_left_to_right_direction (codesys, dst, flags, 0);
5914
5915           ensure_normal_shift (str, dst);
5916
5917           for (i = 0; i < 4; i++)
5918             {
5919               Lisp_Object initial_charset =
5920                 CODING_SYSTEM_ISO2022_INITIAL_CHARSET (codesys, i);
5921               iso2022_designate (initial_charset, i, str, dst);
5922             }
5923         }
5924       if (ch == '\n')
5925         {
5926           if (eol_type != EOL_LF && eol_type != EOL_AUTODETECT)
5927             Dynarr_add (dst, '\r');
5928           if (eol_type != EOL_CR)
5929             Dynarr_add (dst, ch);
5930         }
5931       else
5932         {
5933           if (CODING_SYSTEM_ISO2022_ESCAPE_QUOTED (codesys)
5934               && fit_to_be_escape_quoted (ch))
5935             Dynarr_add (dst, ISO_CODE_ESC);
5936           Dynarr_add (dst, ch);
5937         }
5938     }
5939   else if ( (0x80 <= ch) && (ch <= 0x9f) )
5940     {
5941       charmask = (half == 0 ? 0x00 : 0x80);
5942           
5943       if (CODING_SYSTEM_ISO2022_ESCAPE_QUOTED (codesys)
5944           && fit_to_be_escape_quoted (ch))
5945         Dynarr_add (dst, ISO_CODE_ESC);
5946       /* you asked for it ... */
5947       Dynarr_add (dst, ch);
5948     }
5949   else
5950     {
5951       int reg;
5952
5953       /* Now determine which register to use. */
5954       reg = -1;
5955       for (i = 0; i < 4; i++)
5956         {
5957           if ((CHARSETP (charset = str->iso2022.charset[i])
5958                && ((code_point = charset_code_point (charset, ch, 0)) >= 0))
5959               ||
5960               (CHARSETP
5961                (charset
5962                 = CODING_SYSTEM_ISO2022_INITIAL_CHARSET (codesys, i))
5963                && ((code_point = charset_code_point (charset, ch, 0)) >= 0)))
5964             {
5965               reg = i;
5966               break;
5967             }
5968         }
5969       if (reg == -1)
5970         {
5971           Lisp_Object original_default_coded_charset_priority_list
5972             = Vdefault_coded_charset_priority_list;
5973
5974           while (!EQ (Vdefault_coded_charset_priority_list, Qnil))
5975             {
5976               code_point = ENCODE_CHAR (ch, charset);
5977               if (XCHARSET_FINAL (charset))
5978                 goto found;
5979               Vdefault_coded_charset_priority_list
5980                 = Fcdr (Fmemq (XCHARSET_NAME (charset),
5981                                Vdefault_coded_charset_priority_list));
5982             }
5983           code_point = ENCODE_CHAR (ch, charset);
5984           if (!XCHARSET_FINAL (charset))
5985             {
5986               charset = Vcharset_ascii;
5987               code_point = '~';
5988             }
5989         found:
5990           Vdefault_coded_charset_priority_list
5991             = original_default_coded_charset_priority_list;
5992         }
5993       ensure_correct_direction (XCHARSET_DIRECTION (charset),
5994                                 codesys, dst, flags, 0);
5995       
5996       if (reg == -1)
5997         {
5998           if (XCHARSET_GRAPHIC (charset) != 0)
5999             {
6000               if (!NILP (str->iso2022.charset[1]) &&
6001                   (!CODING_SYSTEM_ISO2022_SEVEN (codesys)
6002                    || CODING_SYSTEM_ISO2022_LOCK_SHIFT (codesys)))
6003                 reg = 1;
6004               else if (!NILP (str->iso2022.charset[2]))
6005                 reg = 2;
6006               else if (!NILP (str->iso2022.charset[3]))
6007                 reg = 3;
6008               else
6009                 reg = 0;
6010             }
6011           else
6012             reg = 0;
6013         }
6014
6015       iso2022_designate (charset, reg, str, dst);
6016               
6017       /* Now invoke that register. */
6018       switch (reg)
6019         {
6020         case 0:
6021           ensure_normal_shift (str, dst);
6022           half = 0;
6023           break;
6024         case 1:
6025           if (CODING_SYSTEM_ISO2022_SEVEN (codesys))
6026             {
6027               ensure_shift_out (str, dst);
6028               half = 0;
6029             }
6030           else
6031             half = 1;
6032           break;
6033         case 2:
6034           if (CODING_SYSTEM_ISO2022_SEVEN (str->codesys))
6035             {
6036               Dynarr_add (dst, ISO_CODE_ESC);
6037               Dynarr_add (dst, 'N');
6038               half = 0;
6039             }
6040           else
6041             {
6042               Dynarr_add (dst, ISO_CODE_SS2);
6043               half = 1;
6044             }
6045           break;
6046         case 3:
6047           if (CODING_SYSTEM_ISO2022_SEVEN (str->codesys))
6048             {
6049               Dynarr_add (dst, ISO_CODE_ESC);
6050               Dynarr_add (dst, 'O');
6051               half = 0;
6052             }
6053           else
6054             {
6055               Dynarr_add (dst, ISO_CODE_SS3);
6056               half = 1;
6057             }
6058           break;
6059         default:
6060           abort ();
6061         }
6062       
6063       charmask = (half == 0 ? 0x00 : 0x80);
6064       
6065       switch (XCHARSET_DIMENSION (charset))
6066         {
6067         case 1:
6068           Dynarr_add (dst, (code_point & 0xFF) | charmask);
6069           break;
6070         case 2:
6071           Dynarr_add (dst, ((code_point >> 8) & 0xFF) | charmask);
6072           Dynarr_add (dst, ( code_point       & 0xFF) | charmask);
6073           break;
6074         case 3:
6075           Dynarr_add (dst, ((code_point >> 16) & 0xFF) | charmask);
6076           Dynarr_add (dst, ((code_point >>  8) & 0xFF) | charmask);
6077           Dynarr_add (dst, ( code_point        & 0xFF) | charmask);
6078           break;
6079         case 4:
6080           Dynarr_add (dst, ((code_point >> 24) & 0xFF) | charmask);
6081           Dynarr_add (dst, ((code_point >> 16) & 0xFF) | charmask);
6082           Dynarr_add (dst, ((code_point >>  8) & 0xFF) | charmask);
6083           Dynarr_add (dst, ( code_point        & 0xFF) | charmask);
6084           break;
6085         default:
6086           abort ();
6087         }
6088     }
6089   str->iso2022.current_charset = charset;
6090   str->iso2022.current_half = half;
6091 }
6092
6093 void
6094 char_finish_iso2022 (struct encoding_stream *str, unsigned_char_dynarr *dst,
6095                      unsigned int *flags)
6096 {
6097   Lisp_Coding_System* codesys = str->codesys;
6098   int i;
6099
6100   restore_left_to_right_direction (codesys, dst, flags, 0);
6101   ensure_normal_shift (str, dst);
6102   for (i = 0; i < 4; i++)
6103     {
6104       Lisp_Object initial_charset
6105         = CODING_SYSTEM_ISO2022_INITIAL_CHARSET (codesys, i);
6106       iso2022_designate (initial_charset, i, str, dst);
6107     }
6108 }
6109 #endif /* MULE */
6110 \f
6111 /************************************************************************/
6112 /*                     No-conversion methods                            */
6113 /************************************************************************/
6114
6115 /* This is used when reading in "binary" files -- i.e. files that may
6116    contain all 256 possible byte values and that are not to be
6117    interpreted as being in any particular decoding. */
6118 static void
6119 decode_coding_no_conversion (Lstream *decoding, const Extbyte *src,
6120                              unsigned_char_dynarr *dst, Lstream_data_count n)
6121 {
6122   struct decoding_stream *str = DECODING_STREAM_DATA (decoding);
6123   unsigned int flags  = str->flags;
6124   unsigned int cpos   = str->cpos;
6125   eol_type_t eol_type = str->eol_type;
6126
6127   while (n--)
6128     {
6129       unsigned char c = *(unsigned char *)src++;
6130
6131       DECODE_HANDLE_EOL_TYPE (eol_type, c, flags, dst);
6132       DECODE_ADD_BINARY_CHAR (c, dst);
6133     label_continue_loop:;
6134     }
6135
6136   DECODE_HANDLE_END_OF_CONVERSION (flags, cpos, dst);
6137
6138   str->flags = flags;
6139   str->cpos  = cpos;
6140 }
6141
6142 static void
6143 encode_coding_no_conversion (Lstream *encoding, const Bufbyte *src,
6144                              unsigned_char_dynarr *dst, Lstream_data_count n)
6145 {
6146   unsigned char c;
6147   struct encoding_stream *str = ENCODING_STREAM_DATA (encoding);
6148   unsigned int flags  = str->flags;
6149   unsigned int ch     = str->ch;
6150   eol_type_t eol_type = CODING_SYSTEM_EOL_TYPE (str->codesys);
6151 #ifdef UTF2000
6152   unsigned char char_boundary = str->iso2022.current_char_boundary;
6153 #endif
6154
6155   while (n--)
6156     {
6157       c = *src++;         
6158 #ifdef UTF2000
6159       if (char_boundary == 0)
6160         if ( c >= 0xfc )
6161           {
6162             ch = c & 0x01;
6163             char_boundary = 5;
6164           }
6165         else if ( c >= 0xf8 )
6166           {
6167             ch = c & 0x03;
6168             char_boundary = 4;
6169           }
6170         else if ( c >= 0xf0 )
6171           {
6172             ch = c & 0x07;
6173             char_boundary = 3;
6174           }
6175         else if ( c >= 0xe0 )
6176           {
6177             ch = c & 0x0f;
6178             char_boundary = 2;
6179           }
6180         else if ( c >= 0xc0 )
6181           {
6182             ch = c & 0x1f;
6183             char_boundary = 1;
6184           }
6185         else
6186           {
6187             ch = 0;
6188             if (c == '\n')
6189               {
6190                 if (eol_type != EOL_LF && eol_type != EOL_AUTODETECT)
6191                   Dynarr_add (dst, '\r');
6192                 if (eol_type != EOL_CR)
6193                   Dynarr_add (dst, c);
6194               }
6195             else
6196               Dynarr_add (dst, c);
6197             char_boundary = 0;
6198           }
6199       else if (char_boundary == 1)
6200         {
6201           ch = ( ch << 6 ) | ( c & 0x3f );
6202           Dynarr_add (dst, ch & 0xff);
6203           char_boundary = 0;
6204         }
6205       else
6206         {
6207           ch = ( ch << 6 ) | ( c & 0x3f );
6208           char_boundary--;
6209         }
6210 #else /* not UTF2000 */
6211       if (c == '\n')
6212         {
6213           if (eol_type != EOL_LF && eol_type != EOL_AUTODETECT)
6214             Dynarr_add (dst, '\r');
6215           if (eol_type != EOL_CR)
6216             Dynarr_add (dst, '\n');
6217           ch = 0;
6218         }
6219       else if (BYTE_ASCII_P (c))
6220         {
6221           assert (ch == 0);
6222           Dynarr_add (dst, c);
6223         }
6224       else if (BUFBYTE_LEADING_BYTE_P (c))
6225         {
6226           assert (ch == 0);
6227           if (c == LEADING_BYTE_LATIN_ISO8859_1 ||
6228               c == LEADING_BYTE_CONTROL_1)
6229             ch = c;
6230           else
6231             Dynarr_add (dst, '~'); /* untranslatable character */
6232         }
6233       else
6234         {
6235           if (ch == LEADING_BYTE_LATIN_ISO8859_1)
6236             Dynarr_add (dst, c);
6237           else if (ch == LEADING_BYTE_CONTROL_1)
6238             {
6239               assert (c < 0xC0);
6240               Dynarr_add (dst, c - 0x20);
6241             }
6242           /* else it should be the second or third byte of an
6243              untranslatable character, so ignore it */
6244           ch = 0;
6245         }
6246 #endif /* not UTF2000 */
6247     }
6248
6249   str->flags = flags;
6250   str->ch    = ch;
6251 #ifdef UTF2000
6252   str->iso2022.current_char_boundary = char_boundary;
6253 #endif
6254 }
6255
6256 \f
6257
6258 /************************************************************************/
6259 /*                             Initialization                           */
6260 /************************************************************************/
6261
6262 void
6263 syms_of_file_coding (void)
6264 {
6265   INIT_LRECORD_IMPLEMENTATION (coding_system);
6266
6267   DEFERROR_STANDARD (Qcoding_system_error, Qio_error);
6268
6269   DEFSUBR (Fcoding_system_p);
6270   DEFSUBR (Ffind_coding_system);
6271   DEFSUBR (Fget_coding_system);
6272   DEFSUBR (Fcoding_system_list);
6273   DEFSUBR (Fcoding_system_name);
6274   DEFSUBR (Fmake_coding_system);
6275   DEFSUBR (Fcopy_coding_system);
6276   DEFSUBR (Fcoding_system_canonical_name_p);
6277   DEFSUBR (Fcoding_system_alias_p);
6278   DEFSUBR (Fcoding_system_aliasee);
6279   DEFSUBR (Fdefine_coding_system_alias);
6280   DEFSUBR (Fsubsidiary_coding_system);
6281
6282   DEFSUBR (Fcoding_system_type);
6283   DEFSUBR (Fcoding_system_doc_string);
6284 #ifdef MULE
6285   DEFSUBR (Fcoding_system_charset);
6286 #endif
6287   DEFSUBR (Fcoding_system_property);
6288
6289   DEFSUBR (Fcoding_category_list);
6290   DEFSUBR (Fset_coding_priority_list);
6291   DEFSUBR (Fcoding_priority_list);
6292   DEFSUBR (Fset_coding_category_system);
6293   DEFSUBR (Fcoding_category_system);
6294
6295   DEFSUBR (Fdetect_coding_region);
6296   DEFSUBR (Fdecode_coding_region);
6297   DEFSUBR (Fencode_coding_region);
6298 #ifdef MULE
6299   DEFSUBR (Fdecode_shift_jis_char);
6300   DEFSUBR (Fencode_shift_jis_char);
6301   DEFSUBR (Fdecode_big5_char);
6302   DEFSUBR (Fencode_big5_char);
6303 #endif /* MULE */
6304   defsymbol (&Qcoding_systemp, "coding-system-p");
6305   defsymbol (&Qno_conversion, "no-conversion");
6306   defsymbol (&Qraw_text, "raw-text");
6307 #ifdef MULE
6308   defsymbol (&Qbig5, "big5");
6309   defsymbol (&Qshift_jis, "shift-jis");
6310   defsymbol (&Qucs4, "ucs-4");
6311   defsymbol (&Qutf8, "utf-8");
6312   defsymbol (&Qutf16, "utf-16");
6313   defsymbol (&Qccl, "ccl");
6314   defsymbol (&Qiso2022, "iso2022");
6315 #endif /* MULE */
6316   defsymbol (&Qmnemonic, "mnemonic");
6317   defsymbol (&Qeol_type, "eol-type");
6318   defsymbol (&Qpost_read_conversion, "post-read-conversion");
6319   defsymbol (&Qpre_write_conversion, "pre-write-conversion");
6320
6321   defsymbol (&Qcr, "cr");
6322   defsymbol (&Qlf, "lf");
6323   defsymbol (&Qcrlf, "crlf");
6324   defsymbol (&Qeol_cr, "eol-cr");
6325   defsymbol (&Qeol_lf, "eol-lf");
6326   defsymbol (&Qeol_crlf, "eol-crlf");
6327 #ifdef MULE
6328   defsymbol (&Qcharset_g0, "charset-g0");
6329   defsymbol (&Qcharset_g1, "charset-g1");
6330   defsymbol (&Qcharset_g2, "charset-g2");
6331   defsymbol (&Qcharset_g3, "charset-g3");
6332   defsymbol (&Qforce_g0_on_output, "force-g0-on-output");
6333   defsymbol (&Qforce_g1_on_output, "force-g1-on-output");
6334   defsymbol (&Qforce_g2_on_output, "force-g2-on-output");
6335   defsymbol (&Qforce_g3_on_output, "force-g3-on-output");
6336   defsymbol (&Qno_iso6429, "no-iso6429");
6337   defsymbol (&Qinput_charset_conversion, "input-charset-conversion");
6338   defsymbol (&Qoutput_charset_conversion, "output-charset-conversion");
6339
6340   defsymbol (&Qshort, "short");
6341   defsymbol (&Qno_ascii_eol, "no-ascii-eol");
6342   defsymbol (&Qno_ascii_cntl, "no-ascii-cntl");
6343   defsymbol (&Qseven, "seven");
6344   defsymbol (&Qlock_shift, "lock-shift");
6345   defsymbol (&Qescape_quoted, "escape-quoted");
6346 #endif /* MULE */
6347 #ifdef UTF2000
6348   defsymbol (&Qutf_8_mcs, "utf-8-mcs");
6349   defsymbol (&Qdisable_composition, "disable-composition");
6350   defsymbol (&Quse_entity_reference, "use-entity-reference");
6351   defsymbol (&Qd, "d");
6352   defsymbol (&Qx, "x");
6353   defsymbol (&QX, "X");
6354 #endif
6355   defsymbol (&Qencode, "encode");
6356   defsymbol (&Qdecode, "decode");
6357
6358 #ifdef MULE
6359   defsymbol (&coding_category_symbol[CODING_CATEGORY_SHIFT_JIS],
6360              "shift-jis");
6361   defsymbol (&coding_category_symbol[CODING_CATEGORY_BIG5],
6362              "big5");
6363   defsymbol (&coding_category_symbol[CODING_CATEGORY_UCS4],
6364              "ucs-4");
6365   defsymbol (&coding_category_symbol[CODING_CATEGORY_UTF16],
6366              "utf-16");
6367   defsymbol (&coding_category_symbol[CODING_CATEGORY_UTF8],
6368              "utf-8");
6369   defsymbol (&coding_category_symbol[CODING_CATEGORY_ISO_7],
6370              "iso-7");
6371   defsymbol (&coding_category_symbol[CODING_CATEGORY_ISO_8_DESIGNATE],
6372              "iso-8-designate");
6373   defsymbol (&coding_category_symbol[CODING_CATEGORY_ISO_8_1],
6374              "iso-8-1");
6375   defsymbol (&coding_category_symbol[CODING_CATEGORY_ISO_8_2],
6376              "iso-8-2");
6377   defsymbol (&coding_category_symbol[CODING_CATEGORY_ISO_LOCK_SHIFT],
6378              "iso-lock-shift");
6379 #endif /* MULE */
6380   defsymbol (&coding_category_symbol[CODING_CATEGORY_NO_CONVERSION],
6381              "no-conversion");
6382 }
6383
6384 void
6385 lstream_type_create_file_coding (void)
6386 {
6387   LSTREAM_HAS_METHOD (decoding, reader);
6388   LSTREAM_HAS_METHOD (decoding, writer);
6389   LSTREAM_HAS_METHOD (decoding, rewinder);
6390   LSTREAM_HAS_METHOD (decoding, seekable_p);
6391   LSTREAM_HAS_METHOD (decoding, flusher);
6392   LSTREAM_HAS_METHOD (decoding, closer);
6393   LSTREAM_HAS_METHOD (decoding, marker);
6394
6395   LSTREAM_HAS_METHOD (encoding, reader);
6396   LSTREAM_HAS_METHOD (encoding, writer);
6397   LSTREAM_HAS_METHOD (encoding, rewinder);
6398   LSTREAM_HAS_METHOD (encoding, seekable_p);
6399   LSTREAM_HAS_METHOD (encoding, flusher);
6400   LSTREAM_HAS_METHOD (encoding, closer);
6401   LSTREAM_HAS_METHOD (encoding, marker);
6402 }
6403
6404 void
6405 vars_of_file_coding (void)
6406 {
6407   int i;
6408
6409   fcd = xnew (struct file_coding_dump);
6410   dump_add_root_struct_ptr (&fcd, &fcd_description);
6411
6412   /* Initialize to something reasonable ... */
6413   for (i = 0; i < CODING_CATEGORY_LAST; i++)
6414     {
6415       fcd->coding_category_system[i] = Qnil;
6416       fcd->coding_category_by_priority[i] = i;
6417     }
6418
6419   Fprovide (intern ("file-coding"));
6420
6421   DEFVAR_LISP ("keyboard-coding-system", &Vkeyboard_coding_system /*
6422 Coding system used for TTY keyboard input.
6423 Not used under a windowing system.
6424 */ );
6425   Vkeyboard_coding_system = Qnil;
6426
6427   DEFVAR_LISP ("terminal-coding-system", &Vterminal_coding_system /*
6428 Coding system used for TTY display output.
6429 Not used under a windowing system.
6430 */ );
6431   Vterminal_coding_system = Qnil;
6432
6433   DEFVAR_LISP ("coding-system-for-read", &Vcoding_system_for_read /*
6434 Overriding coding system used when reading from a file or process.
6435 You should bind this variable with `let', but do not set it globally.
6436 If this is non-nil, it specifies the coding system that will be used
6437 to decode input on read operations, such as from a file or process.
6438 It overrides `buffer-file-coding-system-for-read',
6439 `insert-file-contents-pre-hook', etc.  Use those variables instead of
6440 this one for permanent changes to the environment.  */ );
6441   Vcoding_system_for_read = Qnil;
6442
6443   DEFVAR_LISP ("coding-system-for-write",
6444                &Vcoding_system_for_write /*
6445 Overriding coding system used when writing to a file or process.
6446 You should bind this variable with `let', but do not set it globally.
6447 If this is non-nil, it specifies the coding system that will be used
6448 to encode output for write operations, such as to a file or process.
6449 It overrides `buffer-file-coding-system', `write-region-pre-hook', etc.
6450 Use those variables instead of this one for permanent changes to the
6451 environment.  */ );
6452   Vcoding_system_for_write = Qnil;
6453
6454   DEFVAR_LISP ("file-name-coding-system", &Vfile_name_coding_system /*
6455 Coding system used to convert pathnames when accessing files.
6456 */ );
6457   Vfile_name_coding_system = Qnil;
6458
6459   DEFVAR_LISP ("coded-charset-entity-reference-alist",
6460                &Vcoded_charset_entity_reference_alist /*
6461 Alist of coded-charset vs corresponding entity-reference.
6462 Each element looks like (CCS PREFIX CODE-COLUMNS CODE-TYPE).
6463 CCS is coded-charset.
6464 CODE-COLUMNS is columns of code-point of entity-reference.
6465 CODE-TYPE is format type of code-point of entity-reference.
6466 `d' means decimal value and `x' means hexadecimal value.
6467 */ );
6468   Vcoded_charset_entity_reference_alist = Qnil;
6469
6470   DEFVAR_BOOL ("enable-multibyte-characters", &enable_multibyte_characters /*
6471 Non-nil means the buffer contents are regarded as multi-byte form
6472 of characters, not a binary code.  This affects the display, file I/O,
6473 and behaviors of various editing commands.
6474
6475 Setting this to nil does not do anything.
6476 */ );
6477   enable_multibyte_characters = 1;
6478 }
6479
6480 void
6481 complex_vars_of_file_coding (void)
6482 {
6483   staticpro (&Vcoding_system_hash_table);
6484   Vcoding_system_hash_table =
6485     make_lisp_hash_table (50, HASH_TABLE_NON_WEAK, HASH_TABLE_EQ);
6486
6487   the_codesys_prop_dynarr = Dynarr_new (codesys_prop);
6488   dump_add_root_struct_ptr (&the_codesys_prop_dynarr, &codesys_prop_dynarr_description);
6489
6490 #define DEFINE_CODESYS_PROP(Prop_Type, Sym) do  \
6491 {                                               \
6492   struct codesys_prop csp;                      \
6493   csp.sym = (Sym);                              \
6494   csp.prop_type = (Prop_Type);                  \
6495   Dynarr_add (the_codesys_prop_dynarr, csp);    \
6496 } while (0)
6497
6498   DEFINE_CODESYS_PROP (CODESYS_PROP_ALL_OK,  Qmnemonic);
6499   DEFINE_CODESYS_PROP (CODESYS_PROP_ALL_OK,  Qeol_type);
6500   DEFINE_CODESYS_PROP (CODESYS_PROP_ALL_OK,  Qeol_cr);
6501   DEFINE_CODESYS_PROP (CODESYS_PROP_ALL_OK,  Qeol_crlf);
6502   DEFINE_CODESYS_PROP (CODESYS_PROP_ALL_OK,  Qeol_lf);
6503   DEFINE_CODESYS_PROP (CODESYS_PROP_ALL_OK,  Qpost_read_conversion);
6504   DEFINE_CODESYS_PROP (CODESYS_PROP_ALL_OK,  Qpre_write_conversion);
6505 #ifdef MULE
6506   DEFINE_CODESYS_PROP (CODESYS_PROP_ISO2022, Qcharset_g0);
6507   DEFINE_CODESYS_PROP (CODESYS_PROP_ISO2022, Qcharset_g1);
6508   DEFINE_CODESYS_PROP (CODESYS_PROP_ISO2022, Qcharset_g2);
6509   DEFINE_CODESYS_PROP (CODESYS_PROP_ISO2022, Qcharset_g3);
6510   DEFINE_CODESYS_PROP (CODESYS_PROP_ISO2022, Qforce_g0_on_output);
6511   DEFINE_CODESYS_PROP (CODESYS_PROP_ISO2022, Qforce_g1_on_output);
6512   DEFINE_CODESYS_PROP (CODESYS_PROP_ISO2022, Qforce_g2_on_output);
6513   DEFINE_CODESYS_PROP (CODESYS_PROP_ISO2022, Qforce_g3_on_output);
6514   DEFINE_CODESYS_PROP (CODESYS_PROP_ISO2022, Qshort);
6515   DEFINE_CODESYS_PROP (CODESYS_PROP_ISO2022, Qno_ascii_eol);
6516   DEFINE_CODESYS_PROP (CODESYS_PROP_ISO2022, Qno_ascii_cntl);
6517   DEFINE_CODESYS_PROP (CODESYS_PROP_ISO2022, Qseven);
6518   DEFINE_CODESYS_PROP (CODESYS_PROP_ISO2022, Qlock_shift);
6519   DEFINE_CODESYS_PROP (CODESYS_PROP_ISO2022, Qno_iso6429);
6520   DEFINE_CODESYS_PROP (CODESYS_PROP_ISO2022, Qescape_quoted);
6521   DEFINE_CODESYS_PROP (CODESYS_PROP_ISO2022, Qinput_charset_conversion);
6522   DEFINE_CODESYS_PROP (CODESYS_PROP_ISO2022, Qoutput_charset_conversion);
6523
6524   DEFINE_CODESYS_PROP (CODESYS_PROP_CCL,     Qencode);
6525   DEFINE_CODESYS_PROP (CODESYS_PROP_CCL,     Qdecode);
6526 #ifdef UTF2000
6527   DEFINE_CODESYS_PROP (CODESYS_PROP_ALL_OK,  Qdisable_composition);
6528   DEFINE_CODESYS_PROP (CODESYS_PROP_ALL_OK,  Quse_entity_reference);
6529 #endif
6530 #endif /* MULE */
6531   /* Need to create this here or we're really screwed. */
6532   Fmake_coding_system
6533     (Qraw_text, Qno_conversion,
6534      build_string ("Raw text, which means it converts only line-break-codes."),
6535      list2 (Qmnemonic, build_string ("Raw")));
6536
6537   Fmake_coding_system
6538     (Qbinary, Qno_conversion,
6539      build_string ("Binary, which means it does not convert anything."),
6540      list4 (Qeol_type, Qlf,
6541             Qmnemonic, build_string ("Binary")));
6542
6543 #ifdef UTF2000
6544   Fmake_coding_system
6545     (Qutf_8_mcs, Qutf8,
6546      build_string
6547      ("Coding-system of UTF-8 with Multiple Coded-character-Sets extension."),
6548      list2 (Qmnemonic, build_string ("MTF8")));
6549 #endif
6550
6551   Fdefine_coding_system_alias (Qno_conversion, Qraw_text);
6552
6553   Fdefine_coding_system_alias (Qfile_name, Qbinary);
6554
6555   Fdefine_coding_system_alias (Qterminal, Qbinary);
6556   Fdefine_coding_system_alias (Qkeyboard, Qbinary);
6557
6558   /* Need this for bootstrapping */
6559   fcd->coding_category_system[CODING_CATEGORY_NO_CONVERSION] =
6560     Fget_coding_system (Qraw_text);
6561
6562 #ifdef UTF2000
6563   fcd->coding_category_system[CODING_CATEGORY_UTF8]
6564    = Fget_coding_system (Qutf_8_mcs);
6565 #endif
6566
6567 #if defined(MULE) && !defined(UTF2000)
6568   {
6569     size_t i;
6570
6571     for (i = 0; i < countof (fcd->ucs_to_mule_table); i++)
6572       fcd->ucs_to_mule_table[i] = Qnil;
6573   }
6574   staticpro (&mule_to_ucs_table);
6575   mule_to_ucs_table = Fmake_char_table(Qgeneric);
6576 #endif /* defined(MULE) && !defined(UTF2000) */
6577 }