xref: /freebsd/contrib/less/charset.c (revision dafba19e42e78cd3d7c9264ece49ddd3d7d70da5)
1 /*
2  * Copyright (C) 1984-2025  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 	s = nl_langinfo(CODESET);
433 	if (icharset(s, 1))
434 		return;
435 #endif
436 #endif
437 
438 	/*
439 	 * Check whether LC_ALL, LC_CTYPE or LANG look like UTF-8 is used.
440 	 */
441 	if ((s = lgetenv("LC_ALL")) != NULL ||
442 	    (s = lgetenv("LC_CTYPE")) != NULL ||
443 	    (s = lgetenv("LANG")) != NULL)
444 	{
445 		if (   strstr(s, "UTF-8") != NULL || strstr(s, "utf-8") != NULL
446 		    || strstr(s, "UTF8")  != NULL || strstr(s, "utf8")  != NULL)
447 			if (icharset("utf-8", 1))
448 				return;
449 	}
450 
451 #if HAVE_LOCALE
452 	/*
453 	 * Get character definitions from locale functions,
454 	 * rather than from predefined charset entry.
455 	 */
456 	ilocale();
457 #else
458 #if MSDOS_COMPILER
459 #if MSDOS_COMPILER==WIN32C
460 	(void) icharset("utf-8", 1);
461 #else
462 	(void) icharset("dos", 1);
463 #endif
464 #else
465 	(void) icharset("utf-8", 1);
466 #endif
467 #endif
468 }
469 
470 /*
471  * Initialize charset data structures.
472  */
init_charset(void)473 public void init_charset(void)
474 {
475 	constant char *s;
476 
477 #if HAVE_LOCALE
478 	setlocale(LC_ALL, "");
479 #endif
480 
481 	set_charset();
482 
483 	s = lgetenv("LESSBINFMT");
484 	setfmt(s, &binfmt, &binattr, "*s<%02X>", TRUE);
485 
486 	s = lgetenv("LESSUTFBINFMT");
487 	setfmt(s, &utfbinfmt, &binattr, "<U+%04lX>", TRUE);
488 }
489 
490 /*
491  * Is a given character a "binary" character?
492  */
binary_char(LWCHAR c)493 public lbool binary_char(LWCHAR c)
494 {
495 	if (utf_mode)
496 		return (is_ubin_char(c));
497 	if (c >= sizeof(chardef))
498 		return TRUE;
499 	return ((chardef[c] & IS_BINARY_CHAR) != 0);
500 }
501 
502 /*
503  * Is a given character a "control" character?
504  */
control_char(LWCHAR c)505 public lbool control_char(LWCHAR c)
506 {
507 	if (c >= sizeof(chardef))
508 		return TRUE;
509 	return (chardef[c] & IS_CONTROL_CHAR);
510 }
511 
512 /*
513  * Return the printable form of a character.
514  * For example, in the "ascii" charset '\3' is printed as "^C".
515  */
prchar(LWCHAR c)516 public constant char * prchar(LWCHAR c)
517 {
518 	/* {{ Fixed buffer size means LESSBINFMT etc can be truncated. }} */
519 	static char buf[MAX_PRCHAR_LEN+1];
520 
521 	c &= 0377; /*{{type-issue}}*/
522 	if ((c < 128 || !utf_mode) && !control_char(c))
523 		SNPRINTF1(buf, sizeof(buf), "%c", (int) c);
524 	else if (c == ESC)
525 		strcpy(buf, "ESC");
526 #if IS_EBCDIC_HOST
527 	else if (!binary_char(c) && c < 64)
528 		SNPRINTF1(buf, sizeof(buf), "^%c",
529 		/*
530 		 * This array roughly inverts CONTROL() #defined in less.h,
531 		 * and should be kept in sync with CONTROL() and IBM-1047.
532 		 */
533 		"@ABC.I.?...KLMNO"
534 		"PQRS.JH.XY.."
535 		"\\]^_"
536 		"......W[.....EFG"
537 		"..V....D....TU.Z"[c]);
538 #else
539 	else if (c < 128 && !control_char(c ^ 0100))
540 		SNPRINTF1(buf, sizeof(buf), "^%c", (int) (c ^ 0100));
541 #endif
542 	else
543 		SNPRINTF1(buf, sizeof(buf), binfmt, c);
544 	return (buf);
545 }
546 
547 /*
548  * Return the printable form of a UTF-8 character.
549  */
prutfchar(LWCHAR ch)550 public constant char * prutfchar(LWCHAR ch)
551 {
552 	static char buf[MAX_PRCHAR_LEN+1];
553 
554 	if (ch == ESC)
555 		strcpy(buf, "ESC");
556 	else if (ch < 128 && control_char(ch))
557 	{
558 		if (!control_char(ch ^ 0100))
559 			SNPRINTF1(buf, sizeof(buf), "^%c", ((char) ch) ^ 0100);
560 		else
561 			SNPRINTF1(buf, sizeof(buf), binfmt, (char) ch);
562 	} else if (is_ubin_char(ch) || is_omit_char(ch))
563 	{
564 		SNPRINTF1(buf, sizeof(buf), utfbinfmt, ch);
565 	} else
566 	{
567 		char *p = buf;
568 		if (ch >= 0x80000000)
569 			ch = 0xFFFD; /* REPLACEMENT CHARACTER */
570 		put_wchar(&p, ch);
571 		*p = '\0';
572 	}
573 	return (buf);
574 }
575 
576 /*
577  * Get the length of a UTF-8 character in bytes.
578  */
utf_len(char ch)579 public int utf_len(char ch)
580 {
581 	if ((ch & 0x80) == 0)
582 		return 1;
583 	if ((ch & 0xE0) == 0xC0)
584 		return 2;
585 	if ((ch & 0xF0) == 0xE0)
586 		return 3;
587 	if ((ch & 0xF8) == 0xF0)
588 		return 4;
589 #if 0
590 	if ((ch & 0xFC) == 0xF8)
591 		return 5;
592 	if ((ch & 0xFE) == 0xFC)
593 		return 6;
594 #endif
595 	/* Invalid UTF-8 encoding. */
596 	return 1;
597 }
598 
599 /*
600  * Does the parameter point to the lead byte of a well-formed UTF-8 character?
601  */
is_utf8_well_formed(constant char * ss,int slen)602 public lbool is_utf8_well_formed(constant char *ss, int slen)
603 {
604 	int i;
605 	int len;
606 	unsigned char s0 = (unsigned char) ss[0];
607 
608 	if (IS_UTF8_INVALID(s0))
609 		return (FALSE);
610 
611 	len = utf_len(ss[0]);
612 	if (len > slen)
613 		return (FALSE);
614 	if (len == 1)
615 		return (TRUE);
616 	if (len == 2)
617 	{
618 		if (s0 < 0xC2)
619 			return (FALSE);
620 	} else
621 	{
622 		unsigned char mask = (unsigned char) (~((1 << (8-len)) - 1));
623 		if (s0 == mask && (ss[1] & mask) == 0x80)
624 			return (FALSE);
625 	}
626 
627 	for (i = 1;  i < len;  i++)
628 		if (!IS_UTF8_TRAIL(ss[i]))
629 			return (FALSE);
630 	return (TRUE);
631 }
632 
633 /*
634  * Skip bytes until a UTF-8 lead byte (11xxxxxx) or ASCII byte (0xxxxxxx) is found.
635  */
utf_skip_to_lead(constant char ** pp,constant char * limit)636 public void utf_skip_to_lead(constant char **pp, constant char *limit)
637 {
638 	do {
639 		++(*pp);
640 	} while (*pp < limit && !IS_UTF8_LEAD((*pp)[0] & 0377) && !IS_ASCII_OCTET((*pp)[0]));
641 }
642 
643 
644 /*
645  * Get the value of a UTF-8 character.
646  */
get_wchar(constant char * sp)647 public LWCHAR get_wchar(constant char *sp)
648 {
649 	constant unsigned char *p = (constant unsigned char *) sp;
650 	switch (utf_len(sp[0]))
651 	{
652 	case 1:
653 	default:
654 		/* 0xxxxxxx */
655 		return (LWCHAR)
656 			(p[0] & 0xFF);
657 	case 2:
658 		/* 110xxxxx 10xxxxxx */
659 		return (LWCHAR) (
660 			((p[0] & 0x1F) << 6) |
661 			(p[1] & 0x3F));
662 	case 3:
663 		/* 1110xxxx 10xxxxxx 10xxxxxx */
664 		return (LWCHAR) (
665 			((p[0] & 0x0F) << 12) |
666 			((p[1] & 0x3F) << 6) |
667 			(p[2] & 0x3F));
668 	case 4:
669 		/* 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
670 		return (LWCHAR) (
671 			((p[0] & 0x07) << 18) |
672 			((p[1] & 0x3F) << 12) |
673 			((p[2] & 0x3F) << 6) |
674 			(p[3] & 0x3F));
675 #if 0
676 	case 5:
677 		/* 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx */
678 		return (LWCHAR) (
679 			((p[0] & 0x03) << 24) |
680 			((p[1] & 0x3F) << 18) |
681 			((p[2] & 0x3F) << 12) |
682 			((p[3] & 0x3F) << 6) |
683 			(p[4] & 0x3F));
684 	case 6:
685 		/* 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx */
686 		return (LWCHAR) (
687 			((p[0] & 0x01) << 30) |
688 			((p[1] & 0x3F) << 24) |
689 			((p[2] & 0x3F) << 18) |
690 			((p[3] & 0x3F) << 12) |
691 			((p[4] & 0x3F) << 6) |
692 			(p[5] & 0x3F));
693 #endif
694 	}
695 }
696 
697 /*
698  * Store a character into a UTF-8 string.
699  */
put_wchar(mutable char ** pp,LWCHAR ch)700 public void put_wchar(mutable char **pp, LWCHAR ch)
701 {
702 	if (!utf_mode || ch < 0x80)
703 	{
704 		/* 0xxxxxxx */
705 		*(*pp)++ = (char) ch;
706 	} else if (ch < 0x800)
707 	{
708 		/* 110xxxxx 10xxxxxx */
709 		*(*pp)++ = (char) (0xC0 | ((ch >> 6) & 0x1F));
710 		*(*pp)++ = (char) (0x80 | (ch & 0x3F));
711 	} else if (ch < 0x10000)
712 	{
713 		/* 1110xxxx 10xxxxxx 10xxxxxx */
714 		*(*pp)++ = (char) (0xE0 | ((ch >> 12) & 0x0F));
715 		*(*pp)++ = (char) (0x80 | ((ch >> 6) & 0x3F));
716 		*(*pp)++ = (char) (0x80 | (ch & 0x3F));
717 	} else if (ch < 0x200000)
718 	{
719 		/* 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
720 		*(*pp)++ = (char) (0xF0 | ((ch >> 18) & 0x07));
721 		*(*pp)++ = (char) (0x80 | ((ch >> 12) & 0x3F));
722 		*(*pp)++ = (char) (0x80 | ((ch >> 6) & 0x3F));
723 		*(*pp)++ = (char) (0x80 | (ch & 0x3F));
724 #if 0
725 	} else if (ch < 0x4000000)
726 	{
727 		/* 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx */
728 		*(*pp)++ = (char) (0xF0 | ((ch >> 24) & 0x03));
729 		*(*pp)++ = (char) (0x80 | ((ch >> 18) & 0x3F));
730 		*(*pp)++ = (char) (0x80 | ((ch >> 12) & 0x3F));
731 		*(*pp)++ = (char) (0x80 | ((ch >> 6) & 0x3F));
732 		*(*pp)++ = (char) (0x80 | (ch & 0x3F));
733 	} else
734 	{
735 		/* 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx */
736 		*(*pp)++ = (char) (0xF0 | ((ch >> 30) & 0x01));
737 		*(*pp)++ = (char) (0x80 | ((ch >> 24) & 0x3F));
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 #endif
743 	}
744 }
745 
746 /*
747  * Step forward or backward one character in a string.
748  */
step_charc(constant char ** pp,signed int dir,constant char * limit)749 public LWCHAR step_charc(constant char **pp, signed int dir, constant char *limit)
750 {
751 	LWCHAR ch;
752 	int len;
753 	constant char *p = *pp;
754 
755 	if (!utf_mode)
756 	{
757 		/* It's easy if chars are one byte. */
758 		if (dir > 0)
759 			ch = (LWCHAR) (unsigned char) ((p < limit) ? *p++ : 0);
760 		else
761 			ch = (LWCHAR) (unsigned char) ((p > limit) ? *--p : 0);
762 	} else if (dir > 0)
763 	{
764 		if (p >= limit)
765 			ch = 0;
766 		else
767 		{
768 			len = utf_len(*p);
769 			if (p + len > limit || !is_utf8_well_formed(p, len))
770 			{
771 				ch = (LWCHAR) (unsigned char) *p++;
772 			} else
773 			{
774 				ch = get_wchar(p);
775 				p += len;
776 			}
777 		}
778 	} else
779 	{
780 		while (p > limit && IS_UTF8_TRAIL(p[-1]))
781 			p--;
782 		if (p <= limit)
783 			ch = 0;
784 		else
785 		{
786 			len = utf_len(*--p);
787 			if (p + len != *pp || !is_utf8_well_formed(p, len))
788 			{
789 				p = *pp - 1;
790 				ch = (LWCHAR) (unsigned char) *p;
791 			} else
792 			{
793 				ch = get_wchar(p);
794 			}
795 		}
796 	}
797 	*pp = p;
798 	return ch;
799 }
800 
step_char(char ** pp,signed int dir,constant char * limit)801 public LWCHAR step_char(char **pp, signed int dir, constant char *limit)
802 {
803 	constant char *p = (constant char *) *pp;
804 	LWCHAR ch = step_charc(&p, dir, limit);
805 	*pp = (char *) p;
806 	return ch;
807 }
808 
809 /*
810  * Unicode characters data
811  * Actual data is in the generated *.uni files.
812  */
813 
814 #define DECLARE_RANGE_TABLE_START(name) \
815 	static struct wchar_range name##_array[] = {
816 #define DECLARE_RANGE_TABLE_END(name) \
817 	}; struct wchar_range_table name##_table = { name##_array, countof(name##_array) };
818 
819 DECLARE_RANGE_TABLE_START(compose)
820 #include "compose.uni"
821 DECLARE_RANGE_TABLE_END(compose)
822 
823 DECLARE_RANGE_TABLE_START(ubin)
824 #include "ubin.uni"
825 DECLARE_RANGE_TABLE_END(ubin)
826 
827 DECLARE_RANGE_TABLE_START(wide)
828 #include "wide.uni"
829 DECLARE_RANGE_TABLE_END(wide)
830 
831 DECLARE_RANGE_TABLE_START(fmt)
832 #include "fmt.uni"
833 DECLARE_RANGE_TABLE_END(fmt)
834 
835 DECLARE_RANGE_TABLE_START(omit)
836 #include "omit.uni"
837 DECLARE_RANGE_TABLE_END(omit)
838 
839 /* comb_table is special pairs, not ranges. */
840 static struct wchar_range comb_table[] = {
841 	{0x0644,0x0622}, {0x0644,0x0623}, {0x0644,0x0625}, {0x0644,0x0627},
842 };
843 
844 
is_in_table(LWCHAR ch,struct wchar_range_table * table)845 static lbool is_in_table(LWCHAR ch, struct wchar_range_table *table)
846 {
847 	unsigned int hi;
848 	unsigned int lo;
849 
850 	/* Binary search in the table. */
851 	if (table->table == NULL || table->count == 0 || ch < table->table[0].first)
852 		return FALSE;
853 	lo = 0;
854 	hi = table->count - 1;
855 	while (lo <= hi)
856 	{
857 		unsigned int mid = (lo + hi) / 2;
858 		if (ch > table->table[mid].last)
859 			lo = mid + 1;
860 		else if (ch < table->table[mid].first)
861 			hi = mid - 1;
862 		else
863 			return TRUE;
864 	}
865 	return FALSE;
866 }
867 
868 /*
869  * Is a character in none of a set of specified user tables?
870  */
not_user_defined(LWCHAR ch,struct wchar_range_table * tbl1,struct wchar_range_table * tbl2,struct wchar_range_table * tbl3)871 static lbool not_user_defined(LWCHAR ch, struct wchar_range_table *tbl1, struct wchar_range_table *tbl2, struct wchar_range_table *tbl3)
872 {
873 	if (is_in_table(ch, tbl1)) return FALSE;
874 	if (is_in_table(ch, tbl2)) return FALSE;
875 	if (is_in_table(ch, tbl3)) return FALSE;
876 	return TRUE;
877 }
878 
879 /*
880  * Is a character a UTF-8 composing character?
881  * If a composing character follows any char, the two combine into one glyph.
882  */
is_composing_char(LWCHAR ch)883 public lbool is_composing_char(LWCHAR ch)
884 {
885 	if (is_in_table(ch, &user_prt_table)) return FALSE;
886 	return is_in_table(ch, &user_compose_table) ||
887 	       (is_in_table(ch, &compose_table) ||
888 	       (bs_mode != BS_CONTROL && is_in_table(ch, &fmt_table) &&
889             not_user_defined(ch, &user_prt_table, &user_ubin_table, &user_omit_table)));
890 }
891 
892 /*
893  * Should this UTF-8 character be treated as binary?
894  */
is_ubin_char(LWCHAR ch)895 public lbool is_ubin_char(LWCHAR ch)
896 {
897 	if (is_in_table(ch, &user_prt_table)) return FALSE;
898 	return is_in_table(ch, &user_ubin_table) ||
899 	       (is_in_table(ch, &ubin_table) ||
900 	       (bs_mode == BS_CONTROL && is_in_table(ch, &fmt_table) &&
901             not_user_defined(ch, &user_prt_table, &user_compose_table, &user_omit_table)));
902 }
903 
904 /*
905  * Is this a double width UTF-8 character?
906  */
is_wide_char(LWCHAR ch)907 public lbool is_wide_char(LWCHAR ch)
908 {
909 	return is_in_table(ch, &user_wide_table) ||
910 	       (is_in_table(ch, &wide_table) &&
911             not_user_defined(ch, &user_compose_table, &user_ubin_table, &user_omit_table));
912 }
913 
914 /*
915  * Is this an omittable character?
916  */
is_omit_char(LWCHAR ch)917 public lbool is_omit_char(LWCHAR ch)
918 {
919 	return is_in_table(ch, &user_omit_table) ||
920 	       (is_in_table(ch, &omit_table) &&
921             not_user_defined(ch, &user_prt_table, &user_compose_table, &user_ubin_table));
922 }
923 
924 /*
925  * Is a character a UTF-8 combining character?
926  * A combining char acts like an ordinary char, but if it follows
927  * a specific char (not any char), the two combine into one glyph.
928  */
is_combining_char(LWCHAR ch1,LWCHAR ch2)929 public lbool is_combining_char(LWCHAR ch1, LWCHAR ch2)
930 {
931 	/* The table is small; use linear search. */
932 	int i;
933 	for (i = 0;  i < countof(comb_table);  i++)
934 	{
935 		if (ch1 == comb_table[i].first &&
936 		    ch2 == comb_table[i].last)
937 			return TRUE;
938 	}
939 	return FALSE;
940 }
941