Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ NEW: Add --compact-tables CLI argument #17

Merged
merged 13 commits into from
Aug 23, 2024
18 changes: 9 additions & 9 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,33 +13,33 @@ jobs:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v1
uses: actions/setup-python@v5
with:
python-version: 3.7
- uses: pre-commit/action@v2.0.0
- uses: pre-commit/action@v3.0.0

tests:
runs-on: ${{ matrix.os }}
strategy:
matrix:
python-version: [3.6, 3.7, 3.8, 3.9]
python-version: [3.7, 3.11]
os: [ubuntu-latest, windows-latest]

steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4

- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}

- name: Installation (deps and package)
# we install with flit --pth-file,
# so that coverage will be recorded up for the module
run: |
pip install flit
pip install flit~=3.0
flit install --deps=production --extras=test --pth-file

- name: Run pytest
Expand Down Expand Up @@ -81,9 +81,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout source
uses: actions/checkout@v2
uses: actions/checkout@v4
- name: Set up Python 3.7
uses: actions/setup-python@v1
uses: actions/setup-python@v5
with:
python-version: 3.7
- name: install flit
Expand Down
18 changes: 9 additions & 9 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.4.0
rev: v4.5.0
hooks:
- id: end-of-file-fixer
- id: mixed-line-ending
- id: trailing-whitespace
- id: check-yaml
- id: check-toml
- repo: https://github.com/pre-commit/pygrep-hooks
rev: v1.8.0
rev: v1.10.0
hooks:
- id: python-check-blanket-noqa
- repo: https://github.com/timothycrosley/isort
rev: 5.6.4
rev: 5.13.2
hooks:
- id: isort
- repo: https://github.com/psf/black
rev: 20.8b1
rev: 24.1.1
hooks:
- id: black
- repo: https://gitlab.com/pycqa/flake8
rev: 3.8.4
- repo: https://github.com/PyCQA/flake8
rev: 7.0.0
hooks:
- id: flake8
additional_dependencies:
- flake8-bugbear==20.11.1
- flake8-builtins==1.5.3
- flake8-comprehensions==3.3.1
- flake8-bugbear>=20.11.1
- flake8-builtins>=1.5.3
- flake8-comprehensions>=3.3.1
7 changes: 6 additions & 1 deletion mdformat_tables/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,9 @@

__version__ = "0.4.1"

from .plugin import POSTPROCESSORS, RENDERERS, update_mdit # noqa: F401
from .plugin import ( # noqa: F401
POSTPROCESSORS,
RENDERERS,
add_cli_options,
update_mdit,
)
29 changes: 24 additions & 5 deletions mdformat_tables/plugin.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,30 @@
import argparse
from typing import List, Mapping, Sequence

from markdown_it import MarkdownIt
from mdformat.renderer import RenderContext, RenderTreeNode
from mdformat.renderer.typing import Postprocess, Render

_COMPACT_TABLES = False
"""user-specified flag for toggling compact tables."""


def add_cli_options(parser: argparse.ArgumentParser) -> None:
"""Add options to the mdformat CLI, to be stored in `mdit.options["mdformat"]`."""
parser.add_argument(
"--compact-tables",
action="store_true",
help="If specified, do not add padding to table cells.",
)


def update_mdit(mdit: MarkdownIt) -> None:
"""Update the parser, e.g. by adding a plugin: `mdit.use(myplugin)`"""
mdit.enable("table")

global _COMPACT_TABLES
_COMPACT_TABLES = mdit.options["mdformat"].get("compact_tables", False)


def _to_string(
rows: Sequence[Sequence[str]], align: Sequence[Sequence[str]], widths: Sequence[int]
Expand All @@ -26,7 +42,7 @@ def _to_string(
"| "
+ " | ".join(
(":" if al in ("<", "^") else "-")
+ "-" * (widths[i] - 2)
+ "-" * max(widths[i] - 2, 0)
+ (":" if al in (">", "^") else "-")
for i, al in enumerate(align[0])
)
Expand Down Expand Up @@ -66,10 +82,13 @@ def _render_table(node: RenderTreeNode, context: RenderContext) -> str:
align[-1].append("")
rows[-1].append(descendant.render(context))

# work out the widths for each column
widths = [
max(3, *(len(row[col_idx]) for row in rows)) for col_idx in range(len(rows[0]))
]
def _calculate_width(col_idx: int) -> int:
"""Work out the widths for each column."""
if _COMPACT_TABLES:
return 0
return max(3, *(len(row[col_idx]) for row in rows))

widths = [_calculate_width(col_idx) for col_idx in range(len(rows[0]))]

# write content
# note: assuming always one header row
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ classifiers = [
]
keywords = "mdformat,markdown,markdown-it"

requires-python=">=3.6.1"
requires-python=">=3.7.0"
requires=["mdformat>=0.7.5,<0.8.0"]

[tool.flit.metadata.requires-extra]
Expand Down
137 changes: 137 additions & 0 deletions tests/fixtures-compact.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
simple
.
a | bb
| - | -
1 | 2
.
| a | bb |
| -- | -- |
| 1 | 2 |
.

empty headers
.
| | |
|- | -
|1 | 2
.
| | |
| -- | -- |
| 1 | 2 |
.

no body
.
| | |
|- | -
.
| | |
| -- | -- |
.

alignment
.
a | b | c
:- | -: | :-:
1 | 2 | 3
xxxxxx | yyyyyy | zzzzzz
.
| a | b | c |
| :- | -: | :: |
| 1 | 2 | 3 |
| xxxxxx | yyyyyy | zzzzzz |
KyleKing marked this conversation as resolved.
Show resolved Hide resolved
.

nested syntax
.
*a* | [b](link)
| - | -
`c` | [d](link)
.
| *a* | [b](link) |
| -- | -- |
| `c` | [d](link) |
.

A list takes precedence in case of ambiguity
.
a | b
- | -
1 | 2
.
a | b

- | \-
1 | 2
.

paragraph before/after
.
x
a | bb
-- | -
1 | 2
y
.
x

| a | bb |
| -- | -- |
| 1 | 2 |
| y | |
.

Nested tables in blockquotes:
.
> a|b
> ---|---
> bar|baz
.
> | a | b |
> | -- | -- |
> | bar | baz |
.

references
.
| [![a][b]][c] |
| - |
| [![a][b]][c] |

[b]: link1
[c]: link2
.
| [![a][b]][c] |
| -- |
| [![a][b]][c] |

[b]: link1
[c]: link2
.

Escaped table 1
.
| a |
\| - |
.
| a |
| \- |
.

Escaped table 2
.
a
-\:
.
a
\-:
.

Escaped table 3
.
a
:\-
.
a
:\-
.
15 changes: 15 additions & 0 deletions tests/test_parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,18 @@ def test_fixtures(line, title, text, expected):
output = mdformat.text(text, extensions={"tables"})
print(output)
assert output.rstrip() == expected.rstrip(), output


FIXTURES_COMPACT_PATH = Path(__file__).parent / "fixtures-compact.md"
fixtures_compact = read_fixture_file(FIXTURES_COMPACT_PATH)


@pytest.mark.parametrize(
"line,title,text,expected", fixtures_compact, ids=[f[1] for f in fixtures_compact]
)
def test_fixtures_compact(line, title, text, expected):
output = mdformat.text(
text, extensions={"tables"}, options={"compact_tables": True}
)
print(output)
assert output.rstrip() == expected.rstrip(), output
10 changes: 5 additions & 5 deletions tox.ini
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
[tox]
envlist = py{36,37,38,39}
envlist = py{37,311}
isolated_build = True

[testenv:py{36,37,38,39}]
[testenv:py{37,311}]
extras = test
commands = pytest --cov={envsitepackagesdir}/mdformat_tables {posargs}
commands = pytest --cov={envsitepackagesdir}/mdformat_tables {posargs} --ff --nf -vv

[testenv:py{36,37,38,39}-pre-commit]
[testenv:py{37,311}-pre-commit]
deps = pre-commit
commands = pre-commit run {posargs}

[testenv:py{36,37,38,39}-hook]
[testenv:py{37,311}-hook]
deps = pre-commit
commands = pre-commit run --config .pre-commit-test.yaml {posargs:--all-files --verbose --show-diff-on-failure}

Expand Down