缘起
我们写HTML代码的时候,有时要在好长一段代码中插入两个tag,例如行11和行27:
结果我们神奇地发现sublime text 不会帮你缩进,这意味着11~26共n = 15 行要你手动缩进,即按n = 15 个Tab, n-1 = 14 个 “↓”以及若干个“←”,你大约需要按3n下键盘。
一开始你还能接受,但是越按你越烦躁,尤其是n > 100 的时候,你开始抓狂,甚至感到:
于是……我写了一个神奇的小工具!
另一个解决办法
之前一直不知道,原来在sublime中同时选中很多行,按table,可以同时在选中的每一行前面插入一个table(制表符).
工具演示
为了显示效果,我先把所有的缩进删掉:
然后我们跑一跑这个小程序:
再看看效果:
我们偷偷地发现了很多勇敢的缩进……
注意事项
1.所有缩进都应为TAB
2.结束tag 必须写完整,不能漏掉’/’
如果执行结果异常,很可能是上述两个条件不满足
例如变成这样子:
源代码
可以从gihub:https://github.com/LoHiaufung/Lazy.git下载,文件名为”autoIndent.cpp”或直接从下面复制粘贴。
//*********************************************
// Copyright@LoHiaufung
// 2016.09.24 at SYSU
//
// 注意事项:
// 1.所有缩进都应为TAB
// 2.结束tag /> 和 </ 必须写完整
// 如果执行结果异常,很可能是上述两个条件不满足
//*********************************************
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
using namespace std;
bool isLineBegin(int c, const string&);
int main(){
string fname;
cout << "Enter the file name: ";
cin >> fname;
ifstream infile(fname.c_str());
if (!infile) {
cout << "No this file!" << endl;
} else {
char c;
char c2;
int tabAmount = 0;
string buff;
ofstream oufile("tmpFile");
if (!oufile) {
cout << "Unknown error!" << endl;
return 1;
}
while (!infile.eof()) {
getline(infile, buff);
for (int j = 0; j < buff.length(); j++) {
c = buff[j];
// discard all original indent Tab
if (' ' != c) {
// c's case 1:
if ('<' == c) {
c2 = buff[j+1];
j++;
// meet end tag "</"
if ('/' == c2) {
tabAmount--;
// at the line begin, output indent Tab
// else not output Tab
if (true == isLineBegin(j - 1, buff)) {
for (int i = 0; i < tabAmount ; ++i) {
oufile << '\t';
}
}
// meeting comment " <!
} else if ('!' == c2) {
// at the line begin, output indent Tab
// else not output Tab
if (true == isLineBegin(j - 1, buff)) {
for (int i = 0; i < tabAmount ; ++i) {
oufile << '\t';
}
}
// meeting neither " <! " nor "</ "
// which means meeting a begin tag '<'
} else {
// at the line begin, output indent Tab
// meeting a begin tag '<, counter add 1
if (true == isLineBegin(j - 1, buff)) {
for (int i = 0; i < tabAmount ; ++i) {
oufile << '\t';
}
}
tabAmount++;
}
// write the not Tab char to temp file
oufile << c << c2;
// c's case s:
} else if ('/' == c){
c2 = buff[j+1];
j++;
// meet end tag "/>"
if ('>' == c2) {
tabAmount--;
}
// write the not Tab char to temp file
oufile << c << c2;
// default case:
} else {
oufile << c;
}
}
}
// the function getline() discarded '\n', we repick it
oufile << endl;
}
// write to the original file from temp file
ifstream infile2("tmpFile");
ofstream outfile2(fname.c_str());
while (!infile2.eof()) {
getline(infile2, buff);
outfile2 << buff << endl;
}
// delete temp file
oufile.close();
infile2.close();
remove("tmpFile");
}
return 0;
}
bool isLineBegin(int c, const string& str) {
for (int i = 0; i < c; i++) {
if ('\t' != str[i]) {return false;}
}
return true;
}