Giter VIP home page Giter VIP logo

code-prettify's Introduction

Status: Archived

status: inactive

This repository has been archived and is no longer maintained.


JavaScript code prettifier

Announcement: Action required rawgit.com is going away.

An embeddable script that makes source-code snippets in HTML prettier.

  • Works on HTML pages.
  • Works even if code contains embedded links, line numbers, etc.
  • Simple API: include some JS & CSS and add an onload handler.
  • Lightweights: small download and does not block page from loading while running.
  • Customizable styles via CSS. See the themes gallery.
  • Supports all C-like, Bash-like, and XML-like languages. No need to specify the language.
  • Extensible language handlers for other languages. You can specify the language.
  • Widely used with good cross-browser support. Powers https://code.google.com/ and http://stackoverflow.com/

See an example.

Setup

  • Include the script tag below in your document:
<script src="https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/run_prettify.js"></script>

Usage

Put code snippets in <pre class="prettyprint">...</pre> or <code class="prettyprint">...</code> and it will automatically be pretty-printed.

<pre class="prettyprint">class Voila {
public:
  // Voila
  static const string VOILA = "Voila";

  // will not interfere with embedded <a href="#voila2">tags</a>.
}</pre>

FAQ

For which languages does it work?

The comments in prettify.js are authoritative but the lexer should work on a number of languages including C and friends, Java, Python, Bash, SQL, HTML, XML, CSS, JavaScript, Makefile, and Rust.

It works passably on Ruby, PHP, VB, and Awk and a decent subset of Perl and Ruby, but because of commenting conventions, doesn't work on Smalltalk, OCaml, etc. without a language extension.

Other languages are supported via extensions:

Apollo; Basic; Clojure; CSS; Dart; Erlang; Go; Haskell; Lasso; Lisp, Scheme; LLVM; Logtalk; Lua; MATLAB; MLs: F#, Ocaml,SML; Mumps; Nemerle; Pascal; Protocol buffers; R, S; RD; Rust; Scala; SQL; Swift; TCL; LaTeX; Visual Basic; VHDL; Wiki; XQ; YAML

If you'd like to add an extension for your favorite language, please look at src/lang-lisp.js and submit a pull request.

How do I specify the language of my code?

You don't need to specify the language since PR.prettyPrint() will guess. You can specify a language by specifying the language extension along with the prettyprint class:

<pre class="prettyprint lang-html">
  The lang-* class specifies the language file extensions.
  File extensions supported by default include:
    "bsh", "c", "cc", "cpp", "cs", "csh", "cyc", "cv", "htm", "html", "java",
    "js", "m", "mxml", "perl", "pl", "pm", "py", "rb", "sh", "xhtml", "xml",
    "xsl".
</pre>

You may also use the HTML 5 convention of embedding a <code> element inside the <pre> and using language-java style classes:

<pre class="prettyprint"><code class="language-java">...</code></pre>

It doesn't work on "obfuscated code sample"?

Yes. Prettifying obfuscated code is like putting lipstick on a pig โ€” i.e. outside the scope of this tool.

Which browsers does it work with?

It's been tested with IE 6, Firefox 1.5 & 2, and Safari 2.0.4. Look at the tests to see if it works in your browser.

What's changed?

See the changelog.

Why doesn't Prettyprinting of strings work on WordPress?

Apparently wordpress does "smart quoting" which changes close quotes. This causes end quotes to not match up with open quotes.

This breaks prettifying as well as copying and pasting of code samples. See WordPress's help center for info on how to stop smart quoting of code snippets.

How do I put line numbers in my code?

You can use the linenums class to turn on line numbering. If your code doesn't start at line number 1, you can add a colon and a line number to the end of that class as in linenums:52. For example:

<pre class="prettyprint linenums:4"
>// This is line 4.
foo();
bar();
baz();
boo();
far();
faz();
</pre>

How do I prevent a portion of markup from being marked as code?

You can use the nocode class to identify a span of markup that is not code:

<pre class="prettyprint">
int x = foo();  /* This is a comment  <span class="nocode">This is not code</span>
  Continuation of comment */
int y = bar();
</pre>

For a more complete example see the issue #22 testcase.

I get an error message "a is not a function" or "opt_whenDone is not a function"

If you are calling prettyPrint via an event handler, wrap it in a function. Instead of doing:

addEventListener('load', PR.prettyPrint, false);

wrap it in a closure like:

addEventListener('load', function(event) { PR.prettyPrint(); }, false);

so that the browser does not pass an event object to PR.prettyPrint which will confuse it.

How can I customize the colors and styles of my code?

Prettify adds <span> with classes describing the kind of code. You can create CSS styles to matches these classes.

See the theme gallery for examples.

I can't add classes to my code (because it comes from Markdown, etc.)

Instead of <pre class="prettyprint ..."> you can use a comment or processing instructions that survives processing instructions: <?prettify ...?> works as explained in Getting Started.

How can I put line numbers on every line instead of just every fifth line?

Prettify puts lines into an HTML list element so that line numbers aren't caught by copy/paste, and the line numbering is controlled by CSS in the default stylesheet, prettify.css.

The following should turn line numbering back on for the other lines:

<style>
li.L0, li.L1, li.L2, li.L3,
li.L5, li.L6, li.L7, li.L8 {
  list-style-type: decimal !important;
}
</style>

Discussion

Please use the official support group for discussions, suggestions, and general feedback.

License

Apache License 2.0

code-prettify's People

Contributors

9px avatar alex-milanov avatar alexlynd avatar amroamroamro avatar cassierecher avatar chris-morgan avatar clarfonthey avatar clayreimann avatar coeur avatar ericfromcanada avatar fschumacher avatar graingert avatar grant avatar mathiasbynens avatar mibac138 avatar mikesamuel avatar mprobst avatar ncruces avatar nietaki avatar pedrolamas avatar pmoura avatar sfreilich avatar stargateur avatar weitzhandler avatar wesbos avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

code-prettify's Issues

Handle quotes within python docstring

What steps will reproduce the problem?
1. write python code with """docstrings"""
2. embed a "quoted string" within the docstring.


(Please include HTML, not just your source code)


What is the expected output?  What do you see instead?

Right now, the inner string is treated as not being part of a string. So,
if it contains numbers or English words that happen to be keywords, they
will be highlighted too much.  It would be great if these were just
considered part of the overall string. Or, if there was a
string-within-a-string class, but that might be getting to complicated.

This issue was raised by another user:
http://code.google.com/p/support/issues/detail?id=698

Original issue reported on code.google.com by [email protected] on 3 Feb 2008 at 7:22

Django Templates Don't Work

When viewing Django template files (such at this [1]) in the source
browser the syntax highlighting makes the code extremely difficult to
read. Pygments supports Django template highlighting[2], and could be
a good reference. As for detection of the highlighter to use,
detection of the iconic django {{ }} tags would probably be a safe
enough indicator.

[1] - http://code.google.com/p/rietveld/source/browse/trunk/templates/all.html

[2] -
http://dev.pocoo.org/projects/pygments/browser/pygments/lexers/templates.py#L193

Original issue reported on code.google.com by kubasik.kevin on 19 May 2008 at 7:44

XML tag names can contain :

