Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code blocks and syntax highlight #5

Closed
GBrachetta opened this issue Feb 20, 2021 · 19 comments
Closed

Code blocks and syntax highlight #5

GBrachetta opened this issue Feb 20, 2021 · 19 comments

Comments

@GBrachetta
Copy link

GBrachetta commented Feb 20, 2021

I'm not sure this happens only with your template, but the first line of code blocks gets a ½ character indentation, so for this snippet, for example:

```sql
ALTER ROLE <username> SET client_encoding TO 'utf8';
ALTER ROLE <username> SET default_transaction_isolation TO 'read committed';
ALTER ROLE <username> SET timezone TO 'UTC';
``` (need to write this so the code doesn't render in the issue and shows what I use in the md file, please disregard)

I get this result:

Screenshot 2021-02-20 at 18 08 32

You can see that the first line gets a ½ character indentation. Strange!

Also, I don't get any syntax coloring for my code snippets, regardless of the language I pick.

@hikerpig
Copy link
Owner

Thank you for asking.
Yeah I havn't paid attention to syntax highlighting in gatsby-theme-kb very much, people may have different preferences on this and they can always add gatsby remark prism or other plugins.

But I can try to add some examples in this repo though. Might take a few days.

@GBrachetta
Copy link
Author

GBrachetta commented Feb 21, 2021

Ah, thank you! I didn't realise I needed a plugin! :)

I tried installing

yarn add gatsby-transformer-remark gatsby-remark-prismjs prismjs

and added this in my gatsby-config.js, under your gatsby-plugin-copy-files-enhanced, as an additional plugin:

    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          {
            resolve: `gatsby-remark-prismjs`,
            options: {
              classPrefix: 'language-',
              inlineCodeMarker: null,
              aliases: {},
              showLineNumbers: true,
              noInlineHighlight: false,
              languageExtensions: [
                {
                  language: 'superscript',
                  extend: 'javascript',
                  definition: {
                    superscript_types: /(SuperType)/,
                  },
                  insertBefore: {
                    function: {
                      superscript_keywords: /(superif|superelse)/,
                    },
                  },
                },
              ],
              prompt: {
                user: 'root',
                host: 'localhost',
                global: false,
              },
              escapeEntities: {},
            },
          },
        ],
      },
    }

I then created a gatsby-browser.js file, with

require('prismjs/themes/prism-dark.css');
require('prismjs/plugins/line-numbers/prism-line-numbers.css');
require('prismjs/plugins/command-line/prism-command-line.css');

So I can have a theme, line numbers and a command-line $ prompt for bash commands, but I have the feeling I'm messing things up because things don't seem to be working fine 😄

(note: I tried to follow this)

@hikerpig
Copy link
Owner

Oh, the gatsby-theme-kb is using gatsby-plugin-mdx and not the transformer you mentioned.

@GBrachetta
Copy link
Author

Oh, I knew I was messing things up!

Whenever you have time to show how to do this properly, I'd be really grateful!

@hikerpig
Copy link
Owner

Sure, I will try to finish this before next weekend.

@GBrachetta
Copy link
Author

GBrachetta commented Feb 21, 2021

I don't know if this is the way to go, but I managed to get syntax highlighting doing this:

yarn add gatsby-remark-prismjs prismjs

In gatsby-config.js, add the following line under resolve: gatsby-remark-copy-linked-files:

resolve: `gatsby-remark-prismjs`,

After the closing curly brace for the copy-files-enhanced plugin, added:

    {
      resolve: `gatsby-remark-prismjs`,
      options: {
        classPrefix: 'language-',
        inlineCodeMarker: null,
        aliases: {},
        showLineNumbers: false,
        noInlineHighlight: false,
        prompt: {
          user: 'root',
          host: 'localhost',
          global: true,
        },
        escapeEntities: {},
      },
    },

