1/*
2 * Copyright (C) 1984-2023  Mark Nudelman
3 *
4 * You may distribute under the terms of either the GNU General Public
5 * License or the Less License, as specified in the README file.
6 *
7 * For more information, see the README file.
8 */
9
10
11/*
12 * Functions to define the character set
13 * and do things specific to the character set.
14 */
15
16#include "less.h"
17#if HAVE_LOCALE
18#include <locale.h>
19#include <ctype.h>
20#include <langinfo.h>
21#endif
22
23#include "charset.h"
24#include "xbuf.h"
25
26#if MSDOS_COMPILER==WIN32C
27#define WIN32_LEAN_AND_MEAN
28#include <windows.h>
29#endif
30
31extern int bs_mode;
32
33public int utf_mode = 0;
34
35/*
36 * Predefined character sets,
37 * selected by the LESSCHARSET environment variable.
38 */
39struct charset {
40	char *name;
41	int *p_flag;
42	char *desc;
43} charsets[] = {
44		{ "ascii",              NULL,       "8bcccbcc18b95.b" },
45		{ "utf-8",              &utf_mode,  "8bcccbcc18b95.b126.bb" },
46		{ "iso8859",            NULL,       "8bcccbcc18b95.33b." },
47		{ "latin3",             NULL,       "8bcccbcc18b95.33b5.b8.b15.b4.b12.b18.b12.b." },
48		{ "arabic",             NULL,       "8bcccbcc18b95.33b.3b.7b2.13b.3b.b26.5b19.b" },
49		{ "greek",              NULL,       "8bcccbcc18b95.33b4.2b4.b3.b35.b44.b" },
50		{ "greek2005",          NULL,       "8bcccbcc18b95.33b14.b35.b44.b" },
51		{ "hebrew",             NULL,       "8bcccbcc18b95.33b.b29.32b28.2b2.b" },
52		{ "koi8-r",             NULL,       "8bcccbcc18b95.b." },
53		{ "KOI8-T",             NULL,       "8bcccbcc18b95.b8.b6.b8.b.b.5b7.3b4.b4.b3.b.b.3b." },
54		{ "georgianps",         NULL,       "8bcccbcc18b95.3b11.4b12.2b." },
55		{ "tcvn",               NULL,       "b..b...bcccbccbbb7.8b95.b48.5b." },
56		{ "TIS-620",            NULL,       "8bcccbcc18b95.b.4b.11b7.8b." },
57		{ "next",               NULL,       "8bcccbcc18b95.bb125.bb" },
58		{ "dos",                NULL,       "8bcccbcc12bc5b95.b." },
59		{ "windows-1251",       NULL,       "8bcccbcc12bc5b95.b24.b." },
60		{ "windows-1252",       NULL,       "8bcccbcc12bc5b95.b.b11.b.2b12.b." },
61		{ "windows-1255",       NULL,       "8bcccbcc12bc5b95.b.b8.b.5b9.b.4b." },
62		{ "ebcdic",             NULL,       "5bc6bcc7bcc41b.9b7.9b5.b..8b6.10b6.b9.7b9.8b8.17b3.3b9.7b9.8b8.6b10.b.b.b." },
63		{ "IBM-1047",           NULL,       "4cbcbc3b9cbccbccbb4c6bcc5b3cbbc4bc4bccbc191.b" },
64		{ NULL, NULL, NULL }
65};
66
67/*
68 * Support "locale charmap"/nl_langinfo(CODESET) values, as well as others.
69 */
70struct cs_alias {
71	char *name;
72	char *oname;
73} cs_aliases[] = {
74	{ "UTF-8",              "utf-8" },
75	{ "utf8",               "utf-8" },
76	{ "UTF8",               "utf-8" },
77	{ "ANSI_X3.4-1968",     "ascii" },
78	{ "US-ASCII",           "ascii" },
79	{ "latin1",             "iso8859" },
80	{ "ISO-8859-1",         "iso8859" },
81	{ "latin9",             "iso8859" },
82	{ "ISO-8859-15",        "iso8859" },
83	{ "latin2",             "iso8859" },
84	{ "ISO-8859-2",         "iso8859" },
85	{ "ISO-8859-3",         "latin3" },
86	{ "latin4",             "iso8859" },
87	{ "ISO-8859-4",         "iso8859" },
88	{ "cyrillic",           "iso8859" },
89	{ "ISO-8859-5",         "iso8859" },
90	{ "ISO-8859-6",         "arabic" },
91	{ "ISO-8859-7",         "greek" },
92	{ "IBM9005",            "greek2005" },
93	{ "ISO-8859-8",         "hebrew" },
94	{ "latin5",             "iso8859" },
95	{ "ISO-8859-9",         "iso8859" },
96	{ "latin6",             "iso8859" },
97	{ "ISO-8859-10",        "iso8859" },
98	{ "latin7",             "iso8859" },
99	{ "ISO-8859-13",        "iso8859" },
100	{ "latin8",             "iso8859" },
101	{ "ISO-8859-14",        "iso8859" },
102	{ "latin10",            "iso8859" },
103	{ "ISO-8859-16",        "iso8859" },
104	{ "IBM437",             "dos" },
105	{ "EBCDIC-US",          "ebcdic" },
106	{ "IBM1047",            "IBM-1047" },
107	{ "KOI8-R",             "koi8-r" },
108	{ "KOI8-U",             "koi8-r" },
109	{ "GEORGIAN-PS",        "georgianps" },
110	{ "TCVN5712-1",         "tcvn" },
111	{ "NEXTSTEP",           "next" },
112	{ "windows",            "windows-1252" }, /* backward compatibility */
113	{ "CP1251",             "windows-1251" },
114	{ "CP1252",             "windows-1252" },
115	{ "CP1255",             "windows-1255" },
116	{ NULL, NULL }
117};
118
119#define IS_BINARY_CHAR  01
120#define IS_CONTROL_CHAR 02
121
122static char chardef[256];
123static char *binfmt = NULL;
124static char *utfbinfmt = NULL;
125public int binattr = AT_STANDOUT|AT_COLOR_BIN;
126
127static struct xbuffer user_wide_array;
128static struct xbuffer user_ubin_array;
129static struct xbuffer user_compose_array;
130static struct xbuffer user_prt_array;
131static struct wchar_range_table user_wide_table;
132static struct wchar_range_table user_ubin_table;
133static struct wchar_range_table user_compose_table;
134static struct wchar_range_table user_prt_table;
135
136/*
137 * Set a wchar_range_table to the table in an xbuffer.
138 */
139static void wchar_range_table_set(struct wchar_range_table *tbl, struct xbuffer *arr)
140{
141	tbl->table = (struct wchar_range *) arr->data;
142	tbl->count = arr->end / sizeof(struct wchar_range);
143}
144
145/*
146 * Skip over a "U" or "U+" prefix before a hex codepoint.
147 */
148static char * skip_uprefix(char *s)
149{
150	if (*s == 'U' || *s == 'u')
151		if (*++s == '+') ++s;
152	return s;
153}
154
155/*
156 * Parse a dash-separated range of hex values.
157 */
158static void wchar_range_get(char **ss, struct wchar_range *range)
159{
160	char *s = skip_uprefix(*ss);
161	range->first = lstrtoul(s, &s, 16);
162	if (s[0] == '-')
163	{
164		s = skip_uprefix(&s[1]);
165		range->last = lstrtoul(s, &s, 16);
166	} else
167	{
168		range->last = range->first;
169	}
170	*ss = s;
171}
172
173/*
174 * Parse the LESSUTFCHARDEF variable.
175 */
176static void ichardef_utf(char *s)
177{
178	xbuf_init(&user_wide_array);
179	xbuf_init(&user_ubin_array);
180	xbuf_init(&user_compose_array);
181	xbuf_init(&user_prt_array);
182
183	if (s != NULL)
184	{
185		while (s[0] != '\0')
186		{
187			struct wchar_range range;
188			wchar_range_get(&s, &range);
189			if (range.last == 0)
190			{
191				error("invalid hex number(s) in LESSUTFCHARDEF", NULL_PARG);
192				quit(QUIT_ERROR);
193			}
194			if (*s++ != ':')
195			{
196				error("missing colon in LESSUTFCHARDEF", NULL_PARG);
197				quit(QUIT_ERROR);
198			}
199			switch (*s++)
200			{
201			case 'b':
202				xbuf_add_data(&user_ubin_array, (unsigned char *) &range, sizeof(range));
203				break;
204			case 'c':
205				xbuf_add_data(&user_compose_array, (unsigned char *) &range, sizeof(range));
206				break;
207			case 'w':
208				xbuf_add_data(&user_wide_array, (unsigned char *) &range, sizeof(range));
209				xbuf_add_data(&user_prt_array, (unsigned char *) &range, sizeof(range));
210				break;
211			case 'p': case '.':
212				xbuf_add_data(&user_prt_array, (unsigned char *) &range, sizeof(range));
213				break;
214			case '\0':
215				s--;
216				break;
217			default:
218				/* Ignore unknown character attribute. */
219				break;
220			}
221			if (s[0] == ',') ++s;
222		}
223	}
224	wchar_range_table_set(&user_wide_table, &user_wide_array);
225	wchar_range_table_set(&user_ubin_table, &user_ubin_array);
226	wchar_range_table_set(&user_compose_table, &user_compose_array);
227	wchar_range_table_set(&user_prt_table, &user_prt_array);
228}
229
230/*
231 * Define a charset, given a description string.
232 * The string consists of 256 letters,
233 * one for each character in the charset.
234 * If the string is shorter than 256 letters, missing letters
235 * are taken to be identical to the last one.
236 * A decimal number followed by a letter is taken to be a
237 * repetition of the letter.
238 *
239 * Each letter is one of:
240 *      . normal character
241 *      b binary character
242 *      c control character
243 */
244static void ichardef(char *s)
245{
246	char *cp;
247	int n;
248	char v;
249
250	n = 0;
251	v = 0;
252	cp = chardef;
253	while (*s != '\0')
254	{
255		switch (*s++)
256		{
257		case '.':
258			v = 0;
259			break;
260		case 'c':
261			v = IS_CONTROL_CHAR;
262			break;
263		case 'b':
264			v = IS_BINARY_CHAR|IS_CONTROL_CHAR;
265			break;
266
267		case '0': case '1': case '2': case '3': case '4':
268		case '5': case '6': case '7': case '8': case '9':
269			if (ckd_mul(&n, n, 10) || ckd_add(&n, n, s[-1] - '0'))
270				goto invalid_chardef;
271			continue;
272
273		default:
274		invalid_chardef:
275			error("invalid chardef", NULL_PARG);
276			quit(QUIT_ERROR);
277			/*NOTREACHED*/
278		}
279
280		do
281		{
282			if (cp >= chardef + sizeof(chardef))
283			{
284				error("chardef longer than 256", NULL_PARG);
285				quit(QUIT_ERROR);
286				/*NOTREACHED*/
287			}
288			*cp++ = v;
289		} while (--n > 0);
290		n = 0;
291	}
292
293	while (cp < chardef + sizeof(chardef))
294		*cp++ = v;
295}
296
297/*
298 * Define a charset, given a charset name.
299 * The valid charset names are listed in the "charsets" array.
300 */
301static int icharset(char *name, int no_error)
302{
303	struct charset *p;
304	struct cs_alias *a;
305
306	if (name == NULL || *name == '\0')
307		return (0);
308
309	/* First see if the name is an alias. */
310	for (a = cs_aliases;  a->name != NULL;  a++)
311	{
312		if (strcmp(name, a->name) == 0)
313		{
314			name = a->oname;
315			break;
316		}
317	}
318
319	for (p = charsets;  p->name != NULL;  p++)
320	{
321		if (strcmp(name, p->name) == 0)
322		{
323			ichardef(p->desc);
324			if (p->p_flag != NULL)
325			{
326#if MSDOS_COMPILER==WIN32C
327				*(p->p_flag) = 1 + (GetConsoleOutputCP() != CP_UTF8);
328#else
329				*(p->p_flag) = 1;
330#endif
331			}
332			return (1);
333		}
334	}
335
336	if (!no_error) {
337		error("invalid charset name", NULL_PARG);
338		quit(QUIT_ERROR);
339	}
340	return (0);
341}
342
343#if HAVE_LOCALE
344/*
345 * Define a charset, given a locale name.
346 */
347static void ilocale(void)
348{
349	int c;
350
351	for (c = 0;  c < (int) sizeof(chardef);  c++)
352	{
353		if (isprint(c))
354			chardef[c] = 0;
355		else if (iscntrl(c))
356			chardef[c] = IS_CONTROL_CHAR;
357		else
358			chardef[c] = IS_BINARY_CHAR|IS_CONTROL_CHAR;
359	}
360}
361#endif
362
363/*
364 * Define the printing format for control (or binary utf) chars.
365 */
366public void setfmt(char *s, char **fmtvarptr, int *attrptr, char *default_fmt, int for_printf)
367{
368	if (s && utf_mode)
369	{
370		/* It would be too hard to account for width otherwise.  */
371		char constant *t = s;
372		while (*t)
373		{
374			if (*t < ' ' || *t > '~')
375			{
376				s = default_fmt;
377				goto attr;
378			}
379			t++;
380		}
381	}
382
383	if (s == NULL || *s == '\0')
384		s = default_fmt;
385	else if (for_printf &&
386	    ((*s == '*' && (s[1] == '\0' || s[2] == '\0' || strchr(s + 2, 'n'))) ||
387	     (*s != '*' && strchr(s, 'n'))))
388		/* %n is evil */
389		s = default_fmt;
390
391	/*
392	 * Select the attributes if it starts with "*".
393	 */
394 attr:
395	if (*s == '*' && s[1] != '\0')
396	{
397		switch (s[1])
398		{
399		case 'd':  *attrptr = AT_BOLD;      break;
400		case 'k':  *attrptr = AT_BLINK;     break;
401		case 's':  *attrptr = AT_STANDOUT;  break;
402		case 'u':  *attrptr = AT_UNDERLINE; break;
403		default:   *attrptr = AT_NORMAL;    break;
404		}
405		s += 2;
406	}
407	*fmtvarptr = s;
408}
409
410/*
411 *
412 */
413static void set_charset(void)
414{
415	char *s;
416
417#if MSDOS_COMPILER==WIN32C
418	/*
419	 * If the Windows console is using UTF-8, we'll use it too.
420	 */
421	if (GetConsoleOutputCP() == CP_UTF8)
422		if (icharset("utf-8", 1))
423			return;
424#endif
425
426	ichardef_utf(lgetenv("LESSUTFCHARDEF"));
427
428	/*
429	 * See if environment variable LESSCHARSET is defined.
430	 */
431	s = lgetenv("LESSCHARSET");
432	if (icharset(s, 0))
433		return;
434
435	/*
436	 * LESSCHARSET is not defined: try LESSCHARDEF.
437	 */
438	s = lgetenv("LESSCHARDEF");
439	if (!isnullenv(s))
440	{
441		ichardef(s);
442		return;
443	}
444
445#if HAVE_LOCALE
446#ifdef CODESET
447	/*
448	 * Try using the codeset name as the charset name.
449	 */
450	s = nl_langinfo(CODESET);
451	if (icharset(s, 1))
452		return;
453#endif
454#endif
455
456#if HAVE_STRSTR
457	/*
458	 * Check whether LC_ALL, LC_CTYPE or LANG look like UTF-8 is used.
459	 */
460	if ((s = lgetenv("LC_ALL")) != NULL ||
461	    (s = lgetenv("LC_CTYPE")) != NULL ||
462	    (s = lgetenv("LANG")) != NULL)
463	{
464		if (   strstr(s, "UTF-8") != NULL || strstr(s, "utf-8") != NULL
465		    || strstr(s, "UTF8")  != NULL || strstr(s, "utf8")  != NULL)
466			if (icharset("utf-8", 1))
467				return;
468	}
469#endif
470
471#if HAVE_LOCALE
472	/*
473	 * Get character definitions from locale functions,
474	 * rather than from predefined charset entry.
475	 */
476	ilocale();
477#else
478#if MSDOS_COMPILER
479	/*
480	 * Default to "dos".
481	 */
482	(void) icharset("dos", 1);
483#else
484	/*
485	 * Default to "latin1".
486	 */
487	(void) icharset("latin1", 1);
488#endif
489#endif
490}
491
492/*
493 * Initialize charset data structures.
494 */
495public void init_charset(void)
496{
497	char *s;
498
499#if HAVE_LOCALE
500	setlocale(LC_ALL, "");
501#endif
502
503	set_charset();
504
505	s = lgetenv("LESSBINFMT");
506	setfmt(s, &binfmt, &binattr, "*s<%02X>", TRUE);
507
508	s = lgetenv("LESSUTFBINFMT");
509	setfmt(s, &utfbinfmt, &binattr, "<U+%04lX>", TRUE);
510}
511
512/*
513 * Is a given character a "binary" character?
514 */
515public int binary_char(LWCHAR c)
516{
517	if (utf_mode)
518		return (is_ubin_char(c));
519	c &= 0377;
520	return (chardef[c] & IS_BINARY_CHAR);
521}
522
523/*
524 * Is a given character a "control" character?
525 */
526public int control_char(LWCHAR c)
527{
528	c &= 0377;
529	return (chardef[c] & IS_CONTROL_CHAR);
530}
531
532/*
533 * Return the printable form of a character.
534 * For example, in the "ascii" charset '\3' is printed as "^C".
535 */
536public char * prchar(LWCHAR c)
537{
538	/* {{ This buffer can be overrun if LESSBINFMT is a long string. }} */
539	static char buf[MAX_PRCHAR_LEN+1];
540
541	c &= 0377;
542	if ((c < 128 || !utf_mode) && !control_char(c))
543		SNPRINTF1(buf, sizeof(buf), "%c", (int) c);
544	else if (c == ESC)
545		strcpy(buf, "ESC");
546#if IS_EBCDIC_HOST
547	else if (!binary_char(c) && c < 64)
548		SNPRINTF1(buf, sizeof(buf), "^%c",
549		/*
550		 * This array roughly inverts CONTROL() #defined in less.h,
551		 * and should be kept in sync with CONTROL() and IBM-1047.
552		 */
553		"@ABC.I.?...KLMNO"
554		"PQRS.JH.XY.."
555		"\\]^_"
556		"......W[.....EFG"
557		"..V....D....TU.Z"[c]);
558#else
559	else if (c < 128 && !control_char(c ^ 0100))
560		SNPRINTF1(buf, sizeof(buf), "^%c", (int) (c ^ 0100));
561#endif
562	else
563		SNPRINTF1(buf, sizeof(buf), binfmt, c);
564	return (buf);
565}
566
567/*
568 * Return the printable form of a UTF-8 character.
569 */
570public char * prutfchar(LWCHAR ch)
571{
572	static char buf[MAX_PRCHAR_LEN+1];
573
574	if (ch == ESC)
575		strcpy(buf, "ESC");
576	else if (ch < 128 && control_char(ch))
577	{
578		if (!control_char(ch ^ 0100))
579			SNPRINTF1(buf, sizeof(buf), "^%c", ((char) ch) ^ 0100);
580		else
581			SNPRINTF1(buf, sizeof(buf), binfmt, (char) ch);
582	} else if (is_ubin_char(ch))
583	{
584		SNPRINTF1(buf, sizeof(buf), utfbinfmt, ch);
585	} else
586	{
587		char *p = buf;
588		if (ch >= 0x80000000)
589			ch = 0xFFFD; /* REPLACEMENT CHARACTER */
590		put_wchar(&p, ch);
591		*p = '\0';
592	}
593	return (buf);
594}
595
596/*
597 * Get the length of a UTF-8 character in bytes.
598 */
599public int utf_len(int ch)
600{
601	if ((ch & 0x80) == 0)
602		return 1;
603	if ((ch & 0xE0) == 0xC0)
604		return 2;
605	if ((ch & 0xF0) == 0xE0)
606		return 3;
607	if ((ch & 0xF8) == 0xF0)
608		return 4;
609	if ((ch & 0xFC) == 0xF8)
610		return 5;
611	if ((ch & 0xFE) == 0xFC)
612		return 6;
613	/* Invalid UTF-8 encoding. */
614	return 1;
615}
616
617/*
618 * Does the parameter point to the lead byte of a well-formed UTF-8 character?
619 */
620public int is_utf8_well_formed(char *ss, int slen)
621{
622	int i;
623	int len;
624	unsigned char *s = (unsigned char *) ss;
625
626	if (IS_UTF8_INVALID(s[0]))
627		return (0);
628
629	len = utf_len(s[0]);
630	if (len > slen)
631		return (0);
632	if (len == 1)
633		return (1);
634	if (len == 2)
635	{
636		if (s[0] < 0xC2)
637		    return (0);
638	} else
639	{
640		unsigned char mask;
641		mask = (~((1 << (8-len)) - 1)) & 0xFF;
642		if (s[0] == mask && (s[1] & mask) == 0x80)
643			return (0);
644	}
645
646	for (i = 1;  i < len;  i++)
647		if (!IS_UTF8_TRAIL(s[i]))
648			return (0);
649	return (1);
650}
651
652/*
653 * Skip bytes until a UTF-8 lead byte (11xxxxxx) or ASCII byte (0xxxxxxx) is found.
654 */
655public void utf_skip_to_lead(char **pp, char *limit)
656{
657	do {
658		++(*pp);
659	} while (*pp < limit && !IS_UTF8_LEAD((*pp)[0] & 0377) && !IS_ASCII_OCTET((*pp)[0]));
660}
661
662
663/*
664 * Get the value of a UTF-8 character.
665 */
666public LWCHAR get_wchar(constant char *p)
667{
668	switch (utf_len(p[0]))
669	{
670	case 1:
671	default:
672		/* 0xxxxxxx */
673		return (LWCHAR)
674			(p[0] & 0xFF);
675	case 2:
676		/* 110xxxxx 10xxxxxx */
677		return (LWCHAR) (
678			((p[0] & 0x1F) << 6) |
679			(p[1] & 0x3F));
680	case 3:
681		/* 1110xxxx 10xxxxxx 10xxxxxx */
682		return (LWCHAR) (
683			((p[0] & 0x0F) << 12) |
684			((p[1] & 0x3F) << 6) |
685			(p[2] & 0x3F));
686	case 4:
687		/* 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
688		return (LWCHAR) (
689			((p[0] & 0x07) << 18) |
690			((p[1] & 0x3F) << 12) |
691			((p[2] & 0x3F) << 6) |
692			(p[3] & 0x3F));
693	case 5:
694		/* 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx */
695		return (LWCHAR) (
696			((p[0] & 0x03) << 24) |
697			((p[1] & 0x3F) << 18) |
698			((p[2] & 0x3F) << 12) |
699			((p[3] & 0x3F) << 6) |
700			(p[4] & 0x3F));
701	case 6:
702		/* 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx */
703		return (LWCHAR) (
704			((p[0] & 0x01) << 30) |
705			((p[1] & 0x3F) << 24) |
706			((p[2] & 0x3F) << 18) |
707			((p[3] & 0x3F) << 12) |
708			((p[4] & 0x3F) << 6) |
709			(p[5] & 0x3F));
710	}
711}
712
713/*
714 * Store a character into a UTF-8 string.
715 */
716public void put_wchar(char **pp, LWCHAR ch)
717{
718	if (!utf_mode || ch < 0x80)
719	{
720		/* 0xxxxxxx */
721		*(*pp)++ = (char) ch;
722	} else if (ch < 0x800)
723	{
724		/* 110xxxxx 10xxxxxx */
725		*(*pp)++ = (char) (0xC0 | ((ch >> 6) & 0x1F));
726		*(*pp)++ = (char) (0x80 | (ch & 0x3F));
727	} else if (ch < 0x10000)
728	{
729		/* 1110xxxx 10xxxxxx 10xxxxxx */
730		*(*pp)++ = (char) (0xE0 | ((ch >> 12) & 0x0F));
731		*(*pp)++ = (char) (0x80 | ((ch >> 6) & 0x3F));
732		*(*pp)++ = (char) (0x80 | (ch & 0x3F));
733	} else if (ch < 0x200000)
734	{
735		/* 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
736		*(*pp)++ = (char) (0xF0 | ((ch >> 18) & 0x07));
737		*(*pp)++ = (char) (0x80 | ((ch >> 12) & 0x3F));
738		*(*pp)++ = (char) (0x80 | ((ch >> 6) & 0x3F));
739		*(*pp)++ = (char) (0x80 | (ch & 0x3F));
740	} else if (ch < 0x4000000)
741	{
742		/* 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx */
743		*(*pp)++ = (char) (0xF0 | ((ch >> 24) & 0x03));
744		*(*pp)++ = (char) (0x80 | ((ch >> 18) & 0x3F));
745		*(*pp)++ = (char) (0x80 | ((ch >> 12) & 0x3F));
746		*(*pp)++ = (char) (0x80 | ((ch >> 6) & 0x3F));
747		*(*pp)++ = (char) (0x80 | (ch & 0x3F));
748	} else
749	{
750		/* 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx */
751		*(*pp)++ = (char) (0xF0 | ((ch >> 30) & 0x01));
752		*(*pp)++ = (char) (0x80 | ((ch >> 24) & 0x3F));
753		*(*pp)++ = (char) (0x80 | ((ch >> 18) & 0x3F));
754		*(*pp)++ = (char) (0x80 | ((ch >> 12) & 0x3F));
755		*(*pp)++ = (char) (0x80 | ((ch >> 6) & 0x3F));
756		*(*pp)++ = (char) (0x80 | (ch & 0x3F));
757	}
758}
759
760/*
761 * Step forward or backward one character in a string.
762 */
763public LWCHAR step_char(char **pp, signed int dir, constant char *limit)
764{
765	LWCHAR ch;
766	int len;
767	char *p = *pp;
768
769	if (!utf_mode)
770	{
771		/* It's easy if chars are one byte. */
772		if (dir > 0)
773			ch = (LWCHAR) (unsigned char) ((p < limit) ? *p++ : 0);
774		else
775			ch = (LWCHAR) (unsigned char) ((p > limit) ? *--p : 0);
776	} else if (dir > 0)
777	{
778		len = utf_len(*p);
779		if (p + len > limit)
780		{
781			ch = 0;
782			p = (char *) limit;
783		} else
784		{
785			ch = get_wchar(p);
786			p += len;
787		}
788	} else
789	{
790		while (p > limit && IS_UTF8_TRAIL(p[-1]))
791			p--;
792		if (p > limit)
793			ch = get_wchar(--p);
794		else
795			ch = 0;
796	}
797	*pp = p;
798	return ch;
799}
800
801/*
802 * Unicode characters data
803 * Actual data is in the generated *.uni files.
804 */
805
806#define DECLARE_RANGE_TABLE_START(name) \
807	static struct wchar_range name##_array[] = {
808#define DECLARE_RANGE_TABLE_END(name) \
809	}; struct wchar_range_table name##_table = { name##_array, sizeof(name##_array)/sizeof(*name##_array) };
810
811DECLARE_RANGE_TABLE_START(compose)
812#include "compose.uni"
813DECLARE_RANGE_TABLE_END(compose)
814
815DECLARE_RANGE_TABLE_START(ubin)
816#include "ubin.uni"
817DECLARE_RANGE_TABLE_END(ubin)
818
819DECLARE_RANGE_TABLE_START(wide)
820#include "wide.uni"
821DECLARE_RANGE_TABLE_END(wide)
822
823DECLARE_RANGE_TABLE_START(fmt)
824#include "fmt.uni"
825DECLARE_RANGE_TABLE_END(fmt)
826
827/* comb_table is special pairs, not ranges. */
828static struct wchar_range comb_table[] = {
829	{0x0644,0x0622}, {0x0644,0x0623}, {0x0644,0x0625}, {0x0644,0x0627},
830};
831
832
833static int is_in_table(LWCHAR ch, struct wchar_range_table *table)
834{
835	int hi;
836	int lo;
837
838	/* Binary search in the table. */
839	if (table->table == NULL || table->count == 0 || ch < table->table[0].first)
840		return 0;
841	lo = 0;
842	hi = table->count - 1;
843	while (lo <= hi)
844	{
845		int mid = (lo + hi) / 2;
846		if (ch > table->table[mid].last)
847			lo = mid + 1;
848		else if (ch < table->table[mid].first)
849			hi = mid - 1;
850		else
851			return 1;
852	}
853	return 0;
854}
855
856/*
857 * Is a character a UTF-8 composing character?
858 * If a composing character follows any char, the two combine into one glyph.
859 */
860public int is_composing_char(LWCHAR ch)
861{
862	if (is_in_table(ch, &user_prt_table)) return 0;
863	return is_in_table(ch, &user_compose_table) ||
864	       is_in_table(ch, &compose_table) ||
865	       (bs_mode != BS_CONTROL && is_in_table(ch, &fmt_table));
866}
867
868/*
869 * Should this UTF-8 character be treated as binary?
870 */
871public int is_ubin_char(LWCHAR ch)
872{
873	if (is_in_table(ch, &user_prt_table)) return 0;
874	return is_in_table(ch, &user_ubin_table) ||
875	       is_in_table(ch, &ubin_table) ||
876	       (bs_mode == BS_CONTROL && is_in_table(ch, &fmt_table));
877}
878
879/*
880 * Is this a double width UTF-8 character?
881 */
882public int is_wide_char(LWCHAR ch)
883{
884	return is_in_table(ch, &user_wide_table) ||
885	       is_in_table(ch, &wide_table);
886}
887
888/*
889 * Is a character a UTF-8 combining character?
890 * A combining char acts like an ordinary char, but if it follows
891 * a specific char (not any char), the two combine into one glyph.
892 */
893public int is_combining_char(LWCHAR ch1, LWCHAR ch2)
894{
895	/* The table is small; use linear search. */
896	int i;
897	for (i = 0;  i < sizeof(comb_table)/sizeof(*comb_table);  i++)
898	{
899		if (ch1 == comb_table[i].first &&
900		    ch2 == comb_table[i].last)
901			return 1;
902	}
903	return 0;
904}
905
906