Skip to content

Commit

Permalink
alpha
Browse files Browse the repository at this point in the history
  • Loading branch information
bitwiser73 authored and foh committed Oct 28, 2016
1 parent 53080aa commit 6acffd6
Show file tree
Hide file tree
Showing 10 changed files with 285 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
@@ -0,0 +1 @@
__pycache__
9 changes: 9 additions & 0 deletions Default (Linux).sublime-keymap
@@ -0,0 +1,9 @@
[
{
"keys": ["ctrl+alt+shift+t"],
"command": "markdown_table_formatter_format",
"context": [
{"key": "selector", "operator": "equal", "operand": "text.html.markdown"}
]
}
]
9 changes: 9 additions & 0 deletions Default (OSX).sublime-keymap
@@ -0,0 +1,9 @@
[
{
"keys": ["ctrl+alt+shift+t"],
"command": "markdown_table_formatter_format",
"context": [
{"key": "selector", "operator": "equal", "operand": "text.html.markdown"}
]
}
]
9 changes: 9 additions & 0 deletions Default (Windows).sublime-keymap
@@ -0,0 +1,9 @@
[
{
"keys": ["ctrl+alt+shift+t"],
"command": "markdown_table_formatter_format",
"context": [
{"key": "selector", "operator": "equal", "operand": "text.html.markdown"}
]
}
]
88 changes: 88 additions & 0 deletions Main.sublime-menu
@@ -0,0 +1,88 @@
[
{
"caption": "Preferences",
"mnemonic": "n",
"id": "preferences",
"children":
[
{
"caption": "Package Settings",
"mnemonic": "P",
"id": "package-settings",
"children":
[
{
"caption": "Markdown Table Formatter",
"children":
[
{
"command": "open_file", "args":
{
"file": "${packages}/MarkdownTableFormatter/MarkdownTableFormatter.sublime-settings"
},
"caption": "Settings – Default"
},
{
"command": "open_file", "args":
{
"file": "${packages}/User/MarkdownTableFormatter.sublime-settings"
},
"caption": "Settings – User"
},
{ "caption": "-" },
{
"command": "open_file",
"args": {
"file": "${packages}/MarkdownTableFormatter/Default (OSX).sublime-keymap",
"platform": "OSX"
},
"caption": "Key Bindings – Default"
},
{
"command": "open_file",
"args": {
"file": "${packages}/MarkdownTableFormatter/Default (Linux).sublime-keymap",
"platform": "Linux"
},
"caption": "Key Bindings – Default"
},
{
"command": "open_file",
"args": {
"file": "${packages}/MarkdownTableFormatter/Default (Windows).sublime-keymap",
"platform": "Windows"
},
"caption": "Key Bindings – Default"
},
{
"command": "open_file",
"args": {
"file": "${packages}/User/Default (OSX).sublime-keymap",
"platform": "OSX"
},
"caption": "Key Bindings – User"
},
{
"command": "open_file",
"args": {
"file": "${packages}/User/Default (Linux).sublime-keymap",
"platform": "Linux"
},
"caption": "Key Bindings – User"
},
{
"command": "open_file",
"args": {
"file": "${packages}/User/Default (Windows).sublime-keymap",
"platform": "Windows"
},
"caption": "Key Bindings – User"
},
{ "caption": "-" }
]
}
]
}
]
}
]
4 changes: 4 additions & 0 deletions MarkdownTableFormatter.sublime-settings
@@ -0,0 +1,4 @@
{
// make plugin verbose
"verbose" : true
}
32 changes: 32 additions & 0 deletions markdown_table_formatter.py
@@ -0,0 +1,32 @@
import sublime
import sublime_plugin

import logging

from . import simple_markdown as markdown
from .simple_markdown import table

log = logging.getLogger(__name__)

class MarkdownTableFormatterFormatCommand(sublime_plugin.TextCommand):
def run(self, edit):
logging.basicConfig(level=logging.DEBUG)
for region in self.view.sel():
text = self.view.substr(region)
# get all tables positions as (start,end) list
positions = markdown.table.find_all(text)
offset = 0
for start, end in positions:
raw_table = text[start:end]
log.debug("table found:\n" + raw_table)
table = markdown.table.format(raw_table)
log.debug("formatted output:\n" + table)

