Git Product home page Git Product logo

rainbow_csv's Introduction

Rainbow CSV

rainbow_csv

Installation

Use your favorite package manager.

Vundle: Plugin 'mechatroner/rainbow_csv'
VimPlug: Plug 'mechatroner/rainbow_csv'
dein: call dein#add('mechatroner/rainbow_csv')

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

Overview

Main features:

  • Highlight CSV columns in different rainbow colors.
  • Provide info about column under the cursor
  • Provide SELECT and UPDATE queries in RBQL: SQL-like transprogramming query language.
  • Consistency check for csv files (CSVLint)
  • Align and Shrink CSV fields (add/remove trailing spaces in fields)
  • Cell-level cursor navigation

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 you run :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 use :Select command e.g. :Select a1, a2 or run :RainbowQuery command to enter query editing mode.

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.

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.

:RainbowCellGoUp

Move cursor one cell up.
Consider mapping this to Ctrl+[Up Arrow], see the "Key Mappings" section.

:RainbowCellGoDown

Move cursor one cell down.
Consider mapping this to Ctrl+[Down Arrow], see the "Key Mappings" section.

:RainbowCellGoLeft

Move cursor one cell left.
Consider mapping this to Ctrl+[Left Arrow], see the "Key Mappings" section.

:RainbowCellGoRight

Move cursor one cell right.
Consider mapping this to Ctrl+[Right Arrow], see the "Key Mappings" section.

: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:

  • consistency of double quotes usage in CSV rows
  • consistency of number of fields per CSV row

: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

:RainbowQuery

Enter RBQL Query editing mode.
When in the query editing mode, execute :RainbowQuery again to run the query.
Consider mapping :RainbowQuery to <F5> key i.e. nnoremap <F5> :RainbowQuery<CR>

: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

:RainbowCopyBack

This command only applicable for RBQL output files.
Replace the content of the original file that was used to run the RBQL query with the query result set data.

Key Mappings

Plugin does not create any new key mappings, but you can define your own in your .vimrc file.
All highlighted files have a special buffer variable b:rbcsv set to 1, so you can use this to define conditional csv-only key mappings.
For example, to conditionally map Ctrl+Arrow keys to cell navigation commands you can use this snippet:

nnoremap <expr> <C-Left> get(b:, 'rbcsv', 0) == 1 ? ':RainbowCellGoLeft<CR>' : '<C-Left>'
nnoremap <expr> <C-Right> get(b:, 'rbcsv', 0) == 1 ? ':RainbowCellGoRight<CR>' : '<C-Right>'
nnoremap <expr> <C-Up> get(b:, 'rbcsv', 0) == 1 ? ':RainbowCellGoUp<CR>' : '<C-Up>'
nnoremap <expr> <C-Down> get(b:, 'rbcsv', 0) == 1 ? ':RainbowCellGoDown<CR>' : '<C-Down>'

You can also map arrow keys unconditionally, but this will have no effect outside highlighted CSV files, e.g.

nnoremap <C-Right> :RainbowCellGoRight<CR>

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: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: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.

  • input: same format as the input table
  • tsv: doesn't allow quoted tabs inside fields.
  • csv: is Excel-compatible and allows quoted commas.

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

  • To convert csv to tsv: 1. open csv file. 2. :let g:rbql_output_format='tsv' 3. :Select *
  • To convert tsv to csv: 1. open tsv file. 2. :let g:rbql_output_format='csv' 3. :Select *

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

  • Use Python or JavaScript expressions inside SELECT, UPDATE, WHERE and ORDER BY statements
  • Supports multiple input formats
  • Result set of any query immediately becomes a first-class table on its own
  • No need to provide FROM statement in the query when the input table is defined by the current context.
  • Supports all main SQL keywords
  • Supports aggregate functions and GROUP BY queries
  • Supports user-defined functions (UDF)
  • Provides some new useful query modes which traditional SQL engines do not have
  • Lightweight, dependency-free, works out of the box

Limitations:

  • RBQL doesn't support nested queries, but they can be emulated with consecutive queries
  • Number of tables in all JOIN queries is always 2 (input table and join table), use consecutive queries to join 3 or more tables

