-
Notifications
You must be signed in to change notification settings - Fork 2
/
tex-listing-title-hack.pl
executable file
·63 lines (54 loc) · 1.48 KB
/
tex-listing-title-hack.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/perl
use strict;
use warnings;
use Encode;
my $file = shift @ARGV;
my $title = "YOU HAVE A BUG, SUCKER";
# Turns stupid code snippet captions from:
# {\bf Code caption}
#
# \begin{lstlisting}[...
# to:
# \begin{lstlisting}[...,title={Code caption}]
#
# Moreover, as the TeX conversion drops links from captions for some
# reason, we try to fish them back by grepping the sources (UGH).
sub find_snippet_url {
my ($title) = @_;
$title =~ s/\s+\(.*//; # remove the filename between parentheses
for (<../*.asc>) {
open F2, $_;
while (my $line = decode("utf-8", <F2>)) {
# Drop the "_" from the line before trying to match: the
# emphasis marks are dropped from the LaTeX version
$line =~ s/_//g;
if ($line =~ /^\.$title \((.*)\[.*\]\)/) {
return $1;
}
}
close F2;
}
return;
}
open F, $file;
while (my $line = <F>) {
if ($line =~ /{\\bf (.+)}/) {
$title = decode("iso-8859-1", $1);
<F>; # Discard the next line, should be empty
} elsif ($title && $line =~ /^\\begin{lstlisting}/) {
# Try to find the URL for this snippet. If found, add a link.
my $url = find_snippet_url($title) // "";
if ($url) {
$title =~ /(.+) \((.+)\)/;
my ($human_title, $filename) = ($1, $2);
$line =~ s/,\]/,title={$human_title (\\href{$url}{$filename})}]/;
} else {
$line =~ s/,\]/,title={$title}]/;
}
print $line;
$title = undef;
} else {
print $line;
}
}
close F;