polyglot-readme
Lots of programming language snippets together in a single README. Good for testing syntax highlighting themes.
bash
#!/bin/bash ###### BEGIN CONFIG ACCEPTED_HOSTS="/root/.hag_accepted.conf"BE_VERBOSE=false###### END CONFIG host_root="${APACHE_HOME_DIR}$1/$2/$(title)" echo -e "# Host $1/$2 :"}
clojure
; Comment
coffeescript
= student=if b? then 7 else 6messages="A": "Excellent" -> if studentexcellentWork "A+" else if studentokayStuff if studenttriedHard then "B" else "B-" else "C" = x * x = -> 2 math = root: Mathsqrt square: square : x * square x = print winnerrunners : : alert @name + " moved m." hi = ` { return documenttitle "Hello JavaScript";}` heredoc = """CoffeeScript subst test """ ###CoffeeScript Compiler v1.2.0Released under the MIT License### OPERATOR = /// ^ ///
cpp
int
css
{} ;
dart
/** * Class description and [link](http://dartlang.org/). */@Awesome('it works!')class SomeClass<S extends Iterable> extends BaseClass<S> implements Comparable { factory SomeClass(num param); SomeClass._internal(int q) : super() { assert(q != 1); double z = 0.0; } /// **Sum** function int sum(int a, int b) => a + b; ElementList els() => querySelectorAll('.dart');} String str = ' (${'parameter' + 'zxc'})';String str = " (${true ? 2 + 2 / 2 : null})";String str = r'\nraw\';String str = r"\nraw\";var str = '''Something ${2+3}''';var str = r"""Something ${2+3}""";
glsl
// vertex shader #version 150in vec2 in_Position;in vec3 in_Color; out vec3 ex_Color;void // geometry shader #version 150 void // fragment shader #version 150precision highp float; in vec3 ex_Color;out vec4 gl_FragColor; void
erlang
%% backwards compatibility . %% state
go
package main import ( "fmt" "os") const ( Sunday = iota numberOfDays // this constant is not exported) type Foo interface { FooFunc(int, float32) (complex128, []int)} type Bar struct { os.File /* multi-line comment */ PublicData chan int} func main() { ch := make(chan int) ch <- 1 x, ok := <- ch ok = true float_var := 1.0e10 defer fmt.Println('\'') defer fmt.Println(`exitting now\`) var fv1 float64 = 0.75 go println(len("hello world!")) return}
handlebars
<h3>Hours</h3> <ul> {{#each content.users}} <li {{bindAttr hello="world"}}>{{firstName}}</li> {{/each}}</ul>
haskell
{-# LANGUAGE TypeSynonymInstances #-}module Network.UDP( DataPacket(..), openBoundUDPPort, openListeningUDPPort, pingUDPPort, sendUDPPacketTo, recvUDPPacket, recvUDPPacketFrom) where import qualified Data.ByteString as Strict (ByteString, concat, singleton)import qualified Data.ByteString.Lazy as Lazy (ByteString, toChunks, fromChunks)import Data.ByteString.Char8 (pack, unpack)import Network.Socket hiding (sendTo, recv, recvFrom)import Network.Socket.ByteString (sendTo, recv, recvFrom) -- Type class for converting StringLike types to and from strict ByteStringsclass DataPacket a where toStrictBS :: a -> Strict.ByteString fromStrictBS :: Strict.ByteString -> a instance DataPacket Strict.ByteString where toStrictBS = id {-# INLINE toStrictBS #-} fromStrictBS = id {-# INLINE fromStrictBS #-} openBoundUDPPort :: String -> Int -> IO SocketopenBoundUDPPort uri port = do s <- getUDPSocket bindAddr <- inet_addr uri let a = SockAddrInet (toEnum port) bindAddr bindSocket s a return s pingUDPPort :: Socket -> SockAddr -> IO ()pingUDPPort s a = sendTo s (Strict.singleton 0) a >> return ()
haxe
// quicksort example from http://haxe.org/doc/snip/quicksortclass Quicksort { static var arr = [4,8,0,3,9,1,5,2,6,7]; static function quicksort( lo : Int, hi : Int ) : Void { var i = lo; var j = hi; var buf = arr; var p = buf[ while( i <= j ) { while( arr[i] > p ) i++; while( arr[j] < p ) j--; if( i <= j ) { var t = buf[i]; buf[i++] = buf[j]; buf[j--] = t; } } if( lo < j ) quicksort( lo, j ); if( i < hi ) quicksort( i, hi ); } static function main() { quicksort( 0, arr); trace }}
http
POST /task?id=1 HTTP/1.1Host: example.orgContent-Type: application/json; charset=utf-8Content-Length: 19 {"status": "ok", "extended": true}
ini
;Settings relating to the location and loading of the database [Database]ProfileDir=.ShowProfileMgr=smartProfile1_Name[] = "\|/_-=MegaDestoyer=-_\|/"DefaultProfile=TrueAutoCreate = no [AutoExec]use-prompt="prompt"Glob=autoexec_*.iniAskAboutIgnoredPlugins=0
json
javascript
{ try if blockclassName != -1 return + ' class=""'; catch e /* handle exception */ var e4x = <div>Example <p>1234</p></div>; for var i = 0 / 2; i < classeslength; i++ // "0 / 2" should not be parsed as regexp if === undefined return /\d+[\s/]/g; console;}
less
/*Using the most minimal language subset to ensure wehave enough relevance hints for proper Less detection*/ "fruits"; @rhythm: 1.5em; screen and min-resolution: 2dppx body font-size: 125% section > .foo + :hover margin: @rhythm 0 0 @rhythm; padding: calc5% + 20px; background: #f00ba7 url(http://placehold.alpha-centauri/42.png) no-repeat; background-image: linear-gradient-135deg, wheat, fuchsia !important ; background-blend-mode: multiply; font-family: /* ? */ 'Omega'; src: url('../fonts/omega-webfont.woff?v=2.0.2'); .icon-baz::before display: inline-block; font-family: "Omega", Alpha, sans-serif; content: "\f085"; color: rgba98, 76 /* or 54 */, 231, .75;
lisp
#!/usr/bin/env csi (defun prompt-for-cd () "Prompts for CD" (prompt-read "Title" 1.53 1 2/4 1.7 1.7e0 2.9E-4 +42 -7 #b001 #b001/100 #o777 #O777 #xabc55 #c(0 -5.6)) (prompt-read "Artist" &rest) (or (parse-integer (prompt-read "Rating") :junk-allowed t) 0) (if x (format t "yes") (format t "no" nil) ;and here comment ) ;; second line comment '(+ 1 2) (defvar *lines*) ; list of all lines (position-if-not #'sys::whitespacep line :start beg)) (quote (privet 1 2 3)) '(hello world) (* 5 7) (1 2 34 5) (:use "aaaa") (let ((x 10) (y 20)) (print (+ x y)) )
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, ...) endendlocal function create_signal() return setmetatable({}, signal_mt)end -- Signal testlocal 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 BUILDDIR = _build EXTRAS ?= $(BUILDDIR)/extras @echo "Building main facility..." build_main $(BUILDDIR) rm -rf $(BUILDDIR)/*
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!
nginx
user www www;worker_processes 2;pid /var/run/nginx.pid;error_log /var/log/nginx.error_log debug | info | notice | warn | error | crit; events { connections 2000; use kqueue | rtsig | epoll | /dev/poll | select | poll;} http { log_format main '$remote_addr - $remote_user [$time_local] ' '"$request" $status $bytes_sent ' '"$http_referer" "$http_user_agent" ' '"$gzip_ratio"'; send_timeout 3m; client_header_buffer_size 1k; gzip on; gzip_min_length 1100; #lingering_time 30; server { server_name one.example.com www.one.example.com; access_log /var/log/nginx.access_log main; rewrite (.*) /index.php?page=$1 break; location / { proxy_pass http://127.0.0.1/; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; charset koi8-r; } location /api/ { fastcgi_pass 127.0.0.1:9000; } location ~* \.(jpg|jpeg|gif)$ { root /spool/www; } }}
python
r'''A docstring''' if param1 > param2: # interesting print 'Gre\'ater' return (param2 - param1 + 1 + 0b10l) or None pass >>> message = '''interpreter... prompt'''
rust
use std; /* Factorial */fn fac(n: int) -> int { let s: str = "This isa multi-line string. It ends with an unescaped '\"'."; let c: char = 'Ф'; let r: str = r##" raw string "##; let result = 1, i = 1; while i <= n { // No parens around the condition result *= i; i += 1; } ret result;} pure fn pure_length(ls: list) -> uint { /* ... */ } type t = map::hashtbl;let x = id::(10); // Define some modules.mod foo; impl Seq for [T] { fn len() -> uint { vec::len(self) } fn iter(b: fn(T)) { for elt in self { b(elt); } }} enum list { Nil; Cons(T, @list<T>);} let a: list<int> = Cons(7, @cons(13, @nil)); struct Baz { baz: &'a str,} 'h: for i in range(0,10) { 'g: loop { if i % 2 == 0 { continue 'h; } if i == 9 { break 'h; } break 'g; }}
scala
case class Person(name: String, age: Int) def absoluteValue(n: Int): Int = if (n < 0) -n else n val hux = "hux"def mux = "mux"def qux: String = "qux" type ξ[A] = (A, A) trait Hist { lhs => def ⊕(rhs: Hist): Hist} def gsum[A: Ring](as: Seq[A]): A = as.foldLeft(Ring[A].zero)(_ + _) sealed trait Compasscase object North extends Compasscase object South extends Compasscase object East extends Compasscase object West extends Compass trait Cake { type T; val things: Seq[T] abstract class Spindler def spindle(s: Spindler, ts: Seq[T], reversed: Boolean = false): Seq[T]} val colors = Map( "red" -> 0xFF0000, "turquoise" -> 0x00FFFF, "black" -> 0x000000, "orange" -> 0xFF8040, "brown" -> 0x804000) lazy val ns = for { x <- 0 until 100 y <- 0 until 100} yield (x + y) * 33.33
scss
; // variables ;; // mixins with parameters button div,.navbar,#header,input .row-12 > // nested definitions ul .banner a
sql
BEGIN; ( -- This is the greatest table of all time "id" serial NOT NULL PRIMARY KEY, "forum_id" integer NOT NULL, "subject" varchar(255) NOT NULL -- Because nobody likes an empty subject );"topic" ADD CONSTRAINT forum_id FOREIGN KEY ("forum_id") REFERENCES "forum" ("id"); -- Initials insert into "topic" ("forum_id", "subject") values (2, 'D''artagnian'); select /* comment */ count(*) from cicero_forum; -- this line lacks ; at the end to allow people to be sloppy and omit it in one-liners /*but who cares?*/COMMIT
stylus
@import "nib" // variables$green = #008000$green_dark = $green, 10) // mixin/function) max-width 980px // mixin/function with parameters$color = green) if $color == green background-color #008000 else if $color == red background-color #B22222 button red) #content, .content font Tahoma, Chunkfive, sans-serif background 'hatch.png') color #F0F0F0 !important width 100%
swift
extension MyClass : Interface { class func unarchiveFromFile<A>(file : A, (Int,Int) -> B) -> SKNode? { let path: String = bundle.pathForResource(file, ofType: "file\(name + 5).txt") let funnyNumber = 3 + 0xC2.15p2 * (1_000_000.000_000_1 - 000123.456) + 0o21 var sceneData = NSData.dataWithContentsOfFile(path, options: .DataReadingMappedIfSafe, error: nil) /* a comment /* with a nested comment */ and the end */ } @objc override func shouldAutorotate() { return true }}
typescript
; declare magicNumber number; myArray.forEach;
xml
Ok <![CDATA[ CDATA is <not> magical. ]]> Title body {width: 500px;} function $init() {return true;} Title <!-- here goes the rest of the page -->
Ruby
describe RubyBox::File do it "should use missing_method to expose files fields" do file = RubyBox::File.new(@session, @mini_file) file.id.should == '2631999573' end it "should load all meta information if reload_meta is called" do # request is called once when reload_meta is automatically executed. RubyBox::Session.any_instance.should_receive(:request).once.and_return(@full_file) session = RubyBox::Session.new file = RubyBox::File.new(session, @mini_file) file.size.should == 629644 endend
erb