Supported SQL Keywords (Keywords are case insensitive)

  • SELECT
  • UPDATE
  • WHERE
  • ORDER BY ... [ DESC | ASC ]
  • [ LEFT | INNER ] JOIN
  • DISTINCT
  • GROUP BY
  • TOP N
  • LIMIT N
  • AS

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:

  • a1, a2,..., a{N}
    Variable type: string
    Description: value of i-th field in the current record in input table
  • b1, b2,..., b{N}
    Variable type: string
    Description: value of i-th field in the current record in join table B
  • NR
    Variable type: integer
    Description: Record number (1-based)
  • NF
    Variable type: integer
    Description: Number of fields in the current record
  • a.name, b.Person_age, ... a.{Good_alphanumeric_column_name}
    Variable type: string
    Description: Value of the field referenced by it's "name". You can use this notation if the field in the header has a "good" alphanumeric name
  • a["object id"], a['9.12341234'], b["%$ !! 10 20"] ... a["Arbitrary column name!"]
    Variable type: string
    Description: Value of the field referenced by it's "name". You can use this notation to reference fields by arbitrary values in the header

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, ARRAY_AGG, 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 ARRAY_AGG 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 | table_name ) 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:

  • ~/.rbql_init_source.py - for Python
  • ~/.rbql_init_source.js - for JavaScript

Examples of RBQL queries

With Python expressions

  • SELECT TOP 100 a1, int(a2) * 10, len(a4) WHERE a1 == "Buy" ORDER BY int(a2) DESC
  • SELECT a.id, a.weight / 1000 AS weight_kg
  • SELECT * ORDER BY random.random() - random sort
  • SELECT len(a.vehicle_price) / 10, a2 WHERE int(a.vehicle_price) < 500 and a['Vehicle type'] in ["car", "plane", "boat"] limit 20 - referencing columns by names from header and using Python's "in" to emulate SQL's "in"
  • UPDATE SET a3 = 'NPC' WHERE a3.find('Non-playable character') != -1
  • SELECT NR, * - enumerate records, NR is 1-based
  • SELECT * WHERE re.match(".*ab.*", a1) is not None - select entries where first column has "ab" pattern
  • SELECT a1, b1, b2 INNER JOIN ./countries.txt ON a2 == b1 ORDER BY a1, a3 - example of join query
  • SELECT MAX(a1), MIN(a1) WHERE a.Name != 'John' GROUP BY a2, a3 - example of aggregate query
  • SELECT *a1.split(':') - Using Python3 unpack operator to split one column into many. Do not try this with other SQL engines!

With JavaScript expressions

  • SELECT TOP 100 a1, a2 * 10, a4.length WHERE a1 == "Buy" ORDER BY parseInt(a2) DESC
  • SELECT a.id, a.weight / 1000 AS weight_kg
  • SELECT * ORDER BY Math.random() - random sort
  • SELECT TOP 20 a.vehicle_price.length / 10, a2 WHERE parseInt(a.vehicle_price) < 500 && ["car", "plane", "boat"].indexOf(a['Vehicle type']) > -1 limit 20 - referencing columns by names from header
  • UPDATE SET a3 = 'NPC' WHERE a3.indexOf('Non-playable character') != -1
  • SELECT NR, * - enumerate records, NR is 1-based
  • SELECT a1, b1, b2 INNER JOIN ./countries.txt ON a2 == b1 ORDER BY a1, a3 - example of join query
  • SELECT MAX(a1), MIN(a1) WHERE a.Name != 'John' GROUP BY a2, a3 - example of aggregate query
  • SELECT ...a1.split(':') - Using JS "destructuring assignment" syntax to split one column into many. Do not try this with other SQL engines!

General info

Comparison of Rainbow CSV technology with traditional graphical column alignment

Advantages

  • WYSIWYG
  • Familiar editing environment of your favorite text editor
  • Zero-cost abstraction: Syntax highlighting is essentially free, while graphical column alignment can be computationally expensive
  • High information density: Rainbow CSV shows more data per screen because it doesn't insert column-aligning whitespaces.
  • Works with non-table and semi-tabular files (text files that contain both table(s) and non-table data like text)
  • Ability to visually associate two same-colored columns from two different windows. This is not possible with graphical column alignment

Disadvantages

  • Rainbow CSV technology may be less effective for CSV files with many (> 10) columns

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

rainbow_csv's People

Contributors

dther avatar ebanisadr avatar harrisonmg avatar ksr-yasuda avatar llwwns avatar mechatroner avatar tyru avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rainbow_csv's Issues

WHERE in Python list not working for more than 10 list items

I tried to define a WHERE statement for the python worker with more than 10 items in the IN list and it failed:

If one looks at the resulting worker python file one sees the following problem:

a select statement like

Select a1 where a1 in ["1","2","3","4","5","6","7","8","9","10","11","12"]

