Here's a simple implementation with just HTML, CSS, and Python (no external dependencies) for a local Markdown table editor:
File Structure
/markdown-table-editor/
├── server.py
├── index.html
├── style.css
├── script.js
└── data.md
server.py
import http.server
import socketserver
import json
import os
import re
from urllib.parse import parse_qs, urlparse
PORT = 8000
DATA_FILE = "data.md"
# Create empty data file if it doesn't exist
if not os.path.exists(DATA_FILE):
with open(DATA_FILE, "w") as f:
f.write("# Markdown Tables\n")
class RequestHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
parsed_path = urlparse(self.path)
if parsed_path.path == '/api/tables':
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
with open(DATA_FILE, 'r') as f:
content = f.read()
tables = []
current_table = None
for line in content.split('\n'):
if line.startswith('## '):
if current_table:
tables.append(current_table)
current_table = {
'title': line[3:].strip(),
'headers': [],
'rows': []
}
elif current_table and line.startswith('|'):
cells = [cell.strip() for cell in line.split('|')[1:-1]]
if not current_table['headers']:
current_table['headers'] = cells
elif not all(c.startswith('-') for c in cells):
current_table['rows'].append(cells)
if current_table:
tables.append(current_table)
self.wfile.write(json.dumps(tables).encode())
return
else:
return super().do_GET()
def do_POST(self):
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length).decode('utf-8')
data = json.loads(post_data)
if self.path == '/api/add-table':
title = data.get('title', 'New Table')
with open(DATA_FILE, 'a') as f:
f.write(f"\n## {title}\n| Task | Done |\n| --- | --- |\n")
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({"success": True}).encode())
return
elif self.path == '/api/add-row':
table_title = data.get('table')
task = data.get('task', 'New Task')
done = data.get('done', False)
done_mark = "✅" if done else "⬜"
with open(DATA_FILE, 'r') as f:
content = f.read()
lines = content.split('\n')
table_found = False
separator_found = False
insert_index = -1
for i, line in enumerate(lines):
if line.startswith(f"## {table_title}"):
table_found = True
elif table_found and line.startswith('| --- | --- |'):
separator_found = True
elif table_found and separator_found and (not line.strip() or line.startswith('##')):
insert_index = i
break
if insert_index == -1:
insert_index = len(lines)
lines.insert(insert_index, f"| {task} | {done_mark} |")
with open(DATA_FILE, 'w') as f:
f.write('\n'.join(lines))
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({"success": True}).encode())
return
elif self.path == '/api/update-tables':
tables = data.get('tables', [])
content = "# Markdown Tables\n"
for table in tables:
content += f"\n## {table['title']}\n"
content += f"| {' | '.join(table['headers'])} |\n"
content += f"| {' | '.join(['---' for _ in table['headers']])} |\n"
for row in table['rows']:
content += f"| {' | '.join(row)} |\n"
with open(DATA_FILE, 'w') as f:
f.write(content)
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({"success": True}).encode())
return
self.send_response(404)
self.end_headers()
with socketserver.TCPServer(("", PORT), RequestHandler) as httpd:
print(f"Server running at http://localhost:{PORT}")
httpd.serve_forever()
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Markdown Table Editor</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<h1>Markdown Table Editor</h1>
<button id="add-table-btn">+ Add New Table</button>
</header>
<main id="tables-container">
<!-- Tables will be loaded here -->
</main>
<script src="script.js"></script>
</body>
</html>
style.css
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
line-height: 1.6;
color: #333;
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 30px;
padding-bottom: 10px;
border-bottom: 1px solid #eee;
}
button {
background-color: #4CAF50;
color: white;
border: none;
padding: 8px 16px;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
}
button:hover {
background-color: #45a049;
}
.table-container {
margin-bottom: 40px;
border: 1px solid #ddd;
border-radius: 8px;
padding: 20px;
background-color: #f9f9f9;
}
.table-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 15px;
}
table {
width: 100%;
border-collapse: collapse;
margin-bottom: 15px;
background-color: white;
}
th, td {
border: 1px solid #ddd;
padding: 12px;
text-align: left;
}
th {
background-color: #f2f2f2;
font-weight: bold;
}
.add-row {
background-color: transparent;
border: 1px dashed #ccc;
padding: 10px;
margin-top: 10px;
display: flex;
align-items: center;
}
.add-row input[type="text"] {
flex: 1;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
margin-right: 10px;
}
.add-row button {
background-color: #2196F3;
}
.add-row button:hover {
background-color: #0b7dda;
}
.copy-btn {
background-color: #ff9800;
}
.copy-btn:hover {
background-color: #e68a00;
}
.checkbox {
width: 20px;
height: 20px;
cursor: pointer;
}
script.js
document.addEventListener('DOMContentLoaded', function() {
const tablesContainer = document.getElementById('tables-container');
const addTableBtn = document.getElementById('add-table-btn');
let tables = [];
// Load tables from server
function loadTables() {
fetch('/api/tables')
.then(response => response.json())
.then(data => {
tables = data;
renderTables();
})
.catch(error => console.error('Error loading tables:', error));
}
// Render all tables
function renderTables() {
tablesContainer.innerHTML = '';
tables.forEach(table => {
const tableContainer = document.createElement('div');
tableContainer.className = 'table-container';
// Table header with title and copy button
const tableHeader = document.createElement('div');
tableHeader.className = 'table-header';
const tableTitle = document.createElement('h2');
tableTitle.textContent = table.title;
const copyBtn = document.createElement('button');
copyBtn.className = 'copy-btn';
copyBtn.textContent = 'Copy as Markdown';
copyBtn.addEventListener('click', () => copyTableAsMarkdown(table));
tableHeader.appendChild(tableTitle);
tableHeader.appendChild(copyBtn);
tableContainer.appendChild(tableHeader);
// Create table element
const tableElement = document.createElement('table');
// Create table header
const thead = document.createElement('thead');
const headerRow = document.createElement('tr');
table.headers.forEach(header => {
const th = document.createElement('th');
th.textContent = header;
headerRow.appendChild(th);
});
thead.appendChild(headerRow);
tableElement.appendChild(thead);
// Create table body
const tbody = document.createElement('tbody');
table.rows.forEach(row => {
const tr = document.createElement('tr');
row.forEach((cell, index) => {
const td = document.createElement('td');
if (index === 1 && (cell === '✅' || cell === '⬜')) {
// Create checkbox for "Done" column
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.className = 'checkbox';
checkbox.checked = cell === '✅';
checkbox.addEventListener('change', (e) => {
row[index] = e.target.checked ? '✅' : '⬜';
updateTables();
});
td.appendChild(checkbox);
} else {
td.textContent = cell;
}
tr.appendChild(td);
});
tbody.appendChild(tr);
});
tableElement.appendChild(tbody);
tableContainer.appendChild(tableElement);
// Add row form
const addRowForm = document.createElement('div');
addRowForm.className = 'add-row';
const taskInput = document.createElement('input');
taskInput.type = 'text';
taskInput.placeholder = 'New task name';
const addBtn = document.createElement('button');
addBtn.textContent = '+ ADD';
addBtn.addEventListener('click', () => {
if (taskInput.value.trim()) {
addRow(table.title, taskInput.value.trim());
taskInput.value = '';
}
});
addRowForm.appendChild(taskInput);
addRowForm.appendChild(addBtn);
tableContainer.appendChild(addRowForm);
tablesContainer.appendChild(tableContainer);
});
}
// Add a new table
function addTable(title) {
fetch('/api/add-table', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ title })
})
.then(response => response.json())
.then(() => loadTables())
.catch(error => console.error('Error adding table:', error));
}
// Add a new row to a table
function addRow(tableTitle, task) {
fetch('/api/add-row', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ table: tableTitle, task, done: false })
})
.then(response => response.json())
.then(() => loadTables())
.catch(error => console.error('Error adding row:', error));
}
// Update all tables
function updateTables() {
fetch('/api/update-tables', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ tables })
})
.then(response => response.json())
.catch(error => console.error('Error updating tables:', error));
}
// Copy table as markdown
function copyTableAsMarkdown(table) {
let markdown = `## ${table.title}\n`;
markdown += `| ${table.headers.join(' | ')} |\n`;
markdown += `| ${table.headers.map(() => '---').join(' | ')} |\n`;
table.rows.forEach(row => {
markdown += `| ${row.join(' | ')} |\n`;
});
navigator.clipboard.writeText(markdown)
.then(() => alert('Table copied to clipboard as Markdown!'))
.catch(err => console.error('Could not copy text: ', err));
}
// Event listeners
addTableBtn.addEventListener('click', () => {
const title = prompt('Enter table title:');
if (title) {
addTable(title);
}
});
// Initial load
loadTables();
});
How to Use
- Save all files in a directory
- Run the Python server:
python server.py
- Open your browser and go to:
http://localhost:8000
Features
- Create new tables with the "+ Add New Table" button
- Add rows to tables with the "+ ADD" button in each table
- Mark tasks as done/not done with checkboxes
- Copy tables as Markdown with the "Copy as Markdown" button
- All changes are saved to the
data.md file
This implementation:
- Uses zero external dependencies
- Runs completely locally
- Supports creating and editing Markdown tables
- Has a clean, simple UI with "+ ADD" buttons
- Allows copying tables as Markdown
- Saves all data in a single .md file
Would you like me to explain any specific part of the implementation in more detail?