Skip to content

About

Tool to inject files into markdown files.

Resources

Contributing

Security policy

Stars

9 stars

Watchers

0 watching

Forks

Latest commit

 

History

464 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

inject-markdown

Insert the content of other files, such as code samples, command output or parts of other docs, into your Markdown files, and keep it up to date when those files change.

Mark where the content goes with an HTML comment:

<!--- @@inject: src/example.ts --->

Why

Docs such as README.md often repeat code samples, CLI help output or parts of other docs. Copied by hand, they drift out of date. inject-markdown copies them for you, so the source file stays the single source of truth.

Quick start

  1. Install it as a dev dependency (or skip this and use npx):

    npm install --save-dev inject-markdown
  2. Add a directive where the content should go:

    # My Project
    
    ## Example
    
    <!--- @@inject: code.ts --->
  3. Run it on the Markdown file:

    npx inject-markdown README.md

The file now contains the content of code.ts, followed by an end marker:

# My Project

## Example

<!--- @@inject: code.ts --->

```ts
export function sayHello(name: string): string {
  return `Hello ${name}`;
}
```

<!--- @@inject-end: code.ts --->

Run it again after code.ts changes, and the section between the two markers is refreshed.

To keep it in one place, add a script to package.json:

{
  "scripts": {
    "build:docs": "inject-markdown README.md"
  }
}

How it works

  • Directives are HTML comments, so they don't show up when the Markdown is rendered.
  • The tool writes content after each directive and closes it with an @@inject-end marker. On every run, everything between the directive and its end marker is replaced. Edit the source file, not the injected text.
  • How content is injected depends on the file type: .md files are injected as Markdown, .csv/.tsv files as a table, and everything else as a fenced code block. The directives and options below override this.
  • Paths are relative to the Markdown file that contains the directive. A reference can also be an http(s) URL; GitHub blob URLs are fetched as raw content.
  • Local references must stay inside the injection root — the directory set by --cwd, by default the current directory. See Injection root for why, and for --allow-outside-root.
  • Only .md files are processed. Pass files or glob patterns: inject-markdown README.md "docs/**/*.md".
  • Unchanged files are not rewritten.

Commonly used flags:

Flag Effect
--dry-run Process the files and report, but don't write anything.
--clean Remove injected content. The directives stay, so the next run restores it.
--output-dir Write the results to another directory instead of in place.
--verbose Show more detail about each file.

See CLI options for the full list.

Checking docs in CI

--dry-run exits successfully even when content is out of date. To fail a CI job when docs are stale, regenerate them and check for changes:

npx inject-markdown README.md
git diff --exit-code

Directives

Directive Effect
@@inject: <file> Inject the file: Markdown as Markdown, CSV/TSV as a table, anything else as code.
@@inject-code: <file> Always inject as a fenced code block, including Markdown and CSV/TSV files.
@@inject-table: <file> Always inject as a table, whatever the file extension. A .json file must hold an array of objects; @@inject: <file>.json still injects it as code.
@@inject-start: <file> Same as @@inject.
@@inject-end: <file> Marks the end of injected content. The tool writes it; you don't normally need to.

Injection options

Add options after a # in the file reference, separated by &:

<!--- @@inject: guide.md#heading=Install&quote --->
Option Applies to Effect
heading=<text> Markdown Inject only the section under this heading. The shorthand #<text> also works.
L<n>-L<m> All Inject only lines n to m, e.g. #L5-L7.
lang=<lang> Code Set the code block's language. On a CSV/TSV file, this injects it as code instead of a table.
code Markdown Inject Markdown as a code block. code=<lang> is the same as lang=<lang>.
quote All Inject as a block quote.
markdown Tables Render inline Markdown in cells instead of escaping it.
html-table Tables Emit an HTML table whose cells can hold full Markdown, including lists and paragraphs.
header-rows=<n> Tables How many leading rows form the header. Default 1; 0 means no header.
start-row=<n> Tables First data row to include, counting from 1 after the header rows.
end-row=<n> Tables Last data row to include.
num-rows=<n> Tables Maximum number of data rows. Default 10000.
rebase-links=false Markdown, Tables Keep relative links as written. By default they're rewritten to resolve from the host file. See Relative links.
values=<name:val,…> All Values for {@ name @} placeholders. See Template variables.
value=<name:val> All One placeholder value; commas and colons after the first : are part of the value.
values-file=<path> All JSON files of placeholder values, comma-separated, each under its file name: values.json gives {@ values.version @}. See Values files.
values-file=<:path> All Put a file's values at the top level: :values.json gives {@ version @}.
values-file=<prefix:path> All Put a file's values under your own prefix: pkg:values.json gives {@ pkg.version @}. See Prefixes.
value-alias=<new:target,…> All Resolve one placeholder name as another.
vars All Opt in with no values of its own, to use values from the command line and allowed environment variables.

Recipes

Each example shows the directive and what the tool writes after it.

Inject a Markdown file

<!--- @@inject: example.md --->

# Example

This is an example bit of markdown.

- first
- second
- third

<!--- @@inject-end: example.md --->

Keep relative links working

Relative links in an injected file are rewritten to resolve from the file they're injected into. Here parts/links.md, one directory down, links to ../example.md. Injected into a file next to example.md, that link becomes example.md:

<!--- @@inject: parts/links.md --->

Read the [relative links guide](../docs/guide/relative-links.md)
or the [example](example.md).

<!--- @@inject-end: parts/links.md --->

Use #rebase-links=false or --no-rebase-links to keep links as written. See Relative links for what is and isn't rewritten.

Inject one section of a Markdown file

The section runs from the heading up to the next heading of the same or higher level.

<!--- @@inject: sections.md#heading=Install --->

## Install

```sh
npm install --save-dev inject-markdown
```

<!--- @@inject-end: sections.md#heading=Install --->

Inject a code file

Non-Markdown files become a code block. The language is taken from the file extension; use lang= to override it.

<!--- @@inject-code: sample.json#lang=jsonc --->

```jsonc
{
  "name": "Sample"
}
```

<!--- @@inject-end: sample.json#lang=jsonc --->

Inject selected lines

<!--- @@inject: code.js#L5-L7 --->

```js
export function sayGoodbye(name) {
  return `Goodbye ${name}`;
}
```

<!--- @@inject-end: code.js#L5-L7 --->

Show Markdown as source

<!--- @@inject-code: example.md --->

```markdown
# Example

This is an example bit of markdown.

- first
- second
- third
```

<!--- @@inject-end: example.md --->

Inject as a block quote

<!--- @@inject: example.md#L5-L7&quote --->

> - first
> - second
> - third

<!--- @@inject-end: example.md#L5-L7&quote --->

Inject lines from GitHub

On GitHub, select the lines, choose Copy permalink, and use the URL as the file reference.

<!--- @@inject: https://github.com/streetsidesoftware/inject-markdown/blob/bbb2c709c/src/FileSystemAdapter/fsa.ts#L26-L29 --->

```ts
async function fetchUrl(url: URL): Promise<string> {
  const response = await fetch(mapUrl(url));
  return await response.text();
}
```

<!--- @@inject-end: https://github.com/streetsidesoftware/inject-markdown/blob/bbb2c709c/src/FileSystemAdapter/fsa.ts#L26-L29 --->

Inject a CSV or TSV file as a table

All columns are included. Use @@inject-code or #lang=csv to inject the file as code instead. See Tables for the detailed rules.

<!--- @@inject: sample.csv --->

| name         | role          |
| ------------ | ------------- |
| Ada Lovelace | Mathematician |
| Grace Hopper | Programmer    |

<!--- @@inject-end: sample.csv --->

Header rows and selecting rows

header-rows=<n> makes the first n rows the header:

  • With more than one, each column's header rows are joined with <br />, skipping blank cells. With #html-table they stay separate header rows.
  • header-rows=0 means every row is data. A pipe table then shows column numbers (1, 2, …) as its header, and an #html-table has no header.
  • #header-rows with no value means header-rows=1.
<!--- @@inject: sample-header-rows.csv#header-rows=2 --->

| Date       | Name<br />First | Name<br />Last |
| ---------- | --------------- | -------------- |
| 1815-12-10 | Ada             | Lovelace       |
| 1906-12-09 | Grace           | Hopper         |

<!--- @@inject-end: sample-header-rows.csv#header-rows=2 --->

Renders as:

Date Name
First
Name
Last
1815-12-10 Ada Lovelace
1906-12-09 Grace Hopper

start-row, end-row and num-rows choose which data rows are injected:

  • Rows are numbered from 1, starting after the header rows.
  • num-rows defaults to 10000, so a larger file is cut off unless you raise it.
  • A window past the end of the data gives a table with only its header.
  • A value that isn't a whole number, or start-row=0, is an error.
<!--- @@inject: sample-rows.csv#start-row=2&num-rows=2 --->

| n   | planet |
| --- | ------ |
| 2   | Venus  |
| 3   | Earth  |

<!--- @@inject-end: sample-rows.csv#start-row=2&num-rows=2 --->

JSON as a table

@@inject-table: also accepts a .json file holding an array of objects. Each object is a row, and its keys are the columns. @@inject: on a .json file still injects a code block.

<!--- @@inject-table: sample-table.json --->

| name         | born | fields                       | rank         |
| ------------ | ---- | ---------------------------- | ------------ |
| Ada Lovelace | 1815 | \["mathematics","computing"] |              |
| Grace Hopper | 1906 |                              | Rear Admiral |

<!--- @@inject-end: sample-table.json --->

Renders as:

name born fields rank
Ada Lovelace 1815 ["mathematics","computing"]
Grace Hopper 1906 Rear Admiral
  • The columns are every key found in the rows being shown, in the order they first appear. If no rows are shown, they're every key in the file. A missing key is an empty cell.
  • Numbers and booleans are shown as text, and null is an empty cell.
  • A nested object or array is shown as compact JSON. With #markdown it's a code span, and with #html-table it's a formatted json code block.
  • start-row, end-row and num-rows work as for CSV. A line range (#L1-L10) is an error on a JSON source.
  • The keys are the one header row: header-rows=0 hides it, and a larger value is an error.
  • The file must be a non-empty array of objects; anything else is an error.

Markdown in table cells

By default, Markdown in a cell is escaped and shown literally. Add #markdown to render inline Markdown (emphasis, code, links, images, strikethrough, inline HTML) in every cell, including the header.

  • Block syntax such as # Title or - item stays literal, because a table cell can't hold blocks.
  • A | in the CSV is escaped for you; a newline inside a quoted field becomes <br />.
  • Raw HTML is passed through, so only use #markdown on CSV files you trust as much as the Markdown around them.
<!--- @@inject: sample-markdown.csv#markdown --->

| option       | description                                      |
| ------------ | ------------------------------------------------ |
| `#markdown`  | **Bold**, [links](https://github.com) and `a\|b` |
| - not a list | Stays literal<br />and a newline is a line break |

<!--- @@inject-end: sample-markdown.csv#markdown --->

Renders as:

option description
#markdown Bold, links and a|b
- not a list Stays literal
and a newline is a line break

Block Markdown in table cells

When cells need lists or paragraphs, use #html-table. It writes an HTML <table> instead of a pipe table, and each cell can hold full Markdown. It implies #markdown.

This relies on a CommonMark rule: a blank line after an HTML tag ends the HTML block, so the cell's content is parsed as Markdown. GitHub and other CommonMark renderers support this; others may show the Markdown as plain text.

<!--- @@inject: sample-html-table.csv#html-table --->

<table>
<thead>
<tr>
<th>option</th>
<th>description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`#html-table`

</td>
<td>

Cells can hold **block** Markdown:

- lists
- several paragraphs

</td>
</tr>
<tr>
<td>plain</td>
<td>Plain cells stay on one line</td>
</tr>
</tbody>
</table>

<!--- @@inject-end: sample-html-table.csv#html-table --->

Renders as:

option description

#html-table

Cells can hold block Markdown:

  • lists
  • several paragraphs
plain Plain cells stay on one line

Template variables

Injected content can contain {@ name @} placeholders. The directive supplies the values, so the same snippet can be reused with different values. Given a values-example.md containing npm install my-package@{@ version @}:

<!--- @@inject-code: values-example.md#values=version:1.2.3 --->

```markdown
npm install my-package@1.2.3
```

<!--- @@inject-end: values-example.md#values=version:1.2.3 --->

Placeholders are only replaced when the directive has values=, value=, values-file=, value-alias= or vars. Values can also come from JSON files and the command line (--value, --values-file, --value-alias, --allow-env, --strict-vars). See Template variables for the full rules.

API

inject-markdown can also be called from code. Types are included.

Inject into a file

import { injectFile } from 'inject-markdown';

const result = await injectFile('README.md', { cwd: 'samples' });

for (const error of result.errors) {
  console.error(`README.md:${error.line}: ${error.message}`);
}
  • injectFile writes the file back only if it changed and had no errors.
  • It never prints. It returns:
    • updated: the content changed.
    • written: the file was written.
    • errors and warnings: each has a message, and the directive's line and column.
  • To process several files, call it once for each.

Inject into a document

import { injectMarkdown } from 'inject-markdown';

const result = await injectMarkdown({
  file: 'samples/README.md',
  content: markdown
});
  • A document is the Markdown content and the file it belongs to. Relative @@inject paths resolve from file.
  • Nothing is read from file, and nothing is written.
  • It returns the injected document, plus updated, errors and warnings.

Remove the directives

removeDirectives removes the @@inject directives and end markers from Markdown. Everything else stays exactly as written, including the injected content. This is useful for a copy that is published rather than maintained.

import { injectMarkdown, removeDirectives } from 'inject-markdown';

const result = await injectMarkdown({
  file: 'docs/guide.md',
  content: markdown
});
const published = removeDirectives(result.document.content);

Options

injectFile and injectMarkdown take the same options:

  • cwd: the injection root. Relative paths resolve against it, and local references must stay inside it. Defaults to the current directory.
  • allowOutsideRoot: directories outside cwd that local references may resolve into.
  • rebaseLinks: rebase relative links in injected Markdown. Defaults to true.
  • injectOnly: only rewrite the injected sections. Defaults to true.
  • clean: remove the injected content, keeping the directives.
  • valueDeclarations: placeholder values, as a list. A later entry overrides an earlier one, and a directive's own values override all of them.
  • allowEnv: environment variables a directive may use.
  • strictVars: treat an unresolved placeholder as an error.

For example, valueDeclarations takes the place of --value, --values-file and --value-alias:

await injectFile('README.md', {
  valueDeclarations: [
    {
      // The file's values, under `package`: {@ package.version @}
      kind: 'values-file',
      path: 'package.json',
      prefix: 'package'
    },
    {
      kind: 'value',
      name: 'channel',
      value: 'beta'
    },
    {
      kind: 'alias',
      name: 'version',
      target: 'package.version'
    }
  ]
});

A values file's prefix is a dotted name for its values, or '' to put its keys at the top level.

Errors

  • Errors in the Markdown are returned in errors, never thrown.
  • Invalid options throw an OptionError. This includes a values file that can't be read.
  • A file that can't be read throws the read error.

Reference

  • Template variables — placeholders, values files, aliases, CLI values and how they combine.
  • Injection root — which local files a directive may read, and --allow-outside-root.

CLI options

Help fits the width of your terminal. To use a different width, set the COLUMNS environment variable:

COLUMNS=60 inject-markdown --help
inject-markdown --help
Usage: inject-markdown [options] <files...>

Inject file content into markdown files.

Arguments:
  files                          Files to scan for injected content.

Options:
  --no-must-find-files           No error if files are not found.
  --output-dir <dir>             Output Directory
  --cwd <dir>                    Current Directory
  --allow-outside-root <dir>     Allow local @@inject references to
                                 resolve into <dir>, outside the
                                 injection root (cwd). Repeatable.
  --value <name=val>             Set a run-wide {@ name @} placeholder
                                 value. Repeatable; the last --value,
                                 --values-file or --value-alias defining
                                 a name overrides earlier ones. A
                                 directive's own values override all of
                                 them.
  --values-file <[prefix:]path>  Add a run-wide JSON file of {@ name @}
                                 placeholder values, resolved relative
                                 to --cwd. Repeatable; ordered with
                                 --value.
  --allow-env <name>             Allow a directive to reference the OS
                                 environment variable <name> via {@
                                 env.name @}. Repeatable.
  --value-alias <new=target>     Resolve the {@ new @} placeholder as if
                                 it were {@ target @}. Repeatable;
                                 ordered with --value and --values-file.
  --strict-vars                  Treat an unresolved {@ name @}
                                 placeholder as a directive error.
  --no-rebase-links              Keep relative links in injected
                                 Markdown as written instead of rebasing
                                 them.
  --no-directives                Remove the @@inject directives from
                                 files written to --output-dir.
  --clean                        Remove the injected content.
  --no-inject-only               Update the whole file.
  --verbose                      Verbose output.
  --silent                       Only output errors.
  --no-stop-on-errors            Do not stop if an error occurs.
  --write-on-error               write the file even if an injection
                                 error occurs.
  --color                        Force color.
  --no-color                     Do not use color.
  --no-summary                   Do not show the summary
  --dry-run                      Process the files, but do not write.
  -V, --version                  output the version number
  -h, --help                     display help for command


Brought to you by Street Side Software Logo Street Side Software

About

Tool to inject files into markdown files.

Resources

Contributing

Security policy

Stars

9 stars

Watchers

0 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages