简书支持语法高亮的常用语言
语言名 | 关键字 |
---|---|
Bash | bash |
CoffeeScript | coffeescript |
C++ | cpp |
C# | cs |
CSS | css |
Diff | diff |
HTTP | http |
Ini | ini |
Java | java |
JavaScript | javascript |
JSON | json |
Makefile | makefile |
Markdown | markdown |
Objective-C | objectivec |
Perl | perl |
Python | python |
Ruby | ruby |
SQL | sql |
XML | xml |
ARM汇编 | armasm |
AVR汇编 | avrasm |
MIPS汇编 | mipsasm |
x86汇编 | x86asm |
Elixir | elixir |
Elm | elm |
Erlang | erlang |
F# | fsharp |
Haskell | haskell |
GLSL | glsl |
Clojure | clojure |
Lisp | lisp |
Bash
例:
###### BEGIN CONFIG
ACCEPTED_HOSTS="/root/.hag_accepted.conf"
BE_VERBOSE=false
###### END CONFIG
if [ "$UID" -ne 0 ]
then
echo "Superuser rights is required"
echo 'Printing the # sign'
exit 2
fi
if test $# -eq 0
then
elif test [ $1 == 'start' ]
else
fi
genApacheConf(){
if [[ "$2" = "www" ]]
then
full_domain=$1
else
full_domain=$2.$1
fi
host_root="${APACHE_HOME_DIR}$1/$2/$(title)"
echo -e "# Host $1/$2 :"
}
CoffeeScript
grade = (student, period=(if b? then 7 else 6), messages={"A": "Excellent"}) ->
if student.excellentWork
"A+"
else if student.okayStuff
if student.triedHard then "B" else "B-"
else
"C"
square = (x) -> x * x
two = -> 2
math =
root: Math.sqrt
square: square
cube: (x) -> x * square x
race = (winner, runners...) ->
print winner, runners
class Animal extends Being
constructor: (@name) ->
move: (meters) ->
alert @name + " moved #{meters}m."
hi = `function() {
return [document.title, "Hello JavaScript"].join(": ");
}`
heredoc = """
CoffeeScript subst test #{ 010 + 0xf / 0b10 + "nested string #{ /\n/ }"}
"""
###
CoffeeScript Compiler v1.2.0
Released under the MIT License
###
OPERATOR = /// ^ (
?: [-=]> # function
) ///
C++
#include <iostream>
#define IABS(x) ((x) < 0 ? -(x) : (x))
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;
}
C#
using System;
#pragma warning disable 414, 3021
public class Program
{
/// <summary>The entry point to the program.</summary>
public static int Main(string[] args)
{
Console.WriteLine("Hello, World!");
string s = @"This
""string""
spans
multiple
lines!";
dynamic x = new ExpandoObject();
x.MyProperty = 2;
return 0;
}
}
async Task<int> AccessTheWebAsync()
{
// ...
string urlContents = await getStringTask;
return urlContents.Length;
}
internal static void ExceptionFilters()
{
try
{
throw new Exception();
}
catch (Exception e) when (e.Message == "My error") { }
}
CSS
@media screen and (-webkit-min-device-pixel-ratio: 0) {
body:first-of-type pre::after {
content: 'highlight: ' attr(class);
}
body {
background: linear-gradient(45deg, blue, red);
}
}
@import url('print.css');
@page:right {
margin: 1cm 2cm 1.3cm 4cm;
}
@font-face {
font-family: Chunkfive; src: url('Chunkfive.otf');
}
div.text,
#content,
li[lang=ru] {
font: Tahoma, Chunkfive, sans-serif;
background: url('hatch.png') /* wtf? */; color: #F0F0F0 !important;
width: 100%;
}
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
HTTP
POST /task?id=1 HTTP/1.1
Host: example.org
Content-Type: application/json; charset=utf-8
Content-Length: 19
{"status": "ok", "extended": true}
Ini
; boilerplate
[package]
name = "some_name"
authors = ["Author"]
description = "This is \
a description"
[[lib]]
name = ${NAME}
default = True
auto = no
counter = 1_000
Java
/**
* @author John Smith <john.smith@example.com>
* @version 1.0
*/
package l2f.gameserver.model;
import java.util.ArrayList;
public abstract class L2Character extends L2Object {
public static final Short ABNORMAL_EFFECT_BLEEDING = 0x0_0_0_1; // not sure
public void moveTo(int x, int y, int z) {
_ai = null;
_log.warning("Should not be called");
if (1 > 5) {
return;
}
}
/** Task of AI notification */
@SuppressWarnings( { "nls", "unqualified-field-access", "boxing" })
public class NotifyAITask implements Runnable {
private final CtrlEvent _evt;
List<String> mList = new ArrayList<String>()
public void run() {
try {
getAI().notifyEvent(_evt, _evt.class, null);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
JavaScript
import {x, y} as p from 'point';
const ANSWER = 42;
class Car extends Vehicle {
constructor(speed, cost) {
super(speed);
var c = Symbol('cost');
this[c] = cost;
this.intro = `This is a car runs at
${speed}.`;
}
}
for (let num of [1, 2, 3]) {
console.log(num + 0b111110111);
}
function $initHighlight(block, flags) {
try {
if (block.className.search(/\bno\-highlight\b/) != -1)
return processBlock(block.function, true, 0x0F) + ' class=""';
} catch (e) {
/* handle exception */
var e4x =
<div>Example
<p>1234</p></div>;
}
for (var i = 0 / 2; i < classes.length; i++) { // "0 / 2" should not be parsed as regexp
if (checkCondition(classes[i]) === undefined)
return /\d+[\s/]/g;
}
console.log(Array.every(classes, Boolean));
}
export $initHighlight;
JSON
[
{
"title": "apples",
"count": [12000, 20000],
"description": {"text": "...", "sensitive": false}
},
{
"title": "oranges",
"count": [17500, null],
"description": {"text": "...", "sensitive": false}
}
]
Makefile
# Makefile
BUILDDIR = _build
EXTRAS ?= $(BUILDDIR)/extras
.PHONY: main clean
main:
@echo "Building main facility..."
build_main $(BUILDDIR)
clean:
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!
Objective-C
#import <UIKit/UIKit.h>
#import "Dependency.h"
@protocol WorldDataSource
@optional
- (NSString*)worldName;
@required
- (BOOL)allowsToLive;
@end
@interface Test : NSObject <HelloDelegate, WorldDataSource> {
NSString *_greeting;
}
@property (nonatomic, readonly) NSString *greeting;
- (IBAction) show;
@end
@implementation Test
@synthesize test=_test;
+ (id) test {
return [self testWithGreeting:@"Hello, world!\nFoo bar!"];
}
+ (id) testWithGreeting:(NSString*)greeting {
return [[[self alloc] initWithGreeting:greeting] autorelease];
}
- (id) initWithGreeting:(NSString*)greeting {
if ( (self = [super init]) ) {
_greeting = [greeting retain];
}
return self;
}
- (void) dealloc {
[_greeting release];
[super dealloc];
}
@end
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
PHP
require_once 'Zend/Uri/Http.php';
namespace Location\Web;
interface Factory
{
static function _factory();
}
abstract class URI extends BaseURI implements Factory
{
abstract function test();
public static $st1 = 1;
const ME = "Yo";
var $list = NULL;
private $var;
/**
* Returns a URI
*
* @return URI
*/
static public function _factory($stats = array(), $uri = 'http')
{
echo __METHOD__;
$uri = explode(':', $uri, 0b10);
$schemeSpecific = isset($uri[1]) ? $uri[1] : '';
$desc = 'Multi
line description';
// Security check
if (!ctype_alnum($scheme)) {
throw new Zend_Uri_Exception('Illegal scheme');
}
$this->var = 0 - self::$st;
$this->list = list(Array("1"=> 2, 2=>self::ME, 3 => \Location\Web\URI::class));
return [
'uri' => $uri,
'value' => null,
];
}
}
echo URI::ME . URI::$st1;
__halt_compiler () ; datahere
datahere
datahere */
datahere
Python
@requires_authorization
def somefunc(param1='', param2=0):
r'''A docstring'''
if param1 > param2: # interesting
print 'Gre\'ater'
return (param2 - param1 + 1 + 0b10l) or None
class SomeClass:
pass
>>> message = '''interpreter
... prompt'''
Ruby
class A < B; def self.create(object = User) object end end
class Zebra; def inspect; "X#{2 + self.object_id}" end end
module ABC::DEF
include Comparable
# @param test
# @return [String] nothing
def foo(test)
Thread.new do |blockvar|
ABC::DEF.reverse(:a_symbol, :'a symbol', :<=>, 'test' + ?\012)
answer = valid?4 && valid?CONST && ?A && ?A.ord
end.join
end
def [](index) self[index] end
def ==(other) other == self end
end
class Car < ActiveRecord::Base
has_many :wheels, class_name: 'Wheel', foreign_key: 'car_id'
scope :available, -> { where(available: true) }
end
hash = {1 => 'one', 2 => 'two'}
2.0.0p0 :001 > ['some']
=> ["some"]
SQL
BEGIN;
CREATE TABLE "topic" (
-- 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
);
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');
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
XML
<?xml version="1.0"?>
<response value="ok" xml:lang="en">
<text>Ok</text>
<comment html_allowed="true"/>
<ns1:description><![CDATA[
CDATA is <not> magical.
]]></ns1:description>
<a></a> <a/>
</response>
<!DOCTYPE html>
<title>Title</title>
<style>body {width: 500px;}</style>
<script type="application/javascript">
function $init() {return true;}
</script>
<body>
<p checked class="title" id='title'>Title</p>
<!-- here goes the rest of the page -->
</body>
ARM Assembly
.text
.global connect
connect:
mov r3, #2 ; s->sin_family = AF_INET
strh r3, [sp]
ldr r3, =server_port ; s->sin_port = server_port
ldr r3, [r3]
strh r3, [sp, #2]
ldr r3, =server_addr ; s->sin_addr = server_addr
ldr r3, [r3]
str r3, [sp, #4]
mov r3, #0 ; bzero(&s->sin_zero)
str r3, [sp, #8]
str r3, [sp, #12]
mov r1, sp ; const struct sockaddr *addr = sp
ldr r7, =connect_call
ldr r7, [r7]
swi #0
add sp, sp, #16
pop {r0} ; pop sockfd
pop {r7}
pop {fp, ip, lr}
mov sp, ip
bx lr
.data
socket_call: .long 281
connect_call: .long 283
/* all addresses are network byte-order (big-endian) */
server_addr: .long 0x0100007f ; localhost
server_port: .hword 0x0b1a
AVR汇编
;* Title: Block Copy Routines
;* Version: 1.1
.include "8515def.inc"
rjmp RESET ;reset handle
.def flashsize=r16 ;size of block to be copied
flash2ram:
lpm ;get constant
st Y+,r0 ;store in SRAM and increment Y-pointer
adiw ZL,1 ;increment Z-pointer
dec flashsize
brne flash2ram ;if not end of table, loop more
ret
.def ramtemp =r1 ;temporary storage register
.def ramsize =r16 ;size of block to be copied
MIPS汇编
.text
.global AckermannFunc
# Preconditions:
# 1st parameter ($a0) m
# 2nd parameter ($a1) n
# Postconditions:
# result in ($v0) = value of A(m,n)
AckermannFunc:
addi $sp, $sp, -8
sw $s0, 4($sp)
sw $ra, 0($sp)
# move the parameter registers to temporary - no, only when nec.
LABEL_IF: bne $a0, $zero, LABEL_ELSE_IF
addi $v0, $a1, 1
# jump to LABEL_DONE
j LABEL_DONE
x86汇编
section .text
extern _MessageBoxA@16
%if __NASM_VERSION_ID__ >= 0x02030000
safeseh handler ; register handler as "safe handler"
%endif
handler:
push dword 1 ; MB_OKCANCEL
push dword caption
push dword text
push dword 0
call _MessageBoxA@16
sub eax,1 ; incidentally suits as return value
; for exception handler
ret
global _main
_main: push dword handler
push dword [fs:0]
mov dword [fs:0], esp
xor eax,eax
mov eax, dword[eax] ; cause exception
pop dword [fs:0] ; disengage exception handler
add esp, 4
ret
avx2: vzeroupper
push rbx
mov rbx, rsp
sub rsp, 0h20
vmovdqa ymm0, [rcx]
vpaddb ymm0, [rdx]
leave
ret
text: db 'OK to rethrow, CANCEL to generate core dump',0
caption:db 'SEGV',0
section .drectve info
db '/defaultlib:user32.lib /defaultlib:msvcrt.lib '
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
defmodule ListServer do
@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
pid <- {:foo, "bar"}
greeter = fn(x) -> IO.puts "hey #{x}" end
greeter.("Bob")
Elm
module Examples.Hello (main, Point, Tree(..)) where
import Html exposing (Html, span, text)
import Html.Attributes exposing (..)
import Time
main : Html
main =
span [class "welcome-message"] [text "Hello, World!"]
type alias Point = { x : Int, y : Int }
type Tree a = Leaf a | Node (Tree a) a (Tree a)
flatten : Tree a -> List a
flatten t =
case t of
Leaf a -> [a]
Node l a r -> flatten l ++ a :: flatten r
-- outgoing values
port time : Signal Float
port time = Time.every 1000
Erlang
-module(ssh_cli).
-behaviour(ssh_channel).
-include("ssh.hrl").
%% backwards compatibility
-export([listen/1, listen/2, listen/3, listen/4, stop/1]).
if L =/= [] -> % If L is not empty
sum(L) / count(L);
true ->
error
end.
%% state
-record(state, {
cm,
channel
}).
-spec foo(integer()) -> integer().
foo(X) -> 1 + X.
test(Foo)->Foo.
init([Shell, Exec]) ->
{ok, #state{shell = Shell, exec = Exec}};
init([Shell]) ->
false = not true,
io:format("Hello, \"~p!~n", [atom_to_list('World')]),
{ok, #state{shell = Shell}}.
concat([Single]) -> Single;
concat(RList) ->
EpsilonFree = lists:filter(
fun (Element) ->
case Element of
epsilon -> false;
_ -> true
end
end,
RList),
case EpsilonFree of
[Single] -> Single;
Other -> {concat, Other}
end.
union_dot_union({union, _}=U1, {union, _}=U2) ->
union(lists:flatten(
lists:map(
fun (X1) ->
lists:map(
fun (X2) ->
concat([X1, X2])
end,
union_to_list(U2)
)
end,
union_to_list(U1)
))).
F#
open System
// Single line comment...
(*
This is a
multiline comment.
*)
let checkList alist =
match alist with
| [] -> 0
| [a] -> 1
| [a; b] -> 2
| [a; b; c] -> 3
| _ -> failwith "List is too big!"
let text = "Some text..."
let text2 = @"A ""verbatim"" string..."
let catalog = """
Some "long" string...
"""
let rec fib x = if x <= 2 then 1 else fib(x-1) + fib(x-2)
let fibs =
Async.Parallel [ for i in 0..40 -> async { return fib(i) } ]
|> Async.RunSynchronously
type Sprocket(gears) =
member this.Gears : int = gears
[<AbstractClass>]
type Animal =
abstract Speak : unit -> unit
type Widget =
| RedWidget
| GreenWidget
type Point = {X: float; Y: float;}
[<Measure>]
type s
let minutte = 60<s>
type DefaultMailbox<'a>() =
let mutable inbox = ConcurrentQueue<'a>()
let awaitMsg = new AutoResetEvent(false)
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 ByteStrings
class 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 Socket
openBoundUDPPort 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 ()
Scala
/**
* A person has a name and an age.
*/
case class Person(name: String, age: Int)
abstract class Vertical extends CaseJeu
case class Haut(a: Int) extends Vertical
case class Bas(name: String, b: Double) extends Vertical
sealed trait Ior[+A, +B]
case class Left[A](a: A) extends Ior[A, Nothing]
case class Right[B](b: B) extends Ior[Nothing, B]
case class Both[A, B](a: A, b: B) extends Ior[A, B]
trait Functor[F[_]] {
def map[A, B](fa: F[A], f: A => B): F[B]
}
// beware Int.MinValue
def absoluteValue(n: Int): Int =
if (n < 0) -n else n
def interp(n: Int): String =
s"there are $n ${color} balloons.\n"
type ξ[A] = (A, A)
trait Hist { lhs =>
def ⊕(rhs: Hist): Hist
}
def gsum[A: Ring](as: Seq[A]): A =
as.foldLeft(Ring[A].zero)(_ + _)
val actions: List[Symbol] =
'init :: 'read :: 'write :: 'close :: Nil
trait Cake {
type T;
type Q
val things: Seq[T]
abstract class Spindler
def spindle(s: Spindler, ts: Seq[T], reversed: Boolean = false): Seq[Q]
}
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
GLSL
// vertex shader
#version 150
in vec2 in_Position;
in vec3 in_Color;
out vec3 ex_Color;
void main(void) {
gl_Position = vec4(in_Position.x, in_Position.y, 0.0, 1.0);
ex_Color = in_Color;
}
// geometry shader
#version 150
layout(triangles) in;
layout(triangle_strip, max_vertices = 3) out;
void main() {
for(int i = 0; i < gl_in.length(); i++) {
gl_Position = gl_in[i].gl_Position;
EmitVertex();
}
EndPrimitive();
}
// fragment shader
#version 150
precision highp float;
in vec3 ex_Color;
out vec4 gl_FragColor;
void main(void) {
gl_FragColor = vec4(ex_Color, 1.0);
}
Clojure
; Comment
(def
^{:macro true
:added "1.0"}
let (fn* let [&form &env & decl] (cons 'let* decl)))
(def ^:dynamic chunk-size 17)
(defn next-chunk [rdr]
(let [buf (char-array chunk-size)
s (.read rdr buf)]
(when (pos? s)
(java.nio.CharBuffer/wrap buf 0 s))))
(defn chunk-seq [rdr]
(when-let [chunk (next-chunk rdr)]
(cons chunk (lazy-seq (chunk-seq rdr)))))
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))
)
网友评论