# replace the raw table with the formetted one
table_region = sublime.Region(region.begin() + start + offset,
region.begin() + end + offset)
self.view.replace(edit, table_region, table)

# as table length will likely change, an offset is required to
# keep the modified region consistent
offset = offset + len(table) - (end - start)
Empty file added simple_markdown/__init__.py
Empty file.
66 changes: 66 additions & 0 deletions simple_markdown/table.py
@@ -0,0 +1,66 @@
import re

def find_all(text):
tables = []
offset = 0
while True:
group = re.search(".*\|.*\n[\s\t]*\|?(?::?[-]+:?\|)+(\n.*\|.*)+",
text[offset:], re.MULTILINE)
if group is None:
return tables
tables.append((group.start() + offset, group.end() + offset))
offset = offset + group.end()
return tables

def format(raw_table):
rows = raw_table.splitlines()
# normalize markdown table, add missing leading/trailing '|'
for idx, row in enumerate(rows):
if re.match("^[\s\t]*\|", row) is None:
rows[idx] = "|" + rows[idx]
if re.match(".*\|[\s\t]*\n?$", row) is None:
rows[idx] = rows[idx] + "|"

matrix = [[col.strip() for col in row.split("|")] for row in rows]

# remove first and last empties column
matrix[:] = [row[1:] for row in matrix]
matrix[:] = [row[:-1] for row in matrix]

# ensure there's same column number for each row or add missings
cols = max([len(row) for row in matrix])
matrix[:] = \
[row if len(row) == cols else row+[""]*(cols-len(row)) for row in matrix]

# merge the multiple "-" of the 2nd line
matrix[1] = [re.sub("[- ]+","-", col) for col in matrix[1]]

# determine each column size
widths = [[len(col) for col in row] for row in matrix]
max_widths = [max(item) for item in zip(*widths)]

# construct a clean markdown table without separation row
table = []
for row_idx, row in enumerate(matrix):
line = ["|"]
# keep separation row for later...
if row_idx == 1:
continue
for col_idx, col in enumerate(row):
line.append(" " + col.ljust(max_widths[col_idx]) + " |")
table.append("".join(line))

# construct separation row
sep_row = []
for col_idx, col in enumerate(matrix[1]):
line = list("-" * (max_widths[col_idx] + 2))
if col.startswith(":"):
line[0] = ":"
if col.endswith(":"):
line[-1] = ":"
else:
line[0] = ":"
sep_row.append("".join(line))
table.insert(1, "|" + "|".join(sep_row) + "|")
return "\n".join(table)

67 changes: 67 additions & 0 deletions tests/test.py
@@ -0,0 +1,67 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*_

import os
import sys

sys.path.append(os.path.realpath('..'))
import simple_markdown.table

#import unittest

raw_table = """\
| Tables | Are | Cool |
|-------------|:-------------|:-----:|
| col 1 is | left-aligned | $1600 |
col 2 is || $12
| zebra stripes | are neat | $1 |
|| |$hello
| $2 |"""

expected_table = """\
| Tables | Are | Cool |
|:--------------|:-------------|:------:|
| col 1 is | left-aligned | $1600 |
| col 2 is | | $12 |
| zebra stripes | are neat | $1 |
| | | $hello |
| $2 | | |"""

print(raw_table)
table = simple_markdown.table.format(raw_table)
print(table)

if table == expected_table:
print("OK")

junk_tables = """
| Tables | Are | Cool #1 |
|-------------|:-------------:|:-----|
| col 3 is | right-aligned | $1600 |
col 2 is || $12
| zebra stripes|are neat| $1 |
|| |$hello
| $2 |
hellobar
fooworld
and junk
| Tables | Are | Cool #2 |
|-------------|:-------------:|:-----|
| col 3 is | right-aligned | $1600 |
col 2 is || $12
| zebra stripes | are neat | $1 |
|| |$hello
| $2 |
junk junk junk
and some | to test
if it's still working ||||||
is it?
"""

offsets = simple_markdown.table.find_all(junk_tables)
for offset in offsets:
table = simple_markdown.table.format(junk_tables[offset[0]:offset[1]])
print(table + "\n")

0 comments on commit 6acffd6

Please sign in to comment.