GithubHelp home page GithubHelp logo

highlightjs / highlight.js Goto Github PK

View Code? Open in Web Editor NEW
23.1K 309.0 3.5K 14.59 MB

JavaScript syntax highlighter with language auto-detection and zero dependencies.

Home Page: https://highlightjs.org/

License: BSD 3-Clause "New" or "Revised" License

JavaScript 63.77% CSS 34.83% Shell 0.04% Groovy 0.12% Scheme 0.03% HTML 0.76% Hy 0.08% Dockerfile 0.02% R 0.35%
syntax-highlighting language-grammars highlighting syntax-highlighter javascript hacktoberfest

highlight.js's People

Contributors

amckibben avatar atelierbram avatar bolknote avatar bradleymackey avatar buildersbrewery avatar chriseidhof avatar daiz avatar egor-rogov avatar ericfromcanada avatar greenkeeper[bot] avatar hamaluik avatar hirse avatar idleberg avatar isagalaev avatar jf990 avatar joshgoebel avatar ldct avatar lucaswerkmeister avatar makenowjust avatar marcoscaceres avatar nicolas01 avatar non avatar oicmudkips avatar ozlerhakan avatar rparree avatar sannis avatar sourrust avatar sv avatar temp-impl avatar wkania 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  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

highlight.js's Issues

Line numbers

Hello there.

As you may or may not know I am using your good library on my Chrome extension Sight.
I realized you have a branch called line-numbers. I tried it out and seems to work pretty well.
Any objections or help you need to merge it into master? I want to use this feature.

Cheers,
Tomás

Suggestion: Allow defining a function to parse a mode

I am trying to use highlight.js to highlight Markdown, as well as the code inside of indented code blocks.

It appears that this is one task that the system (and regexes in general) cannot deal with.

So I think it would be great if there is a way to define a function which will be able to compute where the submode will begin and end. All it needs to do is basically check that newlines are being followed by 4 spaces within the block for it to be valid.

What do you think of this? Would this create a problem with the stability of the system or any other factors?

One of the reasons why I want to do this is because the auto-language-detection method is really cool and works really well for these markdown code blocks.

Enhancement Request: Change CSS selector to "code" instead of "pre"

Firstly thank you! After tinkering around with Google Prettify, I decided to go with your fantastic script instead.

I've implemented highlighting of inline-code using hljs.highlightBlock(). The appropriate span classes are added, but the themes will NOT work with inline-code, because by default they are set by the <pre> tag.

For personal use, I've modified the CSS files. But for other users in the future, it may be easier to change the source files.

Would you consider using a code selector instead of pre in your theme CSS files. This will allow the use of hljs.highlightBlock() on inline-code to be "colorized" while still maintaining the default highlighting of <pre><code> blocks.

Coffeescript arguments are not detected

As showed in the Highlight js demo, "student" is not identified

grade = (student) ->
  if student.excellentWork
    "A+"
  else if student.okayStuff
    if student.triedHard then "B" else "B-"
  else
    "C"

Multiline code is not handled correctly

Recently, we have been trying to use highlight.js on VBA code, which we believe has the same syntax as VBScript. We use 'vbscript' as the identifier for specifying the language. Everything works very well except for one part: the handling of multiple line code.

Here is an example fragment which fails at the end:

Dim mary As Person, george As Person, mimi As Person

Set mary = New Person

mary.initialize('Mary White', '1960/11/28', 50000, 'Very kind ' & _

    'and loving, she loves cooking and taking care of the house')

This VBA code works fine in the real world. The '_' is used to split code across two or more lines. However, the last parenthesis ')' of the last line of code is recognised by highlight.js as being part of the string. It is not recognised as being part of the parenthesis expression started on the previous line.

Actually we went through the development guide hoping to create a new language specification for VBA but failed to figure out how to handle the '_' situation, like the one in the above code example.

It would be extremely helpful if you could tell us whether it is possible to do what we want to do.

Thank you very much for your kind attention and help!

PODs in highlight.js require =cut

But in language itself, they are optional. Commonly, documentation is inserted at end of Perl scripts, so if there is no =cut everything is just... black.

Example:

my $a = 2 eq '2'; # arbitary example to test.

=head1 NAME

Blah::Blah - Blah Module

Also, PODs can only happen at beginning of lines, but in case of my @blah=reverse @array highlight.js sees PODs anyways.

'\\' in C++ is disallowed

(ok, sorry for mentioning a lot of issues, but I really find this highlighter interesting)

Following code doesn't work and causes very epic failure (everything is black). It doesn't happen with other backslash escape sequences.

#include <stdio.h>
int main() {
    printf("%c", '\\');
}

JavaScript recognized as PHP

/**
 * Выполнить метод ["objectName", "methodName"]
 * @param {Object|Array|String} method  Выполнить этот метод. 
 *          Если строка, то контекст - window,
 *          иначе контекст определяется из первых параметров массива,
 *          последний - это имя метода.
 * @param {Mix}     params  Передать методу параметры
 * @param {Event}   evt     Объект события
 */
run_method: function(method, params, evt) {
  params = params || {};
  evt = evt || {};
  if (typeof(method) == 'object' || typeof(method) == 'array') {
    var curEl = window;
    if (typeof(window[method[0]]) == 'undefined') {
      APP.load_plugin(method[0], function() {
        APP.run_method(method, params, evt);
      });
      return;
    }
  }
}

Support multiple <code> tags in one <pre> tag

Currently only the first code tag is used - as far as I know from looking through the code.

Therefore I would return a list of code elements in the findCode() method.

function findCodes(pre) {
    var codes = new Array();
    for (var i = 0; i < pre.childNodes.length; i++) {
      var node = pre.childNodes[i];
      if (node.nodeType == 1 && node.nodeName == 'CODE'){ // 1 == ELEMENT_NODE
        codes.push(node);
      }
    }
    return codes;
  }

Отступы в коде: 1 TAB === 4 пробела

Работаю с кодом C++ в Visual Studio. А эта штука совершенно наплевательски относится к тому, чем заполнены отступы: прекрасно всё смотрится в её родном редакторе, но при копировании кода на сайт получаем отступы, разбавленные и пробелами, и табуляцией. В программе 1 табуляция, обычно, равна 4 пробелам. Пусть бы highlight тоже знал об этом.

Пример кода > http://savdalion.blogspot.com/2011/01/test.html#4

[Bash] sharp sign inside single quotes

I try to highlight pre/code[class="bash"]... with highlight.js. When there is a sharp sign (#) inside a single quoted string, it highlights the sharp and the rest of the line as it's being a comment.

It's not reproduced inside double quotes.

I can supply a test. (Not sure how to upload an archive)

Python `def` breaks simple Ruby functions

If Ruby define doesn't have $, {, = or ; it's guessed as Python (this snippet has 21 of relevance for Python and 6 for Ruby). Obviously, it's not Python as def should end with : but highlight.js still accepts it and gives it very high relevance compared to Ruby.

def hello_world
  # puts? Well, this is Ruby
  puts 'Hello, world!'
end

arguments.callee is no longer supported in strict mode

offset = arguments.callee(node.childNodes[i], offset); violate the strict mode rule, since 'arguments.callee is no longer supported' (https://developer.mozilla.org/en/JavaScript/Strict_mode)

function nodeStream(node) {
  var result = [];
  (function (node, offset) {
    for (var i = 0; i < node.childNodes.length; i++) {
      if (node.childNodes[i].nodeType == 3)
        offset += node.childNodes[i].nodeValue.length;
      else if (node.childNodes[i].nodeName == 'BR')
        offset += 1;
      else if (node.childNodes[i].nodeType == 1) {
        result.push({
          event: 'start',
          offset: offset,
          node: node.childNodes[i]
        });
        offset = **arguments.callee**(node.childNodes[i], offset);
        result.push({
          event: 'stop',
          offset: offset,
          node: node.childNodes[i]
        });
      }
    }
    return offset;
  })(node, 0);
  return result;
}

so how about:

function nodeStream(node) {
  var result = [];
  (function callee(node, offset) {
    for (var i = 0; i < node.childNodes.length; i++) {
      if (node.childNodes[i].nodeType == 3)
        offset += node.childNodes[i].nodeValue.length;
      else if (node.childNodes[i].nodeName == 'BR')
        offset += 1;
      else if (node.childNodes[i].nodeType == 1) {
        result.push({
          event: 'start',
          offset: offset,
          node: node.childNodes[i]
        });
        offset = callee(node.childNodes[i], offset);
        result.push({
          event: 'stop',
          offset: offset,
          node: node.childNodes[i]
        });
      }
    }
    return offset;
  })(node, 0);
  return result;
}

HTML Tags parsed?

In this simple HTML file, it seems that the code between the angle brackets are being parsed as HTML tags. Is it just me, or am I doing something wrong? I'm using the C++ example in the demos.

<html>
<head>
<script type ="text/javascript" src="http://yandex.st/highlightjs/6.2/highlight.min.js"></script>
<link rel="stylesheet" href="http://yandex.st/highlightjs/6.2/styles/default.min.css">
<script>hljs.initHighlightingOnLoad();</script>
</head>
<body>
<pre>
<code class="cpp">
#include <iostream>

int main(int argc, char *argv[]) {

  /* An annoying "Hello World" example */
  for (auto i = 0; i < 0xFFFF; i++)
    cout << "Hello, World!" << endl;

  char c = '\n';
  unordered_map <string, vector<string> > m;
  m["key"] = "\\\\"; // this is an error

  return -2e3 + 12l;
}
</code>
</pre>

</body>
</html>

Here is how it looks for me on chrome, windows 7:
http://i.imgur.com/prgSm.png

Any help is appreciated.

CoffeeScript does not work at blogger

issue with 7.0 version of highlight.js. CoffeeScript is detected when <code class="coffeescript"> is present, but script does nothing. When class attribute is omitted, CoffeeScript is detected as ruby or vbscript.

When hljs.LANGUAGES contains only coffeescritpt support it doesn't work either, not only on blogger, but at any site where I've tried to put it

UPD: for me seems it does not work at all
PS I didn't try latest version from github, problem is with http://softwaremaniacs.org/soft/highlight/ version 7.0

bug in packed version

Also the same happens in the unpacked version, but only in Internet Explorer. I think it has something to do with reading the "new line" characters

Можно научить highlight переносить код?

Есть два предложения. Оформлю их по отдельности, чтобы проще было закрыть... невозможные :)

Научить highlight (HL) самому переносить код.

В программах я стараюсь держаться в 80 строках. Но, например, для командной строки bash подобное ограничение имеет мало смысла. Смысл появляется, когда скопированный с терминала код пытаешься подсветить... Хотелось бы не тратить время на расставление переносов.

И переносы для C++. Вот не помещается у меня отформатированный HL код на сайте - и всё тут! А шрифт хочется оставить большим.

Я понимаю, что автопереносы - задача простая только на первый взгляд. Но было бы неплохо, да.

Если возьмётесь за переносы, протестируйте тогда и перенос комментариев для C++ (пример 4, ссылка [1]).

[1] Страница с примерами > http://savdalion.blogspot.com/2011/01/test.html

Give priority to the user markup on merging

I have some existing (and rather complicated) HTML markup for the source code to which I'd like to apply highlighting.

If I call hljs.highlightBlock on the container, my markup gets messed up. If I call it on the individual LI's, language detection doesn't work properly (i.e. ten different languages are detected for the same piece of code).

So right now I'm doing something suboptimal:

    var highlightBlocks = $j('.needsHighlight');
    var lines = highlightBlocks.find('li');
    var text = '';

    // Restore original text from HTML
    lines.each(function() {
      text += this.innerHTML + '\n';
    });

    // Detect language
    var language = hljs.highlightAuto(text).language;

    // Init highlighting
    lines.addClass('language-' + language).each(function() {
      hljs.highlightBlock(this);
    });

There are two operations here I'd rather not do: calling highlightAuto and then discarding the results and touching the DOM (lines.addClass to provide the language for the subsequent highlightBlock call).

Разделение многострочных ключевых слов

Добрый день.

Можете подсказать, трудно ли сделать, чтобы многострочные токены (н-р многострочные комментарии /* ,,, */) были в коде не

<span class="comment">/*
....
*/</span>

а

<span class="comment">/*</span>
<span class="comment">....</span>
<span class="comment">*/</span>

Это необходимо для того, чтобы проще обернуть каждую строку в отдельный span

Спасибо.

Double quote escaping doesn't work for ruby.

for example this will work:

hljs.highlight('ruby', 'f "1 2"').value
"<span class="identifier">f</span> <span class="string">"1 2"</span>"

But this doesn't:

hljs.highlight('ruby', 'f "1 \" 2"').value
"f "1 " 2""

Doesn't work for some specific blocks of PHP code

I am using highlight.js for PHP code and it seems to work perfectly 99.9% of the time, but for some snippets it just fails silently and I can't make sense why.

Examples:

On same page works for one block of PHP, but doesn't for another. No errors in console, no markup applied (it does seem to "flash" code block in Firebug on load, so it it seems to see it).

truncated output

I got a pretty annoying surprise:

hljs.highlight("bash", "ssh -NCL 7003:192.6.1.2:443 myhost")

the result of this is:

ssh -NCL <span class="number">7003</span>:<span class="number">192.6</span>:<span class="number">443</span> myhost

It converted the ip address to a floating number and got rid of the remaining characters...
Is there a way to force it to do the right thing ?( for me the library should never discard any output, in the worst case maybe raise an error but not do this )

CoffeeScript regexpes aren't supported

Or rather, the simple variation of it. This makes following code find /// supported /// but not /not supported/

RegExpes = [
  /not supported/
  /// supported ///
]

In CoffeeScript grammar, those RegExpes are defined as

REGEX = /// ^
  (/ (?! [\s=] )   # disallow leading whitespace or equals signs
  [^ [ / \n \\ ]*  # every other thing
  (?:
    (?: \\[\s\S]   # anything escaped
      | \[         # character class
           [^ \] \n \\ ]*
           (?: \\[\s\S] [^ \] \n \\ ]* )*
         ]
    ) [^ [ / \n \\ ]*
  )*
  /) ([imgy]{0,4}) (?!\w)
///

The following tokens cannot precede RegExp unless they have space after them: ), }, identifiers, this.

Also, RegExp cannot be preceded at all after numbers, RegExpes, true, false, null, undefined, ++, -- and ] (so a[0] /a/ is not RegExp).

<!doctype html5> in tests

In tests, you can notice this.

<!doctype html5>

Official HTML5 doctype is <!doctype html>, not <!doctype html5>. It's minor detail, but it somewhat annoys me.

bug in packed version

Hi

I just want to let u know that the packed distribution from your site adds a new line after each row, unless you add the true argument like hljs.highlightBlock(e, null, true);

This doesn't happen in the unpacked version from github...

thank you for the best syntax-highlighting script out there:)

Perl 5 regexpes only support / as delimiter.

Works:

m/a/;

Doesn't work (all examples on this list are valid Perl 5 regexpes):

m|a|;
m #a#;
m xax; # x as delimiter, sort of hacky, forbidden in Perl 6... but that's Perl 5...
m?a?;
m'a';
m[a];
m{a};
m(a);
m<a>;
m<a<b>c>;
s{a}{b};
s <a> (b);
s xaxbx;

Отключить угадывание когда язык не указан явно

Хотелось бы иметь возможность отключить угадывание когда язык не указан явно (без указания даже no-highlight).

Например: есть тег <pre><code>...</code></pre> содержимое которого подсвечивать не надо, и есть тег <pre><code class="js">...</code></pre> который нужно подсвечивать.

Not working at all

I have a sample page here.

My HTML is

<pre><code>
@requires_authorization
def somefunc(param1, param2):
    r'''A docstring'''
    if param1 > param2: # interesting
        print 'Gre\'ater'
        print ''
    return (param2 - param1 + 1) or None

class SomeClass:
    pass
</code></pre>

(The block of demo python code on your site)

And the javascript:

$('pre code').each(function() {
    hljs.highlightBlock(this, '    ');
});

I include highlight.js, styles/default.css, and python.js, but it doesn't work at all.

What's going wrong?

Perl 5 regexpes overreact

Following code will see regexp / $b ... $c /, when it's obviously divide-by operator. Only second line is needed, but I needed to end regexp, so it would be visible (otherwise, everything would be just black. This doesn't happen in JavaScript and other languages with similar regexp syntax (like Ruby).

my ($a, $b, $c, $d);
my $variable = $a / $b;
my $othervar = $c / $d;

Direct usage of non-built JS code

I am using version v6 simply by including as github repo as submodule and loading scripts from it. It hadn't quite occurred to me to ask if using it that way (as opposed to built script) is supported since it's just worked.

But it seems to have stopped working in v7 with errors about functions missing names in browser console.

Is such direct way no longer (wasn't ever) supported? If so what are my options (if any) to build working script in PHP environment?

Add support for copy source

It would be nice to have a copy source to clipboard button. I tried doing it with clippy and ZeroClipboard, but was unable to get it working. I think it would be a great feature to add.

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.