### Shell Script Example: Starting and Stopping a Server Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/shell/index.html This script shows how to start a server in HTTPS mode and then stop it by finding and killing its process ID. ```shell # start the server in HTTPS mode cd web sudo node ../server.js 443 'yes' >> ../node.log & # here is how to stop the server for pid in `ps aux | grep 'node ../server.js' | awk '{print $2}'` ; do sudo kill -9 $pid 2> /dev/null done exit 0 ``` -------------------------------- ### Kotlin HTTP Server Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/kotlin/index.html A basic Kotlin code example demonstrating the structure of an HTTP server using Netty and Wasabi. This code defines server bootstrap, event loop groups, and methods for starting and stopping the server. ```kotlin package org.wasabi.http import java.util.concurrent.Executors import java.net.InetSocketAddress import org.wasabi.app.AppConfiguration import io.netty.bootstrap.ServerBootstrap import io.netty.channel.nio.NioEventLoopGroup import io.netty.channel.socket.nio.NioServerSocketChannel import org.wasabi.app.AppServer public class HttpServer(private val appServer: AppServer) { val bootstrap: ServerBootstrap val primaryGroup: NioEventLoopGroup val workerGroup: NioEventLoopGroup { // Define worker groups primaryGroup = NioEventLoopGroup() workerGroup = NioEventLoopGroup() // Initialize bootstrap of server bootstrap = ServerBootstrap() bootstrap.group(primaryGroup, workerGroup) bootstrap.channel(javaClass()) bootstrap.childHandler(NettyPipelineInitializer(appServer)) } public fun start(wait: Boolean = true) { val channel = bootstrap.bind(appServer.configuration.port)?.sync()?.channel() if (wait) { channel?.closeFuture()?.sync() } } public fun stop() { // Shutdown all event loops primaryGroup.shutdownGracefully() workerGroup.shutdownGracefully() // Wait till all threads are terminated primaryGroup.terminationFuture().sync() workerGroup.terminationFuture().sync() } } ``` -------------------------------- ### Properties File Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/properties/index.html An example of a typical properties file, demonstrating comments, key-value pairs, multi-line values, and Unicode sequences. ```properties # This is a properties file a.key = A value another.key = http://example.com ! Exclamation mark as comment but.not=Within ! A value # indeed # Spaces at the beginning of a line spaces.before.key=value backslash=Used for multi\ line entries,\ that's convenient. # Unicode sequences unicode.key=This is \u0020 Unicode no.multiline=here # Colons colons : can be used too # Spaces spaces\ in\ keys=Not very common... ``` -------------------------------- ### Install Afterwriting CLI from sources Source: https://github.com/ifrost/afterwriting-labs/blob/master/docs/clients.md Install the Afterwriting CLI from project sources. This involves downloading the sources, navigating to the directory, and running npm install, followed by executing the CLI script. ```bash > cd afterwriting-labs > npm install > node awc.js --help ``` -------------------------------- ### Asterisk Dialplan Configuration Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/asterisk/index.html A comprehensive example of an extensions.conf file, demonstrating various contexts, extensions, and dialplan logic for Asterisk. ```asterisk ; extensions.conf - the Asterisk dial plan ; ; If static is set to no, or omitted, then the pbx_config will rewrite ; this file when extensions are modified. Remember that all comments ; made in the file will be lost when that happens. static=yes #include "/etc/asterisk/additional_general.conf" [iaxprovider] switch => IAX2/user:[key]@myserver/mycontext [dynamic] #exec /usr/bin/dynamic-peers.pl [trunkint] ; ; International long distance through trunk ; exten => _9011.,1,Macro(dundi-e164,${EXTEN:4}) exten => _9011.,n,Dial(${GLOBAL(TRUNK)}/${FILTER(0-9,${EXTEN:${GLOBAL(TRUNKMSD)}})}) [local] ; ; Master context for local, toll-free, and iaxtel calls only ; ignorepat => 9 include => default [demo] include => stdexten ; ; We start with what to do when a call first comes in. ; exten => s,1,Wait(1) ; Wait a second, just for fun same => n,Answer ; Answer the line same => n,Set(TIMEOUT(digit)=5) ; Set Digit Timeout to 5 seconds same => n,Set(TIMEOUT(response)=10) ; Set Response Timeout to 10 seconds same => n(restart),BackGround(demo-congrats) ; Play a congratulatory message same => n(instruct),BackGround(demo-instruct) ; Play some instructions same => n,WaitExten ; Wait for an extension to be dialed. exten => 2,1,BackGround(demo-moreinfo) ; Give some more information. exten => 2,n,Goto(s,instruct) exten => 3,1,Set(LANGUAGE()=fr) ; Set language to french exten => 3,n,Goto(s,restart) ; Start with the congratulations exten => 1000,1,Goto(default,s,1) ; ; We also create an example user, 1234, who is on the console and has ; voicemail, etc. ; exten => 1234,1,Playback(transfer,skip) ; "Please hold while..." ; (but skip if channel is not up) exten => 1234,n,Gosub(${EXTEN},stdexten(${GLOBAL(CONSOLE)})) exten => 1234,n,Goto(default,s,1) ; exited Voicemail exten => 1235,1,Voicemail(1234,u) ; Right to voicemail exten => 1236,1,Dial(Console/dsp) ; Ring forever exten => 1236,n,Voicemail(1234,b) ; Unless busy ; ; # for when they're done with the demo ; exten => #,1,Playback(demo-thanks) ; "Thanks for trying the demo" exten => #,n,Hangup ; Hang them up. ; ; A timeout and "invalid extension rule" ; exten => t,1,Goto(#,1) ; If they take too long, give up exten => i,1,Playback(invalid) ; "That's not valid, try again" ; ; Create an extension, 500, for dialing the ; Asterisk demo. ; exten => 500,1,Playback(demo-abouttotry); Let them know what's going on exten => 500,n,Dial(IAX2/guest@pbx.digium.com/s@default) ; Call the Asterisk demo exten => 500,n,Playback(demo-nogo) ; Couldn't connect to the demo site exten => 500,n,Goto(s,6) ; Return to the start over message. ; ; Create an extension, 600, for evaluating echo latency. ; exten => 600,1,Playback(demo-echotest) ; Let them know what's going on exten => 600,n,Echo ; Do the echo test exten => 600,n,Playback(demo-echodone) ; Let them know it's over exten => 600,n,Goto(s,6) ; Start over ; ; You can use the Macro Page to intercom a individual user exten => 76245,1,Macro(page,SIP/Grandstream1) ; or if your peernames are the same as extensions exten => _7XXX,1,Macro(page,SIP/${EXTEN}) ; ; System Wide Page at extension 7999 ; exten => 7999,1,Set(TIMEOUT(absolute)=60) exten => 7999,2,Page(Local/Grandstream1@page&Local/Xlite1@page&Local/1234@page/n) ; Give voicemail at extension 8500 ; exten => 8500,1,VoicemailMain exten => 8500,n,Goto(s,6) ``` -------------------------------- ### Install Afterwriting CLI using npm Source: https://github.com/ifrost/afterwriting-labs/blob/master/docs/clients.md Install the Afterwriting CLI globally using npm. After installation, you can run the help command to see available options. ```bash > npm install afterwriting -g > afterwriting --help ``` -------------------------------- ### Puppet Class Definition Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/puppet/index.html A comprehensive example of a Puppet class definition for 'automysqlbackup'. It includes parameter declarations, validation, resource creation for files and directories, and conditional package installation. ```puppet # == Class: automysqlbackup # # Puppet module to install AutoMySQLBackup for periodic MySQL backups. # # class { # 'automysqlbackup': # backup_dir => '/mnt/backups', # } class automysqlbackup ( $bin_dir = $automysqlbackup::params::bin_dir, $etc_dir = $automysqlbackup::params::etc_dir, $backup_dir = $automysqlbackup::params::backup_dir, $install_multicore = undef, $config = {}, $config_defaults = {}, ) inherits automysqlbackup::params { # Ensure valid paths are assigned validate_absolute_path($bin_dir) validate_absolute_path($etc_dir) validate_absolute_path($backup_dir) # Create a subdirectory in /etc for config files file { $etc_dir: ensure => directory, owner => 'root', group => 'root', mode => '0750', } # Create an example backup file, useful for reference file { "${etc_dir}/automysqlbackup.conf.example": ensure => file, owner => 'root', group => 'root', mode => '0660', source => 'puppet:///modules/automysqlbackup/automysqlbackup.conf', } # Add files from the developer file { "${etc_dir}/AMB_README": ensure => file, source => 'puppet:///modules/automysqlbackup/AMB_README', } file { "${etc_dir}/AMB_LICENSE": ensure => file, source => 'puppet:///modules/automysqlbackup/AMB_LICENSE', } # Install the actual binary file file { "${bin_dir}/automysqlbackup": ensure => file, owner => 'root', group => 'root', mode => '0755', source => 'puppet:///modules/automysqlbackup/automysqlbackup', } # Create the base backup directory file { $backup_dir: ensure => directory, owner => 'root', group => 'root', mode => '0755', } # If you'd like to keep your config in hiera and pass it to this class if !empty($config) { create_resources('automysqlbackup::backup', $config, $config_defaults) } # If using RedHat family, must have the RPMforge repo's enabled if $install_multicore { package { ['pigz', 'pbzip2']: ensure => installed } } } ``` -------------------------------- ### Installing Prelude Utilities in LiveScript Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/livescript/index.html A meta-function `installPrelude` that adds prelude utilities to a target object if they are not already present. It also marks the prelude as installed. ```livescript # meta export installPrelude = !(target) -> unless target.prelude?isInstalled target <<< out$ # using out$ generated by livescript target <<< target.prelude.isInstalled = true ``` ```livescript export prelude = out$ ``` -------------------------------- ### Cypher Query Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/cypher/index.html An example of a Cypher query syntax highlighting. ```cypher MATCH (joe { name: 'Joe' })-[:knows*2..2]-(friend_of_friend) WHERE NOT (joe)-[:knows]-(friend_of_friend) RETURN friend_of_friend.name, COUNT(*) ORDER BY COUNT(*) DESC , friend_of_friend.name ``` -------------------------------- ### Basic XQuery Syntax Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/xquery/index.html Demonstrates basic XQuery syntax including version declaration, comments, let bindings, and element constructors. ```xquery xquery version "1.0-ml"; (: this is : a "comment" :) let $let := "test"function() $var {function()} {$var} let $joe:=1 return element element { attribute attribute { 1 }, element test { 'a' }, attribute foo { "bar" }, fn:doc() [ foo/@bar eq $let ], //x } (: a more 'evil' test :) (: Modified Blakeley example (: with nested comment :) ... :) ``` -------------------------------- ### D Compile-Time String Formatting Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/d/index.html Demonstrates how to format constants into a string at compile time using the `Format` template. This is analogous to `string.format`. ```d import std.metastrings; import std.stdio; void main() { string s = Format!("Arg %s = %s", "foo", 27); writefln(s); } ``` -------------------------------- ### Cython Syntax Highlighting Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/python/index.html Demonstrates Cython syntax, including C-level type declarations, C-style imports, and Cython decorators. ```cython import numpy as np cimport cython from libc.math cimport sqrt @cython.boundscheck(False) @cython.wraparound(False) def pairwise_cython(double[:, ::1] X): cdef int M = X.shape[0] cdef int N = X.shape[1] cdef double tmp, d cdef double[:, ::1] D = np.empty((M, M), dtype=np.float64) for i in range(M): for j in range(M): d = 0.0 for k in range(N): tmp = X[i, k] - X[j, k] d += tmp * tmp D[i, j] = sqrt(d) return np.asarray(D) ``` -------------------------------- ### Classic PEG.js Grammar Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/pegjs/index.html This is a classic example grammar for PEG.js that recognizes simple arithmetic expressions and computes their value. It defines rules for starting expressions, addition, multiplication, primary expressions (integers or parenthesized expressions), and integers. ```pegjs start = additive additive = left:multiplicative "+" right:additive { return left + right; } multiplicative = left:primary "*" right:multiplicative { return left * right; } primary = integer / "(" additive:additive ")" { return additive; } integer "integer" = digits:[0-9]+ { return parseInt(digits.join(""), 10); } letter = [a-z]+ ``` -------------------------------- ### HTML Mixed Mode Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/htmlmixed/index.html An example of an HTML document with embedded CSS and JavaScript, demonstrating the mixed mode's capabilities. ```html Mixed HTML Example

Mixed HTML Example

``` -------------------------------- ### Markdown Block Code Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/markdown/index.html Demonstrates how to format an entire block of pre-formatted code by indenting lines. ```Markdown If you want your page to validate under XHTML 1.0 Strict, you've got to put paragraph tags in your blockquotes:

For example.

``` -------------------------------- ### Section Header Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/rst/index.html Demonstrates creating a section header by underlining the title with a punctuation character. ```rst ===================== This is a heading ===================== ``` -------------------------------- ### Jinja2 Template Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/jinja2/index.html A sample Jinja2 template demonstrating comments, loops, variable output, conditional logic, includes, and function calls. ```jinja2 {# this is a comment #} {%- for item in li -%}
  • {{ item.label }}
  • {% endfor -%} {{ item.sand == true and item.keyword == false ? 1 : 0 }} {{ app.get(55, 1.2, true) }} {% if app.get('_route') == ('_home') %}home{% endif %} {% if app.session.flashbag.has('message') %} {% for message in app.session.flashbag.get('message') %} {{ message.content }} {% endfor %} {% endif %} {{ path('_home', {'section': app.request.get('section')}) }} {{ path('_home', { 'section': app.request.get('section'), 'boolean': true, 'number': 55.33 }) }} {% include ('test.incl.html.twig') %} ``` -------------------------------- ### Pascal Code Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/pascal/index.html Illustrates basic Pascal control flow structures like while, if-else, for, repeat-until, and case statements. ```pascal while a <> b do writeln('Waiting'); if a > b then writeln('Condition met') else writeln('Condition not met'); for i := 1 to 10 do writeln('Iteration: ', i:1); repeat a := a + 1 until a = 10; case i of 0: write('zero'); 1: write('one'); 2: write('two') end; ``` -------------------------------- ### SQL Syntax Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/sql/index.html Demonstrates various SQL syntax elements supported by the CodeMirror SQL mode, including keywords, identifiers, literals, and comments. ```sql -- SQL Mode for CodeMirror SELECT SQL_NO_CACHE DISTINCT @var1 AS `val1`, @'val2', @global.`sql_mode`, 1.1 AS `float_val`, .14 AS `another_float`, 0.09e3 AS `int_with_esp`, 0xFA5 AS `hex`, x'fa5' AS `hex2`, 0b101 AS `bin`, b'101' AS `bin2`, DATE '1994-01-01' AS `sql_date`, { T "1994-01-01" } AS `odbc_date`, 'my string', _utf8'your string', N'her string', TRUE, FALSE, UNKNOWN FROM DUAL -- space needed after '--' # 1 line comment /* multiline comment! */ LIMIT 1 OFFSET 0; ``` -------------------------------- ### HTTP Request Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/http/index.html An example of an HTTP request that can be highlighted by the HTTP mode. This includes the request line, headers, and a request body. ```http POST /somewhere HTTP/1.1 Host: example.com If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT Content-Type: application/x-www-form-urlencoded; charset=utf-8 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.11 (KHTML, like Gecko) Ubuntu/12.04 Chromium/20.0.1132.47 Chrome/20.0.1132.47 Safari/536.11 This is the request body! ``` -------------------------------- ### reStructuredText Primer Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/rst/index.html An example of a reStructuredText primer, demonstrating basic syntax and structure. ```rst .. This is an excerpt from Sphinx documentation: http://sphinx.pocoo.org/\_sources/rest.txt .. highlightlang:: rest .. \_rst-primer: reStructuredText Primer ======================= This section is a brief introduction to reStructuredText (reST) concepts and syntax, intended to provide authors with enough information to author documents productively. Since reST was designed to be a simple, unobtrusive markup language, this will not take too long. .. seealso:: The authoritative \`reStructuredText User Documentation \` . The "ref" links in this document link to the description of the individual constructs in the reST reference. ``` -------------------------------- ### Octave Syntax Highlighting Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/octave/index.html Demonstrates various Octave syntax elements like numbers, strings, identifiers, operators, and comments. ```octave %numbers [1234 1234i 1234j] [.234 .234j 2.23i] [23e2 12E1j 123D-4 0x234] %strings 'asda''a' "asda""a" %identifiers a + as123 - __asd__ %operators - + = == > < >= <= & ~ ... break zeros default margin round ones rand ceil floor size clear zeros eye mean std cov error eval function abs acos atan asin cos cosh exp log prod sum log10 max min sign sin sinh sqrt tan reshape return case switch else elseif end if otherwise do for while try catch classdef properties events methods global persistent %one line comment %{ multi line commment %} ``` -------------------------------- ### Simple Table Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/rst/index.html Demonstrates the syntax for simple tables in reStructuredText, which are easier to write but have limitations. ```rst ===== ===== ======= A B A and B ===== ===== ======= False False False True False False False True False True True True ===== ===== ======= ``` -------------------------------- ### Example TODO with Debt Markers Source: https://github.com/ifrost/afterwriting-labs/blob/master/docs/adr/002-technical-debt.md Illustrates a TODO comment with debt markers to indicate performance improvement needed. The markers (+++) quantify the debt. ```javascript /** * TODO: Improve performance from O(n^2) to O(n). (+++) */ function foo() { // ... } ``` -------------------------------- ### External Hyperlink Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/rst/index.html Shows how to create inline external hyperlinks with custom link text and a target URL. ```rst `Link text `_ ``` -------------------------------- ### Smalltalk Code Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/smalltalk/index.html A sample Smalltalk code snippet demonstrating a basic Seaside component for a counter. ```smalltalk " This is a test of the Smalltalk code " Seaside.WAComponent subclass: #MyCounter [ | count | MyCounter class >> canBeRoot ^true ] initialize super initialize. count := 0. ] states ^{ self } ] renderContentOn: html html heading: count. html anchor callback: [ count := count + 1 ]; with: '++'. html space. html anchor callback: [ count := count - 1 ]; with: '--'. ] ] ``` -------------------------------- ### RPM Spec File Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/rpm/index.html A complete example of an RPM spec file. This mode is designed for editing .spec files used in RPM package management. ```rpm-spec # # spec file for package minidlna # # Copyright (c) 2011, Sascha Peilicke # # All modifications and additions to the file contributed by third parties # remain the property of their copyright owners, unless otherwise agreed # upon. The license for this file, and modifications and additions to the # file, is the same license as for the pristine package itself (unless the # license for the pristine package is not an Open Source License, in which # case the license is the MIT License). An "Open Source License" is a # license that conforms to the Open Source Definition (Version 1.9) # published by the Open Source Initiative. Name: libupnp6 Version: 1.6.13 Release: 0 Summary: Portable Universal Plug and Play (UPnP) SDK Group: System/Libraries License: BSD-3-Clause Url: http://sourceforge.net/projects/pupnp/ Source0: http://downloads.sourceforge.net/pupnp/libupnp-%{version}.tar.bz2 BuildRoot: %{\_tmppath}/%{name}-%{version}-build %description The portable Universal Plug and Play (UPnP) SDK provides support for building UPnP-compliant control points, devices, and bridges on several operating systems. %package -n libupnp-devel Summary: Portable Universal Plug and Play (UPnP) SDK Group: Development/Libraries/C and C++ Provides: pkgconfig(libupnp) Requires: %{name} = %{version} %description -n libupnp-devel The portable Universal Plug and Play (UPnP) SDK provides support for building UPnP-compliant control points, devices, and bridges on several operating systems. %prep %setup -n libupnp-%{version} %build %configure --disable-static make %{?_smp_mflags} %install %makeinstall find %{buildroot} -type f -name '*.la' -exec rm -f {} ';' %post -p /sbin/ldconfig %postun -p /sbin/ldconfig %files %defattr(-,root,root,-) %doc ChangeLog NEWS README TODO %{\_libdir}/libixml.so.* %{\_libdir}/libthreadutil.so.* %{\_libdir}/libupnp.so.* %files -n libupnp-devel %defattr(-,root,root,-) %{\_libdir}/pkgconfig/libupnp.pc %{\_libdir}/libixml.so %{\_libdir}/libthreadutil.so %{\_libdir}/libupnp.so %{\_includedir}/upnp/ %changelog ``` -------------------------------- ### OCaml: Graphics Triangle Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/mllike/index.html Renders a rotating triangle using the Glut library for OpenGL graphics. ```ocaml let () = ignore( Glut.init Sys.argv ) Glut.initDisplayMode ~double_buffer:true () ignore (Glut.createWindow ~title:"OpenGL Demo") let angle t = 10. *. t *. t let render () = GlClear.clear [ `color ] GlMat.load_identity () GlMat.rotate ~angle:(angle (Sys.time ())) ~z:1. () GlDraw.begins `triangles List.iter GlDraw.vertex2 [-1., -1.; 0., 1.; 1., -1.] GlDraw.ends () Glut.swapBuffers () GlMat.mode `modelview Glut.displayFunc ~cb:render Glut.idleFunc ~cb:(Some Glut.postRedisplay) Glut.mainLoop () ``` -------------------------------- ### Python Syntax Highlighting Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/python/index.html Demonstrates various Python syntax elements including literals, strings, identifiers, operators, delimiters, keywords, and types. ```python # Literals 1234 0.0e101 .123 0b01010011100 0o01234567 0x0987654321abcdef 7 2147483647 3L 79228162514264337593543950336L 0x100000000L 79228162514264337593543950336 0xdeadbeef 3.14j 10.j 10j .001j 1e100j 3.14e-10j # String Literals 'For\'' "God\"" """so loved the world""" '''that he gave his only begotten\' ''' 'that whosoever believeth \ in him' '' # Identifiers __a__ a.b a.b.c # Operators + - * / % & | ^ ~ < > == != <= >= <> << >> // ** and or not in is # Delimiters () [] {} , : ` = ; @ . # Note that @ and . require the proper context. += -= *= /= %= &= |= ^= //= >>= <<= **= # Keywords as assert break class continue def del elif else except finally for from global if import lambda pass raise return try while with yield # Python 2 Keywords (otherwise Identifiers) exec print # Python 3 Keywords (otherwise Identifiers) nonlocal # Types bool classmethod complex dict enumerate float frozenset int list object property reversed set slice staticmethod str super tuple type # Python 2 Types (otherwise Identifiers) basestring buffer file long unicode xrange # Python 3 Types (otherwise Identifiers) bytearray bytes filter map memoryview open range zip # Some Example code import os from package import ParentClass @nonsenseDecorator def doesNothing(): pass class ExampleClass(ParentClass): @staticmethod def example(inputStr): a = list(inputStr) a.reverse() return ''.join(a) def __init__(self, mixin = 'Hello'): self.mixin = mixin ``` -------------------------------- ### Shell Script Example: Cloning Repository and Generating Credentials Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/shell/index.html A shell script demonstrating how to clone a Git repository, generate HTTPS keys, and create a certificate. ```shell #!/bin/bash # clone the repository git clone http://github.com/garden/tree # generate HTTPS credentials cd tree openssl genrsa -aes256 -out https.key 1024 openssl req -new -nodes -key https.key -out https.csr openssl x509 -req -days 365 -in https.csr -signkey https.key -out https.crt cp https.key{,.orig} openssl rsa -in https.key.orig -out https.key ``` -------------------------------- ### XQuery with Complex Element and Try-Catch Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/xquery/index.html Illustrates an XQuery example with nested let bindings, complex element construction, and a try-catch block for error handling. ```xquery let $let := let $let := "let" return element element { attribute attribute { try { xdmp:version() } catch($e) { xdmp:log($e) } }, attribute fn:doc { "bar" castable as xs:string }, element text { text { "text" } }, fn:doc() [ child::eq/(@bar | attribute::attribute) eq $let ], //fn:doc } ``` -------------------------------- ### XML Comment Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/xml/index.html Demonstrates an XML comment within an HTML structure. ```html HTML Example The indentation tries to be somewhat "do what I mean"... but might not match your style. ``` -------------------------------- ### Prime Sieve Example in Go Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/go/index.html This Go code implements the prime sieve algorithm, demonstrating concurrency with channels. It's a direct translation from the Go specification. ```go // Prime Sieve in Go. // Taken from the Go specification. // Copyright © The Go Authors. package main import "fmt" // Send the sequence 2, 3, 4, ... to channel 'ch'. func generate(ch chan<- int) { for i := 2; ; i++ { ch <- i // Send 'i' to channel 'ch' } } // Copy the values from channel 'src' to channel 'dst', // removing those divisible by 'prime'. func filter(src <-chan int, dst chan<- int, prime int) { for i := range src { // Loop over values received from 'src'. if i%prime != 0 { dst <- i // Send 'i' to channel 'dst'. } } } // The prime sieve: Daisy-chain filter processes together. func sieve() { ch := make(chan int) // Create a new channel. go generate(ch) // Start generate() as a subprocess. for { prime := <-ch fmt.Print(prime, "\n") ch1 := make(chan int) go filter(ch, ch1, prime) ch = ch1 } } func main() { sieve() } ``` -------------------------------- ### GFM Task List Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/gfm/index.html Shows the syntax for incomplete and completed task list items in GFM. These are rendered as checkboxes in supported environments. ```markdown - [ ] Incomplete task list item - [x] **Completed** task list item ``` -------------------------------- ### Grid Table Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/rst/index.html Illustrates the syntax for creating a grid table in reStructuredText by manually drawing the cell borders. ```rst +------------------------+------------+----------+----------+ | Header row, column 1 | Header 2 | Header 3 | Header 4 | | (header rows optional) | | | | +========================+============+==========+==========+ | body row 1, column 1 | column 2 | column 3 | column 4 | +------------------------+------------+----------+----------+ | body row 2 | ... | ... | | +------------------------+------------+----------+----------+ ``` -------------------------------- ### mIRC Script Setup Aliases Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/mirc/index.html Defines aliases for controlling join display, maximum stored nicknames, and the AKALogo text. ```mirc alias -l JoinDisplay { return 1 } alias -l MaxNicks { return 20 } alias -l AKALogo { return 06 05A 06K 07A 06 } ``` -------------------------------- ### EJS Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/htmlembedded/index.html Demonstrates the use of EJS (Embedded Javascript) within an HTML context, showing server-side script execution and embedded JavaScript. ```html <% function hello(who) { return "Hello " + who; } %> This is an example of EJS (embedded javascript)

    The program says <%= hello("world") %>.

    ``` -------------------------------- ### Example TOML Document Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/toml/index.html A sample TOML document demonstrating various data types and structures, including strings, integers, dates, arrays, and nested tables. ```toml # This is a TOML document. Boom. title = "TOML Example" [owner] name = "Tom Preston-Werner" organization = "GitHub" bio = "GitHub Cofounder & CEO\nLikes tater tots and beer." dob = 1979-05-27T07:32:00Z # First class dates? Why not? [database] server = "192.168.1.1" ports = [ 8001, 8001, 8002 ] connection_max = 5000 enabled = true [servers] # You can indent as you please. Tabs or spaces. TOML don't care. [servers.alpha] ip = "10.0.0.1" dc = "eqdc10" [servers.beta] ip = "10.0.0.2" dc = "eqdc10" [clients] data = [ ["gamma", "delta"], [1, 2] ] # Line breaks are OK when inside arrays hosts = [ "alpha", "omega" ] ``` -------------------------------- ### C Demo Code Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/clike/index.html Example C code demonstrating the use of zmq and pthread for multithreaded operations. This snippet is intended for use with the C-like mode. ```c /* C demo code */ #include #include #include #include #include #include #include typedef struct { void* arg_socket; zmq_msg_t* arg_msg; char* arg_string; unsigned long arg_len; int arg_int, arg_command; int signal_fd; int pad; void* context; sem_t sem; } acl_zmq_context; #define p(X) (context->arg_##X) void* zmq_thread(void* context_pointer) { acl_zmq_context* context = (acl_zmq_context*)context_pointer; char ok = 'K', err = 'X'; int res; while (1) { while ((res = sem_wait(&context->sem)) == EINTR); if (res) {write(context->signal_fd, &err, 1); goto cleanup;} switch(p(command)) { case 0: goto cleanup; case 1: p(socket) = zmq_socket(context->context, p(int)); break; case 2: p(int) = zmq_close(p(socket)); break; case 3: p(int) = zmq_bind(p(socket), p(string)); break; case 4: p(int) = zmq_connect(p(socket), p(string)); break; case 5: p(int) = zmq_getsockopt(p(socket), p(int), (void*)p(string), &p(len)); break; case 6: p(int) = zmq_setsockopt(p(socket), p(int), (void*)p(string), p(len)); break; case 7: p(int) = zmq_send(p(socket), p(msg), p(int)); break; case 8: p(int) = zmq_recv(p(socket), p(msg), p(int)); break; case 9: p(int) = zmq_poll(p(socket), p(int), p(len)); break; } p(command) = errno; write(context->signal_fd, &ok, 1); } cleanup: close(context->signal_fd); free(context_pointer); return 0; } void* zmq_thread_init(void* zmq_context, int signal_fd) { acl_zmq_context* context = malloc(sizeof(acl_zmq_context)); pthread_t thread; context->context = zmq_context; context->signal_fd = signal_fd; sem_init(&context->sem, 1, 0); pthread_create(&thread, 0, &zmq_thread, context); pthread_detach(thread); return context; } ``` -------------------------------- ### TypeScript Class and Button Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/javascript/typescript.html Demonstrates a basic TypeScript class and its usage to create an interactive button in a web page. ```typescript class Greeter { greeting: string; constructor (message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; } } var greeter = new Greeter("world"); var button = document.createElement('button') button.innerText = "Say Hello" button.onclick = function() { alert(greeter.greet()) } document.body.appendChild(button) ``` -------------------------------- ### JSON-LD Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/javascript/json-ld.html A sample JSON-LD object representing the Empire State Building, used to demonstrate the syntax highlighting capabilities of the mode. ```json { "@context": { "name": "http://schema.org/name", "description": "http://schema.org/description", "image": { "@id": "http://schema.org/image", "@type": "@id" }, "geo": "http://schema.org/geo", "latitude": { "@id": "http://schema.org/latitude", "@type": "xsd:float" }, "longitude": { "@id": "http://schema.org/longitude", "@type": "xsd:float" }, "xsd": "http://www.w3.org/2001/XMLSchema#" }, "name": "The Empire State Building", "description": "The Empire State Building is a 102-story landmark in New York City.", "image": "http://www.civil.usherbrooke.ca/cours/gci215a/empire-state-building.jpg", "geo": { "latitude": "40.75", "longitude": "73.98" } } ``` -------------------------------- ### Hxml Configuration Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/haxe/index.html Shows common Hxml compiler options for configuring the Haxe build process, including library paths, output targets, and conditional compilation flags. ```hxml -cp test -js path/to/file.js #-remap nme:flash --next -D source-map-content -cmd 'test' -lib lime ``` -------------------------------- ### Sass Mode Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/sass/index.html This snippet demonstrates how to initialize a CodeMirror editor for Sass files. It uses the `fromTextArea` method and configures line numbers and bracket matching. ```javascript var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers : true, matchBrackets : true }); ``` -------------------------------- ### Snippet Replacement Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/docs/clients.md Shows the resulting text after snippets defined in the configuration have been replaced within the Fountain script. This illustrates dynamic content insertion. ```text INT. ROOM - DAY BOND enters the room. Dr. Julius No attacks him. DR. JULIUS NO Aaaaa! James Bond kills Dr. Julius No. BOND My name is Bond, James Bond. ``` -------------------------------- ### Explicit Markup Block Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/rst/index.html Illustrates the basic structure of an explicit markup block, which starts with '.. ' and is terminated by indentation. ```rst .. _directives: Directives ---------- A directive (:duref:`ref `) is a generic block of explicit markup. ``` -------------------------------- ### SCSS Example Code Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/css/scss.html This is a sample SCSS code block demonstrating various SCSS features like variables, nesting, mixins, and extends. ```scss /* Some example SCSS */ @import "compass/css3"; $variable: #333; $blue: #3bbfce; $margin: 16px; .content-navigation { #nested { background-color: black; } border-color: $blue; color: darken($blue, 9%); } .border { padding: $margin / 2; margin: $margin / 2; border-color: $blue; } @mixin table-base { th { text-align: center; font-weight: bold; } td, th {padding: 2px} } table.hl { margin: 2em 0; td.ln { text-align: right; } } li { font: { family: serif; weight: bold; size: 1.2em; } } @mixin left($dist) { float: left; margin-left: $dist; } #data { @include left(10px); @include table-base; } .source { @include flow-into(target); border: 10px solid green; margin: 20px; width: 200px; } .new-container { @include flow-from(target); border: 10px solid red; margin: 20px; width: 200px; } body { margin: 0; padding: 3em 6em; font-family: tahoma, arial, sans-serif; color: #000; } @mixin yellow() { background: yellow; } .big { font-size: 14px; } .nested { @include border-radius(3px); @extend .big; p { background: whitesmoke; a { color: red; } } } #navigation a { font-weight: bold; text-decoration: none !important; } h1 { font-size: 2.5em; } h2 { font-size: 1.7em; } h1:before, h2:before { content: "::"; } code { font-family: courier, monospace; font-size: 80%; color: #418A8A; } ``` -------------------------------- ### Turtle RDF Data Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/turtle/index.html An example of Turtle syntax used for RDF data. This format is used for representing linked data. ```turtle @prefix foaf: . @prefix geo: . @prefix rdf: . a foaf:Person; foaf:interest ; foaf:based_near [ geo:lat "34.0736111" ; geo:lon "-118.3994444" ] ``` -------------------------------- ### Erlang Mode Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/erlang/index.html Demonstrates how to initialize a CodeMirror editor for Erlang code. It includes common settings like line numbers, bracket matching, auto-indentation on tab, and a specific theme. ```javascript var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, matchBrackets: true, extraKeys: {"Tab": "indentAuto"}, theme: "erlang-dark" }); ``` -------------------------------- ### Haskell Mode Initialization Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/haskell/index.html Initializes a CodeMirror editor for Haskell code. This example demonstrates enabling line numbers, bracket matching, and applying an 'elegant' theme. ```javascript var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, matchBrackets: true, theme: "elegant" }); ``` -------------------------------- ### Haxe Code Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/haxe/index.html Demonstrates Haxe syntax highlighting, including imports, attributes, classes, generics, functions, loops, conditional statements, comments, and type casting. ```haxe import one.two.Three; @attr("test") class Foo extends Three { public function new() { noFoo = 12; } public static inline function doFoo(obj:{k:Int, l:Float}):Int { for(i in 0...10) { obj.k++; trace(i); var var1 = new Array(); if(var1.length > 1) throw "Error"; } // The following line should not be colored, the variable is scoped out var1; /* Multi line * Comment test */ return obj.k; } private function bar():Void { #if flash var t1:String = "1.21"; #end try { doFoo({k:3, l:1.2}); } catch (e : String) { trace(e); } var t2:Float = cast(3.2); var t3:haxe.Timer = new haxe.Timer(); var t4 = {k:Std.int(t2), l:Std.parseFloat(t1)}; var t5 = ~/123+.*$/i; doFoo(t4); untyped t1 = 4; bob = new Foo } public var okFoo(default, never):Float; var noFoo(getFoo, null):Int; function getFoo():Int { return noFoo; } public var three:Int; } enum Color { red; green; blue; grey( v : Int ); rgb (r:Int,g:Int,b:Int); } ``` -------------------------------- ### Lua Syntax Highlighting Example Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/lua/index.html Demonstrates basic Lua syntax, including multi-line and single-line comments, function definitions, variable declarations, conditional statements, and hexadecimal literals. This is primarily for showcasing syntax highlighting. ```lua --[[ example useless code to show lua syntax highlighting this is multiline comment ]] function blahblahblah(x) local table = { "asd" = 123, "x" = 0.34, } if x ~= 3 then print( x ) elseif x == "string" my_custom_function( 0x34 ) else unknown_function( "some string" ) end --single line comment end function blablabla3() for k,v in ipairs( table ) do --abcde.. y=[[ x=[[ x is a multi line string ]] but its definition is iside a highest level string! ]=] print(" \"\" ") s = math.sin( x ) end end ``` -------------------------------- ### Initialize CodeMirror with HAML Mode Source: https://github.com/ifrost/afterwriting-labs/blob/master/js/libs/codemirror/mode/haml/index.html Demonstrates how to create a CodeMirror instance for HAML code. Ensure the HAML mode is loaded before initializing. ```javascript var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, mode: "text/x-haml" }); ```