惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
Check Point Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
W
WeLiveSecurity
T
Troy Hunt's Blog
Project Zero
Project Zero
Security Archives - TechRepublic
Security Archives - TechRepublic
Attack and Defense Labs
Attack and Defense Labs
Google DeepMind News
Google DeepMind News
T
Threat Research - Cisco Blogs
T
Tenable Blog
Jina AI
Jina AI
Recorded Future
Recorded Future
T
The Exploit Database - CXSecurity.com
N
News | PayPal Newsroom
P
Palo Alto Networks Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
G
GRAHAM CLULEY
A
Arctic Wolf
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The Register - Security
The Register - Security
Last Week in AI
Last Week in AI
P
Privacy & Cybersecurity Law Blog
Microsoft Azure Blog
Microsoft Azure Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
SecWiki News
SecWiki News
S
Schneier on Security
有赞技术团队
有赞技术团队
IT之家
IT之家
美团技术团队
Cisco Talos Blog
Cisco Talos Blog
NISL@THU
NISL@THU
P
Proofpoint News Feed
C
CERT Recently Published Vulnerability Notes
Hacker News: Ask HN
Hacker News: Ask HN
罗磊的独立博客
博客园_首页
Cyberwarzone
Cyberwarzone
Forbes - Security
Forbes - Security
H
Hacker News: Front Page
爱范儿
爱范儿
云风的 BLOG
云风的 BLOG
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Webroot Blog
Webroot Blog
Latest news
Latest news
D
DataBreaches.Net
Know Your Adversary
Know Your Adversary
P
Privacy International News Feed
宝玉的分享
宝玉的分享
Simon Willison's Weblog
Simon Willison's Weblog
N
News and Events Feed by Topic

jdhao's digital space

