GithubHelp home page GithubHelp logo

11ty / eleventy-plugin-syntaxhighlight Goto Github PK

View Code? Open in Web Editor NEW
124.0 8.0 30.0 107 KB

A pack of Eleventy plugins for syntax highlighting in Markdown, Liquid, and Nunjucks templates.

Home Page: https://www.11ty.dev/docs/plugins/syntaxhighlight/

License: MIT License

JavaScript 99.74% Nunjucks 0.26%
eleventy eleventy-plugin syntax-highlighting

eleventy-plugin-syntaxhighlight's Introduction

eleventy Logo

eleventy-plugin-syntaxhighlight 🕚⚡️🎈🐀

A pack of Eleventy plugins for syntax highlighting. No browser/client JavaScript here, these highlight transformations are all done at build-time.

eleventy-plugin-syntaxhighlight's People

Contributors

byoigres avatar chriskirknielsen avatar mathiasbynens avatar mattcheely avatar pborenstein avatar rmcginty avatar yehudab avatar zachleat avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

eleventy-plugin-syntaxhighlight's Issues

Allow to customize attributes applied to the <pre>/<code> tags

The syntaxhighlight plugin provides its own wrappers for code blocks (src/markdownSyntaxHighlightOptions.js:36) which overrides the default wrapper provided by markdown-it/markdown-it#189. Unfortunatly that leaves no room to customize the generated markup as we cannot use a custom renderer rule for code fence blocks. Removing the wrapper from the plugin however, would result in a breaking change as some sites may use the class on the <pre> tag as a styling hook.

Would you be open for a PR that implements an additional option to add custom attributes to the <pre> tag? I would love to display the highlighted language next to my code blocks. Currently my only option would be to do this entirely in CSS:

pre[class$='css'],
pre[class$='scss'],
pre[class$='js'],
pre[class$='php'] {
  position: relative;

  &::after {
    position: absolute;
    top: 0;
    right: 0;
    // ...
  }
}

pre[class$='css']::after  { content: 'CSS' }
pre[class$='scss']::after { content: 'SCSS' }
pre[class$='js']::after   { content: 'JavaScript' }
pre[class$='php']::after  { content: 'PHP' }
//

This would be much easier if I could add a data attribute to the <pre> tag:

pre[class|="language"][data-language] {
  position: relative;

  &::after {
    content: attr(data-language);
    //
  }
}

Render templating code inside highlight tag

Hi 👋

Thanks for the great plugin!

I am currently looking at moving a Jekyll site to Eleventy, where we have a pattern page with a code block showing that pattern's HTML:

_code.html (file)

{% highlight html %}
  {% include folder-example/file-example %}
{% endhighlight %}

With Jekyll, this will actually include the file and output the HTML inside the file:

/pattern (web page)

<div class="pattern-example">
  <p>Hello, I am a pattern</p>
</div>

This is great, as any changes made to the code get reflected in the pattern code block for developers to see.

With the plugin, it actually renders out what is exactly contained inside the {% highlight %} tag:

_code.liquid (file)

{% highlight html %}
  {% include folder-example/file-example %}
{% endhighlight %}

/pattern (web page)

{% include folder-example/file-example %}

Obviously the plugin is doing its job, but is there a way the plugin could render out the templating language that is being used, instead of literally displaying what is written (easier to say than to actually do it)?

Or would you recommend creating a custom filter to render whatever has been written?

Many thanks 👍

Default export not a function?

Hi!

I'm not sure exactly what's going on but when I use:

const syntaxHighlight = require("@11ty/eleventy-plugin-syntaxhighlight");

