
Markdown To Docx
- 607 installs
- 7 repo stars
- Updated June 18, 2026
- duc01226/easyplatform
markdown-to-docx is a Claude Code skill that converts clean Markdown files into polished Word .docx documents for developers who need proposals, specs, user guides, or client deliverables without manual Word formatting.
About
markdown-to-docx is a skills.sh skill from duc01226/easyplatform with 521 installs and rank 9262. It turns clean Markdown source files into polished Microsoft Word .docx documents suitable for proposals, technical specs, user guides, and client deliverables. Developers reach for markdown-to-docx when stakeholders require Word format but the team authors and versions content in Markdown. The skill automates document conversion so engineers avoid hand-copying headings, lists, and body text into Word.
- Converts Markdown to fully formatted Microsoft Word .docx files
- Preserves headings, lists, tables, code blocks, and basic styling
- Runs locally as a lightweight MCP-compatible skill
- Eliminates copy-paste reformatting when sharing docs outside browsers
Markdown To Docx by the numbers
- 607 all-time installs (skills.sh)
- Ranked #358 of 1,879 Documentation skills by installs in the Skillselion catalog
- Data as of Jul 29, 2026 (Skillselion catalog sync)
npx skills add https://github.com/duc01226/easyplatform --skill markdown-to-docxAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 607 |
|---|---|
| repo stars | ★ 7 |
| Last updated | June 18, 2026 |
| Repository | duc01226/easyplatform ↗ |
How do you convert Markdown files to Word docx?
Instantly turn clean Markdown files into polished Word.docx documents for proposals, specs, user guides, or client deliverables.
Who is it for?
Developers and technical writers who maintain docs in Markdown but must deliver formatted Word documents to clients or procurement teams.
Skip if: Teams that publish only HTML or PDF from static site generators and never need .docx output should skip markdown-to-docx.
When should I use this skill?
The user needs to turn a Markdown file into a Word .docx for a proposal, spec, user guide, or client deliverable.
What you get
Polished .docx Word documents generated from Markdown source files.
- Polished .docx Word document
By the numbers
- 521 installs on skills.sh
- Rank 9262 on skills.sh
- Source repository duc01226/easyplatform
Files
Codex compatibility note:
>
- Invoke repository skills with$skill-namein Codex; this mirrored copy rewrites legacy Claude/skill-namereferences.
- Task tracker mandate: BEFORE executing any workflow or skill step, create/update task tracking for all steps and keep it synchronized as progress changes.
- User-question prompts mean to ask the user directly in Codex.
- Ignore Claude-specific mode-switch instructions when they appear.
- Strict execution contract: when a user explicitly invokes a skill, execute that skill protocol as written.
- Subagent authorization: when a skill is user-invoked or AI-detected and its protocol requires subagents, that skill activation authorizes use of the required spawn_agent subagent(s) for that task.- Do not skip, reorder, or merge protocol steps unless the user explicitly approves the deviation first.
- For workflow skills, execute each listed child-skill step explicitly and report step-by-step evidence.
- If a required step/tool cannot run in this environment, stop and ask the user before adapting.
<!-- CODEX:PROJECT-REFERENCE-LOADING:START -->
Codex Project-Reference Loading (No Hooks)
Codex uses static project-reference loading instead of runtime-injected project docs. When coding, planning, debugging, testing, or reviewing, open project docs explicitly using this routing.
Always read:
docs/project-config.json(project-specific paths, commands, modules, and workflow/test settings)docs/project-reference/docs-index-reference.md(routes to the fulldocs/project-reference/*catalog)docs/project-reference/lessons.md(always-on guardrails and anti-patterns)
Missing/stale context route: If docs/project-config.json, the docs index, lessons.md, CLAUDE.md, AGENTS.md, or any task-required reference doc is missing or stale, auto-run $project-init or the narrow setup route ($project-config, $docs-init, $scan-all, $scan --target=<key>, $claude-md-init) before ordinary project-specific work. If Codex mirrors or AGENTS.md are missing/stale, ask the user to run $sync-codex; do not auto-run it.
Situation-based docs:
- Backend/CQRS/API/domain/entity changes:
backend-patterns-reference.md,domain-entities-reference.md,project-structure-reference.md - Frontend/UI/styling/design-system:
frontend-patterns-reference.md,scss-styling-guide.md,design-system/README.md - Spec authoring,
docs/specs/pathing, or TC format:feature-spec-reference.md,spec-system-reference.md,spec-principles.md - Behavior/public-contract changes or spec-test-code sync:
workflow-spec-test-code-cycle-reference.mdplus the spec docs above - Derived spec indexes/ERDs/reimplementation guides:
spec-system-reference.mdand source Feature Specs underdocs/specs/ - Integration test implementation/review:
integration-test-reference.md - E2E test implementation/review:
e2e-test-reference.md - Code review/audit work:
code-review-rules.mdplus domain docs above based on changed files
Do not read all docs blindly. Start from docs-index-reference.md, then open only relevant files for the task.
<!-- CODEX:PROJECT-REFERENCE-LOADING:END -->
Quick Summary
Goal: Convert Markdown files to Microsoft Word (.docx) format with GFM support and proper formatting.
Workflow:
1. Install -- Ensure pandoc is available (required dependency) 2. Convert -- Run pandoc with docx output, apply reference template if provided 3. Verify -- Check output file for formatting fidelity
Key Rules:
- Requires pandoc installed on the system
- Supports GFM tables, code blocks, and images
- Optional reference.docx template for custom styling
Be skeptical. Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence percentages (Idea should be more than 80%).
markdown-to-docx
Convert markdown files to editable Microsoft Word documents with support for tables, code blocks, images, and LaTeX math equations.
Installation Required
This skill requires npm dependencies. Run one of:
# Option 1: ClaudeKit CLI (recommended)
ck init
# Option 2: Manual
cd .claude/skills/markdown-to-docx
npm installDependencies: markdown-docx, gray-matter
Quick Start
# Basic conversion
node .claude/skills/markdown-to-docx/scripts/convert.cjs --input ./README.md
# Specify output path
node .claude/skills/markdown-to-docx/scripts/convert.cjs -i ./doc.md -o ./output.docx
# With custom theme
node .claude/skills/markdown-to-docx/scripts/convert.cjs -i ./doc.md --theme ./theme.jsonCLI Options
| Option | Short | Description | Default |
|---|---|---|---|
--input | -i | Input markdown file | (required) |
--output | -o | Output DOCX path | {input}.docx |
--theme | -t | Custom theme JSON | built-in |
--title | Document title | filename | |
--help | -h | Show help |
Features
- GFM Support: Tables, strikethrough, task lists
- Code Blocks: Syntax preserved with monospace font
- Images: Local and URL images embedded
- Math: LaTeX equations rendered by default (
$...$,$$...$$) - Frontmatter: YAML metadata extracted for title
- No System Dependencies: Pure JavaScript, no Chrome needed
Output
Returns JSON on success:
{
"success": true,
"input": "/path/to/input.md",
"output": "/path/to/output.docx"
}Compatibility
Generated DOCX files work with:
- Microsoft Word (2007+)
- Google Docs (upload to Drive)
- LibreOffice Writer
- Apple Pages
---
[IMPORTANT] Use task tracking to break ALL work into small tasks BEFORE starting — including tasks for each file read. This prevents context loss from long files. For simple tasks, AI MUST ATTENTION ask user whether to skip.
<!-- SYNC:ai-mistake-prevention -->
AI Mistake Prevention — Failure modes to avoid on every task:
>
Re-read files after context changes. Context compaction, resume, or long-running work can make memory stale; verify current files before acting.
Verify generated content against source evidence. AI hallucinates APIs, names, claims, and document facts. Check the relevant source before documenting or referencing.
Check downstream references before deleting or renaming. Removing an artifact can stale docs, generated mirrors, configs, and callers; map references first.
Trace the full impact chain after edits. Changing a definition can miss derived outputs and consumers. Follow the affected chain before declaring done.
Verify ALL affected outputs, not just the first. One green check is not all green checks; validate every output surface the change can affect.
Assume existing values are intentional — ask WHY before changing. Before changing a constant, limit, flag, wording, or pattern, read nearby context and history.
Surface ambiguity before acting — don't pick silently. Multiple valid interpretations require an explicit question or stated assumption with risk.
Keep shared guidance role-relevant. Universal guidance must help every receiving skill or agent; code-specific obligations belong only in code-specific protocols.
<!-- /SYNC:ai-mistake-prevention -->
<!-- SYNC:critical-thinking-mindset -->
Critical Thinking Mindset — Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
Anti-hallucination: Never present guess as fact — cite sources for every claim, admit uncertainty freely, self-check output for errors, cross-reference independently, stay skeptical of own confidence — certainty without evidence root of all hallucination.
<!-- /SYNC:critical-thinking-mindset -->
<!-- SYNC:critical-thinking-mindset:reminder -->
MUST ATTENTION apply critical + sequential thinking — every claim needs appropriate traced evidence (file:line for repo/code claims; source URL or artifact section for research, product, content, and docs claims); confidence >80% to act, <60% DO NOT recommend. Anti-hallucination: never present guess as fact, admit uncertainty freely, cross-reference independently, stay skeptical of own confidence.
<!-- /SYNC:critical-thinking-mindset:reminder -->
<!-- SYNC:ai-mistake-prevention:reminder -->
MUST ATTENTION apply AI mistake prevention — verify generated content against evidence, trace downstream references before deleting or renaming, verify all affected outputs, re-read files after context loss, and surface ambiguity before acting.
<!-- /SYNC:ai-mistake-prevention:reminder -->
Closing Reminders
IMPORTANT MUST ATTENTION break work into small todo tasks using task tracking BEFORE starting
MUST ATTENTION Protocols in force (concise digest of the SYNC/shared blocks this skill carries):
- AI Mistake Prevention: verify generated content against evidence, trace downstream references, verify all affected outputs, re-read after context loss, surface ambiguity.
- Critical Thinking: traced
file:lineproof, confidence >80% to act, NEVER guess as fact.
IMPORTANT MUST ATTENTION search codebase for 3+ similar patterns before creating new code IMPORTANT MUST ATTENTION cite file:line evidence for every claim (confidence >80% to act) IMPORTANT MUST ATTENTION add a final review todo task to verify work quality
[TASK-PLANNING] Before acting, analyze task scope and systematically break it into small todo tasks and sub-tasks using task tracking.
<!-- CODEX:SYNC-PROMPT-PROTOCOLS:START -->
Hookless Prompt Protocol Mirror (Auto-Synced)
Source: .claude/.ck.json + .claude/skills/shared/sync-inline-versions.md (:full blocks) + .claude/scripts/lib/hookless-prompt-protocol.cjs
[WORKFLOW-EXECUTION-PROTOCOL] [BLOCKING] Workflow Execution Protocol — MANDATORY IMPORTANT MUST CRITICAL. Do not skip for any reason.
Generic portability boundary: Reusable skills and protocol text stay project-neutral; project-specific conventions are discovered from docs/project-config.json and docs/project-reference/. Apply shared AI-SDD from shared/sdd-artifact-contract.md. Read docs/project-config.json and docs/project-reference/docs-index-reference.md, then open the project reference docs named there. For spec, test-case, behavior-change, public-contract, or docs/specs/ work, route through the local spec docs named by the docs index: feature-spec-reference.md, spec-system-reference.md, spec-principles.md, and workflow-spec-test-code-cycle-reference.md when specs/tests/code must stay synchronized. If either file or a required reference doc is missing or stale, auto-run $project-init (or the narrow lower-level route such as $project-config, $docs-init, $scan-all, or $scan --target=<key>) before ordinary project-specific work. Any supported AI tool may execute when this shared context and local docs are available.
1. DETECT: If the prompt starts with an explicit slash skill/workflow command, execute it directly. Otherwise match the prompt against the workflow catalog and skill list. 2. ANALYZE: Choose the best option: execute directly, invoke a skill, activate a standard workflow, or compose a custom step combination. 3. AUTO-SELECT: Pick the best option yourself. Do not ask the user to choose between direct execution, skill, standard workflow, or custom workflow. 4. ACTIVATE: For a selected workflow, call $start-workflow <workflowId>; for a selected skill, invoke that skill; for a custom workflow, sequence custom steps directly; for direct execution, proceed with the task. 5. CREATE TASKS: task tracking for ALL workflow/skill/custom steps before execution when the selected path has multiple steps. 6. EXECUTE: Advance per the Workflow Step Advancement & Parallel Phases rule in your context instructions — model-driven; a sub-agent completion advances a step identically to an inline call; a parallel-phase group is an all-return barrier (advance only after ALL members return, never serialize it)
Shared AI-SDD Protocol Markers
Source: .claude/skills/shared/sync-inline-versions.md
SYNC:ai-sdd-artifact-contract
AI-SDD Artifact Contract — Shared spec-driven development rules stay portable and source-owned.
>
1. Keep reusable AI-SDD principles in .claude; put repository-specific paths, commands, owners, products, and formats in project config/reference docs.2. Preserve cycle: spec -> plan -> tasks -> implement -> verify -> update spec/docs.3. Trace every requirement or invariant through decision, task, TC/test, source evidence, and docs/spec update.
4. Treat code-to-spec extraction as reference-only until accepted by the canonical spec owner.
5. Any supported AI tool may plan, implement, review, or verify with synced context; using multiple tools is optional.
6. Update.claudesource first, then sync generated mirrors; do not manually edit.agents,.codex, orAGENTS.md. — why: mirrors are generated artifacts; hand-edits are overwritten on the next sync
7. Ifdocs/project-config.json, root instruction files, or a required project-reference doc is missing or stale, auto-run$project-initor the narrow lower-level route before ordinary project-specific work.
>
Active reference: shared/sdd-artifact-contract.md in the active skills root.---
SYNC:ai-sdd-artifact-contract:reminder
- MANDATORY Apply
shared/sdd-artifact-contract.md; keep reusable AI-SDD in.claudeand local rules in project docs. - MANDATORY Code-to-spec extraction is reference-only until canonical acceptance; any supported AI tool may execute with synced context.
- MANDATORY Update
.claudesource before syncing generated mirrors; do not manually edit.agents,.codex, orAGENTS.md. - MANDATORY Missing or stale project config, root instruction files, or required reference docs route project-specific work through
$project-initor the narrow setup route automatically.
[TASK-PLANNING] [MANDATORY] BEFORE executing any workflow or skill step, create/update task tracking for all planned steps, then keep it synchronized as each step starts/completes.
[LESSON-LEARNED-REMINDER] [BLOCKING] Task Planning & Continuous Improvement — MANDATORY. Do not skip.
Break work into small tasks (task tracking) before starting. Add final task: "Analyze AI mistakes & lessons learned".
Extract lessons — ROOT CAUSE ONLY, not symptom fixes:
1. Name the FAILURE MODE (reasoning/assumption failure), not symptom — "assumed API existed without reading source" not "used wrong enum value". 2. Generality test: does this failure mode apply to ≥3 contexts/codebases? If not, abstract one level up. 3. Write as a universal rule — strip project-specific names/paths/classes. Useful on any codebase. 4. Consolidate: multiple mistakes sharing one failure mode → ONE lesson. 5. Recurrence gate: "Would this recur in future session WITHOUT this reminder?" — No → skip $learn. 6. Auto-fix gate: "Could $code-review/$code-simplifier/$security-review/$lint catch this?" — Yes → improve review skill instead. 7. BOTH gates pass → ask user to run $learn. [CRITICAL-THINKING-MINDSET] Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act. Anti-hallucination principle: Never present guess as fact — cite sources for every claim, admit uncertainty freely, self-check output for errors, cross-reference independently, stay skeptical of own confidence — certainty without evidence root of all hallucination. AI Attention principle (Primacy-Recency): Put the 3 most critical rules at both top and bottom of long prompts/protocols so instruction adherence survives long context windows. Goal-driven execution: Define success criteria first, loop until verified, and stop only when observable checks pass. Tests verify intent: Tests must protect business rules/invariants and fail when the protected intent breaks, not only mirror current behavior.
Common AI Mistake Prevention (System Lessons)
- Re-read files after context compaction. Edit requires prior Read in same context; compaction wipes read state. Re-read before editing.
- Grep for old terms after bulk replacements. AI over-trusts find/replace completeness. Grep full repo after bulk edits for missed refs in docs/configs/catalogs.
- Check downstream references before deleting. Deletions cascade doc/code staleness. Map referencing files before removal.
- After memory loss, check existing state before creating new. Compaction wipes prior-work memory. Query current state to resume — never blindly duplicate.
- Verify AI-generated content against actual code. AI hallucinates APIs, class names, method signatures. Grep to confirm existence before documenting/referencing.
- Trace full dependency chain after edits. Changing a definition misses downstream consumers. Trace the full chain.
- When renaming, grep ALL consumer file types. Some file types silently ignore missing refs (no compile error). Search code, templates, configs, generated files.
- Trace ALL code paths when verifying correctness. Code existing ≠ code executing. Trace early exits, error branches, conditional skips — not just happy path.
- Update docs that embed canonical data when source changes. Docs inlining derived data (workflows, schemas, configs) go stale silently. Update all embedding docs alongside source.
- Verify sub-agent results after context recovery. Background agents may finish while parent compacted — grep-verify output, don't trust assumed completion.
- Cross-check full target list against sub-agent assignments. Parallel sub-agents by category miss boundary items. Reconcile union of assignments against target list before proceeding.
- Sub-agents inherit knowledge only from their agent .md definition — use custom agent types, not built-in Explore. Tool adoption = permission + knowledge + enforcement (numbered workflow step).
- Persist sub-agent findings incrementally, not as a final batch. Long sub-agents hit cutoffs before final write — findings lost. Instruct append-per-section to report file.
- When debugging, ask "whose responsibility?" before fixing. Trace caller (wrong data) vs callee (wrong handling). Fix at responsible layer — never patch symptom site.
- Grep ALL removed names after extraction/refactoring. Primary file "done" ≠ secondary files clean. Grep entire scope for every removed symbol before declaring complete.
- Assume existing values are intentional — ask WHY before changing. Pattern-matching as "wrong" skips context. Before changing any constant/limit/flag: read comments, git blame, surrounding code.
- Verify ALL affected outputs, not just the first. One build green ≠ all green. Multi-stack changes (backend/frontend/tests/docs) require verifying EVERY output.
- Evaluate fit before copying a nearby pattern. Closest example ≠ matching preconditions — verify the new context shares the same constraints, base classes, scope, lifetime.
- Holistic-first debugging — resist nearest-attention trap. Don't dive into first plausible cause. List EVERY precondition (config, env vars, paths, DB, endpoints, creds, versions, DI, data). Verify each against evidence (grep/query — not reasoning). Ask "what would falsify this?" — if nothing, it's not a hypothesis. Most expensive failure: going deeper in "obvious" layer while bug sits in layer never questioned.
- Surgical changes — apply the diff test (context-aware). Two modes: (1) Bug fix → every line traces to the bug; no restyling; orphan cleanup only for imports YOUR changes made unused. (2) Review/enhancement → implement improvements AND announce as "Enhancement beyond main request: [what]". Never silently scope-creep. Diff test: "Would this line exist if I wasn't asked to do X?" — if no, delete or announce.
- Surface ambiguity before coding — don't pick silently. Multiple valid interpretations → present each with effort: "[Request] could mean (1) [N h], (2) [N h]. Which matters?" List scope/format/volume/constraints assumptions first. If simpler path exists, say so. Never silently pick.
- [MANDATORY FIRST ACTION] ALWAYS activate a suitable skill or workflow BEFORE responding. Match task against workflow catalog + skill list; invoke via skill invocation or
$start-workflow <workflowId>. NEVER answer or write code before checking. Skip = protocol violation. - Why-Review adversarial mindset — apply when reviewing any plan, decision, or design. Default SKEPTIC not VALIDATOR: steel-man a rejected alternative, invert each stated reason ("what does it sacrifice?"), stress-test top 2-3 assumptions, run pre-mortem ("ships, fails in 3 months — what breaks?"), surface 1-2 alternatives author missed. Section presence ≠ quality; quality = causal reasoning + concrete mitigations + evidence, not "it's better" or "monitor closely".
- Front-load report-write in sub-agent prompts for large reviews. Many-file sub-agents hit budget before final write — findings lost. Design prompts so: (1) report-write is first explicit deliverable, (2) append per-file/section (not batched), (3) scope bounded so reads don't exhaust budget. Truncated mid-sentence with no report file → spawn narrower scope, don't retry same prompt.
- After context compaction, re-verify all prior phase outcomes before continuing. Summaries describe intent, not environment state (git index, filesystem, processes). On resume, FIRST audit: git status, re-read modified files, verify filesystem. Every "completed" claim is an untested hypothesis until evidence confirms.
- OOM/memory: check row count before row size. Triage: (1) Unbounded query — no DB filter for trigger? Push filter to DB; eliminates OOM. (2) Large rows? Projection reduces proportionally. Row reduction > projection in ROI.
- Keep domain concepts out of generic/shared/infrastructure layers. Reusable layer (shared library, framework, infra module) must reference NO consumer-specific domain concept — tenant/customer/product IDs, business entities, feature rules. Leak compiles + runs → passes review silently while coupling the "reusable" layer to one consumer. Keep shared type domain-free; push domain fields/logic down into the consumer via subclass/composition. — why: a layer coupled to one consumer's domain is no longer reusable.
<!-- CODEX:SYNC-PROMPT-PROTOCOLS:END -->
{
"heading1": "2563EB",
"heading2": "1D4ED8",
"heading3": "1E40AF",
"link": "2563EB",
"code": "374151",
"codeBackground": "F3F4F6",
"heading1Size": 32,
"heading2Size": 24,
"heading3Size": 18,
"paragraphSize": 11,
"codeSize": 10,
"fontFamily": "Calibri",
"codeFontFamily": "Consolas"
}
{
"name": "markdown-to-docx",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "markdown-to-docx",
"version": "1.0.0",
"dependencies": {
"gray-matter": "^4.0.3",
"markdown-docx": "^1.0.0"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@nodable/entities": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/@nodable/entities/-/entities-2.1.0.tgz",
"integrity": "sha512-nyT7T3nbMyBI/lvr6L5TyWbFJAI9FTgVRakNoBqCD+PmID8DzFrrNdLLtHMwMszOtqZa8PAOV24ZqDnQrhQINA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/nodable"
}
],
"license": "MIT"
},
"node_modules/@types/node": {
"version": "24.10.9",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.9.tgz",
"integrity": "sha512-ne4A0IpG3+2ETuREInjPNhUGis1SFjv1d5asp8MzEAGtOZeTeHVDOYqOgqfhvseqg/iXty2hjBf1zAOb7RNiNw==",
"license": "MIT",
"dependencies": {
"undici-types": "~7.16.0"
}
},
"node_modules/argparse": {
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz",
"integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==",
"license": "MIT",
"dependencies": {
"sprintf-js": "~1.0.2"
}
},
"node_modules/commander": {
"version": "13.1.0",
"resolved": "https://registry.npmjs.org/commander/-/commander-13.1.0.tgz",
"integrity": "sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw==",
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/core-util-is": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
"integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==",
"license": "MIT"
},
"node_modules/docx": {
"version": "9.5.1",
"resolved": "https://registry.npmjs.org/docx/-/docx-9.5.1.tgz",
"integrity": "sha512-ABDI7JEirFD2+bHhOBlsGZxaG1UgZb2M/QMKhLSDGgVNhxDesTCDcP+qoDnDGjZ4EOXTRfUjUgwHVuZ6VSTfWQ==",
"license": "MIT",
"dependencies": {
"@types/node": "^24.0.1",
"hash.js": "^1.1.7",
"jszip": "^3.10.1",
"nanoid": "^5.1.3",
"xml": "^1.0.1",
"xml-js": "^1.6.8"
},
"engines": {
"node": ">=10"
}
},
"node_modules/esprima": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz",
"integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==",
"license": "BSD-2-Clause",
"bin": {
"esparse": "bin/esparse.js",
"esvalidate": "bin/esvalidate.js"
},
"engines": {
"node": ">=4"
}
},
"node_modules/extend-shallow": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz",
"integrity": "sha512-zCnTtlxNoAiDc3gqY2aYAWFx7XWWiasuF2K8Me5WbN8otHKTUKBwjPtNpRs/rbUZm7KxWAaNj7P1a/p52GbVug==",
"license": "MIT",
"dependencies": {
"is-extendable": "^0.1.0"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/fast-xml-builder": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/fast-xml-builder/-/fast-xml-builder-1.1.5.tgz",
"integrity": "sha512-4TJn/8FKLeslLAH3dnohXqE3QSoxkhvaMzepOIZytwJXZO69Bfz0HBdDHzOTOon6G59Zrk6VQ2bEiv1t61rfkA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/NaturalIntelligence"
}
],
"license": "MIT",
"dependencies": {
"path-expression-matcher": "^1.1.3"
}
},
"node_modules/fast-xml-parser": {
"version": "5.7.2",
"resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.7.2.tgz",
"integrity": "sha512-P7oW7tLbYnhOLQk/Gv7cZgzgMPP/XN03K02/Jy6Y/NHzyIAIpxuZIM/YqAkfiXFPxA2CTm7NtCijK9EDu09u2w==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/NaturalIntelligence"
}
],
"license": "MIT",
"dependencies": {
"@nodable/entities": "^2.1.0",
"fast-xml-builder": "^1.1.5",
"path-expression-matcher": "^1.5.0",
"strnum": "^2.2.3"
},
"bin": {
"fxparser": "src/cli/cli.js"
}
},
"node_modules/gray-matter": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/gray-matter/-/gray-matter-4.0.3.tgz",
"integrity": "sha512-5v6yZd4JK3eMI3FqqCouswVqwugaA9r4dNZB1wwcmrD02QkV5H0y7XBQW8QwQqEaZY1pM9aqORSORhJRdNK44Q==",
"license": "MIT",
"dependencies": {
"js-yaml": "^3.13.1",
"kind-of": "^6.0.2",
"section-matter": "^1.0.0",
"strip-bom-string": "^1.0.0"
},
"engines": {
"node": ">=6.0"
}
},
"node_modules/hash.js": {
"version": "1.1.7",
"resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.1.7.tgz",
"integrity": "sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA==",
"license": "MIT",
"dependencies": {
"inherits": "^2.0.3",
"minimalistic-assert": "^1.0.1"
}
},
"node_modules/image-size": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/image-size/-/image-size-2.0.2.tgz",
"integrity": "sha512-IRqXKlaXwgSMAMtpNzZa1ZAe8m+Sa1770Dhk8VkSsP9LS+iHD62Zd8FQKs8fbPiagBE7BzoFX23cxFnwshpV6w==",
"license": "MIT",
"bin": {
"image-size": "bin/image-size.js"
},
"engines": {
"node": ">=16.x"
}
},
"node_modules/immediate": {
"version": "3.0.6",
"resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz",
"integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==",
"license": "MIT"
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"license": "ISC"
},
"node_modules/is-extendable": {
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz",
"integrity": "sha512-5BMULNob1vgFX6EjQw5izWDxrecWK9AM72rugNr0TFldMOi0fj6Jk+zeKIt0xGj4cEfQIJth4w3OKWOJ4f+AFw==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/isarray": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
"integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",
"license": "MIT"
},
"node_modules/js-yaml": {
"version": "3.14.2",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz",
"integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==",
"license": "MIT",
"dependencies": {
"argparse": "^1.0.7",
"esprima": "^4.0.0"
},
"bin": {
"js-yaml": "bin/js-yaml.js"
}
},
"node_modules/jszip": {
"version": "3.10.1",
"resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz",
"integrity": "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==",
"license": "(MIT OR GPL-3.0-or-later)",
"dependencies": {
"lie": "~3.3.0",
"pako": "~1.0.2",
"readable-stream": "~2.3.6",
"setimmediate": "^1.0.5"
}
},
"node_modules/katex": {
"version": "0.16.27",
"resolved": "https://registry.npmjs.org/katex/-/katex-0.16.27.tgz",
"integrity": "sha512-aeQoDkuRWSqQN6nSvVCEFvfXdqo1OQiCmmW1kc9xSdjutPv7BGO7pqY9sQRJpMOGrEdfDgF2TfRXe5eUAD2Waw==",
"funding": [
"https://opencollective.com/katex",
"https://github.com/sponsors/katex"
],
"license": "MIT",
"dependencies": {
"commander": "^8.3.0"
},
"bin": {
"katex": "cli.js"
}
},
"node_modules/katex/node_modules/commander": {
"version": "8.3.0",
"resolved": "https://registry.npmjs.org/commander/-/commander-8.3.0.tgz",
"integrity": "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==",
"license": "MIT",
"engines": {
"node": ">= 12"
}
},
"node_modules/kind-of": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz",
"integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/lie": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz",
"integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==",
"license": "MIT",
"dependencies": {
"immediate": "~3.0.5"
}
},
"node_modules/markdown-docx": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/markdown-docx/-/markdown-docx-1.5.1.tgz",
"integrity": "sha512-4mCZ/yVNiles3Yp5211OFLqctMywoGkfMcSxaes6u2zTMaa/N2DwAJPpidt0DxDA+mekD5oo0Zk8QooY8VVkLA==",
"license": "MIT",
"dependencies": {
"commander": "^13.1.0",
"docx": "^9.5.1",
"fast-xml-parser": "^5.3.0",
"image-size": "^2.0.2",
"katex": "^0.16.23",
"marked": "^15.0.8"
},
"bin": {
"markdown-docx": "bin/markdown-docx.mjs"
}
},
"node_modules/marked": {
"version": "15.0.12",
"resolved": "https://registry.npmjs.org/marked/-/marked-15.0.12.tgz",
"integrity": "sha512-8dD6FusOQSrpv9Z1rdNMdlSgQOIP880DHqnohobOmYLElGEqAL/JvxvuxZO16r4HtjTlfPRDC1hbvxC9dPN2nA==",
"license": "MIT",
"bin": {
"marked": "bin/marked.js"
},
"engines": {
"node": ">= 18"
}
},
"node_modules/minimalistic-assert": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz",
"integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==",
"license": "ISC"
},
"node_modules/nanoid": {
"version": "5.1.6",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.6.tgz",
"integrity": "sha512-c7+7RQ+dMB5dPwwCp4ee1/iV/q2P6aK1mTZcfr1BTuVlyW9hJYiMPybJCcnBlQtuSmTIWNeazm/zqNoZSSElBg==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"bin": {
"nanoid": "bin/nanoid.js"
},
"engines": {
"node": "^18 || >=20"
}
},
"node_modules/pako": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz",
"integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==",
"license": "(MIT AND Zlib)"
},
"node_modules/path-expression-matcher": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/path-expression-matcher/-/path-expression-matcher-1.5.0.tgz",
"integrity": "sha512-cbrerZV+6rvdQrrD+iGMcZFEiiSrbv9Tfdkvnusy6y0x0GKBXREFg/Y65GhIfm0tnLntThhzCnfKwp1WRjeCyQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/NaturalIntelligence"
}
],
"license": "MIT",
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/process-nextick-args": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
"integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",
"license": "MIT"
},
"node_modules/readable-stream": {
"version": "2.3.8",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
"integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
"license": "MIT",
"dependencies": {
"core-util-is": "~1.0.0",
"inherits": "~2.0.3",
"isarray": "~1.0.0",
"process-nextick-args": "~2.0.0",
"safe-buffer": "~5.1.1",
"string_decoder": "~1.1.1",
"util-deprecate": "~1.0.1"
}
},
"node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
"license": "MIT"
},
"node_modules/sax": {
"version": "1.4.4",
"resolved": "https://registry.npmjs.org/sax/-/sax-1.4.4.tgz",
"integrity": "sha512-1n3r/tGXO6b6VXMdFT54SHzT9ytu9yr7TaELowdYpMqY/Ao7EnlQGmAQ1+RatX7Tkkdm6hONI2owqNx2aZj5Sw==",
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=11.0.0"
}
},
"node_modules/section-matter": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/section-matter/-/section-matter-1.0.0.tgz",
"integrity": "sha512-vfD3pmTzGpufjScBh50YHKzEu2lxBWhVEHsNGoEXmCmn2hKGfeNLYMzCJpe8cD7gqX7TJluOVpBkAequ6dgMmA==",
"license": "MIT",
"dependencies": {
"extend-shallow": "^2.0.1",
"kind-of": "^6.0.0"
},
"engines": {
"node": ">=4"
}
},
"node_modules/setimmediate": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz",
"integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==",
"license": "MIT"
},
"node_modules/sprintf-js": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",
"integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==",
"license": "BSD-3-Clause"
},
"node_modules/string_decoder": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
"integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
"license": "MIT",
"dependencies": {
"safe-buffer": "~5.1.0"
}
},
"node_modules/strip-bom-string": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/strip-bom-string/-/strip-bom-string-1.0.0.tgz",
"integrity": "sha512-uCC2VHvQRYu+lMh4My/sFNmF2klFymLX1wHJeXnbEJERpV/ZsVuonzerjfrGpIGF7LBVa1O7i9kjiWvJiFck8g==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/strnum": {
"version": "2.2.3",
"resolved": "https://registry.npmjs.org/strnum/-/strnum-2.2.3.tgz",
"integrity": "sha512-oKx6RUCuHfT3oyVjtnrmn19H1SiCqgJSg+54XqURKp5aCMbrXrhLjRN9TjuwMjiYstZ0MzDrHqkGZ5dFTKd+zg==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/NaturalIntelligence"
}
],
"license": "MIT"
},
"node_modules/undici-types": {
"version": "7.16.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz",
"integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==",
"license": "MIT"
},
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
"license": "MIT"
},
"node_modules/xml": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/xml/-/xml-1.0.1.tgz",
"integrity": "sha512-huCv9IH9Tcf95zuYCsQraZtWnJvBtLVE0QHMOs8bWyZAFZNDcYjsPq1nEx8jKA9y+Beo9v+7OBPRisQTjinQMw==",
"license": "MIT"
},
"node_modules/xml-js": {
"version": "1.6.11",
"resolved": "https://registry.npmjs.org/xml-js/-/xml-js-1.6.11.tgz",
"integrity": "sha512-7rVi2KMfwfWFl+GpPg6m80IVMWXLRjO+PxTq7V2CDhoGak0wzYzFgUY2m4XJ47OGdXd8eLE8EmwfAmdjw7lC1g==",
"license": "MIT",
"dependencies": {
"sax": "^1.2.4"
},
"bin": {
"xml-js": "bin/cli.js"
}
}
}
}
{
"name": "markdown-to-docx",
"version": "1.0.0",
"description": "Convert markdown files to DOCX with GFM support and math rendering",
"main": "scripts/convert.cjs",
"scripts": {
"start": "node scripts/convert.cjs",
"test": "node tests/run-tests.cjs"
},
"dependencies": {
"gray-matter": "^4.0.3",
"markdown-docx": "^1.0.0"
},
"engines": {
"node": ">=18.0.0"
}
}
#!/usr/bin/env node
/**
* Markdown to DOCX Converter CLI
*
* Usage:
* node convert.cjs --input ./doc.md [--output ./out.docx] [--theme ./theme.json]
*
* Options:
* --input, -i Input markdown file (required)
* --output, -o Output DOCX path (default: input.docx)
* --theme, -t Custom theme JSON path
* --title Document title (overrides frontmatter)
* --help, -h Show help message
*/
const path = require('path');
/**
* Parse command line arguments
* @param {string[]} argv
* @returns {object}
*/
function parseArgs(argv) {
const args = {
input: null,
output: null,
theme: null,
title: null,
help: false
};
for (let i = 2; i < argv.length; i++) {
const arg = argv[i];
const nextArg = argv[i + 1];
switch (arg) {
case '--input':
case '-i':
args.input = nextArg;
i++;
break;
case '--output':
case '-o':
args.output = nextArg;
i++;
break;
case '--theme':
case '-t':
args.theme = nextArg;
i++;
break;
case '--title':
args.title = nextArg;
i++;
break;
case '--help':
case '-h':
args.help = true;
break;
default:
// Positional argument = input file
if (!arg.startsWith('-') && !args.input) {
args.input = arg;
}
}
}
return args;
}
/**
* Print help message
*/
function printHelp() {
console.log(`
markdown-to-docx - Convert markdown files to Microsoft Word
USAGE:
node convert.cjs --input <file.md> [options]
node convert.cjs <file.md> [options]
OPTIONS:
--input, -i <path> Input markdown file (required)
--output, -o <path> Output DOCX path (default: same as input with .docx)
--theme, -t <path> Custom theme JSON file
--title <string> Document title (overrides frontmatter)
--help, -h Show this help message
FEATURES:
- GFM tables, code blocks, images
- LaTeX math equations (enabled by default)
- Custom styling via theme JSON
- No system dependencies (pure JavaScript)
EXAMPLES:
# Basic conversion
node convert.cjs --input ./README.md
# With custom output
node convert.cjs -i ./docs/guide.md -o ./output/guide.docx
# With custom theme
node convert.cjs -i ./paper.md --theme ./academic-theme.json
OUTPUT:
Returns JSON on success:
{
"success": true,
"input": "/path/to/input.md",
"output": "/path/to/output.docx"
}
Returns JSON on error:
{
"success": false,
"error": "Error description"
}
EXIT CODES:
0 Success
1 Error
`);
}
/**
* Print result as JSON
* @param {object} result
*/
function printResult(result) {
console.log(JSON.stringify(result, null, 2));
}
/**
* Validate arguments
* @param {object} args
* @returns {{valid: boolean, error?: string}}
*/
function validateArgs(args) {
if (!args.input) {
return {
valid: false,
error: 'Input file required. Use --input <path> or provide positional argument.'
};
}
return { valid: true };
}
/**
* Check if dependencies are installed
* @returns {{available: boolean, missing: string[]}}
*/
function checkDependencies() {
const missing = [];
try {
require.resolve('markdown-docx');
} catch {
missing.push('markdown-docx');
}
try {
require.resolve('gray-matter');
} catch {
missing.push('gray-matter');
}
return {
available: missing.length === 0,
missing
};
}
/**
* Main entry point
*/
async function main() {
const args = parseArgs(process.argv);
if (args.help) {
printHelp();
process.exit(0);
}
const validation = validateArgs(args);
if (!validation.valid) {
printResult({ success: false, error: validation.error });
process.exit(1);
}
const deps = checkDependencies();
if (!deps.available) {
printResult({
success: false,
error: `Missing dependencies: ${deps.missing.join(', ')}. Run 'npm install' in skill directory.`,
hint: `cd ${path.dirname(__dirname)} && npm install`
});
process.exit(1);
}
// Import converter (lazy load after dependency check)
const { convert } = require('./lib/converter.cjs');
try {
const result = await convert({
input: args.input,
output: args.output,
theme: args.theme,
title: args.title
});
printResult(result);
process.exit(result.success ? 0 : 1);
} catch (error) {
printResult({
success: false,
error: error.message || 'Unexpected error during conversion'
});
process.exit(1);
}
}
// Run main
main().catch(error => {
console.error(JSON.stringify({
success: false,
error: `Unhandled error: ${error.message}`
}));
process.exit(1);
});
/**
* Configuration and theme loading for DOCX conversion
*/
const fs = require('fs');
const path = require('path');
const ASSETS_DIR = path.join(__dirname, '..', '..', 'assets');
const DEFAULT_THEME_PATH = path.join(ASSETS_DIR, 'default-theme.json');
/**
* Load markdown file and extract frontmatter
* @param {string} filePath
* @returns {{content: string, frontmatter: object}}
*/
function loadMarkdown(filePath) {
if (!fs.existsSync(filePath)) {
throw new Error(`Markdown file not found: ${filePath}`);
}
const raw = fs.readFileSync(filePath, 'utf8');
// Lazy load gray-matter
let matter;
try {
matter = require('gray-matter');
} catch {
// gray-matter not installed, return raw content
return { content: raw, frontmatter: {} };
}
const { content, data } = matter(raw);
return { content, frontmatter: data || {} };
}
/**
* Load theme configuration
* @param {string|null} customThemePath
* @returns {object}
*/
function loadTheme(customThemePath) {
// Load default theme
let theme = {};
if (fs.existsSync(DEFAULT_THEME_PATH)) {
theme = JSON.parse(fs.readFileSync(DEFAULT_THEME_PATH, 'utf8'));
}
// Merge custom theme if provided
if (customThemePath) {
const customPath = path.resolve(customThemePath);
if (!fs.existsSync(customPath)) {
throw new Error(`Theme file not found: ${customThemePath}`);
}
const custom = JSON.parse(fs.readFileSync(customPath, 'utf8'));
theme = { ...theme, ...custom };
}
return theme;
}
/**
* Get theme file path (for validation)
* @param {string|null} customThemePath
* @returns {string}
*/
function getThemePath(customThemePath) {
if (customThemePath) {
const resolved = path.resolve(customThemePath);
if (!fs.existsSync(resolved)) {
throw new Error(`Theme file not found: ${customThemePath}`);
}
return resolved;
}
return DEFAULT_THEME_PATH;
}
/**
* Build markdown-docx configuration
* Math is enabled by default (per validation decision)
* @param {object} options
* @returns {object}
*/
function buildConfig(options) {
const { theme, title } = options;
const config = {
theme: theme || {},
title: title,
creator: 'markdown-to-docx',
// Math enabled by default (validated decision)
math: {
engine: 'katex',
libreOfficeCompat: true
}
};
return config;
}
module.exports = {
loadMarkdown,
loadTheme,
getThemePath,
buildConfig,
DEFAULT_THEME_PATH
};
/**
* Core markdown-to-DOCX converter
* Wraps markdown-docx with configuration and error handling
*/
const fs = require('fs');
const path = require('path');
const { loadMarkdown, loadTheme, buildConfig } = require('./config-loader.cjs');
const { resolveOutputPath } = require('./output-handler.cjs');
/**
* Convert markdown file to DOCX
*
* @param {object} options
* @param {string} options.input - Input markdown file path
* @param {string|null} options.output - Output DOCX path (optional)
* @param {string|null} options.theme - Custom theme JSON path (optional)
* @param {string|null} options.title - Document title (optional)
* @returns {Promise<{success: boolean, input: string, output: string, error?: string}>}
*/
async function convert(options) {
const { input, output, theme, title } = options;
// Validate input
if (!input) {
return { success: false, error: 'Input file path is required' };
}
const absoluteInput = path.resolve(input);
if (!fs.existsSync(absoluteInput)) {
return { success: false, error: `Input file not found: ${absoluteInput}` };
}
try {
// Load markdown and extract frontmatter
const { content, frontmatter } = loadMarkdown(absoluteInput);
// Load theme configuration
const themeConfig = loadTheme(theme);
// Build conversion config
const config = buildConfig({
theme: themeConfig,
title: title || frontmatter.title || path.basename(absoluteInput, '.md')
});
// Import markdown-docx dynamically
let markdownDocx, Packer;
try {
const mdDocx = require('markdown-docx');
markdownDocx = mdDocx.default || mdDocx;
Packer = mdDocx.Packer;
} catch (err) {
return {
success: false,
error: 'markdown-docx not installed. Run `npm install` in the skill directory.'
};
}
// Perform conversion
const doc = await markdownDocx(content, config);
const buffer = await Packer.toBuffer(doc);
// Resolve output path
const outputPath = resolveOutputPath(absoluteInput, output, '.docx');
// Write output
fs.writeFileSync(outputPath, buffer);
// Verify output
if (!fs.existsSync(outputPath)) {
return { success: false, error: 'DOCX generation failed - no output file created' };
}
return {
success: true,
input: absoluteInput,
output: outputPath
};
} catch (error) {
return {
success: false,
error: error.message || 'Unknown conversion error',
stack: process.env.DEBUG ? error.stack : undefined
};
}
}
/**
* Check if markdown-docx is available
* @returns {boolean}
*/
function isAvailable() {
try {
require.resolve('markdown-docx');
return true;
} catch {
return false;
}
}
module.exports = { convert, isAvailable };
/**
* Output path resolution
* Ported from markdown-to-pdf with DOCX extension support
*/
const fs = require('fs');
const path = require('path');
/**
* Resolve output path based on input and user preference
*
* @param {string} inputPath - Input markdown file
* @param {string|null} outputPath - User-specified output (optional)
* @param {string} extension - Output extension (default: .docx)
* @returns {string} Resolved absolute output path
*/
function resolveOutputPath(inputPath, outputPath, extension = '.docx') {
const absoluteInput = path.resolve(inputPath);
const inputDir = path.dirname(absoluteInput);
const inputBasename = path.basename(absoluteInput, path.extname(absoluteInput));
// Default: same directory, new extension
if (!outputPath) {
return path.join(inputDir, `${inputBasename}${extension}`);
}
const absoluteOutput = path.resolve(outputPath);
// Check if output is directory
const isDirectory = outputPath.endsWith(path.sep) ||
outputPath.endsWith('/') ||
(fs.existsSync(absoluteOutput) && fs.statSync(absoluteOutput).isDirectory());
if (isDirectory) {
fs.mkdirSync(absoluteOutput, { recursive: true });
return path.join(absoluteOutput, `${inputBasename}${extension}`);
}
// Ensure parent directory exists
fs.mkdirSync(path.dirname(absoluteOutput), { recursive: true });
// Ensure correct extension
if (!absoluteOutput.toLowerCase().endsWith(extension)) {
return `${absoluteOutput}${extension}`;
}
return absoluteOutput;
}
module.exports = { resolveOutputPath };
/**
* Tests for markdown-to-docx converter and related modules
*/
const fs = require('fs');
const path = require('path');
describe('config-loader', () => {
const { loadMarkdown, loadTheme, buildConfig, getThemePath, DEFAULT_THEME_PATH } = require('../scripts/lib/config-loader.cjs');
const fixturesDir = path.join(__dirname, 'fixtures');
const sampleMd = path.join(fixturesDir, 'sample.md');
it('should have correct DEFAULT_THEME_PATH', () => {
assert.ok(DEFAULT_THEME_PATH.endsWith('default-theme.json'), 'DEFAULT_THEME_PATH should end with default-theme.json');
});
it('should load default theme', () => {
const theme = loadTheme(null);
assert.ok(typeof theme === 'object', 'Theme should be object');
assert.ok('fontFamily' in theme, 'Theme should have fontFamily');
});
it('should throw for missing custom theme via loadTheme', () => {
let threw = false;
try {
loadTheme('/nonexistent/path/to/file.json');
} catch (e) {
threw = true;
assert.ok(e.message.includes('Theme file not found'), 'Error should mention theme file not found');
}
assert.ok(threw, 'Should throw for missing theme file');
});
it('should return default theme path via getThemePath', () => {
const themePath = getThemePath(null);
assert.equal(themePath, DEFAULT_THEME_PATH, 'Should return default theme path');
});
it('should throw for missing custom theme via getThemePath', () => {
let threw = false;
try {
getThemePath('/nonexistent/path/to/file.json');
} catch (e) {
threw = true;
assert.ok(e.message.includes('Theme file not found'), 'Error should mention theme file not found');
}
assert.ok(threw, 'Should throw for missing theme file');
});
it('should load markdown with frontmatter', () => {
const { content, frontmatter } = loadMarkdown(sampleMd);
assert.ok(content.length > 0, 'Content should not be empty');
assert.ok(typeof frontmatter === 'object', 'Frontmatter should be object');
});
it('should throw for missing markdown file', () => {
let threw = false;
try {
loadMarkdown('/nonexistent/file.md');
} catch (e) {
threw = true;
assert.ok(e.message.includes('Markdown file not found'), 'Error should mention file not found');
}
assert.ok(threw, 'Should throw for missing markdown file');
});
it('should build config with math enabled by default', () => {
const config = buildConfig({ theme: {}, title: 'Test' });
assert.ok('math' in config, 'Config should have math');
assert.equal(config.math.engine, 'katex', 'Math engine should be katex');
assert.ok(config.math.libreOfficeCompat, 'LibreOffice compat should be enabled');
});
it('should set document title', () => {
const config = buildConfig({ title: 'My Document' });
assert.equal(config.title, 'My Document', 'Should set document title');
});
});
describe('output-handler', () => {
const { resolveOutputPath } = require('../scripts/lib/output-handler.cjs');
const fixturesDir = path.join(__dirname, 'fixtures');
it('should resolve output path from input (no output specified)', () => {
const result = resolveOutputPath('/path/to/doc.md', null, '.docx');
assert.ok(result.endsWith('.docx'), 'Result should end with .docx');
assert.ok(result.includes('doc.docx'), 'Result should contain doc.docx');
});
it('should use explicit output path', () => {
const result = resolveOutputPath('/path/to/doc.md', '/output/file.docx', '.docx');
assert.ok(result.endsWith('.docx'), 'Output should end with .docx');
});
it('should handle directory output', () => {
const result = resolveOutputPath('/path/to/doc.md', fixturesDir + '/', '.docx');
assert.ok(result.includes('doc.docx'), 'Should append filename to directory');
});
it('should add .docx extension if missing', () => {
const result = resolveOutputPath('/path/to/doc.md', '/output/file', '.docx');
assert.ok(result.endsWith('.docx'), 'Should add .docx extension');
});
});
describe('converter', () => {
const { isAvailable } = require('../scripts/lib/converter.cjs');
it('should report availability', () => {
const available = isAvailable();
assert.ok(typeof available === 'boolean', 'isAvailable should return boolean');
});
});
Sample Document
This is a test markdown file for the markdown-to-docx converter.
Features
- Bullet list item 1
- Bullet list item 2
- Bullet list item 3
Code Block
function hello() {
console.log('Hello, World!');
}Table
| Column A | Column B | Column C |
|---|---|---|
| Value 1 | Value 2 | Value 3 |
| Value 4 | Value 5 | Value 6 |
Math
Inline math: $E = mc^2$
Display math:
$$ \sum_{i=1}^{n} i = \frac{n(n+1)}{2} $$
Blockquote
This is a blockquote.
It can span multiple lines.
Task List
- [x] Completed task
- [ ] Pending task
- [ ] Another pending task
---
End of sample document.
#!/usr/bin/env node
/**
* Test runner for markdown-to-docx skill
*/
const fs = require('fs');
const path = require('path');
// Load test framework
require('./test-framework.cjs');
const testsDir = __dirname;
const testFiles = ['converter.test.cjs'];
console.log('\n' + '='.repeat(60));
console.log('markdown-to-docx Test Suite');
console.log('='.repeat(60));
// Load test files
for (const testFile of testFiles) {
const testPath = path.join(testsDir, testFile);
if (fs.existsSync(testPath)) {
try {
require(testPath);
} catch (error) {
console.error(`\nError loading ${testFile}: ${error.message}`);
if (process.env.DEBUG) {
console.error(error.stack);
}
}
} else {
console.log(`Skipping ${testFile} (not found)`);
}
}
// Run all tests
global.runAllTests().then(({ passed, failed }) => {
process.exit(failed > 0 ? 1 : 0);
});
/**
* Minimal test framework for skill testing
* Provides describe/it/assert pattern without external dependencies
*/
const assert = require('assert');
const suites = [];
let currentSuite = null;
/**
* Define a test suite
* @param {string} name - Suite name
* @param {Function} fn - Suite function containing tests
*/
global.describe = function(name, fn) {
const suite = { name, tests: [] };
suites.push(suite);
currentSuite = suite;
fn();
currentSuite = null;
};
/**
* Define a test case
* @param {string} name - Test name
* @param {Function} fn - Test function
*/
global.it = function(name, fn) {
if (currentSuite) {
currentSuite.tests.push({ name, fn });
}
};
/**
* Make assert available globally
*/
global.assert = assert;
/**
* Run all registered test suites
* @returns {Promise<{passed: number, failed: number}>}
*/
global.runAllTests = async function() {
let passed = 0;
let failed = 0;
const results = {};
for (const suite of suites) {
console.log(`\n ${suite.name}`);
results[suite.name] = { passed: 0, failed: 0 };
for (const test of suite.tests) {
try {
await test.fn();
console.log(` \x1b[32m✓\x1b[0m ${test.name}`);
passed++;
results[suite.name].passed++;
} catch (error) {
console.log(` \x1b[31m✗\x1b[0m ${test.name}`);
console.log(` \x1b[31m${error.message}\x1b[0m`);
failed++;
results[suite.name].failed++;
}
}
}
// Print summary
console.log('\n' + '='.repeat(60));
console.log('Results');
console.log('='.repeat(60) + '\n');
for (const [name, counts] of Object.entries(results)) {
const status = counts.failed === 0 ? '\x1b[32mPASS\x1b[0m' : '\x1b[31mFAIL\x1b[0m';
console.log(`${status}: ${name} (${counts.passed}/${counts.passed + counts.failed})`);
}
console.log('\n' + '='.repeat(60));
console.log(`Total: ${passed + failed} | Passed: ${passed} | Failed: ${failed}`);
console.log('='.repeat(60));
return { passed, failed };
};
module.exports = { suites };
Related skills
How it compares
Use markdown-to-docx when stakeholders require Word .docx deliverables from Markdown-authored docs, instead of Pandoc one-liners you must configure per project.
FAQ
What file types does markdown-to-docx produce?
markdown-to-docx outputs polished Microsoft Word .docx files from clean Markdown source. Typical inputs include proposals, specs, user guides, and other client-facing documentation.
How popular is markdown-to-docx on skills.sh?
markdown-to-docx from duc01226/easyplatform has 521 installs and rank 9262 on skills.sh, indicating steady adoption for Markdown-to-Word conversion in agent workflows.