diff options
| author | JINNOUCHI Yasushi <me@delphinus.dev> | 2021-01-31 18:55:17 +0900 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-01-31 10:55:17 +0100 |
| commit | 1ca1e7ccba203752f7b7f89c2bd3aca13586d460 (patch) | |
| tree | 18dca4487c1a34759b3e7a26a6e8e2c93a1a767f /lua/telescope/utils.lua | |
| parent | 4e0dfa2e705cd34b315315ed4740683988ef5403 (diff) | |
fix: Multi byte truncate for displayer (#464)
This is needed for calling strdisplaywidth() from Lua loop.
See https://github.com/nvim-telescope/telescope.nvim/issues/414
See https://github.com/neovim/neovim/blob/a1ed941a7881122fda2fd48e71e890ed55e4d08e/src/nvim/eval/funcs.c#L9845-L9858
Co-authored-by: Simon Hauser <Simon-Hauser@outlook.de>
Diffstat (limited to 'lua/telescope/utils.lua')
| -rw-r--r-- | lua/telescope/utils.lua | 82 |
1 files changed, 82 insertions, 0 deletions
diff --git a/lua/telescope/utils.lua b/lua/telescope/utils.lua index 913c9a2..9cfc23c 100644 --- a/lua/telescope/utils.lua +++ b/lua/telescope/utils.lua @@ -202,4 +202,86 @@ function utils.get_os_command_output(cmd) return Job:new({ command = command, args = cmd }):sync() end +utils.strdisplaywidth = (function() + if jit then + local ffi = require('ffi') + ffi.cdef[[ + typedef unsigned char char_u; + int linetabsize_col(int startcol, char_u *s); + ]] + + return function(str, col) + local startcol = col or 0 + local s = ffi.new('char[?]', #str + 1) + ffi.copy(s, str) + return ffi.C.linetabsize_col(startcol, s) - startcol + end + else + return function(str, col) + return #str - (col or 0) + end + end +end)() + +utils.utf_ptr2len = (function() + if jit then + local ffi = require('ffi') + ffi.cdef[[ + typedef unsigned char char_u; + int utf_ptr2len(const char_u *const p); + ]] + + return function(str) + local c_str = ffi.new('char[?]', #str + 1) + ffi.copy(c_str, str) + return ffi.C.utf_ptr2len(c_str) + end + else + return function(str) + return str == '' and 0 or 1 + end + end +end)() + +function utils.strcharpart(str, nchar, charlen) + local nbyte = 0 + if nchar > 0 then + while nchar > 0 and nbyte < #str do + nbyte = nbyte + utils.utf_ptr2len(str:sub(nbyte + 1)) + nchar = nchar - 1 + end + else + nbyte = nchar + end + + local len = 0 + if charlen then + while charlen > 0 and nbyte + len < #str do + local off = nbyte + len + if off < 0 then + len = len + 1 + else + len = len + utils.utf_ptr2len(str:sub(off + 1)) + end + charlen = charlen - 1 + end + else + len = #str - nbyte + end + + if nbyte < 0 then + len = len + nbyte + nbyte = 0 + elseif nbyte > #str then + nbyte = #str + end + if len < 0 then + len = 0 + elseif nbyte + len > #str then + len = #str - nbyte + end + + return str:sub(nbyte + 1, nbyte + len) +end + return utils |
