]> git.lizzy.rs Git - linenoise.git/blob - utf8.h
Add support for utf-8 display width
[linenoise.git] / utf8.h
1 #ifndef UTF8_UTIL_H
2 #define UTF8_UTIL_H
3
4 #ifdef __cplusplus
5 extern "C" {
6 #endif
7
8 /**
9  * UTF-8 utility functions
10  *
11  * (c) 2010-2016 Steve Bennett <steveb@workware.net.au>
12  *
13  * See LICENCE for licence details.
14  */
15
16 #ifndef USE_UTF8
17 #include <ctype.h>
18
19 /* No utf-8 support. 1 byte = 1 char */
20 #define utf8_strlen(S, B) ((B) < 0 ? (int)strlen(S) : (B))
21 #define utf8_strwidth(S, B) utf8_strlen((S), (B))
22 #define utf8_tounicode(S, CP) (*(CP) = (unsigned char)*(S), 1)
23 #define utf8_index(C, I) (I)
24 #define utf8_charlen(C) 1
25  #define utf8_width(C) 1
26
27 #else
28 /**
29  * Converts the given unicode codepoint (0 - 0x1fffff) to utf-8
30  * and stores the result at 'p'.
31  *
32  * Returns the number of utf-8 characters
33  */
34 int utf8_fromunicode(char *p, unsigned uc);
35
36 /**
37  * Returns the length of the utf-8 sequence starting with 'c'.
38  *
39  * Returns 1-4, or -1 if this is not a valid start byte.
40  *
41  * Note that charlen=4 is not supported by the rest of the API.
42  */
43 int utf8_charlen(int c);
44
45 /**
46  * Returns the number of characters in the utf-8
47  * string of the given byte length.
48  *
49  * Any bytes which are not part of an valid utf-8
50  * sequence are treated as individual characters.
51  *
52  * The string *must* be null terminated.
53  *
54  * Does not support unicode code points > \u1fffff
55  */
56 int utf8_strlen(const char *str, int bytelen);
57
58 /**
59  * Calculates the display width of the first 'charlen' characters in 'str'.
60  * See utf8_width()
61  */
62 int utf8_strwidth(const char *str, int charlen);
63
64 /**
65  * Returns the byte index of the given character in the utf-8 string.
66  *
67  * The string *must* be null terminated.
68  *
69  * This will return the byte length of a utf-8 string
70  * if given the char length.
71  */
72 int utf8_index(const char *str, int charindex);
73
74 /**
75  * Returns the unicode codepoint corresponding to the
76  * utf-8 sequence 'str'.
77  *
78  * Stores the result in *uc and returns the number of bytes
79  * consumed.
80  *
81  * If 'str' is null terminated, then an invalid utf-8 sequence
82  * at the end of the string will be returned as individual bytes.
83  *
84  * If it is not null terminated, the length *must* be checked first.
85  *
86  * Does not support unicode code points > \u1fffff
87  */
88 int utf8_tounicode(const char *str, int *uc);
89
90 /**
91  * Returns the width (in characters) of the given unicode codepoint.
92  * This is 1 for normal letters and 0 for combining characters and 2 for wide characters.
93  */
94 int utf8_width(int ch);
95
96 #endif
97
98 #ifdef __cplusplus
99 }
100 #endif
101
102 #endif