forked from overvale/text-utilities
-
Notifications
You must be signed in to change notification settings - Fork 0
/
list-numbered
executable file
·102 lines (81 loc) · 2.19 KB
/
list-numbered
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#!/usr/bin/perl
# Makes lines into a numbered list.
# Reorders numbered lists
# Converts bullet lists to numbered
# Perl practices:
# Enables strict mode, requiring that variables are first declared with 'my'.
# This, along with specifying '-w' in the magic first line, is widely
# considered good Perl practice.
use strict;
# Unicode considerations:
# '-CIO' in the magic first line enables Perl to consider STDIN to always
# contain UTF-8, and to always output to STDOUT in UTF-8.
my $result = "";
my %last_marker = (); # Store last marker used for each list depth
$last_marker{0} = "";
my $last_leading_space = "";
my $g_tab_width = 4;
my $g_list_level = 0;
my $line;
my $marker;
my $item;
my $leading_space;
while ($line = <>) {
next if $line =~ /^[\s\t]*$/;
$line =~ s/^([ \t]*)(\d+\. |[\*\+\-] )?/${1}1. /;
$line =~ /^([ \t]*)([\*\+\-]|\d+\.)(\.?\s*)(.*)/;
$leading_space = $1;
$marker = $2;
$item = " " . $4;
$leading_space =~ s/\t/ /g; # Convert tabs to spaces
if ( $line !~ /^([ \t]*)([\*\+\-]|\d+\.)/) {
#$result .= "a";
# not a list line
$result .= $line;
$marker = $last_marker{$g_list_level};
} elsif (length($leading_space) > length($last_leading_space)+3) {
# New list level
#$result .= "b";
$g_list_level++;
$marker =~ s{
(\d+)
}{
# Reset count
"1";
}ex;
$last_leading_space = $leading_space;
$result .= "\t" x $g_list_level;
$result .= $marker . $item . "\n";
} elsif (length($leading_space)+3 < length($last_leading_space)) {
#$result .= "c";
# back to prior list level
$g_list_level = length($leading_space) / 4;
# update marker
$marker = $last_marker{$g_list_level};
$marker =~ s{
(\d+)
}{
$1+1;
}ex;
$last_leading_space = $leading_space;
$result .= "\t" x $g_list_level;
$result .= $marker . $item . "\n";
} else {
# No change in level
#$result .= "d";
# update marker if it exists
if ($last_marker{$g_list_level} ne "") {
$marker = $last_marker{$g_list_level};
$marker =~ s{
(\d+)
}{
$1+1;
}ex;
}
$last_leading_space = $leading_space;
$result .= "\t" x $g_list_level;
$result .= $marker . $item . "\n";
}
$last_marker{$g_list_level} = $marker;
}
print $result;