---
title: "Syntax Highlighting"
---
### HTML
``` html
<!DOCTYPE html SYSTEM "about:legacy-compat">
<html>
<!-- Behold my erudite commentary -->
<head>
<title>Bat Syntax Test</title>
<meta charset="utf-8">
<script>
const x = 'world';
function logGreeting() {
console.log(`Hello, ${x}`);
}
</script>
</head>
<body>
<div>
<h1>Here find some simple tags</h1>
<br />
<p center style="color: rebeccapurple;">
Lorem <strong>ipsum</strong> dolor sit amet consectetur adipisicing
elit. A quo, autem quaerat explicabo impedit mollitia amet molestiae
nulla cum architecto ducimus itaque sit blanditiis quasi animi optio ab
facilis nihil?
</p>
<p>
Here are some escaped characters: & (ampersand), à (a with grave), № (numero sign).
</p>
</div>
<div>
<h1>This is a form that demonstrates loose attribute formatting</h1>
<form action="POST">
<input
disabled
type="text"
name="text input"
id="specificTextInput"
value="yes"
/>
</form>
</div>
<div>
<h1>A table with normal closing tags</h1>
<table>
<caption>
Pet Features
</caption>
<colgroup>
<col />
<col />
<col />
</colgroup>
<thead>
<tr>
<th>Feature</th>
<th>Cat</th>
<th>Dog</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tail</td>
<td>✔</td>
<td>✔</td>
</tr>
<tr>
<td>Eyes</td>
<td>✔</td>
<td>✔</td>
</tr>
<tr>
<td>Ears</td>
<td>✔</td>
<td>✔</td>
</tr>
<tr>
<td>Barking</td>
<td></td>
<td>✔</td>
</tr>
<tr>
<td>Litter Box</td>
<td>✔</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<div>
<h1>A table without closing tags</h1>
<table>
<caption>Pet Features
<colgroup><col><col><col>
<thead>
<tr> <th>Feature <th>Cat <th>Dog
<tbody>
<tr> <td>Tail <td>✔ <td>✔
<tr> <td>Eyes <td>✔ <td>✔
<tr> <td>Ears <td>✔ <td>✔
<tr> <td>Barking <td> <td>✔
<tr> <td>Litter Box <td>✔ <td>
</tbody>
</table>
</div>
<div>
<h1>A math section with CDATA</h1>
<p>You can add a string to a number, but this stringifies the number:</p>
<math>
<ms><![CDATA[a / b]]></ms>
<mo>-</mo>
<mn>7</mn>
<mo>=</mo>
<ms><![CDATA[a / b - 7]]></ms>
</math>
</div>
</body>
</html>
```
### R
``` r
# take input from the user
num = as.integer(readline(prompt="Enter a number: "))
factorial = 1
# check is the number is negative, positive or zero
if(num < 0) {
print("Sorry, factorial does not exist for negative numbers")
} else if(num == 0) {
print("The factorial of 0 is 1")
} else {
for(i in 1:num) {
factorial = factorial * i
}
print(paste("The factorial of", num ,"is",factorial))
}
x <- 0
if (x < 0) {
print("Negative number")
} else if (x > 0) {
print("Positive number")
} else
print("Zero")
x <- 1:5
for (val in x) {
if (val == 3){
next
}
print(val)
}
x <- 1
repeat {
print(x)
x = x+1
if (x == 6){
break
}
}
`%divisible%` <- function(x,y)
{
if (x%%y ==0) return (TRUE)
else return (FALSE)
}
switch("length", "color" = "red", "shape" = "square", "length" = 5)
[1] 5
recursive.factorial <- function(x) {
if (x == 0) return (1)
else return (x * recursive.factorial(x-1))
}
pow <- function(x, y) {
# function to print x raised to the power y
result <- x^y
print(paste(x,"raised to the power", y, "is", result))
}
A <- read.table("x.data", sep=",",
col.names=c("year", "my1", "my2"))
nrow(A) # Count the rows in A
summary(A$year)
A$newcol <- A$my1 + A$my2 # Makes a new
newvar <- A$my1 - A$my2 # Makes a
A$my1 <- NULL # Removes
str(A)
summary(A)
library(Hmisc)
contents(A)
describe(A)
set.seed(102) # This yields a good illustration.
x <- sample(1:3, 15, replace=TRUE)
education <- factor(x, labels=c("None", "School", "College"))
x <- sample(1:2, 15, replace=TRUE)
gender <- factor(x, labels=c("Male", "Female"))
age <- runif(15, min=20,max=60)
D <- data.frame(age, gender, education)
rm(x,age,gender,education)
print(D)
# Table about education
table(D$education)
# Table about education and gender --
table(D$gender, D$education)
# Joint distribution of education and gender --
table(D$gender, D$education)/nrow(D)
# Add in the marginal distributions also
addmargins(table(D$gender, D$education))
addmargins(table(D$gender, D$education))/nrow(D)
# Generate a good LaTeX table out of it --
library(xtable)
xtable(addmargins(table(D$gender, D$education))/nrow(D),
digits=c(0,2,2,2,2))
by(D$age, D$gender, mean)
by(D$age, D$gender, sd)
by(D$age, D$gender, summary)
a <- matrix(by(D$age, list(D$gender, D$education), mean), nrow=2)
rownames(a) <- levels(D$gender)
colnames(a) <- levels(D$education)
print(a)
print(xtable(a))
dat <- read.csv(file = "files/dataset-2013-01.csv", header = TRUE)
interim_object <- data.frame(rep(1:100, 10),
rep(101:200, 10),
rep(201:300, 10))
object.size(interim_object)
rm("interim_object")
ls()
rm(list = ls())
vector1 <- c(5,9,3)
vector2 <- c(10,11,12,13,14,15)
array1 <- array(c(vector1,vector2),dim = c(3,3,2))
vector3 <- c(9,1,0)
vector4 <- c(6,0,11,3,14,1,2,6,9)
array2 <- array(c(vector1,vector2),dim = c(3,3,2))
matrix1 <- array1[,,2]
matrix2 <- array2[,,2]
result <- matrix1+matrix2
print(result)
column.names <- c("COL1","COL2","COL3")
row.names <- c("ROW1","ROW2","ROW3")
matrix.names <- c("Matrix1","Matrix2")
result <- array(c(vector1,vector2),dim = c(3,3,2),dimnames = list(row.names,
column.names, matrix.names))
print(result[3,,2])
print(result[1,3,1])
print(result[,,2])
# Load the package required to read JSON files.
library("rjson")
result <- fromJSON(file = "input.json")
print(result)
x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131)
y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48)
relation <- lm(y~x)
print(relation)
relation <- lm(y~x)
png(file = "linearregression.png")
plot(y,x,col = "blue",main = "Height & Weight Regression",
abline(lm(x~y)),cex = 1.3,pch = 16,xlab = "Weight in Kg",ylab = "Height in cm")
dev.off()
data <- c("East","West","East","North","North","East","West","West","West","East","North")
print(data)
print(is.factor(data))
factor_data <- factor(data)
print(factor_data)
print(is.factor(factor_data))
v <- c(7,12,28,3,41)
# Give the chart file a name.
png(file = "line_chart_label_colored.jpg")
plot(v,type = "o", col = "red", xlab = "Month", ylab = "Rain fall", main = "Rain fall chart")
```
### Python
``` python
from os import getcwd
import numpy as np
from matplotlib.pyplot import plot as plt
from time import *
# COMMENT test
h2 = 4 # this is a comment
"""this is also a comment"""
# Import test
# class test
class Hello:
def __init__(self, x):
self.name = x
def selfprint(self):
print("hello my name is ", self.name)
def testprint(self):
print(1*2, 2+3, 4 % 5, 8-4, 9/4, 23//4)
# Decorators test
class Decorators:
@classmethod
def decoratorsTest(self):
pass
H1 = Hello("john")
H1.selfprint()
H1.testprint()
# list test
a = [1, 2, 3, 4, 5]
a.sort()
print(a[1:3])
print(a[:4])
print(a[2])
print(a[2:])
# dictionary test
# copied from w3schools example
myfamily = {
"child1": {
"name": "Emil",
"year": 2004
},
"child2": {
"name": "Tobias",
"year": 2007
},
"child3": {
"name": "Linus",
"year": 2011
}
}
# tuple test
testTuple = ("one", 2, "3")
print(testTuple)
print(np.random.randint(5, 45))
# string test
a = "hello world"
b = """good morning
hello world
bye"""
formattest = "teststring is ={}".format(5)
# lambda test
def x2(n):
lambda n: n/7
# if else ladder
if 1 > 2:
print("yes")
elif 4 > 5:
print("maybe")
else:
print("no")
# loops
i = 5
while(i > 0):
print(i)
i -= 1
for x in range(1, 20, 2):
print(x)
```
### YAML
``` yaml
---
# comment
string_1: "Bar"
string_2: 'bar'
string_3: bar
inline_keys_ignored: sompath/name/file.jpg
keywords_in_yaml:
- true
- false
- TRUE
- FALSE
- 21
- 21.0
- !!str 123
"quoted_key": &foobar
bar: foo
foo:
"foo": bar
reference: *foobar
multiline_1: |
Multiline
String
multiline_2: >
Multiline
String
multiline_3: "
Multiline string
"
ansible_variables: "foo {{variable}}"
array_nested:
- a
- b: 1
c: 2
- b
- comment
```
### Bash
``` bash
#!/usr/bin/env bash
###### CONFIG
ACCEPTED_HOSTS="/root/.hag_accepted.conf"
BE_VERBOSE=false
if [ "$UID" -ne 0 ]
then
echo "Superuser rights required"
exit 2
fi
genApacheConf(){
echo -e "# Host ${HOME_DIR}$1/$2 :"
}
echo '"quoted"' | tr -d \" > text.txt
```
### C++
``` cpp
#include <iostream>
int main(int argc, char *argv[]) {
/* An annoying "Hello World" example */
for (auto i = 0; i < 0xFFFF; i++)
cout << "Hello, World!" << endl;
char c = '\n';
unordered_map <string, vector<string> > m;
m["key"] = "\\\\"; // this is an error
return -2e3 + 12l;
}
```
### CSS
``` css
@font-face {
font-family: Chunkfive; src: url('Chunkfive.otf');
}
body, .usertext {
color: #F0F0F0; background: #600;
font-family: Chunkfive, sans;
--heading-1: 30px/32px Helvetica, sans-serif;
}
@import url(print.css);
@media print {
a[href^=http]::after {
content: attr(href)
}
}
```
### SCSS
``` css
@import "compass/reset";
// variables
$colorGreen: #008000;
$colorGreenDark: darken($colorGreen, 10);
@mixin container {
max-width: 980px;
}
// mixins with parameters
@mixin button($color:green) {
@if ($color == green) {
background-color: #008000;
}
@else if ($color == red) {
background-color: #B22222;
}
}
button {
@include button(red);
}
div,
.navbar,
#header,
input[type="input"] {
font-family: "Helvetica Neue", Arial, sans-serif;
width: auto;
margin: 0 auto;
display: block;
}
.row-12 > [class*="spans"] {
border-left: 1px solid #B5C583;
}
// nested definitions
ul {
width: 100%;
padding: {
left: 5px; right: 5px;
}
li {
float: left; margin-right: 10px;
.home {
background: url('http://placehold.it/20') scroll no-repeat 0 0;
}
}
}
.banner {
@extend .container;
}
a {
color: $colorGreen;
&:hover { color: $colorGreenDark; }
&:visited { color: #c458cb; }
}
@for $i from 1 through 5 {
.span#{$i} {
width: 20px*$i;
}
}
@mixin mobile {
@media screen and (max-width : 600px) {
@content;
}
}
```
### Markdown
``` markdown
# hello world
you can write text [with links](http://example.com) inline or [link references][1].
* one _thing_ has *em*phasis
* two __things__ are **bold**
[1]: http://example.com
---
hello world
===========
<this_is inline="xml"></this_is>
> markdown is so cool
so are code segments
1. one thing (yeah!)
2. two thing `i can write code`, and `more` wipee!
```
### TypeScript
``` typescript
class MyClass {
public static myValue: string;
constructor(init: string) {
this.myValue = init;
}
}
import fs = require("fs");
module MyModule {
export interface MyInterface extends Other {
myProperty: any;
}
}
declare magicNumber number;
myArray.forEach(() => { }); // fat arrow syntax
```
### Diff
``` diff
Index: languages/ini.js
===================================================================
--- languages/ini.js (revision 199)
+++ languages/ini.js (revision 200)
@@ -1,8 +1,7 @@
hljs.LANGUAGES.ini =
{
case_insensitive: true,
- defaultMode:
- {
+ defaultMode: {
contains: ['comment', 'title', 'setting'],
illegal: '[^\\s]'
},
*** /path/to/original timestamp
--- /path/to/new timestamp
***************
*** 1,3 ****
--- 1,9 ----
+ This is an important
+ notice! It should
+ therefore be located at
+ the beginning of this
+ document!
! compress the size of the
! changes.
It is important to spell
```
### Ruby
``` ruby
# The Greeter class
class Greeter
def initialize(name)
@name = name.capitalize
end
def salute
puts "Hello #{@name}!"
end
end
g = Greeter.new("world")
g.salute
```
### Go
``` 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
}
```
### Java
``` java
/**
* @author John Smith <[email protected]>
*/
package l2f.gameserver.model;
public abstract strictfp class L2Char extends L2Object {
public static final Short ERROR = 0x0001;
public void moveTo(int x, int y, int z) {
_ai = null;
log("Should not be called");
if (1 > 5) { // wtf!?
return;
}
}
}
```
### Javascript
``` javascript
function $initHighlight(block, cls) {
try {
if (cls.search(/\bno\-highlight\b/) != -1)
return process(block, true, 0x0F) +
` class="${cls}"`;
} catch (e) {
/* handle exception */
}
for (var i = 0 / 2; i < classes.length; i++) {
if (checkCondition(classes[i]) === undefined)
console.log('undefined');
}
return (
<div>
<web-component>{block}</web-component>
</div>
)
}
export $initHighlight;
```
### JSON
``` json
[
{
"title": "apples",
"count": [12000, 20000],
"description": {"text": "...", "sensitive": false}
},
{
"title": "oranges",
"count": [17500, null],
"description": {"text": "...", "sensitive": false}
}
]
```
### Kotlin
``` kotlin
import kotlinx.serialization.Serializable
import kotlin.random.Random
interface Building
@Serializable
class House(
private val rooms: Int? = 3,
val name: String = "Palace"
) : Building {
var residents: Int = 4
get() {
println("Current residents: $field")
return field
}
fun burn(evacuation: (people: Int) -> Boolean) {
rooms ?: return
if (evacuation((0..residents).random()))
residents = 0
}
}
fun main() {
val house = House(name = "Skyscraper 1")
house.burn {
Random.nextBoolean()
}
}
```
### Lua
``` lua
--[[
Simple signal/slot implementation
]]
local signal_mt = {
__index = {
register = table.insert
}
}
function signal_mt.__index:emit(... --[[ Comment in params ]])
for _, slot in ipairs(self) do
slot(self, ...)
end
end
local function create_signal()
return setmetatable({}, signal_mt)
end
-- Signal test
local signal = create_signal()
signal:register(function(signal, ...)
print(...)
end)
signal:emit('Answer to Life, the Universe, and Everything:', 42)
--[==[ [=[ [[
Nested ]]
multi-line ]=]
comment ]==]
[==[ Nested
[=[ multi-line
[[ string
]] ]=] ]==]
```
### Makefile
``` makefile
# Makefile
BUILDDIR = _build
EXTRAS ?= $(BUILDDIR)/extras
.PHONY: main clean
main:
@echo "Building main facility..."
build_main $(BUILDDIR)
clean:
rm -rf $(BUILDDIR)/*
```
### Perl
``` perl
# loads object
sub load
{
my $flds = $c->db_load($id,@_) || do {
Carp::carp "Can`t load (class: $c, id: $id): '$!'"; return undef
};
my $o = $c->_perl_new();
$id12 = $id / 24 / 3600;
$o->{'ID'} = $id12 + 123;
#$o->{'SHCUT'} = $flds->{'SHCUT'};
my $p = $o->props;
my $vt;
$string =~ m/^sought_text$/;
$items = split //, 'abc';
$string //= "bar";
for my $key (keys %$p)
{
if(${$vt.'::property'}) {
$o->{$key . '_real'} = $flds->{$key};
tie $o->{$key}, 'CMSBuilder::Property', $o, $key;
}
}
$o->save if delete $o->{'_save_after_load'};
# GH-117
my $g = glob("/usr/bin/*");
return $o;
}
__DATA__
@@ layouts/default.html.ep
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body><%= content %></body>
</html>
__END__
=head1 NAME
POD till the end of file
```
### Objective C
``` objectivec
#import <UIKit/UIKit.h>
#import "Dependency.h"
@protocol WorldDataSource
@optional
- (NSString*)worldName;
@required
- (BOOL)allowsToLive;
@end
@property (nonatomic, readonly) NSString *title;
- (IBAction) show;
@end
```
### Rust
``` rust
#[derive(Debug)]
pub enum State {
Start,
Transient,
Closed,
}
impl From<&'a str> for State {
fn from(s: &'a str) -> Self {
match s {
"start" => State::Start,
"closed" => State::Closed,
_ => unreachable!(),
}
}
}
```
### SQL
``` sql
CREATE TABLE "topic" (
"id" integer NOT NULL PRIMARY KEY,
"forum_id" integer NOT NULL,
"subject" varchar(255) NOT NULL
);
ALTER TABLE "topic"
ADD CONSTRAINT forum_id FOREIGN KEY ("forum_id")
REFERENCES "forum" ("id");
-- Initials
insert into "topic" ("forum_id", "subject")
values (2, 'D''artagnian');
```
### Swift
``` swift
import Foundation
@objc class Person: Entity {
var name: String!
var age: Int!
init(name: String, age: Int) {
/* /* ... */ */
}
// Return a descriptive string for this person
func description(offset: Int = 0) -> String {
return "\(name) is \(age + offset) years old"
}
}
```