Package Exports
- remark-flexible-code-titles
Readme
Become a sponsor 🚀
If you find remark-flexible-code-titles useful in your projects, consider supporting my work.
Your sponsorship means a lot 💖
Be the first sponsor and get featured here and on my sponsor wall.
Thank you for supporting open source! 🙌
remark-flexible-code-titles
This package is a unified (remark) plugin to add title or/and container for code blocks with customizable properties in markdown.
unified is a project that transforms content with abstract syntax trees (ASTs) using the new parser micromark. remark adds support for markdown to unified. mdast is the Markdown Abstract Syntax Tree (AST) which is a specification for representing markdown in a syntax tree.
This plugin is a remark plugin that transforms the mdast.
When should I use this?
remark-flexible-code-titles is useful if you want to add title and container or any of two for code blocks in markdown. It is able to:
- add
titlenode above thecodenode, providing custom tag name, custom class name and also additional properties. - add
containernode for thecodenode, providing custom tag name, custom class name and also additional properties. - correct the syntax of code highligting directives on behalf of related rehype plugins (like rehype-prism-plus)
- handle the titles even if there is no language provided,
- handle the titles composed by more than one word (handle spaces in the title),
- provide a fallback language as an option if the language is missing.
Installation
This package is suitable for ESM only. In Node.js (16.0+), install with npm:
npm install remark-flexible-code-titlesor
yarn add remark-flexible-code-titlesUsage
Say we have the following file, example.md, which consists a code block. The code block's language is "javascript" and its title is "file.js" specified after a colon :
```javascript:file.js
<!-- code block -->
```And our module, example.js, looks as follows:
import { read } from "to-vfile";
import remark from "remark";
import gfm from "remark-gfm";
import remarkRehype from "remark-rehype";
import rehypeStringify from "rehype-stringify";
import remarkCodeTitles from "remark-flexible-code-titles";
main();
async function main() {
const file = await remark()
.use(gfm)
.use(remarkCodeTitles)
.use(remarkRehype)
.use(rehypeStringify)
.process(await read("example.md"));
console.log(String(file));
}Now, running node example.js yields:
<div class="remark-code-container">
<div class="remark-code-title">file.js</div>
<pre>
<code class="language-javascript">
<!-- code block -->
</code>
</pre>
</div>Without remark-flexible-code-titles, you’d get:
<pre>
<code class="language-javascript:file.js">
<!-- code block -->
</code>
</pre>You can use remark-flexible-code-titles even without a language, setting the title just after a colon :
```:title
This is a line of pseudo code.
```Options
All options are optional and some of them have default values.
type RestrictedRecord = Record<string, unknown> & { className?: never };
type PropertyFunction = (language?: string, title?: string) => RestrictedRecord;
use(remarkCodeTitles, {
title?: boolean; // default is true
titleTagName?: string; // default is "div"
titleClassName?: string; // default is "remark-code-title"
titleProperties?: PropertyFunction;
container?: boolean; // default is true
containerTagName?: string; // default is "div"
containerClassName?: string; // default is "remark-code-container"
containerProperties?: PropertyFunction;
handleMissingLanguageAs?: string;
tokenForSpaceInTitle?: string;
} as CodeTitleOptions);title
It is a boolean option for whether or not to add a title node.
By default, it is true, meaningly adds a title node if a title is provided in the language part of the code block.
use(remarkCodeTitles, {
title: false,
});If the option is false, the plugin will not add any title node.
```javascript:file.js
console.log("Hi")
```<div class="remark-code-container">
<!-- there is no title element ! -->
<pre>
<code class="language-javascript">console.log("Hi")</code>
<pre>
</div>titleTagName
It is a string option for providing custom HTML tag name for title nodes.
By default, it is div.
use(remarkCodeTitles, {
titleTagName: "span",
});Now, the title element tag names will be span.
```javascript:file.js
console.log("Hi")
```<div class="remark-code-container">
<span class="remark-code-title">file.js</span>
<pre>
<code class="language-javascript">console.log("Hi")</code>
<pre>
</div>titleClassName
It is a string option for providing custom class name for title nodes.
By default, it is remark-code-title, and all title elements' class names will contain remark-code-title.
use(remarkCodeTitles, {
titleClassName: "custom-code-title",
});Now, the title element class names will be custom-code-title.
```javascript:file.js
console.log("Hi")
```<div class="remark-code-container">
<div class="custom-code-title">file.js</div>
<pre>
<code class="language-javascript">console.log("Hi")</code>
<pre>
</div>titleProperties
It is a callback (language?: string, title?: string) => Record<string, unknown> & { className?: never } option to set additional properties for the title node.
The callback function that takes the language and the title as optional arguments and returns object which is going to be used for adding additional properties into the title node.
The className key is forbidden and effectless in the returned object.
use(remarkCodeTitles, {
titleProperties(language, title) {
return {
title,
["data-language"]: language,
};
},
});Now, the title elements will contain title and data-color properties.
```javascript:file.js
console.log("Hi")
```<div class="remark-code-container">
<div class="remark-code-title" title="file.js" data-language="javascript">file.js</div>
<pre>
<code class="language-javascript">console.log("Hi")</code>
<pre>
</div>container
It is a boolean option for whether or not to add a container node.
By default, it is true, meaningly adds a container node.
use(remarkCodeTitles, {
container: false,
});If the option is false, the plugin doesn't add any container node.
```javascript:file.js
console.log("Hi")
```<!-- there is no container element ! -->
<div class="remark-code-title">file.js</div>
<pre>
<code class="language-javascript">console.log("Hi")</code>
<pre>
containerTagName
It is a string option for providing custom HTML tag name for container nodes.
By default, it is div.
use(remarkCodeTitles, {
containerTagName: "section",
});Now, the container element tag names will be section.
```javascript:file.js
console.log("Hi")
```<section class="remark-code-container">
<div class="remark-code-title">file.js</div>
<pre>
<code class="language-javascript">console.log("Hi")</code>
<pre>
</div>containerClassName
It is a string option for providing custom class name for container nodes.
By default, it is remark-code-container, and all container elements' class names will contain remark-code-container.
use(remarkCodeTitles, {
containerClassName: "custom-code-container",
});Now, the container element class names will be custom-code-container.
```javascript:file.js
console.log("Hi")
```<div class="custom-code-container">
<div class="remark-code-title">file.js</div>
<pre>
<code class="language-javascript">console.log("Hi")</code>
<pre>
</div>containerProperties
It is a callback (language?: string, title?: string) => Record<string, unknown> & { className?: never } option to set additional properties for the container node.
The callback function that takes the language and the title as optional arguments and returns object which is going to be used for adding additional properties into the container node.
The className key is forbidden and effectless in the returned object.
use(remarkCodeTitles, {
titleProperties(language, title) {
return {
title,
["data-language"]: language,
};
},
});Now, the container elements will contain title and data-color properties.
```javascript:file.js
console.log("Hi")
```<div class="remark-code-container" title="file.js" data-language="javascript">
<div class="remark-code-title">file.js</div>
<pre>
<code class="language-javascript">console.log("Hi")</code>
<pre>
</div>handleMissingLanguageAs
It is a string option for providing a fallback language if the language is missing.
use(remarkCodeTitles, {
handleMissingLanguageAs: "unknown",
});Now, the class name of <code> elements will contain language-unknown if the language is missing. If this option was not set, the class property would not be presented in the <code>element.
```
Hello from code block
```<div class="remark-code-container">
<pre>
<code class="language-unknown">Hello from code block</code>
<pre>
</div>tokenForSpaceInTitle
It is a string option for composing the title with more than one word.
Normally, remark-flexible-code-titles can match a code title which is the word that comes after a colon and ends in the first space it encounters. This option is provided to replace a space with a token in order to specify a code title consisting of more than one word.
use(remarkCodeTitles, {
tokenForSpaceInTitle: "@",
});Now, the titles that have more than one word can be set using the token @.
```bash:Useful@Bash@Commands
mkdir project-directory
```<div class="remark-code-container">
<div class="remark-code-title">Useful Bash Commands</div>
<pre>
<code class="language-bash">mkdir project-directory</code>
<pre>
</div>Examples:
Example for only container
```javascript:file.js
let me = "ipikuka";
```use(remarkCodeTitles, {
title: false,
containerTagName: "section",
containerClassName: "custom-code-wrapper",
containerProperties(language, title) {
return {
["data-language"]: language,
title,
};
},
});is going to produce the container section element like below:
<section class="custom-code-wrapper" data-language="javascript" title="file.js">
<pre>
<code class="language-javascript">let me = "ipikuka";</code>
</pre>
</section>Example for only title
```javascript:file.js
let me = "ipikuka";
```use(remarkCodeTitles, {
container: false,
titleTagName: "span",
titleClassName: "custom-code-title",
titleProperties: (language, title) => {
["data-language"]: language,
title,
},
});is going to produce the title span element just before the code block, like below:
<span class="custom-code-title" data-language="javascript" title="file.js">file.js</span>
<pre>
<code class="language-javascript">let me = "ipikuka";</code>
</pre>Example for line highlighting and numbering
[!NOTE] You need a rehype plugin like rehype-prism-plus or rehype-highlight-code-lines for line highlighting and numbering features.
```javascript:file.js {1,3-6} showLineNumbers
let me = "ipikuka";
```remark-flexible-code-titles takes the line highlighting and numbering syntax into consideration, and passes that information to other remark and rehype plugins.
But, if you want to highlight and number the lines without specifying language, you will get the language of the code block as for example language-{2} like strings. Let me give an example:
```{2} showLineNumbers
This is a line which is going to be numbered with rehype-prism-plus.
This is a line which is going to be highlighted and numbered with rehype-prism-plus.
```The above markdown, with no language provided, will lead to produce a mdast "code" node as follows:
{
"type": "code",
"lang": "{2}",
"meta": "showLineNumbers"
}As a result, the html code element will have wrong language language-{2}:
(The class code-highlight in the code element is added by the rehype plugin rehype-prism-plus)
<code class="language-{2} code-highlight">...</code>remark-flexible-code-titles not only adds title and container elements but also corrects the language producing the below mdast which will lead the <code> element has accurate language or not have language as it sould be.
{
"type": "code",
"lang": null,
"meta": "{2} showLineNumbers"
}<code class="code-highlight">
<!-- highlighted and numbered lines -->
</code>If there is no space between the parts (title, line range string and "showLineNumbers"), or there is extra spaces inside the line range string, line highlighting or numbering features by the rehype plugin will not work. remark-flexible-code-titles can handles and corrects this kind of mis-typed situations.
```typescript:title{ 1, 3 - 6 }showLineNumbers
content
```There is mis-typed syntax in above markdown example; and without remark-flexible-code-titles will cause to produce the following mdast; and the rehype plugin not to work properly:
{
"type": "code",
"lang": "typescript:title{",
"meta": " 1, 3 - 6 }showLineNumbers"
}remark-flexible-code-titles will correct the syntax and ensure to produce the following mdast and html:
{
"type": "code",
"lang": "typescript",
"meta": "{1,3-6} showLineNumbers"
}<div class="remark-code-container">
<div class="remark-code-title">title</div>
<pre>
<code class="language-typescript code-highlight">
<!-- highlighted and numbered lines -->
</code>
</pre>
</div>Example for providing a title without any language
You can provide a title without any language just using a colon : at the beginning.
```:title
content
```<div class="remark-code-container">
<div class="remark-code-title">title</div>
<pre>
<code>content</code>
</pre>
</div>Another flexible usage
You can use **remark-flexible-code-titles** just for only correcting language, line highlighting and numbering syntax on behalf of related rehype plugins.
use(remarkCodeTitles, {
container: false,
title: false,
});Now, remark-flexible-code-titles will not add any node, but will correct language, line highlighting and numbering syntax.
Syntax tree
This plugin only modifies the mdast (markdown abstract syntax tree) as explained.
Types
This package is fully typed with TypeScript. The plugin options' type is exported as CodeTitleOptions.
Compatibility
This plugin works with unified version 6+ and remark version 7+. It is compatible with mdx version 2+.
Security
Use of remark-flexible-code-titles does not involve rehype (hast) or user content so there are no openings for cross-site scripting (XSS) attacks.
My Plugins
I like to contribute the Unified / Remark / MDX ecosystem, so I recommend you to have a look my plugins.
My Remark Plugins
remark-flexible-code-titles– Remark plugin to add titles or/and containers for the code blocks with customizable propertiesremark-flexible-containers– Remark plugin to add custom containers with customizable properties in markdownremark-ins– Remark plugin to addinselement in markdownremark-flexible-paragraphs– Remark plugin to add custom paragraphs with customizable properties in markdownremark-flexible-markers– Remark plugin to add custommarkelement with customizable properties in markdownremark-flexible-toc– Remark plugin to expose the table of contents viavfile.dataor via an option referenceremark-mdx-remove-esm– Remark plugin to remove import and/or export statements (mdxjsEsm)
My Rehype Plugins
rehype-pre-language– Rehype plugin to add language information as a property topreelementrehype-highlight-code-lines– Rehype plugin to add line numbers to code blocks and allow highlighting of desired code linesrehype-code-meta– Rehype plugin to copycode.data.metatocode.properties.metastringrehype-image-toolkit– Rehype plugin to enhance Markdown image syntax![]()and Markdown/MDX media elements (<img>,<audio>,<video>) by auto-linking bracketed or parenthesized image URLs, wrapping them in<figure>with optional captions, unwrapping images/videos/audio from paragraph, parsing directives in title for styling and adding attributes, and dynamically converting images into<video>or<audio>elements based on file extension.
My Recma Plugins
recma-mdx-escape-missing-components– Recma plugin to set the default value() => nullfor the Components in MDX in case of missing or not provided so as not to throw an errorrecma-mdx-change-props– Recma plugin to change thepropsparameter into the_propsin thefunction _createMdxContent(props) {/* */}in the compiled source in order to be able to use{props.foo}like expressions. It is useful for thenext-mdx-remoteornext-mdx-remote-clientusers innextjsapplications.recma-mdx-change-imports– Recma plugin to convert import declarations for assets and media with relative links into variable declarations with string URLs, enabling direct asset URL resolution in compiled MDX.recma-mdx-import-media– Recma plugin to turn media relative paths into import declarations for both markdown and html syntax in MDX.recma-mdx-import-react– Recma plugin to ensure gettingReactinstance from the arguments and to make the runtime props{React, jsx, jsxs, jsxDev, Fragment}is available in the dynamically imported components in the compiled source of MDX.recma-mdx-html-override– Recma plugin to allow selected raw HTML elements to be overridden via MDX components.recma-mdx-interpolate– Recma plugin to enable interpolation of identifiers wrapped in curly braces within thealt,src,href, andtitleattributes of markdown link and image syntax in MDX.
License
MIT License © ipikuka