is being translated into the following statement of the process_update function in the resulting worker file:

if len(rhs_records) == 1 and (a1 in ["1","2","3","4","5","6","7","8","9","10","2"0,"2"1]):

I think it is quite obvious what goes wrong with the list items "11" and "12" and so on.

rcsv_colorpairs hex

Good day to you!

Is it possible to use hex-type of color in rcsv_colorpairs?

I'v tried something like this - but no luck
image

Thankyou!

Retain headers/column names in results

is it possible to retain the headers/column names in query results? It would be helpful to have column names in the results buffer.

Either way, this plugin is incredibly helpful. Thanks for releasing it.

Space leader key hijacked with rainbow key mappings disabled

This plugin seems to hijack the space key to create a line fold or something far less useful than my leaderkey, which is space. Using Neovim .7.

I have let g:disable_rainbow_key_mappings = 1 but this is still happening.

Assuming it is this plugin as if I :set ft=md my space leaderkey works as normal.

[feature] Allow user to change the path of temp file

Such as user can assign a variable to change ~/.rbql_table_index,
~/.rainbow_csv_storage to ~/.cache/nvim/.rbql_table_index,
~/.cache/nvim/.rainbow_csv_storage? or more compatible with XDG standard,
$XDG_CACHE_HOME/nvim/.rbql_table_index,
$XDG_CACHE_HOME/nvim/.rainbow_csv_storage?

Thanks!

Node and utf-8 do not agree

When executing RBQL using the node backend, node complains aboout broken utf-8. The error ist:

IO handling
Unable to decode input table as UTF-8. Use binary (latin-1) encoding instead

When I set let g:rbql_encoding = 'latin-1 I get the expected result.

Is this a buggy CSV-file I have (claims to be utf-8 at least) or is there a bug in the Neovim - Windows - node - Pipeline?

CSV tables that contain cells with newlines are not rendered properly

CSV files sometimes contain cells with newlines. This is valid when the cell is properly delimited with double quotes, for instance. Many tools like LibreOffice, the Frictionless Framework and even Github CSV visualization do work well with such files.

However, Rainbow CSV treats such files as invalid, and does not recognize the cell (e.g. for coloring, or the hovering tooltip with the column name).

Here is an example of one such file that contains newlines inside cells.

modeline disables colors

Adding a modeline for vts values turns off the colors unless I also add "ft=tsv".
Occurs on Ubuntu Fossa and cygwin64.

Doesn't handle newlines inside quoted field

Hi,
When a quoted field contains newline characters, the plugin interprets them as a row delimiter:

rainbow_csv

AFAICT, newlines inside quoted fields are allowed by the spec:

escaped = DQUOTE *(TEXTDATA / COMMA / CR / LF / 2DQUOTE) DQUOTE

Tips for dealing with inconsistent number of columns

For reasons outside of my control I often deal with partially populated CSVs - meaning that the header is fully populated but many lines are missing some trailing data without even commas to denote no data.

I have already patched out the warning that appears when moving the cursor to the lines in question, but Select operations still fail.

For my purposes, it would be completely appropriate to assume missing columns are just all empty string values. Does anybody have tips on how to do this easily? If not, I may look into modifying rainbow_csv further.

Thanks!

View CSV columns in separate vim buffers in vertical splits

This would be especially useful for multiline CSV fields.
This also could be useful for very long (oversized) textual fields even if they don't have newlines in them - in a separate buffer they can be line-wrapped by Vim - in this case, one record would correspond to multiple screen lines.
The following commands would be also required:

  • Extract current column into a separate vertical split buffer - will create at most two new buffers: to the left and to the right from the current column.
  • Show current logical row (record number)
  • Sync rows (in all vertical csv buffers jump to the physical lines that correspond to the logical row in the current split buffer)

warning on comment lines are not ignored

After setting g:rainbow_comment_prefix to #. when I put the cursor on a comment line, rainbow_csv reports "The number of fields in header and this (comment) line are different."
I'd expect it to ignore the comment lines.

rainbow_comment_warning

Add option to disable mappings

I don't want to change the mapping by default. So please add an option to disable the mapping.

eg. g:disable_default_mapping = 1

Should delimiter autodetect work in Neovim 0.8.1?

I deal with a balanced mix of files with , and ; delimiters and for some reason i've never been able to autodetect semicolons. If i forcibly set every csv file to csv_semicolon it works but it is as if i can't get the autodetect to run at all.

