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