Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mixio/f2c4f2bc46593b5875d9f9504b0824ef to your computer and use it in GitHub Desktop.
Save mixio/f2c4f2bc46593b5875d9f9504b0824ef to your computer and use it in GitHub Desktop.
BBEdit script to set the tab width of a CSV or TSV document to the size of the longest field in order to view data "in aligned columns"
# This script will use the `xsv` command line tool:
# <https://github.com/BurntSushi/xsv>
# to compute the max length of all cells of columns from 1 to n - 1 of
# the front document of BBEdit if it is a CSV of TSV file with
# respective extensions of '.csv' and '.tsv'.
# It will then set the tab width of the document to this max length,
# allowing the user to view the data in aligned columns.
# For that purpose, in CSV files a tab will be inserted
# after each comma separator when required.
tell application "BBEdit"
try
tell first document of first window
save it
set vFilePath to POSIX path of ((its file) as string)
if vFilePath ends with ".csv" then
set vType to "csv"
else if vFilePath ends with ".tsv" then
set vType to "tsv"
else
error "Not a CSV or TSV file."
end if
set vCommand to "source ~/.zprofile ;" & space -- Import the required PATH environment variable.
set vCommand to vCommand & "xsv stats" & space & the quoted form of vFilePath & space
set vCommand to vCommand & "| sed '$d'" & space -- Remove last line because we don't care about the width of the last column.
set vCommand to vCommand & "| xsv select max_length" & space -- Get column 7 'max_length'.
set vCommand to vCommand & "| xsv sort --numeric --reverse" & space -- Sort reverse numerically.
set vCommand to vCommand & "| xsv slice --no-headers --index 1" & space -- After removing headers, get first line. It is the max length of all cells of columns from 1 to n - 1.
log vCommand
set vMaxLength to do shell script vCommand
log vMaxLength
if vMaxLength > 0 then
set vTabWidth to 2 + (vMaxLength) as integer
set its window's tab width to vTabWidth
else
error "xsv could not compute the max length of all cells of columns from 1 to n - 1;"
end if
if vType = "csv" then
-- Add tabs after commas if required.
replace "(?<=,)\\h*(\"(?:\"\"|[^\"\n\r])*\"|[^,\"\n\r]+)\\h*" using "\t\\1" searchingString its text options {search mode:grep, starting at top:true, wrap around:true, backwards:false, returning results:false, showing results:false}
end if
end tell
on error aMessage
display dialog aMessage
end try
end tell
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment