- Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathrevim
executable file
·102 lines (81 loc) · 2.05 KB
/
revim
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
#!/usr/bin/perl
# vim:set ft=perl ts=4 sw=4 et fdm=marker:
#
# revim - add customized vim modeline for given files
# Copyright (c) 2010 chaoslawful
use strict;
use warnings;
use Getopt::Std;
my%opts;
getopts('hm:', \%opts);
if($opts{h} or !@ARGV) {
die<<EOT;
Usage: revim [-m <vim modeline>] src/*
In <vim modeline>, the following placeholder(s) can be used:
* %t - Expands to vim file type. E.g. 'c' for .c files, 'perl' for .pl files.
EOT
}
my$vim_ml = $opts{m} || "vim:set ft=%t ts=4 sw=4 et fdm=marker:";
my@files = mapglob, @ARGV;
formy$file (@files) {
nextif-d$file;
my ($ft, $ml) = detect_filetype($file, $vim_ml);
nextif !defined($ft);
revim($file, $ml);
}
subdetect_filetype
{
my ($f, $tmpl) = @_;
my ($ft, $lcmt, $rcmt);
my%phs;
if($f =~ /.([cC]|[hH])$/) {
$ft = "c";
($lcmt, $rcmt) = ("/* ", " */");
} elsif($f =~ /.(pl|pm)$/) {
$ft = "perl";
($lcmt, $rcmt) = ("# ", "");
} elsif($f =~ /.t_?$/) {
# assuming tests are written in perl
$ft = "perl";
($lcmt, $rcmt) = ("# ", "");
} else {
$ft = undef;
}
if(defined($ft)) {
%phs = (
"%t"=>$ft,
);
$tmpl =~ s/(%[a-z])/$phs{$1}/ge;
$tmpl =~ s/^/$lcmt/;
$tmpl =~ s/$/$rcmt/;
return ($ft, $tmpl);
}
return (undef, undef);
}
subrevim
{
my ($f, $ml) = @_;
my@lines;
openmy$in, $f
ordie"Can't open $f for reading: $!";
while(<$in>) {
push(@lines, $_);
}
close$in;
my@nlines = grep {!/\bvim?:/} @lines;
warn"revim: $f:\tremoved existing vim modeline.\n"
if(@nlines != @lines);
if($nlines[0] =~ /^#!/) { # has shebang line
my$shebang = shift@nlines;
unshift(@nlines, $shebang, "$ml\n");
} else {
unshift(@nlines, "$ml\n");
}
my$text = join'', @nlines;
openmy$out, "> $f"
ordie"Can't open $f for writing: $!";
binmode$out;
print$out$text;
close$out;
warn"revim: $f:\tdone.\n";
}