Hi
I was playing with the prettify and unnoticed than xml tag names
with : are not displayed correctly. (i.e. for xml with
xml namespaces), the following simple patch fixes this
problem:
--- prettify.js 2007-09-07 09:28:35.000000000 +0100
+++ orig/prettify.js    2007-08-31 03:21:54.000000000 +0100
@@ -618,7 +618,7 @@
     [PR_ATTRIB_VALUE, /^\"[^\"]*(?:\"|$)/, null, '"'],
     [PR_PUNCTUATION,  /^[<>\/=]+/, null, '<>/=']
     ], [
-    [PR_TAG,          /^[\w-:]+/, /^</],
+    [PR_TAG,          /^[\w-]+/, /^</],
     [PR_ATTRIB_VALUE, /^[\w-]+/, /^=/], 
     [PR_ATTRIB_NAME,  /^[\w-]+/, null], 
     [PR_PLAIN,        /^\s+/, null, ' \r\n']

Original issue reported on code.google.com by [email protected] on 7 Sep 2007 at 8:29

Code highlighting for MXML/AS3

Visit this page, for example:
http://code.google.com/p/gmaps-samples-flash/source/browse/trunk/samplecode/Loca
lSearcher.mxml

Notice no highlighting occurs.

This is mixed XML/script, basically.

It also doesn't work for standalone MXML:
http://code.google.com/p/gmaps-samples-flash/source/browse/trunk/samplecode/Hell
oWorld.mxml

It does work for standalone AS3:
http://code.google.com/p/gmaps-samples-flash/source/browse/trunk/samplecode/com/
google/maps/examples/ControlOptions.as

Original issue reported on code.google.com by pamela.fox on 22 May 2008 at 6:14

Use of [ ] inside java string produces incorrect output

What steps will reproduce the problem?
1. Use html like the following:
<pre class="prettyprint">
  throw new RuntimeException("Element [" + element.getName() + 
    "] missing attribute.");
  variable++;
</pre>

What is the expected output?  What do you see instead?
1. Expect that 'variable ++;' line is colored as code, but it is instead
displayed as a comment. The last double-quote character on the preceding
line is printed 'fancy', and all following characters on this same line are
 also colored as comment (colored as code would be expected).

What version are you using?  On what browser?
31-Aug-2007 (small) on Firefox 2.0.0.14. Same problem occurs on Internet
Explorer 7.


Original issue reported on code.google.com by [email protected] on 1 Jul 2008 at 10:30

Output not valid XHTML when document is XHTML

What steps will reproduce the problem?
1. Any prettyprint

What is the expected output?  What do you see instead?
A xhtml conform output.

What version are you using?  On what browser?
Any.

Please provide any additional information below.
<br> tags should really be formatted as <br /> to be xhtml conform.

Quick fix:
-              .replace(/\r\n?|\n/g, '<br>');
+              .replace(/\r\n?|\n/g, '<br />');

Original issue reported on code.google.com by [email protected] on 4 Jun 2007 at 7:26

Lexer does not handle Javascript regular expression literals

What steps will reproduce the problem?
1. Quotes inside javascript regular expression break syntax highlighting.

(Please include HTML, not just your source code)
It actually breaks on Douglas' Crockford's parseJSON code 
http://www.json.org/json.js

Here's the actual break point

  s.parseJSON = function (filter) {
    // Parsing happens in three stages. In the first stage, we run the text
against
    // a regular expression which looks for non-JSON characters. We are
especially
    // concerned with '()' and 'new' because they can cause invocation, and '='
    // because it can cause mutation. But just to be safe, we will reject all
    // unexpected characters.

    try {
      if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.
        test(this)) {

          // In the second stage we use the eval function to compile the
text into a
          // JavaScript structure. The '{' operator is subject to a
syntactic ambiguity
          // in JavaScript: it can begin a block or an object literal. We
wrap the text
          // in parens to eliminate the ambiguity.


What is the expected output?  What do you see instead?

Expected the prettifier to use / as delimiters and properly parse the
single quotation in the regular expression.

What version are you using?  On what browser?
Apr 02 version.

Please provide any additional information below.

Original issue reported on code.google.com by [email protected] on 22 Apr 2007 at 3:30

Support for manpage highlighting syntax

What steps will reproduce the problem?
1. Write a man page and upload it to SVN 
2. Go to the "Source" tab and ether click on "Browse" or "Changes"
3. Find and view the man page
(Please include HTML, not just your source code)


What is the expected output?  What do you see instead?
It would be nice to have color syntax highlighting, instead of everything
being the same color.

What version are you using?  On what browser?
vendion@SE-03:~> man --version
man 2.5.1

My OS is openSUSE 11.0

Browser information:
Konqueror 4.0.4 (KDE 4.0.4 >= 20080505)
Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0) Gecko/2008061600
SUSE/3.0-0.2 Firefox/3.0
Konqueror 3.5.9

Please provide any additional information below.
To hopefully make things easier here is a link to the man page for one of
my projects
<a href="http://code.google.com/p/backup-
make things easier here is a link to the man page for one of
my projects
http://code.google.com/p/backup-light/source/browse/trunk/%20backup-http://code.
google.com/p/backup-light/source/browse/trunk/%20backup-light/trunk/backup-light
.1</a>

Original issue reported on code.google.com by vendion on 17 Jul 2008 at 1:36

syntax highlighting for F#

Would it be possible to add syntax highlighting for F#? F# is really
similar to OCaml, but usually uses the extension .fs.

What steps will reproduce the problem?
Here is an example:
http://code.google.com/p/micado/source/browse/src/BioStreamFS/graph.fs

What is the expected output?  What do you see instead?
The source code is not highlighted. It would be nice to have syntax
highlighting.

Original issue reported on code.google.com by [email protected] on 17 Mar 2008 at 8:35

Recursion loop on prettyPrintOne(&quot;&quot;)

What steps will reproduce the problem?
1. call prettyPrintOne("");

What is the expected output? What do you see instead?
Should return an empty string, instead, it hits an infinite recursion loop.

What version of the product are you using? On what operating system?
Revision 20, firefox 2.

Please provide any additional information below.
I am using this package to perform syntax highlighting on code taken from a
dynamic number of textareas, so just calling prettify() doesn't suit my needs.

Original issue reported on code.google.com by [email protected] on 25 Mar 2007 at 7:23

More verbose CSS class names

I think the current CSS class names are not verbose enough, you can't
understand their purpose by just reading the CSS file.

Why not just change them to:
.str -> .string
.kwd -> .keyword
etc...


Original issue reported on code.google.com by [email protected] on 29 Mar 2007 at 5:36

Fix for innerHTML quirk

What steps will reproduce the problem?
1. &lt;html&gt;
2.    &lt;head&gt;
3.       &lt;title&gt;Test&lt;/title&gt;
4.    &lt;/head&gt;
4. &lt;/html&gt;

(Please include HTML, not just your source code)


What is the expected output?  What do you see instead?

The visual output looks fine. However, when selecting the formatted output
and, copying it, and then pasting into Microsoft Notepad, or Microsoft
Visual Studio .NET 2005, the code, is pasted onto a single line.

For example, if the "code" is ten lines long, when pasting, it is pasted
onto a single line.

When pasting, I would expect to get:
<html>
   <head>
      <title>Test</title>
   </head>
</html>

What I get is:
<html>   <head>      <title>Test</title>   </head></html>


What version are you using?  On what browser?
Version: 22 May 2007
IE 6.0

Please provide any additional information below.
I fixed the code.

As you know, innerHTML has a quick that is automatically collapses all of
the space within the assigned HTML. The problem is that within a PRE
element, the spaces are significant and should not be collapsed.

You solved part of that problem when you replace /(\r\n?|\n| ) /g with
'$1&nbsp;' and /\r\n?|\n/g with '<br>'.

That code helps IE to display the code correctly, but the occurrences of
\r\n|\n are still stripped. I added code in doWork() to replace all <br>'s
with \r\n. Obviously innerHTML cannot be used to do this. I used the DOM to
fix the problem. Below is the relevant code.


  function doWork() {
    var endTime = new Date().getTime() + 250;
    for (; k < elements.length && new Date().getTime() < endTime; k++) {
      var cs = elements[k];
      if (cs.className && cs.className.indexOf('prettyprint') >= 0) {

        // make sure this is not nested in an already prettified element
        var nested = false;
        for (var p = cs.parentNode; p != null; p = p.parentNode) {
          if ((p.tagName == 'pre' || p.tagName == 'code' ||
               p.tagName == 'xmp') &&
              p.className && p.className.indexOf('prettyprint') >= 0) {
            nested = true;
            break;
          }
        }
        if (!nested) {
          // fetch the content as a snippet of properly escaped HTML.
          // Firefox adds newlines at the end.
          var content = PR_getInnerHtml(cs);
          content = content.replace(/(?:\r\n?|\n)$/, '');

          // do the pretty printing
          var newContent = prettyPrintOne(content);

          // push the prettified html back into the tag.
          var elem = null;
          if (!PR_isRawContent(cs)) {
            // just replace the old html with the new
            cs.innerHTML = newContent;
            elem = cs;
          } else {
            // we need to change the tag to a <pre> since <xmp>s do not allow
            // embedded tags such as the span tags used to attach styles to 
            // sections of source code.
            var pre = document.createElement('PRE');
            for (var i = 0; i < cs.attributes.length; ++i) {
              var a = cs.attributes[i];
              if (a.specified) {
                pre.setAttribute(a.name, a.value);
              }
            }
            pre.innerHTML = newContent;
            elem = pre;
            // remove the old
            cs.parentNode.replaceChild(pre, cs);
          }

          // Replace <BR>s with \r\n via DOM.
          replaceBrsWithCrLf(elem);  //TONY - ADDED THIS LINE
        }
      }
    }
    if (k < elements.length) {
      // finish up in a continuation
      setTimeout(doWork, 250);
    }
  }

  doWork();
}

//TONY - Add the following two methods to make copy/paste work correctly.
//       This "restores" the \r\n that IE stripped out when using .innerHTML
//       property.
/** Replace <br>s with \r\n directly in DOM
  *
  * @param elem as DOM element with <br>s
  */
function replaceBrsWithCrLf(elem) {
  var brs = elem.getElementsByTagName("br");

  // Insert all the \r\n first. Cannot use ".replaceChild()" within this loop
  // because I believe the collection is "live".
  for (var i = 0; i < brs.length; i++) {
    var crlf = document.createTextNode("\r\n");
    insertAfter(crlf, brs[i]);
  }
  // Now remove all of the <BR>s
  // Need to do from bottom up, because the collection is "live"
  for (var i = brs.length; i-- > 0;) {
    brs[i].parentNode.removeChild(brs[i]);
  }
}

/** Insert newElement after targetElement, directly in DOM
  *
  * @param newElement to insert
  * @param targetElement to insert in front of
  */
function insertAfter(newElement, targetElement) {
  var parent = targetElement.parentNode;
  if (parent.lastChild == targetElement) {
    parent.appendChild(newElement);
  }
  else {
    parent.insertBefore(newElement, targetElement.nextSibling);
  }
}

Original issue reported on code.google.com by [email protected] on 26 Sep 2007 at 3:58

prettifier does not recognize <br> as newline

What steps will reproduce the problem?
1. <pre class="prettyprint">//comment<br />int main(int argc, char **argv)
{}</pre>
2.
3.
(Please include HTML, not just your source code)


What is the expected output?  What do you see instead?

I expect prettifier only deals with "//commnet" as comment, and the others
as C source code.  But all of them are regarded as comment.
(Google blogger produces such HTML code...)

What version are you using?  On what browser?


Please provide any additional information below.
Quick fix on prettify.js attached.

Original issue reported on code.google.com by [email protected] on 10 May 2007 at 1:59

Attachments:

Semantic HTML

Right now the prettify library doesn't really promote semantic HTML. The
class "prettyprint" doesn't convey what the content of the tag is;
especially not without the prettify library.

Asking the user to manually call the prettyPrint() function using the
onload attribute in the <body> tag isn't very semantic either. Preferrably
the only thing the user should need to do would be to include the
prettify.js file.

I've modified the prettify.js file to include the aforementioned
suggestions (it has been attached to this issue.) <pre class="code"> tags
and <code> (note that no class is required) tags will be highlighted as
soon as the DOM has finished loading (sooner than the onload event) if the
prettify.js file has been loaded.

Original issue reported on code.google.com by andreasblixt on 30 May 2008 at 2:09

Attachments:

Large XML file not highlighted at Code Hosting

What steps will reproduce the problem?
Open
http://code.google.com/p/google-styleguide/source/browse/trunk/cppguide.xml?r=3
That's a 158K, 4300-line XML file viewed in the source browser of Google
Code Hosting.

What is the expected output?  What do you see instead?
Expected the file to be highlighted. It is not.

What version are you using?  On what browser?
Firefox 3.0 on Ubuntu 8.04.

Please provide any additional information below.
I'm not sure whether this is an issue with google-code-prettify proper or
with the way it is used at Code Hosting.

Is there any size limit on the highlighted files?

Original issue reported on code.google.com by alexkon on 30 Jun 2008 at 2:27

Python syntax markup issues

What steps will reproduce the problem?
1. A file labelled as being Python source code, is displayed.
2. The file has a string, delimited by """, and has an ' in the string.
(Please include HTML, not just your source code)
Take a look at this link: 
http://code.google.com/p/spyte/source/browse/trunk/spyte.py

What is the expected output?  What do you see instead?
For only the string delimited by """ to be green... not the entire file.

What version are you using?  On what browser?
The version that google code itself uses.

I am using Firefox 3, on Linux. This appeared the same way on IE7 on
Windows XP, and Firefox 2 on XP. 

Original issue reported on code.google.com by [email protected] on 12 Jul 2008 at 2:29

[PATCH] Add line numbers to source code

This is an enhancement to have prettify display line numbers adjacent to the 
formatted code.

The basic idea is to wrap the pretty-printed <pre> in a <div> and having a new 
<pre> that 
contains line numbers float left of it. This is somewhat of a bigger 
intervention with the DOM 
of the page, but it looks nice. Additionally, users can easily copy/paste the 
code without having 
line numbers all over it, which I think is quite important.

The code below adds a configuration variable, PR_CREATE_LINE_BOX, to 
enable/disable the line 
box, and a variable to configure the line stepping, defaulting to 5. It also 
adds default styles to 
the included stylesheet.

I have also attached the patch in case the formatting goes wrong.

diff -u prettify_31_Aug_2007/prettify.css 
prettify_31_Aug_2007-changed/prettify.css
--- prettify_31_Aug_2007/prettify.css   2007-05-22 14:20:44.000000000 +0200
+++ prettify_31_Aug_2007-changed/prettify.css   2007-11-09 12:16:15.000000000 
+0100
@@ -12,6 +12,8 @@
 .atv { color: #080; }
 .dec { color: #606; }
 pre.prettyprint { padding: 2px; border: 1px solid #888; }
+div.prettycontainer {}
+pre.prettylines { float: left; padding: 3px; margin: 0px; text-align: right; 
margin-right: 10px; }

 @media print {
   .str { color: #060; }
diff -u prettify_31_Aug_2007/prettify.js 
prettify_31_Aug_2007-changed/prettify.js
--- prettify_31_Aug_2007/prettify.js    2007-08-31 04:21:54.000000000 +0200
+++ prettify_31_Aug_2007-changed/prettify.js    2007-11-09 12:29:13.000000000 +0100
@@ -110,6 +110,11 @@
 /** the number of characters between tab columns */
 var PR_TAB_WIDTH = 8;

+/** whether we should create a separate box with line numbers */
+var PR_CREATE_LINE_BOX = true;
+/** the stepping for line numbers */
+var PR_LINE_STEPPING = 5;
+
 // some string utilities
 function PR_isWordChar(ch) {
   return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
@@ -875,6 +880,29 @@
   return html.join('');
 }

+/** wrap the given pre in a div and prepend a pre containing line numbers
+  * 
+  * @param {Element} pre the pre element to wrap
+  */
+function PR_create_line_box(pre, numLines) {
+  // count line numbers within pre
+  var containerdiv = document.createElement('DIV');
+  containerdiv.setAttribute('class', 'prettycontainer')
+  var linespre = document.createElement('PRE');
+  linespre.setAttribute('class', 'prettylines')
+  var text = '';
+  for (var i=1; i < (numLines + 2); i++) {
+    if (i % PR_LINE_STEPPING == 0) {
+      text += i;
+    }
+    text += "\n";
+  }
+  linespre.innerHTML = text;
+  pre.parentNode.replaceChild(containerdiv, pre);
+  containerdiv.appendChild(linespre);
+  containerdiv.appendChild(pre);
+}
+
 /** pretty print a chunk of code.
   *
   * @param {String} sourceCodeHtml code as html
@@ -967,11 +995,13 @@
           // fetch the content as a snippet of properly escaped HTML.
           // Firefox adds newlines at the end.
           var content = PR_getInnerHtml(cs);
+          // number of lines (for line box)
+          var numLines = content.replace(/[^\n]/g, '').length;
           content = content.replace(/(?:\r\n?|\n)$/, '');

           // do the pretty printing
           var newContent = prettyPrintOne(content);
-
+                   
           // push the prettified html back into the tag.
           if (!PR_isRawContent(cs)) {
             // just replace the old html with the new
@@ -990,6 +1020,11 @@
             pre.innerHTML = newContent;
             // remove the old
             cs.parentNode.replaceChild(pre, cs);
+            // update cs to work with PR_create_line_box below
+            cs = pre;
+          }
+          if (PR_CREATE_LINE_BOX && cs.localName.toLowerCase() == 'pre') {
+            PR_create_line_box(cs, numLines);
           }
         }
       }

Original issue reported on code.google.com by [email protected] on 9 Nov 2007 at 11:34

Attachments:

Wiki pages doesn't color AspectJ keywords...

What steps will reproduce the problem?

1. Create a new Wiki page, by adding the following AspectJ code snippet... 

{{{
package edu.sfsu.cs.csc867.msales.voctopus.aspect.loggin;

import java.util.logging.Logger;
import java.util.logging.Level;
import org.aspectj.lang.Signature;

/**
 * Aspect responsible for the loggin of the entire application.
 * @author marcello
 * Feb 16, 2008 8:26:02 AM
 */
public aspect VOctopusExecutionLoggin {

    private Logger vologger = Logger.getLogger("tracer");

    private VOctopusExecutionLoggin() {
        this.vologger.setLevel(Level.ALL);
    }

    pointcut aspects() : within(VOctopusExecutionLoggin);

    pointcut vOcotpusPackage() : execution(*
edu.sfsu.cs.csc867.msales.voctopus..public(..)) ||
execution(edu.sfsu.cs.csc867.msales.voctopus..new(..));

    pointcut excludedObjectCalls() : execution(* Logger.*(..));

    pointcut loggableCalls() : vOcotpusPackage() && !aspects() &&
!excludedObjectCalls();

    before() : loggableCalls() {

        if (this.vologger.isLoggable(Level.INFO)) {
            Signature sig = thisJoinPointStaticPart.getSignature();
            this.vologger.logp(Level.INFO,
sig.getDeclaringType().getName(), sig.getName(), "Entering");
        }
    }
}
}}}

What is the expected output? What do you see instead?

The keywords related to AspectJ grammar are not rendered in blue, as it is
for Java keywords... 

What version of the product are you using? On what operating system?

The current version of Google Code... ;)

Keywords in the example:
In this example, the keywords are as follows:

 * pointcut
 * execution
 * before

Live demo at http://code.google.com/p/v-octopus/wiki/VOctopusAspects

Thanks...

Original issue reported on code.google.com by marcello.sales on 28 Feb 2008 at 3:53

PHP heredoc notation not supported

The highlighter breaks on string specified using the heredoc notation:

http://us2.php.net/manual/en/language.types.string.php#language.types.string.syn
tax.heredoc

Original issue reported on code.google.com by [email protected] on 5 Jun 2008 at 12:42

IE6 copy-paste issue for <xmp>

What steps will reproduce the problem?
1. edit prettify_test.html
2. change pr_isIE6() to return true: function pr_isIE6() { return true; }
3. open prettify_test.html in IE6
4. highlight and copy the code block under "HTML using XMP"
5. paste it into a text editor

(Please include HTML, not just your source code)

What is the expected output?  What do you see instead?

[Expected Output]
<html>
  <head>
    <title>Fibonacci number</title>
  </head>
  <body>
    <noscript>
      <dl>
        <dt>Fibonacci numbers</dt>
...
</html>

[Actual Output]
<html>  <head>    <title>Fibonacci number</title>  </head>  <body>   
<noscript>      <dl>        <dt>Fibonacci numbers</dt> ... </html>


What version are you using?  On what browser?
Prettify revision 39 on IE6.

Please provide any additional information below.

looks like it's a tiny logic error in prettify.js :-) 

'cs' variable is not updated after <xmp> is replaced by new <pre> element.
Here's a patch to resolve the issue:

--- prettify.js (revision 39)
+++ prettify.js (working copy)
@@ -1142,7 +1142,7 @@

               // remove the old
               cs.parentNode.replaceChild(pre, cs);
-              pre = cs;
+              cs = pre;
             }

             // Replace <br>s with line-feeds so that copying and pasting works

Original issue reported on code.google.com by teohuiming on 6 Jul 2008 at 8:26

Enter one-line summary

What steps will reproduce the problem?
1.
2.
3.

What is the expected output? What do you see instead?


What version of the product are you using? On what operating system?


Please provide any additional information below.

Original issue reported on code.google.com by [email protected] on 22 Mar 2007 at 5:29

Other already existing library

Why do an additional library? There is already
http://www.dreamprojections.com/SyntaxHighlighter

Probably this could be combined to have _one_ library.

Original issue reported on code.google.com by [email protected] on 27 Mar 2007 at 11:00

Haskell identifies

What steps will reproduce the problem?
1. open this URL:
<http://code.google.com/p/omega/source/browse/branches/llvm-gen/GenLLVM.hs?r=86#
78>
2. look at the selected line
3. it appears starnge

(Please include HTML, not just your source code)


What is the expected output?  What do you see instead?

In Haskell the apostrophe character can be tacked behind identifiers,
like

a' = 42;
b'' = 25;

Your highlighting code does not seem to cope with this :-(
and treats it like the start of a literal character constant.

What version are you using?  On what browser?
the version in google hosting, see
<http://code.google.com/p/support/issues/detail?id=709>

Safari 3.0 browser.


Original issue reported on code.google.com by [email protected] on 5 Feb 2008 at 6:18

C++ style comments don't work

The following code doesn't prettyprint proper:

public static void main(String[] args) {
  // print the arguments
  System.out.println(Arrays.asList(args));
}

The problem is that the newline delimits the end of a comment, but
google-code-prettify doesn't catch it.

Original issue reported on code.google.com by limpbizkit on 3 Dec 2007 at 10:11

PHP support

Philip says,

> Any chance you add support for those ugly PHP variables in the form of
> $this? Yeah, I hate PHP too, I still use it because it's better
> supported than Python on my server :)

Original issue reported on code.google.com by [email protected] on 22 Mar 2007 at 8:08

prettify.js doesn't work in XHTML

Load prettify.js in an XHTML file.

It breaks because it writes <span class=pln> which is invalid XHTML
(missing quotes around pln).

Original issue reported on code.google.com by [email protected] on 16 Jul 2008 at 6:19

Left angle brackets and ampersands cause problems.

What steps will reproduce the problem?
Formatting any the following code block:
str = '<a href=#>top</a>'
if b<a or c>d:
    str.replace("&","&amp;").replace("<", "&lt;")




What is the expected output? What do you see instead?
Expected: To see the code as it was input.
Instead:
str = 'top'
if bd:
    str.replace("&","&").replace("<", "<")

What version of the product are you using? On what operating system?
Trunk, linux / firefox 2

Please provide any additional information below.

Original issue reported on code.google.com by [email protected] on 1 Apr 2007 at 7:43

VB style comments don't work

See issue 25. Same with vb inline comments

'vb comment

The problem is that the newline delimits the end of a comment, but
google-code-prettify doesn't catch it.

Original issue reported on code.google.com by [email protected] on 8 Jan 2008 at 6:27

JS Error

Error: unterminated regular expression literal
Source File: http://xxx.com/prettify.js
Line: 2, Column: 207
Source Code:
1]="kwd"}else 
if(/^@?[A-Z][A-Z$]*[a-z][A-Za-z$]*$/.test(l)){f[h+1]=l.charAt(0)=="@"?
"lit":"typ"}}}q(f,a,b,2);b+=f.length-2}}return a}var 
D=r([],[["pln",/^[^<]+/,null],["dec",/^<!\w[^>]*(?
:>|$)/,null],["com",/^<!--[ 

Happens when I upload the latest version (small as well as normal) to my 
webspace.

Original issue reported on code.google.com by dlinsin on 26 Jun 2008 at 10:56

broken handling of docstring comments with quotes in them (python)

What steps will reproduce the problem?
URL: http://code.google.com/p/cachalot/source/browse/trunk/app.py

This snippet of code seems around line 118 seems to trigger the failure:

def loggedin(method):
  """Asserts that a known user is logged in.  If they aren't, we redirect
them to
  the login page (if they aren't logged in) or to a "you can't come to our
  party" page if they are logged in but unknown to us.  The wrapped method can
  assume that the user is an acceptable person.
  """

Note the double-quote and single quote in the comment.

Original issue reported on code.google.com by dcoker on 21 Apr 2008 at 10:15

<xmp class="prettyprint"> not styled by CSS

What steps will reproduce the problem?
1. Edit prettify_test.html to add a new test (see [TEST_PATCH]):
a) add a function to display the classname(s) of element with id='htmlXmp'.
b) modify <body onload=""> to show htmXmp's classname(s) before and after
prettyPrint() is called.
2. Open prettify_test.html in IE6.

(Please include HTML, not just your source code)
What is the expected output?  What do you see instead?

[Expected Output]
The classname of 'htmlXmp' should be same before and after prettyPrint() is
called.
1st AlertBox: "before - prettyprint"
2nd AlertBox: "after - prettyprint"

[Actual Output]
The classname of 'htmlXmp' is not set after prettyPrint() is called.
1st AlertBox: "before - prettyprint"
2nd AlertBox: "after - "

What version are you using?  On what browser?
Prettify revision 39, on IE6.

Please provide any additional information below.

It happens that, in IE, 
  pre.setAttribute('class', ..);
does not work, but 
  pre.className = 'classnames'; 
works on IE, and other browsers as well (as discussed in [1]).

[1]
http://www.quirksmode.org/bugreports/archives/2005/03/setAttribute_does_not_work
_in_IE_when_used_with_th.html

So, here's a patch to resolve the issue:

--- prettify.js (revision 39)
+++ prettify.js (working copy)
@@ -1136,6 +1136,9 @@
                 var a = cs.attributes[i];
                 if (a.specified) {
                   pre.setAttribute(a.name, a.value);
+                  if (a.name.toLowerCase() === 'class') {
+                    pre.className = a.value;
+                  }
                 }
               }
               pre.innerHTML = newContent;

============
[TEST_PATCH]
--- ../tests/prettify_test.html (revision 39)
+++ ../tests/prettify_test.html (working copy)
@@ -8,6 +8,9 @@
 // get accurate timing
 PR_SHOULD_USE_CONTINUATION = false;
 function pr_isIE6() { return false; }  // Ensure consistent output.
+function showClass(prefix) {
+  alert(prefix+' - '+document.getElementById('htmlXmp').className);
+}
 </script>
 <link rel="stylesheet" type="text/css" href="../src/prettify.css" />
 <style type="text/css">
@@ -16,7 +19,7 @@
 </head>

 <body
- onload="startClock(); prettyPrint(function () { stopClock(); runTests(); })"
+ onload="showClass('before'); startClock(); prettyPrint(function () {
stopClock(); runTests(); }); showClass('after')"
  bgcolor="white">
 <div id="timing"></div>
 <div id="errorReport" style="white-space: pre"></div>

Original issue reported on code.google.com by teohuiming on 6 Jul 2008 at 2:34

Suggested Improvement (regexp classname search)


The hard-coded class name is too inflexible for code which is already in
production, a VERY small tweak will allow the prettyfier to work on any
existing class name.  

At the top of the code insert the following line.

var prettyClass = new RegExp('prettyprint','i');  

Replace the following lines...

---
if (cs.className && cs.className.indexOf('prettyprint') >= 0) {
with
if (cs.className && cs.className.search(prettyClass) >= 0) {

---

And

---
p.className && p.className.indexOf('prettyprint') >= 0) {
with
p.className && p.className.search(prettyClass) >=0 ) {

---

This allows for the className to be quickly and easily changed in one
single spot and makes the search case-insensitive which further reduces
errors on legacy code.


Original issue reported on code.google.com by [email protected] on 23 Mar 2007 at 10:18

support for lua keywords


I need to create a patch with test cases.  The only keyword additions
really needed for this would be:

var LUA_KEYWORDS = "elseif local nil repeat";

You can grab a quick lua example from http://lua-users.org/wiki if you're
interested in poking around with me.

Cheers!
Joseph Armbruster

Original issue reported on code.google.com by [email protected] on 30 Nov 2007 at 8:50

Blank lines discarded

What steps will reproduce the problem?
1. <pre class="prettyprint">&lt;html&gt;
2.
3. &lt;head&gt;

(Please include HTML, not just your source code)


What is the expected output?  What do you see instead?
EXPECTED
<html>

<head>

GETTING
<html>
<head>

What version are you using?  On what browser?
Version: 22 May 20077
Browser: IE 6.0

Please provide any additional information below.
I fixed the code by adding &nbsp; in front of <br>.
This code is in prettyPrintOne().
   html = html
         .replace(/(\r\n?|\n| ) /g, '$1nbsp;')
         .replace(/\r\n?|\n/g, '&nbsp;<br>');

Original issue reported on code.google.com by [email protected] on 26 Sep 2007 at 3:38

Scrollbar

This is not a issue, just a feature request.
It is possible to add scrollbar to long codes ?

Original issue reported on code.google.com by [email protected] on 8 May 2007 at 12:12

Bug with mixing ' (apostrophe) and SQL "--" line comments

What steps will reproduce the problem?

Insert

{{{
-- Don't
SELECT * from users WHERE id = 3;
-- Don't
}}}

into wiki page and observe how the first apostrophe starts a string and
ends only at the second "Don't".  

This should not happen as the apostrophe is inside a SQL line comment "--".

The HTML generated for the above code is as follows:

{{{
<pre class="prettyprint"><span class="pun">--</span><span class="pln">
</span><span class="typ">Don</span><span class="str">'t<br>SELECT * from
users WHERE id = 3;<br>-- Don'</span><span class="pln">t</span></pre>
}}}

What version are you using?  On what browser?

I'm using the version that's live on code.google.com as of Dec 28, 2007. 
I'm using Firefox but it seems that this is browser compatibility issue.

Original issue reported on code.google.com by [email protected] on 28 Dec 2007 at 10:35

Tabs in IE.

If tabs are used to indent code inside <pre> IE6 and 7 won't honor them
after the script runs.

Code indented with tabs will be shown aligned to the left margin instead of
the proper indenting shown in Firefox.

I'm using Revision 20 of prettify.js, IE 6.0.29.00 in English and IE
7.0.5730.11 in Spanish.

The attached file will reproduce the problem.

Original issue reported on code.google.com by [email protected] on 27 Mar 2007 at 3:07

Attachments:

Lisp Syntax Highlighting + Parenthesis Match

Thank you Mike for this wonderful syntax highlighter.

I was wondering if it be possible (or planned) to support syntax
highlighting for Lisp? Currently the code shows up without any highlighting
(http://code.google.com/p/bld/source/browse/trunk/src/bld-core.lisp).

What would be really cool is if the highlighter had a parenthesis match
feature. I am not sure how they do it but a example of this can be found
http://paste.lisp.org/display/62591
Hovering the pointer at a parenthesis highlights the match (and the
hierarchy) in different colors.

Actually parenthesis match is orthogonal to Lisp highlighting and could
probably be independently useful. Thanks.




Original issue reported on code.google.com by [email protected] on 25 Jun 2008 at 4:10

Asterisk and slashes force following text to be interpreted as comments

What steps will reproduce the problem?

<pre class="prettyprint">
task :system_specs_gem => ['my:setup'] do
  gem = Dir.glob(&#8221;pkg/*.gem&#8221;).first
end

gem = Dir.glob(&#8221;pkg/*.gem&#8221;).first
gem = Dir.glob(&#8221;pkg/*.gem&#8221;).first
</pre>


What is the expected output?  What do you see instead?
I would like to see "pkg/*.gem" interpreted as a normal string, and
everything after to be business as usual.

What version are you using?  On what browser?
31 Aug 2007.  Firefox 2.0.0.12 on Debian Linux.


Please provide any additional information below.
If you give me a hint maybe I can hack the JavaScript.  I took a glance but
was blinded by all the regexen.

Original issue reported on code.google.com by mhawthorne on 28 May 2008 at 2:42

Allow to run prettyprint multiple times

What steps will reproduce the problem?
1. Run prettyprint() twice: the 2nd run causes previous rendered <pre> or 
<code> blocks to 
loose there formatting. 
2.
3.
(Please include HTML, not just your source code)


What is the expected output?  What do you see instead?

I would expect prettify to skip the blocks which already have been formatted.
This is especially useful when running prettify after eg ajax calls.

What version are you using?  On what browser?
vs 31 Aug 2007

Please provide any additional information below.

Suggeted implementation::
I changed prettify.js to add a 'prettified' class to each block when rendered.

         //mark the element as converted
         cs.className = cs.className+' prettified';

Then added a simply check of this classname when entereing the doWork loop

      /* added classname 'prettified' to avoid double processing */
      if (cs.className 
       && cs.className.indexOf('prettyprint') >= 0 
       && cs.className.indexOf('prettified') == -1 ) {





Original issue reported on code.google.com by [email protected] on 2 Jun 2008 at 7:18

Javascript Snippets wrapped in HTML SCRIPT tags hides/destroys inner content of the &lt;script&gt; tags.

What steps will reproduce the problem?
1. In your pre block have a <script> tag followed by javascript.

What is the expected output? What do you see instead?
Expect to see colorized HTML followed by colorized Javascript.   Saw only
the first script line, the rest of the block had been hidden/deleted in
Firefox.

What version of the product are you using? On what operating system?
Win XP.

Original issue reported on code.google.com by [email protected] on 23 Mar 2007 at 10:09

Language tagging

Creating this issue to spec out language tagging requirements.

The feature would allow some way of specifying the language of the block so
that it can be tokenized and highlighted appropriately.


CURRENTLY
=========
There are 2 lexers: one for C-style languages, and one for markup languages.

The C-style lexer does a decent job on some of the most commonly used
languages (incl. python and bash, but excl. lisps and basics), and the
markup one handles XML, HTML, and various HTML-like templating languages.

The current lexing scheme allows descent into tokens with a different lexer.


REASONS FOR
===========
We do not handle other languages, notably VB, Perl, OCAML.  And cannot
without significant work.  Determining the language of a snippet is hard to
do, and if we do it wrong it would make the library less reliable/useful
for those languages it currently supports.

The keyword list for C-style languages is a union of the keywords from all
the languages I've tested with.  It misidentifies as keywords some tokens,
e.g. "template", that are not keywords in many languages.

Some languages (java) have consistently observed naming conventions that
distinguish types, fields, locals, and constants.  Those conflict with
common naming conventions in e.g. C++.


REASONS AGAINST
===============
(1) Bloats code.  Due to lists of keywords and code for languages not used.
 Could be mitigated by some kind of inheritance of definitions, or by
splitting into files.

(2) Complexity of install.  Mitigating (1) by splitting into multiple files
would make it harder to install.  Currently there is only one file to deal
with.

(3) Complexity of use.  Currently the API is very simple.  Could mitigate
by falling back to the existing behavior if no lang specified.


GOAL
====
Provide optional language tagging without bloating code.  Preference is
given to simplicity of use, so we will retain the one file to install property.

DESIGN
======
The current scheme is complicated by the fact that we highlight around
tags, so that if the source includes links around class names, those are
preserved in the prettified output.

Instead of preserving those in stream as first-class tokens, we will
extract those out, keeping their position in the original stream so they
can be reinserted later.

This will let us eliminate the current state machines which take a lot of
code, in favor of regular expressions.

We can inherit keyword lists by using one keyword list as the prototype of
another.

Original issue reported on code.google.com by [email protected] on 15 Aug 2007 at 6:54

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.