Hi, can you help with nvim 0.7 statusline customization for init.vim?
Assistant
Certainly! To customize the statusline in Neovim 0.7 using your init.vim configuration file, you can use the command to define the content and style of your statusline. Neovim statusline can include a variety of information such as the file name, file type, encoding, position in the file, git branch, and more.
User
So consider a statusline that has two groups, one on the left and one on the right. Left has filename and right has line number. How would this set statusline entry look like?
Assistant
To create a statusline in Neovim with the filename on the left and the line number on the right, you can set your statusline in the init.vim like this:
set laststatus=2
set statusline=%f " Set the filename on the left
set statusline+=%= " The equal sign centers the statusline
set statusline+=%l/%L " Set the current line number/total lines on the right
Let's break down what each part does:
%f: This displays the file name.
%=: This is used to split the statusline into two sections; it ensures that anything after %= is right-aligned.
%l/%L: This shows the current line number followed by the total number of lines in the file (e.g., 12/100).
After you have added this to your init.vim, the statusline will show the file name on the left and the line number/total lines on the right side of the statusline. When the window width is not sufficient to show both sides simultaneously, the right side will have priority because it is after %=.
Remember to reload your init.vim using or by restarting Neovim to see these changes in effect.
User
This answer looks nice. How would you update this statusline to truncate the right group first?
Assistant
In Neovim, by default, if the statusline content cannot fit into the available space of the window, the right-most sections (those after the %=) will generally be truncated first. However, if you want more control and ensure that the right group is truncated before the left group, you can use the %< marker in the left group to specify the truncation point more explicitly.
Here is how you might configure your statusline in the init.vim to ensure the right side (line number) is truncated first if there's not enough space:
set laststatus=2
set statusline=%f " Filename on the left
set statusline+=%< " Truncation point after the filename
set statusline+=%= " Split the statusline (left-aligned to left, right-aligned to right)
set statusline+=%l/%L " Current line number / Total lines on the right
User
In my Neovim 0.7, given "set statusline=%f%=%<%l" should show filename and line number, with line number truncated first to the left. But after the line number has been truncated, nvim begins to truncate the filename on the right side. Is there a way to have the line-number truncate first, and then after the first truncation point, truncate the filename from the left. Without functions. ?
Assistant
You're facing a situation where you want complex truncation behavior in the statusline that isn't directly supported through the basic statusline formats that Neovim provides. However, the good news is that this behavior is indeed achievable using the right combination of the truncation items (%<, %=, and %>) without resorting to functions.
Let's try to construct the statusline so that the right side (%l in your case) truncates first, but when it is completely truncated, the filename then begins to truncate from the right:
set laststatus=2
set statusline=%f " Filename on the left
set statusline+=%> " Set a truncation point for the left items
set statusline+=%= " Equal sign splits the statusline
set statusline+=%<%l " Line number on the right with a truncation point before it
User
Nvim 0.7 does not recognize the "%>". Is this a hallucination, and can you find another way to truncate the left items starting from the left.
Assistant
I apologize for the confusion; %> is indeed not a valid statusline item in Neovim or Vim, and my mention of it was incorrect. There is no direct way to achieve the exact truncation behavior you're seeking using only basic syntax, as Neovim's built-in options for truncation are quite limited.
User
In init.vim, is there a way to set the statusline, then set the statusline again, using a function call using the statusline var as a parameter ?
Assistant
User
Assuming let foobar=0, how would one insert the foobar variable contents into statusline?
Assistant
To insert the contents of a variable into the statusline in Neovim or Vim, you can use the %{} expression. This expression allows you to evaluate Vimscript within the statusline and insert the result.
For instance, if you have a variable foobar set to 0, you can insert its content into the statusline with the following command in your init.vim:
let foobar=0
set statusline=%{foobar}
With this setting, the statusline will display the current value of foobar whenever it's updated. If you want to add more context or combine the variable with other statusline items, you can concatenate them like so:
let foobar=0
set statusline=%f\ %=Foobar:\ %{foobar}\ %l/%L
In this setup:
%f will display the filename.
User
How to set (let?) variable barfoo so that it's value is the statusbar ?
Assistant
In Neovim or Vim, the statusline can be set using the set statusline=... command to define its appearance and content. If you want to store the entire current value of your statusline into a variable, you can assign it like this:
let barfoo = &statusline
User
Suppose the statusline is set with "set statusline=%f%<%=%l" in init.vim. There is also:
function! FormatSL()
endfunction
Assistant
If you have a simple statusline set in your init.vim with set statusline=%f%<%=%l and an empty FormatSL function, and you want to use this function to process or set the statusline, you need to add some logic into the FormatSL function to construct the desired statusline string and then return it.
Let's assume you want the FormatSL function to take the current buffer's filename and the line number and format them with some additional text or logic. Here is an example of how you might define the function and utilize it in the :
User
Is there a way to get the evaluated status line length?
Assistant
User
Good work!
Assistant
Thank you! I'm glad to help. If you have any more questions or need further assistance with Neovim, Vim, or any other topics, feel free to ask. Happy coding!
set statusline
Here's a sample configuration for your init.vim that sets up a custom statusline:
" Enable the statusline always
set laststatus=2
" Define custom statusline
set statusline=%f " File name
set statusline+=%m " Modified flag [+] for altered buffer
set statusline+=%r " Read-only flag [RO] if RO
set statusline+=%h " Help buffer flag [Help] if help buffer
set statusline+=%w " Preview window flag [Preview] if preview window
set statusline+=%= " Separation between left and right statusline items
set statusline+=%-14.(%l,%c%V%) " Line number, column number, virtual column number
set statusline+=%< " Truncate here if necessary
set statusline+=%-14.(%p%%) " Percentage through the file
set statusline+=%-14.(%{strftime('%c')}) " Current system time
set statusline+=%-14.(%Y) " File type
" Add as many items as you like using +=
" For coloring, define highlight groups and link them to default ones
highlight User1 guifg=#ffffff guibg=#ff0000 ctermfg=white ctermbg=red
" Usage in statusline: %1* to start using User1 group, %* to stop using it
set statusline+=%1* WARNING %*
In the above example:
%f displays the file name.
%m shows if the buffer is modified.
%r indicates if the file is read-only.
%h indicates if the buffer is a help buffer.
%w indicates if the window is a preview window.
%=% separates the left and right sections of the statusline.
%l, %c, %V display the current line number, column number, and virtual column number respectively.
%p%% shows the percentage through the file.
%{strftime('%c')} inserts the current system time.
%Y shows the file type.
highlight User1 defines a new highlight group for coloring, which you can reference in your statusline with %1*.
You can adjust and add to this template based on what information you want to display and how you want it to look.
Remember to reload your init.vim or restart Neovim to see the changes take effect. To reload your configuration within Neovim, you can use the command:
:source $MYVIMRC
This will load the changes without needing to restart your Neovim editor.
:source $MYVIMRC
The %< marker indicates that if truncation is needed, it should happen after the filename but before the line number information on the right.
With this configuration:
The left group (%f) will be displayed fully unless the window is too narrow to show anything else.
The right group (%l/%L) will be truncated in favor of preserving the left group.
Remember that because %= is used to center the statusline, the right side in our case, being positioned after %=, will already truncate first when there's not enough room for both sides. Adding the %< simply makes this behavior explicit, reinforcing that the left group should be favored for display.
Again, make sure to reload your init.vim or restart Neovim to see the changes.
Explanation:
%> specifies that text on its left will only start truncating once the text on its right has been completely truncated. This will affect the %f part of the statusline, standing for the filename.
%= still separates left and right parts.
%< on the right side sets the truncation point for the line number %l.
The behavior you want should now be manifested as follows: The line number will be truncated first due to the %< on the right side of the %=. When it's fully truncated and more space is needed, truncation will jump to the %f part, which will now start to truncate from the right due to the presence of %> on its left.
Remember, after updating your init.vim, you either need to reload it (:source $MYVIMRC) or restart Neovim for the changes to take effect.
statusline
However, I understand you want to avoid using functions, but the reality is that for advanced formatting and truncation control beyond what is offered by the basic statusline items, using Vimscript functions is often the only solution.
If you are open to using a minimal function, you could achieve your desired behavior by computing the available space for the filename and manually truncating it if needed before setting the statusline. Here is a minimal example of how to do this:
function! TruncatedFilename()
let winwidth = winwidth(0)
let filepath = expand('%:t') " Filename only
let linenum_info = ' ' . line('.') " Prefix line number with a space
if winwidth < len(filepath) + len(linenum_info)
let filepath = filepath[: winwidth - len(linenum_info) - 3] . "..."
endif
return filepath
endfunction
set statusline=%!TruncatedFilename()%=%l
In the TruncatedFilename function:
We get the window width with winwidth(0).
We retrieve the filename with expand('%:t').
We define what will appear on the right side with the current line number line('.').
If the window width is not enough to show both the filename and the line number, we manually truncate the filename and append an ellipsis.
Then in the statusline, we call the function with %!TruncatedFilename() before the split %= and we put the line number %l on the right side.
Even though you wanted to avoid functions, I wanted to provide you with a full picture of what can be done in case you reconsider. If you prefer to stick strictly with statusline items, the closest you can get is the built-in left-side truncation using the %< marker as previously mentioned:
set laststatus=2
set statusline=%f " Filename on the left
set statusline+=%< " Indicate truncation from the right side if needed
set statusline+=%= " Separation between left and right sections
set statusline+=%l " Line number on the right
With this setup, Neovim will try to show as much of the filename as possible before truncating, and then the line number will be truncated first from the right side, based on the earlier discussion.
Yes, in init.vim, you can define a custom function to modify the statusline and then call that function to update the statusline. This can be useful if you want to apply more complex logic or conditional formatting that isn't achievable with the standard statusline syntax.
Here's a simple example to illustrate how a function can take the current statusline setting as a parameter, modify it, and then set it again:
Define a Vimscript function within your init.vim that takes the current statusline as a parameter, performs some modification (for this example, we'll append the current line number to it), and then sets the statusline:
function! UpdateStatusline(current)
let l:modified_statusline = a:current . ' %= Line:%l/%L'
" The %= to ensure right alignment, followed by current line and total lines
execute 'set statusline=' . l:modified_statusline
endfunction
" Initial statusline setting
set statusline=%f " Set the filename on the left
" Call the UpdateStatusline function to modify and set the statusline
call UpdateStatusline(&statusline)
Explanation:
We define a function UpdateStatusline which takes the parameter current, representing the current statusline value.
Inside this function, we modify the statusline by adding more information to it (in the example, the line number with %= Line:%l/%L).
We then use execute to set the statusline with the newly constructed string.
Initially, we set the statusline to include the filename (%f).
Finally, we call the UpdateStatusline function with call UpdateStatusline(&statusline) passing the current statusline setting.
This approach allows you to perform modifications to the statusline dynamically within a function, although your specific use case may vary, so adjust the function body accordingly.
Make sure to reload your init.vim or restart Neovim for the changes to apply.
Keep in mind that directly calling a function to set the statusline is generally not the usual way to manage dynamic status lines. A more typical approach involves setting the statusline to a string that includes function calls, using %{...} syntax, where the function returns part of the statusline dynamically. Hence, the function is evaluated every time the status line is redrawn:
function! LineInfo()
return 'Line:%l/%L'
endfunction
" Directly include function call in statusline setting
set statusline=%f\ %= " Filename and setup for right alignment
set statusline+=%{LineInfo()} " Append the result of LineInfo function
This latter approach is more efficient and ensures the status line updates automatically, as functions within %{...} are evaluated each time the status line needs to be redrawn.
%=% is a separator that aligns the rest of the items to the right of the statusline.
Foobar: is a static text label showing before the variable value.
%{foobar} inserts the value of the variable foobar.
%l/%L shows the current line over the total number of lines.
If the value of foobar changes and you want to see the updated value in the statusline, you'll need to trigger a statusline refresh. Usually, the statusline is updated when certain events occur, like moving the cursor or editing the buffer. If you need to update it programmatically, you can use :redrawstatus.
Remember to reload your init.vim or source it using :source % from the Neovim command mode (the '%' is a shortcut for the current file path) so that changes take effect.
The & symbol is used to get the value of an option in Vimscript. In this case, &statusline retrieves the current value of the statusline setting.
Keep in mind that the statusline option can include special characters and expressions, so if you retrieve it and later want to set the statusline to the value stored in barfoo, you would do so with the let command and the &:
let &statusline = barfoo
However, if you want the barfoo variable to reflect the real-time evaluated string of the statusline (with all statusline expressions processed and replaced), that's not directly possible as the statusline option holds the setting, not the evaluated result. The real-time evaluation of the statusline is handled internally by Neovim/Vim every time the status is redrawn.
For persistent and dynamic elements like buffer name, line number, column number, etc., these elements are evaluated on the fly, and their representation is not stored in a string variable but is part of the statusline's definition that gets interpreted whenever the statusline is rendered.
Suppose you want a variable to dynamically reflect a particular piece of information normally displayed in the statusline, like the filename. In that case, you'll need to set up an autocommand to update your variable whenever related events occur. For example:
autocmd BufEnter,BufReadPost,FileReadPost * let barfoo = expand('%:t')
This autocommand updates the barfoo variable to hold the filename of the current buffer each time you enter a buffer or a file is read. The expand('%:t') is used to get the tail of the current file's path, which means just the filename.
To reiterate, the statusline's setting string and its visual representation are distinctly different: the former defines how to construct the latter upon each redraw of the status line.
FormatSL
statusline
function! FormatSL()
let l:fname = expand('%:t') " Get the filename
let l:linenum = line('.') " Get the line number
" Construct your formatted status line string here
let l:new_statusline = l:fname . ' - Line: ' . l:linenum
return l:new_statusline
endfunction
" Set the statusline to use the FormatSL function
set statusline=%!FormatSL()
" If you want to append more statusline items after your custom function processing
" you can do it like this
" set statusline+=%{other_statusline_item}
In this FormatSL function:
The expand('%:t') function returns the filename of the file in the current buffer.
The line('.') function returns the current line number.
We then construct a string with our custom format and return it.
By setting the statusline with %!FormatSL(), we're telling it to call our custom FormatSL function to get the string that should be displayed. Each time the status line needs to be redrawn, Neovim will call this function and use its return value as the status line.
Remember, this is a very simple example. Depending on what you want to accomplish, you might need to add more complex formatting and additional information to your status line within the FormatSL function.
After you've updated your init.vim file with these changes, you can either restart Neovim or source your init.vim file with :source $MYVIMRC to apply the changes.
In Vim and Neovim, getting the exact length of the evaluated status line (as it appears on the screen) is not directly provided as a built-in function. The statusline option allows you to specify the format of the status line using a set of special characters and expressions, but the actual evaluation and rendering are done internally and not exposed to the user for querying.
However, if you are trying to dynamically adjust content in your statusline and need to prevent overflow or control truncation, you might experiment with the winwidth() function, which returns the width of the window. By comparing your status line elements' character lengths with the window's width, you can implement custom truncation.
For example, you can create a Vimscript function that calculates whether the formatted status line would exceed the window width and then trims it as needed:
function! CustomStatusLine()
" Calculate window width
let win_width = winwidth(0)
" Your statusline elements
let file_name = expand('%:t')
let line_info = 'Line '.line('.').' of '.line('$')
" Start constructing the status line (you can add more elements here)
let status_line_content = file_name . ' ' . line_info
" Calculate length: assume 1 extra space for padding between elements
let status_line_length = len(status_line_content) + 1
" Check if the status line is too long for the window and truncate if needed
if status_line_length > win_width
let remaining_space = win_width - len(line_info) - 4 " 4 = ellipsis + padding
let file_name = file_name[:remaining_space] . '...'
endif
" Return the potentially truncated status line
return file_name . ' ' . line_info
endfunction
" Set the statusline to use the CustomStatusLine function
set statusline=%!CustomStatusLine()
Remember that the actual visual length of elements on the status line may differ from the character lengths due to various factors such as the use of special characters, escape sequences, or variable-width fonts. Therefore, this approach does not guarantee pixel-perfect accuracy, but it does offer a way to dynamically manage the contents of the status line based on the available window width.
Keep in mind that if you use syntax such as %{...} in your status line, these expressions are evaluated at runtime, and you need to calculate their potential lengths within such runtime-evaluated functions, making it quite complex to perform exact measurements without actually rendering the line.
For precise rendering and length calculations, you would need to rely on a more advanced status line plugin or external tooling, but Vim and Neovim itself do not expose a simple means to calculate the evaluated length of the status line text as it appears after rendering.