Самая любимая функция StackOverflow для меня - это то, что он может автоматически обнаруживать код в посте и устанавливать соответствующий цвет для кода.
Интересно, как выставлен цвет. Когда я использую Ctrl + F5 на странице, код сначала выглядит черным, а затем становится цветным. Это делается с помощью jQuery?



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


От Подкаст Stack Overflow # 11:
Atwood: It is. Okay, so that comes from, that's a project some Google engineer, I think, wrote it--it's called "Prettify." And it's a little interesting in that it actually infers all the syntax highlighting, which sounds like it couldn't possibly work--it sounds actually insane, if you think about it. But it actually kind of works. Now, he only supports it for, there's certain dialects that just don't really work well with it, but for all the dialects that sort of, you'd find on Google. I think it comes from Google's Google Code. It's the actual code, it's the actual JavaScript which is on Google Code that highlights that the code that comes back when you're hosting projects on Google Code. And you, and you, um, 'cause I think they use Subversion so you can actually click through...
Spolsky: How do they know, how do they even know what language you're writing in? And therefore, what a comment is and...
Atwood: I don't know. It's crazy. It's prettify.js, so if anyone's interested in looking at this, just do a web search for "prettify.js," and you'll find it.
А вот где вы можете найти prettify.js: http://code.google.com/p/google-code-prettify/
В ответ на..
Spolsky: How do they know, how do they even know what language you're writing in?
Это не так. Маркер очень тупой, но ему это удается, потому что большинство языков программирования очень похожи. Почти все использует синтаксис, достаточно близкий к ..
AFunction("a string")
1 + 4 # <- numbers
# /\ a comment
// also a comment..
..это большинство вещей выделяется должным образом. Вышеупомянутый не является языком программирования на самом деле, но он отлично подчеркивает.
Есть исключения, например, он иногда может рассматривать / как начало регулярного выражения (как в Perl / Ruby). когда это не так:
this [^\s>/] # is highlighted as a regex, not a comment
... но они довольно редки, и он хорошо справляется с большинством вещей, например ...
/*
this is a multi-line comment
"with a string" =~ /and a regex/
*/
but =~ /this is a regex with a [/*] multiline comment
markers in it! */
По словам dbr, это фиктивная подсветка наиболее распространенных конструкций языков. Что плохо работает с некоторыми экзотическими синтаксисами. Интересно, можем ли мы делать разделы кода без выделения, BTW.
For id = 1 To 10 Do
CallSomething() // It likes CamelCase identifiers...
End
for id = 1 to 10 do # Also highlight some common keywords...
if id % 2 then call_something(); x++; end
end
'str' "str" 12 + 15.6 * -7e+9 /* Some common constant forms */
=/regex/ ~/regex/ +/RE/ !/regexpr/ but not /[^regex]/ (no operator before it)
(* Some comment conventions are overlooked... *)
-- Lua's (and some other languages')
; So are these comments...
' And these (Basic)
Работает достаточно хорошо, чтобы общий код создавал иллюзию, и лучше, чем загружать десятки синтаксисов в браузере.
Разделы кода без выделения? Конечно. Просто оберните обычные блоки текста без отступов в теги PRE, как обычный HTML.