Skip to content

Instantly share code, notes, and snippets.

@jbjornson
Created August 29, 2011 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbjornson/1178594 to your computer and use it in GitHub Desktop.
Save jbjornson/1178594 to your computer and use it in GitHub Desktop.
Convert a CSV file to fixed width
import sublime_plugin
# { "keys": ["alt+m"], "command": "convert_to_fixed_column", "args": {"split_char": ";"}}
# https://gist.github.com/1178594
class ConvertToFixedColumnCommand(sublime_plugin.TextCommand):
def run(self, edit, split_char=';'):
for region in self.view.sel():
self.view.replace(edit, region, self.align_content(self.view.substr(region), split_char))
def align_content(self, content, split_char):
# calculate the max width for each column
lines = []
widths = []
for text in iter(content.splitlines()):
line = text.split(split_char)
lines.append(line)
for (cell_idx, cell_val) in enumerate(line):
if cell_idx >= len(widths):
widths.append(0)
widths[cell_idx] = max(widths[cell_idx], len(cell_val))
# format each cell to the max width calculated above (left padded with spaces)
output = []
for line in lines:
for col_idx in range(len(line)):
mask = '%%0%ds' % (widths[col_idx])
line[col_idx] = mask % line[col_idx]
output.append(split_char.join(line))
# make sure that the trailing newline is saved (if there was one)
if content.endswith('\n'):
output.append('')
return '\n'.join(output)
@FichteFoll
Copy link

Nice attempt. Maybe you want to extend this one by using the whole file if there are no extensions (I made something like that here; disregard the sum(1 for reg in sel) == 1 ;) ) or to auto-left- or -right-align by checking every cell whether it's a number or not. I did something similar in AutoIt here but I doubt it'll help.

Anyway, you do not consider elements enclosed by "" which may have the separator char in it without creating a new element (well, that's pretty much the only purpose for them except for newlines). I also have an example for this here (#87).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment