GithubHelp home page GithubHelp logo

davidcouronne / gridsome-plugin-remark-prismjs-all Goto Github PK

View Code? Open in Web Editor NEW
12.0 3.0 1.0 297 KB

Syntax highlighting for Gridsome with PrismJS

Home Page: https://kind-elion-23889d.netlify.com/demo-gridsome-plugin-remark-prismjs-all/

License: MIT License

JavaScript 62.44% SCSS 37.56%
gridsome plugin prismjs gridsome-plugin remark remark-plugin syntax-highlighting syntax markdown css

gridsome-plugin-remark-prismjs-all's Introduction

gridsome-plugin-remark-prismjs-all

NPM version NPM downloads Dependency Status Dev Dependency Status

Twitter: nollan94

contributions welcome

Adds syntax highlighting to code blocks in markdown files using PrismJS

See live demo here !

Inspired by gatsby-remark-prismjs

example

Installation

npm i gridsome-plugin-remark-prismjs-all

Add plugin to gridsome.config.js

// In your gridsome.config.js
transformers: {
    //Add markdown support to all file-system sources
    remark: {
      externalLinksTarget: '_blank',
      externalLinksRel: ['nofollow', 'noopener', 'noreferrer'],
      anchorClassName: 'icon icon-link',
      plugins: [
        'gridsome-plugin-remark-prismjs-all',
      ]
    }
  }

Add theme to your main.js

There is only 3 themes available at this time. Contributions welcomes !

// In your main.js
require("gridsome-plugin-remark-prismjs-all/themes/night-owl.css");
// In your main.js
require("gridsome-plugin-remark-prismjs-all/themes/tomorrow.css");
// In your main.js
require("gridsome-plugin-remark-prismjs-all/themes/solarized.css");

Options

With some options:

// In your gridsome.config.js
transformers: {
    //Add markdown support to all file-system sources
    remark: {
      externalLinksTarget: '_blank',
      externalLinksRel: ['nofollow', 'noopener', 'noreferrer'],
      anchorClassName: 'icon icon-link',
      plugins: [
        ['gridsome-plugin-remark-prismjs-all', {
            highlightClassName: "myCustomClass", //Default `gridsome-highlight`
            codeTitleClassName: "customCodeTitle", //Default 'gridsome-code-title'
            showLineNumbers: true, //  `require("prismjs/plugins/line-numbers/prism-line-numbers.css");`
            languageExtensions: [
              {
                language: "superscript",
                extend: "javascript",
                definition: {
                  superscript_types: /(SuperType)/,
                },
                insertBefore: {
                  function: {
                    superscript_keywords: /(superif|superelse)/,
                  },
                },
              },
            ],

        }]
      ]
    }
  }

All default options

// In your gridsome.config.js
transformers: {
    //Add markdown support to all file-system sources
    remark: {
      externalLinksTarget: '_blank',
      externalLinksRel: ['nofollow', 'noopener', 'noreferrer'],
      anchorClassName: 'icon icon-link',
      plugins: [
        ['gridsome-plugin-remark-prismjs-all', {
            highlightClassName: "gridsome-highlight",
            codeTitleClassName: "gridsome-code-title",
            classPrefix: 'language-',
            aliases: {},
            noInlineHighlight: false,
            showLineNumbers: false,     //  `require("prismjs/plugins/line-numbers/prism-line-numbers.css");`
            languageExtensions: [],
            prompt: {                   //  `require("prismjs/plugins/command-line/prism-command-line.css");`
                user: `root`,
                host: `localhost`,
                global: false,
            }
        }]
      ]
    }
  }

Include CSS

Required: Pick a PrismJS theme or create your own

PrismJS ships with a number of themes

Additional themes: prism-themes

To load a theme, just require its CSS file in your main.js file, e.g.

require("prismjs/themes/prism-solarizedlight.css");

Add line numbering and line highlighting styles

If you want to add line numbering alongside your code, you need to import the corresponding CSS file from PrismJS, right after importing your colorscheme in main.js

//main.js
require("prismjs/themes/prism-solarizedlight.css");
require("prismjs/plugins/line-numbers/prism-line-numbers.css");

You also need to add some additional CSS:

/**
 * Add back the container background-color, border-radius, padding, margin
 * and overflow that we removed from <pre>.
 */
.gridsome-highlight {
  background-color: #fdf6e3; /* for solarized theme */
  border-radius: 0.3em;
  margin: 0.5em 0;
  padding: 1em;
  overflow: auto;
}
.gridsome-highlight-code-line {
  background-color: #feb; /* for solarized theme */
  display: block;
  margin-right: -1em;
  margin-left: -1em;
  padding-right: 1em;
  padding-left: 0.75em;
  border-left: 0.25em solid #f99;
}

/**
 * Remove the default PrismJS theme background-color, border-radius, margin,
 * padding and overflow.
 * 1. Make the element just wide enough to fit its content.
 * 2. Always fill the visible space in .gatsby-highlight.
 * 3. Adjust the position of the line numbers
 */
.gridsome-highlight pre[class*="language-"] {
  background-color: transparent;
  margin: 0;
  padding: 0;
  overflow: initial;
  float: left; /* 1 */
  min-width: 100%; /* 2 */
}

/* Adjust the position of the line numbers */
.gridsome-highlight pre[class*="language-"].line-numbers {
  padding-left: 2.8em;
}

Code titles styling

Example:

```js{codeTitle: "In src/main.js"}
require("prismjs/themes/prism-solarizedlight.css")
require("prismjs/plugins/line-numbers/prism-line-numbers.css")
require("prismjs/plugins/command-line/prism-command-line.css")
```

Is rendered as:

<div class="gridsome-code-title">
  <span>In src/main.js</span>
</div>
<div class="gridsome-highlight" data-language="js">
  <pre class="language-js">
        ... code here
    </pre
  >
</div>

You can add this CSS:

.gridsome-code-title {
  position: relative;
  z-index: 100;
  margin-bottom: -0.8em;
  background-color: #feb; /* solarized highlight lines color */
  color: red; /* why not ;-) */
  font-style: italic;
  font-weight: 100;
  text-align: center;
  font-family: PT Mono, Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace;
  line-height: 1.5;
  border-top-left-radius: 0.3em;
  border-top-right-radius: 0.3em;
}

You can also target the spantag.

Usage in Markdown

Basic usage

```js
const myvar = 'some value";
```

Code Title

```js{codeTitle: "In src/main.js"}
require("prismjs/themes/prism-solarizedlight.css");
require("prismjs/plugins/line-numbers/prism-line-numbers.css");
require("prismjs/plugins/command-line/prism-command-line.css");
```

Line Numbers

To see the line numbers alongside your code, you can use the numberLines option:

```html{numberLines: true}
<template>
  <Layout>
    <h2>Latest blog posts</h2>
    <ul>
      <li v-for="edge in $page.allWordPressPost.edges" :key="edge.node.id">
        {{ edge.node.title }}
      </li>
    </ul>
  </Layout>
</template>
```

You can also start numbering at any index you wish (here, numbering will start at index 21):

```html{numberLines: 21}
<template>
  <Layout>
    <h2>Latest blog posts</h2>
    <ul>
      <li v-for="edge in $page.allWordPressPost.edges" :key="edge.node.id">
        {{ edge.node.title }}
      </li>
    </ul>
  </Layout>
</template>
```

Line Highlighting

You can also add line highlighting. It adds a span around lines of code with a special class .gridsome-highlight-code-line that you can target with styles.

You can specify the highlighted lines outside of the code block. In the following code snippet, lines 3 and 5 through 7 will get the line highlighting. The line range parsing is done with https://www.npmjs.com/package/parse-numeric-range.

```html{3,5-7}
<template>
  <Layout>
    <h2>Latest blog posts</h2>
    <ul>
      <li v-for="edge in $page.allWordPressPost.edges" :key="edge.node.id">
        {{ edge.node.title }}
      </li>
    </ul>
  </Layout>
</template>
```

All Together

```html{3,5-7}{numberLines: 21}{codeTitle: "In src/pages/Index.vue"}
<template>
  <Layout>
    <h2>Latest blog posts</h2>
    <ul>
      <li v-for="edge in $page.allWordPressPost.edges" :key="edge.node.id">
        {{ edge.node.title }}
      </li>
    </ul>
  </Layout>
</template>
```

Prompt

To show fancy prompts next to shell commands (only triggers on bash), either set prompt.global to true in gridsome.config.js, or pass at least one of {outputLines: <range>}, {promptUser: <user>}, or {promptHost: <host>} to a snippet

By default, every line gets a prompt appended to the start, this behaviour can be changed by specifying {outputLines: <range>} to the language.

```bash{outputLines: 2-10,12}

The user and host used in the appended prompt is pulled from the prompt.user and prompt.host values, unless explicitly overridden by the promptUser and promptHost options in the snippet, e.g.:

```bash{promptUser: alice}{promptHost: dev.localhost}

Add new language definition or extend an existing language

You can provide a language extension by giving a single object or an array of language extension objects as the languageExtensions option.

A language extension object looks like this:

languageExtensions: [
  {
    language: "superscript",
    extend: "javascript",
    definition: {
      superscript_types: /(SuperType)/
    },
    insertBefore: {
      function: {
        superscript_keywords: /(superif|superelse)/
      }
    }
  }
];

used options:

  • language (optional) The name of the new language.
  • extend (optional) The language you wish to extend.
  • definition (optional) This is the Prism language definition.
  • insertBefore (optional) Is used to define where in the language definition we want to insert our extension.

More information of the format can be found here: https://prismjs.com/extending.html

Note:

  • One of the parameters language and extend is needed.
  • If only language is given, a new language will be defined from scratch.
  • If only extend is given, an extension will be made to the given language.
  • If both language and extend is given, a new language that extends the extend language will be defined.

In case a language is extended, note that the definitions will not be merged. If the extended language definition and the given definition contains the same token, the original pattern will be overwritten.

One of the parameters definition and insertBefore needs to be defined. insertBefore needs to be combined with definition or extend (otherwise there will not be any language definition tokens to insert before).

In addition to this extension parameters the css also needs to be updated to get a style for the new tokens. Prism will wrap the matched tokens with a span element and give it the classes token and the token name you defined. In the example above we would match superif and superelse. In the html it would result in the following when a match is found:

<span class="token superscript_keywords">superif</span>

History

Discover the release history by heading on over to the releases page.

gridsome-plugin-remark-prismjs-all's People

Contributors

davidcouronne avatar dependabot[bot] avatar scrambldchannel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

scrambldchannel

gridsome-plugin-remark-prismjs-all's Issues

[Bug] Font size not consistent across different languages

Information:

  • gridsome-plugin-remark-prismjs-all: "^0.3.5"

Description
On iOS Chrome and Safari, some of the languages including HTML, some JS, YML showing really big fonts. If the line of code is longer than the screen size, the font size will grow.

How to reproduce bug
You can view it here using iOS Chrome/Safari.

remark attempts to read string interpolation inside code blocks

Description

When using string interpolation inside html code blocks on markdown files, vue-remark attempts to read the variable during render.

Expected result

What should happen?

Since it's just a code block, it's not actual code, so it should render with the string interpolation.
just like javascript code blocks works (or any other language).

Actual result

Markdown:
image

Console:
image

Final result:
image

Environment

OS: Linux 4.19 Ubuntu 18.04.5 LTS (Bionic Beaver)
@gridsome/vue-remark: ^0.2.6 => 0.2.6
gridsome: ^0.7.23 => 0.7.23
gridsome-plugin-remark-prismjs-all: ^0.3.5 => 0.3.5

