+ int code_point = charset_code_point (Vcharset_ucs, ch, 0);
+
+ if ( (code_point < 0) || (code_point > 0x10FFFF) )
+ {
+ if (CODING_SYSTEM_USE_ENTITY_REFERENCE (str->codesys))
+ {
+ Lisp_Object rest = Vcoded_charset_entity_reference_alist;
+ Lisp_Object cell;
+ Lisp_Object ret;
+ Lisp_Object ccs;
+ int format_columns, idx;
+ char buf[16], format[16];
+
+ while (!NILP (rest))
+ {
+ cell = Fcar (rest);
+ ccs = Fcar (cell);
+ if (!NILP (ccs = Ffind_charset (ccs)))
+ {
+ if ( (code_point
+ = charset_code_point (ccs, ch, 0)) >= 0 )
+ {
+ cell = Fcdr (cell);
+ ret = Fcar (cell);
+ if (STRINGP (ret)
+ && ((idx =XSTRING_LENGTH (ret)) <= 6))
+ {
+ strncpy (format, XSTRING_DATA (ret), idx);
+ }
+ else
+ continue;
+
+ cell = Fcdr (cell);
+ ret = Fcar (cell);
+ if (INTP (ret))
+ {
+ format [idx++] = '%';
+ format_columns = XINT (ret);
+ if ( (2 <= format_columns)
+ && (format_columns <= 8) )
+ {
+ format [idx++] = '0';
+ format [idx++] = '0' + format_columns;
+ }
+ }
+
+ cell = Fcdr (cell);
+ ret = Fcar (cell);
+ if (EQ (ret, Qd))
+ format [idx++] = 'd';
+ else if (EQ (ret, Qx))
+ format [idx++] = 'x';
+ else if (EQ (ret, QX))
+ format [idx++] = 'X';
+ else
+ continue;
+ format [idx++] = 0;
+
+ sprintf (buf, format, code_point);
+ Dynarr_add (dst, '&');
+ Dynarr_add_many (dst, buf, strlen (buf));
+ Dynarr_add (dst, ';');
+ return;
+ }
+ }
+ rest = Fcdr (rest);
+ }
+ sprintf (buf, "&MCS-%08X;", ch);
+ Dynarr_add_many (dst, buf, strlen (buf));
+ return;
+ }
+ else
+ code_point = ch;
+ }
+ if (code_point <= 0x7ff)
+ {
+ Dynarr_add (dst, (code_point >> 6) | 0xc0);
+ Dynarr_add (dst, (code_point & 0x3f) | 0x80);
+ }
+ else if (code_point <= 0xffff)
+ {
+ Dynarr_add (dst, (code_point >> 12) | 0xe0);
+ Dynarr_add (dst, ((code_point >> 6) & 0x3f) | 0x80);
+ Dynarr_add (dst, (code_point & 0x3f) | 0x80);
+ }
+ else if (code_point <= 0x1fffff)
+ {
+ Dynarr_add (dst, (code_point >> 18) | 0xf0);
+ Dynarr_add (dst, ((code_point >> 12) & 0x3f) | 0x80);
+ Dynarr_add (dst, ((code_point >> 6) & 0x3f) | 0x80);
+ Dynarr_add (dst, (code_point & 0x3f) | 0x80);
+ }
+ else if (code_point <= 0x3ffffff)
+ {
+ Dynarr_add (dst, (code_point >> 24) | 0xf8);
+ Dynarr_add (dst, ((code_point >> 18) & 0x3f) | 0x80);
+ Dynarr_add (dst, ((code_point >> 12) & 0x3f) | 0x80);
+ Dynarr_add (dst, ((code_point >> 6) & 0x3f) | 0x80);
+ Dynarr_add (dst, (code_point & 0x3f) | 0x80);
+ }
+ else
+ {
+ Dynarr_add (dst, (code_point >> 30) | 0xfc);
+ Dynarr_add (dst, ((code_point >> 24) & 0x3f) | 0x80);
+ Dynarr_add (dst, ((code_point >> 18) & 0x3f) | 0x80);
+ Dynarr_add (dst, ((code_point >> 12) & 0x3f) | 0x80);
+ Dynarr_add (dst, ((code_point >> 6) & 0x3f) | 0x80);
+ Dynarr_add (dst, (code_point & 0x3f) | 0x80);
+ }