javascripthighlight.js

Highlight symbols and numbers with Highlight.js


I would like to use highlight.js library, ‏ and I am not able to highlight the + symbol and numbers (e.g. 1000).‏ Is there anyway to do that?‏

import React, { Component } from 'react'
import hljs from 'highlight.js'

export default class App extends Component {
  constructor(){
    super();
    this.state = {
    }
  }

  componentDidMount(){
    hljs.registerLanguage("pl", function(hljs) {
      return {
        case_insensitive: false,
        keywords: {
        literal: '--',
        symbols: '+',
        keyword0: ' minus # plus   ++ $_  ',
       operator:' 1 2 3 4 /+ ',
       numbers: '/[0-9]+?/',
        keyword1: ' THEMENBEREICH ZEIT AUS BIS GIB HAT IST MAX MIN MIT TYP VAR VON'
        
        },
      contains: [
          {
            className: 'string',
            begin: "'",
          end: "'",
         // contains: [hljs.BACKSLASH_ESCAPE]
          },
          
      hljs.COMMENT(
            '"', // begin
            '"'  // end
      )
        ]
    };
    })

  }

  updateCodeSyntaxHighlighting = () => {
    document.querySelectorAll("pre code").forEach(block => {
      hljs.highlightBlock(block);
    });
  };
  
handle(event){
    this.setState({
        data:event.target.value
  })
}

  render() {
    let eingabe = this.state.data
     return (
      <div>
        <textarea cols="30" rows="5" type="text"  onChange={this.handle.bind(this)}/>
        <br/>
        <button   onClick={this.updateCodeSyntaxHighlighting.bind(this)}>   clik   </button>
        <pre><code class="pl"> 
       
        {this.state.data} 
        </code></pre>
          
      </div>
    )
  }
}

Solution

  • Make separate rules instead of using keywords.

    contains: 
    [
      { 
        className: "number",
        begin: /\d+/
      },
      {
        className: "symbol",
        begin: /+/
      }
    ]
    

    Etc.

    Or you could try keywords.$pattern = /\S+/, ie a keyword is any list of sequential characters that doesn't include a space...

    https://highlightjs.readthedocs.io/en/latest/language-guide.html#keywords