Version 0.4.5 Build Error

Upgrading to 0.4.5 started giving me the following build error:

Initializing plugins...
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:\GitHub\rehansaeed.github.io\node_modules\gridsome-plugin-remark-prismjs-all\dist\index.js
require() of ES modules is not supported.
require() of C:\GitHub\rehansaeed.github.io\node_modules\gridsome-plugin-remark-prismjs-all\dist\index.js from C:\GitHub\rehansaeed.github.io\node_modules\@gridsome\transformer-remark\lib\utils.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from C:\GitHub\rehansaeed.github.io\node_modules\gridsome-plugin-remark-prismjs-all\package.json.

    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1080:13)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at normalize (C:\GitHub\rehansaeed.github.io\node_modules\@gridsome\transformer-remark\lib\utils.js:109:9)
    at C:\GitHub\rehansaeed.github.io\node_modules\@gridsome\transformer-remark\lib\utils.js:115:10
    at Array.map (<anonymous>)
    at normalizePlugins (C:\GitHub\rehansaeed.github.io\node_modules\@gridsome\transformer-remark\lib\utils.js:113:14)
    at exports.createPlugins (C:\GitHub\rehansaeed.github.io\node_modules\@gridsome\transformer-remark\lib\utils.js:80:10)
    at RemarkTransformer.createProcessor (C:\GitHub\rehansaeed.github.io\node_modules\@gridsome\transformer-remark\index.js:157:21)
    at new RemarkTransformer (C:\GitHub\rehansaeed.github.io\node_modules\@gridsome\transformer-remark\index.js:41:27)
    at PluginStore._createTransformer (C:\GitHub\rehansaeed.github.io\node_modules\gridsome\lib\store\PluginStore.js:111:12)
    at C:\GitHub\rehansaeed.github.io\node_modules\gridsome\lib\store\PluginStore.js:22:19
    at C:\GitHub\rehansaeed.github.io\node_modules\lodash\lodash.js:13427:38
    at C:\GitHub\rehansaeed.github.io\node_modules\lodash\lodash.js:4925:15
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] build: `gridsome build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\musa\AppData\Roaming\npm-cache\_logs\2021-05-17T08_20_55_702Z-debug.log

You can find my code here: https://github.com/RehanSaeed/rehansaeed.github.io.

Unable to style inline blocks separately

Hi David

Thanks for this plugin, it has some nice little features! I love the control it gives me over the formatting.

I am having a slight issue working out how best to style inline blocks differently to multi-line blocks. I would like to be able to override the style for inline code so that they match my light theme better but use a dark theme like night-owl for multi-line blocks. I tried setting noInlineHighlight to true but it doesn't do what I want (I guess this only effects the text highlighting, not the rest of the styling).

Perhaps you could use a different class name for the inline code blocks? This would make it possible to add custom CSS if you want to for inline text only? I played around with it and it seemed to work. I'll raise a PR to show you what I mean, it may not be the best way.

Cheers
Alex

How to configure other prismjs plugins

Sorry, another user question. I'd be happy to send a PR with updated documentation or whatever is needed if you can point me in the right direction. I've added your plugin to the gridsome site I'm building. I want to enable the copy-to-clipboard prismjs plugin (which also requires the toolbar prismjs plugin). Is there a way to do so easily?

Only works on localhost

When I deployed using netlify, I realized that I wasn't getting syntax highlighting. Somehow it works on localhost but doesn't work when the site is live. Tried it using both Chrome and Mozilla and got the same effect. Is this a bug or am I doing something wrong?

Seemingly unable to use with remark-code-import

Sorry this is more a user question than an actual issue ... do you know if it's possible to use this with the remark-code-import plugin? I like to keep my code examples separate from my MD files because then I can lint them, can reuse them in multiple code blocks, etc. It would be a-maz-ing to be able to pull in specific line numbers from the external file and then highlight specific line numbers using this plugin.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.