module.exports = function(eleventyConfig) {
    // ... config stuff
    eleventyConfig.addPlugin(syntaxHighlight);

I get:

$ eleventy --serve --watch
/usr/local/lib/node_modules/@11ty/eleventy/src/UserConfig.js:255
      throw new Error(
      ^

Error: EleventyConfig.addPlugin expects the first argument to be a function.
    at UserConfig.addPlugin (/usr/local/lib/node_modules/@11ty/eleventy/src/UserConfig.js:255:13)
    at module.exports (/Users/andrescuervo/code/cwervo.com/.eleventy.js:10:20)
    at TemplateConfig.mergeConfig (/usr/local/lib/node_modules/@11ty/eleventy/src/TemplateConfig.js:92:21)
    at new TemplateConfig (/usr/local/lib/node_modules/@11ty/eleventy/src/TemplateConfig.js:20:24)
    at Object.<anonymous> (/usr/local/lib/node_modules/@11ty/eleventy/src/Config.js:5:14)
    at Module._compile (internal/modules/cjs/loader.js:936:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:947:10)
    at Module.load (internal/modules/cjs/loader.js:790:32)
    at Function.Module._load (internal/modules/cjs/loader.js:703:12)
    at Module.require (internal/modules/cjs/loader.js:830:19)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

However, if I use:

eleventyConfig.addPlugin(syntaxHighlight.configFunction);

Everything works as expected. ¯_(ツ)_/¯

Make it possible to pass custom Prism plugins

Can haz a way to pass custom Prism plugins to this 11ty plugin? Maybe this can be solved generically by allowing something like this in 11ty's plugin system:

-eleventyConfig.addPlugin(syntaxHighlight);
+eleventyConfig.addPlugin(syntaxHighlight, initializer);

For this particular plugin, initializer would be a function that gets called with the Prism object as an argument. Users could then do something like:

const initializer = (Prism) => {
  Prism.languages.myCustomLanguage = /* */;
};
eleventyConfig.addPlugin(syntaxHighlight, initializer);

What do you think?

Confusing error on unrecognized language

If I use an unrecognized syntax, for instance:

File index.md:

```asdfl
```

Then the error is confusing.

Language does not exist asdfl
Problem writing Eleventy templates: (more in DEBUG output)
> Having trouble rendering njk (and markdown) template ./index.md

`TemplateContentRenderError` was thrown
> Cannot read property 'rest' of undefined

The first line mentions that the language doesn't exist, but I didn't realize for quite a while that that warning was the cause of the later fatal error.

Expected Behavior:
Unrecognized languages should give a warning and then simply fail to highlight that syntax.

Multiline comments not working

When I try to add a multi line comment in any c like language it doesn't render properly. I didn't add any extensions to Prism.

/*
  This is a
  Block comment
*/

screenshot

Default rendering with newlines and ins/del/mark

After #5 and #7 were merged, I’m now thinking about the best way to style the line highlighter to make it render how it used to with full width background colors.

Previous behavior on eleventy-base-blog:

image

New behavior:

This is what it renders like without CSS (this is showing default styles for ins/del/mark, which are okay). I’ve added a few newlines in there just to see how #5 would look too (those were not in the previous behavior screenshot):
image

This is what it looks like on eleventy-base-blog after removing the ins/del/mark styles:
image

The display: block Problem:

When using .highlight-line { display: block; } to get full width highlights, the problem exhibits itself:
image

image

If I move the <br> inside of the highlight-line elements, I get what I want with display: block;
image

image

Would it be better to move the <br>? Or to use CSS to hide the <br> altogether when using display: block;

Chrome ignores br tags to make a new highlight line

Not an issue of the plugin itself, but I noticed that Chrome removes br tags from a resulting code tag which was highlighted. Here's the exact same page, first on FIrefox and then on Chrome:

Firefox

Captura de pantalla 2021-01-10 a la(s) 12 37 43

Chrome

Captura de pantalla 2021-01-10 a la(s) 12 38 08

This test page has no JavaScript or CSS.

Here's the reproduction case from above, if you want to run it locally:

test.zip

My advice here would be to move the default lineSeparator option to \n and fire a warning if the user sets it to <br> in the mean time, as the output of the package it's broken out of the box because of this.

If we decide this is the way we want to go I'm more than happy to create a PR.

BUG / FR / documentation: prism loading - possibility to load other languages; other prism components;

When adding the plugin and trying extending languages, only a few are available. Later on other languages will be accessible.

This is IMO a bug.

Adding new languages - init should be called after all other languages are loaded by the plugin (or prismjs)

Features I miss (some might just need documentation to be added):

  • default language fallback (text) - at least for MD
  • possibility to add aliases for languages
  • possibility to tell which languages get's loaded
  • also which components are loaded (like line highlight, line numbering, etc... although some might need extra plugin code)
    eleventyConfig.addPlugin(syntaxHighlight, {
        init: function({ Prism }) {
            
            Prism.languages.console = Prism.languages.extend('markup', {});
            Prism.languages.terminal = Prism.languages.extend('markup', {});
            console.log('init', Object.keys(Prism.languages))
        }
    });
init [
  'extend',   'insertBefore',
  'DFS',      'markup',
  'html',     'mathml',
  'svg',      'xml',
  'ssml',     'atom',
  'rss',      'css',
  'clike',    'javascript',
  'js',       'console',
  'terminal'
]

Later on languages include more: ruby,rb,yaml,yml,markdown,md,liquid,bash,shell,java,python,py

But still missing: cs, sql, ...

After upgrading from 3.0.4 to 3.0.5: `TemplateContentRenderError` was thrown when building

Issue

After upgrading eleventy-plugin-syntaxhighlight from 3.0.4 to 3.0.5, I'm getting the following error when building HTML templates with liquid:

> Having trouble rendering html template ./src/index.html

`TemplateContentRenderError` was thrown
> Having trouble compiling template ./src/index.html

`TemplateContentCompileError` was thrown
> Cannot read property 'parser' of undefined, file:./src/index.html, line:2

`ParseError` was thrown
> Cannot read property 'parser' of undefined

`TypeError` was thrown:
    TypeError: Cannot read property 'parser' of undefined
        at Object.parse (/FAKE_PATH/eleventy-syntax-highlighting-bug/node_modules/@11ty/eleventy-plugin-syntaxhighlight/src/LiquidHighlightTag.js:18:34)
        at Object.parse (/FAKE_PATH/eleventy-syntax-highlighting-bug/node_modules/liquidjs/dist/liquid.common.js:1876:22)
        at Object.construct (/FAKE_PATH/eleventy-syntax-highlighting-bug/node_modules/liquidjs/dist/liquid.common.js:1887:14)
        at parseTag (/FAKE_PATH/eleventy-syntax-highlighting-bug/node_modules/liquidjs/dist/liquid.common.js:2037:16)
        at parseToken (/FAKE_PATH/eleventy-syntax-highlighting-bug/node_modules/liquidjs/dist/liquid.common.js:2021:15)
        at Object.parse (/FAKE_PATH/eleventy-syntax-highlighting-bug/node_modules/liquidjs/dist/liquid.common.js:2012:22)
        at Object.parse$$1 [as parse] (/FAKE_PATH/eleventy-syntax-highlighting-bug/node_modules/liquidjs/dist/liquid.common.js:3420:24)
        at Liquid.compile (/FAKE_PATH/eleventy-syntax-highlighting-bug/node_modules/@11ty/eleventy/src/Engines/Liquid.js:199:29)
        at Html.compile (/FAKE_PATH/eleventy-syntax-highlighting-bug/node_modules/@11ty/eleventy/src/Engines/Html.js:11:29)
        at TemplateRender.getCompiledTemplate (/FAKE_PATH/eleventy-syntax-highlighting-bug/node_modules/@11ty/eleventy/src/TemplateRender.js:206:26)

Output previous version

With [email protected]:

$ eleventy
Writing _site/index.html from ./src/index.html.
Wrote 1 file in 0.09 seconds (v0.11.1)
✨  Done in 1.91s.

Repro

// package.json
{
  "name": "eleventy-syntax-highlighting-bug",
  "version": "1.0.0",
  "private": "true",
  "dependencies": {
    "@11ty/eleventy": "^0.11.1"
  },
  "scripts": {
    "build": "eleventy"
  },
  "devDependencies": {
    "@11ty/eleventy-plugin-syntaxhighlight": "3.0.5"
  }
}

// .eleventy.js
const syntaxHighlight = require("@11ty/eleventy-plugin-syntaxhighlight");

module.exports = function (eleventyConfig) {
  eleventyConfig.addPlugin(syntaxHighlight);

  return {
    dir: {
      input: "src",
    },
  };
};

// ./src/index.html
<div>
    {% highlight js %}
        console.log("hello world")
    {% endhighlight %}
</div>

Is there a copy button?

Not an issue, but I was wondering if there are any code examples or plugins that would add a copy button/icon to the code block so you can copy it to the clipboard?

Build error

Hi! Since installing this plugin, I'm getting this error when trying to build my site:

Problem writing eleventy templates:
TypeError: Cannot read property 'buildPlaceholders' of undefined
    at /Users/eduardoboucas/Sites/eduardoboucas.com/node_modules/prismjs/components/prism-php.js:118:39
    at Object.run (/Users/eduardoboucas/Sites/eduardoboucas.com/node_modules/prismjs/prism.js:456:5)
    at Object.highlight (/Users/eduardoboucas/Sites/eduardoboucas.com/node_modules/prismjs/prism.js:285:11)
    at Object.module.exports [as highlight] (/Users/eduardoboucas/Sites/eduardoboucas.com/node_modules/@11ty/eleventy-plugin-syntaxhighlight/src/markdownSyntaxHighlight.js:23:18)
    at Object.default_rules.fence (/Users/eduardoboucas/Sites/eduardoboucas.com/node_modules/markdown-it/lib/renderer.js:50:27)
    at Renderer.render (/Users/eduardoboucas/Sites/eduardoboucas.com/node_modules/markdown-it/lib/renderer.js:326:38)
    at MarkdownIt.render (/Users/eduardoboucas/Sites/eduardoboucas.com/node_modules/markdown-it/lib/index.js:543:24)
    at /Users/eduardoboucas/Sites/eduardoboucas.com/node_modules/@11ty/eleventy/src/Engines/Markdown.js:68:38
    at <anonymous>

It seems that the PHP highlighter is causing the issue in question. I found this, but not sure how useful that is in tracking down the problem.

Any thoughts are much appreciated. Happy to provide any information about my setup that you find useful.

Thanks!

Add processing of inline code in Markdown

Hi,

Recently I've tried writing some code with 11ty in markdown and faced with something unexpectable. With block code, everything works fine. But inline code is not.

This code
image

will be transformed into this:

image

Seems like inline code isn't processed at all. On block code result there are bunch of extra classes but on inline none of them.

As temporal fix I'm using HTML in markdown (<code class="language-">Some inline code with custom wrap</code>).

Is this a bug or my misconfiguration?

HTML entities are not encoded when using plain text

Using this Markdown code:

```text
<b>test</b>
```

The HTML is not encoded and I end up with a code block that just says "test", in bold. In other words this is the HTML output:

<pre class="language-text"><code class="language-text"><b>test</b></code></pre>

It should be this:

<pre class="language-text"><code class="language-text">&lt;b&gt;test&lt;/b&gt;</code></pre>

Using any other language (e.g. js) encodes the entities correctly. As does omitting a language (just using ```) but then you don't get the default highlighting (box colour etc).

Line highlight is being added to the wrong lines

I realized that in version 3.0.1, the mark wrapper along with the highlight-line-active are being added to the line you declared plus 1.

Ex.

using ``` js/3

console.log(...);
console.log(...);
console.log("should be here");
console.log("but it highlights this line");

I fixed it locally by changing this line https://github.com/11ty/eleventy-plugin-syntaxhighlight/blob/master/src/markdownSyntaxHighlightOptions.js#L30
with let lineContent = highlights.getLineMarkup(j + 1, line);

Is this a problem that everybody is facing or is there something wrong on my local setup?

Code blocks not maintaining preformatted whitespace

I noticed the code blocks on my site are missing the expected whitespace. When I checked the docs I noticed the 11ty site is suffering from the same issue.

I hadn't noticed this until recently; I know for sure code blocks were displaying as expected at some point (as they were in the 11ty docs). The only recent change I've made that I can think might be related is updating to Eleventy version 0.11.1.

I can get the expected whitespace in the output by fencing with backticks. However, if I add the language identifier to the fenced block the whitespace goes away.

```scss # highlighting, but with incorrect whitespace
``` # correct whitespace, but obviously no syntax highlighting

In addition, {% highlight scss %} gives me the same result as backticks + language identifier.

{% highlight scss %} # highlighting, but with incorrect whitespace

Thanks. Let me know if I can provide any additional details.

Template Literal syntax causing new line

This example on 11ty.io:

var { graphql, buildSchema } = require("graphql");
  
// this could also be `async function`
module.exports = function() {
  // if you want to `await` for other things here, use `async function`
  var schema = buildSchema(`type Query {
    hello: String
  }`);
  
  var root = {
    hello: () => "Hello world async!"
  };
  
  return graphql(schema, "{ hello }", root);
};

Works fine on https://prismjs.com/test.html
Works fine when using language text.
But when using language js it outputs this:

image

Note the ); on a new line.

Major issue with syntax-highlight plugin for multi-line code blocks

@zachleat Everything that is being highlighted by eleventy-plugin-syntaxhighlight on 11ty.dev has some issues with the styling.

Each of the multi-line code blocks are formatted into a single line. This issue is probably happening for everyone using the plugin, as I first noticed it on my own website.

Also, all of the <pre> tags have an extra space at the beginning of the class declaration like this (which I don't think matters but just wanted to note everything I saw)

<pre class=" language-html">

Screenshot of issue:
Screen Shot 2020-12-12 at 1 26 21 PM

The above code snippets are supposed to be multi line but obviously they are not.

I tried to tweak the CSS in my prism.css file locally to get the multi-line format to come back but I'm still trying to figure out where exactly the problem is at.

Characters are not escaped when a code block's language is set to `text`

Problem

When using fenced code blocks like this:

```text
some plain text code in here
```

The plain-text code is not properly escaped. So if it has < or >, those get rendered as literal tags and start throwing all kinds of HTML validation errors (this is currently affecting multiple pages on my site).

Steps to reproduce

  1. Create a basic 11ty site with this plugin installed.
  2. Create a markdown post with this code block:
```text
This <is> some text.
```
  1. Observe that the rendered source has unescaped characters.

Example:

image

Question

Is this not how I should be using the text language? I can render fenced code blocks without specifying any language, but then I don't get any classes on the rendered pre/code or any nested spans. I was under the impression that text should still escape characters.

Unsupported diff-* highlighting

Prism allows convenient diff line highlighting with preservation of underlying syntax highlighting via a Diff Highlight plugin: https://prismjs.com/plugins/diff-highlight/

However, trying to use it via 11ty via e.g. ```diff-javascript tag currently fails with

`TemplateContentRenderError` was thrown
> "diff-javascript" is not a valid Prism.js language for eleventy-plugin-syntaxhighlight

`Error` was thrown:
    Error: "diff-javascript" is not a valid Prism.js language for eleventy-plugin-syntaxhighlight
        at module.exports (/mnt/c/src/web.dev/node_modules/.pnpm/@11ty/[email protected]_@[email protected]/node_modules/@11ty/eleventy-plugin-syntaxhighlight/src/PrismLoader.js:11:11)
...

Looks like this might require some special handling similarly to TypeScript tag?

highlight html

I have one code snippet in a .MD file

```html
<div id="container" class="my-container">
  I want my <span class="text red">color</span>
</div>

<style>
#container span {
  color: blue;
}

.my-container .text.red {
  color: red;
}
</style>

But the HTML part of this snippet is being rendered as HTML:
image

Add filename to code block

Is there a way to add a filename to the code block with this library? What I have is mind is something like what is shown in the topright corner of the screenshot below.
image

'class' attribute value in preAttributes and codeAttributes doesn't work

Description

When a user adds a class attribute value to preAttributes or codeAttributes, nothing happens:

eleventyConfig.addPlugin(pluginSyntaxHighlight, {
    preAttributes: {
      class: "hey-this-is-a-custom-class-name",
    },
    codeAttributes: "this-is-also-custom-class-name",
});

Resulting DOM:

Screenshot 2021-06-03 at 23 48 32

I assume this is because <pre> and <code> already have a class name that denotes the language being used (e.g. language-js).

Possible solutions

  1. Maybe we can concatenate the new class names to the existing one, taking care not to overwrite the originals
  2. ...or add the possibility for the user to add a wrapper element over the <pre>, because the scenario (at least in my case) is to add some layout styling to the code block (say, max-width):
eleventyConfig.addPlugin(pluginSyntaxHighlight, {
    wrapper: {
      element: "div",
      attributes: {
         // here be attributes
      }
    },
});

Providing a default language for fenced code blocks

Use case

In many markdown editors, I can write a fenced code blog and receive plaintext code styling without specifying a language.

E.g. writing this in GitHub markdown:

```
This is some plain text
```

Looks like this:

This is some plain text

Currently, when no language is specified on a fenced code block, this plugin outputs plain <pre> and <code> tags without a "language-*" class applied. In many Prism themes, such as the prism-okaidia theme shown in the plugin docs, this means the code block will not receive any styling. This is unexpected behavior for me.

Proposed Solution

To avoid breaking changes, I propose adding a defaultLanguage plugin option, which users may want to set to "plain". That way a generic code block like this:

```
This is some plain text
```

could be rendered as

<pre class="language-plain"><code class="language-plain">
This is some plain text
</code></pre>

Additional Context

Initially I thought I could set default languages like so:

eleventyConfig.addPlugin(pluginSyntaxHighlight, {
    preAttributes: {
      class: "language-plain",
    },
    codeAttributes: {
      class: "language-plain",
    },
});

However, as brought up in #52 this does not work. Resolving that issue could also resolve this one.

Diff Highlights

The eleventy docs site for this plugin includes the following css snippets:

.highlight-line-add {
  background-color: #45844b;
}
.highlight-line-remove {
  background-color: #902f2f;
}

Is diff highlighting supported? If so, what is the syntax? I tried:

```language-diff-typescript
- const foo = 'test';
+ const bar = 'test';
```

and the highlight classes are not applied 🤔

Highlight specific keywords in the codeblock

It would be great to pass an additional keywords parameter which is then matched in the code to add highlight or bold.

{% highlight lang keywords="['card', 'card-large', 'card-footer']" %}
      <div class="card card-large">
          <div class="card-header">Header</div>
          <div class="card-body">body</div>
          <div class="card-footer">footer</div>
      </div>
{% endhighlight %}

This would then have the keywords matched and wrapped in a class that add special styling to make them bold.

<div class="<span class="highlight-keyword">card</span> <span class="highlight-keyword">card-large</span>">
       <div class="card-header">Header</div>
      <div class="card-body">body</div>
      <div class="<span class="highlight-keyword">card-footer</span>">footer</div>
</div>

I had a go at using the init option to try extend Prism, but wasn't sure how I could capture the keywords being passed.

Does anyone know if this can already be done or otherwise how I might go about implementing something similar?

Provide a `| highlight` filter as well?

The paired shortcode is great when I know that an entire block rendered in my template will be code - but sometimes I'm rendering arbitrary markdown that might have code blocks nested inside. In that case, I'd love to do something like:

{{ data | markdown | highlight | safe }}

For now, I'll try importing prism as a stand-alone in addition to eleventy-plugin-syntaxhighlight - and use it to generate a custom filter (or tag along on my markdown filter).

Use only some of the highlighter pack

Eleventy currently imports all the highlighters (2 liquid tags, markdown in v1.0.4) when using eleventyConfig.addPlugin.

This issue is to gather public support for the option to include only some of these highlighters in your .eleventy.js.

Thumbs up here if you want this, otherwise it won’t get implemented 😎

npm audit shows high severity advisory

# npm audit report

css-what  <5.0.1
Severity: high
Denial of Service - https://npmjs.com/advisories/1754
fix available via `npm audit fix --force`
Will install [email protected], which is a breaking change
node_modules/css-what
  css-select  <=3.1.2
  Depends on vulnerable versions of css-what
  node_modules/css-select
    linkedom  0.1.0 - 0.7.3
    Depends on vulnerable versions of css-select
    node_modules/linkedom

3 high severity vulnerabilities

linkedom currently pinned ^0.5.5

Syntax highlighting adds <br> elements between lines, effectively causing double line spacing

The lines.join("<br>") call in the line below causes the resulting markup to have <br> elements joining highlighted lines.

return `<pre class="language-${language}"><code class="language-${language}">` + lines.join("<br>") + "</code></pre>";

<pre class="language-csharp">
    <code class="language-csharp">
        <span class="highlight-line">
            <span class="token keyword">public</span>
            <span class="token keyword">string</span>
            <span class="token function">GetEvenOdd</span>
            <span class="token punctuation">(</span>
            <span class="token keyword">int</span> i
            <span class="token punctuation">)</span>
        </span>
        <br>
        <span class="highlight-line">
            <span class="token punctuation">{</span>
        </span>
        <br>
        <span class="highlight-line">
            <span class="token keyword">if</span>
            <span class="token punctuation">(</span>i 
            <span class="token operator">%</span>
            <span class="token number">2</span>
            <span class="token operator">==</span>
            <span class="token number">0</span>
            <span class="token punctuation">)</span>
        </span>
        <br>
        <span class="highlight-line">
            <span class="token punctuation">{</span>
        </span>
        <br>
        <span class="highlight-line">
            <span class="token keyword">return</span>
            <span class="token string">"even"</span>
            <span class="token punctuation">;</span>
        </span>
        <br>
        <span class="highlight-line">
            <span class="token punctuation">}</span>
        </span>
        <br>
        <span class="highlight-line"></span>
        <br>
        <span class="highlight-line">
            <span class="token keyword">return</span>
            <span class="token string">"odd"</span>
            <span class="token punctuation">;</span>
        </span>
        <br>
        <span class="highlight-line">
            <span class="token punctuation">}</span>
        </span>
    </code>
</pre>

This causes double line spacing and doesn't look right. Instead of this

public string GetEvenOdd(int i)
{
    if (i % 2 == 0)
    {
        return "even";
    }

    return "odd";
}

You get this

public string GetEvenOdd(int i)

{

    if (i % 2 == 0)

    {

        return "even";

    }



    return "odd";

}

As rendered on the page

image

I'm using eleventy 0.8.3, eleventy-plugin-syntaxhighlight 2.0.3 with nunjucks templates.

Loading PrismJS in Eleventy config breaks plugin

Hello, folks.

To be honest, I'm not sure if this is an expected behavior, or something unintended. In a recent project, I was using eleventy-plugin-syntaxhighlight to provide straightforward highlighting for markdown files. However, I also created a shortcode for creating previews of code snippets and their processed output. Essentially, what Bootstrap does in their documentation.

Screen Shot 2020-10-28 at 5 19 01 PM

For this shortcode, I ended up needing to load my own instance of PrismJS, and the languages I'd need to utilize. Here's a shorthand of what was going on in my config.

eleventy.js

// Load libraries and dependencies
const prism = require("prismjs");
const loadLanguages = require("prismjs/components/");
loadLanguages(['html', 'jsx', 'json', 'twig', 'velocity']);
const syntaxHighlight = require("@11ty/eleventy-plugin-syntaxhighlight");

module.exports = function(eleventyConfig) {
  eleventyConfig.addPlugin(syntaxHighlight);

  // Code examples shortcode
  eleventyConfig.addPairedShortcode("example", function(content, title, show_preview, show_markup) {
    let highlightedContent = prism.highlight(content.trim(), prism.languages["html"], "html");

    let lines = highlightedContent.split("\n");
    lines = lines.map(function(line, j) {
      return line;
    });

    return outdent`
      <div class="card docs-example">
        ${title ? `<h6 class="card-header">${title}</h6>` : `<h6 class="card-header">Example</h6>`}
        <div class="card-body">
          ${show_preview ? `<div class="docs-example-content">${content}</div>` : ``}
          ${show_markup ? `<div class="docs-example-markup"><pre class="language-html"><code class="language-html">` + lines.join("<br>") + "</code></pre></div>" : ``}
        </div><!-- /.card-body -->
      </div><!-- /.docs-example -->
    `
  });

  // And so on
}

In one of my markdown files, I attempted to use eleventy-plugin-syntaxhighlight to style a bash script. What I've discovered is that, by loading PrismJS for use with my shortcode, I inadvertently caused the eleventy-plugin-syntaxhighlight plugin to no longer load the correct languages. I received an error in my console explaining that bash was not an available language for PrismJS.

I ran in circles for a bit before thinking to remove my shortcode and the const prism = require("prismjs"); module. I think the error is occurring either from loading Prism in the config, or by loading const loadLanguages = require("prismjs/components/"); in the config. Even if I removed my shortcode and kept the module imports, the same error would occur. Removing the modules caused the plugin to successfully process the bash highlighting without issue.

Any thoughts on whether or not this is expected, or how to use both functions while maintaining compatibility?

Added and removed lines get no special styling

I ran the demo with a fenced code block that had some lines added and removed.

```js/4-5/2-3
let multilineString = `
  this is the first line
  this line is removed
  this line is also removed
  this line is added
  this line is also added
  this is the last line
`;
```

Those lines didn't seem to differentiate from "normal" lines. Here's a GIF:

hl-lines

The generated markup is fine. It's just that test.css hides the browser's default styles for <ins>, and <del>.

Could the stylesheet perhaps be changed so that we give appropriate background-color-s to .highlight-line-* similarly to how eleventy-base-blog does it?

If OK, would you be open to a PR?

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.