First i played around with various configs to see if they would change anything but e.g these did nothing:
vim.g.disable_rainbow_csv_autodetect = 0
vim.g.rbql_with_headers = 1
vim.g.rcsv_delimiters = {";"}
vim.g.rbql_use_system_python = 1

Despite zero vimscript knowledge, i even tried debugging the code with error messages. From what i can tell it seems that no autodetect code is ever run on file open. It always stops doing anything when it finds that "rainbow_features_enabled" is on and just always set the file type to "csv" with this:
execute "set ft=" . ft_power_cycle

Am i just dumb or why is it not able to detect that e.g this is a semicolon file?:

date;amount;other_party;category;account;recipient;bank;description
2018-05-31;148.35;p;data;a;b;;data
2018-05-31;415;p;data;a;b;;data
2018-05-31;-2.6;p;data;a;b;;data
2018-06-01;-2.6;p;data;a;b;;data

Manually setting it works fine but not auto. Is there a config i'm missing?

Wijmo License Expired

I see this when doing a CSV Preview.

Wijmo License

The Wijmo license in this application has expired. The license expiration date is 2/1/2021.

Please create a license or contact GrapeCity: [email protected].

CLOSE
Wijmo Evaluation Version (5.20201.664)

`g:rbql_use_system_python` does not work well

With g:rbql_use_system_python enabled, RBQL query does not work well.

" ${HOME}/.vimrc
Plugin 'mechatroner/rainbow_csv'

let g:rbql_backend_language  = 'python'
let g:rbql_use_system_python = v:true
:Select a1 group by a1

" Vim message
executing...
OK^M

" The target window does not change.

It works with g:rbql_backend_language = 'js'.


