/vim-sort-folds

Sort vim folds based on their first line

Primary LanguagePythonMIT LicenseMIT

SortFolds

GitHub Workflow Status

Overview


(Demo \w SimpylFold, colorscheme xoria256)

Sorting folds is not easily possible in vanilla vim. You could join all lines in a fold, sort and split them up again; however, it is time consuming and tedious.

This little plugin solves that issue: It sorts a visually selected region while keeping closed folds intact. Since folds can be created in a variety of ways, it is therefore straight-forward to sort arbitrary groups of text based on their first line.

One use-case (demonstrated above and the original motivation for this plugin) is to sort functions alphabetically after the fact.

Furthermore, it is possible to sort based on other lines than then first.

Requirements

  • Python 3.5+ (3.4+ should be fine, but tests only cover Python 3.5+)
  • Relatively recent version of vim (8.0.0+, no guarantees about 7.x.x)/neovim with support for Python 3.
    • vim: 8.0.0+, 7.x.x are untested but might still work… tested again HEAD
    • neovim: all versions supported, currently testing against the latest stable (v0.4.4) and HEAD.

Python 2

The last Python 2 compatible commit is still available as tag last-py2.

Installation

SortFolds is compatible with most plugin managers for vim. Just drop the following line in your .vimrc:

Plugin 'obreitwi/vim-sort-folds' (for Vundle)

Plug 'obreitwi/vim-sort-folds' (for vim-plug)

Mappings

Per default, sorting visually selected folds is mapped to <leader>sf, if available, but can be easily remapped.

Configuration

You can ignore case when sorting by modifying this variable:

let g:sort_folds_ignore_case = 1

Default is 0

Custom key-function

Sometimes you need to sort folds by some custom key. For this reason, you can define a custom sort function in Python that maps fold contents (essentially a list of lines) to a a key (a string) by which the fold will be sorted.

Afterwards, you need to set g:sort_folds_key_function to the name of the function.

Example: Sort BibTeX-entries by key only, but not entry type

BibTeX-entries can be of several types (article, book, inproceedings, online, to name a few…). However, we might want to sort them by citekey regardless of type.

Hence, we might add a piece of code to extract the citekey:

py3 <<EOF
def get_citekey(fold):
    # very crude extraction without regexes
    return fold[0].split("{")[1].split(",")[0]

import sort_folds
sort_folds.register_key_function(get_citekey)
EOF

autocmd FileType bib let sort_folds_key_function="get_citekey"

Note: get_citekey is already part of the builtin functions.