Skip to content

Instantly share code, notes, and snippets.

@cb109
Last active September 21, 2018 08:31
Show Gist options
  • Select an option

  • Save cb109/824b0db6e91c564d490d0fd783e141dc to your computer and use it in GitHub Desktop.

Select an option

Save cb109/824b0db6e91c564d490d0fd783e141dc to your computer and use it in GitHub Desktop.
Format lists in Sublime exactly the way I like it.
import sublime_plugin
class FormatListOneLinePerItemCommand(sublime_plugin.TextCommand):
"""Format a one-line list/tuple into one-item-per-line.
E.g. from:
list_display = ("name", "kind", "parent",)
to:
list_display = (
"name",
"kind",
"parent",
)
Keeps original indentation level and adds one level to items.
Handles trailing comma/no trailing comma, but not much else.
"""
def run(self, edit,
split_pattern=",",
remove_empty=True,
indent_char=" "):
view = self.view
cursors = view.sel()
if len(cursors) != 1:
return
view.run_command("expand_selection", args={"to": "brackets"})
cursor = cursors[0]
line = view.line(cursor)
line_str = view.substr(line)
indent = len(line_str) - len(line_str.lstrip())
offset = indent_char * indent
offset_border = offset
offset_inner = offset + (indent_char * 4)
region = cursor
content = view.substr(region)
parts = [part.strip() for part in content.split(split_pattern)
if not remove_empty or part.strip() != ""]
new_content = "\n" + offset_inner
new_content += "{}\n{}".format(split_pattern,
offset_inner).join(parts)
new_content += split_pattern + "\n" + offset_border
view.replace(edit, region, new_content)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment