How to Add Line Numbers to All Lines in Google Prettify

How to add line numbers to all lines in Google Prettify?

The root cause is list-style-type: none in prettify.css:

/* Specify class=linenums on a pre to get line numbering */
ol.linenums { margin-top: 0; margin-bottom: 0 } /* IE indents via margin-left */
li.L0,
li.L1,
li.L2,
li.L3,
li.L5,
li.L6,
li.L7,
li.L8 { list-style-type: none /* <<< THIS is the cause! */ }
/* Alternate shading for lines */
li.L1,
li.L3,
li.L5,
li.L7,
li.L9 { background: #eee }

You can either remove that rule or override it with:

.linenums li {
list-style-type: decimal;
}

How to add line numbers when using google prettify in the nocode class?

Put the nocode class on the pre element..

<pre class="prettyprint linenums nocode">

Demo at http://jsfiddle.net/gaby/8Jwja/1/


Update

To show all numbers (and show them without the dot after the number) you will have to override the CSS

Add

ol.linenums{
counter-reset:linenumber;
}
ol.linenums li{
list-style-type:none;
counter-increment:linenumber;
}
ol.linenums li:before{
content: counter(linenumber);
float:left;
margin-left:-4em;
text-align:right;
width:3em;
}

Demo at http://jsfiddle.net/gaby/8Jwja/2/

How can I add linenums dynamically to Google Code prettify?

By calling prettyPrintOne you're essentially circumventing the class based initialisation. That method has arguments that tell prettify how to behave.

You're trying to modify how prettify behaves with classes but prettify ignores that because it only cares about the arguments which are null, therefore they fallback to internal defaults.

See the source documenting the method:

    /**
* Pretty print a chunk of code.
* @param {string} sourceCodeHtml The HTML to pretty print.
* @param {string} opt_langExtension The language name to use.
* Typically, a filename extension like 'cpp' or 'java'.
* @param {number|boolean} opt_numberLines True to number lines,
* or the 1-indexed number of the first line in sourceCodeHtml.
* @return {string} code as html, but prettier
*/

prettyPrintOne is essentially for parsing some code passed to it as a string, and returning the result, with the options controlled by those arguments. Conversely prettyPrint will traverse the DOM looking for the classes you're adding, behaving according to the classes it finds. As you want to toggle, you'll want to keep using prettyPrintOne so that we can have control of when to show prettified output, and when to show the original - more on that later.

As an aside, you're telling prettify to format JS when what you've got there is HTML including JS in script tags and CSS in style tags. So you'll want to use HTML as the lang extension, not JS.

Anyway, all you need to do is adjust your call to the below, additionally adding the prettify class solely so your prettify theme CSS applies:

$("#pre").html( PR.prettyPrintOne($("#pre").html(), "html", true) )
.addClass("prettyprint");

Et voila:

Showing line numbers in action

As for toggling, you just need to adjust the logic so that you store the original HTML somewhere on prettify-ing and restore it next time the button is clicked:

  $("#button").on("click", function() {
// Cache jquery object
var $pre = $("#pre");
// If the element has a prettyprint class, it's already been manually
// prettified
if (!$pre.hasClass("prettyprint")) {
// Element hasn't been prettified, store the html in jQuery data
$pre.data("original-html", $pre.html());
// Manually prettify
$pre.html(PR.prettyPrintOne($pre.html(), "html", true))
.addClass("prettyprint");
} else {
// Element has been prettified, restore the orginal html stored in jQuery
// data and remove the prettyprint class, back to where we started
$pre.html($pre.data("original-html"))
.removeClass("prettyprint");
// Remove the jQuery data entry for our original HTML, so next time we
// start fresh
$pre.data("original-html", null);
}
});

Here's a jsfiddle showing that in action: https://jsfiddle.net/joshdavenport/68thqus1/27/

Google Prettify: Line numbers won't show

Found the issue. It had to do with setting list item to display:inline-block. Removing that fixed it.

Google Code Prettify - stripes/piano keys without line numbers?

If you look at the themes gallery you'll see that this is affected by the stylesheet, and that there are some with line numbers on every line.


Something like

<style>li.L4, li.L9 { list-style-type: none }</style>

should do it.

The operative part of the default stylesheet is

li.L0,
li.L1,
li.L2,
li.L3,
li.L5,
li.L6,
li.L7,
li.L8 { list-style-type: none }

which turns off list bulleting for all items with index i where (i % 10) ∉ (4,9), hence the li.L4, li.L9 selector fills the gaps.

html: How to add line numbers to a source code block

While technically my question is already answered by Rounin (thanks), truth is I was not fully satisfied with the result, because I didn't state a couple other requisites that I felt were important after posting the question, and they fail with that solution:


  1. When a line wraps around, it should go underneath the above line, not underneath the line numbers.
  2. Both the numbers and the text columns should be style-able (notably, the background of the whole column should be easily changeable).

I tried a solution with another inline-block, but it failed #5, and had problems with adjusting to any width.

<OL> was quite close, but not quite there. An alternative to <OL> that I knew wouldn't fly was to use a table. It wouldn't fly, because the browser needs a <PRE> element in order to copy/paste spaces and tabs properly.

Then all of a sudden, a solution clicked in my head. Forcing an element that is not a table to behave as if it was a table, is the exact purpose of the table-xxxx display values!

So here we go. Tested in Iceweasel 24.7.0 and Chromium 35.0.1916.153. The demo includes extra styling as an example of the versatility of the method.

The CSS:

/* Bare bones style for the desired effect */
pre.code {
display: table;
table-layout: fixed;
width: 100%; /* anything but auto, otherwise fixed layout not guaranteed */
white-space: pre-wrap;
}
pre.code::before {
counter-reset: linenum;
}
pre.code span.tr {
display: table-row;
counter-increment: linenum;
}
pre.code span.th { /* used for line numbers */
display: table-cell;
user-select: none;
-moz-user-select: none;
-webkit-user-select: none;
}
pre.code span.th::before {
content: counter(linenum);
text-align: right;
display: block;
}
pre.code span.th {
width: 4em; /* or whatever the desired width of the numbers column is */
}
pre.code code {
display: table-cell;
}

And the HTML:

<pre class="code">
<span class="tr first-row"><span class="th"></span><code> indented line</code></span>
<span class="tr"><span class="th"></span><code>unindented line</code></span>
<span class="tr"><span class="th"></span><code> line starting and ending with tab </code></span>
<span class="tr"><span class="th"></span><code></code></span>
<span class="tr"><span class="th"></span><code>the above line should be empty</code></span>
<span class="tr"><span class="th"></span><code>overlong line that wraps around or so I hope because it's really long and should overflow the right sided margin of the web page in your browser</code></span>
<span class="tr"><span class="th"></span><code>fill up to ten</code></span>
<span class="tr"><span class="th"></span><code>lines to check</code></span>
<span class="tr"><span class="th"></span><code>alignment</code></span>
<span class="tr"><span class="th"></span><code>of numbers</code></span>
</pre>

Demo with extra styling

Update: Since I posted the question, learned that the GeSHi syntax highlighter has an option to use the following schema, which also meets all requisites and may be more acceptable to those that are allergic to tables:

<ol>
<li><pre>code</pre></li>
<li><pre>code</pre></li>
<li><pre>...</pre></li>
</ol>

Add line numbers to beginning of every line in a file using C

You have a large number of small problems to address. First, unless you are using a non-conforming compiler, the conforming declarations for main are int main (void) and int main (int argc, char **argv) (which you will see written with the equivalent char *argv[]). See: C11 Standard §5.1.2.2.1 Program startup p1 (draft n1570). See also: What should main() return in C and C++?

Next, c must be type int not type char to match EOF, e.g.

    int c, last = 0; /* c must be type int, not char to match EOF */

Don't hardcode filenames or use magic-numbers. Either pass the filename as an argument to main() or prompt for it within your program. You can conveniently take a filename to open or read from stdin by default with the ternary operator as follows:

    /* use filename provided as 1st argument (stdin by default) */
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

Finally to your code, since you want to Prefix each line with the line number, you must output the line number for the first line Before you output the characters for that line (and the same for each subsequent line). You can do that simply by outputting the number first (using the "%06zu " conversion specifier with the modifiers '0' to output leading zeros and the field-width 6 to match your format shown). Also note the type for your ln counter is changed from int to size_t, the recommended type for counters in C (you can't have a negative line-count).

Putting this together with the use of the last character to allow checking for the '\n' before outputting your characters, you could do:

#include <stdio.h>

int main (int argc, char **argv) {

int c, last = 0; /* c must be type int, not char to match EOF */
size_t ln = 1; /* use size_t for counters */
/* use filename provided as 1st argument (stdin by default) */
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

if (!fp) { /* validate file open for reading */
perror ("file open failed");
return 1;
}
printf ("%06zu ", ln++); /* output line 1 number */
while ((c = getc(fp)) != EOF) { /* read each character */
if (last) /* test if last set */
putchar (last); /* output all characters */
if (last == '\n') /* test if last is newline */
printf ("%06zu ", ln++); /* output next line number */
last = c; /* set last to c */
}
putchar (last); /* output final character */
if (last != '\n') /* check POSIX eof */
putchar('\n'); /* tidy up with newline */
if (fp != stdin) /* close file if not stdin */
fclose (fp);

return 0;
}

(note: the check of if (last != '\n') after exiting the loop checks for the presence of a POSIX line ending on the last line, and if not, you should manually output a '\n' so that your program is POSIX compliant)

Example Input File

$ cat ../dat/captnjack.txt
This is a tale
Of Captain Jack Sparrow
A Pirate So Brave
On the Seven Seas.

Example Use/Output

$ ./bin/linenos ../dat/captnjack_noeol.txt
000001 This is a tale
000002 Of Captain Jack Sparrow
000003 A Pirate So Brave
000004 On the Seven Seas.

Look things over and let me know if you have further questions.

(also note: if your compiler does not support the zu conversion specifier for size_t, remove the 'z' and output as an unsigned value - VS10 or earlier do not support zu)



Related Topics



Leave a reply



Submit