| 1 | local utf8length |
| 2 | local utf8positions |
| 3 | |
| 4 | local has_native, nativelib = pcall(require, 'obvious.lib.unicode.native') |
| 5 | |
| 6 | if has_native then |
| 7 | return nativelib |
| 8 | end |
| 9 | |
| 10 | local naughty = require 'naughty' |
| 11 | |
| 12 | naughty.notify { |
| 13 | title = 'Obvious', |
| 14 | text = 'Not using native Unicode library for obvious - it is highly recommended to compile the native library for accuracy', |
| 15 | timeout = 0, |
| 16 | } |
| 17 | |
| 18 | if utf8 then |
| 19 | utf8length = utf8.len |
| 20 | else |
| 21 | local sbyte = string.byte |
| 22 | |
| 23 | function utf8positions(s) |
| 24 | local function iter(s, pos) |
| 25 | if not pos then |
| 26 | return 1 |
| 27 | end |
| 28 | |
| 29 | local byte = sbyte(s, pos) |
| 30 | |
| 31 | if byte >= 0xf0 then |
| 32 | pos = pos + 4 |
| 33 | elseif byte >= 0xe0 then |
| 34 | pos = pos + 3 |
| 35 | elseif byte >= 0xc0 then |
| 36 | pos = pos + 2 |
| 37 | else |
| 38 | pos = pos + 1 |
| 39 | end |
| 40 | |
| 41 | if pos > #s then |
| 42 | return nil |
| 43 | end |
| 44 | |
| 45 | return pos |
| 46 | end |
| 47 | |
| 48 | if s == '' then |
| 49 | return function() end, s, nil |
| 50 | else |
| 51 | return iter, s, nil |
| 52 | end |
| 53 | end |
| 54 | |
| 55 | function utf8length(s) |
| 56 | local count = 0 |
| 57 | |
| 58 | for _ in utf8positions(s) do |
| 59 | count = count + 1 |
| 60 | end |
| 61 | |
| 62 | return count |
| 63 | end |
| 64 | end |
| 65 | |
| 66 | local function utf8sub(s, start, finish) |
| 67 | local start_byte |
| 68 | local end_byte = #s |
| 69 | |
| 70 | local charno = 1 |
| 71 | for pos in utf8positions(s) do |
| 72 | if charno == start then |
| 73 | start_byte = pos |
| 74 | |
| 75 | if not finish then |
| 76 | break |
| 77 | end |
| 78 | end |
| 79 | |
| 80 | if finish and charno == finish + 1 then |
| 81 | end_byte = pos - 1 |
| 82 | break |
| 83 | end |
| 84 | |
| 85 | charno = charno + 1 |
| 86 | end |
| 87 | |
| 88 | return string.sub(s, start_byte, end_byte) |
| 89 | end |
| 90 | |
| 91 | return { |
| 92 | length = utf8length, |
| 93 | sub = utf8sub, |
| 94 | } |