Created a file `gatsby-browser.js, and added:

require('prismjs/themes/prism-okaidia.css');
require('prismjs/plugins/command-line/prism-command-line.css');
require('prismjs/plugins/line-numbers/prism-line-numbers.css');
require('./style.css');

created inside _layouts a file style.css, referenced in gatsby-browser.js and added my styles as described here.

I'm not sure if this is the way you would do it, but It seems to be working so far though! 😄 (although I have the feeling my gatsby-config file isn't correct because my options aren't working...)

@hikerpig
Copy link
Owner

@GBrachetta Actually that what I will do, congrats! As for the options, I don't have a clue yet, though. Will wait for I get started. And I will take your solution as a start, thank you !

@GBrachetta
Copy link
Author

Oh that's nice to hear!!

I think the options have to be passed in this function

getPluginMdx(defaultPluginMdx) {
         defaultPluginMdx.options.gatsbyRemarkPlugins.push({
           resolve: `gatsby-remark-copy-linked-files`,
           resolve: `gatsby-remark-prismjs`,
           options: {
             ignoreFileExtensions: ['md', 'mdx'],
           },
         });
         return defaultPluginMdx;
       },

under ignoreFileExtensions, but for some reason when I do so the rendering hangs when I request a note.

I'll wait for your solution 😄

@GBrachetta
Copy link
Author

GBrachetta commented Feb 21, 2021

I managed 😄

These are the files, in case you find them useful:

  • package.json
{
    "name": "foam-template-gatsby-kb",
    "version": "1.0.0",
    "description": "A foam template using gatsby-theme-kb for publishing you knowledge base",
    "main": "index.js",
    "scripts": {
        "dev": "gatsby develop",
        "build": "gatsby build --prefix-paths",
        "serve": "gatsby serve"
    },
    "keywords": [
        "foam"
    ],
    "author": "chenmin",
    "license": "MIT",
    "dependencies": {
        "gatsby": "^2.31.1",
        "gatsby-plugin-copy-files-enhanced": "^1.1.1",
        "gatsby-remark-copy-linked-files": "^2.10.0",
        "gatsby-remark-prismjs": "^3.13.0",
        "gatsby-theme-kb": "latest",
        "prismjs": "^1.23.0"
    }
}
  • gatsby-config.js
const path = require('path');

module.exports = {
  pathPrefix: `/`,
  siteMetadata: {
    title: `Title`,
    author: `Author`,
    description: `Description`,
  },
  plugins: [
    {
      resolve: `gatsby-theme-kb`,
      options: {
        rootNote: '/readme',
        contentPath: `${__dirname}/..`,
        ignore: [
          '**/_layouts/**',
          '**/.git/**',
          '**/.github/**',
          '**/.vscode/**',
          '**/.cache/**',
        ],
        getPluginMdx(defaultPluginMdx) {
          defaultPluginMdx.options.gatsbyRemarkPlugins.push({
            resolve: `gatsby-remark-copy-linked-files`,
            options: {
              ignoreFileExtensions: ['md', 'mdx'],
            },
          });
          defaultPluginMdx.options.gatsbyRemarkPlugins.push({
            resolve: `gatsby-remark-prismjs`,
            options: {
              prompt: {
                user: 'root',
                host: 'localhost',
                global: true,
              },
              inlineCodeMarker: '>',
            },
          });
          return defaultPluginMdx;
        },
      },
    },
    {
      resolve: 'gatsby-plugin-copy-files-enhanced',
      options: {
        source: path.resolve(__dirname, `../assets`),
        destination: '/assets',
        purge: false,
      },
    },
  ],
};
  • gatsby-browser.js
require('prismjs/themes/prism-okaidia.css');
require('prismjs/plugins/command-line/prism-command-line.css');
require('prismjs/plugins/line-numbers/prism-line-numbers.css');
require('./style.css'); // optional
  • style.css (optional, in case the file is required in gatsby-browser.js. Here's where the user tweaks the styling of the plugin.
/* Styles for line numbering */
.gatsby-highlight pre[class*="language-"].line-numbers {
  padding-left: 2.8em;
}

/* Styles for line highlighting */
.gatsby-highlight-code-line {
  background-color: rgba(30, 66, 87, 0.5);
  display: block;
  margin-right: -1em;
  margin-left: -1em;
  padding-right: 1em;
  padding-left: 0.75em;
  border-left: 0.25em solid rgb(143, 29, 29);
}

/* Styles for bash prompt */
.command-line-prompt > span:before {
  color: #7bbeb9;
  content: " ";
  display: block;
  padding-right: 0.8em;
}

/* Prompt for all users */
.command-line-prompt > span[data-user]:before {
  content: "[" attr(data-user) "@" attr(data-host) "] $";
}

/* Prompt for root */
.command-line-prompt > span[data-user="root"]:before {
  content: "[" attr(data-user) "@" attr(data-host) "] #";
}

.command-line-prompt > span[data-prompt]:before {
  content: attr(data-prompt);
}

/* Styles for code background color */
:not(pre) > code[class*="language-"],
pre[class*="language-"] {
  background-color: #292e3a;
}

Hope you don't mind me sending you these, but perhaps saves you some time!

@orta
Copy link
Contributor

orta commented Feb 21, 2021

I added shiki and twoslash ( the infra which powers TypeScript's website) in https://github.com/orta/notes - config:

          defaultPluginMdx.options.gatsbyRemarkPlugins.push({
            resolve: "gatsby-remark-shiki-twoslash",
            options: {
              theme: "github-light",
              useNodeModules: true,
              nodeModulesTypesPath: path.join(__dirname, "..", "node_modules"),
            },
          });

CSS

@GBrachetta
Copy link
Author

@orta This looks quite nice actually!
There's a lot more css involved, but I like the flexibility.
I managed to run it, without creating a src folder but just the css file and requiring it in gatsby-browser.
Where can I find more information to style it? (Also about line numbers/bash prompts, etc)
I also see the language displayed in the top-left corner, and would like to get rid of it:

Screenshot 2021-02-21 at 20 53 41

Thanks for this tip, it looks quite nice.

@orta
Copy link
Contributor

orta commented Feb 21, 2021

ah yeah, I use Gatsby theme shadowing to inject my CSS: https://github.com/orta/notes/tree/master/_layouts/src/gatsby-theme-kb/components/Topic

[Shiki]|(https://shiki.matsu.io) is pretty sparsely documented, it's on the todo to get some of those kind of features in

@hikerpig
Copy link
Owner

So glad to see you two get what you wanted and learn something about shiki and twoslash. 🥳
I should put this discussion in the readme for example, and just fix the indentation in gatsby-theme-kb.

@hikerpig hikerpig changed the title Strange indentation in code blocks Code blocks and syntax highlight Feb 26, 2021
@hikerpig
Copy link
Owner

I've add example configs to default gatsby-config.js, I chose PrismJS over shiki for I want to change some of the syntax styles when switching between dark/light mode, and in my tests shiki produces inline style which is not easy to change, I guess.

@GBrachetta
Copy link
Author

Amazing! I'll compare it with what I did and will obviously overwrite my wrongs with your solution! Thank you!

@GBrachetta
Copy link
Author

Hi! Just following up on the issue with the offseft first line in codeblocks, I see that when using line numbers the same happens to the vertical alignment, so it is not only horizontally offset half space but as well vertically.

I created a quick screenshot to illustrate it:

Git_Gists___My_Brain

I wonder if these two displacements are related?

@hikerpig
Copy link
Owner

@GBrachetta I will fix this today. 👍

@hikerpig
Copy link
Owner

@GBrachetta Some quick fixes

/* This rule will fix the horizontal offset, I shall add it to gatsby-theme-kb and publish some days later, but you can add it to your styles for a quickfix */
pre code {
  padding: 0;
}

/*
  This will fix the line number issue,
  you should add this only if you have `showLineNumbers: true` option for gatsby-remark-prismjs
*/
.line-numbers .line-numbers-rows {
  padding-top: 1em;
  padding-bottom: 1em;
}

@GBrachetta
Copy link
Author

Yes, wonderful, that sorts it!

I don't show numbers by default (meaning I don't have 'showLineNumbers: true') but only when I pass them with {numberLines: true}.

This looks a lot better now:

Screenshot 2021-03-14 at 16 48 21

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants