highlightjs / highlight.js Goto Github PK
View Code? Open in Web Editor NEWJavaScript syntax highlighter with language auto-detection and zero dependencies.
Home Page: https://highlightjs.org/
License: BSD 3-Clause "New" or "Revised" License
JavaScript syntax highlighter with language auto-detection and zero dependencies.
Home Page: https://highlightjs.org/
License: BSD 3-Clause "New" or "Revised" License
Any plans to add Sass and SCSS code highlighting? You'd be my hero :)
Following nginx configuration file isn't highlighted.
server {
# This = causes problems
rewrite (.*) /index.php?page=$1 break;
}
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
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.
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.
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"
Need to get rid of nodeValue
everywhere in favor of value
.
On the last line:
304393/151570 0.963 rrule.py:102(_iter_cached)
304393/1
is highlighted as a single number
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!
Is there any option to show line numbers?
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.
(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", '\\');
}
/**
* Выполнить метод ["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;
}
}
}
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;
}
Работаю с кодом C++ в Visual Studio. А эта штука совершенно наплевательски относится к тому, чем заполнены отступы: прекрасно всё смотрится в её родном редакторе, но при копировании кода на сайт получаем отступы, разбавленные и пробелами, и табуляцией. В программе 1 табуляция, обычно, равна 4 пробелам. Пусть бы highlight тоже знал об этом.
Пример кода > http://savdalion.blogspot.com/2011/01/test.html#4
<?php
// highlights correctly
?>
<?
// does not highlight correctly
?>
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)
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
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;
}
Method that matches language keyword is highlighted as keyword as well (as I see for Perl).
Thus, e.g. there is built-in function (keyword) "sort" and if one prints "object->sort", so in this case "sort" as method of the class will be treated by highlight.js as keyword. Screen shot is here:
http://www.flickr.com/photos/yaskevich/5870302481/
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.
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
but highlight.pack.js works - are they different?
sorry, I closed the issue by mistake :)
I'm new to this github thingie.
Here's my reply:
https://github.com/isagalaev/highlight.js/issues/closed#issue/11
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 (HL) самому переносить код.
В программах я стараюсь держаться в 80 строках. Но, например, для командной строки bash подобное ограничение имеет мало смысла. Смысл появляется, когда скопированный с терминала код пытаешься подсветить... Хотелось бы не тратить время на расставление переносов.
И переносы для C++. Вот не помещается у меня отформатированный HL код на сайте - и всё тут! А шрифт хочется оставить большим.
Я понимаю, что автопереносы - задача простая только на первый взгляд. Но было бы неплохо, да.
Если возьмётесь за переносы, протестируйте тогда и перенос комментариев для C++ (пример 4, ссылка [1]).
[1] Страница с примерами > http://savdalion.blogspot.com/2011/01/test.html
var notreturn;
return
is highlighted. I'm thinking that regexp before keyword detection rule is a problem.
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
Спасибо.
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""
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).
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 )
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).
For HTML
<link href='http://yandex.st/highlightjs/6.0/styles/sunburst.min.css' rel='stylesheet'/> <script src='http://yandex.st/highlightjs/6.0/highlight.min.js' type='text/javascript'></script>
we see different colors of tags (at the least) on highlight of XML code [1]
meaning b'...'
and friends
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.
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:)
Example:
@page:right {
margin: 1cm 2cm 1.3cm 4cm;
}
Highlight.js rocks. It's the best of its kind!
Could you add an AMD module definition? This would make Highlight.js compatible with all AMD loaders out there.
Here is some info: http://requirejs.org/docs/whyamd.html#dolib
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> который нужно подсвечивать.
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?
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;
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?
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.
doesn't display the syntax highlighting
Highlighting crashes if the variable/method name contain '
(quote symbol).
Example:
length' xs = sum [1 | _ <- xs]
https://github.com/isagalaev/highlight.js/blob/master/src/languages/ruby.js#L201
This causes issues in Internet Explorer. That comma should be removed.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.