Publishing to gh-pages

This commit is contained in:
Martin/Geno 2018-12-07 15:48:05 +01:00
parent b45e37c5f9
commit c944749dd4
No known key found for this signature in database
GPG Key ID: 9D7D3C6BFF600C6A
984 changed files with 76724 additions and 0 deletions

76
categories/index.html Normal file
View File

@ -0,0 +1,76 @@
<!doctype html><html lang="en">
<head>
<meta charset="utf-8">
<title>Categories</title>
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="stylesheet" href="https://ccchb.github.io/presentations/reveal-js/css/reveal.css">
<link rel="stylesheet" href="/presentations/css/main.css" id="theme">
<link rel="stylesheet" href="https://ccchb.github.io/presentations/highlight-js/src/styles/qtcreator_dark.css">
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'https:\/\/ccchb.github.io\/presentations\/reveal-js/css/print/pdf.css' : 'https:\/\/ccchb.github.io\/presentations\/reveal-js/css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
</head>
<body>
<div class="reveal">
<div class="slides">
</div>
</div>
<script type="application/json" id="reveal-hugo-site-params">{"custom_theme":"css/main.css","highlight_theme":"qtcreator_dark","history":true,"margin":0.2,"transition":"slide","transition_speed":"fast"}</script>
<script type="application/json" id="reveal-hugo-page-params">null</script>
<script type="text/javascript"> window.revealHugoDependencies = { dependencies: [ { src: 'https:\/\/ccchb.github.io\/presentations\/reveal-js/lib/js/classList.js', condition: function() { return !document.body.classList; } },
{ src: 'https:\/\/ccchb.github.io\/presentations\/reveal-js/plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'https:\/\/ccchb.github.io\/presentations\/reveal-js/plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'https:\/\/ccchb.github.io\/presentations\/reveal-js/plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
{ src: 'https:\/\/ccchb.github.io\/presentations\/reveal-js/plugin/zoom-js/zoom.js', async: true },
{ src: '\/presentations\/reveal-js\/plugin\/notes\/notes.js', async: true }
]};
</script>
<script src="https://ccchb.github.io/presentations/reveal-js/lib/js/head.min.js"></script>
<script src="https://ccchb.github.io/presentations/reveal-js/js/reveal.js"></script>
<script type="text/javascript">
function camelize(map) {
if (map) {
Object.keys(map).forEach(function(k) {
newK = k.replace(/(\_\w)/g, function(m) { return m[1].toUpperCase() });
if (newK != k) {
map[newK] = map[k];
delete map[k];
}
});
}
return map;
}
var revealHugoDefaults = { center: true, controls: true, history: true, progress: true, transition: "slide" };
var revealHugoSiteParams = JSON.parse(document.getElementById('reveal-hugo-site-params').innerHTML);
var revealHugoPageParams = JSON.parse(document.getElementById('reveal-hugo-page-params').innerHTML);
var options = Object.assign({},
camelize(revealHugoDefaults),
camelize(revealHugoSiteParams),
camelize(revealHugoPageParams),
revealHugoDependencies);
Reveal.initialize(options);
</script>
</body>
</html>

1
css/35c3.min.css vendored Normal file

File diff suppressed because one or more lines are too long

BIN
css/fonts/35c3-black.woff Normal file

Binary file not shown.

BIN
css/fonts/35c3-black.woff2 Normal file

Binary file not shown.

BIN
css/fonts/35c3-light.woff Normal file

Binary file not shown.

BIN
css/fonts/35c3-light.woff2 Normal file

Binary file not shown.

11
css/main.css Normal file
View File

@ -0,0 +1,11 @@
@import "reveal.css";
.reveal .slides {
text-align: left;
}
body {
background-image: url(https://ccchb.de/logo/CCCHB-logo_256x256_bw.png);
background-position: left 20px top 10px;
background-repeat: no-repeat;
background-size: 8% auto;
}

293
css/reveal.css Normal file
View File

@ -0,0 +1,293 @@
@import "35c3.min.css";
body {
color:#fff;
background-color:#000;
font-size: 32px;
font-weight: normal;
padding: 5px;
}
.reveal {
padding: 5px;
border: 8px solid;
border-image: linear-gradient(to right, #00a356, #0084b0) 1;
}
.reveal .controls {
color: #00a356;
right: 50px;
bottom: 50px;
}
::selection {
color: #fff;
background: #ffc0d5;
text-shadow: none;
}
::-moz-selection {
color: #fff;
background: #ffc0d5;
text-shadow: none;
}
.reveal .slides > section,
.reveal .slides > section > section {
line-height: 1.3;
font-weight: inherit;
}
/*********************************************
* HEADERS
*********************************************/
.reveal h1,
.reveal h2,
.reveal h3,
.reveal h4,
.reveal h5,
.reveal h6 {
margin: 0 0 20px 0;
font-weight: 700;
line-height: 1.2;
letter-spacing: normal;
text-transform: uppercase;
text-shadow: none;
word-wrap: break-word;
}
.reveal h1 {
font-size: 2.6em;
}
.reveal h2 {
font-size: 2.2em;
}
.reveal h3 {
font-size: 1.7em;
}
.reveal h4 {
font-size: 1.4em;
}
.reveal h1 {
text-shadow: none;
}
/*********************************************
* OTHER
*********************************************/
.reveal p {
margin: 20px 0;
line-height: 1.3;
}
/* Ensure certain elements are never larger than the slide itself */
.reveal img,
.reveal video,
.reveal iframe {
max-width: 95%;
max-height: 95%;
}
.reveal strong,
.reveal b {
font-weight: bold;
}
.reveal em {
font-style: italic;
}
.reveal ol,
.reveal dl,
.reveal ul {
display: inline-block;
text-align: left;
margin: 0 0 0 1em;
}
.reveal ol {
list-style-type: decimal;
}
.reveal ul {
list-style-type: disc;
}
.reveal ul ul {
list-style-type: square;
}
.reveal ul ul ul {
list-style-type: circle;
}
.reveal ul ul,
.reveal ul ol,
.reveal ol ol,
.reveal ol ul {
display: block;
margin-left: 40px;
}
.reveal dt {
font-weight: bold;
}
.reveal dd {
margin-left: 40px;
}
.reveal blockquote {
display: block;
position: relative;
width: 70%;
margin: 20px auto;
padding: 5px;
font-style: italic;
background: rgba(255, 255, 255, 0.05);
box-shadow: 0px 0px 2px rgba(0, 0, 0, 0.2);
}
.reveal blockquote p:first-child,
.reveal blockquote p:last-child {
display: inline-block;
}
.reveal q {
font-style: italic;
}
.reveal pre {
display: block;
position: relative;
width: 90%;
margin: 20px auto;
text-align: left;
font-size: 0.55em;
font-family: monospace;
line-height: 1.2em;
word-wrap: break-word;
box-shadow: 0px 0px 6px rgba(0, 0, 0, 0.3);
border: 2px solid transparent;
border-image: linear-gradient(to right, #00a356, #0084b0) 1 round;
}
.reveal code {
font-family: monospace;
text-transform: none;
}
.reveal pre code {
display: block;
padding: 5px;
overflow: auto;
max-height: 400px;
word-wrap: normal;
}
.reveal table {
margin: auto;
border-collapse: collapse;
border-spacing: 0;
}
.reveal table th {
font-weight: bold;
}
.reveal table th,
.reveal table td {
text-align: left;
padding: 0.2em 0.5em 0.2em 0.5em;
border-bottom: 1px solid;
}
.reveal table th[align="center"],
.reveal table td[align="center"] {
text-align: center;
}
.reveal table th[align="right"],
.reveal table td[align="right"] {
text-align: right;
}
.reveal table tbody tr:last-child th,
.reveal table tbody tr:last-child td {
border-bottom: none;
}
.reveal sup {
vertical-align: super;
}
.reveal sub {
vertical-align: sub;
}
.reveal small {
display: inline-block;
font-size: 0.6em;
line-height: 1.2em;
vertical-align: top;
}
.reveal small * {
vertical-align: top;
}
/*********************************************
* LINKS
*********************************************/
.reveal .roll span:after {
color: #fff;
background: #f30053;
}
/*********************************************
* IMAGES
*********************************************/
.reveal section img {
margin: 15px 0px;
background: rgba(255, 255, 255, 0.12);
border: 4px solid #363636;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.15);
}
.reveal section img.plain {
border: 0;
box-shadow: none;
}
.reveal a img {
-webkit-transition: all .15s linear;
-moz-transition: all .15s linear;
transition: all .15s linear;
}
.reveal a:hover img {
background: rgba(255, 255, 255, 0.2);
border-color: #00a356;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.55);
}
/*********************************************
* PROGRESS BAR
*********************************************/
.reveal .progress span {
-webkit-transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985);
-moz-transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985);
transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985);
}
.reveal .progress {
margin: 2px;
z-index: 1000;
background: rgba(0, 0, 0, 0.2);
color: #00a356;
}

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="200" width="185">
<circle cx="62" cy="50" r="15" fill="white" />
<circle cx="125" cy="50" r="15" fill="white" />
<circle cx="25" cy="100" r="15" fill="white" />
<circle cx="62" cy="150" r="15" fill="white" />
<circle cx="125" cy="150" r="15" fill="white" />
<circle cx="162" cy="100" r="15" fill="white" />
<rect x="80" y="85" width="30" height="30" fill="white" />
<line x1="62" y1="50" x2="95" y2="100" stroke="white"/>
<line x1="125" y1="50" x2="92" y2="100" stroke="white"/>
<line x1="25" y1="100" x2="95" y2="100" stroke="white"/>
<line x1="62" y1="150" x2="95" y2="100" stroke="white"/>
<line x1="125" y1="150" x2="95" y2="100" stroke="white"/>
<line x1="162" y1="100" x2="95" y2="100" stroke="white"/>
</svg>

After

Width:  |  Height:  |  Size: 910 B

View File

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="utf-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="200" width="190">
<circle cx="62" cy="50" r="15" fill="white" />
<circle cx="20" cy="80" r="15" fill="white" />
<line x1="62" y1="50" x2="70" y2="100" stroke="white"/>
<line x1="20" y1="80" x2="70" y2="100" stroke="white"/>
<rect x="55" y="85" width="30" height="30" fill="white" />
<circle cx="125" cy="40" r="15" fill="white" />
<circle cx="175" cy="60" r="15" fill="white" />
<circle cx="175" cy="135" r="15" fill="white" />
<line x1="125" y1="40" x2="140" y2="100" stroke="white"/>
<line x1="175" y1="60" x2="140" y2="100" stroke="white"/>
<line x1="175" y1="135" x2="140" y2="100" stroke="white"/>
<rect x="125" y="85" width="30" height="30" fill="white" />
<circle cx="65" cy="185" r="15" fill="white" />
<circle cx="130" cy="185" r="15" fill="white" />
<line x1="65" y1="185" x2="100" y2="150" stroke="white"/>
<line x1="130" y1="185" x2="100" y2="150" stroke="white"/>
<rect x="85" y="135" width="30" height="30" fill="white" />
<line x1="70" y1="100" x2="140" y2="100" stroke="white"/>
<line x1="70" y1="100" x2="100" y2="150" stroke="white"/>
<line x1="100" y1="150" x2="140" y2="100" stroke="white"/>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="200" width="185">
<circle cx="62" cy="50" r="15" fill="white" />
<circle cx="125" cy="50" r="15" fill="white" />
<circle cx="25" cy="100" r="15" fill="white" />
<circle cx="62" cy="150" r="15" fill="white" />
<circle cx="125" cy="150" r="15" fill="white" />
<circle cx="162" cy="100" r="15" fill="white" />
<line x1="62" y1="50" x2="125" y2="50" stroke="white"/>
<line x1="62" y1="50" x2="25" y2="100" stroke="white"/>
<line x1="62" y1="50" x2="62" y2="150" stroke="white"/>
<line x1="62" y1="50" x2="125" y2="150" stroke="white"/>
<line x1="62" y1="50" x2="162" y2="100" stroke="white"/>
<line x1="125" y1="50" x2="162" y2="100" stroke="white"/>
<line x1="62" y1="150" x2="162" y2="100" stroke="white"/>
<line x1="25" y1="100" x2="162" y2="100" stroke="white"/>
<line x1="125" y1="150" x2="162" y2="100" stroke="white"/>
<line x1="62" y1="150" x2="125" y2="150" stroke="white"/>
<line x1="62" y1="150" x2="25" y2="100" stroke="white"/>
<line x1="62" y1="150" x2="125" y2="50" stroke="white"/>
<line x1="25" y1="100" x2="125" y2="50" stroke="white"/>
<line x1="25" y1="100" x2="125" y2="150" stroke="white"/>
<line x1="125" y1="50" x2="125" y2="150" stroke="white"/>
</svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

@ -0,0 +1,562 @@
<!doctype html><html lang="en">
<head>
<meta charset="utf-8">
<title>Dezentrale Messenger</title>
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="stylesheet" href="https://ccchb.github.io/presentations/reveal-js/css/reveal.css">
<link rel="stylesheet" href="/presentations/css/main.css" id="theme">
<link rel="stylesheet" href="https://ccchb.github.io/presentations/highlight-js/src/styles/qtcreator_dark.css">
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'https:\/\/ccchb.github.io\/presentations\/reveal-js/css/print/pdf.css' : 'https:\/\/ccchb.github.io\/presentations\/reveal-js/css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
</head>
<body>
<div class="reveal">
<div class="slides">
<section>
<p><h2 style="white-space: nowrap;">Dezentrale Messenger</h2>
<br/>
<h4 style="white-space: nowrap;">The very last word in instant messaging</h4>
(Motto vom XMPP-Client Converations)</p>
<p><span class="text-reboot">genofire - Chaos Computer Club Bremen e.V.</span></p>
</section><section>
<h2 id="agenda">Agenda</h2>
<ul>
<li>Dezentralität</li>
<li>XMPP - Der Standard</li>
<li>Software (Client und Server)</li>
<li>Ist der Hoster gut</li>
<li>Verschlüsselung</li>
<li>Ausblick</li>
<li>Alternativen</li>
</ul>
</section><section>
<h2 id="dezentralität">Dezentralität</h2>
<ul>
<li>vs. <strong>Zentralität</strong></li>
</ul>
<p>Leider von den meisten Messenger verwendet</p>
<p><img src="./img/central.svg" style="border: none; background:transparent;" /></p>
</section><section>
<h2 id="dezentralität-1">Dezentralität</h2>
<ul>
<li><strong>Federation</strong></li>
</ul>
<p>Kommunikation über verschieden unabhängige zentrale Komponenten</p>
<p><img src="./img/federation.svg" style="border: none; background:transparent;" /></p>
<aside class="notes"><p><strong>Federation</strong>
- E-Mail (ISP: benutzer@hoster.de)
- Telefonnummern (Addr: hat oftmals die ersten Ziffern für sich reserviert)</p>
</aside>
</section><section>
<h2 id="dezentralität-2">Dezentralität</h2>
<ul>
<li><strong>Peer-to-Peer</strong></li>
</ul>
<p>Geräte tauschen direkt miteinander Nachrichten aus (ohne eine zentrale Componente)</p>
<p><img src="./img/p2p.svg" style="border: none; background:transparent;" /></p>
<aside class="notes"><p><strong>P2P</strong>
- Postkasten, jeder kann zum Empfänger gehen und selbst etwas in den Kasten werfen.
(wenn es keine Post gibt)</p>
</aside>
</section><section>
<h2 id="dezentralität-3">Dezentralität</h2>
<h4 id="warum-notwendig">Warum notwendig?</h4>
<ul>
<li>Eröffnet ein Wettbewerb</li>
<li>kleine und viele Angriffsziele
<ul>
<li>vor Kriminelle</li>
<li>vor Regierungen</li>
<li>alle Überwachen</li>
<li>blockieren / sperren (Zensur)</li>
</ul></li>
<li>Verringert Missbrauch durch Vertrauen</li>
</ul>
<aside class="notes"><ul>
<li><em>Eröffnet einen Wettbewerb:</em> damit fortschritt
(Gewinne gehen zum größten Teile in die USA)
<ul>
<li>Entscheidungen: z.B. nur noch auf Englisch, Mark Zuckerberg darf Nachrichten löschen</li>
</ul></li>
<li><em>Angriffsziele:</em>
<ul>
<li>Hacker können nicht alle Server kompromentieren</li>
<li>Regierungen können nicht</li>
<li>den Zugang zu allen Servern verlangen (NSA - Snowden)</li>
<li>alle Server blockieren (Telegram - Russland)</li>
</ul></li>
<li><em>Verringert Missbrauch durch Vertrauen</em>
<ul>
<li><strong>Auswirkung:</strong> nicht alle Daten können <strong>geklaut</strong> oder <strong>analysiert</strong> werden</li>
<li>Analysiert zur Manipulation (Werbung oder politisch, siehe Cambridge Analytica)</li>
<li><strong>Bei Missbrauch</strong> leichterer Wechsel</li>
</ul></li>
</ul>
</aside>
</section><section>
<h2 id="dezentralität-4">Dezentralität</h2>
<h4 id="nachteile">Nachteile</h4>
<ul>
<li>Komplexität steigt</li>
<li>Gewollte Verringerung an Marktanteil</li>
<li>Kann auch von kriminellen Elementen genutzt werden</li>
<li>Nutzer müssen ggf. sich Ihre Adresse und Passwort merken</li>
</ul>
<aside class="notes"><ul>
<li><em>Komplexität steigt:</em> Da nicht nur Clients, sondern auch Server untereinander sicher (Ausfall, vertrauensvoll) kommunizieren müssen.</li>
<li><em>kriminellen Elementen:</em> wie bei jeder Technologie kann diese auch von Bösen genutzt werden.</li>
<li><em>&hellip; sich merken:</em> allerdings müssen Sie dies auch für Ihre E-Mail-Adresse, was noch Standard im Internet ist.</li>
</ul>
</aside>
</section><section>
<h3 id="extensible-messaging-and-presence-protocol-xmpp">Extensible Messaging and Presence Protocol (XMPP)</h3>
<ul>
<li>Existiert seit 1999 (unter den Namen Jabber)</li>
<li><p>IETF Standard seit 2002</p></li>
<li><p>Google Talk 2005 - 2013 (entwickelte Jingle)</p></li>
<li><p>Facebook 2010 - 2014</p></li>
<li><p>WhatsApp nutzt es intern</p></li>
</ul>
<aside class="notes"><ul>
<li>Jingle:
<ul>
<li>Aushandlung von Datenverbindung (angelehnt an SIP)</li>
<li>für: Datenaustausch, Video/Voice-Chat, &hellip;</li>
</ul></li>
</ul>
</aside>
</section><section>
<h2 id="xmpp">XMPP</h2>
<h4 id="adressierung">Adressierung</h4>
<p>JID (Jabber ID) genannt:</p>
<pre><code>node@domain/ressource
</code></pre>
<p>URI-Format: (falls MUC mit <code>?join</code> am Ende)</p>
<pre><code>xmpp:node@domain?join
</code></pre>
<aside class="notes"><ul>
<li>MUC (Multi User Chat): Gruppenchat</li>
</ul>
<p><strong>Als User</strong></p>
<ul>
<li>benutzer@server/gerät</li>
</ul>
<p><strong>In MUC</strong></p>
<ul>
<li>chatraum@muc-server/nickame</li>
</ul>
<p><strong>Transport</strong>
- ganz unterschiedlich</p>
</aside>
</section><section>
<h2 id="xmpp-1">XMPP</h2>
<p><strong>Message</strong></p>
<pre><code class="language-xml">&lt;message from=&quot;geno@fireorbit.de&quot;
to=&quot;#ccchb@irc.hackint.org&quot; type=&quot;groupchat&quot;&gt;
Hello World
&lt;/message&gt;
</code></pre>
<p>Types:</p>
<ul>
<li>chat</li>
<li>groupchat</li>
<li>headline</li>
<li>normal</li>
<li>error</li>
</ul>
</section><section>
<h2 id="xmpp-2">XMPP</h2>
<p><strong>Present</strong>: Aktuelle Live Informationen</p>
<pre><code class="language-xml">&lt;present to=&quot;#ccchb@irc.hackint.org&quot; type=&quot;subscribe&quot;&gt;
&lt;/present&gt;
</code></pre>
<p>Types:</p>
<ul>
<li>error</li>
<li>probe</li>
<li>subscribe(d)</li>
<li>unavailable</li>
<li>unsubscribe(d)</li>
</ul>
</section><section>
<h2 id="xmpp-3">XMPP</h2>
<p><strong>IQ</strong> (Instant Query): Abfragen mit Rückantworten</p>
<pre><code class="language-xml">&lt;iq to=&quot;irc.hackint.org&quot; type=&quot;get&quot;&gt;
&lt;ping xmlns='urn:xmpp:ping'/&gt;
&lt;/iq&gt;
</code></pre>
<p>Types:</p>
<ul>
<li>get</li>
<li>set</li>
<li>result</li>
<li>error</li>
</ul>
<aside class="notes"><ul>
<li>Die Inhalte, die in diesen XML-Elementen drin sind, werden im RFC nicht vorgegeben und kann für viele Funktionen genutzt werden.</li>
</ul>
</aside>
</section><section>
<h2 id="software-small-clients-small">Software <small>Clients</small></h2>
<h4 id="empfehlungen">Empfehlungen:</h4>
<ul>
<li>Conversations (Android)
<ul>
<li>Pix-Art Messenger</li>
</ul></li>
<li>ChatSecure (iPhone)</li>
<li>Gajim (Desktop)</li>
<li>ConverseJS (WebClient)</li>
<li>Viele mehr
<ul>
<li>mit <a href="https://omemo.top">OMEMO</a></li>
<li><a href="https://xmpp.org/software/clients.html">alle</a></li>
</ul></li>
</ul>
</section><section>
<h2 id="software-small-clients-small-1">Software <small>Clients</small></h2>
<p>Bombus - Client in J2ME für normale Telefone
<center>
<img width="50%" src="img/j2me-bombus.jpg" alt="Wikipedia - Article Java"/>
</center></p>
</section><section>
<h2 id="software-small-server-small">Software <small>Server</small></h2>
<ul>
<li><p><strong>prosody</strong> in lua</p>
<ul>
<li>leicht erweiterbar</li>
<li>riesige Sammlung an erweiterbaren Modulen (die man nutzen muss)</li>
</ul></li>
<li><p><strong>ejabberd</strong> (Fork: mongooseIM) in erlang</p>
<ul>
<li>besitzt alle nötigen Funktionen von Haus aus</li>
<li>sehr gut gewartet</li>
</ul></li>
<li><p><strong>OpenFire</strong> in Java</p></li>
</ul>
</section><section>
<h2 id="ist-der-hoster-gut">Ist der Hoster gut</h2>
<p>Tools zum Testen des Servers (Auswahl an Servern)</p>
<ul>
<li><a href="https://compliance.conversations.im/">Compliance</a> (<a href="https://compliance.conversations.im/api/compliant_servers/">support Alles</a> / API)</li>
<li><a href="https://status.conversations.im/historical/">Status</a> für S2S + Uptime</li>
</ul>
<p>XEPs:</p>
<ul>
<li>PEP / PubSub</li>
<li>MAM (für MUC)</li>
<li>HTTP-Upload</li>
<li>DNS-SRV for TLS (HTTPS)</li>
</ul>
<aside class="notes"><ul>
<li>Personal Eventing Protocol: Geolocation, Mood, Activity, Tune</li>
<li>Message Archive Management:
<ul>
<li>Vorteil gegenüber: Threema und WhatsApp (mit OMEMO auch gegenüber Telegram)</li>
<li>OMEMO: Neue Geräte können alte Nachrichten nicht entschlüsseln</li>
</ul></li>
<li>HTTP-Upload: Offline und in MUC Datenaustausch</li>
<li>&ldquo;umgeht&rdquo; Firewalls</li>
</ul>
</aside>
</section><section>
<h2 id="xmpp-4">XMPP</h2>
<h3 id="verschlüsselung">Verschlüsselung</h3>
<ul>
<li>Off-The-Record</li>
<li>OpenPGP</li>
<li>OX</li>
<li>OMEMO</li>
</ul>
<p>Detailert: <a href="https://conversations.im/omemo">here</a></p>
<aside class="notes"><ul>
<li>Neben TLS (SSL)</li>
</ul>
</aside>
</section><section>
<h2 id="xmpp-small-verschlüsselung-small">XMPP <small>Verschlüsselung</small></h2>
<ul>
<li>Geräte erstellt <strong>asynchrones</strong> Schlüsselpaar
<ul>
<li>öffentlichen Schlüssel wird per PubSub auf dem Server hinterlegt</li>
</ul></li>
<li>Kontakte werden durch PEP / PubSub über neuen Schlüssel informiert
<ul>
<li>Dieser muss diesen öffentlichen Schlüssel laden</li>
</ul></li>
</ul>
<aside class="notes"><ul>
<li>synchrone: Entspricht einem Passwort, was allen Gesprächsteilnehmern bekannt ist.
<ul>
<li>asynchrone: mathematisches Verfahren mit Schlüsselpaaren (öffentlicher und privater Schlüssel)</li>
</ul></li>
<li>Kontakte = Roster</li>
<li><p>den <strong>neuen oder weiteren</strong> öffentlichen Schlüssel</p></li>
<li><p>Signiert und verschlüsselt</p></li>
<li><p>zurückziehen des Schlüssels</p></li>
</ul>
</aside>
</section><section>
<p><center>
<h1>Demo</h1>
<a href="https://media.kuketz.de/blog/artikel/2016/conversations/Anleitung_Conversations_V1.1_CC-BY-SA.pdf">Anleitung</a>
</center></p>
</section><section>
<h2 id="ausblick">Ausblick</h2>
<ul>
<li>Transports
<ul>
<li>Biboumi: IRC</li>
<li>Spectrum2: e.g AIM, ICQ, MSN, Yahoo, Telegram, Twitter, &ldquo;WhatsApp&rdquo;</li>
</ul></li>
<li>PubSub
<ul>
<li>Blogging / Posting (siehe Movim)</li>
</ul></li>
<li>Commands
<ul>
<li>Internet of Things</li>
</ul></li>
</ul>
<p><a href="https://xmpp.org/extensions/">XEP-Liste</a> letzter Eintrag: XEP-0410: MUC Self-Ping (Schrödinger&rsquo;s Chat)</p>
<aside class="notes"><ul>
<li>Transport WhatsApp Warnung, vor Protokolländerungen und Sperrungen</li>
</ul>
</aside>
</section><section>
<h2 id="alternativen-zu-xmpp">Alternativen zu XMPP</h2>
<h4 id="peer-to-peer">Peer-to-Peer</h4>
<ul>
<li>Nutzen das Tor-Netzwerk
<ul>
<li><strong>Tox</strong></li>
<li><strong>Briar</strong>
<ul>
<li>kann auch Local per Wifi und Bluetooth genutzt werden</li>
</ul></li>
<li>&hellip; (viele mehr)</li>
</ul></li>
<li><p>libp2p</p></li>
<li><p>(mir sonst keine Weiteren bekannt &hellip;)</p></li>
</ul>
</section><section>
<h2 id="alternativen-zu-xmpp-1">Alternativen zu XMPP</h2>
<h4 id="federation">Federation</h4>
<ul>
<li><strong>Matrix</strong> (Riot):
<ul>
<li>Änderungsvorschläge am Protokoll werden durch das Unternehmen entschieden</li>
</ul></li>
<li>(mir sonst keine Weiteren bekannt &hellip;)</li>
</ul>
</section><section>
<p><center>
<h1>Ende</h1>
<a href="https://www.ccc.de/de/hackerethik"><h4>Hackerethik</h4></a></p>
<p><strong>3. Mißtraue Autoritäten fördere Dezentralisierung.</strong>
</center></p>
</section>
</div>
</div>
<script type="application/json" id="reveal-hugo-site-params">{"custom_theme":"css/main.css","highlight_theme":"qtcreator_dark","history":true,"margin":0.2,"transition":"slide","transition_speed":"fast"}</script>
<script type="application/json" id="reveal-hugo-page-params">null</script>
<script type="text/javascript"> window.revealHugoDependencies = { dependencies: [ { src: 'https:\/\/ccchb.github.io\/presentations\/reveal-js/lib/js/classList.js', condition: function() { return !document.body.classList; } },
{ src: 'https:\/\/ccchb.github.io\/presentations\/reveal-js/plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'https:\/\/ccchb.github.io\/presentations\/reveal-js/plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'https:\/\/ccchb.github.io\/presentations\/reveal-js/plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
{ src: 'https:\/\/ccchb.github.io\/presentations\/reveal-js/plugin/zoom-js/zoom.js', async: true },
{ src: '\/presentations\/reveal-js\/plugin\/notes\/notes.js', async: true }
]};
</script>
<script src="https://ccchb.github.io/presentations/reveal-js/lib/js/head.min.js"></script>
<script src="https://ccchb.github.io/presentations/reveal-js/js/reveal.js"></script>
<script type="text/javascript">
function camelize(map) {
if (map) {
Object.keys(map).forEach(function(k) {
newK = k.replace(/(\_\w)/g, function(m) { return m[1].toUpperCase() });
if (newK != k) {
map[newK] = map[k];
delete map[k];
}
});
}
return map;
}
var revealHugoDefaults = { center: true, controls: true, history: true, progress: true, transition: "slide" };
var revealHugoSiteParams = JSON.parse(document.getElementById('reveal-hugo-site-params').innerHTML);
var revealHugoPageParams = JSON.parse(document.getElementById('reveal-hugo-page-params').innerHTML);
var options = Object.assign({},
camelize(revealHugoDefaults),
camelize(revealHugoSiteParams),
camelize(revealHugoPageParams),
revealHugoDependencies);
Reveal.initialize(options);
</script>
</body>
</html>

View File

@ -0,0 +1,8 @@
[*]
end_of_line = lf
insert_final_newline = true
[*.{js,css}]
charset = utf-8
indent_style = space
indent_size = 2

4
highlight-js/.gitattributes vendored Normal file
View File

@ -0,0 +1,4 @@
# The build script and some tests use `\n` as markers, so we need to make sure
# that all javascript files are checked out using UNIX line endings (not `\r\n`)
*.js eol=lf
*.txt eol=lf

9
highlight-js/.gitignore vendored Normal file
View File

@ -0,0 +1,9 @@
.DS_Store
build
docs/_build
.idea/
__pycache__
*.swp
node_modules
.project
yarn.lock

30
highlight-js/.travis.yml Normal file
View File

@ -0,0 +1,30 @@
language: node_js
node_js:
- "lts/*"
- "node"
env:
-
- BROWSER=1
- BROWSER=1 NOCOMPRESS=1
script:
- |
export BUILD_PARAMS=""
if [ "x$BROWSER" = "x1" ]; then
export BUILD_PARAMS="$BUILD_PARAMS -t browser"
else
export BUILD_PARAMS="$BUILD_PARAMS -t node"
fi
if [ "x$NOCOMPRESS" = "x1" ]; then
export BUILD_PARAMS="$BUILD_PARAMS -n"
fi
node tools/build.js $BUILD_PARAMS
if [ "x$BROWSER" = "x1" ]; then
npm run test-browser
else
npm run test
fi
sudo: false # Use container-based architecture

274
highlight-js/AUTHORS.en.txt Normal file
View File

@ -0,0 +1,274 @@
Syntax highlighting with language autodetection.
URL: https://highlightjs.org/
Current core developers (alphabetical):
- Gidi Meir Morris <gidi@gidi.io>
- Jan T. Sott <git@idleberg.com>
- Li Xuanji <xuanji@gmail.com>
- Marcos Cáceres <marcos@marcosc.com>
- Sang Dang <sang.dang@polku.io>
Former maintainers:
- Ivan Sagalaev (original author) <maniac@softwaremaniacs.org>
- Jeremy Hull <sourdrums@gmail.com>
- Oleg Efimov <efimovov@gmail.com>
Contributors:
- Peter Leonov <gojpeg@gmail.com>
- Victor Karamzin <Victor.Karamzin@enterra-inc.com>
- Vsevolod Solovyov <vsevolod.solovyov@gmail.com>
- Anton Kovalyov <anton@kovalyov.net>
- Nikita Ledyaev <lenikita@yandex.ru>
- Konstantin Evdokimenko <qewerty@gmail.com>
- Dmitri Roudakov <dmitri@roudakov.ru>
- Yuri Ivanov <ivanov@supersoft.ru>
- Vladimir Ermakov <vooon341@mail.ru>
- Vladimir Gubarkov <xonixx@gmail.com>
- Brian Beck <exogen@gmail.com>
- MajestiC <majestic2k@gmail.com>
- Vasily Polovnyov <vast@whiteants.net>
- Vladimir Epifanov <voldmar@voldmar.ru>
- Alexander Makarov <sam@rmcreative.ru>
- Vah <vahtenberg@gmail.com>
- Shuen-Huei Guan <drake.guan@gmail.com>
- Jason Diamond <jason@diamond.name>
- Michal Gabrukiewicz <mgabru@gmail.com>
- Ruslan Keba <rukeba@gmail.com>
- Sergey Baranov <segyrn@yandex.ru>
- Zaripov Yura <yur4ik7@ukr.net>
- Oleg Volchkov <oleg@volchkov.net>
- Vasily Mikhailitchenko <vaskas@programica.ru>
- Jan Berkel <jan.berkel@gmail.com>
- Vladimir Moskva <vladmos@gmail.com>
- Loren Segal <lsegal@soen.ca>
- Andrew Fedorov <dmmdrs@mail.ru>
- Igor Kalnitsky <igor@kalnitsky.org>
- Valerii Hiora <valerii.hiora@gmail.com>
- Nikolay Zakharov <nikolay.desh@gmail.com>
- Dmitry Kovega <arhibot@gmail.com>
- Sergey Ignatov <sergey@ignatov.spb.su>
- Antono Vasiljev <self@antono.info>
- Stephan Kountso <steplg@gmail.com>
- pumbur <pumbur@pumbur.net>
- John Crepezzi <john.crepezzi@gmail.com>
- Andrey Vlasovskikh <andrey.vlasovskikh@gmail.com>
- Alexander Myadzel <myadzel@gmail.com>
- Evgeny Stepanischev <imbolk@gmail.com>
- Dmytrii Nagirniak <dnagir@gmail.com>
- Luigi Maselli <grigio.org@gmail.com>
- Denis Bardadym <bardadymchik@gmail.com>
- Aahan Krish <geekpanth3r@gmail.com>
- Ilya Baryshev <baryshev@gmail.com>
- Aleksandar Ruzicic <aleksandar@ruzicic.info>
- Joe Cheng <joe@rstudio.org>
- Angel G. Olloqui <angelgarcia.mail@gmail.com>
- Jason Tate <adminz@web-cms-designs.com>
- Sergey Tikhomirov <sergey@tikhomirov.io>
- Marc Fornos <marc.fornos@gmail.com>
- Yoshihide Jimbo <yjimbo@gmail.com>
- Casey Duncan <casey.duncan@gmail.com>
- Eugene Nizhibitsky <nizhibitsky@gmail.com>
- Alberto Gimeno <gimenete@gmail.com>
- Kirk Kimmel <kimmel.k.programmer@gmail.com>
- Nathan Grigg <nathan@nathanamy.org>
- Dr. Drang <drdrang@gmail.com>
- Robin Ward <robin.ward@gmail.com>
- Dmitry Medvinsky <me@dmedvinsky.name>
- Jason Jacobson <jason.a.jacobson@gmail.com>
- Jonas Follesø <jonas@follesoe.no>
- Dan Allen <dan.j.allen@gmail.com>
- noformnocontent <i@noformnocontent.com>
- Damien White <damien.white@visoftinc.com>
- Alexander Marenin <great_muchacho@mail.ru>
- Cédric Néhémie <cedric.nehemie@gmail.com>
- Simon Madine <simon@angryrobotzombie.com>
- Benjamin Pannell <contact@sierrasoftworks.com>
- Eric Knibbe <eric@lassosoft.com>
- Poren Chiang <ren.chiang@gmail.com>
- Kelley van Evert <kelleyvanevert@gmail.com>
- Kurt Emch <kurt@kurtemch.com>
- Mehdi Dogguy <mehdi@dogguy.org>
- Nicolas Braud-Santoni <nicolas.braud-santoni@ens-cachan.fr>
- Ralf Bitter <rabit@revigniter.com>
- Sylvestre Ledru <sylvestre.ledru@scilab-enterprises.com>
- Troy Kershaw <hello@troykershaw.com>
- Zena Treep <zena.treep@gmail.com>
- Daniel Kvasnicka <dkvasnicka@vendavo.com>
- Carlo Kok <ck@remobjects.com>
- Bram de Haan <info@atelierbramdehaan.nl>
- Seongwon Lee <dlimpid@gmail.com>
- Zaven Muradyan <megalivoithos@gmail.com>
- Brent Bradbury <brent@brentium.com>
- Martin Dilling-Hansen <martindlling@gmail.com>
- Ilya Vassilevsky <vassilevsky@gmail.com>
- Josh Adams <josh@isotope11.com>
- Dan Tao <daniel.tao@gmail.com>
- Jeff Escalante <hello@jenius.me>
- Jun Yang <yangjvn@126.com>
- Nikolay Lisienko <info@neor.ru>
- Heiko August <post@auge8472.de>
- Domen Kožar <domen@dev.si>
- Travis Odom <travis.a.odom@gmail.com>
- innocenat <innocenat@gmail.com>
- Arthur Bikmullin <devolonter@gmail.com>
- Pascal Hurni <phi@ruby-reactive.org>
- Roman Shmatov <romanshmatov@gmail.com>
- Nic West <nic@letolab.com>
- Panu Horsmalahti <panu.horsmalahti@iki.fi>
- Flaviu Tamas <tamas.flaviu@gmail.com>
- Damian Mee <mee.damian@gmail.com>
- Christopher Kaster <ikasoki@gmail.com>
- Chris Eidhof <chris@eidhof.nl>
- Nate Cook <natecook@gmail.com>
- Matt Diephouse <matt@diephouse.com>
- Erik Osheim <d_m@plastic-idolatry.com>
- Guillaume Laforge <glaforge@gmail.com>
- Lucas Mazza <lucastmazza@gmail.com>
- Maxim Dikun <dikmax@gmail.com>
- Henrik Feldt <henrik@haf.se>
- Anton Kochkov <anton.kochkov@gmail.com>
- Michael Allen <Michael.Allen@benefitfocus.com>
- JP Verkamp <me@jverkamp.com>
- Adam Joseph Cook <adam.joseph.cook@gmail.com>
- Sergey Vidyuk <svidyuk@gmail.com>
- Radek Liska <radekliska@gmail.com>
- Jose Molina Colmenero <gaudy41@gmail.com>
- Max Mikhailov <seven.phases.max@gmail.com>
- Bryant Williams <b.n.williams@gmail.com>
- Erik Paluka <erik.paluka@gmail.com>
- Luke Holder <lukemh@gmail.com>
- David Mohundro <david@mohundro.com>
- Nicholas Blumhardt <nblumhardt@nblumhardt.com>
- Christophe de Dinechin <christophe@taodyne.com>
- Taneli Vatanen <taneli.vatanen@gmail.com>
- Jen Evers-Corvina <jen@sevvie.net>
- Kassio Borges <kassioborgesm@gmail.com>
- Cedric Sohrauer <sohrauer@googlemail.com>
- Mickaël Delahaye <mickael.delahaye@gmail.com>
- Hakan Özler <ozler.hakan@gmail.com>
- Trey Shugart <treshugart@gmail.com>
- Vincent Zurczak <vzurczak@linagora.com>
- Adam Joseph Cook <adam.joseph.cook@gmail.com>
- Edwin Dalorzo <edwin@dalorzo.org>
- mucaho <mkucko@gmail.com>
- Dennis Titze <dennis.titze@gmail.com>
- Jon Evans <jon@craftyjon.com>
- Brian Quistorff <bquistorff@gmail.com>
- Jonathan Suever <suever@gmail.com>
- Alexis Hénaut <alexis@henaut.net>
- Chris Kiehl <audionautic@gmail.com>
- Peter Piwowarski <oldlaptop654@aol.com>
- Kenta Sato <bicycle1885@gmail.com>
- Anthony Scemama <scemama@irsamc.ups-tlse.fr>
- Taufik Nurrohman <latitudu.latitudu@gmail.com>
- Pedro Oliveira <kanytu@gmail.com>
- Gu Yiling <justice360@gmail.com>
- Thomas Applencourt <thomas.applencourt@irsamc.ups-tlse.fr>
- Andrew Farmer <ahfarmer@gmail.com>
- Sergey Mashkov <cy6erGn0m@gmail.com>
- Raivo Laanemets <raivo@infdot.com>
- Kenneth Fuglsang <kfuglsang@gmail.com>
- David Anson <david@dlaa.me>
- Louis Barranqueiro <louis.barranqueiro@gmail.com>
- Tim Schumacher <tim@datenknoten.me>
- Lucas Werkmeister <mail@lucaswerkmeister.de>
- Dan Panzarella <alsoelp@gmail.com>
- Bruno Dias <bruno.r.dias@gmail.com>
- Jay Strybis <jay.strybis@gmail.com>
- Guillaume Gomez <guillaume1.gomez@gmail.com>
- Janis Voigtländer <janis.voigtlaender@gmail.com>
- Dirk Kirsten <dk@basex.org>
- MY Sun <simonmysun@gmail.com>
- Vadimtro <vadimtro@yahoo.com>
- Benjamin Auder <benjamin.auder@gmail.com>
- Dotan Dimet <dotan@corky.net>
- Manh Tuan <junookyo@gmail.com>
- Philippe Charrière <ph.charriere@gmail.com>
- Stefan Bechert <stefan.bechert@gmx.net>
- Samuel Reed <sam@bitmex.com>
- Yury Selivanov <yselivanov@gmail.com>
- Tsuyusato Kitsune <make.just.on@gmail.com>
- Mick MacCallum <micksmaccallum@gmail.com>
- Kristoffer Gronlund <kgronlund@suse.com>
- Søren Enevoldsen <senevoldsen90@gmail.com>
- Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com>
- Ladislav Prskavec <ladislav@prskavec.net>
- Jan Kühle <jkuehle90@gmail.com>
- Stefan Wienert <stwienert@gmail.com>
- Nikita Savchenko <zitros.lab@gmail.com>
- Stefania Mellai <s.mellai@arduino.cc>
- Nebuleon Fumika <nebuleon.fumika@gmail.com>
- prince <MC.prince.0203@gmail.com>
- Brendan Rocks <rocks.brendan@gmail.com>
- Raphaël Assénat <raph@raphnet.net>
- Matt Evans <matt@aptech.com>
- Martin Braun <martin.braun@ettus.com>
- Boris Cherny <boris@performancejs.com>
- John Foster <jfoster@esri.com>
- Robert Dodier <robert.dodier@gmail.com>
- Anthony Dugois <dev.anthonydugois@gmail.com>
- Qeole <qeole@outlook.com>
- Denis Ciccale <dciccale@gmail.com>
- Michael Johnston <lastobelus@gmail.com>
- Taras <oxdef@oxdef.info>
- Philipp Wolfer <ph.wolfer@gmail.com>
- Mikko Kouhia <mikko.kouhia@iki.fi>
- Billy Quith <chinbillybilbo@gmail.com>
- Herbert Shin <initbar@protonmail.ch>
- Tristano Ajmone <tajmone@gmail.com>
- Taisuke Fujimoto <temp-impl@users.noreply.github.com>
- Boone Severson <boone.severson@gmail.com>
- Victor Zhou <OiCMudkips@users.noreply.github.com>
- Lars Schulna <kartoffelbrei.mit.muskatnuss@gmail.org>
- Jacob Childress <jacobc@gmail.com>
- Gavin Siu <gavsiu@gmail.com>
- Builder's Brewery <buildersbrewery@gmail.com>
- Sergey Bronnikov <sergeyb@bronevichok.ru>
- Joe Eli McIlvain <joe.eli.mac@gmail.org>
- Stephan Boyer <stephan@stephanboyer.com>
- Alex McKibben <alex@nullscope.net>
- Daniel Gamage <hellodanielgamage@gmail.com>
- Matthew Daly <matthewbdaly@gmail.com>
- Magnus Madsen <mmadsen@uwaterloo.ca>
- Camil Staps <info@camilstaps.nl>
- Alexander Lichter <manniL@gmx.net>
- Nicolas Le Gall <contact@nlegall.fr>
- Kenton Hamaluik <kentonh@gmail.com>
- Marvin Saignat <contact@zgmrvn.com>
- Michael Rodler <contact@f0rki.at>
- Sergey Sobko <s.sobko@profitware.ru>
- Hale Chan <halechan@qq.com>
- Kasper Andersen <kma_untrusted@protonmail.com>
- Philipp A. <flying-sheep@web.de>
- Guannan Wei <guannanwei@outlook.com>
- Sam Wu <samsam2310@gmail.com>
- Ike Ku <dempfi@yahoo.com>
- Andres Täht <andres.taht@gmail.com>
- Rene Saarsoo <nene@triin.net>
- Jordi Petit <jordi.petit@gmail.com>
- Raphaël Parrëe <rparree@edc4it.com>
- Joël Porquet <joel@porquet.org>
- Alex Arslan <ararslan@comcast.net>
- Stanislav Belov <stbelov@gmail.com>
- Ivan Dementev <ivan_div@mail.ru>
- Nicolas LLOBERA <nllobera@gmail.com>
- Morten Piibeleht <morten.piibeleht@gmail.com>
- Martin Clausen <martin.clausene@gmail.com>
- Arctic Ice Studio <development@arcticicestudio.com>
- Google Inc. (David Benjamin) <davidben@google.com>
- Ahmad Awais <me@AhmadAwais.com>
- Tristian Kelly <tristian.kelly560@gmail.com>
- Melissa Geels <melissa@nimble.tools>
- Dmitriy Tarasov <dimatar@gmail.com>
- Egor Rogov <e.rogov@postgrespro.ru>
- Meseta <meseta@gmail.com>
- Harmon <Harmon.Public@gmail.com>
- Eric Bailey <eric.w.bailey@gmail.com>
- Gustavo Costa <gusbemacbe@gmail.com>
- Antoine Boisier-Michaud <aboisiermichaud@gmail.com>
- Alejandro Isaza <al@isaza.ca>
- Laurent Voullemier <laurent.voullemier@gmail.com>

1757
highlight-js/CHANGES.md Normal file

File diff suppressed because it is too large Load Diff

24
highlight-js/LICENSE Normal file
View File

@ -0,0 +1,24 @@
Copyright (c) 2006, Ivan Sagalaev
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of highlight.js nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

186
highlight-js/README.md Normal file
View File

@ -0,0 +1,186 @@
# Highlight.js
[![Build Status](https://travis-ci.org/highlightjs/highlight.js.svg?branch=master)](https://travis-ci.org/highlightjs/highlight.js)
Highlight.js is a syntax highlighter written in JavaScript. It works in
the browser as well as on the server. It works with pretty much any
markup, doesnt depend on any framework, and has automatic language
detection.
## Getting Started
The bare minimum for using highlight.js on a web page is linking to the
library along with one of the styles and calling
[`initHighlightingOnLoad`][1]:
```html
<link rel="stylesheet" href="/path/to/styles/default.css">
<script src="/path/to/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
```
This will find and highlight code inside of `<pre><code>` tags; it tries
to detect the language automatically. If automatic detection doesnt
work for you, you can specify the language in the `class` attribute:
```html
<pre><code class="html">...</code></pre>
```
The list of supported language classes is available in the [class
reference][2]. Classes can also be prefixed with either `language-` or
`lang-`.
To make arbitrary text look like code, but without highlighting, use the
`plaintext` class:
```html
<pre><code class="plaintext">...</code></pre>
```
To disable highlighting altogether use the `nohighlight` class:
```html
<pre><code class="nohighlight">...</code></pre>
```
## Custom Initialization
When you need a bit more control over the initialization of
highlight.js, you can use the [`highlightBlock`][3] and [`configure`][4]
functions. This allows you to control *what* to highlight and *when*.
Heres an equivalent way to calling [`initHighlightingOnLoad`][1] using
jQuery:
```javascript
$(document).ready(function() {
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
});
```
You can use any tags instead of `<pre><code>` to mark up your code. If
you don't use a container that preserves line breaks you will need to
configure highlight.js to use the `<br>` tag:
```javascript
hljs.configure({useBR: true});
$('div.code').each(function(i, block) {
hljs.highlightBlock(block);
});
```
For other options refer to the documentation for [`configure`][4].
## Web Workers
You can run highlighting inside a web worker to avoid freezing the browser
window while dealing with very big chunks of code.
In your main script:
```javascript
addEventListener('load', function() {
var code = document.querySelector('#code');
var worker = new Worker('worker.js');
worker.onmessage = function(event) { code.innerHTML = event.data; }
worker.postMessage(code.textContent);
})
```
In worker.js:
```javascript
onmessage = function(event) {
importScripts('<path>/highlight.pack.js');
var result = self.hljs.highlightAuto(event.data);
postMessage(result.value);
}
```
## Getting the Library
You can get highlight.js as a hosted, or custom-build, browser script or
as a server module. Right out of the box the browser script supports
both AMD and CommonJS, so if you wish you can use RequireJS or
Browserify without having to build from source. The server module also
works perfectly fine with Browserify, but there is the option to use a
build specific to browsers rather than something meant for a server.
Head over to the [download page][5] for all the options.
**Don't link to GitHub directly.** The library is not supposed to work straight
from the source, it requires building. If none of the pre-packaged options
work for you refer to the [building documentation][6].
**The CDN-hosted package doesn't have all the languages.** Otherwise it'd be
too big. If you don't see the language you need in the ["Common" section][5],
it can be added manually:
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/languages/go.min.js"></script>
```
**On Almond.** You need to use the optimizer to give the module a name. For
example:
```
r.js -o name=hljs paths.hljs=/path/to/highlight out=highlight.js
```
### CommonJS
You can import Highlight.js as a CommonJS-module:
```bash
npm install highlight.js --save
```
In your application:
```javascript
import hljs from 'highlight.js';
```
The default import imports all languages! Therefore it is likely to be more efficient to import only the library and the languages you need:
```javascript
import hljs from 'highlight.js/lib/highlight';
import javascript from 'highlight.js/lib/languages/javascript';
hljs.registerLanguage('javascript', javascript);
```
To set the syntax highlighting style, if your build tool processes CSS from your JavaScript entry point, you can import the stylesheet directly into your CommonJS-module:
```javascript
import hljs from 'highlight.js/lib/highlight';
import 'highlight.js/styles/github.css'
```
## License
Highlight.js is released under the BSD License. See [LICENSE][7] file
for details.
## Links
The official site for the library is at <https://highlightjs.org/>.
Further in-depth documentation for the API and other topics is at
<http://highlightjs.readthedocs.io/>.
Authors and contributors are listed in the [AUTHORS.en.txt][8] file.
[1]: http://highlightjs.readthedocs.io/en/latest/api.html#inithighlightingonload
[2]: http://highlightjs.readthedocs.io/en/latest/css-classes-reference.html
[3]: http://highlightjs.readthedocs.io/en/latest/api.html#highlightblock-block
[4]: http://highlightjs.readthedocs.io/en/latest/api.html#configure-options
[5]: https://highlightjs.org/download/
[6]: http://highlightjs.readthedocs.io/en/latest/building-testing.html
[7]: https://github.com/highlightjs/highlight.js/blob/master/LICENSE
[8]: https://github.com/highlightjs/highlight.js/blob/master/AUTHORS.en.txt

142
highlight-js/README.ru.md Normal file
View File

@ -0,0 +1,142 @@
# Highlight.js
Highlight.js — это инструмент для подсветки синтаксиса, написанный на JavaScript. Он работает
и в браузере, и на сервере. Он работает с практически любой HTML разметкой, не
зависит от каких-либо фреймворков и умеет автоматически определять язык.
## Начало работы
Минимум, что нужно сделать для использования highlight.js на веб-странице — это
подключить библиотеку, CSS-стили и вызывать [`initHighlightingOnLoad`][1]:
```html
<link rel="stylesheet" href="/path/to/styles/default.css">
<script src="/path/to/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
```
Библиотека найдёт и раскрасит код внутри тегов `<pre><code>`, попытавшись
автоматически определить язык. Когда автоопределение не срабатывает, можно явно
указать язык в атрибуте class:
```html
<pre><code class="html">...</code></pre>
```
Список поддерживаемых классов языков доступен в [справочнике по классам][2].
Класс также можно предварить префиксами `language-` или `lang-`.
Чтобы отключить подсветку для какого-то блока, используйте класс `nohighlight`:
```html
<pre><code class="nohighlight">...</code></pre>
```
## Инициализация вручную
Чтобы иметь чуть больше контроля за инициализацией подсветки, вы можете
использовать функции [`highlightBlock`][3] и [`configure`][4]. Таким образом
можно управлять тем, *что* и *когда* подсвечивать.
Вот пример инициализации, эквивалентной вызову [`initHighlightingOnLoad`][1], но
с использованием jQuery:
```javascript
$(document).ready(function() {
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
});
```
Вы можете использовать любые теги разметки вместо `<pre><code>`. Если
используете контейнер, не сохраняющий переводы строк, вам нужно сказать
highlight.js использовать для них тег `<br>`:
```javascript
hljs.configure({useBR: true});
$('div.code').each(function(i, block) {
hljs.highlightBlock(block);
});
```
Другие опции можно найти в документации функции [`configure`][4].
## Web Workers
Подсветку можно запустить внутри web worker'а, чтобы окно
браузера не подтормаживало при работе с большими кусками кода.
В основном скрипте:
```javascript
addEventListener('load', function() {
var code = document.querySelector('#code');
var worker = new Worker('worker.js');
worker.onmessage = function(event) { code.innerHTML = event.data; }
worker.postMessage(code.textContent);
})
```
В worker.js:
```javascript
onmessage = function(event) {
importScripts('<path>/highlight.pack.js');
var result = self.hljs.highlightAuto(event.data);
postMessage(result.value);
}
```
## Установка библиотеки
Highlight.js можно использовать в браузере прямо с CDN хостинга или скачать
индивидуальную сборку, а также установив модуль на сервере. На
[странице загрузки][5] подробно описаны все варианты.
**Не подключайте GitHub напрямую.** Библиотека не предназначена для
использования в виде исходного кода, а требует отдельной сборки. Если вам не
подходит ни один из готовых вариантов, читайте [документацию по сборке][6].
**Файл на CDN содержит не все языки.** Иначе он будет слишком большого размера.
Если нужного вам языка нет в [категории "Common"][5], можно дообавить его
вручную:
```html
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.4.0/languages/go.min.js"></script>
```
**Про Almond.** Нужно задать имя модуля в оптимизаторе, например:
```
r.js -o name=hljs paths.hljs=/path/to/highlight out=highlight.js
```
## Лицензия
Highlight.js распространяется под лицензией BSD. Подробнее читайте файл
[LICENSE][7].
## Ссылки
Официальный сайт билиотеки расположен по адресу <https://highlightjs.org/>.
Более подробная документация по API и другим темам расположена на
<http://highlightjs.readthedocs.io/>.
Авторы и контрибьюторы перечислены в файле [AUTHORS.ru.txt][8] file.
[1]: http://highlightjs.readthedocs.io/en/latest/api.html#inithighlightingonload
[2]: http://highlightjs.readthedocs.io/en/latest/css-classes-reference.html
[3]: http://highlightjs.readthedocs.io/en/latest/api.html#highlightblock-block
[4]: http://highlightjs.readthedocs.io/en/latest/api.html#configure-options
[5]: https://highlightjs.org/download/
[6]: http://highlightjs.readthedocs.io/en/latest/building-testing.html
[7]: https://github.com/highlightjs/highlight.js/blob/master/LICENSE
[8]: https://github.com/highlightjs/highlight.js/blob/master/AUTHORS.ru.txt

119
highlight-js/demo/demo.js Normal file
View File

@ -0,0 +1,119 @@
(function() {
'use strict';
var $window = $(window),
$languages = $('#languages div'),
$linkTitle = $('link[title]'),
$categoryContainer = $('#categories'),
$styleContainer = $('#styles');
function resizeLists() {
var screenHeight = $window.height()
$categoryContainer.css('max-height', screenHeight / 4);
$categoryContainer.perfectScrollbar('update');
$styleContainer.height(
screenHeight - $styleContainer.position().top - 20
);
$styleContainer.perfectScrollbar('update');
}
function selectCategory(category) {
$languages.each(function(i, language) {
var $language = $(language);
if ($language.hasClass(category)) {
var code = $language.find('code');
if (!code.hasClass('hljs')) {
hljs.highlightBlock(code.get(0));
}
$language.show();
} else {
$language.hide();
}
});
$(document).scrollTop(0);
}
function categoryKey(c) {
return c === 'common' ? '' : c === 'misc' ? 'z' : c === 'all' ? 'zz' : c;
}
function initCategories() {
var $categories, categoryNames;
var categories = {};
$languages.each(function(i, div) {
if (!div.className) {
div.className += 'misc';
}
div.className += ' all';
div.className.split(' ').forEach(function(c) {
categories[c] = (categories[c] || 0) + 1;
});
});
categoryNames = Object.keys(categories);
categoryNames.sort(function(a, b) {
a = categoryKey(a);
b = categoryKey(b);
return a < b ? -1 : a > b ? 1 : 0;
});
categoryNames.forEach(function(c) {
$categoryContainer.append(
'<li data-category="' + c + '">' + c + ' (' + categories[c] +')</li>'
);
});
$categories = $categoryContainer.find('li');
$categories.click(function() {
var $category = $(this);
$categories.removeClass('current');
$category.addClass('current');
selectCategory($category.data('category'));
});
$categories.first().click();
$categoryContainer.perfectScrollbar();
}
function selectStyle(style) {
$linkTitle.each(function(i, link) {
link.disabled = (link.title !== style);
});
}
function initStyles() {
var $styles;
$linkTitle.each(function(i, link) {
$styleContainer.append('<li>' + link.title + '</li>');
});
$styles = $styleContainer.find('li');
$styles.click(function() {
var $style = $(this);
$styles.removeClass('current');
$style.addClass('current');
selectStyle($style.text());
});
$styles.first().click();
$styleContainer.perfectScrollbar();
}
$(function() {
initCategories();
initStyles();
$window.resize(resizeLists);
resizeLists();
});
}).call(this);

View File

@ -0,0 +1,55 @@
<!DOCTYPE html>
<html lang="en">
<!-- This file is intended to be built using the instructions here: http://highlightjs.readthedocs.io/en/latest/building-testing.html#building -->
<head>
<meta charset="utf-8">
<title>highlight.js demo</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="perfect-scrollbar.min.css">
<link rel="stylesheet" title="Default" href="styles/default.css">
<% _.each(styles, function(style) { %>
<link rel="alternate stylesheet" title="<%= style.name %>" href="<%= style.path %>">
<% }); %>
</head>
<body>
<div id="sidebar">
<div id="header">
<h1><a href="https://highlightjs.org/">highlight.js</a> demo</h1>
</div>
<div id="lists">
<div>
<h2>Language categories</h2>
<ul id="categories"></ul>
</div>
<div>
<h2>Styles</h2>
<ul id="styles"></ul>
</div>
</div>
</div>
<div id="content">
<div id="languages">
<% _.each(blobs, function(blob) { %>
<% var categories = blob.fileInfo.Category; %>
<div <% if(categories) { %>class="<%= categories.join(' ') %>"<% } %>>
<h2><%- blob.fileInfo.Language %></h2>
<pre><code class="<%- path.basename(blob.name, '.js') %>"><%- blob.result %></code></pre>
</div>
<% }); %>
</div>
</div>
<script src="../highlight.pack.js"></script>
<script src="jquery-2.1.1.min.js"></script>
<script src="perfect-scrollbar.min.js"></script>
<script src="demo.js"></script>
</body>
</html>

4
highlight-js/demo/jquery-2.1.1.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,5 @@
/*! perfect-scrollbar - v0.5.7
* http://noraesae.github.com/perfect-scrollbar/
* Copyright (c) 2014 Hyunje Alex Jun; Licensed MIT */
.ps-container.ps-active-x>.ps-scrollbar-x-rail,.ps-container.ps-active-y>.ps-scrollbar-y-rail{display:block}.ps-container>.ps-scrollbar-x-rail{display:none;position:absolute;-webkit-border-radius:4px;-moz-border-radius:4px;-ms-border-radius:4px;border-radius:4px;opacity:0;-ms-filter:"alpha(Opacity=0)";filter:alpha(opacity=0);-webkit-transition:background-color .2s linear,opacity .2s linear;-moz-transition:background-color .2s linear,opacity .2s linear;-o-transition:background-color .2s linear,opacity .2s linear;transition:background-color .2s linear,opacity .2s linear;bottom:3px;height:8px}.ps-container>.ps-scrollbar-x-rail>.ps-scrollbar-x{position:absolute;background-color:#aaa;-webkit-border-radius:4px;-moz-border-radius:4px;-ms-border-radius:4px;border-radius:4px;-webkit-transition:background-color .2s linear;-moz-transition:background-color .2s linear;-o-transition:background-color .2s linear;transition:background-color .2s linear;bottom:0;height:8px}.ps-container>.ps-scrollbar-x-rail.in-scrolling{background-color:#eee;opacity:.9;-ms-filter:"alpha(Opacity=90)";filter:alpha(opacity=90)}.ps-container>.ps-scrollbar-y-rail{display:none;position:absolute;-webkit-border-radius:4px;-moz-border-radius:4px;-ms-border-radius:4px;border-radius:4px;opacity:0;-ms-filter:"alpha(Opacity=0)";filter:alpha(opacity=0);-webkit-transition:background-color .2s linear,opacity .2s linear;-moz-transition:background-color .2s linear,opacity .2s linear;-o-transition:background-color .2s linear,opacity .2s linear;transition:background-color .2s linear,opacity .2s linear;right:3px;width:8px}.ps-container>.ps-scrollbar-y-rail>.ps-scrollbar-y{position:absolute;background-color:#aaa;-webkit-border-radius:4px;-moz-border-radius:4px;-ms-border-radius:4px;border-radius:4px;-webkit-transition:background-color .2s linear;-moz-transition:background-color .2s linear;-o-transition:background-color .2s linear;transition:background-color .2s linear;right:0;width:8px}.ps-container>.ps-scrollbar-y-rail.in-scrolling{background-color:#eee;opacity:.9;-ms-filter:"alpha(Opacity=90)";filter:alpha(opacity=90)}.ps-container:hover>.ps-scrollbar-x-rail,.ps-container:hover>.ps-scrollbar-y-rail{opacity:.6;-ms-filter:"alpha(Opacity=60)";filter:alpha(opacity=60)}.ps-container:hover>.ps-scrollbar-x-rail.in-scrolling,.ps-container:hover>.ps-scrollbar-y-rail.in-scrolling{background-color:#eee;opacity:.9;-ms-filter:"alpha(Opacity=90)";filter:alpha(opacity=90)}.ps-container:hover>.ps-scrollbar-x-rail:hover{background-color:#eee;opacity:.9;-ms-filter:"alpha(Opacity=90)";filter:alpha(opacity=90)}.ps-container:hover>.ps-scrollbar-x-rail:hover>.ps-scrollbar-x{background-color:#999}.ps-container:hover>.ps-scrollbar-y-rail:hover{background-color:#eee;opacity:.9;-ms-filter:"alpha(Opacity=90)";filter:alpha(opacity=90)}.ps-container:hover>.ps-scrollbar-y-rail:hover>.ps-scrollbar-y{background-color:#999}

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1 @@
To view this demo in browser, please follow the [build instructions](http://highlightjs.readthedocs.io/en/latest/building-testing.html#building) with browser as the target, and then open the generated build/demo/index.html.

View File

@ -0,0 +1,74 @@
/* Base styles */
body {
color: #F0F0F0;
background: #500;
font-family: Arial, sans;
margin: 0; padding: 0;
}
a {
color: white;
}
h1 {
font: bold 150% Arial, sans-serif;
margin: 0; padding: 1em 0;
}
h2 {
font: bold 120% Arial, sans-serif;
margin: 1.5em 0 0.5em 0;
}
pre {
margin: 0;
font-size: medium;
}
#sidebar {
float: left; width: 16em; height: 1000em; position: fixed;
padding: 1px 1em;
background: #600;
box-shadow: 0 0 15px black;
}
#sidebar ul,
#sidebar li {
list-style: none;
margin: 0; padding: 0;
}
#sidebar ul {
position: relative;
overflow-y: hidden;
}
#sidebar li {
padding: 1px 1em;
cursor: pointer;
}
#sidebar li:hover {
background: #500;
}
#sidebar li.current:before {
content: '▶'; font-size: smaller;
position: absolute; left: 0;
}
#content {
margin-left: 19em;
}
#languages {
padding: 1px 4em;
}
#languages div {
display: none;
}
#languages div {
margin: 3em 0;
}

153
highlight-js/docs/Makefile Normal file
View File

@ -0,0 +1,153 @@
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/highlightjs.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/highlightjs.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/highlightjs"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/highlightjs"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."

0
highlight-js/docs/_static/.gitkeep vendored Normal file
View File

0
highlight-js/docs/_templates/.gitkeep vendored Normal file
View File

120
highlight-js/docs/api.rst Normal file
View File

@ -0,0 +1,120 @@
Library API
===========
Highlight.js exports a few functions as methods of the ``hljs`` object.
``highlight(name, value, ignore_illegals, continuation)``
---------------------------------------------------------
Core highlighting function.
Accepts a language name, or an alias, and a string with the code to highlight.
The ``ignore_illegals`` parameter, when present and evaluates to a true value,
forces highlighting to finish even in case of detecting illegal syntax for the
language instead of throwing an exception.
The ``continuation`` is an optional mode stack representing unfinished parsing.
When present, the function will restart parsing from this state instead of
initializing a new one.
Returns an object with the following properties:
* ``language``: language name, same as the one passed into a function, returned for consistency with ``highlightAuto``
* ``relevance``: integer value
* ``value``: HTML string with highlighting markup
* ``top``: top of the current mode stack
``highlightAuto(value, languageSubset)``
----------------------------------------
Highlighting with language detection.
Accepts a string with the code to highlight and an optional array of language names and aliases restricting detection to only those languages. The subset can also be set with ``configure``, but the local parameter overrides the option if set.
Returns an object with the following properties:
* ``language``: detected language
* ``relevance``: integer value
* ``value``: HTML string with highlighting markup
* ``second_best``: object with the same structure for second-best heuristically detected language, may be absent
``fixMarkup(value)``
--------------------
Post-processing of the highlighted markup. Currently consists of replacing indentation TAB characters and using ``<br>`` tags instead of new-line characters. Options are set globally with ``configure``.
Accepts a string with the highlighted markup.
``highlightBlock(block)``
-------------------------
Applies highlighting to a DOM node containing code.
This function is the one to use to apply highlighting dynamically after page load
or within initialization code of third-party Javascript frameworks.
The function uses language detection by default but you can specify the language
in the ``class`` attribute of the DOM node. See the :doc:`class reference
</css-classes-reference>` for all available language names and aliases.
``configure(options)``
----------------------
Configures global options:
* ``tabReplace``: a string used to replace TAB characters in indentation.
* ``useBR``: a flag to generate ``<br>`` tags instead of new-line characters in the output, useful when code is marked up using a non-``<pre>`` container.
* ``classPrefix``: a string prefix added before class names in the generated markup, used for backwards compatibility with stylesheets.
* ``languages``: an array of language names and aliases restricting auto detection to only these languages.
Accepts an object representing options with the values to updated. Other options don't change
::
hljs.configure({
tabReplace: ' ', // 4 spaces
classPrefix: '' // don't append class prefix
// … other options aren't changed
})
hljs.initHighlighting();
``initHighlighting()``
----------------------
Applies highlighting to all ``<pre><code>..</code></pre>`` blocks on a page.
``initHighlightingOnLoad()``
----------------------------
Attaches highlighting to the page load event.
``registerLanguage(name, language)``
------------------------------------
Adds new language to the library under the specified name. Used mostly internally.
* ``name``: a string with the name of the language being registered
* ``language``: a function that returns an object which represents the
language definition. The function is passed the ``hljs`` object to be able
to use common regular expressions defined within it.
``listLanguages()``
----------------------------
Returns the languages names list.
.. _getLanguage:
``getLanguage(name)``
---------------------
Looks up a language by name or alias.
Returns the language object if found, ``undefined`` otherwise.

View File

@ -0,0 +1,88 @@
Building and testing
====================
To actually run highlight.js it is necessary to build it for the environment
where you're going to run it: a browser, the node.js server, etc.
Building
--------
The build tool is written in JavaScript using node.js. Before running the
script, make sure to have node installed and run ``npm install`` to get the
dependencies.
The tool is located in ``tools/build.js``. A few useful examples:
* Build for a browser using only common languages::
node tools/build.js :common
* Build for node.js including all available languages::
node tools/build.js -t node
* Build two specific languages for debugging, skipping compression in this case::
node tools/build.js -n python ruby
On some systems the node binary is named ``nodejs``; simply replace ``node``
with ``nodejs`` in the examples above if that is the case.
The full option reference is available with the usual ``--help`` option.
The build result will be in the ``build/`` directory.
.. _basic-testing:
Basic testing
-------------
The usual approach to debugging and testing a language is first doing it
visually. You need to build highlight.js with only the language you're working
on (without compression, to have readable code in browser error messages) and
then use the Developer tool in ``tools/developer.html`` to see how it highlights
a test snippet in that language.
A test snippet should be short and give the idea of the overall look of the
language. It shouldn't include every possible syntactic element and shouldn't
even make practical sense.
After you satisfied with the result you need to make sure that language
detection still works with your language definition included in the whole suite.
Testing is done using `Mocha <http://mochajs.org/>`_ and the
files are found in the ``test/`` directory. You can use the node build to
run the tests in the command line with ``npm test`` after installing the
dependencies with ``npm install``.
**Note**: for Debian-based machine, like Ubuntu, you might need to create an
alias or symbolic link for nodejs to node. The reason for this is the
dependencies that are requires to test highlight.js has a reference to
"node".
Place the snippet you used inside the browser in
``test/detect/<language>/default.txt``, build the package with all the languages
for node and run the test suite. If your language breaks auto-detection, it
should be fixed by :ref:`improving relevance <relevance>`, which is a black art
in and of itself. When in doubt, please refer to the discussion group!
Testing markup
--------------
You can also provide additional markup tests for the language to test isolated
cases of various syntactic construct. If your language has 19 different string
literals or complicated heuristics for telling division (``/``) apart from
regexes (``/ .. /``) -- this is the place.
A test case consists of two files:
* ``test/markup/<language>/<test_name>.txt``: test code
* ``test/markup/<language>/<test_name>.expect.txt``: reference rendering
To generate reference rendering use the Developer tool located at
``tools/developer.html``. Make sure to explicitly select your language in the
drop-down menu, as automatic detection is unlikely to work in this case.

242
highlight-js/docs/conf.py Normal file
View File

@ -0,0 +1,242 @@
# -*- coding: utf-8 -*-
#
# highlight.js documentation build configuration file, created by
# sphinx-quickstart on Wed Sep 12 23:48:27 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'highlight.js'
copyright = u'20122018, Ivan Sagalaev'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '9.13'
# The full version, including alpha/beta/rc tags.
release = '9.13.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'highlightjsdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'highlightjs.tex', u'highlight.js Documentation',
u'Ivan Sagalaev', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'highlightjs', u'highlight.js Documentation',
[u'Ivan Sagalaev'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'highlightjs', u'highlight.js Documentation',
u'Ivan Sagalaev', 'highlightjs', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'

View File

@ -0,0 +1,462 @@
CSS classes reference
=====================
Stylable classes
----------------
+------------------------------------------------------------------------------+
| **General-purpose** |
+--------------------------+---------------------------------------------------+
| keyword | keyword in a regular Algol-style language |
+--------------------------+---------------------------------------------------+
| built_in | built-in or library object (constant, class, |
| | function) |
+--------------------------+---------------------------------------------------+
| type | user-defined type in a language with first-class |
| | syntactically significant types, like Haskell |
+--------------------------+---------------------------------------------------+
| literal | special identifier for a built-in value ("true", |
| | "false", "null") |
+--------------------------+---------------------------------------------------+
| number | number, including units and modifiers, if any. |
+--------------------------+---------------------------------------------------+
| regexp | literal regular expression |
+--------------------------+---------------------------------------------------+
| string | literal string, character |
+--------------------------+---------------------------------------------------+
| subst | parsed section inside a literal string |
+--------------------------+---------------------------------------------------+
| symbol | symbolic constant, interned string, goto label |
+--------------------------+---------------------------------------------------+
| class | class or class-level declaration (interfaces, |
| | traits, modules, etc) |
+--------------------------+---------------------------------------------------+
| function | function or method declaration |
+--------------------------+---------------------------------------------------+
| title | name of a class or a function at the place of |
| | declaration |
+--------------------------+---------------------------------------------------+
| params | block of function arguments (parameters) at the |
| | place of declaration |
+--------------------------+---------------------------------------------------+
| **Meta** |
+--------------------------+---------------------------------------------------+
| comment | comment |
+--------------------------+---------------------------------------------------+
| doctag | documentation markup within comments |
+--------------------------+---------------------------------------------------+
| meta | flags, modifiers, annotations, processing |
| | instructions, preprocessor directive, etc |
+--------------------------+---------------------------------------------------+
| meta-keyword | keyword or built-in within meta construct |
+--------------------------+---------------------------------------------------+
| meta-string | string within meta construct |
+--------------------------+---------------------------------------------------+
| **Tags, attributes, configs** |
+--------------------------+---------------------------------------------------+
| section | heading of a section in a config file, heading in |
| | text markup |
+--------------------------+---------------------------------------------------+
| tag | XML/HTML tag |
+--------------------------+---------------------------------------------------+
| name | name of an XML tag, the first word in an |
| | s-expression |
+--------------------------+---------------------------------------------------+
| builtin-name | s-expression name from the language standard |
| | library |
+--------------------------+---------------------------------------------------+
| attr | name of an attribute with no language defined |
| | semantics (keys in JSON, setting names in .ini), |
| | also sub-attribute within another highlighted |
| | object, like XML tag |
+--------------------------+---------------------------------------------------+
| attribute | name of an attribute followed by a structured |
| | value part, like CSS properties |
+--------------------------+---------------------------------------------------+
| variable | variable in a config or a template file, |
| | environment var expansion in a script |
+--------------------------+---------------------------------------------------+
| **Markup** |
+--------------------------+---------------------------------------------------+
| bullet | list item bullet in text markup |
+--------------------------+---------------------------------------------------+
| code | code block in text markup |
+--------------------------+---------------------------------------------------+
| emphasis | emphasis in text markup |
+--------------------------+---------------------------------------------------+
| strong | strong emphasis in text markup |
+--------------------------+---------------------------------------------------+
| formula | mathematical formula in text markup |
+--------------------------+---------------------------------------------------+
| link | hyperlink in text markup |
+--------------------------+---------------------------------------------------+
| quote | quotation in text markup |
+--------------------------+---------------------------------------------------+
| **CSS** |
+--------------------------+---------------------------------------------------+
| selector-tag | tag selector in CSS |
+--------------------------+---------------------------------------------------+
| selector-id | #id selector in CSS |
+--------------------------+---------------------------------------------------+
| selector-class | .class selector in CSS |
+--------------------------+---------------------------------------------------+
| selector-attr | [attr] selector in CSS |
+--------------------------+---------------------------------------------------+
| selector-pseudo | :pseudo selector in CSS |
+--------------------------+---------------------------------------------------+
| **Templates** |
+--------------------------+---------------------------------------------------+
| template-tag | tag of a template language |
+--------------------------+---------------------------------------------------+
| template-variable | variable in a template language |
+--------------------------+---------------------------------------------------+
| **diff** |
+--------------------------+---------------------------------------------------+
| addition | added or changed line in a diff |
+--------------------------+---------------------------------------------------+
| deletion | deleted line in a diff |
+--------------------------+---------------------------------------------------+
| **ReasonML** |
+--------------------------+---------------------------------------------------+
| operator | reasonml operator such as pipe |
+--------------------------+---------------------------------------------------+
| pattern-match | reasonml pattern matching matchers |
+--------------------------+---------------------------------------------------+
| typing | type signatures on function parameters |
+--------------------------+---------------------------------------------------+
| constructor | type constructors |
+--------------------------+---------------------------------------------------+
| module-access | scope access into a ReasonML module |
+--------------------------+---------------------------------------------------+
| module | ReasonML module reference within scope access |
+--------------------------+---------------------------------------------------+
Language names and aliases
--------------------------
+-------------------------+---------------------------------------------------+
| 1C | 1c |
+-------------------------+---------------------------------------------------+
| ABNF | abnf |
+-------------------------+---------------------------------------------------+
| Access logs | accesslog |
+-------------------------+---------------------------------------------------+
| Ada | ada |
+-------------------------+---------------------------------------------------+
| ARM assembler | armasm, arm |
+-------------------------+---------------------------------------------------+
| AVR assembler | avrasm |
+-------------------------+---------------------------------------------------+
| ActionScript | actionscript, as |
+-------------------------+---------------------------------------------------+
| AngelScript | angelscript, asc |
+-------------------------+---------------------------------------------------+
| Apache | apache, apacheconf |
+-------------------------+---------------------------------------------------+
| AppleScript | applescript, osascript |
+-------------------------+---------------------------------------------------+
| Arcade | arcade |
+-------------------------+---------------------------------------------------+
| AsciiDoc | asciidoc, adoc |
+-------------------------+---------------------------------------------------+
| AspectJ | aspectj |
+-------------------------+---------------------------------------------------+
| AutoHotkey | autohotkey |
+-------------------------+---------------------------------------------------+
| AutoIt | autoit |
+-------------------------+---------------------------------------------------+
| Awk | awk, mawk, nawk, gawk |
+-------------------------+---------------------------------------------------+
| Axapta | axapta |
+-------------------------+---------------------------------------------------+
| Bash | bash, sh, zsh |
+-------------------------+---------------------------------------------------+
| Basic | basic |
+-------------------------+---------------------------------------------------+
| BNF | bnf |
+-------------------------+---------------------------------------------------+
| Brainfuck | brainfuck, bf |
+-------------------------+---------------------------------------------------+
| C# | cs, csharp |
+-------------------------+---------------------------------------------------+
| C++ | cpp, c, cc, h, c++, h++, hpp |
+-------------------------+---------------------------------------------------+
| C/AL | cal |
+-------------------------+---------------------------------------------------+
| Cache Object Script | cos, cls |
+-------------------------+---------------------------------------------------+
| CMake | cmake, cmake.in |
+-------------------------+---------------------------------------------------+
| Coq | coq |
+-------------------------+---------------------------------------------------+
| CSP | csp |
+-------------------------+---------------------------------------------------+
| CSS | css |
+-------------------------+---------------------------------------------------+
| Capn Proto | capnproto, capnp |
+-------------------------+---------------------------------------------------+
| Clojure | clojure, clj |
+-------------------------+---------------------------------------------------+
| CoffeeScript | coffeescript, coffee, cson, iced |
+-------------------------+---------------------------------------------------+
| Crmsh | crmsh, crm, pcmk |
+-------------------------+---------------------------------------------------+
| Crystal | crystal, cr |
+-------------------------+---------------------------------------------------+
| D | d |
+-------------------------+---------------------------------------------------+
| DNS Zone file | dns, zone, bind |
+-------------------------+---------------------------------------------------+
| DOS | dos, bat, cmd |
+-------------------------+---------------------------------------------------+
| Dart | dart |
+-------------------------+---------------------------------------------------+
| Delphi | delphi, dpr, dfm, pas, pascal, freepascal, |
| | lazarus, lpr, lfm |
+-------------------------+---------------------------------------------------+
| Diff | diff, patch |
+-------------------------+---------------------------------------------------+
| Django | django, jinja |
+-------------------------+---------------------------------------------------+
| Dockerfile | dockerfile, docker |
+-------------------------+---------------------------------------------------+
| dsconfig | dsconfig |
+-------------------------+---------------------------------------------------+
| DTS (Device Tree) | dts |
+-------------------------+---------------------------------------------------+
| Dust | dust, dst |
+-------------------------+---------------------------------------------------+
| EBNF | ebnf |
+-------------------------+---------------------------------------------------+
| Elixir | elixir |
+-------------------------+---------------------------------------------------+
| Elm | elm |
+-------------------------+---------------------------------------------------+
| Erlang | erlang, erl |
+-------------------------+---------------------------------------------------+
| Excel | excel, xls, xlsx |
+-------------------------+---------------------------------------------------+
| F# | fsharp, fs |
+-------------------------+---------------------------------------------------+
| FIX | fix |
+-------------------------+---------------------------------------------------+
| Fortran | fortran, f90, f95 |
+-------------------------+---------------------------------------------------+
| G-Code | gcode, nc |
+-------------------------+---------------------------------------------------+
| Gams | gams, gms |
+-------------------------+---------------------------------------------------+
| GAUSS | gauss, gss |
+-------------------------+---------------------------------------------------+
| Gherkin | gherkin |
+-------------------------+---------------------------------------------------+
| Go | go, golang |
+-------------------------+---------------------------------------------------+
| Golo | golo, gololang |
+-------------------------+---------------------------------------------------+
| Gradle | gradle |
+-------------------------+---------------------------------------------------+
| Groovy | groovy |
+-------------------------+---------------------------------------------------+
| HTML, XML | xml, html, xhtml, rss, atom, xjb, xsd, xsl, plist |
+-------------------------+---------------------------------------------------+
| HTTP | http, https |
+-------------------------+---------------------------------------------------+
| Haml | haml |
+-------------------------+---------------------------------------------------+
| Handlebars | handlebars, hbs, html.hbs, html.handlebars |
+-------------------------+---------------------------------------------------+
| Haskell | haskell, hs |
+-------------------------+---------------------------------------------------+
| Haxe | haxe, hx |
+-------------------------+---------------------------------------------------+
| Hy | hy, hylang |
+-------------------------+---------------------------------------------------+
| Ini, TOML | ini, toml |
+-------------------------+---------------------------------------------------+
| Inform7 | inform7, i7 |
+-------------------------+---------------------------------------------------+
| IRPF90 | irpf90 |
+-------------------------+---------------------------------------------------+
| JSON | json |
+-------------------------+---------------------------------------------------+
| Java | java, jsp |
+-------------------------+---------------------------------------------------+
| JavaScript | javascript, js, jsx |
+-------------------------+---------------------------------------------------+
| Kotlin | kotlin, kt |
+-------------------------+---------------------------------------------------+
| Leaf | leaf |
+-------------------------+---------------------------------------------------+
| Lasso | lasso, ls, lassoscript |
+-------------------------+---------------------------------------------------+
| Less | less |
+-------------------------+---------------------------------------------------+
| LDIF | ldif |
+-------------------------+---------------------------------------------------+
| Lisp | lisp |
+-------------------------+---------------------------------------------------+
| LiveCode Server | livecodeserver |
+-------------------------+---------------------------------------------------+
| LiveScript | livescript, ls |
+-------------------------+---------------------------------------------------+
| Lua | lua |
+-------------------------+---------------------------------------------------+
| Makefile | makefile, mk, mak |
+-------------------------+---------------------------------------------------+
| Markdown | markdown, md, mkdown, mkd |
+-------------------------+---------------------------------------------------+
| Mathematica | mathematica, mma |
+-------------------------+---------------------------------------------------+
| Matlab | matlab |
+-------------------------+---------------------------------------------------+
| Maxima | maxima |
+-------------------------+---------------------------------------------------+
| Maya Embedded Language | mel |
+-------------------------+---------------------------------------------------+
| Mercury | mercury |
+-------------------------+---------------------------------------------------+
| Mizar | mizar |
+-------------------------+---------------------------------------------------+
| Mojolicious | mojolicious |
+-------------------------+---------------------------------------------------+
| Monkey | monkey |
+-------------------------+---------------------------------------------------+
| Moonscript | moonscript, moon |
+-------------------------+---------------------------------------------------+
| N1QL | n1ql |
+-------------------------+---------------------------------------------------+
| NSIS | nsis |
+-------------------------+---------------------------------------------------+
| Nginx | nginx, nginxconf |
+-------------------------+---------------------------------------------------+
| Nimrod | nimrod, nim |
+-------------------------+---------------------------------------------------+
| Nix | nix |
+-------------------------+---------------------------------------------------+
| OCaml | ocaml, ml |
+-------------------------+---------------------------------------------------+
| Objective C | objectivec, mm, objc, obj-c |
+-------------------------+---------------------------------------------------+
| OpenGL Shading Language | glsl |
+-------------------------+---------------------------------------------------+
| OpenSCAD | openscad, scad |
+-------------------------+---------------------------------------------------+
| Oracle Rules Language | ruleslanguage |
+-------------------------+---------------------------------------------------+
| Oxygene | oxygene |
+-------------------------+---------------------------------------------------+
| PF | pf, pf.conf |
+-------------------------+---------------------------------------------------+
| PHP | php, php3, php4, php5, php6 |
+-------------------------+---------------------------------------------------+
| Parser3 | parser3 |
+-------------------------+---------------------------------------------------+
| Perl | perl, pl, pm |
+-------------------------+---------------------------------------------------+
| Plaintext: no highlight | plaintext |
+-------------------------+---------------------------------------------------+
| Pony | pony |
+-------------------------+---------------------------------------------------+
| PostgreSQL & PL/pgSQL | pgsql, postgres, postgresql |
+-------------------------+---------------------------------------------------+
| PowerShell | powershell, ps |
+-------------------------+---------------------------------------------------+
| Processing | processing |
+-------------------------+---------------------------------------------------+
| Prolog | prolog |
+-------------------------+---------------------------------------------------+
| Properties | properties |
+-------------------------+---------------------------------------------------+
| Protocol Buffers | protobuf |
+-------------------------+---------------------------------------------------+
| Puppet | puppet, pp |
+-------------------------+---------------------------------------------------+
| Python | python, py, gyp |
+-------------------------+---------------------------------------------------+
| Python profiler results | profile |
+-------------------------+---------------------------------------------------+
| Q | k, kdb |
+-------------------------+---------------------------------------------------+
| QML | qml |
+-------------------------+---------------------------------------------------+
| R | r |
+-------------------------+---------------------------------------------------+
| ReasonML | reasonml, re |
+-------------------------+---------------------------------------------------+
| RenderMan RIB | rib |
+-------------------------+---------------------------------------------------+
| RenderMan RSL | rsl |
+-------------------------+---------------------------------------------------+
| Roboconf | graph, instances |
+-------------------------+---------------------------------------------------+
| Ruby | ruby, rb, gemspec, podspec, thor, irb |
+-------------------------+---------------------------------------------------+
| Rust | rust, rs |
+-------------------------+---------------------------------------------------+
| SCSS | scss |
+-------------------------+---------------------------------------------------+
| SQL | sql |
+-------------------------+---------------------------------------------------+
| STEP Part 21 | p21, step, stp |
+-------------------------+---------------------------------------------------+
| Scala | scala |
+-------------------------+---------------------------------------------------+
| Scheme | scheme |
+-------------------------+---------------------------------------------------+
| Scilab | scilab, sci |
+-------------------------+---------------------------------------------------+
| Shell | shell, console |
+-------------------------+---------------------------------------------------+
| Smali | smali |
+-------------------------+---------------------------------------------------+
| Smalltalk | smalltalk, st |
+-------------------------+---------------------------------------------------+
| Stan | stan |
+-------------------------+---------------------------------------------------+
| Stata | stata |
+-------------------------+---------------------------------------------------+
| SAS | SAS, sas |
+-------------------------+---------------------------------------------------+
| Stylus | stylus, styl |
+-------------------------+---------------------------------------------------+
| SubUnit | subunit |
+-------------------------+---------------------------------------------------+
| Swift | swift |
+-------------------------+---------------------------------------------------+
| Test Anything Protocol | tap |
+-------------------------+---------------------------------------------------+
| Tcl | tcl, tk |
+-------------------------+---------------------------------------------------+
| TeX | tex |
+-------------------------+---------------------------------------------------+
| Thrift | thrift |
+-------------------------+---------------------------------------------------+
| TP | tp |
+-------------------------+---------------------------------------------------+
| Twig | twig, craftcms |
+-------------------------+---------------------------------------------------+
| TypeScript | typescript, ts |
+-------------------------+---------------------------------------------------+
| VB.Net | vbnet, vb |
+-------------------------+---------------------------------------------------+
| VBScript | vbscript, vbs |
+-------------------------+---------------------------------------------------+
| VHDL | vhdl |
+-------------------------+---------------------------------------------------+
| Vala | vala |
+-------------------------+---------------------------------------------------+
| Verilog | verilog, v |
+-------------------------+---------------------------------------------------+
| Vim Script | vim |
+-------------------------+---------------------------------------------------+
| x86 Assembly | x86asm |
+-------------------------+---------------------------------------------------+
| XL | xl, tao |
+-------------------------+---------------------------------------------------+
| XQuery | xquery, xpath, xq |
+-------------------------+---------------------------------------------------+
| Zephir | zephir, zep |
+-------------------------+---------------------------------------------------+

View File

@ -0,0 +1,44 @@
.. highlight.js documentation master file, created by
sphinx-quickstart on Wed Sep 12 23:48:27 2012.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
``highlight.js`` developer documentation
==========================================
Contents:
.. toctree::
:maxdepth: 1
api
language-guide
reference
css-classes-reference
style-guide
language-contribution
building-testing
maintainers-guide
Miscellaneous:
.. toctree::
:maxdepth: 1
line-numbers
language-requests
Links:
- Code: https://github.com/highlightjs/highlight.js
- Discussion: http://groups.google.com/group/highlightjs
- Bug tracking: https://github.com/highlightjs/highlight.js/issues
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

View File

@ -0,0 +1,77 @@
Language contributor checklist
==============================
1. Put language definition into a .js file
------------------------------------------
The file defines a function accepting a reference to the library and returning a language object.
The library parameter is useful to access common modes and regexps. You should not immediately call this function,
this is done during the build process and details differ for different build targets.
::
function(hljs) {
return {
keywords: 'foo bar',
contains: [ ..., hljs.NUMBER_MODE, ... ]
}
}
The name of the file is used as a short language identifier and should be usable as a class name in HTML and CSS.
2. Provide meta data
--------------------
At the top of the file there is a specially formatted comment with meta data processed by a build system.
Meta data format is simply key-value pairs each occupying its own line:
::
/*
Language: Superlanguage
Requires: java.js, sql.js
Author: John Smith <email@domain.com>
Contributors: Mike Johnson <...@...>, Matt Wilson <...@...>
Description: Some cool language definition
*/
``Language`` — the only required header giving a human-readable language name.
``Requires`` — a list of other language files required for this language to work.
This make it possible to describe languages that extend definitions of other ones.
Required files aren't processed in any special way.
The build system just makes sure that they will be in the final package in
``LANGUAGES`` object.
The meaning of the other headers is pretty obvious.
3. Create a code example
------------------------
The code example is used both to test language detection and for the demo page
on https://highlightjs.org/. Put it in ``test/detect/<language>/default.txt``.
Take inspiration from other languages in ``test/detect/`` and read
:ref:`testing instructions <basic-testing>` for more details.
4. Write class reference
------------------------
Class reference lives in the :doc:`CSS classes reference </css-classes-reference>`..
Describe shortly names of all meaningful modes used in your language definition.
5. Add yourself to AUTHORS.*.txt and CHANGES.md
-----------------------------------------------
If you're a new contributor add yourself to the authors list.
Also it will be good to update CHANGES.md.
6. Create a pull request
------------------------
Send your contribution as a pull request on GitHub.

View File

@ -0,0 +1,264 @@
Language definition guide
=========================
Highlighting overview
---------------------
Programming language code consists of parts with different rules of parsing: keywords like ``for`` or ``if``
don't make sense inside strings, strings may contain backslash-escaped symbols like ``\"``
and comments usually don't contain anything interesting except the end of the comment.
In highlight.js such parts are called "modes".
Each mode consists of:
* starting condition
* ending condition
* list of contained sub-modes
* lexing rules and keywords
* …exotic stuff like another language inside a language
The parser's work is to look for modes and their keywords.
Upon finding, it wraps them into the markup ``<span class="...">...</span>``
and puts the name of the mode ("string", "comment", "number")
or a keyword group name ("keyword", "literal", "built-in") as the span's class name.
General syntax
--------------
A language definition is a JavaScript object describing the default parsing mode for the language.
This default mode contains sub-modes which in turn contain other sub-modes, effectively making the language definition a tree of modes.
Here's an example:
::
{
case_insensitive: true, // language is case-insensitive
keywords: 'for if while',
contains: [
{
className: 'string',
begin: '"', end: '"'
},
hljs.COMMENT(
'/\\*', // begin
'\\*/', // end
{
contains: [
{
className: 'doc', begin: '@\\w+'
}
]
}
)
]
}
Usually the default mode accounts for the majority of the code and describes all language keywords.
A notable exception here is XML in which a default mode is just a user text that doesn't contain any keywords,
and most interesting parsing happens inside tags.
Keywords
--------
In the simple case language keywords are defined in a string, separated by space:
::
{
keywords: 'else for if while'
}
Some languages have different kinds of "keywords" that might not be called as such by the language spec
but are very close to them from the point of view of a syntax highlighter. These are all sorts of "literals", "built-ins", "symbols" and such.
To define such keyword groups the attribute ``keywords`` becomes an object each property of which defines its own group of keywords:
::
{
keywords: {
keyword: 'else for if while',
literal: 'false true null'
}
}
The group name becomes then a class name in a generated markup enabling different styling for different kinds of keywords.
To detect keywords highlight.js breaks the processed chunk of code into separate words — a process called lexing.
The "word" here is defined by the regexp ``[a-zA-Z][a-zA-Z0-9_]*`` that works for keywords in most languages.
Different lexing rules can be defined by the ``lexemes`` attribute:
::
{
lexemes: '-[a-z]+',
keywords: '-import -export'
}
Sub-modes
---------
Sub-modes are listed in the ``contains`` attribute:
::
{
keywords: '...',
contains: [
hljs.QUOTE_STRING_MODE,
hljs.C_LINE_COMMENT,
{ ... custom mode definition ... }
]
}
A mode can reference itself in the ``contains`` array by using a special keyword ``'self``'.
This is commonly used to define nested modes:
::
{
className: 'object',
begin: '{', end: '}',
contains: [hljs.QUOTE_STRING_MODE, 'self']
}
Comments
--------
To define custom comments it is recommended to use a built-in helper function ``hljs.COMMENT`` instead of describing the mode directly, as it also defines a few default sub-modes that improve language detection and do other nice things.
Parameters for the function are:
::
hljs.COMMENT(
begin, // begin regex
end, // end regex
extra // optional object with extra attributes to override defaults
// (for example {relevance: 0})
)
Markup generation
-----------------
Modes usually generate actual highlighting markup — ``<span>`` elements with specific class names that are defined by the ``className`` attribute:
::
{
contains: [
{
className: 'string',
// ... other attributes
},
{
className: 'number',
// ...
}
]
}
Names are not required to be unique, it's quite common to have several definitions with the same name.
For example, many languages have various syntaxes for strings, comments, etc…
Sometimes modes are defined only to support specific parsing rules and aren't needed in the final markup.
A classic example is an escaping sequence inside strings allowing them to contain an ending quote.
::
{
className: 'string',
begin: '"', end: '"',
contains: [{begin: '\\\\.'}],
}
For such modes ``className`` attribute should be omitted so they won't generate excessive markup.
Mode attributes
---------------
Other useful attributes are defined in the :doc:`mode reference </reference>`.
.. _relevance:
Relevance
---------
Highlight.js tries to automatically detect the language of a code fragment.
The heuristics is essentially simple: it tries to highlight a fragment with all the language definitions
and the one that yields most specific modes and keywords wins. The job of a language definition
is to help this heuristics by hinting relative relevance (or irrelevance) of modes.
This is best illustrated by example. Python has special kinds of strings defined by prefix letters before the quotes:
``r"..."``, ``u"..."``. If a code fragment contains such strings there is a good chance that it's in Python.
So these string modes are given high relevance:
::
{
className: 'string',
begin: 'r"', end: '"',
relevance: 10
}
On the other hand, conventional strings in plain single or double quotes aren't specific to any language
and it makes sense to bring their relevance to zero to lessen statistical noise:
::
{
className: 'string',
begin: '"', end: '"',
relevance: 0
}
The default value for relevance is 1. When setting an explicit value it's recommended to use either 10 or 0.
Keywords also influence relevance. Each of them usually has a relevance of 1, but there are some unique names
that aren't likely to be found outside of their languages, even in the form of variable names.
For example just having ``reinterpret_cast`` somewhere in the code is a good indicator that we're looking at C++.
It's worth to set relevance of such keywords a bit higher. This is done with a pipe:
::
{
keywords: 'for if reinterpret_cast|10'
}
Illegal symbols
---------------
Another way to improve language detection is to define illegal symbols for a mode.
For example in Python first line of class definition (``class MyClass(object):``) cannot contain symbol "{" or a newline.
Presence of these symbols clearly shows that the language is not Python and the parser can drop this attempt early.
Illegal symbols are defined as a a single regular expression:
::
{
className: 'class',
illegal: '[${]'
}
Pre-defined modes and regular expressions
-----------------------------------------
Many languages share common modes and regular expressions. Such expressions are defined in core highlight.js code
at the end under "Common regexps" and "Common modes" titles. Use them when possible.
Contributing
------------
Follow the :doc:`contributor checklist </language-contribution>`.

View File

@ -0,0 +1,17 @@
On requesting new languages
===========================
This is a general answer to requests for adding new languages that appear from
time to time in the highlight.js issue tracker and discussion group.
Highlight.js doesn't have a fundamental plan for implementing languages,
instead the project works by accepting language definitions from
interested contributors. There are also no rules at the moment forbidding
any languages from being added to the library, no matter how obscure or
weird.
This means that there's no point in requesting a new language without
providing an implementation for it. If you want to see a particular language
included in highlight.js but cannot implement it, the best way to make it
happen is to get another developer interested in doing so. Here's our
:doc:`language-guide`.

View File

@ -0,0 +1,39 @@
Line numbers
============
Highlight.js' notable lack of line numbers support is not an oversight but a
feature. Following is the explanation of this policy from the current project
maintainer (hey guys!):
One of the defining design principles for highlight.js from the start was
simplicity. Not the simplicity of code (in fact, it's quite complex) but
the simplicity of usage and of the actual look of highlighted snippets on
HTML pages. Many highlighters, in my opinion, are overdoing it with such
things as separate colors for every single type of lexemes, striped
backgrounds, fancy buttons around code blocks and — yes — line numbers.
The more fancy stuff resides around the code the more it distracts a
reader from understanding it.
This is why it's not a straightforward decision: this new feature will not
just make highlight.js better, it might actually make it worse simply by
making it look more bloated in blog posts around the Internet. This is why
I'm asking people to show that it's worth it.
The only real use-case that ever was brought up in support of line numbers
is referencing code from the descriptive text around it. On my own blog I
was always solving this either with comments within the code itself or by
breaking the larger snippets into smaller ones and describing each small
part separately. I'm not saying that my solution is better. But I don't
see how line numbers are better either. And the only way to show that they
are better is to set up some usability research on the subject. I doubt
anyone would bother to do it.
Then there's maintenance. So far the core code of highlight.js is
maintained by only one person — yours truly. Inclusion of any new code in
highlight.js means that from that moment I will have to fix bugs in it,
improve it further, make it work together with the rest of the code,
defend its design. And I don't want to do all this for the feature that I
consider "evil" and probably will never use myself.
This position is `subject to discuss <http://groups.google.com/group/highlightjs>`_.
Also it doesn't stop anyone from forking the code and maintaining line-numbers implementation separately.

View File

@ -0,0 +1,34 @@
Maintainer's guide
==================
Commit policy
-------------
* Pull requests from outside contributors require a review from a maintainer.
* Maintainers should avoid working on a master branch directly and create branches for everything. A code review from another maintainer is recommended but not required, use your best judgment.
Release process
---------------
Releases happen on a 6-week schedule. Currently due to a long break the date of the next release is not set.
* Update CHANGES.md with everything interesting since the last update.
* Update version numbers using the three-part x.y.z notation everywhere:
* The header in CHANGES.md (this is where the site looks for the latest version number)
* ``"version"`` attribute in package.json
* ``"version"`` attribute in package-lock.json (run `npm install`)
* Two places in docs/conf.py (``version`` and ``release``)
* Commit the version changes and tag the commit with the plain version number (no "v." or anything like that)
* Push the commit and the tags to master (``git push && git push --tags``)
Pushing the tag triggers the update process which can be monitored at http://highlightjs.org/api/release/
When something didn't work *and* it's fixable in code (version numbers mismatch, last minute patches, etc), simply make another release incrementing the third (revision) part of the version number.

View File

@ -0,0 +1,360 @@
Mode reference
==============
Types
-----
Types of attributes values in this reference:
+------------+-------------------------------------------------------------------------------------+
| identifier | String suitable to be used as a Javascript variable and CSS class name |
| | (i.e. mostly ``/[A-Za-z0-9_]+/``) |
+------------+-------------------------------------------------------------------------------------+
| regexp | String representing a Javascript regexp. |
| | Note that since it's not a literal regexp all back-slashes should be repeated twice |
+------------+-------------------------------------------------------------------------------------+
| boolean | Javascript boolean: ``true`` or ``false`` |
+------------+-------------------------------------------------------------------------------------+
| number | Javascript number |
+------------+-------------------------------------------------------------------------------------+
| object | Javascript object: ``{ ... }`` |
+------------+-------------------------------------------------------------------------------------+
| array | Javascript array: ``[ ... ]`` |
+------------+-------------------------------------------------------------------------------------+
Attributes
----------
case_insensitive
^^^^^^^^^^^^^^^^
**type**: boolean
Case insensitivity of language keywords and regexps. Used only on the top-level mode.
aliases
^^^^^^^
**type**: array
A list of additional names (besides the canonical one given by the filename) that can be used to identify a language in HTML classes and in a call to :ref:`getLanguage <getLanguage>`.
className
^^^^^^^^^
**type**: identifier
The name of the mode. It is used as a class name in HTML markup.
Multiple modes can have the same name. This is useful when a language has multiple variants of syntax
for one thing like string in single or double quotes.
begin
^^^^^
**type**: regexp
Regular expression starting a mode. For example a single quote for strings or two forward slashes for C-style comments.
If absent, ``begin`` defaults to a regexp that matches anything, so the mode starts immediately.
end
^^^
**type**: regexp
Regular expression ending a mode. For example a single quote for strings or "$" (end of line) for one-line comments.
It's often the case that a beginning regular expression defines the entire mode and doesn't need any special ending.
For example a number can be defined with ``begin: "\\b\\d+"`` which spans all the digits.
If absent, ``end`` defaults to a regexp that matches anything, so the mode ends immediately.
Sometimes a mode can end not by itself but implicitly with its containing (parent) mode.
This is achieved with :ref:`endsWithParent <endsWithParent>` attribute.
beginKeywords
^^^^^^^^^^^^^^^^
**type**: string
Used instead of ``begin`` for modes starting with keywords to avoid needless repetition:
::
{
begin: '\\b(extends|implements) ',
keywords: 'extends implements'
}
… becomes:
::
{
beginKeywords: 'extends implements'
}
Unlike the :ref:`keywords <keywords>` attribute, this one allows only a simple list of space separated keywords.
If you do need additional features of ``keywords`` or you just need more keywords for this mode you may include ``keywords`` along with ``beginKeywords``.
.. _endsWithParent:
endsWithParent
^^^^^^^^^^^^^^
**type**: boolean
A flag showing that a mode ends when its parent ends.
This is best demonstrated by example. In CSS syntax a selector has a set of rules contained within symbols "{" and "}".
Individual rules separated by ";" but the last one in a set can omit the terminating semicolon:
::
p {
width: 100%; color: red
}
This is when ``endsWithParent`` comes into play:
::
{
className: 'rules', begin: '{', end: '}',
contains: [
{className: 'rule', /* ... */ end: ';', endsWithParent: true}
]
}
.. _endsParent:
endsParent
^^^^^^^^^^^^^^
**type**: boolean
Forces closing of the parent mode right after the current mode is closed.
This is used for modes that don't have an easily expressible ending lexeme but
instead could be closed after the last interesting sub-mode is found.
Here's an example with two ways of defining functions in Elixir, one using a
keyword ``do`` and another using a comma:
::
def foo :clear, list do
:ok
end
def foo, do: IO.puts "hello world"
Note that in the first case the parameter list after the function title may also
include a comma. And if we're only interested in highlighting a title we can
tell it to end the function definition after itself:
::
{
className: 'function',
beginKeywords: 'def', end: /\B\b/,
contains: [
{
className: 'title',
begin: hljs.IDENT_RE, endsParent: true
}
]
}
(The ``end: /\B\b/`` regex tells function to never end by itself.)
.. _endSameAsBegin:
endSameAsBegin
^^^^^^^^^^^^^^
**type**: boolean
Acts as ``end`` matching exactly the same string that was found by the
corresponding ``begin`` regexp.
For example, in PostgreSQL string constants can uee "dollar quotes",
consisting of a dollar sign, an optional tag of zero or more characters,
and another dollar sign. String constant must be ended with the same
construct using the same tag. It is possible to nest dollar-quoted string
constants by choosing different tags at each nesting level:
::
$foo$
...
$bar$ nested $bar$
...
$foo$
In this case you can't simply specify the same regexp for ``begin`` and
``end`` (say, ``"\\$[a-z]\\$"``), but you can use ``begin: "\\$[a-z]\\$"``
and ``endSameAsBegin: true``.
.. _lexemes:
lexemes
^^^^^^^
**type**: regexp
A regular expression that extracts individual lexemes from language text to find :ref:`keywords <keywords>` among them.
Default value is ``hljs.IDENT_RE`` which works for most languages.
.. _keywords:
keywords
^^^^^^^^
**type**: object
Keyword definition comes in two forms:
* ``'for while if else weird_voodoo|10 ... '`` -- a string of space-separated keywords with an optional relevance over a pipe
* ``{'keyword': ' ... ', 'literal': ' ... '}`` -- an object whose keys are names of different kinds of keywords and values are keyword definition strings in the first form
For detailed explanation see :doc:`Language definition guide </language-guide>`.
illegal
^^^^^^^
**type**: regexp
A regular expression that defines symbols illegal for the mode.
When the parser finds a match for illegal expression it immediately drops parsing the whole language altogether.
excludeBegin, excludeEnd
^^^^^^^^^^^^^^^^^^^^^^^^
**type**: boolean
Exclude beginning or ending lexemes out of mode's generated markup. For example in CSS syntax a rule ends with a semicolon.
However visually it's better not to color it as the rule contents. Having ``excludeEnd: true`` forces a ``<span>`` element for the rule to close before the semicolon.
returnBegin
^^^^^^^^^^^
**type**: boolean
Returns just found beginning lexeme back into parser. This is used when beginning of a sub-mode is a complex expression
that should not only be found within a parent mode but also parsed according to the rules of a sub-mode.
Since the parser is effectively goes back it's quite possible to create a infinite loop here so use with caution!
returnEnd
^^^^^^^^^
**type**: boolean
Returns just found ending lexeme back into parser. This is used for example to parse Javascript embedded into HTML.
A Javascript block ends with the HTML closing tag ``</script>`` that cannot be parsed with Javascript rules.
So it is returned back into its parent HTML mode that knows what to do with it.
Since the parser is effectively goes back it's quite possible to create a infinite loop here so use with caution!
contains
^^^^^^^^
**type**: array
The list of sub-modes that can be found inside the mode. For detailed explanation see :doc:`Language definition guide </language-guide>`.
starts
^^^^^^
**type**: identifier
The name of the mode that will start right after the current mode ends. The new mode won't be contained within the current one.
Currently this attribute is used to highlight Javascript and CSS contained within HTML.
Tags ``<script>`` and ``<style>`` start sub-modes that use another language definition to parse their contents (see :ref:`subLanguage`).
variants
^^^^^^^^
**type**: array
Modification to the main definitions of the mode, effectively expanding it into several similar modes
each having all the attributes from the main definition augmented or overridden by the variants::
{
className: 'string',
contains: [hljs.BACKSLASH_ESCAPE],
relevance: 0,
variants: [
{begin: /"/, end: /"/},
{begin: /'/, end: /'/, relevance: 1}
]
}
.. _subLanguage:
subLanguage
^^^^^^^^^^^
**type**: string or array
Highlights the entire contents of the mode with another language.
When using this attribute there's no point to define internal parsing rules like :ref:`lexemes` or :ref:`keywords`. Also it is recommended to skip ``className`` attribute since the sublanguage will wrap the text in its own ``<span class="language-name">``.
The value of the attribute controls which language or languages will be used for highlighting:
* language name: explicit highlighting with the specified language
* empty array: auto detection with all the languages available
* array of language names: auto detection constrained to the specified set
skip
^^^^
**type**: boolean
Skips any markup processing for the mode ensuring that it remains a part of its
parent buffer along with the starting and the ending lexemes. This works in
conjunction with the parent's :ref:`subLanguage` when it requires complex
parsing.
Consider parsing PHP inside HTML::
<p><? echo 'PHP'; /* ?> */ ?></p>
The ``?>`` inside the comment should **not** end the PHP part, so we have to
handle pairs of ``/* .. */`` to correctly find the ending ``?>``::
{
begin: /<\?/, end: /\?>/,
subLanguage: 'php',
contains: [{begin: '/\\*', end: '\\*/', skip: true}]
}
Without ``skip: true`` every comment would cause the parser to drop out back
into the HTML mode.
disableAutodetect
^^^^^^^^^^^^^^^^^
**type**: boolean
Disables autodetection for this language.

View File

@ -0,0 +1,106 @@
Style guide
===========
Key principle
-------------
Highlight.js themes are language agnostic.
Instead of trying to make a *rich* set of highlightable classes look good in a
handful of languages we have a *limited* set of classes that work for all
languages.
Hence, there are two important implications:
* Highlight.js styles tend to be minimalistic.
* It's not possible to exactly emulate themes from other highlighting engines.
Defining a theme
----------------
A theme is a single CSS defining styles for class names listed in the
:doc:`class reference </css-classes-reference>`. The general guideline is to
style all available classes, however an author may deliberately choose to
exclude some (for example, ``.attr`` is usually left unstyled).
You are not required to invent a separate styling for every group of class
names, it's perfectly okay to group them:
::
.hljs-string,
.hljs-section,
.hljs-selector-class,
.hljs-template-variable,
.hljs-deletion {
color: #800;
}
Use as few or as many unique style combinations as you want.
Typography and layout dos and don'ts
------------------------------------
Don't use:
* non-standard borders/margin/paddings for the root container ``.hljs``
* specific font faces
* font size, line height and anything that affects position and size of
characters within the container
Okay to use:
* colors (obviously!)
* italic, bold, underlining, etc.
* image backgrounds
These may seem arbitrary at first but it's what has shown to make sense in
practice.
There's also a common set of rules that *has* to be defined for the root
container verbatim:
::
.hljs {
display: block;
overflow-x: auto;
padding: 0.5em;
}
``.subst``
----------
One important caveat: don't forget to style ``.subst``. It's used for parsed
sections within strings and almost always should be reset to the default color:
::
.hljs,
.hljs-subst {
color: black;
}
Contributing
------------
You should include a comment at the top of the CSS file with attribution and
other meta data if necessary. The format is free:
::
/*
Fancy style (c) John Smith <email@domain.com>
*/
If you're a new contributor add yourself to the authors list in AUTHORS.en.txt
Also update CHANGES.md with your contribution.
Send your contribution as a pull request on GitHub.

2040
highlight-js/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

46
highlight-js/package.json Normal file
View File

@ -0,0 +1,46 @@
{
"name": "highlight.js",
"description": "Syntax highlighting with language autodetection.",
"keywords": [
"highlight",
"syntax"
],
"homepage": "https://highlightjs.org/",
"version": "9.13.1",
"author": {
"name": "Ivan Sagalaev",
"email": "maniac@softwaremaniacs.org"
},
"contributors": [],
"bugs": {
"url": "https://github.com/highlightjs/highlight.js/issues"
},
"license": "BSD-3-Clause",
"repository": {
"type": "git",
"url": "git://github.com/highlightjs/highlight.js.git"
},
"main": "./lib/index.js",
"scripts": {
"mocha": "mocha",
"test": "mocha --globals document test",
"test-browser": "mocha --globals document test/browser"
},
"engines": {
"node": "*"
},
"devDependencies": {
"bluebird": "^3.5.1",
"commander": "^2.3.0",
"del": "^3.0.0",
"gear": "^0.9.4",
"gear-lib": "^0.9.2",
"glob": "^7.0.3",
"js-beautify": "^1.5.10",
"jsdom": "^9.2.1",
"lodash": "^4.0.0",
"mocha": "^5.2.0",
"should": "^13.2.3",
"tiny-worker": "^2.1.2"
}
}

View File

@ -0,0 +1,834 @@
/*
Syntax highlighting with language autodetection.
https://highlightjs.org/
*/
(function(factory) {
// Find the global object for export to both the browser and web workers.
var globalObject = typeof window === 'object' && window ||
typeof self === 'object' && self;
// Setup highlight.js for different environments. First is Node.js or
// CommonJS.
if(typeof exports !== 'undefined') {
factory(exports);
} else if(globalObject) {
// Export hljs globally even when using AMD for cases when this script
// is loaded with others that may still expect a global hljs.
globalObject.hljs = factory({});
// Finally register the global hljs with AMD.
if(typeof define === 'function' && define.amd) {
define([], function() {
return globalObject.hljs;
});
}
}
}(function(hljs) {
// Convenience variables for build-in objects
var ArrayProto = [],
objectKeys = Object.keys;
// Global internal variables used within the highlight.js library.
var languages = {},
aliases = {};
// Regular expressions used throughout the highlight.js library.
var noHighlightRe = /^(no-?highlight|plain|text)$/i,
languagePrefixRe = /\blang(?:uage)?-([\w-]+)\b/i,
fixMarkupRe = /((^(<[^>]+>|\t|)+|(?:\n)))/gm;
var spanEndTag = '</span>';
// Global options used when within external APIs. This is modified when
// calling the `hljs.configure` function.
var options = {
classPrefix: 'hljs-',
tabReplace: null,
useBR: false,
languages: undefined
};
/* Utility functions */
function escape(value) {
return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
function tag(node) {
return node.nodeName.toLowerCase();
}
function testRe(re, lexeme) {
var match = re && re.exec(lexeme);
return match && match.index === 0;
}
function isNotHighlighted(language) {
return noHighlightRe.test(language);
}
function blockLanguage(block) {
var i, match, length, _class;
var classes = block.className + ' ';
classes += block.parentNode ? block.parentNode.className : '';
// language-* takes precedence over non-prefixed class names.
match = languagePrefixRe.exec(classes);
if (match) {
return getLanguage(match[1]) ? match[1] : 'no-highlight';
}
classes = classes.split(/\s+/);
for (i = 0, length = classes.length; i < length; i++) {
_class = classes[i];
if (isNotHighlighted(_class) || getLanguage(_class)) {
return _class;
}
}
}
function inherit(parent) { // inherit(parent, override_obj, override_obj, ...)
var key;
var result = {};
var objects = Array.prototype.slice.call(arguments, 1);
for (key in parent)
result[key] = parent[key];
objects.forEach(function(obj) {
for (key in obj)
result[key] = obj[key];
});
return result;
}
/* Stream merging */
function nodeStream(node) {
var result = [];
(function _nodeStream(node, offset) {
for (var child = node.firstChild; child; child = child.nextSibling) {
if (child.nodeType === 3)
offset += child.nodeValue.length;
else if (child.nodeType === 1) {
result.push({
event: 'start',
offset: offset,
node: child
});
offset = _nodeStream(child, offset);
// Prevent void elements from having an end tag that would actually
// double them in the output. There are more void elements in HTML
// but we list only those realistically expected in code display.
if (!tag(child).match(/br|hr|img|input/)) {
result.push({
event: 'stop',
offset: offset,
node: child
});
}
}
}
return offset;
})(node, 0);
return result;
}
function mergeStreams(original, highlighted, value) {
var processed = 0;
var result = '';
var nodeStack = [];
function selectStream() {
if (!original.length || !highlighted.length) {
return original.length ? original : highlighted;
}
if (original[0].offset !== highlighted[0].offset) {
return (original[0].offset < highlighted[0].offset) ? original : highlighted;
}
/*
To avoid starting the stream just before it should stop the order is
ensured that original always starts first and closes last:
if (event1 == 'start' && event2 == 'start')
return original;
if (event1 == 'start' && event2 == 'stop')
return highlighted;
if (event1 == 'stop' && event2 == 'start')
return original;
if (event1 == 'stop' && event2 == 'stop')
return highlighted;
... which is collapsed to:
*/
return highlighted[0].event === 'start' ? original : highlighted;
}
function open(node) {
function attr_str(a) {return ' ' + a.nodeName + '="' + escape(a.value).replace('"', '&quot;') + '"';}
result += '<' + tag(node) + ArrayProto.map.call(node.attributes, attr_str).join('') + '>';
}
function close(node) {
result += '</' + tag(node) + '>';
}
function render(event) {
(event.event === 'start' ? open : close)(event.node);
}
while (original.length || highlighted.length) {
var stream = selectStream();
result += escape(value.substring(processed, stream[0].offset));
processed = stream[0].offset;
if (stream === original) {
/*
On any opening or closing tag of the original markup we first close
the entire highlighted node stack, then render the original tag along
with all the following original tags at the same offset and then
reopen all the tags on the highlighted stack.
*/
nodeStack.reverse().forEach(close);
do {
render(stream.splice(0, 1)[0]);
stream = selectStream();
} while (stream === original && stream.length && stream[0].offset === processed);
nodeStack.reverse().forEach(open);
} else {
if (stream[0].event === 'start') {
nodeStack.push(stream[0].node);
} else {
nodeStack.pop();
}
render(stream.splice(0, 1)[0]);
}
}
return result + escape(value.substr(processed));
}
/* Initialization */
function expand_mode(mode) {
if (mode.variants && !mode.cached_variants) {
mode.cached_variants = mode.variants.map(function(variant) {
return inherit(mode, {variants: null}, variant);
});
}
return mode.cached_variants || (mode.endsWithParent && [inherit(mode)]) || [mode];
}
function compileLanguage(language) {
function reStr(re) {
return (re && re.source) || re;
}
function langRe(value, global) {
return new RegExp(
reStr(value),
'm' + (language.case_insensitive ? 'i' : '') + (global ? 'g' : '')
);
}
function compileMode(mode, parent) {
if (mode.compiled)
return;
mode.compiled = true;
mode.keywords = mode.keywords || mode.beginKeywords;
if (mode.keywords) {
var compiled_keywords = {};
var flatten = function(className, str) {
if (language.case_insensitive) {
str = str.toLowerCase();
}
str.split(' ').forEach(function(kw) {
var pair = kw.split('|');
compiled_keywords[pair[0]] = [className, pair[1] ? Number(pair[1]) : 1];
});
};
if (typeof mode.keywords === 'string') { // string
flatten('keyword', mode.keywords);
} else {
objectKeys(mode.keywords).forEach(function (className) {
flatten(className, mode.keywords[className]);
});
}
mode.keywords = compiled_keywords;
}
mode.lexemesRe = langRe(mode.lexemes || /\w+/, true);
if (parent) {
if (mode.beginKeywords) {
mode.begin = '\\b(' + mode.beginKeywords.split(' ').join('|') + ')\\b';
}
if (!mode.begin)
mode.begin = /\B|\b/;
mode.beginRe = langRe(mode.begin);
if (mode.endSameAsBegin)
mode.end = mode.begin;
if (!mode.end && !mode.endsWithParent)
mode.end = /\B|\b/;
if (mode.end)
mode.endRe = langRe(mode.end);
mode.terminator_end = reStr(mode.end) || '';
if (mode.endsWithParent && parent.terminator_end)
mode.terminator_end += (mode.end ? '|' : '') + parent.terminator_end;
}
if (mode.illegal)
mode.illegalRe = langRe(mode.illegal);
if (mode.relevance == null)
mode.relevance = 1;
if (!mode.contains) {
mode.contains = [];
}
mode.contains = Array.prototype.concat.apply([], mode.contains.map(function(c) {
return expand_mode(c === 'self' ? mode : c);
}));
mode.contains.forEach(function(c) {compileMode(c, mode);});
if (mode.starts) {
compileMode(mode.starts, parent);
}
var terminators =
mode.contains.map(function(c) {
return c.beginKeywords ? '\\.?(' + c.begin + ')\\.?' : c.begin;
})
.concat([mode.terminator_end, mode.illegal])
.map(reStr)
.filter(Boolean);
mode.terminators = terminators.length ? langRe(terminators.join('|'), true) : {exec: function(/*s*/) {return null;}};
}
compileMode(language);
}
/*
Core highlighting function. Accepts a language name, or an alias, and a
string with the code to highlight. Returns an object with the following
properties:
- relevance (int)
- value (an HTML string with highlighting markup)
*/
function highlight(name, value, ignore_illegals, continuation) {
function escapeRe(value) {
return new RegExp(value.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'm');
}
function subMode(lexeme, mode) {
var i, length;
for (i = 0, length = mode.contains.length; i < length; i++) {
if (testRe(mode.contains[i].beginRe, lexeme)) {
if (mode.contains[i].endSameAsBegin) {
mode.contains[i].endRe = escapeRe( mode.contains[i].beginRe.exec(lexeme)[0] );
}
return mode.contains[i];
}
}
}
function endOfMode(mode, lexeme) {
if (testRe(mode.endRe, lexeme)) {
while (mode.endsParent && mode.parent) {
mode = mode.parent;
}
return mode;
}
if (mode.endsWithParent) {
return endOfMode(mode.parent, lexeme);
}
}
function isIllegal(lexeme, mode) {
return !ignore_illegals && testRe(mode.illegalRe, lexeme);
}
function keywordMatch(mode, match) {
var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];
return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];
}
function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {
var classPrefix = noPrefix ? '' : options.classPrefix,
openSpan = '<span class="' + classPrefix,
closeSpan = leaveOpen ? '' : spanEndTag;
openSpan += classname + '">';
return openSpan + insideSpan + closeSpan;
}
function processKeywords() {
var keyword_match, last_index, match, result;
if (!top.keywords)
return escape(mode_buffer);
result = '';
last_index = 0;
top.lexemesRe.lastIndex = 0;
match = top.lexemesRe.exec(mode_buffer);
while (match) {
result += escape(mode_buffer.substring(last_index, match.index));
keyword_match = keywordMatch(top, match);
if (keyword_match) {
relevance += keyword_match[1];
result += buildSpan(keyword_match[0], escape(match[0]));
} else {
result += escape(match[0]);
}
last_index = top.lexemesRe.lastIndex;
match = top.lexemesRe.exec(mode_buffer);
}
return result + escape(mode_buffer.substr(last_index));
}
function processSubLanguage() {
var explicit = typeof top.subLanguage === 'string';
if (explicit && !languages[top.subLanguage]) {
return escape(mode_buffer);
}
var result = explicit ?
highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) :
highlightAuto(mode_buffer, top.subLanguage.length ? top.subLanguage : undefined);
// Counting embedded language score towards the host language may be disabled
// with zeroing the containing mode relevance. Usecase in point is Markdown that
// allows XML everywhere and makes every XML snippet to have a much larger Markdown
// score.
if (top.relevance > 0) {
relevance += result.relevance;
}
if (explicit) {
continuations[top.subLanguage] = result.top;
}
return buildSpan(result.language, result.value, false, true);
}
function processBuffer() {
result += (top.subLanguage != null ? processSubLanguage() : processKeywords());
mode_buffer = '';
}
function startNewMode(mode) {
result += mode.className? buildSpan(mode.className, '', true): '';
top = Object.create(mode, {parent: {value: top}});
}
function processLexeme(buffer, lexeme) {
mode_buffer += buffer;
if (lexeme == null) {
processBuffer();
return 0;
}
var new_mode = subMode(lexeme, top);
if (new_mode) {
if (new_mode.skip) {
mode_buffer += lexeme;
} else {
if (new_mode.excludeBegin) {
mode_buffer += lexeme;
}
processBuffer();
if (!new_mode.returnBegin && !new_mode.excludeBegin) {
mode_buffer = lexeme;
}
}
startNewMode(new_mode, lexeme);
return new_mode.returnBegin ? 0 : lexeme.length;
}
var end_mode = endOfMode(top, lexeme);
if (end_mode) {
var origin = top;
if (origin.skip) {
mode_buffer += lexeme;
} else {
if (!(origin.returnEnd || origin.excludeEnd)) {
mode_buffer += lexeme;
}
processBuffer();
if (origin.excludeEnd) {
mode_buffer = lexeme;
}
}
do {
if (top.className) {
result += spanEndTag;
}
if (!top.skip && !top.subLanguage) {
relevance += top.relevance;
}
top = top.parent;
} while (top !== end_mode.parent);
if (end_mode.starts) {
if (end_mode.endSameAsBegin) {
end_mode.starts.endRe = end_mode.endRe;
}
startNewMode(end_mode.starts, '');
}
return origin.returnEnd ? 0 : lexeme.length;
}
if (isIllegal(lexeme, top))
throw new Error('Illegal lexeme "' + lexeme + '" for mode "' + (top.className || '<unnamed>') + '"');
/*
Parser should not reach this point as all types of lexemes should be caught
earlier, but if it does due to some bug make sure it advances at least one
character forward to prevent infinite looping.
*/
mode_buffer += lexeme;
return lexeme.length || 1;
}
var language = getLanguage(name);
if (!language) {
throw new Error('Unknown language: "' + name + '"');
}
compileLanguage(language);
var top = continuation || language;
var continuations = {}; // keep continuations for sub-languages
var result = '', current;
for(current = top; current !== language; current = current.parent) {
if (current.className) {
result = buildSpan(current.className, '', true) + result;
}
}
var mode_buffer = '';
var relevance = 0;
try {
var match, count, index = 0;
while (true) {
top.terminators.lastIndex = index;
match = top.terminators.exec(value);
if (!match)
break;
count = processLexeme(value.substring(index, match.index), match[0]);
index = match.index + count;
}
processLexeme(value.substr(index));
for(current = top; current.parent; current = current.parent) { // close dangling modes
if (current.className) {
result += spanEndTag;
}
}
return {
relevance: relevance,
value: result,
language: name,
top: top
};
} catch (e) {
if (e.message && e.message.indexOf('Illegal') !== -1) {
return {
relevance: 0,
value: escape(value)
};
} else {
throw e;
}
}
}
/*
Highlighting with language detection. Accepts a string with the code to
highlight. Returns an object with the following properties:
- language (detected language)
- relevance (int)
- value (an HTML string with highlighting markup)
- second_best (object with the same structure for second-best heuristically
detected language, may be absent)
*/
function highlightAuto(text, languageSubset) {
languageSubset = languageSubset || options.languages || objectKeys(languages);
var result = {
relevance: 0,
value: escape(text)
};
var second_best = result;
languageSubset.filter(getLanguage).filter(autoDetection).forEach(function(name) {
var current = highlight(name, text, false);
current.language = name;
if (current.relevance > second_best.relevance) {
second_best = current;
}
if (current.relevance > result.relevance) {
second_best = result;
result = current;
}
});
if (second_best.language) {
result.second_best = second_best;
}
return result;
}
/*
Post-processing of the highlighted markup:
- replace TABs with something more useful
- replace real line-breaks with '<br>' for non-pre containers
*/
function fixMarkup(value) {
return !(options.tabReplace || options.useBR)
? value
: value.replace(fixMarkupRe, function(match, p1) {
if (options.useBR && match === '\n') {
return '<br>';
} else if (options.tabReplace) {
return p1.replace(/\t/g, options.tabReplace);
}
return '';
});
}
function buildClassName(prevClassName, currentLang, resultLang) {
var language = currentLang ? aliases[currentLang] : resultLang,
result = [prevClassName.trim()];
if (!prevClassName.match(/\bhljs\b/)) {
result.push('hljs');
}
if (prevClassName.indexOf(language) === -1) {
result.push(language);
}
return result.join(' ').trim();
}
/*
Applies highlighting to a DOM node containing code. Accepts a DOM node and
two optional parameters for fixMarkup.
*/
function highlightBlock(block) {
var node, originalStream, result, resultNode, text;
var language = blockLanguage(block);
if (isNotHighlighted(language))
return;
if (options.useBR) {
node = document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
node.innerHTML = block.innerHTML.replace(/\n/g, '').replace(/<br[ \/]*>/g, '\n');
} else {
node = block;
}
text = node.textContent;
result = language ? highlight(language, text, true) : highlightAuto(text);
originalStream = nodeStream(node);
if (originalStream.length) {
resultNode = document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
resultNode.innerHTML = result.value;
result.value = mergeStreams(originalStream, nodeStream(resultNode), text);
}
result.value = fixMarkup(result.value);
block.innerHTML = result.value;
block.className = buildClassName(block.className, language, result.language);
block.result = {
language: result.language,
re: result.relevance
};
if (result.second_best) {
block.second_best = {
language: result.second_best.language,
re: result.second_best.relevance
};
}
}
/*
Updates highlight.js global options with values passed in the form of an object.
*/
function configure(user_options) {
options = inherit(options, user_options);
}
/*
Applies highlighting to all <pre><code>..</code></pre> blocks on a page.
*/
function initHighlighting() {
if (initHighlighting.called)
return;
initHighlighting.called = true;
var blocks = document.querySelectorAll('pre code');
ArrayProto.forEach.call(blocks, highlightBlock);
}
/*
Attaches highlighting to the page load event.
*/
function initHighlightingOnLoad() {
addEventListener('DOMContentLoaded', initHighlighting, false);
addEventListener('load', initHighlighting, false);
}
function registerLanguage(name, language) {
var lang = languages[name] = language(hljs);
if (lang.aliases) {
lang.aliases.forEach(function(alias) {aliases[alias] = name;});
}
}
function listLanguages() {
return objectKeys(languages);
}
function getLanguage(name) {
name = (name || '').toLowerCase();
return languages[name] || languages[aliases[name]];
}
function autoDetection(name) {
var lang = getLanguage(name);
return lang && !lang.disableAutodetect;
}
/* Interface definition */
hljs.highlight = highlight;
hljs.highlightAuto = highlightAuto;
hljs.fixMarkup = fixMarkup;
hljs.highlightBlock = highlightBlock;
hljs.configure = configure;
hljs.initHighlighting = initHighlighting;
hljs.initHighlightingOnLoad = initHighlightingOnLoad;
hljs.registerLanguage = registerLanguage;
hljs.listLanguages = listLanguages;
hljs.getLanguage = getLanguage;
hljs.autoDetection = autoDetection;
hljs.inherit = inherit;
// Common regexps
hljs.IDENT_RE = '[a-zA-Z]\\w*';
hljs.UNDERSCORE_IDENT_RE = '[a-zA-Z_]\\w*';
hljs.NUMBER_RE = '\\b\\d+(\\.\\d+)?';
hljs.C_NUMBER_RE = '(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)'; // 0x..., 0..., decimal, float
hljs.BINARY_NUMBER_RE = '\\b(0b[01]+)'; // 0b...
hljs.RE_STARTERS_RE = '!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~';
// Common modes
hljs.BACKSLASH_ESCAPE = {
begin: '\\\\[\\s\\S]', relevance: 0
};
hljs.APOS_STRING_MODE = {
className: 'string',
begin: '\'', end: '\'',
illegal: '\\n',
contains: [hljs.BACKSLASH_ESCAPE]
};
hljs.QUOTE_STRING_MODE = {
className: 'string',
begin: '"', end: '"',
illegal: '\\n',
contains: [hljs.BACKSLASH_ESCAPE]
};
hljs.PHRASAL_WORDS_MODE = {
begin: /\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/
};
hljs.COMMENT = function (begin, end, inherits) {
var mode = hljs.inherit(
{
className: 'comment',
begin: begin, end: end,
contains: []
},
inherits || {}
);
mode.contains.push(hljs.PHRASAL_WORDS_MODE);
mode.contains.push({
className: 'doctag',
begin: '(?:TODO|FIXME|NOTE|BUG|XXX):',
relevance: 0
});
return mode;
};
hljs.C_LINE_COMMENT_MODE = hljs.COMMENT('//', '$');
hljs.C_BLOCK_COMMENT_MODE = hljs.COMMENT('/\\*', '\\*/');
hljs.HASH_COMMENT_MODE = hljs.COMMENT('#', '$');
hljs.NUMBER_MODE = {
className: 'number',
begin: hljs.NUMBER_RE,
relevance: 0
};
hljs.C_NUMBER_MODE = {
className: 'number',
begin: hljs.C_NUMBER_RE,
relevance: 0
};
hljs.BINARY_NUMBER_MODE = {
className: 'number',
begin: hljs.BINARY_NUMBER_RE,
relevance: 0
};
hljs.CSS_NUMBER_MODE = {
className: 'number',
begin: hljs.NUMBER_RE + '(' +
'%|em|ex|ch|rem' +
'|vw|vh|vmin|vmax' +
'|cm|mm|in|pt|pc|px' +
'|deg|grad|rad|turn' +
'|s|ms' +
'|Hz|kHz' +
'|dpi|dpcm|dppx' +
')?',
relevance: 0
};
hljs.REGEXP_MODE = {
className: 'regexp',
begin: /\//, end: /\/[gimuy]*/,
illegal: /\n/,
contains: [
hljs.BACKSLASH_ESCAPE,
{
begin: /\[/, end: /\]/,
relevance: 0,
contains: [hljs.BACKSLASH_ESCAPE]
}
]
};
hljs.TITLE_MODE = {
className: 'title',
begin: hljs.IDENT_RE,
relevance: 0
};
hljs.UNDERSCORE_TITLE_MODE = {
className: 'title',
begin: hljs.UNDERSCORE_IDENT_RE,
relevance: 0
};
hljs.METHOD_GUARD = {
// excludes method names from keyword processing
begin: '\\.\\s*' + hljs.UNDERSCORE_IDENT_RE,
relevance: 0
};
return hljs;
}));

View File

@ -0,0 +1,516 @@
/*
Language: 1C:Enterprise (v7, v8)
Author: Stanislav Belov <stbelov@gmail.com>
Description: built-in language 1C:Enterprise (v7, v8)
Category: enterprise
*/
function(hljs){
// общий паттерн для определения идентификаторов
var UNDERSCORE_IDENT_RE = '[A-Za-zА-Яа-яёЁ_][A-Za-zА-Яа-яёЁ_0-9]+';
// v7 уникальные ключевые слова, отсутствующие в v8 ==> keyword
var v7_keywords =
'далее ';
// v8 ключевые слова ==> keyword
var v8_keywords =
'возврат вызватьисключение выполнить для если и из или иначе иначеесли исключение каждого конецесли ' +
'конецпопытки конеццикла не новый перейти перем по пока попытка прервать продолжить тогда цикл экспорт ';
// keyword : ключевые слова
var KEYWORD = v7_keywords + v8_keywords;
// v7 уникальные директивы, отсутствующие в v8 ==> meta-keyword
var v7_meta_keywords =
'загрузитьизфайла ';
// v8 ключевые слова в инструкциях препроцессора, директивах компиляции, аннотациях ==> meta-keyword
var v8_meta_keywords =
'вебклиент вместо внешнеесоединение клиент конецобласти мобильноеприложениеклиент мобильноеприложениесервер ' +
'наклиенте наклиентенасервере наклиентенасерверебезконтекста насервере насерверебезконтекста область перед ' +
'после сервер толстыйклиентобычноеприложение толстыйклиентуправляемоеприложение тонкийклиент ';
// meta-keyword : ключевые слова в инструкциях препроцессора, директивах компиляции, аннотациях
var METAKEYWORD = v7_meta_keywords + v8_meta_keywords;
// v7 системные константы ==> built_in
var v7_system_constants =
'разделительстраниц разделительстрок символтабуляции ';
// v7 уникальные методы глобального контекста, отсутствующие в v8 ==> built_in
var v7_global_context_methods =
'ansitooem oemtoansi ввестивидсубконто ввестиперечисление ввестипериод ввестиплансчетов выбранныйплансчетов ' +
'датагод датамесяц датачисло заголовоксистемы значениевстроку значениеизстроки каталогиб каталогпользователя ' +
'кодсимв конгода конецпериодаби конецрассчитанногопериодаби конецстандартногоинтервала конквартала конмесяца ' +
'коннедели лог лог10 максимальноеколичествосубконто названиеинтерфейса названиенабораправ назначитьвид ' +
'назначитьсчет найтиссылки началопериодаби началостандартногоинтервала начгода начквартала начмесяца ' +
'начнедели номерднягода номерднянедели номернеделигода обработкаожидания основнойжурналрасчетов ' +
'основнойплансчетов основнойязык очиститьокносообщений периодстр получитьвремята получитьдатута ' +
'получитьдокументта получитьзначенияотбора получитьпозициюта получитьпустоезначение получитьта ' +
'префиксавтонумерации пропись пустоезначение разм разобратьпозициюдокумента рассчитатьрегистрына ' +
'рассчитатьрегистрыпо симв создатьобъект статусвозврата стрколичествострок сформироватьпозициюдокумента ' +
'счетпокоду текущеевремя типзначения типзначениястр установитьтана установитьтапо фиксшаблон шаблон ';
// v8 методы глобального контекста ==> built_in
var v8_global_context_methods =
'acos asin atan base64значение base64строка cos exp log log10 pow sin sqrt tan xmlзначение xmlстрока ' +
'xmlтип xmlтипзнч активноеокно безопасныйрежим безопасныйрежимразделенияданных булево ввестидату ввестизначение ' +
'ввестистроку ввестичисло возможностьчтенияxml вопрос восстановитьзначение врег выгрузитьжурналрегистрации ' +
'выполнитьобработкуоповещения выполнитьпроверкуправдоступа вычислить год данныеформывзначение дата день деньгода ' +
'деньнедели добавитьмесяц заблокироватьданныедляредактирования заблокироватьработупользователя завершитьработусистемы ' +
'загрузитьвнешнююкомпоненту закрытьсправку записатьjson записатьxml записатьдатуjson записьжурналарегистрации ' +
'заполнитьзначениясвойств запроситьразрешениепользователя запуститьприложение запуститьсистему зафиксироватьтранзакцию ' +
'значениевданныеформы значениевстрокувнутр значениевфайл значениезаполнено значениеизстрокивнутр значениеизфайла ' +
'изxmlтипа импортмоделиxdto имякомпьютера имяпользователя инициализироватьпредопределенныеданные информацияобошибке ' +
'каталогбиблиотекимобильногоустройства каталогвременныхфайлов каталогдокументов каталогпрограммы кодироватьстроку ' +
'кодлокализацииинформационнойбазы кодсимвола командасистемы конецгода конецдня конецквартала конецмесяца конецминуты ' +
'конецнедели конецчаса конфигурациябазыданныхизмененадинамически конфигурацияизменена копироватьданныеформы ' +
'копироватьфайл краткоепредставлениеошибки лев макс местноевремя месяц мин минута монопольныйрежим найти ' +
айтинедопустимыесимволыxml найтиокнопонавигационнойссылке найтипомеченныенаудаление найтипоссылкам найтифайлы ' +
'началогода началодня началоквартала началомесяца началоминуты началонедели началочаса начатьзапросразрешенияпользователя ' +
'начатьзапускприложения начатькопированиефайла начатьперемещениефайла начатьподключениевнешнейкомпоненты ' +
'начатьподключениерасширенияработыскриптографией начатьподключениерасширенияработысфайлами начатьпоискфайлов ' +
'начатьполучениекаталогавременныхфайлов начатьполучениекаталогадокументов начатьполучениерабочегокаталогаданныхпользователя ' +
'начатьполучениефайлов начатьпомещениефайла начатьпомещениефайлов начатьсозданиедвоичныхданныхизфайла начатьсозданиекаталога ' +
'начатьтранзакцию начатьудалениефайлов начатьустановкувнешнейкомпоненты начатьустановкурасширенияработыскриптографией ' +
'начатьустановкурасширенияработысфайлами неделягода необходимостьзавершениясоединения номерсеансаинформационнойбазы ' +
'номерсоединенияинформационнойбазы нрег нстр обновитьинтерфейс обновитьнумерациюобъектов обновитьповторноиспользуемыезначения ' +
'обработкапрерыванияпользователя объединитьфайлы окр описаниеошибки оповестить оповеститьобизменении ' +
'отключитьобработчикзапросанастроекклиенталицензирования отключитьобработчикожидания отключитьобработчикоповещения ' +
'открытьзначение открытьиндекссправки открытьсодержаниесправки открытьсправку открытьформу открытьформумодально ' +
'отменитьтранзакцию очиститьжурналрегистрации очиститьнастройкипользователя очиститьсообщения параметрыдоступа ' +
'перейтипонавигационнойссылке переместитьфайл подключитьвнешнююкомпоненту ' +
'подключитьобработчикзапросанастроекклиенталицензирования подключитьобработчикожидания подключитьобработчикоповещения ' +
'подключитьрасширениеработыскриптографией подключитьрасширениеработысфайлами подробноепредставлениеошибки ' +
'показатьвводдаты показатьвводзначения показатьвводстроки показатьвводчисла показатьвопрос показатьзначение ' +
'показатьинформациюобошибке показатьнакарте показатьоповещениепользователя показатьпредупреждение полноеимяпользователя ' +
'получитьcomобъект получитьxmlтип получитьадреспоместоположению получитьблокировкусеансов получитьвремязавершенияспящегосеанса ' +
'получитьвремязасыпанияпассивногосеанса получитьвремяожиданияблокировкиданных получитьданныевыбора ' +
'получитьдополнительныйпараметрклиенталицензирования получитьдопустимыекодылокализации получитьдопустимыечасовыепояса ' +
'получитьзаголовокклиентскогоприложения получитьзаголовоксистемы получитьзначенияотборажурналарегистрации ' +
'получитьидентификаторконфигурации получитьизвременногохранилища получитьимявременногофайла ' +
'получитьимяклиенталицензирования получитьинформациюэкрановклиента получитьиспользованиежурналарегистрации ' +
'получитьиспользованиесобытияжурналарегистрации получитькраткийзаголовокприложения получитьмакетоформления ' +
'получитьмаскувсефайлы получитьмаскувсефайлыклиента получитьмаскувсефайлысервера получитьместоположениепоадресу ' +
'получитьминимальнуюдлинупаролейпользователей получитьнавигационнуюссылку получитьнавигационнуюссылкуинформационнойбазы ' +
'получитьобновлениеконфигурациибазыданных получитьобновлениепредопределенныхданныхинформационнойбазы получитьобщиймакет ' +
'получитьобщуюформу получитьокна получитьоперативнуюотметкувремени получитьотключениебезопасногорежима ' +
'получитьпараметрыфункциональныхопцийинтерфейса получитьполноеимяпредопределенногозначения ' +
'получитьпредставлениянавигационныхссылок получитьпроверкусложностипаролейпользователей получитьразделительпути ' +
'получитьразделительпутиклиента получитьразделительпутисервера получитьсеансыинформационнойбазы ' +
'получитьскоростьклиентскогосоединения получитьсоединенияинформационнойбазы получитьсообщенияпользователю ' +
'получитьсоответствиеобъектаиформы получитьсоставстандартногоинтерфейсаodata получитьструктурухранениябазыданных ' +
'получитьтекущийсеансинформационнойбазы получитьфайл получитьфайлы получитьформу получитьфункциональнуюопцию ' +
'получитьфункциональнуюопциюинтерфейса получитьчасовойпоясинформационнойбазы пользователиос поместитьвовременноехранилище ' +
'поместитьфайл поместитьфайлы прав праводоступа предопределенноезначение представлениекодалокализации представлениепериода ' +
'представлениеправа представлениеприложения представлениесобытияжурналарегистрации представлениечасовогопояса предупреждение ' +
'прекратитьработусистемы привилегированныйрежим продолжитьвызов прочитатьjson прочитатьxml прочитатьдатуjson пустаястрока ' +
'рабочийкаталогданныхпользователя разблокироватьданныедляредактирования разделитьфайл разорватьсоединениесвнешнимисточникомданных ' +
'раскодироватьстроку рольдоступна секунда сигнал символ скопироватьжурналрегистрации смещениелетнеговремени ' +
'смещениестандартноговремени соединитьбуферыдвоичныхданных создатькаталог создатьфабрикуxdto сокрл сокрлп сокрп сообщить ' +
'состояние сохранитьзначение сохранитьнастройкипользователя сред стрдлина стрзаканчиваетсяна стрзаменить стрнайти стрначинаетсяс ' +
'строка строкасоединенияинформационнойбазы стрполучитьстроку стрразделить стрсоединить стрсравнить стрчисловхождений '+
'стрчислострок стршаблон текущаядата текущаядатасеанса текущаяуниверсальнаядата текущаяуниверсальнаядатавмиллисекундах ' +
'текущийвариантинтерфейсаклиентскогоприложения текущийвариантосновногошрифтаклиентскогоприложения текущийкодлокализации ' +
'текущийрежимзапуска текущийязык текущийязыксистемы тип типзнч транзакцияактивна трег удалитьданныеинформационнойбазы ' +
'удалитьизвременногохранилища удалитьобъекты удалитьфайлы универсальноевремя установитьбезопасныйрежим ' +
'установитьбезопасныйрежимразделенияданных установитьблокировкусеансов установитьвнешнююкомпоненту ' +
'установитьвремязавершенияспящегосеанса установитьвремязасыпанияпассивногосеанса установитьвремяожиданияблокировкиданных ' +
'установитьзаголовокклиентскогоприложения установитьзаголовоксистемы установитьиспользованиежурналарегистрации ' +
'установитьиспользованиесобытияжурналарегистрации установитькраткийзаголовокприложения ' +
'установитьминимальнуюдлинупаролейпользователей установитьмонопольныйрежим установитьнастройкиклиенталицензирования ' +
'установитьобновлениепредопределенныхданныхинформационнойбазы установитьотключениебезопасногорежима ' +
'установитьпараметрыфункциональныхопцийинтерфейса установитьпривилегированныйрежим ' +
'установитьпроверкусложностипаролейпользователей установитьрасширениеработыскриптографией ' +
'установитьрасширениеработысфайлами установитьсоединениесвнешнимисточникомданных установитьсоответствиеобъектаиформы ' +
'установитьсоставстандартногоинтерфейсаodata установитьчасовойпоясинформационнойбазы установитьчасовойпояссеанса ' +
'формат цел час часовойпояс часовойпояссеанса число числопрописью этоадресвременногохранилища ';
// v8 свойства глобального контекста ==> built_in
var v8_global_context_property =
'wsссылки библиотекакартинок библиотекамакетовоформлениякомпоновкиданных библиотекастилей бизнеспроцессы ' +
'внешниеисточникиданных внешниеобработки внешниеотчеты встроенныепокупки главныйинтерфейс главныйстиль ' +
'документы доставляемыеуведомления журналыдокументов задачи информацияобинтернетсоединении использованиерабочейдаты ' +
'историяработыпользователя константы критерииотбора метаданные обработки отображениерекламы отправкадоставляемыхуведомлений ' +
'отчеты панельзадачос параметрзапуска параметрысеанса перечисления планывидоврасчета планывидовхарактеристик ' +
'планыобмена планысчетов полнотекстовыйпоиск пользователиинформационнойбазы последовательности проверкавстроенныхпокупок ' +
'рабочаядата расширенияконфигурации регистрыбухгалтерии регистрынакопления регистрырасчета регистрысведений ' +
'регламентныезадания сериализаторxdto справочники средствагеопозиционирования средствакриптографии средствамультимедиа ' +
'средстваотображениярекламы средствапочты средствателефонии фабрикаxdto файловыепотоки фоновыезадания хранилищанастроек ' +
'хранилищевариантовотчетов хранилищенастроекданныхформ хранилищеобщихнастроек хранилищепользовательскихнастроекдинамическихсписков ' +
'хранилищепользовательскихнастроекотчетов хранилищесистемныхнастроек ';
// built_in : встроенные или библиотечные объекты (константы, классы, функции)
var BUILTIN =
v7_system_constants +
v7_global_context_methods + v8_global_context_methods +
v8_global_context_property;
// v8 системные наборы значений ==> class
var v8_system_sets_of_values =
'webцвета windowsцвета windowsшрифты библиотекакартинок рамкистиля символы цветастиля шрифтыстиля ';
// v8 системные перечисления - интерфейсные ==> class
var v8_system_enums_interface =
'автоматическоесохранениеданныхформывнастройках автонумерациявформе автораздвижениесерий ' +
'анимациядиаграммы вариантвыравниванияэлементовизаголовков вариантуправлениявысотойтаблицы ' +
'вертикальнаяпрокруткаформы вертикальноеположение вертикальноеположениеэлемента видгруппыформы ' +
'виддекорацииформы виддополненияэлементаформы видизмененияданных видкнопкиформы видпереключателя ' +
'видподписейкдиаграмме видполяформы видфлажка влияниеразмеранапузырекдиаграммы горизонтальноеположение ' +
'горизонтальноеположениеэлемента группировкаколонок группировкаподчиненныхэлементовформы ' +
'группыиэлементы действиеперетаскивания дополнительныйрежимотображения допустимыедействияперетаскивания ' +
'интервалмеждуэлементамиформы использованиевывода использованиеполосыпрокрутки ' +
'используемоезначениеточкибиржевойдиаграммы историявыборапривводе источникзначенийоситочекдиаграммы ' +
'источникзначенияразмерапузырькадиаграммы категориягруппыкоманд максимумсерий начальноеотображениедерева ' +
'начальноеотображениесписка обновлениетекстаредактирования ориентациядендрограммы ориентациядиаграммы ' +
'ориентацияметокдиаграммы ориентацияметоксводнойдиаграммы ориентацияэлементаформы отображениевдиаграмме ' +
'отображениевлегендедиаграммы отображениегруппыкнопок отображениезаголовкашкалыдиаграммы ' +
'отображениезначенийсводнойдиаграммы отображениезначенияизмерительнойдиаграммы ' +
'отображениеинтерваладиаграммыганта отображениекнопки отображениекнопкивыбора отображениеобсужденийформы ' +
'отображениеобычнойгруппы отображениеотрицательныхзначенийпузырьковойдиаграммы отображениепанелипоиска ' +
'отображениеподсказки отображениепредупрежденияприредактировании отображениеразметкиполосырегулирования ' +
'отображениестраницформы отображениетаблицы отображениетекстазначениядиаграммыганта ' +
'отображениеуправленияобычнойгруппы отображениефигурыкнопки палитрацветовдиаграммы поведениеобычнойгруппы ' +
'поддержкамасштабадендрограммы поддержкамасштабадиаграммыганта поддержкамасштабасводнойдиаграммы ' +
'поисквтаблицепривводе положениезаголовкаэлементаформы положениекартинкикнопкиформы ' +
'положениекартинкиэлементаграфическойсхемы положениекоманднойпанелиформы положениекоманднойпанелиэлементаформы ' +
'положениеопорнойточкиотрисовки положениеподписейкдиаграмме положениеподписейшкалызначенийизмерительнойдиаграммы ' +
'положениесостоянияпросмотра положениестрокипоиска положениетекстасоединительнойлинии положениеуправленияпоиском ' +
'положениешкалывремени порядокотображенияточекгоризонтальнойгистограммы порядоксерийвлегендедиаграммы ' +
'размеркартинки расположениезаголовкашкалыдиаграммы растягиваниеповертикалидиаграммыганта ' +
'режимавтоотображениясостояния режимвводастроктаблицы режимвыборанезаполненного режимвыделениядаты ' +
'режимвыделениястрокитаблицы режимвыделениятаблицы режимизмененияразмера режимизменениясвязанногозначения ' +
'режимиспользованиядиалогапечати режимиспользованияпараметракоманды режиммасштабированияпросмотра ' +
'режимосновногоокнаклиентскогоприложения режимоткрытияокнаформы режимотображениявыделения ' +
'режимотображениягеографическойсхемы режимотображениязначенийсерии режимотрисовкисеткиграфическойсхемы ' +
'режимполупрозрачностидиаграммы режимпробеловдиаграммы режимразмещениянастранице режимредактированияколонки ' +
'режимсглаживаниядиаграммы режимсглаживанияиндикатора режимсписказадач сквозноевыравнивание ' +
'сохранениеданныхформывнастройках способзаполнениятекстазаголовкашкалыдиаграммы ' +
'способопределенияограничивающегозначениядиаграммы стандартнаягруппакоманд стандартноеоформление ' +
'статусоповещенияпользователя стильстрелки типаппроксимациилиниитрендадиаграммы типдиаграммы ' +
'типединицышкалывремени типимпортасерийслоягеографическойсхемы типлиниигеографическойсхемы типлиниидиаграммы ' +
'типмаркерагеографическойсхемы типмаркерадиаграммы типобластиоформления ' +
'типорганизацииисточникаданныхгеографическойсхемы типотображениясериислоягеографическойсхемы ' +
'типотображенияточечногообъектагеографическойсхемы типотображенияшкалыэлементалегендыгеографическойсхемы ' +
'типпоискаобъектовгеографическойсхемы типпроекциигеографическойсхемы типразмещенияизмерений ' +
'типразмещенияреквизитовизмерений типрамкиэлементауправления типсводнойдиаграммы ' +
'типсвязидиаграммыганта типсоединениязначенийпосериямдиаграммы типсоединенияточекдиаграммы ' +
'типсоединительнойлинии типстороныэлементаграфическойсхемы типформыотчета типшкалырадарнойдиаграммы ' +
'факторлиниитрендадиаграммы фигуракнопки фигурыграфическойсхемы фиксациявтаблице форматдняшкалывремени ' +
'форматкартинки ширинаподчиненныхэлементовформы ';
// v8 системные перечисления - свойства прикладных объектов ==> class
var v8_system_enums_objects_properties =
'виддвижениябухгалтерии виддвижениянакопления видпериодарегистрарасчета видсчета видточкимаршрутабизнеспроцесса ' +
'использованиеагрегатарегистранакопления использованиегруппиэлементов использованиережимапроведения ' +
'использованиесреза периодичностьагрегатарегистранакопления режимавтовремя режимзаписидокумента режимпроведениядокумента ';
// v8 системные перечисления - планы обмена ==> class
var v8_system_enums_exchange_plans =
'авторегистрацияизменений допустимыйномерсообщения отправкаэлементаданных получениеэлементаданных ';
// v8 системные перечисления - табличный документ ==> class
var v8_system_enums_tabular_document =
'использованиерасшифровкитабличногодокумента ориентациястраницы положениеитоговколоноксводнойтаблицы ' +
'положениеитоговстроксводнойтаблицы положениетекстаотносительнокартинки расположениезаголовкагруппировкитабличногодокумента ' +
'способчтениязначенийтабличногодокумента типдвустороннейпечати типзаполненияобластитабличногодокумента ' +
'типкурсоровтабличногодокумента типлиниирисункатабличногодокумента типлинииячейкитабличногодокумента ' +
'типнаправленияпереходатабличногодокумента типотображениявыделениятабличногодокумента типотображениялинийсводнойтаблицы ' +
'типразмещениятекстатабличногодокумента типрисункатабличногодокумента типсмещениятабличногодокумента ' +
'типузоратабличногодокумента типфайлатабличногодокумента точностьпечати чередованиерасположениястраниц ';
// v8 системные перечисления - планировщик ==> class
var v8_system_enums_sheduler =
'отображениевремениэлементовпланировщика ';
// v8 системные перечисления - форматированный документ ==> class
var v8_system_enums_formatted_document =
'типфайлаформатированногодокумента ';
// v8 системные перечисления - запрос ==> class
var v8_system_enums_query =
'обходрезультатазапроса типзаписизапроса ';
// v8 системные перечисления - построитель отчета ==> class
var v8_system_enums_report_builder =
'видзаполнениярасшифровкипостроителяотчета типдобавленияпредставлений типизмеренияпостроителяотчета типразмещенияитогов ';
// v8 системные перечисления - работа с файлами ==> class
var v8_system_enums_files =
'доступкфайлу режимдиалогавыборафайла режимоткрытияфайла ';
// v8 системные перечисления - построитель запроса ==> class
var v8_system_enums_query_builder =
'типизмеренияпостроителязапроса ';
// v8 системные перечисления - анализ данных ==> class
var v8_system_enums_data_analysis =
'видданныханализа методкластеризации типединицыинтервалавременианализаданных типзаполнениятаблицырезультатаанализаданных ' +
'типиспользованиячисловыхзначенийанализаданных типисточникаданныхпоискаассоциаций типколонкианализаданныхдереворешений ' +
'типколонкианализаданныхкластеризация типколонкианализаданныхобщаястатистика типколонкианализаданныхпоискассоциаций ' +
'типколонкианализаданныхпоискпоследовательностей типколонкимоделипрогноза типмерырасстоянияанализаданных ' +
'типотсеченияправилассоциации типполяанализаданных типстандартизациианализаданных типупорядочиванияправилассоциациианализаданных ' +
'типупорядочиванияшаблоновпоследовательностейанализаданных типупрощениядереварешений ';
// v8 системные перечисления - xml, json, xs, dom, xdto, web-сервисы ==> class
var v8_system_enums_xml_json_xs_dom_xdto_ws =
'wsнаправлениепараметра вариантxpathxs вариантзаписидатыjson вариантпростоготипаxs видгруппымоделиxs видфасетаxdto ' +
ействиепостроителяdom завершенностьпростоготипаxs завершенностьсоставноготипаxs завершенностьсхемыxs запрещенныеподстановкиxs ' +
сключениягруппподстановкиxs категорияиспользованияатрибутаxs категорияограниченияидентичностиxs категорияограниченияпространствименxs ' +
етоднаследованияxs модельсодержимогоxs назначениетипаxml недопустимыеподстановкиxs обработкапробельныхсимволовxs обработкасодержимогоxs ' +
'ограничениезначенияxs параметрыотбораузловdom переносстрокjson позициявдокументеdom пробельныесимволыxml типатрибутаxml типзначенияjson ' +
'типканоническогоxml типкомпонентыxs типпроверкиxml типрезультатаdomxpath типузлаdom типузлаxml формаxml формапредставленияxs ' +
орматдатыjson экранированиесимволовjson ';
// v8 системные перечисления - система компоновки данных ==> class
var v8_system_enums_data_composition_system =
'видсравнениякомпоновкиданных действиеобработкирасшифровкикомпоновкиданных направлениесортировкикомпоновкиданных ' +
'расположениевложенныхэлементоврезультатакомпоновкиданных расположениеитоговкомпоновкиданных расположениегруппировкикомпоновкиданных ' +
'расположениеполейгруппировкикомпоновкиданных расположениеполякомпоновкиданных расположениереквизитовкомпоновкиданных ' +
'расположениересурсовкомпоновкиданных типбухгалтерскогоостаткакомпоновкиданных типвыводатекстакомпоновкиданных ' +
'типгруппировкикомпоновкиданных типгруппыэлементовотборакомпоновкиданных типдополненияпериодакомпоновкиданных ' +
'типзаголовкаполейкомпоновкиданных типмакетагруппировкикомпоновкиданных типмакетаобластикомпоновкиданных типостаткакомпоновкиданных ' +
'типпериодакомпоновкиданных типразмещениятекстакомпоновкиданных типсвязинаборовданныхкомпоновкиданных типэлементарезультатакомпоновкиданных ' +
'расположениелегендыдиаграммыкомпоновкиданных типпримененияотборакомпоновкиданных режимотображенияэлементанастройкикомпоновкиданных ' +
'режимотображениянастроеккомпоновкиданных состояниеэлементанастройкикомпоновкиданных способвосстановлениянастроеккомпоновкиданных ' +
'режимкомпоновкирезультата использованиепараметракомпоновкиданных автопозицияресурсовкомпоновкиданных '+
'вариантиспользованиягруппировкикомпоновкиданных расположениересурсоввдиаграммекомпоновкиданных фиксациякомпоновкиданных ' +
'использованиеусловногооформлениякомпоновкиданных ';
// v8 системные перечисления - почта ==> class
var v8_system_enums_email =
'важностьинтернетпочтовогосообщения обработкатекстаинтернетпочтовогосообщения способкодированияинтернетпочтовоговложения ' +
'способкодированиянеasciiсимволовинтернетпочтовогосообщения типтекстапочтовогосообщения протоколинтернетпочты ' +
'статусразборапочтовогосообщения ';
// v8 системные перечисления - журнал регистрации ==> class
var v8_system_enums_logbook =
'режимтранзакциизаписижурналарегистрации статустранзакциизаписижурналарегистрации уровеньжурналарегистрации ';
// v8 системные перечисления - криптография ==> class
var v8_system_enums_cryptography =
'расположениехранилищасертификатовкриптографии режимвключениясертификатовкриптографии режимпроверкисертификатакриптографии ' +
'типхранилищасертификатовкриптографии ';
// v8 системные перечисления - ZIP ==> class
var v8_system_enums_zip =
одировкаименфайловвzipфайле методсжатияzip методшифрованияzip режимвосстановленияпутейфайловzip режимобработкиподкаталоговzip ' +
'режимсохраненияпутейzip уровеньсжатияzip ';
// v8 системные перечисления -
// Блокировка данных, Фоновые задания, Автоматизированное тестирование,
// Доставляемые уведомления, Встроенные покупки, Интернет, Работа с двоичными данными ==> class
var v8_system_enums_other =
'звуковоеоповещение направлениепереходакстроке позициявпотоке порядокбайтов режимблокировкиданных режимуправленияблокировкойданных ' +
'сервисвстроенныхпокупок состояниефоновогозадания типподписчикадоставляемыхуведомлений уровеньиспользованиязащищенногосоединенияftp ';
// v8 системные перечисления - схема запроса ==> class
var v8_system_enums_request_schema =
'направлениепорядкасхемызапроса типдополненияпериодамисхемызапроса типконтрольнойточкисхемызапроса типобъединениясхемызапроса ' +
'типпараметрадоступнойтаблицысхемызапроса типсоединениясхемызапроса ';
// v8 системные перечисления - свойства объектов метаданных ==> class
var v8_system_enums_properties_of_metadata_objects =
'httpметод автоиспользованиеобщегореквизита автопрефиксномеразадачи вариантвстроенногоязыка видиерархии видрегистранакопления ' +
'видтаблицывнешнегоисточникаданных записьдвиженийприпроведении заполнениепоследовательностей индексирование ' +
'использованиебазыпланавидоврасчета использованиебыстроговыбора использованиеобщегореквизита использованиеподчинения ' +
'использованиеполнотекстовогопоиска использованиеразделяемыхданныхобщегореквизита использованиереквизита ' +
'назначениеиспользованияприложения назначениерасширенияконфигурации направлениепередачи обновлениепредопределенныхданных ' +
'оперативноепроведение основноепредставлениевидарасчета основноепредставлениевидахарактеристики основноепредставлениезадачи ' +
'основноепредставлениепланаобмена основноепредставлениесправочника основноепредставлениесчета перемещениеграницыприпроведении ' +
'периодичностьномерабизнеспроцесса периодичностьномерадокумента периодичностьрегистрарасчета периодичностьрегистрасведений ' +
'повторноеиспользованиевозвращаемыхзначений полнотекстовыйпоискпривводепостроке принадлежностьобъекта проведение ' +
'разделениеаутентификацииобщегореквизита разделениеданныхобщегореквизита разделениерасширенийконфигурацииобщегореквизита '+
'режимавтонумерацииобъектов режимзаписирегистра режимиспользованиямодальности ' +
'режимиспользованиясинхронныхвызововрасширенийплатформыивнешнихкомпонент режимповторногоиспользованиясеансов ' +
'режимполученияданныхвыборапривводепостроке режимсовместимости режимсовместимостиинтерфейса ' +
'режимуправленияблокировкойданныхпоумолчанию сериикодовпланавидовхарактеристик сериикодовпланасчетов ' +
'сериикодовсправочника созданиепривводе способвыбора способпоискастрокипривводепостроке способредактирования ' +
'типданныхтаблицывнешнегоисточникаданных типкодапланавидоврасчета типкодасправочника типмакета типномерабизнеспроцесса ' +
'типномерадокумента типномеразадачи типформы удалениедвижений ';
// v8 системные перечисления - разные ==> class
var v8_system_enums_differents =
'важностьпроблемыприменениярасширенияконфигурации вариантинтерфейсаклиентскогоприложения вариантмасштабаформклиентскогоприложения ' +
'вариантосновногошрифтаклиентскогоприложения вариантстандартногопериода вариантстандартнойдатыначала видграницы видкартинки ' +
'видотображенияполнотекстовогопоиска видрамки видсравнения видцвета видчисловогозначения видшрифта допустимаядлина допустимыйзнак ' +
спользованиеbyteordermark использованиеметаданныхполнотекстовогопоиска источникрасширенийконфигурации клавиша кодвозвратадиалога ' +
одировкаxbase кодировкатекста направлениепоиска направлениесортировки обновлениепредопределенныхданных обновлениеприизмененииданных ' +
'отображениепанелиразделов проверказаполнения режимдиалогавопрос режимзапускаклиентскогоприложения режимокругления режимоткрытияформприложения ' +
'режимполнотекстовогопоиска скоростьклиентскогосоединения состояниевнешнегоисточникаданных состояниеобновленияконфигурациибазыданных ' +
'способвыборасертификатаwindows способкодированиястроки статуссообщения типвнешнейкомпоненты типплатформы типповеденияклавишиenter ' +
'типэлементаинформацииовыполненииобновленияконфигурациибазыданных уровеньизоляциитранзакций хешфункция частидаты';
// class: встроенные наборы значений, системные перечисления (содержат дочерние значения, обращения к которым через разыменование)
var CLASS =
v8_system_sets_of_values +
v8_system_enums_interface +
v8_system_enums_objects_properties +
v8_system_enums_exchange_plans +
v8_system_enums_tabular_document +
v8_system_enums_sheduler +
v8_system_enums_formatted_document +
v8_system_enums_query +
v8_system_enums_report_builder +
v8_system_enums_files +
v8_system_enums_query_builder +
v8_system_enums_data_analysis +
v8_system_enums_xml_json_xs_dom_xdto_ws +
v8_system_enums_data_composition_system +
v8_system_enums_email +
v8_system_enums_logbook +
v8_system_enums_cryptography +
v8_system_enums_zip +
v8_system_enums_other +
v8_system_enums_request_schema +
v8_system_enums_properties_of_metadata_objects +
v8_system_enums_differents;
// v8 общие объекты (у объектов есть конструктор, экземпляры создаются методом НОВЫЙ) ==> type
var v8_shared_object =
'comобъект ftpсоединение httpзапрос httpсервисответ httpсоединение wsопределения wsпрокси xbase анализданных аннотацияxs ' +
'блокировкаданных буфердвоичныхданных включениеxs выражениекомпоновкиданных генераторслучайныхчисел географическаясхема ' +
'географическиекоординаты графическаясхема группамоделиxs данныерасшифровкикомпоновкиданных двоичныеданные дендрограмма ' +
'диаграмма диаграммаганта диалогвыборафайла диалогвыборацвета диалогвыборашрифта диалограсписаниярегламентногозадания ' +
'диалогредактированиястандартногопериода диапазон документdom документhtml документацияxs доставляемоеуведомление ' +
аписьdom записьfastinfoset записьhtml записьjson записьxml записьzipфайла записьданных записьтекста записьузловdom ' +
'запрос защищенноесоединениеopenssl значенияполейрасшифровкикомпоновкиданных извлечениетекста импортxs интернетпочта ' +
'интернетпочтовоесообщение интернетпочтовыйпрофиль интернетпрокси интернетсоединение информациядляприложенияxs ' +
спользованиеатрибутаxs использованиесобытияжурналарегистрации источникдоступныхнастроеккомпоновкиданных ' +
'итераторузловdom картинка квалификаторыдаты квалификаторыдвоичныхданных квалификаторыстроки квалификаторычисла ' +
'компоновщикмакетакомпоновкиданных компоновщикнастроеккомпоновкиданных конструктормакетаоформлениякомпоновкиданных ' +
'конструкторнастроеккомпоновкиданных конструкторформатнойстроки линия макеткомпоновкиданных макетобластикомпоновкиданных ' +
'макетоформлениякомпоновкиданных маскаxs менеджеркриптографии наборсхемxml настройкикомпоновкиданных настройкисериализацииjson ' +
'обработкакартинок обработкарасшифровкикомпоновкиданных обходдереваdom объявлениеатрибутаxs объявлениенотацииxs ' +
'объявлениеэлементаxs описаниеиспользованиясобытиядоступжурналарегистрации ' +
'описаниеиспользованиясобытияотказвдоступежурналарегистрации описаниеобработкирасшифровкикомпоновкиданных ' +
'описаниепередаваемогофайла описаниетипов определениегруппыатрибутовxs определениегруппымоделиxs ' +
'определениеограниченияидентичностиxs определениепростоготипаxs определениесоставноготипаxs определениетипадокументаdom ' +
'определенияxpathxs отборкомпоновкиданных пакетотображаемыхдокументов параметрвыбора параметркомпоновкиданных ' +
'параметрызаписиjson параметрызаписиxml параметрычтенияxml переопределениеxs планировщик полеанализаданных ' +
'полекомпоновкиданных построительdom построительзапроса построительотчета построительотчетаанализаданных ' +
'построительсхемxml поток потоквпамяти почта почтовоесообщение преобразованиеxsl преобразованиекканоническомуxml ' +
'процессорвыводарезультатакомпоновкиданныхвколлекциюзначений процессорвыводарезультатакомпоновкиданныхвтабличныйдокумент ' +
'процессоркомпоновкиданных разыменовательпространствименdom рамка расписаниерегламентногозадания расширенноеимяxml ' +
'результатчтенияданных своднаядиаграмма связьпараметравыбора связьпотипу связьпотипукомпоновкиданных сериализаторxdto ' +
'сертификатклиентаwindows сертификатклиентафайл сертификаткриптографии сертификатыудостоверяющихцентровwindows ' +
'сертификатыудостоверяющихцентровфайл сжатиеданных системнаяинформация сообщениепользователю сочетаниеклавиш ' +
'сравнениезначений стандартнаядатаначала стандартныйпериод схемаxml схемакомпоновкиданных табличныйдокумент ' +
'текстовыйдокумент тестируемоеприложение типданныхxml уникальныйидентификатор фабрикаxdto файл файловыйпоток ' +
асетдлиныxs фасетколичестваразрядовдробнойчастиxs фасетмаксимальноговключающегозначенияxs ' +
асетмаксимальногоисключающегозначенияxs фасетмаксимальнойдлиныxs фасетминимальноговключающегозначенияxs ' +
асетминимальногоисключающегозначенияxs фасетминимальнойдлиныxs фасетобразцаxs фасетобщегоколичестваразрядовxs ' +
асетперечисленияxs фасетпробельныхсимволовxs фильтрузловdom форматированнаястрока форматированныйдокумент ' +
рагментxs хешированиеданных хранилищезначения цвет чтениеfastinfoset чтениеhtml чтениеjson чтениеxml чтениеzipфайла ' +
'чтениеданных чтениетекста чтениеузловdom шрифт элементрезультатакомпоновкиданных ';
// v8 универсальные коллекции значений ==> type
var v8_universal_collection =
'comsafearray деревозначений массив соответствие списокзначений структура таблицазначений фиксированнаяструктура ' +
'фиксированноесоответствие фиксированныймассив ';
// type : встроенные типы
var TYPE =
v8_shared_object +
v8_universal_collection;
// literal : примитивные типы
var LITERAL = 'null истина ложь неопределено';
// number : числа
var NUMBERS = hljs.inherit(hljs.NUMBER_MODE);
// string : строки
var STRINGS = {
className: 'string',
begin: '"|\\|', end: '"|$',
contains: [{begin: '""'}]
};
// number : даты
var DATE = {
begin: "'", end: "'", excludeBegin: true, excludeEnd: true,
contains: [
{
className: 'number',
begin: '\\d{4}([\\.\\\\/:-]?\\d{2}){0,5}'
}
]
};
// comment : комментарии
var COMMENTS = hljs.inherit(hljs.C_LINE_COMMENT_MODE);
// meta : инструкции препроцессора, директивы компиляции
var META = {
className: 'meta',
lexemes: UNDERSCORE_IDENT_RE,
begin: '#|&', end: '$',
keywords: {'meta-keyword': KEYWORD + METAKEYWORD},
contains: [
COMMENTS
]
};
// symbol : метка goto
var SYMBOL = {
className: 'symbol',
begin: '~', end: ';|:', excludeEnd: true
};
// function : объявление процедур и функций
var FUNCTION = {
className: 'function',
lexemes: UNDERSCORE_IDENT_RE,
variants: [
{begin: 'процедура|функция', end: '\\)', keywords: 'процедура функция'},
{begin: 'конецпроцедуры|конецфункции', keywords: 'конецпроцедуры конецфункции'}
],
contains: [
{
begin: '\\(', end: '\\)', endsParent : true,
contains: [
{
className: 'params',
lexemes: UNDERSCORE_IDENT_RE,
begin: UNDERSCORE_IDENT_RE, end: ',', excludeEnd: true, endsWithParent: true,
keywords: {
keyword: 'знач',
literal: LITERAL
},
contains: [
NUMBERS,
STRINGS,
DATE
]
},
COMMENTS
]
},
hljs.inherit(hljs.TITLE_MODE, {begin: UNDERSCORE_IDENT_RE})
]
};
return {
case_insensitive: true,
lexemes: UNDERSCORE_IDENT_RE,
keywords: {
keyword: KEYWORD,
built_in: BUILTIN,
class: CLASS,
type: TYPE,
literal: LITERAL
},
contains: [
META,
FUNCTION,
COMMENTS,
SYMBOL,
NUMBERS,
STRINGS,
DATE
]
}
}

View File

@ -0,0 +1,75 @@
/*
Language: Augmented Backus-Naur Form
Author: Alex McKibben <alex@nullscope.net>
*/
function(hljs) {
var regexes = {
ruleDeclaration: "^[a-zA-Z][a-zA-Z0-9-]*",
unexpectedChars: "[!@#$^&',?+~`|:]"
};
var keywords = [
"ALPHA",
"BIT",
"CHAR",
"CR",
"CRLF",
"CTL",
"DIGIT",
"DQUOTE",
"HEXDIG",
"HTAB",
"LF",
"LWSP",
"OCTET",
"SP",
"VCHAR",
"WSP"
];
var commentMode = hljs.COMMENT(";", "$");
var terminalBinaryMode = {
className: "symbol",
begin: /%b[0-1]+(-[0-1]+|(\.[0-1]+)+){0,1}/
};
var terminalDecimalMode = {
className: "symbol",
begin: /%d[0-9]+(-[0-9]+|(\.[0-9]+)+){0,1}/
};
var terminalHexadecimalMode = {
className: "symbol",
begin: /%x[0-9A-F]+(-[0-9A-F]+|(\.[0-9A-F]+)+){0,1}/,
};
var caseSensitivityIndicatorMode = {
className: "symbol",
begin: /%[si]/
};
var ruleDeclarationMode = {
begin: regexes.ruleDeclaration + '\\s*=',
returnBegin: true,
end: /=/,
relevance: 0,
contains: [{className: "attribute", begin: regexes.ruleDeclaration}]
};
return {
illegal: regexes.unexpectedChars,
keywords: keywords.join(" "),
contains: [
ruleDeclarationMode,
commentMode,
terminalBinaryMode,
terminalDecimalMode,
terminalHexadecimalMode,
caseSensitivityIndicatorMode,
hljs.QUOTE_STRING_MODE,
hljs.NUMBER_MODE
]
};
}

View File

@ -0,0 +1,43 @@
/*
Language: Access log
Author: Oleg Efimov <efimovov@gmail.com>
Description: Apache/Nginx Access Logs
*/
function(hljs) {
return {
contains: [
// IP
{
className: 'number',
begin: '\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}(:\\d{1,5})?\\b'
},
// Other numbers
{
className: 'number',
begin: '\\b\\d+\\b',
relevance: 0
},
// Requests
{
className: 'string',
begin: '"(GET|POST|HEAD|PUT|DELETE|CONNECT|OPTIONS|PATCH|TRACE)', end: '"',
keywords: 'GET POST HEAD PUT DELETE CONNECT OPTIONS PATCH TRACE',
illegal: '\\n',
relevance: 10
},
// Dates
{
className: 'string',
begin: /\[/, end: /\]/,
illegal: '\\n'
},
// Strings
{
className: 'string',
begin: '"', end: '"',
illegal: '\\n'
}
]
};
}

View File

@ -0,0 +1,79 @@
/*
Language: ActionScript
Author: Alexander Myadzel <myadzel@gmail.com>
Category: scripting
*/
function(hljs) {
var IDENT_RE = '[a-zA-Z_$][a-zA-Z0-9_$]*';
var IDENT_FUNC_RETURN_TYPE_RE = '([*]|[a-zA-Z_$][a-zA-Z0-9_$]*)';
var AS3_REST_ARG_MODE = {
className: 'rest_arg',
begin: '[.]{3}', end: IDENT_RE,
relevance: 10
};
return {
aliases: ['as'],
keywords: {
keyword: 'as break case catch class const continue default delete do dynamic each ' +
'else extends final finally for function get if implements import in include ' +
'instanceof interface internal is namespace native new override package private ' +
'protected public return set static super switch this throw try typeof use var void ' +
'while with',
literal: 'true false null undefined'
},
contains: [
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
hljs.C_NUMBER_MODE,
{
className: 'class',
beginKeywords: 'package', end: '{',
contains: [hljs.TITLE_MODE]
},
{
className: 'class',
beginKeywords: 'class interface', end: '{', excludeEnd: true,
contains: [
{
beginKeywords: 'extends implements'
},
hljs.TITLE_MODE
]
},
{
className: 'meta',
beginKeywords: 'import include', end: ';',
keywords: {'meta-keyword': 'import include'}
},
{
className: 'function',
beginKeywords: 'function', end: '[{;]', excludeEnd: true,
illegal: '\\S',
contains: [
hljs.TITLE_MODE,
{
className: 'params',
begin: '\\(', end: '\\)',
contains: [
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
AS3_REST_ARG_MODE
]
},
{
begin: ':\\s*' + IDENT_FUNC_RETURN_TYPE_RE
}
]
},
hljs.METHOD_GUARD
],
illegal: /#/
};
}

View File

@ -0,0 +1,181 @@
/*
Language: Ada
Author: Lars Schulna <kartoffelbrei.mit.muskatnuss@gmail.org>
Description: Ada is a general-purpose programming language that has great support for saftey critical and real-time applications.
It has been developed by the DoD and thus has been used in military and safety-critical applications (like civil aviation).
The first version appeared in the 80s, but it's still actively developed today with
the newest standard being Ada2012.
*/
// We try to support full Ada2012
//
// We highlight all appearances of types, keywords, literals (string, char, number, bool)
// and titles (user defined function/procedure/package)
// CSS classes are set accordingly
//
// Languages causing problems for language detection:
// xml (broken by Foo : Bar type), elm (broken by Foo : Bar type), vbscript-html (broken by body keyword)
// sql (ada default.txt has a lot of sql keywords)
function(hljs) {
// Regular expression for Ada numeric literals.
// stolen form the VHDL highlighter
// Decimal literal:
var INTEGER_RE = '\\d(_|\\d)*';
var EXPONENT_RE = '[eE][-+]?' + INTEGER_RE;
var DECIMAL_LITERAL_RE = INTEGER_RE + '(\\.' + INTEGER_RE + ')?' + '(' + EXPONENT_RE + ')?';
// Based literal:
var BASED_INTEGER_RE = '\\w+';
var BASED_LITERAL_RE = INTEGER_RE + '#' + BASED_INTEGER_RE + '(\\.' + BASED_INTEGER_RE + ')?' + '#' + '(' + EXPONENT_RE + ')?';
var NUMBER_RE = '\\b(' + BASED_LITERAL_RE + '|' + DECIMAL_LITERAL_RE + ')';
// Identifier regex
var ID_REGEX = '[A-Za-z](_?[A-Za-z0-9.])*';
// bad chars, only allowed in literals
var BAD_CHARS = '[]{}%#\'\"'
// Ada doesn't have block comments, only line comments
var COMMENTS = hljs.COMMENT('--', '$');
// variable declarations of the form
// Foo : Bar := Baz;
// where only Bar will be highlighted
var VAR_DECLS = {
// TODO: These spaces are not required by the Ada syntax
// however, I have yet to see handwritten Ada code where
// someone does not put spaces around :
begin: '\\s+:\\s+', end: '\\s*(:=|;|\\)|=>|$)',
// endsWithParent: true,
// returnBegin: true,
illegal: BAD_CHARS,
contains: [
{
// workaround to avoid highlighting
// named loops and declare blocks
beginKeywords: 'loop for declare others',
endsParent: true,
},
{
// properly highlight all modifiers
className: 'keyword',
beginKeywords: 'not null constant access function procedure in out aliased exception'
},
{
className: 'type',
begin: ID_REGEX,
endsParent: true,
relevance: 0,
}
]
};
return {
case_insensitive: true,
keywords: {
keyword:
'abort else new return abs elsif not reverse abstract end ' +
'accept entry select access exception of separate aliased exit or some ' +
'all others subtype and for out synchronized array function overriding ' +
'at tagged generic package task begin goto pragma terminate ' +
'body private then if procedure type case in protected constant interface ' +
'is raise use declare range delay limited record when delta loop rem while ' +
'digits renames with do mod requeue xor',
literal:
'True False',
},
contains: [
COMMENTS,
// strings "foobar"
{
className: 'string',
begin: /"/, end: /"/,
contains: [{begin: /""/, relevance: 0}]
},
// characters ''
{
// character literals always contain one char
className: 'string',
begin: /'.'/
},
{
// number literals
className: 'number',
begin: NUMBER_RE,
relevance: 0
},
{
// Attributes
className: 'symbol',
begin: "'" + ID_REGEX,
},
{
// package definition, maybe inside generic
className: 'title',
begin: '(\\bwith\\s+)?(\\bprivate\\s+)?\\bpackage\\s+(\\bbody\\s+)?', end: '(is|$)',
keywords: 'package body',
excludeBegin: true,
excludeEnd: true,
illegal: BAD_CHARS
},
{
// function/procedure declaration/definition
// maybe inside generic
begin: '(\\b(with|overriding)\\s+)?\\b(function|procedure)\\s+', end: '(\\bis|\\bwith|\\brenames|\\)\\s*;)',
keywords: 'overriding function procedure with is renames return',
// we need to re-match the 'function' keyword, so that
// the title mode below matches only exactly once
returnBegin: true,
contains:
[
COMMENTS,
{
// name of the function/procedure
className: 'title',
begin: '(\\bwith\\s+)?\\b(function|procedure)\\s+',
end: '(\\(|\\s+|$)',
excludeBegin: true,
excludeEnd: true,
illegal: BAD_CHARS
},
// 'self'
// // parameter types
VAR_DECLS,
{
// return type
className: 'type',
begin: '\\breturn\\s+', end: '(\\s+|;|$)',
keywords: 'return',
excludeBegin: true,
excludeEnd: true,
// we are done with functions
endsParent: true,
illegal: BAD_CHARS
},
]
},
{
// new type declarations
// maybe inside generic
className: 'type',
begin: '\\b(sub)?type\\s+', end: '\\s+',
keywords: 'type',
excludeBegin: true,
illegal: BAD_CHARS
},
// see comment above the definition
VAR_DECLS,
// no markup
// relevance boosters for small snippets
// {begin: '\\s*=>\\s*'},
// {begin: '\\s*:=\\s*'},
// {begin: '\\s+:=\\s+'},
]
};
}

View File

@ -0,0 +1,112 @@
/*
Language: AngelScript
Author: Melissa Geels <melissa@nimble.tools>
Category: scripting
*/
function(hljs) {
var builtInTypeMode = {
className: 'built_in',
begin: '\\b(void|bool|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|string|ref|array|double|float|auto|dictionary)'
};
var objectHandleMode = {
className: 'symbol',
begin: '[a-zA-Z0-9_]+@'
};
var genericMode = {
className: 'keyword',
begin: '<', end: '>',
contains: [ builtInTypeMode, objectHandleMode ]
};
builtInTypeMode.contains = [ genericMode ];
objectHandleMode.contains = [ genericMode ];
return {
aliases: [ 'asc' ],
keywords:
'for in|0 break continue while do|0 return if else case switch namespace is cast ' +
'or and xor not get|0 in inout|10 out override set|0 private public const default|0 ' +
'final shared external mixin|10 enum typedef funcdef this super import from interface ' +
'abstract|0 try catch protected explicit',
// avoid close detection with C# and JS
illegal: '(^using\\s+[A-Za-z0-9_\\.]+;$|\\bfunction\s*[^\\(])',
contains: [
{ // 'strings'
className: 'string',
begin: '\'', end: '\'',
illegal: '\\n',
contains: [ hljs.BACKSLASH_ESCAPE ],
relevance: 0
},
{ // "strings"
className: 'string',
begin: '"', end: '"',
illegal: '\\n',
contains: [ hljs.BACKSLASH_ESCAPE ],
relevance: 0
},
// """heredoc strings"""
{
className: 'string',
begin: '"""', end: '"""'
},
hljs.C_LINE_COMMENT_MODE, // single-line comments
hljs.C_BLOCK_COMMENT_MODE, // comment blocks
{ // interface or namespace declaration
beginKeywords: 'interface namespace', end: '{',
illegal: '[;.\\-]',
contains: [
{ // interface or namespace name
className: 'symbol',
begin: '[a-zA-Z0-9_]+'
}
]
},
{ // class declaration
beginKeywords: 'class', end: '{',
illegal: '[;.\\-]',
contains: [
{ // class name
className: 'symbol',
begin: '[a-zA-Z0-9_]+',
contains: [
{
begin: '[:,]\\s*',
contains: [
{
className: 'symbol',
begin: '[a-zA-Z0-9_]+'
}
]
}
]
}
]
},
builtInTypeMode, // built-in types
objectHandleMode, // object handles
{ // literals
className: 'literal',
begin: '\\b(null|true|false)'
},
{ // numbers
className: 'number',
begin: '(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?f?|\\.\\d+f?)([eE][-+]?\\d+f?)?)'
}
]
};
}

View File

@ -0,0 +1,54 @@
/*
Language: Apache
Author: Ruslan Keba <rukeba@gmail.com>
Contributors: Ivan Sagalaev <maniac@softwaremaniacs.org>
Website: http://rukeba.com/
Description: language definition for Apache configuration files (httpd.conf & .htaccess)
Category: common, config
*/
function(hljs) {
var NUMBER = {className: 'number', begin: '[\\$%]\\d+'};
return {
aliases: ['apacheconf'],
case_insensitive: true,
contains: [
hljs.HASH_COMMENT_MODE,
{className: 'section', begin: '</?', end: '>'},
{
className: 'attribute',
begin: /\w+/,
relevance: 0,
// keywords arent needed for highlighting per se, they only boost relevance
// for a very generally defined mode (starts with a word, ends with line-end
keywords: {
nomarkup:
'order deny allow setenv rewriterule rewriteengine rewritecond documentroot ' +
'sethandler errordocument loadmodule options header listen serverroot ' +
'servername'
},
starts: {
end: /$/,
relevance: 0,
keywords: {
literal: 'on off all'
},
contains: [
{
className: 'meta',
begin: '\\s\\[', end: '\\]$'
},
{
className: 'variable',
begin: '[\\$%]\\{', end: '\\}',
contains: ['self', NUMBER]
},
NUMBER,
hljs.QUOTE_STRING_MODE
]
}
}
],
illegal: /\S/
};
}

View File

@ -0,0 +1,91 @@
/*
Language: AppleScript
Authors: Nathan Grigg <nathan@nathanamy.org>, Dr. Drang <drdrang@gmail.com>
Category: scripting
*/
function(hljs) {
var STRING = hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: ''});
var PARAMS = {
className: 'params',
begin: '\\(', end: '\\)',
contains: ['self', hljs.C_NUMBER_MODE, STRING]
};
var COMMENT_MODE_1 = hljs.COMMENT('--', '$');
var COMMENT_MODE_2 = hljs.COMMENT(
'\\(\\*',
'\\*\\)',
{
contains: ['self', COMMENT_MODE_1] //allow nesting
}
);
var COMMENTS = [
COMMENT_MODE_1,
COMMENT_MODE_2,
hljs.HASH_COMMENT_MODE
];
return {
aliases: ['osascript'],
keywords: {
keyword:
'about above after against and around as at back before beginning ' +
'behind below beneath beside between but by considering ' +
'contain contains continue copy div does eighth else end equal ' +
'equals error every exit fifth first for fourth from front ' +
'get given global if ignoring in into is it its last local me ' +
'middle mod my ninth not of on onto or over prop property put ref ' +
'reference repeat returning script second set seventh since ' +
'sixth some tell tenth that the|0 then third through thru ' +
'timeout times to transaction try until where while whose with ' +
'without',
literal:
'AppleScript false linefeed return pi quote result space tab true',
built_in:
'alias application boolean class constant date file integer list ' +
'number real record string text ' +
'activate beep count delay launch log offset read round ' +
'run say summarize write ' +
'character characters contents day frontmost id item length ' +
'month name paragraph paragraphs rest reverse running time version ' +
'weekday word words year'
},
contains: [
STRING,
hljs.C_NUMBER_MODE,
{
className: 'built_in',
begin:
'\\b(clipboard info|the clipboard|info for|list (disks|folder)|' +
'mount volume|path to|(close|open for) access|(get|set) eof|' +
'current date|do shell script|get volume settings|random number|' +
'set volume|system attribute|system info|time to GMT|' +
'(load|run|store) script|scripting components|' +
'ASCII (character|number)|localized string|' +
'choose (application|color|file|file name|' +
'folder|from list|remote application|URL)|' +
'display (alert|dialog))\\b|^\\s*return\\b'
},
{
className: 'literal',
begin:
'\\b(text item delimiters|current application|missing value)\\b'
},
{
className: 'keyword',
begin:
'\\b(apart from|aside from|instead of|out of|greater than|' +
"isn't|(doesn't|does not) (equal|come before|come after|contain)|" +
'(greater|less) than( or equal)?|(starts?|ends|begins?) with|' +
'contained by|comes (before|after)|a (ref|reference)|POSIX file|' +
'POSIX path|(date|time) string|quoted form)\\b'
},
{
beginKeywords: 'on',
illegal: '[${=;\\n]',
contains: [hljs.UNDERSCORE_TITLE_MODE, PARAMS]
}
].concat(COMMENTS),
illegal: '//|->|=>|\\[\\['
};
}

View File

@ -0,0 +1,142 @@
/*
Language: ArcGIS Arcade
Category: scripting
Author: John Foster <jfoster@esri.com>
Description: ArcGIS Arcade is an expression language used in many Esri ArcGIS products such as Pro, Online, Server, Runtime, JavaScript, and Python
*/
function(hljs) {
var IDENT_RE = '[A-Za-z_][0-9A-Za-z_]*';
var KEYWORDS = {
keyword:
'if for while var new function do return void else break',
literal:
'true false null undefined NaN Infinity PI BackSlash DoubleQuote ForwardSlash NewLine SingleQuote Tab',
built_in:
'Abs Acos Area AreaGeodetic Asin Atan Atan2 Average Boolean Buffer BufferGeodetic ' +
'Ceil Centroid Clip Console Constrain Contains Cos Count Crosses Cut Date DateAdd ' +
'DateDiff Day Decode DefaultValue Dictionary Difference Disjoint Distance Distinct ' +
'DomainCode DomainName Equals Exp Extent Feature FeatureSet FeatureSetById FeatureSetByTitle ' +
'FeatureSetByUrl Filter First Floor Geometry Guid HasKey Hour IIf IndexOf Intersection ' +
'Intersects IsEmpty Length LengthGeodetic Log Max Mean Millisecond Min Minute Month ' +
'MultiPartToSinglePart Multipoint NextSequenceValue Now Number OrderBy Overlaps Point Polygon ' +
'Polyline Pow Random Relate Reverse Round Second SetGeometry Sin Sort Sqrt Stdev Sum ' +
'SymmetricDifference Tan Text Timestamp Today ToLocal Top Touches ToUTC TypeOf Union Variance ' +
'Weekday When Within Year '
};
var EXPRESSIONS;
var SYMBOL = {
className: 'symbol',
begin: '\\$[feature|layer|map|value|view]+'
};
var NUMBER = {
className: 'number',
variants: [
{ begin: '\\b(0[bB][01]+)' },
{ begin: '\\b(0[oO][0-7]+)' },
{ begin: hljs.C_NUMBER_RE }
],
relevance: 0
};
var SUBST = {
className: 'subst',
begin: '\\$\\{', end: '\\}',
keywords: KEYWORDS,
contains: [] // defined later
};
var TEMPLATE_STRING = {
className: 'string',
begin: '`', end: '`',
contains: [
hljs.BACKSLASH_ESCAPE,
SUBST
]
};
SUBST.contains = [
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
TEMPLATE_STRING,
NUMBER,
hljs.REGEXP_MODE
];
var PARAMS_CONTAINS = SUBST.contains.concat([
hljs.C_BLOCK_COMMENT_MODE,
hljs.C_LINE_COMMENT_MODE
]);
return {
aliases: ['arcade'],
keywords: KEYWORDS,
contains: [
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
TEMPLATE_STRING,
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
SYMBOL,
NUMBER,
{ // object attr container
begin: /[{,]\s*/, relevance: 0,
contains: [
{
begin: IDENT_RE + '\\s*:', returnBegin: true,
relevance: 0,
contains: [{className: 'attr', begin: IDENT_RE, relevance: 0}]
}
]
},
{ // "value" container
begin: '(' + hljs.RE_STARTERS_RE + '|\\b(return)\\b)\\s*',
keywords: 'return',
contains: [
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
hljs.REGEXP_MODE,
{
className: 'function',
begin: '(\\(.*?\\)|' + IDENT_RE + ')\\s*=>', returnBegin: true,
end: '\\s*=>',
contains: [
{
className: 'params',
variants: [
{
begin: IDENT_RE
},
{
begin: /\(\s*\)/,
},
{
begin: /\(/, end: /\)/,
excludeBegin: true, excludeEnd: true,
keywords: KEYWORDS,
contains: PARAMS_CONTAINS
}
]
}
]
}
],
relevance: 0
},
{
className: 'function',
beginKeywords: 'function', end: /\{/, excludeEnd: true,
contains: [
hljs.inherit(hljs.TITLE_MODE, {begin: IDENT_RE}),
{
className: 'params',
begin: /\(/, end: /\)/,
excludeBegin: true,
excludeEnd: true,
contains: PARAMS_CONTAINS
}
],
illegal: /\[|%/
},
{
begin: /\$[(.]/
}
],
illegal: /#(?!!)/
};
}

View File

@ -0,0 +1,106 @@
/*
Language: Arduino
Author: Stefania Mellai <s.mellai@arduino.cc>
Description: The Arduino® Language is a superset of C++. This rules are designed to highlight the Arduino® source code. For info about language see http://www.arduino.cc.
Requires: cpp.js
*/
function(hljs) {
var CPP = hljs.getLanguage('cpp').exports;
return {
keywords: {
keyword:
'boolean byte word string String array ' + CPP.keywords.keyword,
built_in:
'setup loop while catch for if do goto try switch case else ' +
'default break continue return ' +
'KeyboardController MouseController SoftwareSerial ' +
'EthernetServer EthernetClient LiquidCrystal ' +
'RobotControl GSMVoiceCall EthernetUDP EsploraTFT ' +
'HttpClient RobotMotor WiFiClient GSMScanner ' +
'FileSystem Scheduler GSMServer YunClient YunServer ' +
'IPAddress GSMClient GSMModem Keyboard Ethernet ' +
'Console GSMBand Esplora Stepper Process ' +
'WiFiUDP GSM_SMS Mailbox USBHost Firmata PImage ' +
'Client Server GSMPIN FileIO Bridge Serial ' +
'EEPROM Stream Mouse Audio Servo File Task ' +
'GPRS WiFi Wire TFT GSM SPI SD ' +
'runShellCommandAsynchronously analogWriteResolution ' +
'retrieveCallingNumber printFirmwareVersion ' +
'analogReadResolution sendDigitalPortPair ' +
'noListenOnLocalhost readJoystickButton setFirmwareVersion ' +
'readJoystickSwitch scrollDisplayRight getVoiceCallStatus ' +
'scrollDisplayLeft writeMicroseconds delayMicroseconds ' +
'beginTransmission getSignalStrength runAsynchronously ' +
'getAsynchronously listenOnLocalhost getCurrentCarrier ' +
'readAccelerometer messageAvailable sendDigitalPorts ' +
'lineFollowConfig countryNameWrite runShellCommand ' +
'readStringUntil rewindDirectory readTemperature ' +
'setClockDivider readLightSensor endTransmission ' +
'analogReference detachInterrupt countryNameRead ' +
'attachInterrupt encryptionType readBytesUntil ' +
'robotNameWrite readMicrophone robotNameRead cityNameWrite ' +
'userNameWrite readJoystickY readJoystickX mouseReleased ' +
'openNextFile scanNetworks noInterrupts digitalWrite ' +
'beginSpeaker mousePressed isActionDone mouseDragged ' +
'displayLogos noAutoscroll addParameter remoteNumber ' +
'getModifiers keyboardRead userNameRead waitContinue ' +
'processInput parseCommand printVersion readNetworks ' +
'writeMessage blinkVersion cityNameRead readMessage ' +
'setDataMode parsePacket isListening setBitOrder ' +
'beginPacket isDirectory motorsWrite drawCompass ' +
'digitalRead clearScreen serialEvent rightToLeft ' +
'setTextSize leftToRight requestFrom keyReleased ' +
'compassRead analogWrite interrupts WiFiServer ' +
'disconnect playMelody parseFloat autoscroll ' +
'getPINUsed setPINUsed setTimeout sendAnalog ' +
'readSlider analogRead beginWrite createChar ' +
'motorsStop keyPressed tempoWrite readButton ' +
'subnetMask debugPrint macAddress writeGreen ' +
'randomSeed attachGPRS readString sendString ' +
'remotePort releaseAll mouseMoved background ' +
'getXChange getYChange answerCall getResult ' +
'voiceCall endPacket constrain getSocket writeJSON ' +
'getButton available connected findUntil readBytes ' +
'exitValue readGreen writeBlue startLoop IPAddress ' +
'isPressed sendSysex pauseMode gatewayIP setCursor ' +
'getOemKey tuneWrite noDisplay loadImage switchPIN ' +
'onRequest onReceive changePIN playFile noBuffer ' +
'parseInt overflow checkPIN knobRead beginTFT ' +
'bitClear updateIR bitWrite position writeRGB ' +
'highByte writeRed setSpeed readBlue noStroke ' +
'remoteIP transfer shutdown hangCall beginSMS ' +
'endWrite attached maintain noCursor checkReg ' +
'checkPUK shiftOut isValid shiftIn pulseIn ' +
'connect println localIP pinMode getIMEI ' +
'display noBlink process getBand running beginSD ' +
'drawBMP lowByte setBand release bitRead prepare ' +
'pointTo readRed setMode noFill remove listen ' +
'stroke detach attach noTone exists buffer ' +
'height bitSet circle config cursor random ' +
'IRread setDNS endSMS getKey micros ' +
'millis begin print write ready flush width ' +
'isPIN blink clear press mkdir rmdir close ' +
'point yield image BSSID click delay ' +
'read text move peek beep rect line open ' +
'seek fill size turn stop home find ' +
'step tone sqrt RSSI SSID ' +
'end bit tan cos sin pow map abs max ' +
'min get run put',
literal:
'DIGITAL_MESSAGE FIRMATA_STRING ANALOG_MESSAGE ' +
'REPORT_DIGITAL REPORT_ANALOG INPUT_PULLUP ' +
'SET_PIN_MODE INTERNAL2V56 SYSTEM_RESET LED_BUILTIN ' +
'INTERNAL1V1 SYSEX_START INTERNAL EXTERNAL ' +
'DEFAULT OUTPUT INPUT HIGH LOW'
},
contains: [
CPP.preprocessor,
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
hljs.C_NUMBER_MODE
]
};
}

View File

@ -0,0 +1,98 @@
/*
Language: ARM Assembly
Author: Dan Panzarella <alsoelp@gmail.com>
Description: ARM Assembly including Thumb and Thumb2 instructions
Category: assembler
*/
function(hljs) {
//local labels: %?[FB]?[AT]?\d{1,2}\w+
return {
case_insensitive: true,
aliases: ['arm'],
lexemes: '\\.?' + hljs.IDENT_RE,
keywords: {
meta:
//GNU preprocs
'.2byte .4byte .align .ascii .asciz .balign .byte .code .data .else .end .endif .endm .endr .equ .err .exitm .extern .global .hword .if .ifdef .ifndef .include .irp .long .macro .rept .req .section .set .skip .space .text .word .arm .thumb .code16 .code32 .force_thumb .thumb_func .ltorg '+
//ARM directives
'ALIAS ALIGN ARM AREA ASSERT ATTR CN CODE CODE16 CODE32 COMMON CP DATA DCB DCD DCDU DCDO DCFD DCFDU DCI DCQ DCQU DCW DCWU DN ELIF ELSE END ENDFUNC ENDIF ENDP ENTRY EQU EXPORT EXPORTAS EXTERN FIELD FILL FUNCTION GBLA GBLL GBLS GET GLOBAL IF IMPORT INCBIN INCLUDE INFO KEEP LCLA LCLL LCLS LTORG MACRO MAP MEND MEXIT NOFP OPT PRESERVE8 PROC QN READONLY RELOC REQUIRE REQUIRE8 RLIST FN ROUT SETA SETL SETS SN SPACE SUBT THUMB THUMBX TTL WHILE WEND ',
built_in:
'r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 '+ //standard registers
'pc lr sp ip sl sb fp '+ //typical regs plus backward compatibility
'a1 a2 a3 a4 v1 v2 v3 v4 v5 v6 v7 v8 f0 f1 f2 f3 f4 f5 f6 f7 '+ //more regs and fp
'p0 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 '+ //coprocessor regs
'c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15 '+ //more coproc
'q0 q1 q2 q3 q4 q5 q6 q7 q8 q9 q10 q11 q12 q13 q14 q15 '+ //advanced SIMD NEON regs
//program status registers
'cpsr_c cpsr_x cpsr_s cpsr_f cpsr_cx cpsr_cxs cpsr_xs cpsr_xsf cpsr_sf cpsr_cxsf '+
'spsr_c spsr_x spsr_s spsr_f spsr_cx spsr_cxs spsr_xs spsr_xsf spsr_sf spsr_cxsf '+
//NEON and VFP registers
's0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13 s14 s15 '+
's16 s17 s18 s19 s20 s21 s22 s23 s24 s25 s26 s27 s28 s29 s30 s31 '+
'd0 d1 d2 d3 d4 d5 d6 d7 d8 d9 d10 d11 d12 d13 d14 d15 '+
'd16 d17 d18 d19 d20 d21 d22 d23 d24 d25 d26 d27 d28 d29 d30 d31 ' +
'{PC} {VAR} {TRUE} {FALSE} {OPT} {CONFIG} {ENDIAN} {CODESIZE} {CPU} {FPU} {ARCHITECTURE} {PCSTOREOFFSET} {ARMASM_VERSION} {INTER} {ROPI} {RWPI} {SWST} {NOSWST} . @'
},
contains: [
{
className: 'keyword',
begin: '\\b('+ //mnemonics
'adc|'+
'(qd?|sh?|u[qh]?)?add(8|16)?|usada?8|(q|sh?|u[qh]?)?(as|sa)x|'+
'and|adrl?|sbc|rs[bc]|asr|b[lx]?|blx|bxj|cbn?z|tb[bh]|bic|'+
'bfc|bfi|[su]bfx|bkpt|cdp2?|clz|clrex|cmp|cmn|cpsi[ed]|cps|'+
'setend|dbg|dmb|dsb|eor|isb|it[te]{0,3}|lsl|lsr|ror|rrx|'+
'ldm(([id][ab])|f[ds])?|ldr((s|ex)?[bhd])?|movt?|mvn|mra|mar|'+
'mul|[us]mull|smul[bwt][bt]|smu[as]d|smmul|smmla|'+
'mla|umlaal|smlal?([wbt][bt]|d)|mls|smlsl?[ds]|smc|svc|sev|'+
'mia([bt]{2}|ph)?|mrr?c2?|mcrr2?|mrs|msr|orr|orn|pkh(tb|bt)|rbit|'+
'rev(16|sh)?|sel|[su]sat(16)?|nop|pop|push|rfe([id][ab])?|'+
'stm([id][ab])?|str(ex)?[bhd]?|(qd?)?sub|(sh?|q|u[qh]?)?sub(8|16)|'+
'[su]xt(a?h|a?b(16)?)|srs([id][ab])?|swpb?|swi|smi|tst|teq|'+
'wfe|wfi|yield'+
')'+
'(eq|ne|cs|cc|mi|pl|vs|vc|hi|ls|ge|lt|gt|le|al|hs|lo)?'+ //condition codes
'[sptrx]?' , //legal postfixes
end: '\\s'
},
hljs.COMMENT('[;@]', '$', {relevance: 0}),
hljs.C_BLOCK_COMMENT_MODE,
hljs.QUOTE_STRING_MODE,
{
className: 'string',
begin: '\'',
end: '[^\\\\]\'',
relevance: 0
},
{
className: 'title',
begin: '\\|', end: '\\|',
illegal: '\\n',
relevance: 0
},
{
className: 'number',
variants: [
{begin: '[#$=]?0x[0-9a-f]+'}, //hex
{begin: '[#$=]?0b[01]+'}, //bin
{begin: '[#$=]\\d+'}, //literal
{begin: '\\b\\d+'} //bare number
],
relevance: 0
},
{
className: 'symbol',
variants: [
{begin: '^[a-z_\\.\\$][a-z0-9_\\.\\$]+'}, //ARM syntax
{begin: '^\\s*[a-z_\\.\\$][a-z0-9_\\.\\$]+:'}, //GNU ARM syntax
{begin: '[=#]\\w+' } //label reference
],
relevance: 0
}
]
};
}

View File

@ -0,0 +1,196 @@
/*
Language: AsciiDoc
Requires: xml.js
Author: Dan Allen <dan.j.allen@gmail.com>
Website: http://google.com/profiles/dan.j.allen
Description: A semantic, text-based document format that can be exported to HTML, DocBook and other backends.
Category: markup
*/
function(hljs) {
return {
aliases: ['adoc'],
contains: [
// block comment
hljs.COMMENT(
'^/{4,}\\n',
'\\n/{4,}$',
// can also be done as...
//'^/{4,}$',
//'^/{4,}$',
{
relevance: 10
}
),
// line comment
hljs.COMMENT(
'^//',
'$',
{
relevance: 0
}
),
// title
{
className: 'title',
begin: '^\\.\\w.*$'
},
// example, admonition & sidebar blocks
{
begin: '^[=\\*]{4,}\\n',
end: '\\n^[=\\*]{4,}$',
relevance: 10
},
// headings
{
className: 'section',
relevance: 10,
variants: [
{begin: '^(={1,5}) .+?( \\1)?$'},
{begin: '^[^\\[\\]\\n]+?\\n[=\\-~\\^\\+]{2,}$'},
]
},
// document attributes
{
className: 'meta',
begin: '^:.+?:',
end: '\\s',
excludeEnd: true,
relevance: 10
},
// block attributes
{
className: 'meta',
begin: '^\\[.+?\\]$',
relevance: 0
},
// quoteblocks
{
className: 'quote',
begin: '^_{4,}\\n',
end: '\\n_{4,}$',
relevance: 10
},
// listing and literal blocks
{
className: 'code',
begin: '^[\\-\\.]{4,}\\n',
end: '\\n[\\-\\.]{4,}$',
relevance: 10
},
// passthrough blocks
{
begin: '^\\+{4,}\\n',
end: '\\n\\+{4,}$',
contains: [
{
begin: '<', end: '>',
subLanguage: 'xml',
relevance: 0
}
],
relevance: 10
},
// lists (can only capture indicators)
{
className: 'bullet',
begin: '^(\\*+|\\-+|\\.+|[^\\n]+?::)\\s+'
},
// admonition
{
className: 'symbol',
begin: '^(NOTE|TIP|IMPORTANT|WARNING|CAUTION):\\s+',
relevance: 10
},
// inline strong
{
className: 'strong',
// must not follow a word character or be followed by an asterisk or space
begin: '\\B\\*(?![\\*\\s])',
end: '(\\n{2}|\\*)',
// allow escaped asterisk followed by word char
contains: [
{
begin: '\\\\*\\w',
relevance: 0
}
]
},
// inline emphasis
{
className: 'emphasis',
// must not follow a word character or be followed by a single quote or space
begin: '\\B\'(?![\'\\s])',
end: '(\\n{2}|\')',
// allow escaped single quote followed by word char
contains: [
{
begin: '\\\\\'\\w',
relevance: 0
}
],
relevance: 0
},
// inline emphasis (alt)
{
className: 'emphasis',
// must not follow a word character or be followed by an underline or space
begin: '_(?![_\\s])',
end: '(\\n{2}|_)',
relevance: 0
},
// inline smart quotes
{
className: 'string',
variants: [
{begin: "``.+?''"},
{begin: "`.+?'"}
]
},
// inline code snippets (TODO should get same treatment as strong and emphasis)
{
className: 'code',
begin: '(`.+?`|\\+.+?\\+)',
relevance: 0
},
// indented literal block
{
className: 'code',
begin: '^[ \\t]',
end: '$',
relevance: 0
},
// horizontal rules
{
begin: '^\'{3,}[ \\t]*$',
relevance: 10
},
// images and links
{
begin: '(link:)?(http|https|ftp|file|irc|image:?):\\S+\\[.*?\\]',
returnBegin: true,
contains: [
{
begin: '(link|image:?):',
relevance: 0
},
{
className: 'link',
begin: '\\w',
end: '[^\\[]+',
relevance: 0
},
{
className: 'string',
begin: '\\[',
end: '\\]',
excludeBegin: true,
excludeEnd: true,
relevance: 0
}
],
relevance: 10
}
]
};
}

View File

@ -0,0 +1,149 @@
/*
Language: AspectJ
Author: Hakan Ozler <ozler.hakan@gmail.com>
Description: Syntax Highlighting for the AspectJ Language which is a general-purpose aspect-oriented extension to the Java programming language.
*/
function (hljs) {
var KEYWORDS =
'false synchronized int abstract float private char boolean static null if const ' +
'for true while long throw strictfp finally protected import native final return void ' +
'enum else extends implements break transient new catch instanceof byte super volatile case ' +
'assert short package default double public try this switch continue throws privileged ' +
'aspectOf adviceexecution proceed cflowbelow cflow initialization preinitialization ' +
'staticinitialization withincode target within execution getWithinTypeName handler ' +
'thisJoinPoint thisJoinPointStaticPart thisEnclosingJoinPointStaticPart declare parents '+
'warning error soft precedence thisAspectInstance';
var SHORTKEYS = 'get set args call';
return {
keywords : KEYWORDS,
illegal : /<\/|#/,
contains : [
hljs.COMMENT(
'/\\*\\*',
'\\*/',
{
relevance : 0,
contains : [
{
// eat up @'s in emails to prevent them to be recognized as doctags
begin: /\w+@/, relevance: 0
},
{
className : 'doctag',
begin : '@[A-Za-z]+'
}
]
}
),
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
{
className : 'class',
beginKeywords : 'aspect',
end : /[{;=]/,
excludeEnd : true,
illegal : /[:;"\[\]]/,
contains : [
{
beginKeywords : 'extends implements pertypewithin perthis pertarget percflowbelow percflow issingleton'
},
hljs.UNDERSCORE_TITLE_MODE,
{
begin : /\([^\)]*/,
end : /[)]+/,
keywords : KEYWORDS + ' ' + SHORTKEYS,
excludeEnd : false
}
]
},
{
className : 'class',
beginKeywords : 'class interface',
end : /[{;=]/,
excludeEnd : true,
relevance: 0,
keywords : 'class interface',
illegal : /[:"\[\]]/,
contains : [
{beginKeywords : 'extends implements'},
hljs.UNDERSCORE_TITLE_MODE
]
},
{
// AspectJ Constructs
beginKeywords : 'pointcut after before around throwing returning',
end : /[)]/,
excludeEnd : false,
illegal : /["\[\]]/,
contains : [
{
begin : hljs.UNDERSCORE_IDENT_RE + '\\s*\\(',
returnBegin : true,
contains : [hljs.UNDERSCORE_TITLE_MODE]
}
]
},
{
begin : /[:]/,
returnBegin : true,
end : /[{;]/,
relevance: 0,
excludeEnd : false,
keywords : KEYWORDS,
illegal : /["\[\]]/,
contains : [
{
begin : hljs.UNDERSCORE_IDENT_RE + '\\s*\\(',
keywords : KEYWORDS + ' ' + SHORTKEYS,
relevance: 0
},
hljs.QUOTE_STRING_MODE
]
},
{
// this prevents 'new Name(...), or throw ...' from being recognized as a function definition
beginKeywords : 'new throw',
relevance : 0
},
{
// the function class is a bit different for AspectJ compared to the Java language
className : 'function',
begin : /\w+ +\w+(\.)?\w+\s*\([^\)]*\)\s*((throws)[\w\s,]+)?[\{;]/,
returnBegin : true,
end : /[{;=]/,
keywords : KEYWORDS,
excludeEnd : true,
contains : [
{
begin : hljs.UNDERSCORE_IDENT_RE + '\\s*\\(',
returnBegin : true,
relevance: 0,
contains : [hljs.UNDERSCORE_TITLE_MODE]
},
{
className : 'params',
begin : /\(/, end : /\)/,
relevance: 0,
keywords : KEYWORDS,
contains : [
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
hljs.C_NUMBER_MODE,
hljs.C_BLOCK_COMMENT_MODE
]
},
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE
]
},
hljs.C_NUMBER_MODE,
{
// annotation is also used in this language
className : 'meta',
begin : '@[A-Za-z]+'
}
]
};
}

View File

@ -0,0 +1,65 @@
/*
Language: AutoHotkey
Author: Seongwon Lee <dlimpid@gmail.com>
Description: AutoHotkey language definition
Category: scripting
*/
function(hljs) {
var BACKTICK_ESCAPE = {
begin: '`[\\s\\S]'
};
return {
case_insensitive: true,
aliases: [ 'ahk' ],
keywords: {
keyword: 'Break Continue Critical Exit ExitApp Gosub Goto New OnExit Pause return SetBatchLines SetTimer Suspend Thread Throw Until ahk_id ahk_class ahk_pid ahk_exe ahk_group',
literal: 'A|0 true false NOT AND OR',
built_in: 'ComSpec Clipboard ClipboardAll ErrorLevel',
},
contains: [
{
className: 'built_in',
begin: 'A_[a-zA-Z0-9]+'
},
BACKTICK_ESCAPE,
hljs.inherit(hljs.QUOTE_STRING_MODE, {contains: [BACKTICK_ESCAPE]}),
hljs.COMMENT(';', '$', {relevance: 0}),
hljs.C_BLOCK_COMMENT_MODE,
{
className: 'number',
begin: hljs.NUMBER_RE,
relevance: 0
},
{
className: 'subst', // FIXED
begin: '%(?=[a-zA-Z0-9#_$@])', end: '%',
illegal: '[^a-zA-Z0-9#_$@]'
},
{
className: 'built_in',
begin: '^\\s*\\w+\\s*,'
//I don't really know if this is totally relevant
},
{
className: 'meta',
begin: '^\\s*#\w+', end:'$',
relevance: 0
},
{
className: 'symbol',
contains: [BACKTICK_ESCAPE],
variants: [
{begin: '^[^\\n";]+::(?!=)'},
{begin: '^[^\\n";]+:(?!=)', relevance: 0} // zero relevance as it catches a lot of things
// followed by a single ':' in many languages
]
},
{
// consecutive commas, not for highlighting but just for relevance
begin: ',\\s*,'
}
]
}
}

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,67 @@
/*
Language: AVR Assembler
Author: Vladimir Ermakov <vooon341@gmail.com>
Category: assembler
*/
function(hljs) {
return {
case_insensitive: true,
lexemes: '\\.?' + hljs.IDENT_RE,
keywords: {
keyword:
/* mnemonic */
'adc add adiw and andi asr bclr bld brbc brbs brcc brcs break breq brge brhc brhs ' +
'brid brie brlo brlt brmi brne brpl brsh brtc brts brvc brvs bset bst call cbi cbr ' +
'clc clh cli cln clr cls clt clv clz com cp cpc cpi cpse dec eicall eijmp elpm eor ' +
'fmul fmuls fmulsu icall ijmp in inc jmp ld ldd ldi lds lpm lsl lsr mov movw mul ' +
'muls mulsu neg nop or ori out pop push rcall ret reti rjmp rol ror sbc sbr sbrc sbrs ' +
'sec seh sbi sbci sbic sbis sbiw sei sen ser ses set sev sez sleep spm st std sts sub ' +
'subi swap tst wdr',
built_in:
/* general purpose registers */
'r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 ' +
'r23 r24 r25 r26 r27 r28 r29 r30 r31 x|0 xh xl y|0 yh yl z|0 zh zl ' +
/* IO Registers (ATMega128) */
'ucsr1c udr1 ucsr1a ucsr1b ubrr1l ubrr1h ucsr0c ubrr0h tccr3c tccr3a tccr3b tcnt3h ' +
'tcnt3l ocr3ah ocr3al ocr3bh ocr3bl ocr3ch ocr3cl icr3h icr3l etimsk etifr tccr1c ' +
'ocr1ch ocr1cl twcr twdr twar twsr twbr osccal xmcra xmcrb eicra spmcsr spmcr portg ' +
'ddrg ping portf ddrf sreg sph spl xdiv rampz eicrb eimsk gimsk gicr eifr gifr timsk ' +
'tifr mcucr mcucsr tccr0 tcnt0 ocr0 assr tccr1a tccr1b tcnt1h tcnt1l ocr1ah ocr1al ' +
'ocr1bh ocr1bl icr1h icr1l tccr2 tcnt2 ocr2 ocdr wdtcr sfior eearh eearl eedr eecr ' +
'porta ddra pina portb ddrb pinb portc ddrc pinc portd ddrd pind spdr spsr spcr udr0 ' +
'ucsr0a ucsr0b ubrr0l acsr admux adcsr adch adcl porte ddre pine pinf',
meta:
'.byte .cseg .db .def .device .dseg .dw .endmacro .equ .eseg .exit .include .list ' +
'.listmac .macro .nolist .org .set'
},
contains: [
hljs.C_BLOCK_COMMENT_MODE,
hljs.COMMENT(
';',
'$',
{
relevance: 0
}
),
hljs.C_NUMBER_MODE, // 0x..., decimal, float
hljs.BINARY_NUMBER_MODE, // 0b...
{
className: 'number',
begin: '\\b(\\$[a-zA-Z0-9]+|0o[0-7]+)' // $..., 0o...
},
hljs.QUOTE_STRING_MODE,
{
className: 'string',
begin: '\'', end: '[^\\\\]\'',
illegal: '[^\\\\][^\']'
},
{className: 'symbol', begin: '^[A-Za-z0-9_.$]+:'},
{className: 'meta', begin: '#', end: '$'},
{ // подстановка в «.macro»
className: 'subst',
begin: '@[0-9]+'
}
]
};
}

View File

@ -0,0 +1,59 @@
/*
Language: Awk
Author: Matthew Daly <matthewbdaly@gmail.com>
Website: http://matthewdaly.co.uk/
Description: language definition for Awk scripts
*/
function(hljs) {
var VARIABLE = {
className: 'variable',
variants: [
{begin: /\$[\w\d#@][\w\d_]*/},
{begin: /\$\{(.*?)}/}
]
};
var KEYWORDS = 'BEGIN END if else while do for in break continue delete next nextfile function func exit|10';
var STRING = {
className: 'string',
contains: [hljs.BACKSLASH_ESCAPE],
variants: [
{
begin: /(u|b)?r?'''/, end: /'''/,
relevance: 10
},
{
begin: /(u|b)?r?"""/, end: /"""/,
relevance: 10
},
{
begin: /(u|r|ur)'/, end: /'/,
relevance: 10
},
{
begin: /(u|r|ur)"/, end: /"/,
relevance: 10
},
{
begin: /(b|br)'/, end: /'/
},
{
begin: /(b|br)"/, end: /"/
},
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE
]
};
return {
keywords: {
keyword: KEYWORDS
},
contains: [
VARIABLE,
STRING,
hljs.REGEXP_MODE,
hljs.HASH_COMMENT_MODE,
hljs.NUMBER_MODE
]
}
}

View File

@ -0,0 +1,36 @@
/*
Language: Axapta
Author: Dmitri Roudakov <dmitri@roudakov.ru>
Category: enterprise
*/
function(hljs) {
return {
keywords: 'false int abstract private char boolean static null if for true ' +
'while long throw finally protected final return void enum else ' +
'break new catch byte super case short default double public try this switch ' +
'continue reverse firstfast firstonly forupdate nofetch sum avg minof maxof count ' +
'order group by asc desc index hint like dispaly edit client server ttsbegin ' +
'ttscommit str real date container anytype common div mod',
contains: [
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
hljs.C_NUMBER_MODE,
{
className: 'meta',
begin: '#', end: '$'
},
{
className: 'class',
beginKeywords: 'class interface', end: '{', excludeEnd: true,
illegal: ':',
contains: [
{beginKeywords: 'extends implements'},
hljs.UNDERSCORE_TITLE_MODE
]
}
]
};
}

View File

@ -0,0 +1,81 @@
/*
Language: Bash
Author: vah <vahtenberg@gmail.com>
Contributrors: Benjamin Pannell <contact@sierrasoftworks.com>
Category: common
*/
function(hljs) {
var VAR = {
className: 'variable',
variants: [
{begin: /\$[\w\d#@][\w\d_]*/},
{begin: /\$\{(.*?)}/}
]
};
var QUOTE_STRING = {
className: 'string',
begin: /"/, end: /"/,
contains: [
hljs.BACKSLASH_ESCAPE,
VAR,
{
className: 'variable',
begin: /\$\(/, end: /\)/,
contains: [hljs.BACKSLASH_ESCAPE]
}
]
};
var APOS_STRING = {
className: 'string',
begin: /'/, end: /'/
};
return {
aliases: ['sh', 'zsh'],
lexemes: /\b-?[a-z\._]+\b/,
keywords: {
keyword:
'if then else elif fi for while in do done case esac function',
literal:
'true false',
built_in:
// Shell built-ins
// http://www.gnu.org/software/bash/manual/html_node/Shell-Builtin-Commands.html
'break cd continue eval exec exit export getopts hash pwd readonly return shift test times ' +
'trap umask unset ' +
// Bash built-ins
'alias bind builtin caller command declare echo enable help let local logout mapfile printf ' +
'read readarray source type typeset ulimit unalias ' +
// Shell modifiers
'set shopt ' +
// Zsh built-ins
'autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles ' +
'compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate ' +
'fc fg float functions getcap getln history integer jobs kill limit log noglob popd print ' +
'pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit ' +
'unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof ' +
'zpty zregexparse zsocket zstyle ztcp',
_:
'-ne -eq -lt -gt -f -d -e -s -l -a' // relevance booster
},
contains: [
{
className: 'meta',
begin: /^#![^\n]+sh\s*$/,
relevance: 10
},
{
className: 'function',
begin: /\w[\w\d_]*\s*\(\s*\)\s*\{/,
returnBegin: true,
contains: [hljs.inherit(hljs.TITLE_MODE, {begin: /\w[\w\d_]*/})],
relevance: 0
},
hljs.HASH_COMMENT_MODE,
QUOTE_STRING,
APOS_STRING,
VAR
]
};
}

View File

@ -0,0 +1,55 @@
/*
Language: Basic
Author: Raphaël Assénat <raph@raphnet.net>
Description: Based on the BASIC reference from the Tandy 1000 guide
*/
function(hljs) {
return {
case_insensitive: true,
illegal: '^\.',
// Support explicitely typed variables that end with $%! or #.
lexemes: '[a-zA-Z][a-zA-Z0-9_\$\%\!\#]*',
keywords: {
keyword:
'ABS ASC AND ATN AUTO|0 BEEP BLOAD|10 BSAVE|10 CALL CALLS CDBL CHAIN CHDIR CHR$|10 CINT CIRCLE ' +
'CLEAR CLOSE CLS COLOR COM COMMON CONT COS CSNG CSRLIN CVD CVI CVS DATA DATE$ ' +
'DEFDBL DEFINT DEFSNG DEFSTR DEF|0 SEG USR DELETE DIM DRAW EDIT END ENVIRON ENVIRON$ ' +
'EOF EQV ERASE ERDEV ERDEV$ ERL ERR ERROR EXP FIELD FILES FIX FOR|0 FRE GET GOSUB|10 GOTO ' +
'HEX$ IF|0 THEN ELSE|0 INKEY$ INP INPUT INPUT# INPUT$ INSTR IMP INT IOCTL IOCTL$ KEY ON ' +
'OFF LIST KILL LEFT$ LEN LET LINE LLIST LOAD LOC LOCATE LOF LOG LPRINT USING LSET ' +
'MERGE MID$ MKDIR MKD$ MKI$ MKS$ MOD NAME NEW NEXT NOISE NOT OCT$ ON OR PEN PLAY STRIG OPEN OPTION ' +
'BASE OUT PAINT PALETTE PCOPY PEEK PMAP POINT POKE POS PRINT PRINT] PSET PRESET ' +
'PUT RANDOMIZE READ REM RENUM RESET|0 RESTORE RESUME RETURN|0 RIGHT$ RMDIR RND RSET ' +
'RUN SAVE SCREEN SGN SHELL SIN SOUND SPACE$ SPC SQR STEP STICK STOP STR$ STRING$ SWAP ' +
'SYSTEM TAB TAN TIME$ TIMER TROFF TRON TO USR VAL VARPTR VARPTR$ VIEW WAIT WHILE ' +
'WEND WIDTH WINDOW WRITE XOR'
},
contains: [
hljs.QUOTE_STRING_MODE,
hljs.COMMENT('REM', '$', {relevance: 10}),
hljs.COMMENT('\'', '$', {relevance: 0}),
{
// Match line numbers
className: 'symbol',
begin: '^[0-9]+\ ',
relevance: 10
},
{
// Match typed numeric constants (1000, 12.34!, 1.2e5, 1.5#, 1.2D2)
className: 'number',
begin: '\\b([0-9]+[0-9edED\.]*[#\!]?)',
relevance: 0
},
{
// Match hexadecimal numbers (&Hxxxx)
className: 'number',
begin: '(\&[hH][0-9a-fA-F]{1,4})'
},
{
// Match octal numbers (&Oxxxxxx)
className: 'number',
begin: '(\&[oO][0-7]{1,6})'
}
]
};
}

View File

@ -0,0 +1,33 @@
/*
Language: BackusNaur Form
Author: Oleg Efimov <efimovov@gmail.com>
*/
function(hljs){
return {
contains: [
// Attribute
{
className: 'attribute',
begin: /</, end: />/
},
// Specific
{
begin: /::=/,
starts: {
end: /$/,
contains: [
{
begin: /</, end: />/
},
// Common
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE
]
}
}
]
};
}

View File

@ -0,0 +1,41 @@
/*
Language: Brainfuck
Author: Evgeny Stepanischev <imbolk@gmail.com>
*/
function(hljs){
var LITERAL = {
className: 'literal',
begin: '[\\+\\-]',
relevance: 0
};
return {
aliases: ['bf'],
contains: [
hljs.COMMENT(
'[^\\[\\]\\.,\\+\\-<> \r\n]',
'[\\[\\]\\.,\\+\\-<> \r\n]',
{
returnEnd: true,
relevance: 0
}
),
{
className: 'title',
begin: '[\\[\\]]',
relevance: 0
},
{
className: 'string',
begin: '[\\.,]',
relevance: 0
},
{
// this mode works as the only relevance counter
begin: /\+\+|\-\-/, returnBegin: true,
contains: [LITERAL]
},
LITERAL
]
};
}

View File

@ -0,0 +1,85 @@
/*
Language: C/AL
Author: Kenneth Fuglsang Christensen <kfuglsang@gmail.com>
Description: Provides highlighting of Microsoft Dynamics NAV C/AL code files
*/
function(hljs) {
var KEYWORDS =
'div mod in and or not xor asserterror begin case do downto else end exit for if of repeat then to ' +
'until while with var';
var LITERALS = 'false true';
var COMMENT_MODES = [
hljs.C_LINE_COMMENT_MODE,
hljs.COMMENT(
/\{/,
/\}/,
{
relevance: 0
}
),
hljs.COMMENT(
/\(\*/,
/\*\)/,
{
relevance: 10
}
)
];
var STRING = {
className: 'string',
begin: /'/, end: /'/,
contains: [{begin: /''/}]
};
var CHAR_STRING = {
className: 'string', begin: /(#\d+)+/
};
var DATE = {
className: 'number',
begin: '\\b\\d+(\\.\\d+)?(DT|D|T)',
relevance: 0
};
var DBL_QUOTED_VARIABLE = {
className: 'string', // not a string technically but makes sense to be highlighted in the same style
begin: '"',
end: '"'
};
var PROCEDURE = {
className: 'function',
beginKeywords: 'procedure', end: /[:;]/,
keywords: 'procedure|10',
contains: [
hljs.TITLE_MODE,
{
className: 'params',
begin: /\(/, end: /\)/,
keywords: KEYWORDS,
contains: [STRING, CHAR_STRING]
}
].concat(COMMENT_MODES)
};
var OBJECT = {
className: 'class',
begin: 'OBJECT (Table|Form|Report|Dataport|Codeunit|XMLport|MenuSuite|Page|Query) (\\d+) ([^\\r\\n]+)',
returnBegin: true,
contains: [
hljs.TITLE_MODE,
PROCEDURE
]
};
return {
case_insensitive: true,
keywords: { keyword: KEYWORDS, literal: LITERALS },
illegal: /\/\*/,
contains: [
STRING, CHAR_STRING,
DATE, DBL_QUOTED_VARIABLE,
hljs.NUMBER_MODE,
OBJECT,
PROCEDURE
]
};
}

View File

@ -0,0 +1,55 @@
/*
Language: Capn Proto
Author: Oleg Efimov <efimovov@gmail.com>
Description: Capn Proto message definition format
Category: protocols
*/
function(hljs) {
return {
aliases: ['capnp'],
keywords: {
keyword:
'struct enum interface union group import using const annotation extends in of on as with from fixed',
built_in:
'Void Bool Int8 Int16 Int32 Int64 UInt8 UInt16 UInt32 UInt64 Float32 Float64 ' +
'Text Data AnyPointer AnyStruct Capability List',
literal:
'true false'
},
contains: [
hljs.QUOTE_STRING_MODE,
hljs.NUMBER_MODE,
hljs.HASH_COMMENT_MODE,
{
className: 'meta',
begin: /@0x[\w\d]{16};/,
illegal: /\n/
},
{
className: 'symbol',
begin: /@\d+\b/
},
{
className: 'class',
beginKeywords: 'struct enum', end: /\{/,
illegal: /\n/,
contains: [
hljs.inherit(hljs.TITLE_MODE, {
starts: {endsWithParent: true, excludeEnd: true} // hack: eating everything after the first title
})
]
},
{
className: 'class',
beginKeywords: 'interface', end: /\{/,
illegal: /\n/,
contains: [
hljs.inherit(hljs.TITLE_MODE, {
starts: {endsWithParent: true, excludeEnd: true} // hack: eating everything after the first title
})
]
}
]
};
}

View File

@ -0,0 +1,70 @@
/*
Language: Ceylon
Author: Lucas Werkmeister <mail@lucaswerkmeister.de>
*/
function(hljs) {
// 2.3. Identifiers and keywords
var KEYWORDS =
'assembly module package import alias class interface object given value ' +
'assign void function new of extends satisfies abstracts in out return ' +
'break continue throw assert dynamic if else switch case for while try ' +
'catch finally then let this outer super is exists nonempty';
// 7.4.1 Declaration Modifiers
var DECLARATION_MODIFIERS =
'shared abstract formal default actual variable late native deprecated' +
'final sealed annotation suppressWarnings small';
// 7.4.2 Documentation
var DOCUMENTATION =
'doc by license see throws tagged';
var SUBST = {
className: 'subst', excludeBegin: true, excludeEnd: true,
begin: /``/, end: /``/,
keywords: KEYWORDS,
relevance: 10
};
var EXPRESSIONS = [
{
// verbatim string
className: 'string',
begin: '"""',
end: '"""',
relevance: 10
},
{
// string literal or template
className: 'string',
begin: '"', end: '"',
contains: [SUBST]
},
{
// character literal
className: 'string',
begin: "'",
end: "'"
},
{
// numeric literal
className: 'number',
begin: '#[0-9a-fA-F_]+|\\$[01_]+|[0-9_]+(?:\\.[0-9_](?:[eE][+-]?\\d+)?)?[kMGTPmunpf]?',
relevance: 0
}
];
SUBST.contains = EXPRESSIONS;
return {
keywords: {
keyword: KEYWORDS + ' ' + DECLARATION_MODIFIERS,
meta: DOCUMENTATION
},
illegal: '\\$[^01]|#[^0-9a-fA-F]',
contains: [
hljs.C_LINE_COMMENT_MODE,
hljs.COMMENT('/\\*', '\\*/', {contains: ['self']}),
{
// compiler annotation
className: 'meta',
begin: '@[a-z]\\w*(?:\\:\"[^\"]*\")?'
}
].concat(EXPRESSIONS)
};
}

View File

@ -0,0 +1,33 @@
/*
Language: Clean
Author: Camil Staps <info@camilstaps.nl>
Category: functional
Website: http://clean.cs.ru.nl
*/
function(hljs) {
return {
aliases: ['clean','icl','dcl'],
keywords: {
keyword:
'if let in with where case of class instance otherwise ' +
'implementation definition system module from import qualified as ' +
'special code inline foreign export ccall stdcall generic derive ' +
'infix infixl infixr',
built_in:
'Int Real Char Bool',
literal:
'True False'
},
contains: [
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
hljs.C_NUMBER_MODE,
{begin: '->|<-[|:]?|#!?|>>=|\\{\\||\\|\\}|:==|=:|<>'} // relevance booster
]
};
}

View File

@ -0,0 +1,22 @@
/*
Language: Clojure REPL
Description: Clojure REPL sessions
Author: Ivan Sagalaev <maniac@softwaremaniacs.org>
Requires: clojure.js
Category: lisp
*/
function(hljs) {
return {
contains: [
{
className: 'meta',
begin: /^([\w.-]+|\s*#_)?=>/,
starts: {
end: /$/,
subLanguage: 'clojure'
}
}
]
}
}

View File

@ -0,0 +1,103 @@
/*
Language: Clojure
Description: Clojure syntax (based on lisp.js)
Author: mfornos
Contributors: Martin Clausen <martin.clausene@gmail.com>
Category: lisp
*/
function(hljs) {
var keywords = {
'builtin-name':
// Clojure keywords
'def defonce cond apply if-not if-let if not not= = < > <= >= == + / * - rem '+
'quot neg? pos? delay? symbol? keyword? true? false? integer? empty? coll? list? '+
'set? ifn? fn? associative? sequential? sorted? counted? reversible? number? decimal? '+
'class? distinct? isa? float? rational? reduced? ratio? odd? even? char? seq? vector? '+
'string? map? nil? contains? zero? instance? not-every? not-any? libspec? -> ->> .. . '+
'inc compare do dotimes mapcat take remove take-while drop letfn drop-last take-last '+
'drop-while while intern condp case reduced cycle split-at split-with repeat replicate '+
'iterate range merge zipmap declare line-seq sort comparator sort-by dorun doall nthnext '+
'nthrest partition eval doseq await await-for let agent atom send send-off release-pending-sends '+
'add-watch mapv filterv remove-watch agent-error restart-agent set-error-handler error-handler '+
'set-error-mode! error-mode shutdown-agents quote var fn loop recur throw try monitor-enter '+
'monitor-exit defmacro defn defn- macroexpand macroexpand-1 for dosync and or '+
'when when-not when-let comp juxt partial sequence memoize constantly complement identity assert '+
'peek pop doto proxy defstruct first rest cons defprotocol cast coll deftype defrecord last butlast '+
'sigs reify second ffirst fnext nfirst nnext defmulti defmethod meta with-meta ns in-ns create-ns import '+
'refer keys select-keys vals key val rseq name namespace promise into transient persistent! conj! '+
'assoc! dissoc! pop! disj! use class type num float double short byte boolean bigint biginteger '+
'bigdec print-method print-dup throw-if printf format load compile get-in update-in pr pr-on newline '+
'flush read slurp read-line subvec with-open memfn time re-find re-groups rand-int rand mod locking '+
'assert-valid-fdecl alias resolve ref deref refset swap! reset! set-validator! compare-and-set! alter-meta! '+
'reset-meta! commute get-validator alter ref-set ref-history-count ref-min-history ref-max-history ensure sync io! '+
'new next conj set! to-array future future-call into-array aset gen-class reduce map filter find empty '+
'hash-map hash-set sorted-map sorted-map-by sorted-set sorted-set-by vec vector seq flatten reverse assoc dissoc list '+
'disj get union difference intersection extend extend-type extend-protocol int nth delay count concat chunk chunk-buffer '+
'chunk-append chunk-first chunk-rest max min dec unchecked-inc-int unchecked-inc unchecked-dec-inc unchecked-dec unchecked-negate '+
'unchecked-add-int unchecked-add unchecked-subtract-int unchecked-subtract chunk-next chunk-cons chunked-seq? prn vary-meta '+
'lazy-seq spread list* str find-keyword keyword symbol gensym force rationalize'
};
var SYMBOLSTART = 'a-zA-Z_\\-!.?+*=<>&#\'';
var SYMBOL_RE = '[' + SYMBOLSTART + '][' + SYMBOLSTART + '0-9/;:]*';
var SIMPLE_NUMBER_RE = '[-+]?\\d+(\\.\\d+)?';
var SYMBOL = {
begin: SYMBOL_RE,
relevance: 0
};
var NUMBER = {
className: 'number', begin: SIMPLE_NUMBER_RE,
relevance: 0
};
var STRING = hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: null});
var COMMENT = hljs.COMMENT(
';',
'$',
{
relevance: 0
}
);
var LITERAL = {
className: 'literal',
begin: /\b(true|false|nil)\b/
};
var COLLECTION = {
begin: '[\\[\\{]', end: '[\\]\\}]'
};
var HINT = {
className: 'comment',
begin: '\\^' + SYMBOL_RE
};
var HINT_COL = hljs.COMMENT('\\^\\{', '\\}');
var KEY = {
className: 'symbol',
begin: '[:]{1,2}' + SYMBOL_RE
};
var LIST = {
begin: '\\(', end: '\\)'
};
var BODY = {
endsWithParent: true,
relevance: 0
};
var NAME = {
keywords: keywords,
lexemes: SYMBOL_RE,
className: 'name', begin: SYMBOL_RE,
starts: BODY
};
var DEFAULT_CONTAINS = [LIST, STRING, HINT, HINT_COL, COMMENT, KEY, COLLECTION, NUMBER, LITERAL, SYMBOL];
LIST.contains = [hljs.COMMENT('comment', ''), NAME, BODY];
BODY.contains = DEFAULT_CONTAINS;
COLLECTION.contains = DEFAULT_CONTAINS;
HINT_COL.contains = [COLLECTION];
return {
aliases: ['clj'],
illegal: /\S/,
contains: [LIST, STRING, HINT, HINT_COL, COMMENT, KEY, COLLECTION, NUMBER, LITERAL]
}
}

View File

@ -0,0 +1,59 @@
/*
Language: CMake
Description: CMake is an open-source cross-platform system for build automation.
Author: Igor Kalnitsky <igor@kalnitsky.org>
Website: http://kalnitsky.org/
*/
function(hljs) {
return {
aliases: ['cmake.in'],
case_insensitive: true,
keywords: {
keyword:
// scripting commands
'break cmake_host_system_information cmake_minimum_required cmake_parse_arguments ' +
'cmake_policy configure_file continue elseif else endforeach endfunction endif endmacro ' +
'endwhile execute_process file find_file find_library find_package find_path ' +
'find_program foreach function get_cmake_property get_directory_property ' +
'get_filename_component get_property if include include_guard list macro ' +
'mark_as_advanced math message option return separate_arguments ' +
'set_directory_properties set_property set site_name string unset variable_watch while ' +
// project commands
'add_compile_definitions add_compile_options add_custom_command add_custom_target ' +
'add_definitions add_dependencies add_executable add_library add_link_options ' +
'add_subdirectory add_test aux_source_directory build_command create_test_sourcelist ' +
'define_property enable_language enable_testing export fltk_wrap_ui ' +
'get_source_file_property get_target_property get_test_property include_directories ' +
'include_external_msproject include_regular_expression install link_directories ' +
'link_libraries load_cache project qt_wrap_cpp qt_wrap_ui remove_definitions ' +
'set_source_files_properties set_target_properties set_tests_properties source_group ' +
'target_compile_definitions target_compile_features target_compile_options ' +
'target_include_directories target_link_directories target_link_libraries ' +
'target_link_options target_sources try_compile try_run ' +
// CTest commands
'ctest_build ctest_configure ctest_coverage ctest_empty_binary_directory ctest_memcheck ' +
'ctest_read_custom_files ctest_run_script ctest_sleep ctest_start ctest_submit ' +
'ctest_test ctest_update ctest_upload ' +
// deprecated commands
'build_name exec_program export_library_dependencies install_files install_programs ' +
'install_targets load_command make_directory output_required_files remove ' +
'subdir_depends subdirs use_mangled_mesa utility_source variable_requires write_file ' +
'qt5_use_modules qt5_use_package qt5_wrap_cpp ' +
// core keywords
'on off true false and or not command policy target test exists is_newer_than ' +
'is_directory is_symlink is_absolute matches less greater equal less_equal ' +
'greater_equal strless strgreater strequal strless_equal strgreater_equal version_less ' +
'version_greater version_equal version_less_equal version_greater_equal in_list defined'
},
contains: [
{
className: 'variable',
begin: '\\${', end: '}'
},
hljs.HASH_COMMENT_MODE,
hljs.QUOTE_STRING_MODE,
hljs.NUMBER_MODE
]
};
}

View File

@ -0,0 +1,153 @@
/*
Language: CoffeeScript
Author: Dmytrii Nagirniak <dnagir@gmail.com>
Contributors: Oleg Efimov <efimovov@gmail.com>, Cédric Néhémie <cedric.nehemie@gmail.com>
Description: CoffeeScript is a programming language that transcompiles to JavaScript. For info about language see http://coffeescript.org/
Category: common, scripting
*/
function(hljs) {
var KEYWORDS = {
keyword:
// JS keywords
'in if for while finally new do return else break catch instanceof throw try this ' +
'switch continue typeof delete debugger super yield import export from as default await ' +
// Coffee keywords
'then unless until loop of by when and or is isnt not',
literal:
// JS literals
'true false null undefined ' +
// Coffee literals
'yes no on off',
built_in:
'npm require console print module global window document'
};
var JS_IDENT_RE = '[A-Za-z$_][0-9A-Za-z$_]*';
var SUBST = {
className: 'subst',
begin: /#\{/, end: /}/,
keywords: KEYWORDS
};
var EXPRESSIONS = [
hljs.BINARY_NUMBER_MODE,
hljs.inherit(hljs.C_NUMBER_MODE, {starts: {end: '(\\s*/)?', relevance: 0}}), // a number tries to eat the following slash to prevent treating it as a regexp
{
className: 'string',
variants: [
{
begin: /'''/, end: /'''/,
contains: [hljs.BACKSLASH_ESCAPE]
},
{
begin: /'/, end: /'/,
contains: [hljs.BACKSLASH_ESCAPE]
},
{
begin: /"""/, end: /"""/,
contains: [hljs.BACKSLASH_ESCAPE, SUBST]
},
{
begin: /"/, end: /"/,
contains: [hljs.BACKSLASH_ESCAPE, SUBST]
}
]
},
{
className: 'regexp',
variants: [
{
begin: '///', end: '///',
contains: [SUBST, hljs.HASH_COMMENT_MODE]
},
{
begin: '//[gim]*',
relevance: 0
},
{
// regex can't start with space to parse x / 2 / 3 as two divisions
// regex can't start with *, and it supports an "illegal" in the main mode
begin: /\/(?![ *])(\\\/|.)*?\/[gim]*(?=\W|$)/
}
]
},
{
begin: '@' + JS_IDENT_RE // relevance booster
},
{
subLanguage: 'javascript',
excludeBegin: true, excludeEnd: true,
variants: [
{
begin: '```', end: '```',
},
{
begin: '`', end: '`',
}
]
}
];
SUBST.contains = EXPRESSIONS;
var TITLE = hljs.inherit(hljs.TITLE_MODE, {begin: JS_IDENT_RE});
var PARAMS_RE = '(\\(.*\\))?\\s*\\B[-=]>';
var PARAMS = {
className: 'params',
begin: '\\([^\\(]', returnBegin: true,
/* We need another contained nameless mode to not have every nested
pair of parens to be called "params" */
contains: [{
begin: /\(/, end: /\)/,
keywords: KEYWORDS,
contains: ['self'].concat(EXPRESSIONS)
}]
};
return {
aliases: ['coffee', 'cson', 'iced'],
keywords: KEYWORDS,
illegal: /\/\*/,
contains: EXPRESSIONS.concat([
hljs.COMMENT('###', '###'),
hljs.HASH_COMMENT_MODE,
{
className: 'function',
begin: '^\\s*' + JS_IDENT_RE + '\\s*=\\s*' + PARAMS_RE, end: '[-=]>',
returnBegin: true,
contains: [TITLE, PARAMS]
},
{
// anonymous function start
begin: /[:\(,=]\s*/,
relevance: 0,
contains: [
{
className: 'function',
begin: PARAMS_RE, end: '[-=]>',
returnBegin: true,
contains: [PARAMS]
}
]
},
{
className: 'class',
beginKeywords: 'class',
end: '$',
illegal: /[:="\[\]]/,
contains: [
{
beginKeywords: 'extends',
endsWithParent: true,
illegal: /[:="\[\]]/,
contains: [TITLE]
},
TITLE
]
},
{
begin: JS_IDENT_RE + ':', end: ':',
returnBegin: true, returnEnd: true,
relevance: 0
}
])
};
}

View File

@ -0,0 +1,72 @@
/*
Language: Coq
Author: Stephan Boyer <stephan@stephanboyer.com>
Category: functional
*/
function(hljs) {
return {
keywords: {
keyword:
'_ as at cofix else end exists exists2 fix for forall fun if IF in let ' +
'match mod Prop return Set then Type using where with ' +
'Abort About Add Admit Admitted All Arguments Assumptions Axiom Back BackTo ' +
'Backtrack Bind Blacklist Canonical Cd Check Class Classes Close Coercion ' +
'Coercions CoFixpoint CoInductive Collection Combined Compute Conjecture ' +
'Conjectures Constant constr Constraint Constructors Context Corollary ' +
'CreateHintDb Cut Declare Defined Definition Delimit Dependencies Dependent' +
'Derive Drop eauto End Equality Eval Example Existential Existentials ' +
'Existing Export exporting Extern Extract Extraction Fact Field Fields File ' +
'Fixpoint Focus for From Function Functional Generalizable Global Goal Grab ' +
'Grammar Graph Guarded Heap Hint HintDb Hints Hypotheses Hypothesis ident ' +
'Identity If Immediate Implicit Import Include Inductive Infix Info Initial ' +
'Inline Inspect Instance Instances Intro Intros Inversion Inversion_clear ' +
'Language Left Lemma Let Libraries Library Load LoadPath Local Locate Ltac ML ' +
'Mode Module Modules Monomorphic Morphism Next NoInline Notation Obligation ' +
'Obligations Opaque Open Optimize Options Parameter Parameters Parametric ' +
'Path Paths pattern Polymorphic Preterm Print Printing Program Projections ' +
'Proof Proposition Pwd Qed Quit Rec Record Recursive Redirect Relation Remark ' +
'Remove Require Reserved Reset Resolve Restart Rewrite Right Ring Rings Save ' +
'Scheme Scope Scopes Script Search SearchAbout SearchHead SearchPattern ' +
'SearchRewrite Section Separate Set Setoid Show Solve Sorted Step Strategies ' +
'Strategy Structure SubClass Table Tables Tactic Term Test Theorem Time ' +
'Timeout Transparent Type Typeclasses Types Undelimit Undo Unfocus Unfocused ' +
'Unfold Universe Universes Unset Unshelve using Variable Variables Variant ' +
'Verbose Visibility where with',
built_in:
'abstract absurd admit after apply as assert assumption at auto autorewrite ' +
'autounfold before bottom btauto by case case_eq cbn cbv change ' +
'classical_left classical_right clear clearbody cofix compare compute ' +
'congruence constr_eq constructor contradict contradiction cut cutrewrite ' +
'cycle decide decompose dependent destruct destruction dintuition ' +
'discriminate discrR do double dtauto eapply eassumption eauto ecase ' +
'econstructor edestruct ediscriminate eelim eexact eexists einduction ' +
'einjection eleft elim elimtype enough equality erewrite eright ' +
'esimplify_eq esplit evar exact exactly_once exfalso exists f_equal fail ' +
'field field_simplify field_simplify_eq first firstorder fix fold fourier ' +
'functional generalize generalizing gfail give_up has_evar hnf idtac in ' +
'induction injection instantiate intro intro_pattern intros intuition ' +
'inversion inversion_clear is_evar is_var lapply lazy left lia lra move ' +
'native_compute nia nsatz omega once pattern pose progress proof psatz quote ' +
'record red refine reflexivity remember rename repeat replace revert ' +
'revgoals rewrite rewrite_strat right ring ring_simplify rtauto set ' +
'setoid_reflexivity setoid_replace setoid_rewrite setoid_symmetry ' +
'setoid_transitivity shelve shelve_unifiable simpl simple simplify_eq solve ' +
'specialize split split_Rabs split_Rmult stepl stepr subst sum swap ' +
'symmetry tactic tauto time timeout top transitivity trivial try tryif ' +
'unfold unify until using vm_compute with'
},
contains: [
hljs.QUOTE_STRING_MODE,
hljs.COMMENT('\\(\\*', '\\*\\)'),
hljs.C_NUMBER_MODE,
{
className: 'type',
excludeBegin: true,
begin: '\\|\\s*',
end: '\\w+'
},
{begin: /[-=]>/} // relevance booster
]
};
}

View File

@ -0,0 +1,128 @@
/*
Language: Caché Object Script
Author: Nikita Savchenko <zitros.lab@gmail.com>
Category: enterprise, scripting
*/
function cos (hljs) {
var STRINGS = {
className: 'string',
variants: [
{
begin: '"',
end: '"',
contains: [{ // escaped
begin: "\"\"",
relevance: 0
}]
}
]
};
var NUMBERS = {
className: "number",
begin: "\\b(\\d+(\\.\\d*)?|\\.\\d+)",
relevance: 0
};
var COS_KEYWORDS =
'property parameter class classmethod clientmethod extends as break ' +
'catch close continue do d|0 else elseif for goto halt hang h|0 if job ' +
'j|0 kill k|0 lock l|0 merge new open quit q|0 read r|0 return set s|0 ' +
'tcommit throw trollback try tstart use view while write w|0 xecute x|0 ' +
'zkill znspace zn ztrap zwrite zw zzdump zzwrite print zbreak zinsert ' +
'zload zprint zremove zsave zzprint mv mvcall mvcrt mvdim mvprint zquit ' +
'zsync ascii';
// registered function - no need in them due to all functions are highlighted,
// but I'll just leave this here.
//"$bit", "$bitcount",
//"$bitfind", "$bitlogic", "$case", "$char", "$classmethod", "$classname",
//"$compile", "$data", "$decimal", "$double", "$extract", "$factor",
//"$find", "$fnumber", "$get", "$increment", "$inumber", "$isobject",
//"$isvaliddouble", "$isvalidnum", "$justify", "$length", "$list",
//"$listbuild", "$listdata", "$listfind", "$listfromstring", "$listget",
//"$listlength", "$listnext", "$listsame", "$listtostring", "$listvalid",
//"$locate", "$match", "$method", "$name", "$nconvert", "$next",
//"$normalize", "$now", "$number", "$order", "$parameter", "$piece",
//"$prefetchoff", "$prefetchon", "$property", "$qlength", "$qsubscript",
//"$query", "$random", "$replace", "$reverse", "$sconvert", "$select",
//"$sortbegin", "$sortend", "$stack", "$text", "$translate", "$view",
//"$wascii", "$wchar", "$wextract", "$wfind", "$wiswide", "$wlength",
//"$wreverse", "$xecute", "$zabs", "$zarccos", "$zarcsin", "$zarctan",
//"$zcos", "$zcot", "$zcsc", "$zdate", "$zdateh", "$zdatetime",
//"$zdatetimeh", "$zexp", "$zhex", "$zln", "$zlog", "$zpower", "$zsec",
//"$zsin", "$zsqr", "$ztan", "$ztime", "$ztimeh", "$zboolean",
//"$zconvert", "$zcrc", "$zcyc", "$zdascii", "$zdchar", "$zf",
//"$ziswide", "$zlascii", "$zlchar", "$zname", "$zposition", "$zqascii",
//"$zqchar", "$zsearch", "$zseek", "$zstrip", "$zwascii", "$zwchar",
//"$zwidth", "$zwpack", "$zwbpack", "$zwunpack", "$zwbunpack", "$zzenkaku",
//"$change", "$mv", "$mvat", "$mvfmt", "$mvfmts", "$mviconv",
//"$mviconvs", "$mvinmat", "$mvlover", "$mvoconv", "$mvoconvs", "$mvraise",
//"$mvtrans", "$mvv", "$mvname", "$zbitand", "$zbitcount", "$zbitfind",
//"$zbitget", "$zbitlen", "$zbitnot", "$zbitor", "$zbitset", "$zbitstr",
//"$zbitxor", "$zincrement", "$znext", "$zorder", "$zprevious", "$zsort",
//"device", "$ecode", "$estack", "$etrap", "$halt", "$horolog",
//"$io", "$job", "$key", "$namespace", "$principal", "$quit", "$roles",
//"$storage", "$system", "$test", "$this", "$tlevel", "$username",
//"$x", "$y", "$za", "$zb", "$zchild", "$zeof", "$zeos", "$zerror",
//"$zhorolog", "$zio", "$zjob", "$zmode", "$znspace", "$zparent", "$zpi",
//"$zpos", "$zreference", "$zstorage", "$ztimestamp", "$ztimezone",
//"$ztrap", "$zversion"
return {
case_insensitive: true,
aliases: ["cos", "cls"],
keywords: COS_KEYWORDS,
contains: [
NUMBERS,
STRINGS,
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
{
className: "comment",
begin: /;/, end: "$",
relevance: 0
},
{ // Functions and user-defined functions: write $ztime(60*60*3), $$myFunc(10), $$^Val(1)
className: "built_in",
begin: /(?:\$\$?|\.\.)\^?[a-zA-Z]+/
},
{ // Macro command: quit $$$OK
className: "built_in",
begin: /\$\$\$[a-zA-Z]+/
},
{ // Special (global) variables: write %request.Content; Built-in classes: %Library.Integer
className: "built_in",
begin: /%[a-z]+(?:\.[a-z]+)*/
},
{ // Global variable: set ^globalName = 12 write ^globalName
className: "symbol",
begin: /\^%?[a-zA-Z][\w]*/
},
{ // Some control constructions: do ##class(Package.ClassName).Method(), ##super()
className: "keyword",
begin: /##class|##super|#define|#dim/
},
// sub-languages: are not fully supported by hljs by 11/15/2015
// left for the future implementation.
{
begin: /&sql\(/, end: /\)/,
excludeBegin: true, excludeEnd: true,
subLanguage: "sql"
},
{
begin: /&(js|jscript|javascript)</, end: />/,
excludeBegin: true, excludeEnd: true,
subLanguage: "javascript"
},
{
// this brakes first and last tag, but this is the only way to embed a valid html
begin: /&html<\s*</, end: />\s*>/,
subLanguage: "xml"
}
]
};
}

View File

@ -0,0 +1,198 @@
/*
Language: C++
Author: Ivan Sagalaev <maniac@softwaremaniacs.org>
Contributors: Evgeny Stepanischev <imbolk@gmail.com>, Zaven Muradyan <megalivoithos@gmail.com>, Roel Deckers <admin@codingcat.nl>, Sam Wu <samsam2310@gmail.com>, Jordi Petit <jordi.petit@gmail.com>, Pieter Vantorre <pietervantorre@gmail.com>, Google Inc. (David Benjamin) <davidben@google.com>
Category: common, system
*/
function(hljs) {
var CPP_PRIMITIVE_TYPES = {
className: 'keyword',
begin: '\\b[a-z\\d_]*_t\\b'
};
var STRINGS = {
className: 'string',
variants: [
{
begin: '(u8?|U|L)?"', end: '"',
illegal: '\\n',
contains: [hljs.BACKSLASH_ESCAPE]
},
{
// TODO: This does not handle raw string literals with prefixes. Using
// a single regex with backreferences would work (note to use *?
// instead of * to make it non-greedy), but the mode.terminators
// computation in highlight.js breaks the counting.
begin: '(u8?|U|L)?R"\\(', end: '\\)"',
},
{
begin: '\'\\\\?.', end: '\'',
illegal: '.'
}
]
};
var NUMBERS = {
className: 'number',
variants: [
{ begin: '\\b(0b[01\']+)' },
{ begin: '(-?)\\b([\\d\']+(\\.[\\d\']*)?|\\.[\\d\']+)(u|U|l|L|ul|UL|f|F|b|B)' },
{ begin: '(-?)(\\b0[xX][a-fA-F0-9\']+|(\\b[\\d\']+(\\.[\\d\']*)?|\\.[\\d\']+)([eE][-+]?[\\d\']+)?)' }
],
relevance: 0
};
var PREPROCESSOR = {
className: 'meta',
begin: /#\s*[a-z]+\b/, end: /$/,
keywords: {
'meta-keyword':
'if else elif endif define undef warning error line ' +
'pragma ifdef ifndef include'
},
contains: [
{
begin: /\\\n/, relevance: 0
},
hljs.inherit(STRINGS, {className: 'meta-string'}),
{
className: 'meta-string',
begin: /<[^\n>]*>/, end: /$/,
illegal: '\\n',
},
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE
]
};
var FUNCTION_TITLE = hljs.IDENT_RE + '\\s*\\(';
var CPP_KEYWORDS = {
keyword: 'int float while private char catch import module export virtual operator sizeof ' +
'dynamic_cast|10 typedef const_cast|10 const for static_cast|10 union namespace ' +
'unsigned long volatile static protected bool template mutable if public friend ' +
'do goto auto void enum else break extern using asm case typeid ' +
'short reinterpret_cast|10 default double register explicit signed typename try this ' +
'switch continue inline delete alignof constexpr decltype ' +
'noexcept static_assert thread_local restrict _Bool complex _Complex _Imaginary ' +
'atomic_bool atomic_char atomic_schar ' +
'atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong ' +
'atomic_ullong new throw return ' +
'and or not',
built_in: 'std string cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream ' +
'auto_ptr deque list queue stack vector map set bitset multiset multimap unordered_set ' +
'unordered_map unordered_multiset unordered_multimap array shared_ptr abort abs acos ' +
'asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp ' +
'fscanf isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper ' +
'isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow ' +
'printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp ' +
'strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan ' +
'vfprintf vprintf vsprintf endl initializer_list unique_ptr',
literal: 'true false nullptr NULL'
};
var EXPRESSION_CONTAINS = [
CPP_PRIMITIVE_TYPES,
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
NUMBERS,
STRINGS
];
return {
aliases: ['c', 'cc', 'h', 'c++', 'h++', 'hpp'],
keywords: CPP_KEYWORDS,
illegal: '</',
contains: EXPRESSION_CONTAINS.concat([
PREPROCESSOR,
{
begin: '\\b(deque|list|queue|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<', end: '>',
keywords: CPP_KEYWORDS,
contains: ['self', CPP_PRIMITIVE_TYPES]
},
{
begin: hljs.IDENT_RE + '::',
keywords: CPP_KEYWORDS
},
{
// This mode covers expression context where we can't expect a function
// definition and shouldn't highlight anything that looks like one:
// `return some()`, `else if()`, `(x*sum(1, 2))`
variants: [
{begin: /=/, end: /;/},
{begin: /\(/, end: /\)/},
{beginKeywords: 'new throw return else', end: /;/}
],
keywords: CPP_KEYWORDS,
contains: EXPRESSION_CONTAINS.concat([
{
begin: /\(/, end: /\)/,
keywords: CPP_KEYWORDS,
contains: EXPRESSION_CONTAINS.concat(['self']),
relevance: 0
}
]),
relevance: 0
},
{
className: 'function',
begin: '(' + hljs.IDENT_RE + '[\\*&\\s]+)+' + FUNCTION_TITLE,
returnBegin: true, end: /[{;=]/,
excludeEnd: true,
keywords: CPP_KEYWORDS,
illegal: /[^\w\s\*&]/,
contains: [
{
begin: FUNCTION_TITLE, returnBegin: true,
contains: [hljs.TITLE_MODE],
relevance: 0
},
{
className: 'params',
begin: /\(/, end: /\)/,
keywords: CPP_KEYWORDS,
relevance: 0,
contains: [
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
STRINGS,
NUMBERS,
CPP_PRIMITIVE_TYPES,
// Count matching parentheses.
{
begin: /\(/, end: /\)/,
keywords: CPP_KEYWORDS,
relevance: 0,
contains: [
'self',
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
STRINGS,
NUMBERS,
CPP_PRIMITIVE_TYPES
]
}
]
},
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
PREPROCESSOR
]
},
{
className: 'class',
beginKeywords: 'class struct', end: /[{;:]/,
contains: [
{begin: /</, end: />/, contains: ['self']}, // skip generic stuff
hljs.TITLE_MODE
]
}
]),
exports: {
preprocessor: PREPROCESSOR,
strings: STRINGS,
keywords: CPP_KEYWORDS
}
};
}

View File

@ -0,0 +1,101 @@
/*
Language: crmsh
Author: Kristoffer Gronlund <kgronlund@suse.com>
Website: http://crmsh.github.io
Description: Syntax Highlighting for the crmsh DSL
Category: config
*/
function(hljs) {
var RESOURCES = 'primitive rsc_template';
var COMMANDS = 'group clone ms master location colocation order fencing_topology ' +
'rsc_ticket acl_target acl_group user role ' +
'tag xml';
var PROPERTY_SETS = 'property rsc_defaults op_defaults';
var KEYWORDS = 'params meta operations op rule attributes utilization';
var OPERATORS = 'read write deny defined not_defined in_range date spec in ' +
'ref reference attribute type xpath version and or lt gt tag ' +
'lte gte eq ne \\';
var TYPES = 'number string';
var LITERALS = 'Master Started Slave Stopped start promote demote stop monitor true false';
return {
aliases: ['crm', 'pcmk'],
case_insensitive: true,
keywords: {
keyword: KEYWORDS + ' ' + OPERATORS + ' ' + TYPES,
literal: LITERALS
},
contains: [
hljs.HASH_COMMENT_MODE,
{
beginKeywords: 'node',
starts: {
end: '\\s*([\\w_-]+:)?',
starts: {
className: 'title',
end: '\\s*[\\$\\w_][\\w_-]*'
}
}
},
{
beginKeywords: RESOURCES,
starts: {
className: 'title',
end: '\\s*[\\$\\w_][\\w_-]*',
starts: {
end: '\\s*@?[\\w_][\\w_\\.:-]*'
}
}
},
{
begin: '\\b(' + COMMANDS.split(' ').join('|') + ')\\s+',
keywords: COMMANDS,
starts: {
className: 'title',
end: '[\\$\\w_][\\w_-]*'
}
},
{
beginKeywords: PROPERTY_SETS,
starts: {
className: 'title',
end: '\\s*([\\w_-]+:)?'
}
},
hljs.QUOTE_STRING_MODE,
{
className: 'meta',
begin: '(ocf|systemd|service|lsb):[\\w_:-]+',
relevance: 0
},
{
className: 'number',
begin: '\\b\\d+(\\.\\d+)?(ms|s|h|m)?',
relevance: 0
},
{
className: 'literal',
begin: '[-]?(infinity|inf)',
relevance: 0
},
{
className: 'attr',
begin: /([A-Za-z\$_\#][\w_-]+)=/,
relevance: 0
},
{
className: 'tag',
begin: '</?',
end: '/?>',
relevance: 0
}
]
};
}

View File

@ -0,0 +1,192 @@
/*
Language: Crystal
Author: TSUYUSATO Kitsune <make.just.on@gmail.com>
*/
function(hljs) {
var INT_SUFFIX = '(_*[ui](8|16|32|64|128))?';
var FLOAT_SUFFIX = '(_*f(32|64))?';
var CRYSTAL_IDENT_RE = '[a-zA-Z_]\\w*[!?=]?';
var CRYSTAL_METHOD_RE = '[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~|]|//|//=|&[-+*]=?|&\\*\\*|\\[\\][=?]?';
var CRYSTAL_PATH_RE = '[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?';
var CRYSTAL_KEYWORDS = {
keyword:
'abstract alias annotation as as? asm begin break case class def do else elsif end ensure enum extend for fun if ' +
'include instance_sizeof is_a? lib macro module next nil? of out pointerof private protected rescue responds_to? ' +
'return require select self sizeof struct super then type typeof union uninitialized unless until verbatim when while with yield ' +
'__DIR__ __END_LINE__ __FILE__ __LINE__',
literal: 'false nil true'
};
var SUBST = {
className: 'subst',
begin: '#{', end: '}',
keywords: CRYSTAL_KEYWORDS
};
var EXPANSION = {
className: 'template-variable',
variants: [
{begin: '\\{\\{', end: '\\}\\}'},
{begin: '\\{%', end: '%\\}'}
],
keywords: CRYSTAL_KEYWORDS
};
function recursiveParen(begin, end) {
var
contains = [{begin: begin, end: end}];
contains[0].contains = contains;
return contains;
}
var STRING = {
className: 'string',
contains: [hljs.BACKSLASH_ESCAPE, SUBST],
variants: [
{begin: /'/, end: /'/},
{begin: /"/, end: /"/},
{begin: /`/, end: /`/},
{begin: '%[Qwi]?\\(', end: '\\)', contains: recursiveParen('\\(', '\\)')},
{begin: '%[Qwi]?\\[', end: '\\]', contains: recursiveParen('\\[', '\\]')},
{begin: '%[Qwi]?{', end: '}', contains: recursiveParen('{', '}')},
{begin: '%[Qwi]?<', end: '>', contains: recursiveParen('<', '>')},
{begin: '%[Qwi]?\\|', end: '\\|'},
{begin: /<<-\w+$/, end: /^\s*\w+$/},
],
relevance: 0,
};
var Q_STRING = {
className: 'string',
variants: [
{begin: '%q\\(', end: '\\)', contains: recursiveParen('\\(', '\\)')},
{begin: '%q\\[', end: '\\]', contains: recursiveParen('\\[', '\\]')},
{begin: '%q{', end: '}', contains: recursiveParen('{', '}')},
{begin: '%q<', end: '>', contains: recursiveParen('<', '>')},
{begin: '%q\\|', end: '\\|'},
{begin: /<<-'\w+'$/, end: /^\s*\w+$/},
],
relevance: 0,
};
var REGEXP = {
begin: '(?!%})(' + hljs.RE_STARTERS_RE + '|\\n|\\b(case|if|select|unless|until|when|while)\\b)\\s*',
keywords: 'case if select unless until when while',
contains: [
{
className: 'regexp',
contains: [hljs.BACKSLASH_ESCAPE, SUBST],
variants: [
{begin: '//[a-z]*', relevance: 0},
{begin: '/(?!\\/)', end: '/[a-z]*'},
]
}
],
relevance: 0
};
var REGEXP2 = {
className: 'regexp',
contains: [hljs.BACKSLASH_ESCAPE, SUBST],
variants: [
{begin: '%r\\(', end: '\\)', contains: recursiveParen('\\(', '\\)')},
{begin: '%r\\[', end: '\\]', contains: recursiveParen('\\[', '\\]')},
{begin: '%r{', end: '}', contains: recursiveParen('{', '}')},
{begin: '%r<', end: '>', contains: recursiveParen('<', '>')},
{begin: '%r\\|', end: '\\|'},
],
relevance: 0
};
var ATTRIBUTE = {
className: 'meta',
begin: '@\\[', end: '\\]',
contains: [
hljs.inherit(hljs.QUOTE_STRING_MODE, {className: 'meta-string'})
]
};
var CRYSTAL_DEFAULT_CONTAINS = [
EXPANSION,
STRING,
Q_STRING,
REGEXP2,
REGEXP,
ATTRIBUTE,
hljs.HASH_COMMENT_MODE,
{
className: 'class',
beginKeywords: 'class module struct', end: '$|;',
illegal: /=/,
contains: [
hljs.HASH_COMMENT_MODE,
hljs.inherit(hljs.TITLE_MODE, {begin: CRYSTAL_PATH_RE}),
{begin: '<'} // relevance booster for inheritance
]
},
{
className: 'class',
beginKeywords: 'lib enum union', end: '$|;',
illegal: /=/,
contains: [
hljs.HASH_COMMENT_MODE,
hljs.inherit(hljs.TITLE_MODE, {begin: CRYSTAL_PATH_RE}),
],
relevance: 10
},
{
beginKeywords: 'annotation', end: '$|;',
illegal: /=/,
contains: [
hljs.HASH_COMMENT_MODE,
hljs.inherit(hljs.TITLE_MODE, {begin: CRYSTAL_PATH_RE}),
],
relevance: 10
},
{
className: 'function',
beginKeywords: 'def', end: /\B\b/,
contains: [
hljs.inherit(hljs.TITLE_MODE, {
begin: CRYSTAL_METHOD_RE,
endsParent: true
})
]
},
{
className: 'function',
beginKeywords: 'fun macro', end: /\B\b/,
contains: [
hljs.inherit(hljs.TITLE_MODE, {
begin: CRYSTAL_METHOD_RE,
endsParent: true
})
],
relevance: 5
},
{
className: 'symbol',
begin: hljs.UNDERSCORE_IDENT_RE + '(\\!|\\?)?:',
relevance: 0
},
{
className: 'symbol',
begin: ':',
contains: [STRING, {begin: CRYSTAL_METHOD_RE}],
relevance: 0
},
{
className: 'number',
variants: [
{ begin: '\\b0b([01_]+)' + INT_SUFFIX },
{ begin: '\\b0o([0-7_]+)' + INT_SUFFIX },
{ begin: '\\b0x([A-Fa-f0-9_]+)' + INT_SUFFIX },
{ begin: '\\b([1-9][0-9_]*[0-9]|[0-9])(\\.[0-9][0-9_]*)?([eE]_*[-+]?[0-9_]*)?' + FLOAT_SUFFIX + '(?!_)' },
{ begin: '\\b([1-9][0-9_]*|0)' + INT_SUFFIX }
],
relevance: 0
}
];
SUBST.contains = CRYSTAL_DEFAULT_CONTAINS;
EXPANSION.contains = CRYSTAL_DEFAULT_CONTAINS.slice(1); // without EXPANSION
return {
aliases: ['cr'],
lexemes: CRYSTAL_IDENT_RE,
keywords: CRYSTAL_KEYWORDS,
contains: CRYSTAL_DEFAULT_CONTAINS
};
}

View File

@ -0,0 +1,191 @@
/*
Language: C#
Author: Jason Diamond <jason@diamond.name>
Contributor: Nicolas LLOBERA <nllobera@gmail.com>, Pieter Vantorre <pietervantorre@gmail.com>
Category: common
*/
function(hljs) {
var KEYWORDS = {
keyword:
// Normal keywords.
'abstract as base bool break byte case catch char checked const continue decimal ' +
'default delegate do double enum event explicit extern finally fixed float ' +
'for foreach goto if implicit in int interface internal is lock long nameof ' +
'object operator out override params private protected public readonly ref sbyte ' +
'sealed short sizeof stackalloc static string struct switch this try typeof ' +
'uint ulong unchecked unsafe ushort using virtual void volatile while ' +
// Contextual keywords.
'add alias ascending async await by descending dynamic equals from get global group into join ' +
'let on orderby partial remove select set value var where yield',
literal:
'null false true'
};
var NUMBERS = {
className: 'number',
variants: [
{ begin: '\\b(0b[01\']+)' },
{ begin: '(-?)\\b([\\d\']+(\\.[\\d\']*)?|\\.[\\d\']+)(u|U|l|L|ul|UL|f|F|b|B)' },
{ begin: '(-?)(\\b0[xX][a-fA-F0-9\']+|(\\b[\\d\']+(\\.[\\d\']*)?|\\.[\\d\']+)([eE][-+]?[\\d\']+)?)' }
],
relevance: 0
};
var VERBATIM_STRING = {
className: 'string',
begin: '@"', end: '"',
contains: [{begin: '""'}]
};
var VERBATIM_STRING_NO_LF = hljs.inherit(VERBATIM_STRING, {illegal: /\n/});
var SUBST = {
className: 'subst',
begin: '{', end: '}',
keywords: KEYWORDS
};
var SUBST_NO_LF = hljs.inherit(SUBST, {illegal: /\n/});
var INTERPOLATED_STRING = {
className: 'string',
begin: /\$"/, end: '"',
illegal: /\n/,
contains: [{begin: '{{'}, {begin: '}}'}, hljs.BACKSLASH_ESCAPE, SUBST_NO_LF]
};
var INTERPOLATED_VERBATIM_STRING = {
className: 'string',
begin: /\$@"/, end: '"',
contains: [{begin: '{{'}, {begin: '}}'}, {begin: '""'}, SUBST]
};
var INTERPOLATED_VERBATIM_STRING_NO_LF = hljs.inherit(INTERPOLATED_VERBATIM_STRING, {
illegal: /\n/,
contains: [{begin: '{{'}, {begin: '}}'}, {begin: '""'}, SUBST_NO_LF]
});
SUBST.contains = [
INTERPOLATED_VERBATIM_STRING,
INTERPOLATED_STRING,
VERBATIM_STRING,
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
NUMBERS,
hljs.C_BLOCK_COMMENT_MODE
];
SUBST_NO_LF.contains = [
INTERPOLATED_VERBATIM_STRING_NO_LF,
INTERPOLATED_STRING,
VERBATIM_STRING_NO_LF,
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
NUMBERS,
hljs.inherit(hljs.C_BLOCK_COMMENT_MODE, {illegal: /\n/})
];
var STRING = {
variants: [
INTERPOLATED_VERBATIM_STRING,
INTERPOLATED_STRING,
VERBATIM_STRING,
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE
]
};
var TYPE_IDENT_RE = hljs.IDENT_RE + '(<' + hljs.IDENT_RE + '(\\s*,\\s*' + hljs.IDENT_RE + ')*>)?(\\[\\])?';
return {
aliases: ['csharp', 'c#'],
keywords: KEYWORDS,
illegal: /::/,
contains: [
hljs.COMMENT(
'///',
'$',
{
returnBegin: true,
contains: [
{
className: 'doctag',
variants: [
{
begin: '///', relevance: 0
},
{
begin: '<!--|-->'
},
{
begin: '</?', end: '>'
}
]
}
]
}
),
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
{
className: 'meta',
begin: '#', end: '$',
keywords: {
'meta-keyword': 'if else elif endif define undef warning error line region endregion pragma checksum'
}
},
STRING,
NUMBERS,
{
beginKeywords: 'class interface', end: /[{;=]/,
illegal: /[^\s:,]/,
contains: [
hljs.TITLE_MODE,
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE
]
},
{
beginKeywords: 'namespace', end: /[{;=]/,
illegal: /[^\s:]/,
contains: [
hljs.inherit(hljs.TITLE_MODE, {begin: '[a-zA-Z](\\.?\\w)*'}),
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE
]
},
{
// [Attributes("")]
className: 'meta',
begin: '^\\s*\\[', excludeBegin: true, end: '\\]', excludeEnd: true,
contains: [
{className: 'meta-string', begin: /"/, end: /"/}
]
},
{
// Expression keywords prevent 'keyword Name(...)' from being
// recognized as a function definition
beginKeywords: 'new return throw await else',
relevance: 0
},
{
className: 'function',
begin: '(' + TYPE_IDENT_RE + '\\s+)+' + hljs.IDENT_RE + '\\s*\\(', returnBegin: true,
end: /\s*[{;=]/, excludeEnd: true,
keywords: KEYWORDS,
contains: [
{
begin: hljs.IDENT_RE + '\\s*\\(', returnBegin: true,
contains: [hljs.TITLE_MODE],
relevance: 0
},
{
className: 'params',
begin: /\(/, end: /\)/,
excludeBegin: true,
excludeEnd: true,
keywords: KEYWORDS,
relevance: 0,
contains: [
STRING,
NUMBERS,
hljs.C_BLOCK_COMMENT_MODE
]
},
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE
]
}
]
};
}

View File

@ -0,0 +1,29 @@
/*
Language: CSP
Description: Content Security Policy definition highlighting
Author: Taras <oxdef@oxdef.info>
vim: ts=2 sw=2 st=2
*/
function(hljs) {
return {
case_insensitive: false,
lexemes: '[a-zA-Z][a-zA-Z0-9_-]*',
keywords: {
keyword: 'base-uri child-src connect-src default-src font-src form-action' +
' frame-ancestors frame-src img-src media-src object-src plugin-types' +
' report-uri sandbox script-src style-src',
},
contains: [
{
className: 'string',
begin: "'", end: "'"
},
{
className: 'attribute',
begin: '^Content', end: ':', excludeEnd: true,
},
]
};
}

View File

@ -0,0 +1,109 @@
/*
Language: CSS
Category: common, css
*/
function(hljs) {
var IDENT_RE = '[a-zA-Z-][a-zA-Z0-9_-]*';
var RULE = {
begin: /[A-Z\_\.\-]+\s*:/, returnBegin: true, end: ';', endsWithParent: true,
contains: [
{
className: 'attribute',
begin: /\S/, end: ':', excludeEnd: true,
starts: {
endsWithParent: true, excludeEnd: true,
contains: [
{
begin: /[\w-]+\(/, returnBegin: true,
contains: [
{
className: 'built_in',
begin: /[\w-]+/
},
{
begin: /\(/, end: /\)/,
contains: [
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE
]
}
]
},
hljs.CSS_NUMBER_MODE,
hljs.QUOTE_STRING_MODE,
hljs.APOS_STRING_MODE,
hljs.C_BLOCK_COMMENT_MODE,
{
className: 'number', begin: '#[0-9A-Fa-f]+'
},
{
className: 'meta', begin: '!important'
}
]
}
}
]
};
return {
case_insensitive: true,
illegal: /[=\/|'\$]/,
contains: [
hljs.C_BLOCK_COMMENT_MODE,
{
className: 'selector-id', begin: /#[A-Za-z0-9_-]+/
},
{
className: 'selector-class', begin: /\.[A-Za-z0-9_-]+/
},
{
className: 'selector-attr',
begin: /\[/, end: /\]/,
illegal: '$'
},
{
className: 'selector-pseudo',
begin: /:(:)?[a-zA-Z0-9\_\-\+\(\)"'.]+/
},
{
begin: '@(font-face|page)',
lexemes: '[a-z-]+',
keywords: 'font-face page'
},
{
begin: '@', end: '[{;]', // at_rule eating first "{" is a good thing
// because it doesnt let it to be parsed as
// a rule set but instead drops parser into
// the default mode which is how it should be.
illegal: /:/, // break on Less variables @var: ...
contains: [
{
className: 'keyword',
begin: /\w+/
},
{
begin: /\s/, endsWithParent: true, excludeEnd: true,
relevance: 0,
contains: [
hljs.APOS_STRING_MODE, hljs.QUOTE_STRING_MODE,
hljs.CSS_NUMBER_MODE
]
}
]
},
{
className: 'selector-tag', begin: IDENT_RE,
relevance: 0
},
{
begin: '{', end: '}',
illegal: /\S/,
contains: [
hljs.C_BLOCK_COMMENT_MODE,
RULE,
]
}
]
};
}

View File

@ -0,0 +1,265 @@
/*
Language: D
Author: Aleksandar Ruzicic <aleksandar@ruzicic.info>
Description: D is a language with C-like syntax and static typing. It pragmatically combines efficiency, control, and modeling power, with safety and programmer productivity.
Version: 1.0a
Date: 2012-04-08
*/
/**
* Known issues:
*
* - invalid hex string literals will be recognized as a double quoted strings
* but 'x' at the beginning of string will not be matched
*
* - delimited string literals are not checked for matching end delimiter
* (not possible to do with js regexp)
*
* - content of token string is colored as a string (i.e. no keyword coloring inside a token string)
* also, content of token string is not validated to contain only valid D tokens
*
* - special token sequence rule is not strictly following D grammar (anything following #line
* up to the end of line is matched as special token sequence)
*/
function(hljs) {
/**
* Language keywords
*
* @type {Object}
*/
var D_KEYWORDS = {
keyword:
'abstract alias align asm assert auto body break byte case cast catch class ' +
'const continue debug default delete deprecated do else enum export extern final ' +
'finally for foreach foreach_reverse|10 goto if immutable import in inout int ' +
'interface invariant is lazy macro mixin module new nothrow out override package ' +
'pragma private protected public pure ref return scope shared static struct ' +
'super switch synchronized template this throw try typedef typeid typeof union ' +
'unittest version void volatile while with __FILE__ __LINE__ __gshared|10 ' +
'__thread __traits __DATE__ __EOF__ __TIME__ __TIMESTAMP__ __VENDOR__ __VERSION__',
built_in:
'bool cdouble cent cfloat char creal dchar delegate double dstring float function ' +
'idouble ifloat ireal long real short string ubyte ucent uint ulong ushort wchar ' +
'wstring',
literal:
'false null true'
};
/**
* Number literal regexps
*
* @type {String}
*/
var decimal_integer_re = '(0|[1-9][\\d_]*)',
decimal_integer_nosus_re = '(0|[1-9][\\d_]*|\\d[\\d_]*|[\\d_]+?\\d)',
binary_integer_re = '0[bB][01_]+',
hexadecimal_digits_re = '([\\da-fA-F][\\da-fA-F_]*|_[\\da-fA-F][\\da-fA-F_]*)',
hexadecimal_integer_re = '0[xX]' + hexadecimal_digits_re,
decimal_exponent_re = '([eE][+-]?' + decimal_integer_nosus_re + ')',
decimal_float_re = '(' + decimal_integer_nosus_re + '(\\.\\d*|' + decimal_exponent_re + ')|' +
'\\d+\\.' + decimal_integer_nosus_re + decimal_integer_nosus_re + '|' +
'\\.' + decimal_integer_re + decimal_exponent_re + '?' +
')',
hexadecimal_float_re = '(0[xX](' +
hexadecimal_digits_re + '\\.' + hexadecimal_digits_re + '|'+
'\\.?' + hexadecimal_digits_re +
')[pP][+-]?' + decimal_integer_nosus_re + ')',
integer_re = '(' +
decimal_integer_re + '|' +
binary_integer_re + '|' +
hexadecimal_integer_re +
')',
float_re = '(' +
hexadecimal_float_re + '|' +
decimal_float_re +
')';
/**
* Escape sequence supported in D string and character literals
*
* @type {String}
*/
var escape_sequence_re = '\\\\(' +
'[\'"\\?\\\\abfnrtv]|' + // common escapes
'u[\\dA-Fa-f]{4}|' + // four hex digit unicode codepoint
'[0-7]{1,3}|' + // one to three octal digit ascii char code
'x[\\dA-Fa-f]{2}|' + // two hex digit ascii char code
'U[\\dA-Fa-f]{8}' + // eight hex digit unicode codepoint
')|' +
'&[a-zA-Z\\d]{2,};'; // named character entity
/**
* D integer number literals
*
* @type {Object}
*/
var D_INTEGER_MODE = {
className: 'number',
begin: '\\b' + integer_re + '(L|u|U|Lu|LU|uL|UL)?',
relevance: 0
};
/**
* [D_FLOAT_MODE description]
* @type {Object}
*/
var D_FLOAT_MODE = {
className: 'number',
begin: '\\b(' +
float_re + '([fF]|L|i|[fF]i|Li)?|' +
integer_re + '(i|[fF]i|Li)' +
')',
relevance: 0
};
/**
* D character literal
*
* @type {Object}
*/
var D_CHARACTER_MODE = {
className: 'string',
begin: '\'(' + escape_sequence_re + '|.)', end: '\'',
illegal: '.'
};
/**
* D string escape sequence
*
* @type {Object}
*/
var D_ESCAPE_SEQUENCE = {
begin: escape_sequence_re,
relevance: 0
};
/**
* D double quoted string literal
*
* @type {Object}
*/
var D_STRING_MODE = {
className: 'string',
begin: '"',
contains: [D_ESCAPE_SEQUENCE],
end: '"[cwd]?'
};
/**
* D wysiwyg and delimited string literals
*
* @type {Object}
*/
var D_WYSIWYG_DELIMITED_STRING_MODE = {
className: 'string',
begin: '[rq]"',
end: '"[cwd]?',
relevance: 5
};
/**
* D alternate wysiwyg string literal
*
* @type {Object}
*/
var D_ALTERNATE_WYSIWYG_STRING_MODE = {
className: 'string',
begin: '`',
end: '`[cwd]?'
};
/**
* D hexadecimal string literal
*
* @type {Object}
*/
var D_HEX_STRING_MODE = {
className: 'string',
begin: 'x"[\\da-fA-F\\s\\n\\r]*"[cwd]?',
relevance: 10
};
/**
* D delimited string literal
*
* @type {Object}
*/
var D_TOKEN_STRING_MODE = {
className: 'string',
begin: 'q"\\{',
end: '\\}"'
};
/**
* Hashbang support
*
* @type {Object}
*/
var D_HASHBANG_MODE = {
className: 'meta',
begin: '^#!',
end: '$',
relevance: 5
};
/**
* D special token sequence
*
* @type {Object}
*/
var D_SPECIAL_TOKEN_SEQUENCE_MODE = {
className: 'meta',
begin: '#(line)',
end: '$',
relevance: 5
};
/**
* D attributes
*
* @type {Object}
*/
var D_ATTRIBUTE_MODE = {
className: 'keyword',
begin: '@[a-zA-Z_][a-zA-Z_\\d]*'
};
/**
* D nesting comment
*
* @type {Object}
*/
var D_NESTING_COMMENT_MODE = hljs.COMMENT(
'\\/\\+',
'\\+\\/',
{
contains: ['self'],
relevance: 10
}
);
return {
lexemes: hljs.UNDERSCORE_IDENT_RE,
keywords: D_KEYWORDS,
contains: [
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
D_NESTING_COMMENT_MODE,
D_HEX_STRING_MODE,
D_STRING_MODE,
D_WYSIWYG_DELIMITED_STRING_MODE,
D_ALTERNATE_WYSIWYG_STRING_MODE,
D_TOKEN_STRING_MODE,
D_FLOAT_MODE,
D_INTEGER_MODE,
D_CHARACTER_MODE,
D_HASHBANG_MODE,
D_SPECIAL_TOKEN_SEQUENCE_MODE,
D_ATTRIBUTE_MODE
]
};
}

View File

@ -0,0 +1,112 @@
/*
Language: Dart
Requires: markdown.js
Author: Maxim Dikun <dikmax@gmail.com>
Description: Dart is a JavaScript replacement language developed by Google. For more information see http://dartlang.org/
Category: scripting
*/
function (hljs) {
var SUBST = {
className: 'subst',
variants: [
{begin: '\\${', end: '}'},
{begin: '\\$[A-Za-z0-9_]+'}
],
keywords: 'true false null this is new super'
};
var STRING = {
className: 'string',
variants: [
{
begin: 'r\'\'\'', end: '\'\'\''
},
{
begin: 'r"""', end: '"""'
},
{
begin: 'r\'', end: '\'',
illegal: '\\n'
},
{
begin: 'r"', end: '"',
illegal: '\\n'
},
{
begin: '\'\'\'', end: '\'\'\'',
contains: [hljs.BACKSLASH_ESCAPE, SUBST]
},
{
begin: '"""', end: '"""',
contains: [hljs.BACKSLASH_ESCAPE, SUBST]
},
{
begin: '\'', end: '\'',
illegal: '\\n',
contains: [hljs.BACKSLASH_ESCAPE, SUBST]
},
{
begin: '"', end: '"',
illegal: '\\n',
contains: [hljs.BACKSLASH_ESCAPE, SUBST]
}
]
};
SUBST.contains = [
hljs.C_NUMBER_MODE, STRING
];
var KEYWORDS = {
keyword: 'assert async await break case catch class const continue default do else enum extends false final ' +
'finally for if in is new null rethrow return super switch sync this throw true try var void while with yield ' +
'abstract as dynamic export external factory get implements import library operator part set static typedef',
built_in:
// dart:core
'print Comparable DateTime Duration Function Iterable Iterator List Map Match Null Object Pattern RegExp Set ' +
'Stopwatch String StringBuffer StringSink Symbol Type Uri bool double int num ' +
// dart:html
'document window querySelector querySelectorAll Element ElementList'
};
return {
keywords: KEYWORDS,
contains: [
STRING,
hljs.COMMENT(
'/\\*\\*',
'\\*/',
{
subLanguage: 'markdown'
}
),
hljs.COMMENT(
'///',
'$',
{
subLanguage: 'markdown'
}
),
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
{
className: 'class',
beginKeywords: 'class interface', end: '{', excludeEnd: true,
contains: [
{
beginKeywords: 'extends implements'
},
hljs.UNDERSCORE_TITLE_MODE
]
},
hljs.C_NUMBER_MODE,
{
className: 'meta', begin: '@[A-Za-z]+'
},
{
begin: '=>' // No markup, just a relevance booster
}
]
}
}

View File

@ -0,0 +1,72 @@
/*
Language: Delphi
*/
function(hljs) {
var KEYWORDS =
'exports register file shl array record property for mod while set ally label uses raise not ' +
'stored class safecall var interface or private static exit index inherited to else stdcall ' +
'override shr asm far resourcestring finalization packed virtual out and protected library do ' +
'xorwrite goto near function end div overload object unit begin string on inline repeat until ' +
'destructor write message program with read initialization except default nil if case cdecl in ' +
'downto threadvar of try pascal const external constructor type public then implementation ' +
'finally published procedure absolute reintroduce operator as is abstract alias assembler ' +
'bitpacked break continue cppdecl cvar enumerator experimental platform deprecated ' +
'unimplemented dynamic export far16 forward generic helper implements interrupt iochecks ' +
'local name nodefault noreturn nostackframe oldfpccall otherwise saveregisters softfloat ' +
'specialize strict unaligned varargs ';
var COMMENT_MODES = [
hljs.C_LINE_COMMENT_MODE,
hljs.COMMENT(/\{/, /\}/, {relevance: 0}),
hljs.COMMENT(/\(\*/, /\*\)/, {relevance: 10})
];
var DIRECTIVE = {
className: 'meta',
variants: [
{begin: /\{\$/, end: /\}/},
{begin: /\(\*\$/, end: /\*\)/}
]
};
var STRING = {
className: 'string',
begin: /'/, end: /'/,
contains: [{begin: /''/}]
};
var CHAR_STRING = {
className: 'string', begin: /(#\d+)+/
};
var CLASS = {
begin: hljs.IDENT_RE + '\\s*=\\s*class\\s*\\(', returnBegin: true,
contains: [
hljs.TITLE_MODE
]
};
var FUNCTION = {
className: 'function',
beginKeywords: 'function constructor destructor procedure', end: /[:;]/,
keywords: 'function constructor|10 destructor|10 procedure|10',
contains: [
hljs.TITLE_MODE,
{
className: 'params',
begin: /\(/, end: /\)/,
keywords: KEYWORDS,
contains: [STRING, CHAR_STRING, DIRECTIVE].concat(COMMENT_MODES)
},
DIRECTIVE
].concat(COMMENT_MODES)
};
return {
aliases: ['dpr', 'dfm', 'pas', 'pascal', 'freepascal', 'lazarus', 'lpr', 'lfm'],
case_insensitive: true,
keywords: KEYWORDS,
illegal: /"|\$[G-Zg-z]|\/\*|<\/|\|/,
contains: [
STRING, CHAR_STRING,
hljs.NUMBER_MODE,
CLASS,
FUNCTION,
DIRECTIVE
].concat(COMMENT_MODES)
};
}

View File

@ -0,0 +1,46 @@
/*
Language: Diff
Description: Unified and context diff
Author: Vasily Polovnyov <vast@whiteants.net>
Category: common
*/
function(hljs) {
return {
aliases: ['patch'],
contains: [
{
className: 'meta',
relevance: 10,
variants: [
{begin: /^@@ +\-\d+,\d+ +\+\d+,\d+ +@@$/},
{begin: /^\*\*\* +\d+,\d+ +\*\*\*\*$/},
{begin: /^\-\-\- +\d+,\d+ +\-\-\-\-$/}
]
},
{
className: 'comment',
variants: [
{begin: /Index: /, end: /$/},
{begin: /={3,}/, end: /$/},
{begin: /^\-{3}/, end: /$/},
{begin: /^\*{3} /, end: /$/},
{begin: /^\+{3}/, end: /$/},
{begin: /\*{5}/, end: /\*{5}$/}
]
},
{
className: 'addition',
begin: '^\\+', end: '$'
},
{
className: 'deletion',
begin: '^\\-', end: '$'
},
{
className: 'addition',
begin: '^\\!', end: '$'
}
]
};
}

View File

@ -0,0 +1,71 @@
/*
Language: Django
Requires: xml.js
Author: Ivan Sagalaev <maniac@softwaremaniacs.org>
Contributors: Ilya Baryshev <baryshev@gmail.com>
Category: template
*/
function(hljs) {
var FILTER = {
begin: /\|[A-Za-z]+:?/,
keywords: {
name:
'truncatewords removetags linebreaksbr yesno get_digit timesince random striptags ' +
'filesizeformat escape linebreaks length_is ljust rjust cut urlize fix_ampersands ' +
'title floatformat capfirst pprint divisibleby add make_list unordered_list urlencode ' +
'timeuntil urlizetrunc wordcount stringformat linenumbers slice date dictsort ' +
'dictsortreversed default_if_none pluralize lower join center default ' +
'truncatewords_html upper length phone2numeric wordwrap time addslashes slugify first ' +
'escapejs force_escape iriencode last safe safeseq truncatechars localize unlocalize ' +
'localtime utc timezone'
},
contains: [
hljs.QUOTE_STRING_MODE,
hljs.APOS_STRING_MODE
]
};
return {
aliases: ['jinja'],
case_insensitive: true,
subLanguage: 'xml',
contains: [
hljs.COMMENT(/\{%\s*comment\s*%}/, /\{%\s*endcomment\s*%}/),
hljs.COMMENT(/\{#/, /#}/),
{
className: 'template-tag',
begin: /\{%/, end: /%}/,
contains: [
{
className: 'name',
begin: /\w+/,
keywords: {
name:
'comment endcomment load templatetag ifchanged endifchanged if endif firstof for ' +
'endfor ifnotequal endifnotequal widthratio extends include spaceless ' +
'endspaceless regroup ifequal endifequal ssi now with cycle url filter ' +
'endfilter debug block endblock else autoescape endautoescape csrf_token empty elif ' +
'endwith static trans blocktrans endblocktrans get_static_prefix get_media_prefix ' +
'plural get_current_language language get_available_languages ' +
'get_current_language_bidi get_language_info get_language_info_list localize ' +
'endlocalize localtime endlocaltime timezone endtimezone get_current_timezone ' +
'verbatim'
},
starts: {
endsWithParent: true,
keywords: 'in by as',
contains: [FILTER],
relevance: 0
}
}
]
},
{
className: 'template-variable',
begin: /\{\{/, end: /}}/,
contains: [FILTER]
}
]
};
}

View File

@ -0,0 +1,34 @@
/*
Language: DNS Zone file
Author: Tim Schumacher <tim@datenknoten.me>
Category: config
*/
function(hljs) {
return {
aliases: ['bind', 'zone'],
keywords: {
keyword:
'IN A AAAA AFSDB APL CAA CDNSKEY CDS CERT CNAME DHCID DLV DNAME DNSKEY DS HIP IPSECKEY KEY KX ' +
'LOC MX NAPTR NS NSEC NSEC3 NSEC3PARAM PTR RRSIG RP SIG SOA SRV SSHFP TA TKEY TLSA TSIG TXT'
},
contains: [
hljs.COMMENT(';', '$', {relevance: 0}),
{
className: 'meta',
begin: /^\$(TTL|GENERATE|INCLUDE|ORIGIN)\b/
},
// IPv6
{
className: 'number',
begin: '((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))\\b'
},
// IPv4
{
className: 'number',
begin: '((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\b'
},
hljs.inherit(hljs.NUMBER_MODE, {begin: /\b\d+[dhwm]?/})
]
};
}

View File

@ -0,0 +1,29 @@
/*
Language: Dockerfile
Requires: bash.js
Author: Alexis Hénaut <alexis@henaut.net>
Description: language definition for Dockerfile files
Category: config
*/
function(hljs) {
return {
aliases: ['docker'],
case_insensitive: true,
keywords: 'from maintainer expose env arg user onbuild stopsignal',
contains: [
hljs.HASH_COMMENT_MODE,
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
hljs.NUMBER_MODE,
{
beginKeywords: 'run cmd entrypoint volume add copy workdir label healthcheck shell',
starts: {
end: /[^\\]$/,
subLanguage: 'bash'
}
}
],
illegal: '</'
}
}

View File

@ -0,0 +1,57 @@
/*
Language: DOS .bat
Author: Alexander Makarov <sam@rmcreative.ru>
Contributors: Anton Kochkov <anton.kochkov@gmail.com>
*/
function(hljs) {
var COMMENT = hljs.COMMENT(
/^\s*@?rem\b/, /$/,
{
relevance: 10
}
);
var LABEL = {
className: 'symbol',
begin: '^\\s*[A-Za-z._?][A-Za-z0-9_$#@~.?]*(:|\\s+label)',
relevance: 0
};
return {
aliases: ['bat', 'cmd'],
case_insensitive: true,
illegal: /\/\*/,
keywords: {
keyword:
'if else goto for in do call exit not exist errorlevel defined ' +
'equ neq lss leq gtr geq',
built_in:
'prn nul lpt3 lpt2 lpt1 con com4 com3 com2 com1 aux ' +
'shift cd dir echo setlocal endlocal set pause copy ' +
'append assoc at attrib break cacls cd chcp chdir chkdsk chkntfs cls cmd color ' +
'comp compact convert date dir diskcomp diskcopy doskey erase fs ' +
'find findstr format ftype graftabl help keyb label md mkdir mode more move path ' +
'pause print popd pushd promt rd recover rem rename replace restore rmdir shift' +
'sort start subst time title tree type ver verify vol ' +
// winutils
'ping net ipconfig taskkill xcopy ren del'
},
contains: [
{
className: 'variable', begin: /%%[^ ]|%[^ ]+?%|![^ ]+?!/
},
{
className: 'function',
begin: LABEL.begin, end: 'goto:eof',
contains: [
hljs.inherit(hljs.TITLE_MODE, {begin: '([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*'}),
COMMENT
]
},
{
className: 'number', begin: '\\b\\d+',
relevance: 0
},
COMMENT
]
};
}

View File

@ -0,0 +1,52 @@
/*
Language: dsconfig
Description: dsconfig batch configuration language for LDAP directory servers
Contributors: Jacob Childress <jacobc@gmail.com>
Category: enterprise, config
*/
function(hljs) {
var QUOTED_PROPERTY = {
className: 'string',
begin: /"/, end: /"/
};
var APOS_PROPERTY = {
className: 'string',
begin: /'/, end: /'/
};
var UNQUOTED_PROPERTY = {
className: 'string',
begin: '[\\w-?]+:\\w+', end: '\\W',
relevance: 0
};
var VALUELESS_PROPERTY = {
className: 'string',
begin: '\\w+-?\\w+', end: '\\W',
relevance: 0
};
return {
keywords: 'dsconfig',
contains: [
{
className: 'keyword',
begin: '^dsconfig', end: '\\s', excludeEnd: true,
relevance: 10
},
{
className: 'built_in',
begin: '(list|create|get|set|delete)-(\\w+)', end: '\\s', excludeEnd: true,
illegal: '!@#$%^&*()',
relevance: 10
},
{
className: 'built_in',
begin: '--(\\w+)', end: '\\s', excludeEnd: true
},
QUOTED_PROPERTY,
APOS_PROPERTY,
UNQUOTED_PROPERTY,
VALUELESS_PROPERTY,
hljs.HASH_COMMENT_MODE
]
};
}

View File

@ -0,0 +1,131 @@
/*
Language: Device Tree
Description: *.dts files used in the Linux kernel
Author: Martin Braun <martin.braun@ettus.com>, Moritz Fischer <moritz.fischer@ettus.com>
Category: config
*/
function(hljs) {
var STRINGS = {
className: 'string',
variants: [
hljs.inherit(hljs.QUOTE_STRING_MODE, { begin: '((u8?|U)|L)?"' }),
{
begin: '(u8?|U)?R"', end: '"',
contains: [hljs.BACKSLASH_ESCAPE]
},
{
begin: '\'\\\\?.', end: '\'',
illegal: '.'
}
]
};
var NUMBERS = {
className: 'number',
variants: [
{ begin: '\\b(\\d+(\\.\\d*)?|\\.\\d+)(u|U|l|L|ul|UL|f|F)' },
{ begin: hljs.C_NUMBER_RE }
],
relevance: 0
};
var PREPROCESSOR = {
className: 'meta',
begin: '#', end: '$',
keywords: {'meta-keyword': 'if else elif endif define undef ifdef ifndef'},
contains: [
{
begin: /\\\n/, relevance: 0
},
{
beginKeywords: 'include', end: '$',
keywords: {'meta-keyword': 'include'},
contains: [
hljs.inherit(STRINGS, {className: 'meta-string'}),
{
className: 'meta-string',
begin: '<', end: '>',
illegal: '\\n'
}
]
},
STRINGS,
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE
]
};
var DTS_REFERENCE = {
className: 'variable',
begin: '\\&[a-z\\d_]*\\b'
};
var DTS_KEYWORD = {
className: 'meta-keyword',
begin: '/[a-z][a-z\\d-]*/'
};
var DTS_LABEL = {
className: 'symbol',
begin: '^\\s*[a-zA-Z_][a-zA-Z\\d_]*:'
};
var DTS_CELL_PROPERTY = {
className: 'params',
begin: '<',
end: '>',
contains: [
NUMBERS,
DTS_REFERENCE
]
};
var DTS_NODE = {
className: 'class',
begin: /[a-zA-Z_][a-zA-Z\d_@]*\s{/,
end: /[{;=]/,
returnBegin: true,
excludeEnd: true
};
var DTS_ROOT_NODE = {
className: 'class',
begin: '/\\s*{',
end: '};',
relevance: 10,
contains: [
DTS_REFERENCE,
DTS_KEYWORD,
DTS_LABEL,
DTS_NODE,
DTS_CELL_PROPERTY,
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
NUMBERS,
STRINGS
]
};
return {
keywords: "",
contains: [
DTS_ROOT_NODE,
DTS_REFERENCE,
DTS_KEYWORD,
DTS_LABEL,
DTS_NODE,
DTS_CELL_PROPERTY,
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
NUMBERS,
STRINGS,
PREPROCESSOR,
{
begin: hljs.IDENT_RE + '::',
keywords: ""
}
]
};
}

View File

@ -0,0 +1,39 @@
/*
Language: Dust
Requires: xml.js
Author: Michael Allen <michael.allen@benefitfocus.com>
Description: Matcher for dust.js templates.
Category: template
*/
function(hljs) {
var EXPRESSION_KEYWORDS = 'if eq ne lt lte gt gte select default math sep';
return {
aliases: ['dst'],
case_insensitive: true,
subLanguage: 'xml',
contains: [
{
className: 'template-tag',
begin: /\{[#\/]/, end: /\}/, illegal: /;/,
contains: [
{
className: 'name',
begin: /[a-zA-Z\.-]+/,
starts: {
endsWithParent: true, relevance: 0,
contains: [
hljs.QUOTE_STRING_MODE
]
}
}
]
},
{
className: 'template-variable',
begin: /\{/, end: /\}/, illegal: /;/,
keywords: EXPRESSION_KEYWORDS
}
]
};
}

View File

@ -0,0 +1,37 @@
/*
Language: Extended Backus-Naur Form
Author: Alex McKibben <alex@nullscope.net>
*/
function(hljs) {
var commentMode = hljs.COMMENT(/\(\*/, /\*\)/);
var nonTerminalMode = {
className: "attribute",
begin: /^[ ]*[a-zA-Z][a-zA-Z-]*([\s-]+[a-zA-Z][a-zA-Z]*)*/
};
var specialSequenceMode = {
className: "meta",
begin: /\?.*\?/
};
var ruleBodyMode = {
begin: /=/, end: /;/,
contains: [
commentMode,
specialSequenceMode,
// terminals
hljs.APOS_STRING_MODE, hljs.QUOTE_STRING_MODE
]
};
return {
illegal: /\S/,
contains: [
commentMode,
nonTerminalMode,
ruleBodyMode
]
};
}

View File

@ -0,0 +1,106 @@
/*
Language: Elixir
Author: Josh Adams <josh@isotope11.com>
Description: language definition for Elixir source code files (.ex and .exs). Based on ruby language support.
Category: functional
*/
function(hljs) {
var ELIXIR_IDENT_RE = '[a-zA-Z_][a-zA-Z0-9_.]*(\\!|\\?)?';
var ELIXIR_METHOD_RE = '[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?';
var ELIXIR_KEYWORDS =
'and false then defined module in return redo retry end for true self when ' +
'next until do begin unless nil break not case cond alias while ensure or ' +
'include use alias fn quote require import with|0';
var SUBST = {
className: 'subst',
begin: '#\\{', end: '}',
lexemes: ELIXIR_IDENT_RE,
keywords: ELIXIR_KEYWORDS
};
var STRING = {
className: 'string',
contains: [hljs.BACKSLASH_ESCAPE, SUBST],
variants: [
{
begin: /'/, end: /'/
},
{
begin: /"/, end: /"/
}
]
};
var FUNCTION = {
className: 'function',
beginKeywords: 'def defp defmacro', end: /\B\b/, // the mode is ended by the title
contains: [
hljs.inherit(hljs.TITLE_MODE, {
begin: ELIXIR_IDENT_RE,
endsParent: true
})
]
};
var CLASS = hljs.inherit(FUNCTION, {
className: 'class',
beginKeywords: 'defimpl defmodule defprotocol defrecord', end: /\bdo\b|$|;/
});
var ELIXIR_DEFAULT_CONTAINS = [
STRING,
hljs.HASH_COMMENT_MODE,
CLASS,
FUNCTION,
{
begin: '::'
},
{
className: 'symbol',
begin: ':(?![\\s:])',
contains: [STRING, {begin: ELIXIR_METHOD_RE}],
relevance: 0
},
{
className: 'symbol',
begin: ELIXIR_IDENT_RE + ':(?!:)',
relevance: 0
},
{
className: 'number',
begin: '(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b',
relevance: 0
},
{
className: 'variable',
begin: '(\\$\\W)|((\\$|\\@\\@?)(\\w+))'
},
{
begin: '->'
},
{ // regexp container
begin: '(' + hljs.RE_STARTERS_RE + ')\\s*',
contains: [
hljs.HASH_COMMENT_MODE,
{
className: 'regexp',
illegal: '\\n',
contains: [hljs.BACKSLASH_ESCAPE, SUBST],
variants: [
{
begin: '/', end: '/[a-z]*'
},
{
begin: '%r\\[', end: '\\][a-z]*'
}
]
}
],
relevance: 0
}
];
SUBST.contains = ELIXIR_DEFAULT_CONTAINS;
return {
lexemes: ELIXIR_IDENT_RE,
keywords: ELIXIR_KEYWORDS,
contains: ELIXIR_DEFAULT_CONTAINS
};
}

View File

@ -0,0 +1,95 @@
/*
Language: Elm
Author: Janis Voigtlaender <janis.voigtlaender@gmail.com>
Category: functional
*/
function(hljs) {
var COMMENT = {
variants: [
hljs.COMMENT('--', '$'),
hljs.COMMENT(
'{-',
'-}',
{
contains: ['self']
}
)
]
};
var CONSTRUCTOR = {
className: 'type',
begin: '\\b[A-Z][\\w\']*', // TODO: other constructors (built-in, infix).
relevance: 0
};
var LIST = {
begin: '\\(', end: '\\)',
illegal: '"',
contains: [
{className: 'type', begin: '\\b[A-Z][\\w]*(\\((\\.\\.|,|\\w+)\\))?'},
COMMENT
]
};
var RECORD = {
begin: '{', end: '}',
contains: LIST.contains
};
var CHARACTER = {
className: 'string',
begin: '\'\\\\?.', end: '\'',
illegal: '.'
};
return {
keywords:
'let in if then else case of where module import exposing ' +
'type alias as infix infixl infixr port effect command subscription',
contains: [
// Top-level constructions.
{
beginKeywords: 'port effect module', end: 'exposing',
keywords: 'port effect module where command subscription exposing',
contains: [LIST, COMMENT],
illegal: '\\W\\.|;'
},
{
begin: 'import', end: '$',
keywords: 'import as exposing',
contains: [LIST, COMMENT],
illegal: '\\W\\.|;'
},
{
begin: 'type', end: '$',
keywords: 'type alias',
contains: [CONSTRUCTOR, LIST, RECORD, COMMENT]
},
{
beginKeywords: 'infix infixl infixr', end: '$',
contains: [hljs.C_NUMBER_MODE, COMMENT]
},
{
begin: 'port', end: '$',
keywords: 'port',
contains: [COMMENT]
},
// Literals and names.
CHARACTER,
hljs.QUOTE_STRING_MODE,
hljs.C_NUMBER_MODE,
CONSTRUCTOR,
hljs.inherit(hljs.TITLE_MODE, {begin: '^[_a-z][\\w\']*'}),
COMMENT,
{begin: '->|<-'} // No markup, relevance booster
],
illegal: /;/
};
}

View File

@ -0,0 +1,23 @@
/*
Language: ERB (Embedded Ruby)
Requires: xml.js, ruby.js
Author: Lucas Mazza <lucastmazza@gmail.com>
Contributors: Kassio Borges <kassioborgesm@gmail.com>
Description: "Bridge" language defining fragments of Ruby in HTML within <% .. %>
Category: template
*/
function(hljs) {
return {
subLanguage: 'xml',
contains: [
hljs.COMMENT('<%#', '%>'),
{
begin: '<%[%=-]?', end: '[%-]?%>',
subLanguage: 'ruby',
excludeBegin: true,
excludeEnd: true
}
]
};
}

Some files were not shown because too many files have changed in this diff Show More