Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
listings with labels instead of raw line numbers for latex (hack)
#!/usr/bin/env python
# This file defines a simple mechanism to use labels in source code,
# rather than raw line numbers, for the lstinputlisting-command in
# latex. Use the format
#
# \lstinputlisting[firstline=LABEL1, lastline=LABEL2, ...]{filename}
#
# especially, firstline and lastline must be the first two
# arguments. In your sourcecode, you simply add a comment containing
# LABEL1 before the stuff that has to be included, and a comment
# containing LABEL2 after it. Then run this program with your
# .tex-file as commandline argument, and save its output to another
# .tex-file. The other .tex-file will then have the labels replaced by
# the respective line numbers.
#
# It is probably a good idea to have this as a part of a makefile or
# something.
#
# s x d
# Copyright (c) 2016 Christoph-Simon Senjak, <c s u u . e>
# @ l
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
from __future__ import print_function
import re
import sys
def find_tag (str, filename):
with open(filename) as q:
n = 0
for l in q:
n = n + 1
if l.count(str) > 0:
return n
lmatch = re.compile(r"(\s*\\lstinputlisting\[firstline=)([^,]*)(, *lastline=)([^,\]]*)(.*?\]\{)([^\}]+)(\}.*)", re.DOTALL)
with open(sys.argv[1]) as q:
for l in q:
q = lmatch.match(l)
if q == None:
print (l, end='')
else:
g = q.groups()
filename = g[5]
firstline = str(find_tag(g[1], filename) + 1)
lastline = str(find_tag(g[3], filename) - 1)
print (g[0] + firstline + g[2] + lastline + g[4] + filename + g[6], end='')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.