Skip to content

Highlighting

Rob Garrison edited this page Feb 17, 2016 · 2 revisions

Syntax Highlight code examples used in the demo

CSS

/* Code error example (no closing comment tag)

/* Repository Network Tree */
#network .repo img[alt="T"], #network .repo img[alt="I"], #network .repo img[alt="L"] {
  width: 26px !important;
  height: 0 !important;
  padding-top: 22px !important;
}
#network .repo img[alt="T"] {
  background: url(http://StylishThemes.github.io/GitHub-Dark/images/t.png) no-repeat !important;
}

.js-expand-btn, .dashboard-tabs li a, pre.headers, .box-header {
  background: #181818 !important;
  background-image: -webkit-gradient(linear, left top, left bottom, from(#333), to(#181818)) !important;
  background-image: -webkit-linear-gradient(top, #333, #181818) !important;
  background-image: -moz-linear-gradient(top, #333, #181818) !important;
  background-image: -o-linear-gradient(top, #333, #181818) !important;
  background-image: linear-gradient(to bottom, #333, #181818) !important;
  border-color: #333 !important;
}

/* contributors page - svg styling */
svg|svg.spark, svg|svg.viz {
  background-color:  #181818 !important;
}
svg|svg.viz {
  border: 1px solid #555 !important;
  display: block !important;
}
.graphs svg|line {
  stroke: #444 !important;
  shape-rendering: geometricPrecision !important;
}

/* placeholder */
::-webkit-input-placeholder {
  color: #444 !important;
}
:-moz-placeholder {
  color: #444 !important;
}
::-moz-placeholder {
  color: #444 !important;
  opacity: 1 !important;
}

SCSS

/* Icon sprite example */
$icon: sprite-map("bg/icon/*.png",
  $layout: smart
);
$icon2x: sprite-map("bg/icon2x/*.png",
  $layout: smart
);

@mixin icon-sprite($sprite, $from: $base-font-size, $offset-x: 0, $offset-y: 0){
  @include use-sprite($icon, $icon2x, $sprite, $from, $offset-x, $offset-y);
}

/* Vertical mode with spacing example */
$vertical: sprite-map("bg/vertical/*.png",
  $layout: vertical,
  $spacing: 24px
);
$vertical2x: sprite-map("bg/vertical2x/*.png",
  $layout: smart,
  $spacing: 48px
);

@mixin vertical-sprite($sprite, $from: $base-font-size, $offset-x: 0, $offset-y: 0){
  @include use-sprite($vertical, $vertical2x, $sprite, $from, $offset-x, $offset-y);
}

HTML

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <title>GitHub Dark Syntax Highlighting Themes</title>

 <!-- themes -->
 <link rel="stylesheet" title="Fruity" href="themes/pygments-fruity.min.css">
 <link rel="stylesheet" title="Monokai" href="themes/pygments-monokai.min.css">
 <link rel="stylesheet" title="Native" href="themes/pygments-native.min.css">
 <link rel="stylesheet" title="GitHub Dark" href="themes/pygments-github-dark.min.css">
 <link rel="stylesheet" title="Slate" href="themes/pygments-slate.min.css">
 <link rel="stylesheet" title="Solarized Dark" href="themes/pygments-solarized-dark.min.css">
 <link rel="stylesheet" title="Vim" href="themes/pygments-vim.min.css">
 <link rel="stylesheet" title="Wombat" href="themes/pygments-wombat.min.css">
 <link rel="stylesheet" title="Zenburn" href="themes/pygments-zenburn.min.css">

 <!-- jQuery -->
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

</head>
<body>
 <h1><a href="http://userstyles.org/styles/37035">GitHub Dark for Stylish</a></h1>
 <h2>Syntax Highlighting themes</h2>
 <h3>Select a syntax highlighting theme: <select></select></h3>

<h3>Code block</h3>
<div class="highlight">
 <pre><code>
   <!-- ... -->
 </code></pre>
</div>

Javascript

$(function(){
 var t,
   $links = $('link[title]'),
   $select = $('select'),
   theme = "Native-Mod",
   ls = false,
   selectTheme = function(theme){
     $links.prop('disabled', true);
     $links.filter('[title="' + theme + '"]').prop('disabled', false);
   };
 // https://gist.github.com/paulirish/5558557
 if ("localStorage" in window) {
   try {
     window.localStorage.setItem('_tmptest', 'temp');
     ls = true;
     window.localStorage.removeItem('_tmptest');
   } catch(e) {}
 }
 if (ls) {
   theme = localStorage['github-dark-theme'] || theme;
 }

 t = '';
 $links.each(function(){
   t += '<option>' + this.title + '</option>';
 });
 $select
   .append(t)
   .on('change', function(){
     selectTheme(this.value);
     if (ls) {
       localStorage['github-dark-theme'] = this.value;
     }
   })
   .val(theme);

 $(window).load(function(){
   $select.val(theme);
   selectTheme(theme);
 });

});

PHP

<?php
class A_Request {

   private $_request;

   private $_fields = array(
 'title',
 'fullname',
 'email',
 'company',
     );

   public function __construct() {
 $this->_request = array();
 $this->_errors  = array();
   }

   public function initialize($data) {
 foreach ($this->_fields as $field) {
     if ( ! in_array($field, $this->_optional_fields)) {
   if (array_key_exists($field, $this->_validation_exceptions)) {
       $method = $this->_validation_exceptions[$field];
       $this->$method($data[$field]);
       continue;
   }

   if (isset($data[$field]) AND !empty($data[$field])) {
       if (array_key_exists($field, $this->_specific_validations)) {
     $method = $this->_specific_validations[$field];
     $this->$method($data[$field]);
       }
       $this->_request[$field] = $data[$field];
   } else {
       $this->_errors[$field] = 'error';
   }
     } else {
   if (isset($data[$field])) {
       $this->_request[$field] = $data[$field];
   }
     }
 }
   }

   public function valid_email($str) {
 $valid = ( ! preg_match(
     "/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix",
     $str
 ) ) ? FALSE : TRUE;

 if ( ! $valid) {
     $this->_errors['email'] = 'error';
 }
   }

}

Python

def dump_args(func):
    "This decorator dumps out the arguments passed to a function before calling it"
    argnames = func.func_code.co_varnames[:func.func_code.co_argcount]
    fname = func.func_name
    def echo_func(*args,**kwargs):
        print fname, ":", ', '.join(
            '%s=%r' % entry
            for entry in zip(argnames,args) + kwargs.items())
        return func(*args, **kwargs)
    return echo_func

@dump_args
def f1(a,b,c):
    print a + b + c

f1(1, 2, 3)

def precondition(precondition, use_conditions=DEFAULT_ON):
    return conditions(precondition, None, use_conditions)

def postcondition(postcondition, use_conditions=DEFAULT_ON):
    return conditions(None, postcondition, use_conditions)

class conditions(object):
    __slots__ = ('__precondition', '__postcondition')

    def __init__(self, pre, post, use_conditions=DEFAULT_ON):
        if not use_conditions:
            pre, post = None, None

        self.__precondition  = pre
        self.__postcondition = post

Ruby

def power(x,n)
  result = 1
  while n.nonzero?
    if n[0].nonzero?
      result *= x
      n -= 1
    end
    x *= x
    n /= 2
  end
  return result
end

def f(x)
  Math.sqrt(x.abs) + 5*x ** 3
end

(0...11).collect{ gets.to_i }.reverse.each do |x|
  y = f(x)
  puts "#{x} #{y.infinite? ? 'TOO LARGE' : y}"
end
# Map color names to short hex
COLORS = { :black   => "000",
           :red     => "f00",
           :green   => "0f0",
           :yellow  => "ff0",
           :blue    => "00f",
           :magenta => "f0f",
           :cyan    => "0ff",
           :white   => "fff" }

class String
  COLORS.each do |color,code|
    define_method "in_#{color}" do
      "<span style=\"color: ##{code}\">#{self}</span>"
    end
  end
end

C++

#include "algostuff.hpp"
using namespace std;

bool bothEvenOrOdd (int elem1, int elem2)
{
    return elem1 % 2 == elem2 % 2;
}

int main()
{
    vector<int> coll1;
    list<int> coll2;

    float m = 40.0f;

    INSERT_ELEMENTS(coll1,1,7);
    INSERT_ELEMENTS(coll2,3,9);

    PRINT_ELEMENTS(coll1,"coll1: \n");
    PRINT_ELEMENTS(coll2,"coll2: \n");

    // check whether both collections are equal
    if (equal (coll1.begin(), coll1.end(),  // first range
               coll2.begin())) {            // second range
        cout << "coll1 == coll2" << endl;
    } /* TODO Shouldn't there be an 'else' case? */

    // check for corresponding even and odd elements
    if (equal (coll1.begin(), coll1.end(),  // first range
               coll2.begin(),               // second range
               bothEvenOrOdd)) {            // comparison criterion
        cout << "even and odd elements correspond" << endl;
    }
}

Haskell

import System
import Foreign
import qualified Data.ByteString as B

main = do
    w <- getArgs >>= readIO . head
    let n      = w `div` 8
        loop_y = B.unfoldrN n (next_x w (2/fromIntegral w) n)

        unfold x = case loop_y x of
                    (s, Nothing) -> B.putStr s
                    (s, Just x)  -> B.putStr s >> unfold x

    putStrLn ("P4\n"++show w++" "++show w)
    unfold (T 1 0 0 (-1))

data T = T !Int !Int !Int !Double

next_x !w !iw !bw (T bx x y ci)
    | y  == w   = Nothing
    | bx == bw  = Just (loop_x w x 8 iw ci 0, T 1 0    (y+1)   (iw+ci))
    | otherwise = Just (loop_x w x 8 iw ci 0, T (bx+1) (x+8) y ci)

loop_x !w !x !n !iw !ci !b
    | x < w = if n == 0
                    then b
                    else loop_x w (x+1) (n-1) iw ci (b+b+v)
    | otherwise = b `shiftL` n
  where
    v = fractal 0 0 (fromIntegral x * iw - 1.5) ci 50

fractal :: Double -> Double -> Double -> Double -> Int -> Word8
fractal !r !i !cr !ci !k
    | r2 + i2 > 4 = 0
    | k == 0      = 1
    | otherwise   = fractal (r2-i2+cr) ((r+r)*i+ci) cr ci (k-1)
  where
    (!r2,!i2) = (r*r,i*i)

SQL

CREATE TABLE My_table(
    my_field1   INT,
    my_field2   VARCHAR(50),
    my_field3   DATE         NOT NULL,
    PRIMARY KEY (my_field1, my_field2)
);

ALTER TABLE My_table ADD my_field4 NUMBER(3) NOT NULL;

GRANT SELECT, UPDATE
    ON My_table
    TO some_user, another_user;

REVOKE SELECT, UPDATE
    ON My_table
    FROM some_user, another_user;

SELECT Book.title,
        COUNT(*) AS Authors
    FROM  Book JOIN Book_author
       ON Book.isbn = Book_author.isbn
    GROUP BY Book.title;

Java

import java.io.*;
import java.util.*;

public class KeyboardIntegerReader {

 public static void main (String[] args) throws java.io.IOException {
  String s1;
  String s2;
  int num = 0;

  // set up the buffered reader to read from the keyboard
  BufferedReader br = new BufferedReader (new InputStreamReader (
            System.in));

  boolean cont = true;

  while (cont)
     {
      System.out.print ("Enter an integer:");
      s1 = br.readLine();
      StringTokenizer st = new StringTokenizer (s1);
      s2 = "";

      while (cont && st.hasMoreTokens())
     {
          try
          {
           s2 = st.nextToken();
           num = Integer.parseInt(s2);
           cont = false;
          }
          catch (NumberFormatException n)
          {
           System.out.println("The value in \"" + s2 + "\" is not an integer");
          }
    }
     }

  System.out.println ("You entered the integer: " + num);
 }
}

Lua

function settable_event (table, key, value)
    local h
    if type(table) == "table" then
        local v = rawget(table, key)
        -- if key is present, do raw assignment
        if v ~= nil then rawset(table, key, value); return end
        h = metatable(table).__newindex
        if h == nil then rawset(table, key, value); return end
    else
        h = metatable(table).__newindex
        if h == nil then
            error(···)
        end
    end
    if type(h) == "function" then
        h(table, key,value)           -- call the handler
    else h[key] = value             -- or repeat operation on it
    end
end

Perl

package Dancer::Handler::Standalone;

use strict;
use warnings;

use HTTP::Server::Simple::PSGI;
use base 'Dancer::Handler', 'HTTP::Server::Simple::PSGI';

use Dancer::HTTP;

        # ...

        $dancer->run();
    }
}

sub print_startup_info {
    my $pid    = shift;
    my $ipaddr = setting('server');
    my $port   = setting('port');

    # we only print the info if we need to
    setting('startup_info') or return;

    # bare minimum
    print STDERR ">> Dancer $Dancer::VERSION server $pid listening " .
                 "on http://$ipaddr:$port\n";

    # all loaded plugins
    foreach my $module ( grep { $_ =~ m{^Dancer/Plugin/} } keys %INC ) {
        $module =~ s{/}{::}g;  # change / to ::

Bash (shell)

# Source global definitions
if [ -f /etc/bashrc ]; then
        . /etc/bashrc
fi
#
# aliases
alias grpe=grep
alias grep='grep --color --line-number'
alias vim="vim -p"
alias rebash="source ~/.bashrc"

alias install='sudo apt-get -y install'
alias search='apt-cache search'
alias purge='sudo apt-get purge'

export EDITOR=vim

# set up the prompt to the hostname
shopt -s checkwinsize
PS1="\e[1;35m[\w]   ---   \@ \d \n$>\[\e[0m\]"
PS2="\e[1;35m->\[\e[0m\]"

#--------------------------------------------------
#    grabs some definitions from google
#--------------------------------------------------
define () {
 lynx -dump "http://www.google.com/search?hl=en&q=define%3A+${1}" | grep -m 25 -w "*"  | sed 's/;/ -/g' | cut -d- -f5 > /tmp/templookup.txt
             if [[ -s  /tmp/templookup.txt ]] ;then
                 until ! read response
                     do
                     echo "${response}"
                     done < /tmp/templookup.txt
                 else
                     echo "Sorry $USER, I can't find the term \"${1} \""
              fi
  rm -f /tmp/templookup.txt
}

#--------------------------------------------------
#    Extracts most files, mostly
#--------------------------------------------------
extract () {
 if [ -f $1 ] ; then
   case $1 in
     *.tar.bz2)  tar xjf $1    ;;
     *.tar.gz)   tar xzf $1    ;;
     *.bz2)      bunzip2 $1    ;;
     *.rar)      rar x $1      ;;
     *.gz)       gunzip $1     ;;
     *.tar)      tar xf $1     ;;
     *.tbz2)     tar xjf $1    ;;
     *.tgz)      tar xzf $1    ;;
     *.zip)      unzip $1      ;;
     *.Z)        uncompress $1 ;;
     *)          echo "'$1' cannot be extracted via extract()" ;;
   esac
 else
   echo "'$1' is not a valid file"
 fi
}

LaTex

\documentclass[12pt]{article}

\usepackage[option1, option2]{package}

\begin{document}

% Here is a comment. Commands in tex are called by backslash: \command
\section{Section head}
\subsection{Subsection head}

This is text, and the following is in-line mathematics:
$\mathrm{e}^{-\pi\matrhm{i}} = -1$.
A display-style equation is shown below:

\begin{equation}
  E = mc^2
\end{equation}

\end{document}

Fortran

integer :: my_seed
        becomes
  integer, optional :: my_seed
module ran_mod
! ran1 returns a uniform random number between 0-1
! the seed is optional and used to reset the generator
contains
    function ran1(my_seed)
      use numz
      implicit none
       real(b8) ran1,r
      integer, optional ,intent(in) :: my_seed  ! optional argument not changed in the routine
      integer,allocatable :: seed(:)
      integer the_size,j
      if(present(my_seed))then            ! use the seed if present
          call random_seed(size=the_size) ! how big is the intrisic seed?
          allocate(seed(the_size))        ! allocate space for seed
          do j=1,the_size                 ! create the seed
             seed(j)=abs(my_seed)+(j-1)   ! abs is generic
          enddo
          call random_seed(put=seed)      ! assign the seed
          deallocate(seed)                ! deallocate space
      endif
       call random_number(r)
      ran1=r
  end function ran1
end module

 program darwin
    use numz
    use ran_mod          ! interface required if we have
                         ! optional or intent arguments
    real(b8) x,y
    x=ran1(my_seed=12345) ! we can specify the name of the argument
    y=ran1()
    write(*,*)x,y
    x=ran1(12345)         ! with only one optional argument we don't need to
    y=ran1()
    write(*,*)x,y
end program

* Note: Some code examples copied from Vivify

-- Customizing

-- Testing

  • Emoji (All GitHub Emoji)

-- Outdated Pages

Clone this wiki locally