User:Coffman/Syntax Highlight

From Meta, a Wikimedia project coordination wiki

Jump to: navigation, search
Blue Glass Arrow.svg MediaWiki logo.png
This page should be moved to MediaWiki.org.
Please do not move the page by hand. It will be imported by a MediaWiki.org administrator with the full edit history. In the meantime, you may continue to edit the page as normal.

I am involved on the development of a new extension, this one is very simple (like the others one) and its intended to HIGHLIGHT Syntax on code posted at the wiki. The extension will use enscript (available on all linuxes) and will put colour to the code , and them will put it under "pre" tags.

The CVS location of the code is : http://www.wickle.com/horde/cvs/cvs.php/mediawikiextensions

An example can be found at http://www.wickle.com/wikis/index.php/Syntax_Highlight_extension

Contents

[edit] Requisites

There are no good programs without little requirements ;) The only one is enscript

I am using 1.6.1 but I tested successfully under last version 1.6.4

[edit] Download

  • Download the extension from my CVS at wickle
  • Alternate Download at SF.net : SF.net CVS

[edit] Installation

Copy SyntaxHighlight.php to $mediawiki/extensions directory and add this line to LocalSettings.php:

include("extensions/SyntaxHighlight.php");

Also you must set $wgSyntaxSettings->dotCommand = "/usr/bin/enscript"; to accomplish your installation of SyntaxHighlight.

Create the subdirectories syntax and tmp in your images directory.

Make sure that your web server has write permission to these directories. E.g.,

chown apache:apache syntax tmp

If you are using a distribution with SELinux enabled (e.g., Fedora Core 4) just changing the write permission on the directories will not work. You must also set the security context. To make the images directory and all directories below it writable, change directory to the $mediawiki directory and issue:

chcon -R -h root:object_r:httpd_sys_script_rw_t images

[edit] Usage

To use , the only thing you must do are put the code between

<code> and </code>

tags. And inside this tags you must put one tag indicating the

language used (for example <perl/>,<sh/>,<java/>)

[edit] Samples

You can view the samples working at my wiki.

[edit] Perl

#!/usr/local/bin/perl5.8.2
#envia un correo a account_for_backups@gmail.com como usuario wickle con el backup de las
#ultimas base de datos de wickle y con el label Backup
#Usa Mail::Webmail::Gmail en #http://search.cpan.org/dist/Mail-Webmail-Gmail/lib/Mail/Webmail/Gmail.pm
#Syntax ./send_gmail.pl file_to_backup.tar.gz

use Mail::Webmail::Gmail;

my $backup_label="Backups";
my $file_to_backup=$ARGV[0];
my $mail_to_backup="account_for_backups@gmail.com";
my $now = localtime time;
print "It is now $now.\nfile to backup: $file_to_backup\n";
my ( $gmail ) = Mail::Webmail::Gmail->new(
            username => 'mygmailaccount', password => 'mypassword', );
    my $msgid = $gmail->send_message( to => 'account_for_backups@gmail.com', subject => 'Backup bases de datos '. $now, msgbody => 'Backup del dia '.$now. ' realizado', file0 => [$file_to_backup] );
    print "Msgid: $msgid\n";
    if ( $msgid ) {
        if ( $gmail->error() ) {
            print $gmail->error_msg();
        } else {
                ### Add this label to our new message ###
                $gmail->edit_labels( label => $backup_label, action => 'add', 'msgid' => $msgid );
                if ( $gmail->error() ) {
                    print $gmail->error_msg();
                } else {
                    print "Added label: $backup_label to message $msgid\n";
                }
        }
    }


[edit] bash

