### Basic Dockerfile Setup
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/dockerfile/default.expect.txt
This is a standard Dockerfile for setting up a PHP environment. It includes package installation, configuration, and runtime settings.
```dockerfile
FROM ubuntu
MAINTAINER laurent@docker.com
ARG debug=0
COPY www.conf /etc/php5/fpm/pool.d/
RUN apt-get update
&& apt-get install -y php5-fpm php-apc php5-curl php5-gd php5-intl php5-mysql
RUN mkdir /tmp/sessions
ENV APPLICATION_ENV dev
USER www-data
EXPOSE 80
VOLUME [ "/var/www/html" ]
WORKDIR "/var/www/html"
CMD [ "/usr/sbin/php5-fpm", "-F" ]
```
--------------------------------
### NSIS Installer Script Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/detect/nsis/default.txt
A basic NSIS installer script demonstrating includes, defines, settings, pages, sections, and functions. It shows conditional installation directory based on a define and logging execution of a command.
```nsis
/*
NSIS Scheme
for highlight.js
*/
; Includes
!include MUI2.nsh
; Defines
!define x64 "true"
; Settings
Name "installer_name"
OutFile "installer_name.exe"
RequestExecutionLevel user
CRCCheck on
!ifdef ${x64}
InstallDir "$PROGRAMFILES64\installer_name"
!else
InstallDir "$PROGRAMFILES\installer_name"
!endif
; Pages
!insertmacro MUI_PAGE_INSTFILES
; Sections
Section "section_name" section_index
nsExec::ExecToLog "calc.exe"
SectionEnd
; Functions
Function .onInit
DetailPrint "The install button reads $(^InstallBtn)"
DetailPrint 'Here comes a$\n$\rline-break!'
DetailPrint `Escape the dollar-sign: $$`
FunctionEnd
```
--------------------------------
### Basic Dockerfile Structure
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/dockerfile/default.txt
This snippet shows a typical Dockerfile setup including base image, maintainer, arguments, file copying, package installation, directory creation, environment variables, user, exposed ports, volumes, working directory, and the command to run.
```dockerfile
FROM ubuntu
MAINTAINER laurent@docker.com
ARG debug=0
COPY www.conf /etc/php5/fpm/pool.d/
RUN apt-get update \
&& apt-get install -y php5-fpm php-apc php5-curl php5-gd php5-intl php5-mysql
RUN mkdir /tmp/sessions
ENV APPLICATION_ENV dev
USER www-data
EXPOSE 80
VOLUME ["/var/www/html"]
WORKDIR "/var/www/html"
CMD [ "/usr/sbin/php5-fpm", "-F" ]
```
--------------------------------
### Define Mode with begin and keywords
Source: https://github.com/highlightjs/highlight.js/blob/main/docs/mode-reference.rst
This example shows how to define a mode using both 'begin' for the starting pattern and 'keywords' for keyword matching. This is an alternative to using 'beginKeywords'.
```javascript
{
begin: '\\b(class|interface)\\b',
keywords: 'class interface'
}
```
--------------------------------
### NSIS Initialization Function
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/nsis/default.txt
The .onInit function runs when the installer starts. It prints messages including variables and escaped characters.
```nsis
Function .onInit
DetailPrint "The install button reads $(^InstallBtn)"
DetailPrint 'Here comes a$\n$\rline-break!'
DetailPrint `Escape the dollar-sign: $$`
FunctionEnd
```
--------------------------------
### Install Highlight.js via NPM
Source: https://github.com/highlightjs/highlight.js/blob/main/README.md
Install the main Highlight.js package, which includes all supported languages, using NPM or Yarn.
```bash
npm install highlight.js
# or
yarn add highlight.js
```
--------------------------------
### G-code: Basic Setup and Toolpath
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/gcode/default.expect.txt
This snippet demonstrates initial setup commands like tool changes and spindle activation, followed by a simple cutting path with cutter radius compensation.
```gcode
N2 G54 G90 G49 G80
N3 M6 T1 (1.ENDMILL)
N4 M3 S1800
N5 G0 X-.6 Y2.050
N6 G43 H1 Y.1
N7 G1 Z-.3 F50.
N8 G41 D1 Y1.45
N9 G1 X0 F20.
N10 G2 J-1.45
(CUTTER COMP CANCEL)
N11 G1 Z-.2 F50.
N12 Y-.990
N13 G40
N14 G0 X-.6 Y1.590
N15 G0 Z.1
N16 M5 G49 G28 G91 Z0
N17 CALL O9456
```
--------------------------------
### NSIS Installer Configuration
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/nsis/default.txt
Basic NSIS installer setup including name, output file, execution level, and CRC check.
```nsis
!assert ${NSIS_CHAR_SIZE} = 2 "Unicode required"
; Includes
!include MUI2.nsh
; Defines
!define x64 "true"
; Settings
Name "installer_name"
OutFile "installer_name.exe"
RequestExecutionLevel user
CRCCheck on
```
--------------------------------
### Roxygen Example with Inline Code and Tag
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/r/roxygen.expect.txt
Shows an Roxygen example tag containing inline code and another Roxygen tag within the example string itself.
```R
#' @examples
# test = '`code{1 + 2} @return`'
format = function (str) {}
```
--------------------------------
### Elixir GenServer Behaviour Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/detect/elixir/default.txt
Shows how to define a GenServer behaviour with a guard clause and public API for starting the server.
```elixir
defmodule ListServer do
defguardp apostrophe?(c) when c == ?'
@moduledoc """
This module provides an easy to use ListServer, useful for keeping
lists of things.
"""
use GenServer.Behaviour
alias Foo.Bar
### Public API
@doc """
Starts and links a new ListServer, returning {:ok, pid}
## Example
iex> {:ok, pid} = ListServer.start_link
"""
def start_link do
:gen_server.start_link({:local, :list}, __MODULE__, [], [])
end
### GenServer API
def init(list) do
{:ok, list}
end
# Clear the list
def handle_cast :clear, list do
{:noreply, []}
end
end
{:ok, pid} = ListServer.start_link
```
--------------------------------
### Class-Based Plugin Example
Source: https://github.com/highlightjs/highlight.js/blob/main/docs/plugin-api.rst
An example of a class-based plugin for managing configuration options and state, demonstrating the constructor and a callback hook.
```javascript
class DataLanguagePlugin {
constructor(options) {
self.prefix = options.dataPrefix;
}
'after:highlightElement'({ el, result, text }) {
// ...
}
}
hljs.addPlugin(new DataLanguagePlugin({ dataPrefix: 'hljs' }));
```
--------------------------------
### Non-Highlighted Julia Code Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/julia-repl/default.txt
Shows examples of ordinary Julia code, such as package installation and type definition, which are not highlighted in the REPL.
```julia
Pkg.add("Combinatorics")
abstract type Foo end
```
--------------------------------
### Build for Node.js with All Languages
Source: https://github.com/highlightjs/highlight.js/blob/main/docs/building-testing.rst
Build the Highlight.js library for a Node.js environment, including all available languages. Ensure Node.js is installed and dependencies are fetched with `npm install`.
```bash
node tools/build.js -t node
```
--------------------------------
### JRuby String Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/ruby/prompt.expect.txt
A basic string literal example in the JRuby prompt.
```ruby
jruby-1.7.16 :001 > "RVM-Format"
```
--------------------------------
### Clojure Deps EDN Configuration Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/clojure/deps_edn.txt
A comprehensive example of a deps.edn file, demonstrating project dependencies, aliases for development and export, and source paths.
```clojure
{:aliases {:export {:exec-fn stelcodes.dev-blog.generator/export},
:repl {:extra-deps {cider/cider-nrepl {:mvn/version "0.25.2"},
nrepl/nrepl {:mvn/version "0.8.3"}},
:extra-paths ["dev"],
:main-opts ["-m"
"nrepl.cmdline"
"--middleware"
"[cider.nrepl/cider-middleware]"
"--interactive"]},
:webhook {:exec-fn stelcodes.dev-blog.webhook/listen}},
:deps {http-kit/http-kit {:mvn/version "2.5.3"},
org.clojure/clojure {:mvn/version "1.10.1"},
stasis/stasis {:mvn/version "2.5.1"}},
:paths ["src" "resources"]}
```
--------------------------------
### Basic Processing Sketch Structure
Source: https://github.com/highlightjs/highlight.js/blob/main/test/detect/processing/default.txt
This snippet shows the essential setup and draw functions in Processing. The setup function runs once at the beginning, and the draw function runs repeatedly to create animation or interactive elements.
```processing
import java.util.LinkedList;
import java.awt.Point;
PGraphics pg;
String load;
void setup() {
size(displayWidth, displayHeight, P3D);
pg = createGraphics(displayWidth*2,displayHeight,P2D);
pg.beginDraw();
pg.background(255,255,255);
//pg.smooth(8);
pg.endDraw();
}
void draw(){
background(255);
}
```
--------------------------------
### NSIS Installer Configuration
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/nsis/default.expect.txt
Basic NSIS script demonstrating configuration directives like Name, OutFile, and ExecutionLevel, along with conditional installation directory based on architecture.
```nsis
!assert ${NSIS_CHAR_SIZE} = 2 "Unicode required"
; Includes
!include MUI2.nsh
; Defines
!define x64 "true"
; Settings
Name "installer_name"
OutFile "installer_name.exe"
RequestExecutionLevel user
CRCCheck on
!ifdef ${x64}
InstallDir "$PROGRAMFILES64\installer_name"
!else
InstallDir "$PROGRAMFILES\installer_name"
!endif
; Pages
!insertmacro MUI_PAGE_INSTFILES
; Sections
Section "section_name" section_index
nsExec::ExecToLog "calc.exe"
SectionEnd
; Functions
Function .onInit
DetailPrint "The install button reads $(^InstallBtn)"
DetailPrint 'Here comes a
line-break!'
DetailPrint `Escape the dollar-sign: $$`
FunctionEnd
```
--------------------------------
### Note Block Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/detect/asciidoc/default.txt
Demonstrates how to create a note block in AsciiDoc.
```asciidoc
NOTE: AsciiDoc is quite cool, you should try it.
```
--------------------------------
### Nix REPL: Derivation Creation
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/nix/default.txt
Example of creating a file derivation using pkgs.writeText in the Nix REPL.
```nix
:b pkgs.writeText "file.txt" "content"
```
--------------------------------
### R Function with Roxygen Examples and See Also
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/r/roxygen.expect.txt
Demonstrates a R function with Roxygen comments including examples and a 'see also' tag. The examples show inline code and a link that should not be highlighted, while the 'see also' tag links to a base R function and should be highlighted.
```R
#' Sum of numbers
#'
#' `sum_all` is a wrapper for `sum(..., na.rm = TRUE)`.
#' @param ... one or more numeric vectors
#' @examples
# sum_all(1 : 10) # 55 @this \link{should not be highlighted!}
# sum_all(1, NA, 2, 3) # 6
#' @seealso \link[base]{sum} # this SHOULD be highlighted again.
#' comment
sum_all <- function (...) {
sum(..., na.rm = TRUE)
}
```
--------------------------------
### Lambda Function Examples
Source: https://github.com/highlightjs/highlight.js/blob/main/test/detect/livescript/default.txt
Shows two examples of lambda functions: one with a fixed return value and another taking an argument.
```LiveScript
f = !-> 2
g = (x) !-> x + 2
```
--------------------------------
### Instantiate and Use Classes
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/powershell/classes.txt
Demonstrates creating instances of 'Rack' and 'Device', adding a device to the rack, and retrieving available slots.
```powershell
$rack = [Rack]::new()
$surface = [Device]::new()
$surface.Brand = "Microsoft"
$surface.Model = "Surface Pro 4"
$surface.VendorSku = "5072641000"
$rack.AddDevice($surface, 2)
$rack
$rack.GetAvailableSlots()
```
--------------------------------
### Build for Browser with Common Languages
Source: https://github.com/highlightjs/highlight.js/blob/main/docs/building-testing.rst
Build the Highlight.js library for a browser environment, including only common languages. Ensure Node.js is installed and dependencies are fetched with `npm install`.
```bash
node tools/build.js :common
```
--------------------------------
### Inline Code Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/markdown/code.txt
Demonstrates inline code formatting.
```plaintext
code
```
```plaintext
more code
```
--------------------------------
### Configure Interface Description and VLANs
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/shell/prompt-with-slash.txt
This example demonstrates setting an interface description, ensuring it's not shut down, configuring it as a trunk port, assigning it to a default VLAN, and specifying a comprehensive list of allowed VLANs for trunking. It also includes MTU and flow control settings.
```shell
!
interface ethernet1/1/1
description pao-sw-a03-09_port56
no shutdown
switchport mode trunk
switchport access vlan 1
switchport trunk allowed vlan 998,1000,1006,1010,1012-1015,1102,1200,1210,1296,1300-1304,1310-1312,1320-1322,1330-1332,1340-1352,1400-1404,1410-1412,1420-1422,1430-1432,1440-1452,1500-1504,1510-1512,1520-1522,1530-1532,1540-1552,1600-1604,1610-1612,1620-1622,1630-1632,1640-1652,1700-1704,1710-1712,1720-1722,1730-1732,1740-1752,1800-1804,1810-1812,1820-1822,1830-1832,1840-1852,1900-1904,1910-1912,1920-1922,1930-1932,1940-1952,3939
mtu 9216
flowcontrol receive on
flowcontrol transmit off
```
--------------------------------
### Install CDN Assets Package
Source: https://github.com/highlightjs/highlight.js/blob/main/README.md
Install the package containing prebuilt CDN assets, including ES6 Modules for browser import, using NPM or Yarn.
```bash
npm install @highlightjs/cdn-assets
# or
yarn add @highlightjs/cdn-assets
```
--------------------------------
### ListServer.start_link
Source: https://github.com/highlightjs/highlight.js/blob/main/test/detect/elixir/default.txt
Starts and links a new ListServer, returning {:ok, pid}. This is the primary function to initiate the ListServer.
```APIDOC
## ListServer.start_link
### Description
Starts and links a new ListServer, returning {:ok, pid}.
### Method
N/A (Function Call)
### Parameters
None
### Request Example
```elixir
{:ok, pid} = ListServer.start_link
```
### Response
#### Success Response
- **pid** (pid) - The process identifier of the started ListServer.
### Response Example
```elixir
{:ok, #PID<0.123.0>}
```
```
--------------------------------
### SAS Initialization and Setup
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/sas/default.txt
Sets up SAS options, defines macro variables for directories, creates a directory, and assigns a libname. Essential for preparing the SAS environment.
```sas
%put Started at %sysfunc(putn(%sysfunc(datetime()), datetime.));
options
errors = 20 /* Maximum number of prints of repeat errors */
fullstimer /* Detailed timer after each step execution */
;
%let maindir = /path/to/maindir;
%let outdir = &maindir/out.;
systask command "mkdir -p &outdir." wait;
libname main "&maindir" access = readonly;
```
--------------------------------
### CSS Attribute and Language Selectors
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/css/sample.txt
Selects elements based on an attribute containing 'example' or starting with 'en', setting their font size.
```css
a[href*="example"], * [lang^=en] {
font-size: 2em;
}
```
--------------------------------
### Browser Setup with Automatic Highlighting
Source: https://github.com/highlightjs/highlight.js/blob/main/README.md
Include the library and a theme, then call highlightAll() to automatically detect and highlight code within <pre><code> tags.
```html
```
--------------------------------
### Makefile Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/makefile/default.expect.txt
A sample Makefile demonstrating build and clean targets. It defines build directories and commands for building and cleaning the project.
```makefile
# Makefile
BUILDDIR = _build
EXTRAS ?= $(BUILDDIR)/extras
.PHONY: main clean
main:
@echo "Building main facility..."
build_main $(BUILDDIR)
clean:
rm -rf $(BUILDDIR)/*
```
--------------------------------
### Single Quote Strings
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/matlab/transpose.txt
Shows examples of single quote (') strings in MATLAB, including strings starting at the first column and arrays/cells of strings.
```matlab
sq1 = 'a single quote string';
sq2 = ...
' abcd '; % single quote string starting at column 1
sq3 = ['a','bc']; % array of single quote strings
sq4 = {'a','bc'}; % cell of single quote strings
```
--------------------------------
### PureBASIC Enumeration Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/purebasic/default.txt
Demonstrates the declaration and usage of enumerations with constants in PureBASIC.
```purebasic
Enumeration Test 3 Step 10
#Constant_One ; Will be 3
#Constant_Two ; Will be 13
EndEnumeration
```
--------------------------------
### Go Main Function Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/detect/go/default.txt
This snippet demonstrates the basic structure of a Go program, including channel creation, sending and receiving values, deferring a print statement, and launching a goroutine.
```go
package main
import "fmt"
func main() {
ch := make(chan float64)
ch <- 1.0e10 // magic number
x, ok := <- ch
defer fmt.Println(`exitting now`)
go println(len("hello world!"))
return
}
```
--------------------------------
### Shell Plain Prompt Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/shell/plain-prompt.expect.txt
Shows a basic shell prompt followed by a command.
```shell
> foo
```
--------------------------------
### Inline Code Example 1
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/markdown/code.expect.txt
An example of inline code.
```plaintext
`code`
```
--------------------------------
### SAS Example with Options and Variables
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/sas/default.expect.txt
This snippet sets up directories, options, and defines variables for a SAS program. It includes comments explaining specific options.
```sas
/**********************************************************************
* Program: example.sas
* Purpose: SAS Example for HighlightJS Plug-in
**********************************************************************/
%put Started at %sysfunc(putn(%sysfunc(datetime()), datetime.));
options
errors = 20 /* Maximum number of prints of repeat errors */
fullstimer /* Detailed timer after each step execution */
;
%let maindir = /path/to/maindir;
%let outdir = &maindir/out.;
systask command "mkdir -p &outdir." wait;
libname main "&maindir" access = readonly;
```
--------------------------------
### Begin Scope Example
Source: https://github.com/highlightjs/highlight.js/blob/main/docs/mode-reference.rst
Applies a scope to the 'begin' match portion of a mode.
```javascript
{
begin: /def/,
beginScope: "keyword"
}
```
--------------------------------
### JavaScript Loop Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/cos/embedded.txt
An example of an embedded JavaScript loop.
```javascript
for (var i = 0; i < String("test").split("").length); ++i) { console.log(i); }
```
--------------------------------
### Elixir Defrecord Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/detect/elixir/default.txt
Demonstrates defining a record with default values and a method.
```elixir
defrecord Person, first_name: nil, last_name: "Dudington" do
def name record do # huh ?
"#{record.first_name} #{record.last_name}"
end
end
defrecord User, name: "José", age: 25
guy = Person.new first_name: "Guy"
guy.name
```
--------------------------------
### Defining Simple Functions
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/nix/default.expect.txt
Provides examples of defining simple Nix functions, including a formatted and an unformatted version.
```nix
function = a: b: a // b;
unformattedFunction = a : b : a == b;
```
--------------------------------
### Inline Code Example 2
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/markdown/code.expect.txt
Another example of inline code.
```plaintext
`more code`
```
--------------------------------
### LaTeX \mint command example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/latex/verbatim.expect.txt
Demonstrates the \mint command for block code with syntax highlighting, specifying options and language.
```latex
\mint{\foo{bar}[}.\foo{bar}.
```
--------------------------------
### Nix REPL: Building a Derivation
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/nix/default.expect.txt
Demonstrates using the ':b' command in the Nix REPL to build a derivation and shows its output path.
```nix
nix-repl> :b pkgs.writeText "file.txt" "content"
This derivation produced the following outputs:
out -> /nix/store/v5a715bk02cgvb0fv9kby0nsyy1prpy2-file.txt
[2 built]
```
--------------------------------
### LaTeX verbatim environment example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/latex/verbatim.expect.txt
Demonstrates the standard \begin{verbatim} environment for displaying literal text, including special characters.
```latex
\begin{verbatim}
Some verbatim text
}}%&$
\end{verbatim}
```
--------------------------------
### PostgreSQL String Aggregation Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/pgsql/window-functions.txt
Example of using string_agg with an order clause.
```sql
SELECT string_agg(empno, ',' ORDER BY a) FROM empsalary;
```
--------------------------------
### Setup Element Relationships
Source: https://github.com/highlightjs/highlight.js/blob/main/tools/sample_files/python.txt
Initializes the relationships between the current element and its parent, previous/next elements, and previous/next siblings.
```python
def setup(self, parent=None, previous_element=None, next_element=None,
previous_sibling=None, next_sibling=None):
"""Sets up the initial relations between this element and
other elements."""
self.parent = parent
self.previous_element = previous_element
if previous_element is not None:
self.previous_element.next_element = self
self.next_element = next_element
if self.next_element:
self.next_element.previous_element = self
self.next_sibling = next_sibling
if self.next_sibling:
self.next_sibling.previous_sibling = self
if (
not previous_sibling
and self.parent is not None and self.parent.contents):
previous_sibling = self.parent.contents[-1]
self.previous_sibling = previous_sibling
if previous_sibling:
self.previous_sibling.next_sibling = self
```
--------------------------------
### NSIS Page Insertion
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/nsis/default.txt
Inserts the standard file installation page into the installer.
```nsis
!insertmacro MUI_PAGE_INSTFILES
```
--------------------------------
### Importing Modules and Applying Theme
Source: https://github.com/highlightjs/highlight.js/blob/main/test/detect/xl/default.txt
Demonstrates how to import external modules and apply a specific theme for scene rendering.
```XL
import Animate
import SeasonsGreetingsTheme
import "myhelper.xl"
theme "SeasonsGreetings"
```
--------------------------------
### PostgreSQL Filter Clause Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/pgsql/window-functions.txt
Example of using the FILTER clause with a count aggregate function.
```sql
SELECT count(*) FILTER (WHERE i < 5) FROM generate_series(1,10) AS s(i);
```
--------------------------------
### C++ Hello World with Loop
Source: https://github.com/highlightjs/highlight.js/blob/main/test/detect/cpp/default.txt
Demonstrates a basic C++ main function that prints 'Hello, World!' multiple times using a loop. Includes standard library includes and return value.
```cpp
#include
int main(int argc, char *argv[]) {
/* An annoying "Hello World" example */
for (auto i = 0; i < 0xFFFF; i++)
cout << "Hello, World!" << endl;
char c = '\n';
unordered_map > m;
m["key"] = "\\\\"; // this is an error
return -2e3 + 12l;
}
```
--------------------------------
### Line Continuation Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/detect/purebasic/default.txt
Demonstrates string concatenation across multiple lines using the '+' operator.
```purebasic
StrangeProcedureCall ("This command is split " +
"over two lines") ; Line continuation example
```
--------------------------------
### PostgreSQL Percentile Cont Function Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/pgsql/window-functions.txt
Example of calculating a continuous percentile using percentile_cont.
```sql
SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY income) FROM households;
```
--------------------------------
### VB.NET Main Method Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/vbnet/default.txt
Demonstrates a VB.NET Main method with conditional logic, loops, error handling, and LINQ.
```vbnet
Imports System.IO
'#Const DEBUG = True ' Set to false for prod
Namespace Highlighter.Test
''' This is an example class.
Public Class Program
Protected Shared hello As Integer = 3
Private Const ABC As Boolean = False
#Region "Code"
' Cheers!
_
Public Shared Sub Main(ByVal args() As String, ParamArray arr As Object) Handles Form1.Click
On Error Resume Next
If ABC Then
While ABC : Console.WriteLine() : End While
For i As Long = 0 To 1000 Step 123
Try
System.Windows.Forms.MessageBox.Show(CInt("1").ToString())
Catch ex As Exception ' What are you doing? Well...
Dim exp = CType(ex, IOException)
REM ORZ
Return
End Try
Next
Else
Dim l As New System.Collections.List()
SyncLock l
If TypeOf l Is Decimal And l IsNot Nothing Then
RemoveHandler button1.Paint, delegate
End If
Dim d = New System.Threading.Thread(AddressOf ThreadProc)
Dim a = New Action(Sub(x, y) x + y)
Static u = From x As String In l Select x.Substring(2, 4) Where x.Length > 0
End SyncLock
Do : Laugh() : Loop Until hello = 4
End If
End Sub
#End Region
End Class
End Namespace
```
--------------------------------
### NSIS Conditional Installation Directory
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/nsis/default.txt
Sets the installation directory based on whether the system is 64-bit.
```nsis
!ifdef ${x64}
InstallDir "$PROGRAMFILES64\installer_name"
!else
InstallDir "$PROGRAMFILES\installer_name"
!endif
```
--------------------------------
### Class Definition and Instantiation
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/moonscript/default.expect.txt
Shows how to define a class with a constructor and methods, and then instantiate it.
```moonscript
class Inventory
new: =>
@items = {}
add_item: (name) =>
if @items[name]
@items[name] += 1
else
@items[name] = 1
inv = Inventory!
inv.add_item "t-shirt"
inv.add_item "pants"
```
--------------------------------
### AutoIt Singleton Pattern and Looping Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/autoit/default.expect.txt
Demonstrates how to ensure only one instance of a script runs using _Singleton and how to loop through numbers, displaying a message box for each indicating if it's even or odd. Requires the Misc.au3 include file.
```AutoIt
#NoTrayIcon
#AutoIt3Wrapper_Run_Tidy=Y
#include
_Singleton(@ScriptName) ; Allow only one instance
example(0, 10)
Func example($min, $max)
For $i = $min To $max
If Mod($i, 2) == 0 Then
MsgBox(64, "Message", $i & ' is even number!')
Else
MsgBox(64, "Message", $i & ' is odd number!')
EndIf
Next
EndFunc ;==>example
```
--------------------------------
### CSS Attribute Selector with Starts With
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/css/css_consistency.expect.txt
Selects elements whose attribute value starts with a specific substring.
```css
[class^="top"] {}
```
--------------------------------
### Get String Length
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/erlang-repl/default.expect.txt
Calls the test:length function to get the length of the string stored in Str.
```erlang
L = test:length(Str).
```
--------------------------------
### newInstance
Source: https://github.com/highlightjs/highlight.js/blob/main/docs/api.rst
Creates and returns a new instance of the highlighter with default configuration.
```APIDOC
## newInstance
### Description
Returns a new instance of the highlighter with default configuration.
```
--------------------------------
### Swift Interpolation Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/swift/identifiers.expect.txt
Demonstrates string interpolation in Swift using a simple expression.
```swift
func
{ $0 + 1 }
```
--------------------------------
### VB.NET Non-Doc Comment Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/vbnet/comments.txt
An example showing that a single quote followed by HTML is not treated as a documentation comment.
```vbnet
' Not a doc-comment, but html:
```
--------------------------------
### Inline XML Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/detect/asciidoc/default.txt
Demonstrates how to include inline XML content within AsciiDoc.
```asciidoc
++++
++++
```
--------------------------------
### Dart Asynchronous Function Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/detect/dart/default.txt
An example of an asynchronous function in Dart that uses the 'await' keyword to handle a Future.
```dart
checkVersion() async {
var version = await lookUpVersion();
}
```
--------------------------------
### Basic CMakeLists.txt Configuration
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/cmake/default.expect.txt
This snippet sets up a basic CMake project, including version requirements, project name, conditional messages based on the operating system, and automatic MOC processing for Qt.
```cmake
cmake_minimum_required(VERSION 2.8.8)
project(cmake_example)
# Show message on Linux platform
if (${CMAKE_SYSTEM_NAME} MATCHES Linux)
message("Good choice, bro!")
endif()
# Tell CMake to run moc when necessary:
set(CMAKE_AUTOMOC ON)
# As moc files are generated in the binary dir,
# tell CMake to always look for includes there:
set(CMAKE_INCLUDE_CURRENT_DIR ON)
# Widgets finds its own dependencies.
find_package(Qt5Widgets REQUIRED)
add_executable(myproject main.cpp mainwindow.cpp)
qt5_use_modules(myproject Widgets)
#[[This is a bracket comment.
It runs until the close bracket.]]
message("First Argument\n" #[[Bracket Comment]] "Second Argument")
```
--------------------------------
### Adding Plugins
Source: https://github.com/highlightjs/highlight.js/blob/main/docs/plugin-api.rst
Demonstrates how to add plugins to Highlight.js, supporting both class instances and keyed objects of functions.
```javascript
addPlugin(new SimplePlugin());
addPlugin(new MoreComplexPlugin(options));
addPlugin({
'after:highlightElement': ({ el, result, text }) => {
// ...
}
});
```
--------------------------------
### Main Function with Signal Connection and Emission in Vala
Source: https://github.com/highlightjs/highlight.js/blob/main/test/detect/vala/default.txt
The entry point of the Vala program, showing how to instantiate a class, connect signal callbacks, and emit a signal.
```vala
/*
* Entry point can be outside class
*/
void main () {
var long_string = """
Example of "verbatim string".
Same as in @"string" in C#
""";
var foo = new Foo ();
foo.some_event.connect (callback_a); // connecting the callback functions
foo.some_event.connect (callback_b);
foo.method ();
}
```
--------------------------------
### Main Class with Basic Haxe Syntax
Source: https://github.com/highlightjs/highlight.js/blob/main/test/detect/haxe/default.txt
Illustrates basic Haxe class structure, including inheritance, implementation, and instance variables.
```haxe
class Main extends BaseClass implements SomeFunctionality {
var callback:Void->Void = null;
var myArray:Array = new Array();
var arr = [4,8,0,3,9,1,5,2,6,7];
public function new(x) {
super(x);
}
// ... other methods ...
}
```
--------------------------------
### C# Float Literal Examples
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/csharp/floats.expect.txt
Demonstrates different valid syntaxes for float literals in C#.
```csharp
float test = 1.0f;
float test2 = 1.f;
float test3 = 1.0;
float test4 = 1;
float test5 = 1_000;
```
--------------------------------
### HSP Basic Syntax Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/hsp/default.expect.txt
Demonstrates basic HSP syntax including include directives, comments, string literals, variable assignment, and control flow statements like 'if' and 'else'.
```hsp
#include "foo.hsp"
// line comment
message = "Hello, World!"
message2 = {"Multi
line
string"}
num = 0
mes message
input num : button "sqrt", *label
stop
*label
/*
block comment
*/
if(num >= 0) {
dialog "sqrt(" + num + ") = " + sqrt(num)
} else {
dialog "error", 1
}
stop
```
--------------------------------
### Prime Markup Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/pony/prime.expect.txt
Demonstrates the creation of a new element with a name, appending 'a' to it. This is a basic example of string concatenation within markup.
```markup
new create(name': String) =>
name = name' + 'a'
```
--------------------------------
### Curried Function Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/detect/livescript/default.txt
Shows how to create a curried function 'take-three' by partially applying the 'take' function.
```LiveScript
take-three = take 3
take-three [6, 7, 8, 9, 10]
```
--------------------------------
### Setting Up Scene Display
Source: https://github.com/highlightjs/highlight.js/blob/main/test/detect/xl/default.txt
Configures the scene's background color, hand scale, and displays a background image with animated textures.
```XL
page "A nice car",
// --------------------------------------
// Display car model on a pedestal
// --------------------------------------
clear_color 0, 0, 0, 1
hand_scale -> 0.3
// Display the background image
background -4000,
locally
disable_depth_test
corridor N:integer ->
locally
rotatez 60 * N
translatex 1000
rotatey 90
color "white"
texture "stars.png"
texture_wrap true, true
texture_transform
translate (time + N) * 0.02 mod 1, 0, 0
scale 0.2, 0.3, 0.3
rectangle 0, 0, 100000, 1154
```
--------------------------------
### Nix REPL: Basic Arithmetic Operation
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/nix/default.expect.txt
An example of a simple arithmetic operation performed in the Nix REPL.
```nix
nix-repl> 1 + 2
```
--------------------------------
### Subunit Failure Line Examples
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/subunit/subunit-failureline.expect.txt
These examples demonstrate various formats of Subunit failure lines, highlighting differences in spacing and the presence of colons.
```text
failure: test simplename1
```
```text
failure test simplename1
```
```text
failure: test simple name1
```
```text
failure test simple name1
```
--------------------------------
### Get Highlight.js Version String
Source: https://github.com/highlightjs/highlight.js/blob/main/docs/api.rst
Retrieves the full version string of the Highlight.js library.
```javascript
versionString
```
--------------------------------
### CoffeeScript Non-Regex Examples
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/coffeescript/regex.expect.txt
Provides examples that might appear similar to regular expressions but are interpreted differently in CoffeeScript, such as comments or string literals.
```coffeescript
x = //test
x = /boo/test
```
--------------------------------
### Setting and Using Variables
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/cos/basic.txt
Illustrates setting local and global variables and performing arithmetic operations. Conditional logic is also shown.
```intersystems-iris
SET test = 1
set ^global = 2
Write "Current date """, $ztimestamp, """, result: ", test + ^global = 3
if (^global = 2) {
do ##class(Cinema.Utils).AddShow("test") // line comment
}
d:(^global = 2) ..thisClassMethod(1, 2, "test")
```
--------------------------------
### Build and Test with Docker
Source: https://github.com/highlightjs/highlight.js/blob/main/docs/building-testing.rst
Build a Docker container for Highlight.js development. This avoids installing dependencies directly on your system.
```bash
docker build -t highlight-js .
```
--------------------------------
### Scala while-do loop example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/scala/while-do.expect.txt
A basic example of an infinite while-do loop in Scala. This loop will continuously print 'hello' because the condition is always true.
```scala
def f = while true do println("hello")
```
--------------------------------
### Type Definition with Commented Examples in ReasonML
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/reasonml/comments.txt
Shows a ReasonML type definition with examples of how values of this type are represented when commented out. This is useful for documentation or debugging.
```reasonml
type t =
| A(string)
| B(int);
/* A("foo") -> { TAG: 0, _0: "Foo" } */
/* B(2) -> { TAG: 1, _0: 2 } */
```
--------------------------------
### Program Calls and Execution
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/tp/default.expect.txt
Illustrates how to call and run programs or functions with various arguments, including literal strings and variables.
```highlightjs
! program calls ;
CALL TEST ;
CALL TEST(1,'string',SR[1],AR[1]) ;
RUN TEST ;
RUN TEST(1,'string',SR[1],AR[1]) ;
```
--------------------------------
### Erlang Various Sigil Examples
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/erlang/sigil.txt
Provides examples of various Erlang sigils including parenthesis, angle brackets, backticks, hash pounds, and pipes.
```Erlang
~(parenthesis).
```
```Erlang
~.
```
```Erlang
~`backticks`.
```
```Erlang
~#hashpounds#.
```
```Erlang
~|pipes|.
```
--------------------------------
### Include and Define Directives
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/cpp/preprocessor.expect.txt
Demonstrates the use of #include for header files and #define for creating constants and macros.
```cpp
#include
#define foo 1<<16
```
--------------------------------
### Define Perl Class with Inheritance
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/perl/class.txt
Defines a Perl class 'Example::Subclass' that inherits from 'Example::Base'. Includes field declarations with parameters and default values.
```perl
use v5.38;
class Example::Subclass :isa(Example::Base 2.345) {
field $_config :param :param :param;
field $_name : param = 'Test';
method test() {
$_name == 'Test' ? 'y' : 'n';
}
}
```
--------------------------------
### Array Begin with Scopes Example
Source: https://github.com/highlightjs/highlight.js/blob/main/docs/mode-reference.rst
Uses an array for 'begin' and specifies individual scopes for different parts of the match. This allows for granular highlighting within the 'begin' sequence.
```javascript
{
begin: [
/function!/,
/\s+/,
hljs.IDENT_RE
],
beginScope: {
1: "keyword",
3: "title"
},
}
```
--------------------------------
### Basic Language Definition Example
Source: https://github.com/highlightjs/highlight.js/blob/main/docs/language-guide.rst
A basic JavaScript object defining a case-insensitive language with keywords, strings, and comments. This serves as a foundational example for language definitions.
```javascript
{
case_insensitive: true,
keywords: 'for if while',
contains: [
{
scope: 'string',
begin: '"',
end: '"'
},
hljs.COMMENT(
'/\*',
'\*/',
{
contains: [
{
scope: 'doc',
begin: '@\w+'
}
]
}
)
]
}
```
--------------------------------
### LaTeX \hyperref and \href command examples
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/latex/verbatim.expect.txt
Illustrates commands for creating hyperlinks in LaTeX, including specifying labels, categories, and options.
```latex
\hyperref{url}{category}{name}{text}
```
```latex
\hyperref[label]{text}
```
```latex
\href{url}{text}
```
```latex
\href[options]{url}{text}
```
```latex
\href[
several,
options,
on=lines,
]{url}{text}
```
--------------------------------
### Build Highlight.js from Source
Source: https://github.com/highlightjs/highlight.js/blob/main/README.md
Build the Highlight.js library from source for different targets (Node.js, browser, CDN) using the provided build script.
```bash
node tools/build.js -t node
node tools/build.js -t browser :common
node tools/build.js -t cdn :common
```
--------------------------------
### Implement a LiveCode Command
Source: https://github.com/highlightjs/highlight.js/blob/main/test/detect/livecodeserver/default.txt
Defines a simple command named 'blog'. It initializes a local variable and loads helper functions.
```livecode
command blog
-- simple comment
put "Hello World!" into sTest
# ANOTHER COMMENT
put "form,url,asset" into tHelpers
rigLoadHelper tHelpers
end blog
```
--------------------------------
### Stata: Logical Operation Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/stata/built_ins.expect.txt
Assigns a value based on a logical operation. This example uses the 'ln' function, likely for a natural logarithm, in conjunction with a string literal.
```stata
local b1 = ln(`or')
```
--------------------------------
### Julia Method with Keyword Arguments and Assertions
Source: https://github.com/highlightjs/highlight.js/blob/main/test/detect/julia/default.txt
A comprehensive Julia method example showcasing default keyword arguments, version number types, assertions, string interpolation with Unicode characters, local and global variables, and running shell commands.
```julia
function method0(x, y::Int; version::VersionNumber=v"0.1.2")
"""
Triple
Quoted
String
"""
@assert π > e
s = 1.2
変数 = "variable"
if s * 100_000 ≥ 5.2e+10 && true || x === nothing
s = 1. + .5im
elseif 1 ∈ [1, 2, 3]
println("s is $s and 変数 is $変数")
else
x = [1 2 3; 4 5 6]
@show x'
end
local var = rand(10)
global g = 44
var[1:5]
var[5:end-1]
var[end]
opt = "-la"
run(`ls $opt`)
try
ccall(:lib, (Ptr{Void},), Ref{C_NULL})
catch
throw(ArgumentError("wat"))
finally
warn("god save the queen")
end
'\u2200' != 'T'
return 5s / 2
end
```
--------------------------------
### PHP Nowdoc Example with Variable Output
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/php/strings.expect.txt
This example demonstrates that even though variables and expressions are present in the nowdoc content, they are output literally because nowdoc does not perform interpolation.
```php
name}! Welcome to $company!
TEXT
);
```
--------------------------------
### Erlang Triple-Quoted String for Compiler Warning Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/erlang/triple_quote_string.txt
This example uses a triple-quoted string to contain Erlang code that demonstrates a compiler warning for useless tuple building.
```erlang
effect_warning() ->
"""
f() ->
%% Test that the compiler warns for useless tuple building.
{a,b,c},
ok.
""".
```
--------------------------------
### HTML Auto-passthru Example
Source: https://github.com/highlightjs/highlight.js/blob/main/VERSION_11_UPGRADE.md
This example shows how HTML within code blocks is handled. Unescaped HTML will now be ignored and logged as a warning. Ensure all HTML is properly escaped.
```html
var a = 4;
var a = 4;
```
--------------------------------
### ISO-10303-21 File Example
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/step21/default.txt
This snippet shows a basic example of an ISO-10303-21 formatted file, commonly used for CAD data exchange. It includes header information and data definitions.
```plaintext
ISO-10303-21;
HEADER;
FILE_DESCRIPTION((''),'2;1');
FILE_NAME('CUBE_4SQUARE','2013-11-29T',('acook'),(''),
'SOMETHINGCAD BY SOME CORPORATION, 2012130',
'SOMETHINGCAD BY SOME CORPORATION, 2012130','');
FILE_SCHEMA (('CONFIG_CONTROL_DESIGN'));
ENDSEC;
/* file written by SomethingCAD */
DATA;
#1=DIRECTION('',(1.E0,0.E0,0.E0));
#2=VECTOR('',#1,4.E0);
#3=CARTESIAN_POINT('',(-2.E0,-2.E0,-2.E0));
#4=LINE('',#3,#2);
#5=DIRECTION('',(0.E0,1.E0,0.E0));
#6=VECTOR('',#5,4.E0);
#7=CARTESIAN_POINT('',(2.E0,-2.E0,-2.E0));
#8=LINE('',#7,#6);
#9=DIRECTION('',(-1.E0,0.E0,0.E0));
#10=VECTOR('',#9,4.E0);
#11=CARTESIAN_POINT('',(2.E0,2.E0,-2.E0));
#12=LINE('',#11,#10);
#13=DIRECTION('',(0.E0,-1.E0,0.E0));
#14=VECTOR('',#13,4.E0);
#15=CARTESIAN_POINT('',(-2.E0,2.E0,-2.E0));
#16=LINE('',#15,#14);
#17=DIRECTION('',(0.E0,0.E0,1.E0));
#18=VECTOR('',#17,4.E0);
#19=CARTESIAN_POINT('',(-2.E0,-2.E0,-2.E0));
#20=LINE('',#19,#18);
#21=DIRECTION('',(0.E0,0.E0,1.E0));
ENDSEC;
END-ISO-10303-21;
```
--------------------------------
### String Initialization
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/cpp/initializers.expect.txt
Demonstrates direct initialization of string variables with literal values.
```cpp
string a("hello"), b("world");
```
--------------------------------
### Haxe Control Flow Examples
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/haxe/default.expect.txt
Demonstrates for, do-while, and while loops, including continue and break statements. Also shows exception handling with try-catch blocks and instantiation of IntMap.
```haxe
for(i in 0..3) {
trace(i);
continue;
break;
}
do {
trace("Hey-o!");
} while(false);
var done:Bool = false;
while(!done) {
done = true;
}
var H:Int = cast new MyAbstract(42);
var h:Int = cast(new MyAbstract(31), Int);
try {
throw "error";
}
catch(err:String) {
trace(err);
}
var map = new haxe.ds.IntMap();
var f = map.set.bind(_,
"12");
```
--------------------------------
### Roxygen Example with Embedded Code
Source: https://github.com/highlightjs/highlight.js/blob/main/test/markup/r/roxygen.txt
Shows an Roxygen `@examples` tag containing a string literal that itself includes R code syntax like `\code{1 + 2}` and `@return`.
```r
#' @examples
#' test = '\code{1 + 2} @return'
format = function (str) {}
```
--------------------------------
### Starting Point for Prime Selection
Source: https://github.com/highlightjs/highlight.js/blob/main/test/detect/clean/default.txt
Defines the starting point for prime number selection by taking the Nth prime from a list that includes 2, 3, and the generated primes.
```Standard ML
Start :: Int
Start = select [2, 3 : primes] NrOfPrimes
```