Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

org-mode source inclusion line numbers

Tags:

emacs

org-mode

Org-mode has a great feature to include source code like this:

#+begin_src java -n
    /**
     * @param foo
     */
    public static void doBar(Baz ba)
    {
        Collection<String> strings = ba.getStrings(true);
        return strings;
    }
#+end_src

The -n option shows line numbers.

There's a +n option to have the numbering continue from the last block.

Is there any option to set the starting number? This would be useful for source code snippets where you want the line numbers to correspond to the full file.

like image 737
justingordon Avatar asked Dec 15 '22 20:12

justingordon


2 Answers

This has been added in Org Mode 9. It's now possible to pass numbers to both -n and +n.

So, for example, you could make the example start on line 12 by using the following header:

#+begin_src java -n 12
...
#+end_src
like image 87
jco Avatar answered Dec 27 '22 08:12

jco


I agree with jco. A long answer to the question could read like the following. But except from the screenshot it's just copy and paste from the manual.

As documented in the Section Literal Examples you can add line numbers to the source blocks and example blocks:

Both in example and in src snippets, you can add a -n switch to the end of the BEGIN line, to get the lines of the example numbered. The -n takes an optional numeric argument specifying the starting line number of the block. If you use a +n switch, the numbering from the previous numbered snippet will be continued in the current one. The +n can also take a numeric argument. The value of the argument will be added to the last line of the previous block to determine the starting line number.

You can also refer to line numbers:

In literal examples, Org will interpret strings like (ref:name) as labels, and use them as targets for special hyperlinks like [[(name)]] (i.e., the reference name enclosed in single parenthesis). In HTML, hovering the mouse over such a link will remote-highlight the corresponding code line, which is kind of cool.

An example for demonstrating both features is

#+BEGIN_SRC emacs-lisp -n -r
(save-excursion                  (ref:sc)
   (goto-char (point-min)))      (ref:jump)
#+END_SRC

In line [[(sc)]] we remember the current position.
[[(jump)][Line (jump)]] jumps to point-min.

It would produce

Screenshot of referenced code with line numbers.

like image 37
pjs Avatar answered Dec 27 '22 09:12

pjs