166 lines
7.6 KiB
Python
166 lines
7.6 KiB
Python
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import csv
|
||
|
|
import io
|
||
|
|
import re
|
||
|
|
from dataclasses import dataclass
|
||
|
|
|
||
|
|
MAX_ROWS = 1000
|
||
|
|
MAX_COLUMNS = 100
|
||
|
|
|
||
|
|
|
||
|
|
def validate_table_size(rows: list[list[str]]) -> None:
|
||
|
|
if len(rows) > MAX_ROWS or any(len(row) > MAX_COLUMNS for row in rows):
|
||
|
|
raise ValueError(f"图形表格最多支持 {MAX_ROWS} 行(含表头)、{MAX_COLUMNS} 列。\n"
|
||
|
|
"未导入超限内容,原表格保持不变。请拆分表格或在源码中编辑。")
|
||
|
|
|
||
|
|
|
||
|
|
def parse_tsv(text: str) -> list[list[str]]:
|
||
|
|
rows = []
|
||
|
|
for row in csv.reader(io.StringIO(text), delimiter="\t"):
|
||
|
|
if len(rows) >= MAX_ROWS or len(row) > MAX_COLUMNS:
|
||
|
|
raise ValueError(f"粘贴内容超过 {MAX_ROWS} 行或 {MAX_COLUMNS} 列,未导入任何内容。请拆分后重试。")
|
||
|
|
rows.append(row or [""])
|
||
|
|
return rows
|
||
|
|
|
||
|
|
|
||
|
|
def format_table(rows: list[list[str]], alignments: list[str]) -> str:
|
||
|
|
count = max((len(row) for row in rows), default=1)
|
||
|
|
rows = rows or [["列1"]]
|
||
|
|
def line(row: list[str]) -> str:
|
||
|
|
cells = [row[i] if i < len(row) else "" for i in range(count)]
|
||
|
|
# Preserve existing escaped pipes; multiline spreadsheet cells become line breaks.
|
||
|
|
cells = [re.sub(r"(?<!\\)\|", r"\|", cell.replace("\r\n", "\n").replace("\n", "<br>")).strip() for cell in cells]
|
||
|
|
return "| " + " | ".join(cells) + " |"
|
||
|
|
separators = {"left": ":---", "center": ":---:", "right": "---:", "": "---"}
|
||
|
|
rule = [separators.get(alignments[i] if i < len(alignments) else "", "---") for i in range(count)]
|
||
|
|
return "\n".join([line(rows[0]), line(rule), *[line(row) for row in rows[1:]]])
|
||
|
|
|
||
|
|
|
||
|
|
@dataclass
|
||
|
|
class TableSelection:
|
||
|
|
start: int
|
||
|
|
end: int
|
||
|
|
rows: list[list[str]]
|
||
|
|
alignments: list[str]
|
||
|
|
|
||
|
|
|
||
|
|
def table_at_line(source: str, line: int) -> TableSelection | None:
|
||
|
|
from markdown_it import MarkdownIt
|
||
|
|
tokens = MarkdownIt().enable("table").parse(source)
|
||
|
|
for i, token in enumerate(tokens):
|
||
|
|
if token.type != "table_open" or token.map is None or not token.map[0] <= line < token.map[1]:
|
||
|
|
continue
|
||
|
|
if token.level > 0:
|
||
|
|
return None
|
||
|
|
# Nested quote/list tables need their prefix retained; leave those to source editing.
|
||
|
|
start, end = token.map
|
||
|
|
source_lines = source.splitlines(keepends=True)
|
||
|
|
if source_lines[start].lstrip().startswith((">", "- ", "* ")):
|
||
|
|
return None
|
||
|
|
rows: list[list[str]] = []
|
||
|
|
aligns: list[str] = []
|
||
|
|
for child in tokens[i+1:]:
|
||
|
|
if child.type == "table_close":
|
||
|
|
break
|
||
|
|
if child.type == "tr_open":
|
||
|
|
rows.append([])
|
||
|
|
elif child.type == "inline" and rows:
|
||
|
|
rows[-1].append(child.content)
|
||
|
|
elif child.type == "th_open":
|
||
|
|
aligns.append((child.attrGet("style") or "").removeprefix("text-align:"))
|
||
|
|
return TableSelection(sum(map(len, source_lines[:start])), sum(map(len, source_lines[:end])), rows, aligns)
|
||
|
|
return None
|
||
|
|
|
||
|
|
|
||
|
|
def edit_table(parent: object, rows: list[list[str]] | None = None, alignments: list[str] | None = None) -> str | None:
|
||
|
|
from PySide6.QtWidgets import (QApplication, QComboBox, QDialog, QDialogButtonBox, QHBoxLayout,
|
||
|
|
QLabel, QMessageBox, QPushButton, QSpinBox, QTableWidget, QTableWidgetItem, QVBoxLayout)
|
||
|
|
rows = rows or [["列1", "列2"], ["", ""], ["", ""]]
|
||
|
|
try:
|
||
|
|
validate_table_size(rows)
|
||
|
|
except ValueError as exc:
|
||
|
|
QMessageBox.warning(parent, "表格过大", str(exc))
|
||
|
|
return None
|
||
|
|
alignment = list(alignments or [""] * max(map(len, rows)))
|
||
|
|
dialog = QDialog(parent)
|
||
|
|
dialog.setWindowTitle("编辑 Markdown 表格")
|
||
|
|
dialog.resize(820, 540)
|
||
|
|
layout = QVBoxLayout(dialog)
|
||
|
|
layout.addWidget(QLabel("第一行为表头;可直接编辑单元格,也可从 Excel 粘贴。应用后可整体撤销。"))
|
||
|
|
controls = QHBoxLayout()
|
||
|
|
row_count, column_count = QSpinBox(), QSpinBox()
|
||
|
|
row_count.setRange(1, MAX_ROWS)
|
||
|
|
column_count.setRange(1, MAX_COLUMNS)
|
||
|
|
row_count.setValue(len(rows))
|
||
|
|
column_count.setValue(max(map(len, rows)))
|
||
|
|
controls.addWidget(QLabel("行数(含表头)")); controls.addWidget(row_count)
|
||
|
|
controls.addWidget(QLabel("列数")); controls.addWidget(column_count)
|
||
|
|
align = QComboBox()
|
||
|
|
for label, value in [("默认", ""), ("左对齐", "left"), ("居中", "center"), ("右对齐", "right")]:
|
||
|
|
align.addItem(label, value)
|
||
|
|
controls.addWidget(QLabel("当前列")); controls.addWidget(align)
|
||
|
|
layout.addLayout(controls)
|
||
|
|
table = QTableWidget(len(rows), max(map(len, rows)))
|
||
|
|
layout.addWidget(table)
|
||
|
|
|
||
|
|
def populate(values: list[list[str]]) -> None:
|
||
|
|
table.clearContents()
|
||
|
|
row_count.setValue(len(values)); column_count.setValue(max(map(len, values)))
|
||
|
|
for r, row in enumerate(values):
|
||
|
|
for c, cell in enumerate(row):
|
||
|
|
table.setItem(r, c, QTableWidgetItem(cell))
|
||
|
|
table.setCurrentCell(0, 0)
|
||
|
|
|
||
|
|
def columns(value: int) -> None:
|
||
|
|
table.setColumnCount(value)
|
||
|
|
alignment.extend([""] * max(0, value - len(alignment)))
|
||
|
|
del alignment[value:]
|
||
|
|
row_count.valueChanged.connect(table.setRowCount)
|
||
|
|
column_count.valueChanged.connect(columns)
|
||
|
|
def selection(r: int, c: int, *_: object) -> None:
|
||
|
|
align.blockSignals(True)
|
||
|
|
align.setCurrentIndex(max(0, align.findData(alignment[c] if 0 <= c < len(alignment) else "")))
|
||
|
|
align.blockSignals(False)
|
||
|
|
table.currentCellChanged.connect(selection)
|
||
|
|
def set_alignment() -> None:
|
||
|
|
if table.currentColumn() >= 0:
|
||
|
|
alignment[table.currentColumn()] = str(align.currentData())
|
||
|
|
align.currentIndexChanged.connect(set_alignment)
|
||
|
|
populate(rows)
|
||
|
|
actions = QHBoxLayout()
|
||
|
|
def add_row() -> None:
|
||
|
|
if table.rowCount() < MAX_ROWS:
|
||
|
|
table.insertRow(max(1, table.currentRow() + 1))
|
||
|
|
row_count.setValue(table.rowCount())
|
||
|
|
def remove_row() -> None:
|
||
|
|
if table.rowCount() > 1 and table.currentRow() >= 0:
|
||
|
|
table.removeRow(table.currentRow()); row_count.setValue(table.rowCount())
|
||
|
|
def add_column() -> None:
|
||
|
|
if table.columnCount() < MAX_COLUMNS:
|
||
|
|
index = max(0, table.currentColumn() + 1)
|
||
|
|
table.insertColumn(index); alignment.insert(index, ""); column_count.setValue(table.columnCount())
|
||
|
|
def remove_column() -> None:
|
||
|
|
if table.columnCount() > 1 and table.currentColumn() >= 0:
|
||
|
|
alignment.pop(table.currentColumn()); table.removeColumn(table.currentColumn()); column_count.setValue(table.columnCount())
|
||
|
|
def paste() -> None:
|
||
|
|
try:
|
||
|
|
values = parse_tsv(QApplication.clipboard().text())
|
||
|
|
except (ValueError, csv.Error) as exc:
|
||
|
|
QMessageBox.warning(dialog, "无法粘贴表格", str(exc))
|
||
|
|
return
|
||
|
|
if values:
|
||
|
|
populate(values)
|
||
|
|
for title, callback in [("插入行", add_row), ("删除行", remove_row), ("插入列", add_column),
|
||
|
|
("删除列", remove_column), ("从 Excel 粘贴", paste)]:
|
||
|
|
button = QPushButton(title); button.clicked.connect(callback); actions.addWidget(button)
|
||
|
|
layout.addLayout(actions)
|
||
|
|
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
|
||
|
|
buttons.accepted.connect(dialog.accept); buttons.rejected.connect(dialog.reject)
|
||
|
|
layout.addWidget(buttons)
|
||
|
|
if dialog.exec() != QDialog.DialogCode.Accepted:
|
||
|
|
return None
|
||
|
|
result = [[table.item(r, c).text() if table.item(r, c) else "" for c in range(table.columnCount())]
|
||
|
|
for r in range(table.rowCount())]
|
||
|
|
return format_table(result, alignment)
|