In my env, Windows MSYS, Vim native python looks not working well (see msys2/MSYS2-packages#1930, The python lib subprocess raises an error).

So, I'd like to use external python binary, but it just returns the message OK as above.

It looks writing into /tmp/TARGET_FILE_NAME.txt on every query,
but it does not switching the window to the output file.


Env

% cmd /v | head -n1
Microsoft Windows [Version 10.0.22631.3155]

% pacman -Q msys2-runtime
msys2-runtime 3.4.10-5

% pacman -Q vim
vim 9.1.0000-1

% vim --version
VIM - Vi IMproved 9.1 (2024 Jan 02, compiled Jan 04 2024 08:28:51)
Compiled by <https://www.msys2.org/>
Huge version without GUI.  Features included (+) or not (-):
+acl               +file_in_path      +mouse_urxvt       -tag_any_white
+arabic            +find_in_path      +mouse_xterm       -tcl
+autocmd           +float             +multi_byte        +termguicolors
+autochdir         +folding           +multi_lang        +terminal
-autoservername    -footer            -mzscheme          +terminfo
-balloon_eval      +fork()            +netbeans_intg     +termresponse
+balloon_eval_term +gettext           +num64             +textobjects
-browse            -hangul_input      +packages          +textprop
++builtin_terms    +iconv             +path_extra        +timers
+byte_offset       +insert_expand     +perl/dyn          +title
+channel           +ipv6              +persistent_undo   -toolbar
+cindent           +job               +popupwin          +user_commands
-clientserver      +jumplist          +postscript        +vartabs
+clipboard         +keymap            +printer           +vertsplit
+cmdline_compl     +lambda            +profile           +vim9script
+cmdline_hist      +langmap           -python            +viminfo
+cmdline_info      +libcall           +python3/dyn       +virtualedit
+comments          +linebreak         +quickfix          +visual
+conceal           +lispindent        +reltime           +visualextra
+cryptv            +listcmds          +rightleft         +vreplace
+cscope            +localmap          +ruby/dyn          +wildignore
+cursorbind        -lua               +scrollbind        +wildmenu
+cursorshape       +menu              +signs             +windows
+dialog_con        +mksession         +smartindent       +writebackup
+diff              +modify_fname      -sodium            -X11
+digraphs          +mouse             -sound             +xattr
-dnd               -mouseshape        +spell             -xfontset
-ebcdic            +mouse_dec         +startuptime       -xim
+emacs_tags        -mouse_gpm         +statusline        -xpm
+eval              -mouse_jsbterm     -sun_workshop      -xsmp
+ex_extra          +mouse_netterm     +syntax            -xterm_clipboard
+extra_search      +mouse_sgr         +tag_binary        -xterm_save
-farsi             -mouse_sysmouse    -tag_old_static    
   system vimrc file: "/etc/vimrc"
     user vimrc file: "$HOME/.vimrc"
 2nd user vimrc file: "~/.vim/vimrc"
      user exrc file: "$HOME/.exrc"
       defaults file: "$VIMRUNTIME/defaults.vim"
  fall-back for $VIM: "/etc"
 f-b for $VIMRUNTIME: "/usr/share/vim/vim91"
Compilation: gcc -c -I. -Iproto -DHAVE_CONFIG_H -I/usr/include/ncursesw -march=nocona -msahf -mtune=generic -O2 -pipe -D_REENTRANT -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1 
Linking: 
gcc -pipe -Wl,--as-needed -o vim.exe -lm -lncursesw -liconv -lacl -lintl 

% pacman -Q {mingw-w64-x86_64-,}python
mingw-w64-x86_64-python 3.11.8-1
python 3.11.8-1

% type -ap python
/mingw64/bin/python             # for MINGW64 binary
/usr/bin/python                 # for MSYS binary
/bin/python                     # for MSYS binary (the same of the above)
/c/Users/xxxxxxxx/AppData/Local/Microsoft/WindowsApps/python
                                # for Windows binary installer (not installed now)

rainbow_csv interferes with lightline

Using neovim and lightline on a German Windows 10. Neovim is set to english (FWIW)

When opening the RBQL - query window with F5 I get the following error message:

Error detected while processing function rainbow_csv#restore_statusline:
line    8:
E540: Unclosed expression sequence: statusline=%{lightline#link()}%#LightlineLeft_active_0#%(\ %{lightline#mode()}\ %)%{(&paste)?"
E10: \ should be followed by /, ? or &

[bug] Error when source a non-exist syntax

#!/usr/bin/env -S vi -u
" $ uname -r
" 5.19.7-arch1-1
" $ has
" ✓ vi 0.7.2
" $ cat test.vim
set runtimepath=$VIMRUNTIME
set runtimepath+=~/.local/share/nvim/repos/github.com/mechatroner/rainbow_csv
" $ chmod +x test.vim
" $ ./test.vim
ex: filetype=none

Expected

Nothing happened.

Actual

Error detected while processing /home/wzy/.local/share/nvim/repos/github.com/mechatroner/rainbow_csv/autoload/rainbow_csv.vim:
line  132:
E12: Command not allowed from exrc/vimrc in current dir or tag search: augroup RainbowCsvPluginInitAuGrp
line  134:
E12: Command not allowed from exrc/vimrc in current dir or tag search:     autocmd!
line  136:
E12: Command not allowed from exrc/vimrc in current dir or tag search:     autocmd VimEnter * call rainbow_csv#init_rb_color_groups()
line  137:
E12: Command not allowed from exrc/vimrc in current dir or tag search:     autocmd ColorScheme * call rainbow_csv#init_rb_color_groups()
line  138:
E12: Command not allowed from exrc/vimrc in current dir or tag search: augroup END

Key bindings

Are there any keyboard shortcuts for the commands in the package?

Quoted delimiters still interpreted

Hi, first off, I love the project!
It's Exactly what I was looking for to get a visual representation of columns without trying turn vim into excel.

I did notice, though that delimiters within quotes are still interpreted as delimiters. I am aware of a lack of standardization with *sv's in general, but it seems pretty common to put cells that contain the delimiter within quotes, ex:

Jack,20  
Maria,18 
"John, the cool one",40  
Dmitry,27
Maria,30 
John,17

which ends up highlighting like this:

screen shot 2017-05-24 at 12 49 41 pm

Because of the lack of standardization, people also may use \ escaping, but I'm not sure how common that is - I know excel uses double quotes and have a feeling google sheets uses the same.

Is there any way to add support for delimiters that should be ignored? At least the common double-quoted case?

I'd be happy to help -- haven't looked at your code to see how much work it would be, but should theoretically be possible, though it may add a lot of complication and may open some doors to problems like "\"" -- would have to do some experimenting with excel, libreoffice and google sheets to see what's common

[bug] change colorscheme will make color disappear

" $ uname -r
" 5.13.10-arch1-1
" $ has nvim
" ✓ nvim 0.5.0
" $ has python
" ✓ python 3.9.6
" $ cat test.vim
set runtimepath=$VIMRUNTIME
set runtimepath+=~/.local/share/nvim/repos/github.com/mechatroner/rainbow_csv
autocmd VimEnter * colorscheme default
" $ vi -u test.vim a.csv

The color will disappear.

I guess it maybe should add some code like

autocmd! colorscheme * call some_function_render_csv()

Thanks!

Failed to load Python host.

I installed vim-rainbow_csv using vim-plug. However, when I press F5 I get the following error:

function provider#python#Call[9]..remote#host#Require[10]..provider#pythonx#Require[13]..provider#Poll, line 4 Vim(if):Error invoking 'poll' on channel 8:^@ch 8 was closed by the client Failed to load python host. You can try to see what happened by starting nvim with $NVIM_PYTHON_LOG_FILE set and opening the generated log file. Also, the host stderr is av ailable in messages. Press ENTER or type command to continue

I did pip install rbql, but it did not fix anything.
What could be the cause of this error?

Alignment Issues in Nvim

Hi,
I am facing a slight issue, would appreciate your thoughts on this. if say I've a CSV data which contains a index field which would mean header would have trailing comma in it. Take a look in the following example:

,first,second,third,fourth
1,the,why,you,align
2,the,why,you,align
3,the,why,you,align

1,2&3 is the index number of the data.
Screenshot 2023-11-15 at 12 02 10 PM

Plugin is able to detect the correct order of colours when I'm not trying to align it. As we can see in the picture, it is colouring the index in the separate colour. But what happens when I try to align the data is:

first ,second ,third ,fourth 
    1 ,the    ,why   ,you    ,align 
    2 ,the    ,why   ,you    ,align 
    3 ,the    ,why   ,you    ,align 

It somehow align the index into first column and last column is orphan without any header for it. It kind of ignores the first comma of the header. VSCode rainbow plugin handles this properly.
I hope I explained the issue rightfully. Do let me know if I missed anything. Will put in more detail if required.
Thanks

[feature] Allow user customize hotkey

Why not change

    if !exists("g:disable_rainbow_key_mappings")
        nnoremap <buffer> <F7> :call rainbow_csv#copy_file_content_to_buf(b:self_path, b:root_table_buf_number)<cr>
    endif

to

execute 'nnoremap <buffer> ' . get(g:, 'rainbow_key_mapping', '<F7>') . ':call rainbow_csv#copy_file_content_to_buf(b:self_path, b:root_table_buf_number)<cr>'

?

Thanks!

Make Header Row Sticky

Tooltips are really helpful, however, if the first row (if there is a header) would move along with scrolling would be really great. Any idea if this is feasible?

Unconditional setting of nocompatible too intrusive

I observed that due to the setting of nocompatible in the function rainbow_csv#buffer_enable_rainbow_features
my viminfo setting was reset to its default values.

Therefore I think the setting must not be unconditional but only if not yet set.
Thus my suggestion for a patch of the autoload file as follows:
diff_rainbow_csv_vim.txt

rainbow color

my rainbow is not colorful enough.
is there a way to customize your rainbow?

image

Don't modify laststatus

Hello,

for some reason, the plugin sets laststatus to 2 every time a csv buffer is focused. Why is it like that? Could we have an option to disable that?

statement fails with message 'unexpected identifier'

Using Rainbow_CSV on Neovim nightly on Windows 10.

Scripting engine is node, installed with npm install -g rbql and set let g:rbql_backend_language = 'js' in init.vim

The following statement

select *
where a19.length > 0
and a19 % 1 != 1
limit 100

should filter rows in the CSV-file, where column 19 contains non-integer numbers.

It results in the following error message:

unexpected
Unexpected identifier

duplicate colors?

I may just really not understand but no matter what I do col 6 and 7 have the same color is there a way to fix this? See image.
image

Windows: Powershell and node (Python too?) cannot interact

Using RBQL on Windows 10 and node as the RBQL backend and with shell set to Powershell as described here:

https://neovim.io/doc/user/options.html , search for powershell:

let &shell = has('win32') ? 'powershell' : 'pwsh'
set shellquote= shellpipe=\| shellxquote=
set shellcmdflag=-NoLogo\ -NoProfile\ -ExecutionPolicy\ RemoteSigned\ -Command
set shellredir=\|\ Out-File\ -Encoding\ UTF8

When trying to run an RBQL command with F5 the interaction between Powershell and node dies with this error message:

IO handling
Unknown output csv policy

g:rainbow_comment_prefix Not Honored

I can set the comment prefix in runtime by running the RainbowComment command over a pound sign (#), but if I try to set it in my vim init via vim.g.rainbow_comment_prefix = '#' the comments are not highlighted and warnings are not ignored on that line.

I can check that when during runtime with:
:let g:rainbow_comment_prefix
which does return:
g:rainbow_comment_prefix #

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.