Created
August 29, 2011 15:19
-
-
Save jbjornson/1178594 to your computer and use it in GitHub Desktop.
Convert a CSV file to fixed width
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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).