4

So I have looked at the following:

Suppress line numbering for specific lines in listings package

And the solution works great for the nth line of code. What if I want to suppress the very first line of code? Can not make it suppress the very first line...

1 Answer 1

2

Basis Ideas

The idea here is very simple. Simply define two styles, one with no line number, another with line numbers. Then input the first line of listing with the first style, input the rest with the second style.

The first attempt produced a small hitch where the physical second line was being numbered 1. A patch from https://tex.stackexchange.com/a/27240/14103, helped here.

The Code

Simply copy the required portions to your file preamble. To input your code files use, \getfilewithnofirslinenumber{filename}.

\documentclass{article}

\usepackage{filecontents}

\usepackage{listings}

% Your input files
\begin{filecontents*}{\jobname code1.xml}
<document>
  <part>
    <chapter>
      <section>
        <subsection>
          <subsubsection>
            <paragraph>
              text
            </paragraph>
          </subsubsection>
        </subsection>
      </section>
    </chapter>
  </part>
</document>
\end{filecontents*}

\begin{filecontents*}{\jobname code2.xml}
  <XML Version 1.0>
\end{filecontents*}


% Define numbering and nonumbering styles
\lstdefinestyle{nonumber}
{
  language=XML,
  numbers=none
}
\lstdefinestyle{withnumbers}
{
  language=XML,
  numbers=left,
  stepnumber=1
}


% For file input
\def\getfilewithnofirslinenumber#1{%
  \lstset{style=nonumber}
  \lstinputlisting[linerange={1-1},belowskip=0.0mm]{#1}
  \lstset{style=withnumbers}
  \lstinputlisting[firstline=2,aboveskip=0.0mm]{#1}
}

% This part has been taken from
% https://tex.stackexchange.com/a/27240/14103. Delete/comment out the
% following if you want your physical second line to be numbered 1.
\usepackage{etoolbox}
\makeatletter
\patchcmd{\lst@GLI@}% <command>
  {\def\lst@firstline{#1\relax}}% <search>
  {\def\lst@firstline{#1\relax}\def\lst@firstnumber{#1\relax}}% <replace>
  {\typeout{listings firstnumber=firstline}}% <success>
  {\typeout{listings firstnumber not set}}% <failure>
\makeatother



\begin{document}

The first line numbers in codes are not shown.

First file.

\getfilewithnofirslinenumber{\jobname code1.xml}

\hrule

\bigskip

Second file with only one line.

\getfilewithnofirslinenumber{\jobname code2.xml}


\end{document}

The Output

enter image description here

Tweaks

Definitely you will want to set the code language, your own styles for code font, number appearance etc.

Should you want your physical second line to be numbered 1, delete/comment out the portion:

\usepackage{etoolbox} 
\makeatletter 
.....
\makeatother

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .