b0o / incline.nvim

🎈 Floating statuslines for Neovim, winbar alternative
MIT License
794 stars 14 forks source link

fix(winline): use api.nvim_strwidth to calculate lengths #5

Closed akinsho closed 2 years ago

akinsho commented 2 years ago

Whilst messing about with a more jazzy winline 👇🏿 I noticed that it was rendering with a much longer window than necessary because I was using icons. Applying this fix gives the correct length for the string passed in.

Screen Shot 2022-04-27 at 17 37 59

This image is of the corrected string.

This is because Lua's # or len function count the number of bytes rather than the cells that a string will occupy. This means that it will often over count the size of a string for usecases like TUI elements in nvim

The function to create this is

          render = function(props)
            ---@diagnostic disable-next-line: redefined-local
            local fmt, icons = string.format, as.style.icons.misc
            local bufname = vim.api.nvim_buf_get_name(props.buf)
            if bufname == '' then
              return '[No name]'
            end
            local parts = vim.split(vim.fn.fnamemodify(bufname, ':.'), '/')
            local icon, _ = require('nvim-web-devicons').get_icon(bufname, nil, { default = true })
            parts[#parts] = fmt('%s %s', icon, parts[#parts])
            return table.concat(parts, fmt(' %s ', icons.chevron_right))
          end
b0o commented 2 years ago

Thank you Akin!! I discovered this too, and I have already fixed it in my local repo. However, I did not know about vim.api.nvim_strwidth(); I was using vim.fn.strchars(). And now that I'm looking at it, I probably was using the wrong function anyway, since there is also vim.fn.strdisplaywidth(). I will take your lead and change to using nvim_strwidth because I'd rather use the nvim API whenever possible.

Sorry for not pushing my changes sooner! I am going to create a develop branch and start pushing my commits there as I make them.

akinsho commented 2 years ago

No worries @b0o I'll close this out and await your fix 👍🏾