Conversion between base64 and OpenCV or PIL Image 腾讯云对象存储博客图床开启 CDN 加速(不需要购买额外域名) Search and Replace in Multiple Files in Vim/Neovim Change Table Column Width in LaTeX Image or Table Side by Side in LaTeX LaTeX 并排显示图像或表格 Firenvim: Neovim inside Your Browser Content inside HTML tags missing in Latest Hugo? Creating Markdown Front Matter with Ultisnips Labelme JSON 标注格式转 voc XML 格式 Nifty Nvim Techniques That Make My Life Easier -- Series 6 macOS 下如何为视频制作字幕 Running Command Asynchronously inside Neovim Resolving Merge Conflict after Git Stash Pop Pylint: command not found? A Hands-on Experience with Neovim's Built-in LSP Support How to Convert PDF to Images with Imagemagick 互联网上常用缩略语集锦 File Backup in Neovim Converting PDF Pages to Images with Poppler Nifty Nvim Techniques That Make My Life Easier -- Series 5 Neovim Configuration for System-wide Use How to sort a list of tuple or list in Python -- lambda or itemgetter? Building A Vim Statusline from Scratch 人类第一颗原子弹爆炸始末 Distributed Training in PyTorch with Horovod Learning Expect Programming Essential Knowledge about SSH Nifty LaTeX Techniques -- Series 1 更改 Adsense 邮寄地址,重新寄送 PIN Mintty Tips and Configurations Generating Table of Contents for Markdown with Tagbar Convert Python Script to Exe on Windows with Pyinstaller Ubuntu on Windows Missing after Windows Update 使用代理加速 Mac 终端下载速度 My Experience with Several Zsh Plugin Managers 深圳租房小记 How to Install zplug inside Docker Container Why don't settings inside bashrc or bash_profile take effect? Setting Up Locale in Linux 谷歌 Adsense 申请及在 Hugo 中的配置 How to Write Algorithm Pseudo Code in LaTeX Nifty Nvim Techniques That Make My Life Easier -- Series 4 A Few Grammar Questions in Writing How to Read and Write Images with Unicode Paths in OpenCV Creating A Professional Table in LaTeX with booktabs Linux Tips and Tricks -- s1 JPEG Image Orientation and Exif How Do I Show the Current File Path In Neovim? JPEG Image Quality in PIL Difference between view, reshape, transpose and permute in PyTorch Convert PIL or OpenCV Image to Bytes without Saving to Disk Fast Movement and Navigation Inside Vim or Neovim Unintuitive Behaviour of Case Sensitivity in Python glob Binding Keys in Zsh 几把机械键盘试用体验 Nvim Autocompletion with Deoplete Converting Markdown to Beautiful PDF with Pandoc Exclusive and Inclusive Motion in Neovim/Vim Nifty Nvim Techniques Which Make My Life Easier -- Series 3 Why Doesn't Jedi Autocompletion Work for Some Methods Vim-like Editing inside Browser Markdown 生成 HTML 时汉字之间出现多余空格问题 小米 9 安装谷歌商店(Google Play Store)与相关配置 Create Mappings That Take A Count in Neovim Spell Checking in Nvim English Words Completion inside Neovim/Vim How to Use Python Inside Vim Script with Neovim Nifty Little Nvim Techniques to Make My Life Easier -- Series 2 Setting up Ultisnips for Neovim Mac 上罗技 M590 鼠标设置 Nifty Little Nvim Techniques to Make My Life Easier -- Series 1 A Complete Guide on Writing LaTeX with Vimtex in Neovim Manipulating Images with Alpha Channels in Pillow Sublime Text Regular Expression Cheat Sheet Cropping Rotated Rectangles from Image with OpenCV Boosting Your Productivity on Terminal with Zsh and Plugins 最新版 Rime 输入法使用 (2022 更新) Display Image with Pillow inside Ubuntu on Windows Faster Directory Navigation with z.lua Cmder Advanced Configurations Nvim-qt Settings on Windows 10 Tmux Plugin Install and Management How to Debug Python Code in Terminal Markdown Writing and Previewing in Neovim -- A Complete Guide Line Number Settings for More Efficient Movement in Neovim 两个大规模中文语料库介绍以及处理 Windows 系统下几款程序员不可不用的神器 我的 2018 阅读清单 A Complete Guide to Neovim Configuration for Python Development How Is Newline Handled in Python and Various Editors? Two Issues Related to ImageFont Module in PIL 在 Listary 中调用 GoldenDict 或欧路词典查单词 Reading and Writing Text Files on Windows The Mathematics behind Font Shapes --- Bézier Curves and More 快速识别图片字体:字体识别工具介绍 Deoplete Failed to Load at Startup after Updating Python neovim Package What Is The Difference between pip, pip3 and pip3.6 Shipped with Anaconda3? Windows 10 系统下 Neovim 安装与配置 How to Use shutil.move() on Windows and Linux
How to Create Proper Folding for Vim/Nvim Configuration
2019-08-16 · via jdhao's digital space
Folded config

Introduction#

I started using Neovim about a year ago. During the process, I have been constantly evolving my configuration (the init.vim file): adding some settings and plugins and dropping others. At its peak, my init.vim has over 1600 lines of settings and comments. Managing a configuration of this size requires grouping the relevant settings into different sections or even subsections. This is when I started thinking about folding my configuration properly. The end result is shown in the title image.

Nvim offers several methods to fold a file:

I found that fold-expr and fold-marker is easy to use and understand. In this article, I only introduce these two methods.

Folding with Marker#

When we fold with a marker, Nvim will create a fold where the fold marker appears. The default fold marker is {{{ (for opening a fold) and }}} (for closing a fold). To fold the Nvim config with marker, you have to use marker as the folding method:

To indicate the fold level, you can append a number after the fold marker. I show an example config using fold markers below:

"{{{ Some settings
"{{{2 Plugin install
call plug#begin(expand('~/.local/share/nvim/plugged'))
Plug 'neoclide/coc.nvim', {'do': './install.sh'}
Plug 'Shougo/neco-vim'
Plug 'neoclide/coc-neco'
call plug#end()
"}}}2

"{{{2 Built-in options
set number
set relativenumber
set pyxversion=3
set foldmethod=marker
set wildoptions=pum
"}}}2
"}}}1

"{{{ Color schemes
set background=dark
color desert
"}}}

In the above sample configuration, I define two level 1 sections. Inside the first level 1 section, there are two level 2 sub-sections.

