cameron-wags / rainbow_csv.nvim

Neovim port of mechatroner/rainbow_csv
MIT License
96 stars 4 forks source link
csv neovim neovim-plugin syntax-highlighting

Rainbow CSV (nvim lua port)

WARNING

This port is a lightly-tested side project. Use at your own risk.

If functionality is important to you, please use the original rainbow_csv.

Why port?

I love rainbow_csv, but I wanted :RainbowAlign to run faster. Porting to lua made it a few times faster.

Installation

With packer.nvim:

use {
    'cameron-wags/rainbow_csv.nvim',
    config = function()
        require 'rainbow_csv'.setup()
    end,
    -- optional lazy-loading below
    module = {
        'rainbow_csv',
        'rainbow_csv.fns'
    },
    ft = {
        'csv',
        'tsv',
        'csv_semicolon',
        'csv_whitespace',
        'csv_pipe',
        'rfc_csv',
        'rfc_semicolon'
    }
}

With lazy.nvim:

{
    'cameron-wags/rainbow_csv.nvim',
    config = true,
    ft = {
        'csv',
        'tsv',
        'csv_semicolon',
        'csv_whitespace',
        'csv_pipe',
        'rfc_csv',
        'rfc_semicolon'
    },
    cmd = {
        'RainbowDelim',
        'RainbowDelimSimple',
        'RainbowDelimQuoted',
        'RainbowMultiDelim'
    }
}

No additional steps required - Rainbow CSV will work out of the box.

Overview

Main features:

There are 4 ways to enable csv columns highlighting:

  1. CSV autodetection based on file content and/or extension
  2. Manual CSV delimiter selection with :RainbowDelim command with cursor over the delimiter
  3. Manual CSV delimiter selection with :RainbowMultiDelim for multi-character delimiters selecting them in "VISUAL" mode
  4. Explicitly activate one of the built-in filetypes, e.g. :set ft=csv

The core functionality of the plugin is written in pure vimscript, no additional libraries required.

Rainbow CSV Screenshot

Plugin description

Built-in and autogenerated filetypes

Rainbow CSV has 7 built-in CSV filetypes and infinite number of autogenerated filetypes.
Each Rainbow CSV filetype is mapped to a separator and "policy" which describes additional properties e.g. if separator can be escaped inside double quoted field.
If user uses :RainbowDelim or :RainbowMultiDelim to select a separator that doesn't map to one of the built-in filetypes, Rainbow CSV will dynamically generate the filetype syntax file and put it into the "syntax" folder.
List of built-in filetypes:

Filetype Separator Extension Properties
csv , (comma) .csv Ignored inside double-quoted fields
tsv \t (TAB) .tsv .tab
csv_semicolon ; (semicolon) Ignored inside double-quoted fields
csv_whitespace whitespace Consecutive whitespaces are merged
csv_pipe | (pipe)
rfc_csv , (comma) Same as "csv" but allows multiline fields
rfc_semicolon ; (semicolon) Same as "csv_semicolon" but allows multiline fields

Associating file extensions with CSV dialects

In most cases the built-in autodetection algorithm should correctly detect correct CSV dialect for all CSV tables that you open in Vim, but if you have disabled the autodetection algorithm or don't want to rely on it for some reason, you can manually associate file extensions with available csv dialects.
Example: to associate ".dat" extension with "csv_pipe" dialect and ".csv" extension with "csv_semicolon" add the folowing lines to your .vimrc:

autocmd BufNewFile,BufRead *.csv   set filetype=csv_semicolon
autocmd BufNewFile,BufRead *.dat   set filetype=csv_pipe

Working with multiline CSV fields

In rare cases some CSV files can contain double-quoted fields spanning multiple lines.
To work with such files you can set filetype to either "rfc_csv" or "rfc_semicolon" e.g. :set ft=rfc_csv.
Syntax highlighting for rfc_csv and rfc_semicolon dialects can sometimes go out of sync with the file content, use :syntax sync fromstart command in that case.
rfc_csv and rfc_semicolon are fully supported by RBQL which among other things allows you to easily convert them to line-by-line CSV by replacing newlines in fields with sequences of 4 spaces or something like that.
rfc_csv and rfc_semicolon take their name from RFC 4180 memo with which they are fully compatible.

Built-in RBQL query language

Rainbow CSV comes with built-in lightweight RBQL SQL-like query engine. To run an RBQL query either press F5 (:RbSelect command) or enter the query in vim command line e.g. :Select a1, a2
As soon as you finish entering ":select" (or ":update") and press whitespace, the plugin will show column names in the status line.

Demonstration of rainbow_csv highlighting and RBQL queries

demo_screencast

In this demo python expressions were used, but JavaScript is also available.

Rainbow highlighting for non-table files

You can use rainbow highlighting and RBQL even for non-csv/tsv files.
E.g. you can highlight records in log files, one-line xmls and other delimited records.
You can even highlight function arguments in your programming language using comma or comma+whitespaces as a delimiter for :RainbowDelim or :RainbowMultiDelim commands.
And you can always turn off the rainbow highlighting using :NoRainbowDelim command.

Key Mappings

Key mappings are only assigned for files with active rainbow highlighting

Key Action
F5 Start query editing for the current csv file
F5 Execute currently edited query
F7 Copy query result set to the parent buffer

You can disable these mappings by setting let g:disable_rainbow_key_mappings = 1

Commands

:RainbowDelim

Mark current file as a table and highlight it's columns in rainbow colors. Character under the cursor will be used as a delimiter. The delimiter will be saved in a config file for future vim sessions.

You can also use this command for non-csv files, e.g. to highlight function arguments
in source code in different colors. To return back to original syntax highlighting run :NoRainbowDelim

:RainbowMultiDelim

Same as :RainbowDelim, but works with multicharacter separators. Visually select the multicharacter separator (e.g. ~#~) and run :RainbowMultiDelim command.

:NoRainbowDelim

Disable rainbow columns highlighting for the current file.

:RainbowComment

Mark the character under the cursor as the comment prefix, e.g. #. By default Rainbow CSV doesn't highlight comments in CSV files.
You can also use :RainbowCommentMulti to mark a visual selection as a multicharacter comment prefix

:NoRainbowComment

Disable all comments for the current CSV file.
This command is especially useful when you have set g:rainbow_comment_prefix variable and want to exclude just one particular file.

:CSVLint

The linter checks the following:

:RainbowAlign

Align CSV columns with whitespaces.
Don't run this command if you treat leading and trailing whitespaces in fields as part of the data.
You can edit aligned CSV file in Vim column-edit mode (Ctrl+v).

:RainbowShrink

Remove leading and trailing whitespaces from all fields. Opposite to RainbowAlign

:Select ...

Allows to enter RBQL select query as vim command. e.g. :Select a1, a2 order by a1

:Update ...

Allows to enter RBQL update query as vim command. e.g. :Update a1 = a1 + " " + a2

:RainbowName \<name>

Assign any name to the current table. You can use this name in join operation instead of the table path. E.g.

JOIN customers ON a1 == b1

intead of:

JOIN /path/to/my/customers/table ON a1 == b1

Configuration

g:disable_rainbow_hover

Set to 1 to stop showing info about the column under the cursor in Vim command line
Example:

let g:disable_rainbow_hover = 1

g:rainbow_hover_debounce_ms

Max frequency column hover info is calculated when moving the cursor rapidly. Set to 0 to disable this behavior. Example:

let g:rainbow_hover_debounce_ms = 300

g:disable_rainbow_statusline

Set to 1 to stop modifying 'statusline' settings when rainbow csv features are enabled. Example:

let g:disable_rainbow_statusline = 1

g:rcsv_delimiters

Default: ["\t", ",", ";", "|"] List of separators to try for content-based autodetection
You can add or remove values from the list. Example:

let g:rcsv_delimiters = ["\t", ",", "^", "~#~"]

g:disable_rainbow_csv_autodetect

Set to 1 to disable CSV autodetection mechanism
Example:

let g:disable_rainbow_csv_autodetect = 1

Manual delimiter selection would still be possible. You can also manually associate specific file extensions with 'csv' or 'tsv' filetypes

g:rainbow_comment_prefix

Default: ''
A string to use as a comment prefix for all CSV files you open in Vim.
This setting is helpful if you are dealing with lots of CSV files which consistently use the same comment prefix e.g. '#' or '>>'
If you want to enable comments on file-by-file basis, use the :RainbowComment or :RainbowCommentMulti commands instead.
To cancel the effect of g:rainbow_comment_prefix just for the current file use :NoRainbowComment command.

g:rcsv_max_columns

Default: 30

Autodetection will fail if buffer has more than g:rcsv_max_columns columns.
You can increase or decrease this limit.

g:rcsv_colorpairs

List of color name pairs to customize rainbow highlighting.
Each entry in the list is a pair of two colors: the first color is for terminal mode, the second one is for GUI mode.
Example:

let g:rcsv_colorpairs = [['red', 'red'], ['blue', 'blue'], ['green', 'green'], ['magenta', 'magenta'], ['NONE', 'NONE'], ['darkred', 'darkred'], ['darkblue', 'darkblue'], ['darkgreen', 'darkgreen'], ['darkmagenta', 'darkmagenta'], ['darkcyan', 'darkcyan']]

g:multiline_search_range

Default: 10
This settings is only relevant for rfc_csv and rfc_semicolon dialects.
If some multiline records contain more lines that this value, hover info will not work correctly. It is not recommended to significantly increase this value because it will have negative impact on hover info performance

g:disable_rainbow_key_mappings

Disable default key mappings introduced by the extension

g:rbql_backend_language

Default: python Supported values: 'python', 'js'

Scripting language to use in RBQL expressions.

g:rbql_encoding

Default: utf-8 Supported values: 'utf-8', 'latin-1'

CSV files encoding for RBQL.

g:rbql_output_format

Default: input
Supported values: tsv, csv, input

Format of RBQL result set tables.

Essentially format is a pair: delimiter + quoting policy.
This setting for example can be used to convert files between tsv and csv format:

g:rbql_use_system_python

Set to 1 to use system python interpreter for RBQL queries instead of the python interpreter built into your vim/neovim editor.

g:rbql_with_headers

If most of the CSV files that you work with have headers, you can set this value to 1. In this case RBQL will treat first records in files as headers by default.
Example: :let g:rbql_with_headers = 1
You can also adjust (or override) this setting by adding WITH (header) or WITH (noheader) to the end of your RBQL queries.

RBQL (Rainbow Query Language) Description

RBQL is an eval-based SQL-like query engine for (not only) CSV file processing. It provides SQL-like language that supports SELECT queries with Python or JavaScript expressions.
RBQL is best suited for data transformation, data cleaning, and analytical queries.
RBQL is distributed with CLI apps, text editor plugins, Python and JS libraries.

Official Site

Main Features

Limitations:

Supported SQL Keywords (Keywords are case insensitive)

All keywords have the same meaning as in SQL queries. You can check them online

RBQL variables

RBQL for CSV files provides the following variables which you can use in your queries:

UPDATE statement

UPDATE query produces a new table where original values are replaced according to the UPDATE expression, so it can also be considered a special type of SELECT query.

Aggregate functions and queries

RBQL supports the following aggregate functions, which can also be used with GROUP BY keyword:
COUNT, _ARRAYAGG, MIN, MAX, SUM, AVG, VARIANCE, MEDIAN

Limitation: aggregate functions inside Python (or JS) expressions are not supported. Although you can use expressions inside aggregate functions.
E.g. MAX(float(a1) / 1000) - valid; MAX(a1) / 1000 - invalid.
There is a workaround for the limitation above for _ARRAYAGG function which supports an optional parameter - a callback function that can do something with the aggregated array. Example:
SELECT a2, ARRAY_AGG(a1, lambda v: sorted(v)[:5]) GROUP BY a2 - Python; SELECT a2, ARRAY_AGG(a1, v => v.sort().slice(0, 5)) GROUP BY a2 - JS

JOIN statements

Join table B can be referenced either by its file path or by its name - an arbitrary string which the user should provide before executing the JOIN query.
RBQL supports STRICT LEFT JOIN which is like LEFT JOIN, but generates an error if any key in the left table "A" doesn't have exactly one matching key in the right table "B".
Table B path can be either relative to the working dir, relative to the main table or absolute.
Limitation: JOIN statements can't contain Python/JS expressions and must have the following form: _<JOIN_KEYWORD> (/path/to/table.tsv | tablename ) ON a... == b... [AND a... == b... [AND ... ]]

SELECT EXCEPT statement

SELECT EXCEPT can be used to select everything except specific columns. E.g. to select everything but columns 2 and 4, run: SELECT * EXCEPT a2, a4
Traditional SQL engines do not support this query mode.

UNNEST() operator

UNNEST(list) takes a list/array as an argument and repeats the output record multiple times - one time for each value from the list argument.
Example: SELECT a1, UNNEST(a2.split(';'))

LIKE() function

RBQL does not support LIKE operator, instead it provides "like()" function which can be used like this: SELECT * where like(a1, 'foo%bar')

WITH (header) and WITH (noheader) statements

You can set whether the input (and join) CSV file has a header or not using the environment configuration parameters which could be --with_headers CLI flag or GUI checkbox or something else. But it is also possible to override this selection directly in the query by adding either WITH (header) or WITH (noheader) statement at the end of the query. Example: select top 5 NR, * with (header)

User Defined Functions (UDF)

RBQL supports User Defined Functions
You can define custom functions and/or import libraries in two special files:

Examples of RBQL queries

With Python expressions

With JavaScript expressions

General info

Comparison of Rainbow CSV technology with traditional graphical column alignment

Advantages

Disadvantages

References

Rainbow CSV and similar plugins in other editors:

RBQL

Related vim plugins:

Rainbow CSV name and original implementation was significantly influenced by rainbow_parentheses Vim plugin.

There also exists an old vim syntax file csv_color which, despite it's name, can highlight only *.tsv files.
And, of course, there is csv.vim