#!/bin/bash
#Getting some variables
FULLPATH=`dirname $1`;
BASE=`basename $1`;
# Needs an argument
if [ $# -eq 0 ] ; then
  # no argument given, print usage
  echo "start control version on configuration file";
  echo "use: $0 file";
else
  # check if RCS directory exist or create it
  if [ -d $FULLPATH/RCS ] ; then
    echo "revisions directory existent ...";
  else
    mkdir $FULLPATH/RCS
  fi

  # Things to do when a RCS file exist
  if [ -e $FULLPATH/RCS/$BASE,v ] ; then
    echo "File exist. Checking for differences ..."
    # Check if there is any differences
    if ! rcsdiff $1; then
      echo "==================================="
      echo "WARNING: changes have been made to $1 and are not in the repository. Carefully look at the diff above, comment them below for committing or CTRL+C to abort."
      # Lock file
      /usr/bin/rcs -l $1
      if ! /usr/bin/ci -u $1; then
        echo "Error when commiting. Aborting"
        exit
      fi
    fi
    echo "==================================="
    echo "Getting lastest revision and locking it ..."
    /usr/bin/co -l $1
  fi

  echo "Launching editor ..."
  vim $1
  # changes made, commit them to the repository unlocked
  /usr/bin/ci -u $1
  exit
fi


[edit] Java

/*
 * Algernon - a rule-based inference engine in Java.
 * http://algernon-j.sourceforge.net/
 *
 * This example shows how to open a Protege knowledge base
 * in Java and use Algernon to query the KB.
 *
 * To run it, be sure to change the path in NEWSPAPER_PROJECT
 * to match the correct project on your system.
 *
 * Micheal Hewett
 * 05 May 2004
 * hewett@cs.stanford.edu
 */

package org.algernon.test;

import java.util.*;

import org.algernon.Algernon;
import org.algernon.util.ErrorSet;
import org.algernon.datatype.Result;
import org.algernon.datatype.BindingList;
import org.algernon.kb.okbc.protege.AlgernonProtegeKB;
import org.algernon.kb.AlgernonKB;


// date created: Wed Aug 14 11:02:44 2002
/**
 * Opens the Protege newspaper KB and makes some simple queries on it.
 *
 * Example:
 * 

 * java  -classpath algernon.jar:protege.jar org.algernon.test.SimpleAlgernonExample
 * 


 * @see org.algernon.Algernon
 * @author  Micheal S. Hewett    hewett@smi.stanford.edu
 *
 */
public class SimpleAlgernonExample extends Object
{
  public static String     NEWSPAPER_PROJECT = "/Applications/Protege_2.0/examples/newspaper/newspaper.pprj";

  protected Algernon   f_algy        = null;   // Algernon instance
  protected AlgernonKB f_kb          = null;
  protected String     f_projectFile = "";



  // date created: Wed Aug 14 11:02:44 2002
  // created by:   Micheal S. Hewett    hewett@smi.stanford.edu
  public SimpleAlgernonExample()
  {
    f_projectFile = NEWSPAPER_PROJECT;
  }

  public SimpleAlgernonExample(String project)
  {
    f_projectFile = project;
  }


  /**
   * Opens the KB and initializes Algernon.
   */
  public void init()
  {
    try {
      f_algy = new Algernon();
      f_kb   = new AlgernonProtegeKB(f_algy, f_projectFile);
      f_algy.addKB(f_kb);
    }
    catch (Exception e) {
      System.err.println(e + "\nUnable to open the '" + f_projectFile + "' KB.");
      stop();
    }

  }


   /**
    * Halts the program nicely.
    */
   public void stop()
   {
     if (f_kb != null)
       f_kb.close();
   }

  public static void main(String[] args)
  {
    SimpleAlgernonExample example = new SimpleAlgernonExample(NEWSPAPER_PROJECT);
    example.init();
    example.start();
  }

  public void start()
  {

    try {
      // Example that retrieves all bindings of the variable ?X.
      // Note that the variable names are case-sensitive:

      ErrorSet errors = new ErrorSet();
      String   query  = "((:instance Author ?a)(name ?a ?name))";

      Result result = (Result)f_algy.ask(query, errors);

      if (result == null)
      {
        System.err.println("Errors during ask of '" + query + "'");
        System.err.println(errors.toString());
      }
      else
      {
        // One way to access the results is to iterate on the results
        // using result.iterator().  Each element of the iterator
        // is of type BindingList.
        for (Iterator iterator = result.iterator();
             iterator.hasNext();)
        {
          // Result contains some BindingList objects.
          BindingList bl = (BindingList) iterator.next();

          // The bound object will either be a Java Object (Integer, Float, etc.)
          // or a KB object (typically a Protege Instance).
          // If you want Algernon objects, use algy.getAlgernonBinding().
          Object author = f_algy.getBinding("?a",    bl);
          Object name   = f_algy.getBinding("?name", bl);

          System.out.println("Author: " + author + ",  name: " + name);

          // If for some reason you don't know the names of the variables
          // in the Binding Lists, you can iterate on the BindingList to
          // retrieve variable names and values. See the JavaDoc documentation
          // for the BindingList api.
        }

        // A simpler way to show the results is to let Algernon print the results:
        System.out.println(f_algy.printResultToString("ask", result));

        }
    } catch (Exception e) {
      System.err.println("Error running Algernon: " + e);
      e.printStackTrace();
    } finally {
      stop();
    }
  }

}