If you open Nvim with the above configuration:

nvim -u init.vim init.vim

the folding is like the following:

+-- 17 lines: Some settings ··········································

+--  4 lines: Color schemes···········································

Two level 1 folds will be shown. Go to the first level 1 fold and use zo to open the fold. Now the buffer will be shown as the following:

"{{{ Some settings
+---  7 lines: Plugin install·········································

+---  7 lines: Built-in options········································
"}}}1

+--  4 lines: Color schemes···········································

In the closed fold line, there are some texts shown to indicate the meaning of this fold and how many lines have been folded1. It is called foldtext in Nvim. By default, the foldtext option will use the function foldtext() to evaluate the opening fold line and return a reasonable string as the fold text. See the foldtext() doc for details. If you are not satisfied with the style of the default fold text, you may define your fold text function to replace the foldtext(). We will cover that later in this post.

Folding with Expression#

Folding with marker is not flexible enough since you have to use the marker and indicate the folding level by appending a number behind the marker. Folding with expression is more flexible and powerful.

To fold Nvim config with an expression, you have to use expr for the foldmethod option and define your custom folding function:

set foldmethod=expr
set foldexpr=VimFolds(v:lnum)

In the above settings, we define the folding function VimFolds(), which will evaluate each line of the config and return its folding level. The variable v:lnum is a special variable which indicates the current line the folding function is evaluating. That is where the power of fold-expr resides: you can structure your configuration the way you want and use the folding function to parse the config and returns the correct folding level for each line.

With custom folding expression, we can define our own fold indicator. For example, I am currently using the number of { to indicate the level of a folding:

  • "{: level 1
  • "{{: level 2
  • "{{{: level 3
  • ……

I use the following folding function to parse the configuration:

function! VimFolds(lnum)
    " get content of current line and the line below
    let l:cur_line = getline(a:lnum)
    let l:next_line = getline(a:lnum+1)

    if l:cur_line =~# '^"{'
        return '>' . (matchend(l:cur_line, '"{*') - 1)
    else
        if l:cur_line ==# '' && (matchend(l:next_line, '"{*') - 1) == 1
            return 0
        else
            return '='
        endif
    endif
endfunction

For lines starting with "{, the above function will extract the number of curly braces and return its folding level. For empty lines which are followed by a level 1 fold, its folding level is 0, which means that this line is not in a fold and will not be folded. For other lines, its folding level is the same as the previous line.

The format for the folding level can be found in :h fold-expr.

Custom Folding Text#

Now that we can define the folding level by the folding expression. We need to customize the folding text as well. Or the fold text produced by the default foldtext() function will look ugly:

+-- 21 lines: { Some settings··················································

+-- 27 lines: { Custom functions···············································

+--  4 lines: { Color schemes··················································

To customize the fold text, as I have mentioned earlier, we need to create a custom fold text function to produce the folding text we want.

Below I show a custom folding text function:

function! MyFoldText()
    let line = getline(v:foldstart)
    let folded_line_num = v:foldend - v:foldstart
    let line_text = substitute(line, '^"{\+', '', 'g')
    let fillcharcount = &textwidth - len(line_text) - len(folded_line_num)
    return '+'. repeat('-', 4) . line_text . repeat('.', fillcharcount) . ' (' . folded_line_num . ' L)'
endfunction

In the above function, v:foldstart and v:foldend are the special variable provided by Vim for a particular folding level. We need to set the foldtext option to use the custom function:

set foldtext=MyFoldText()

Reopen Nvim and now the fold text becomes:

Some settings  -------------------------------------------------------- (20 L)···········

Custom functions  ----------------------------------------------------- (26 L)···········

Color schemes  --------------------------------------------------------- (3 L)···········

The trailing · characters at the end of each folding line is added by Nvim if there are spaces after the fold text in the current window. If you do not want these trailing characters, you can add the following setting to Nvim config:

" note that there is a space character behind backslash
set fillchars=fold:\

Conclusion#

In this post, I introduced how to create folding for the Nvim configuration file and use custom folding text for a fold. With this knowledge, you can create fancy foldings and folding text as you want.

References#