Beautify your code VB (VBS) code formatting implementation code

Time:2021-9-22

However, vb.net does have many new functions that VB6 does not have. The automatic typesetting of code is one, which is the function we want to realize today – VB code formatting.
Let’s look at the effect:

Before formatting:

Copy codeThe code is as follows:

For i = 0 To WebBrowser1.Document.All.length – 1
If WebBrowser1.Document.All(i).tagName = “HTML” Then
strContent = strContent & WebBrowser1.Document.All(i).innerHTML
Exit For
End If
Next


After formatting:

Copy codeThe code is as follows:

For i = 0 To WebBrowser1.Document.All.length – 1
If WebBrowser1.Document.All(i).tagName = “HTML” Then
strContent = strContent & WebBrowser1.Document.All(i).innerHTML
Exit For
End If
Next


C + + level has been very bad, so I chose C + + as the training language to write this simple VB code formatting tool. The code is not long, only more than 200 lines, which is implemented in standard C + +. In addition, in order to completely eliminate the idea that some people continue to use VC6, the auto keyword is used, hey hey. Well, cut the crap and go straight to the code:

Copy codeThe code is as follows:

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<fstream>
using namespace std;

//Determine whether it is a space
bool isSpace(const char chr)
{
return chr == ‘ ‘;
}

//Remove left margin
void leftTrim(string &str)
{
string::iterator p=find_if(str.begin(),str.end(),not1(ptr_fun(isSpace)));
str.erase(str.begin(),p);
}

//Remove right margin
void rightTrim(string& str)
{
string::reverse_iterator p=find_if(str.rbegin(),str.rend(),not1(ptr_fun(isSpace)));
str.erase(p.base(),str.end());
}

//Remove the blank on both sides
string trim(const string& str)
{
string strRet(str);
leftTrim(strRet);
rightTrim(strRet);
return strRet;
}

//Convert to lowercase
string toLower(const string& str)
{
string strRet(str);
transform(strRet.begin(),strRet.end(),strRet.begin(),(int (*)(int))tolower);
return strRet;
}

//Determines whether to start with the given keyword
bool startWith(const vector<string>& vecCodeKeywords,const string& strCodeLine)
{
string line(toLower(strCodeLine));
for(auto keyword=vecCodeKeywords.begin(); keyword!=vecCodeKeywords.end(); keyword++)
if(line.find(*keyword + ” “)==0 || line== *keyword)
return true;
return false;
}

//If… Then… Special inspection
bool checkForIfThen(const string& strCodeLine)
{
vector<string> vecIf;
vecIf.push_back(“if”);
if(!startWith(vecIf,strCodeLine))
return false;
if(toLower(strCodeLine).find(“then”)==string::npos)
return false;
string line(trim(toLower(strCodeLine)));
if(line.length()<7)
return false;
return !(line.substr(line.length()-4,4) == “then”);
}

//Format the given row and mark the relevant information
int formatAndMarkLine(string& strCodeLine)
{
//Starting keywords “if”, “for”, “private | friend | public] [static] [sub | function | property | type],” with “,” do “,” select “
vector<string> vecStartKeywords;
vecStartKeywords.push_back(“if”);
vecStartKeywords.push_back(“for”);
vecStartKeywords.push_back(“with”);
vecStartKeywords.push_back(“do”);
vecStartKeywords.push_back(“select”);
string _ pfp[] = {“private”,”friend”,”public”}; // Can be empty
string _ s[] = {“static”}; // Can be empty
string _sfpt[] = {“sub”,”function”,”property”,”type”};
//_ pfp _ S is empty
for(auto i=0; i<4; i++)
vecStartKeywords.push_back(_sfpt[i]);
//_ PFP is null
for(auto i=0; i<4; i++)
vecStartKeywords.push_back(_s[0] + ” ” + _sfpt[i]);
//_ S is empty
for(auto i=0; i<4; i++)
for(auto j=0; j<3; j++)
vecStartKeywords.push_back(_pfp[j] + ” ” + _sfpt[i]);
//_ pfp _ S is not empty
for(auto i=0; i<4; i++)
for(auto j=0; j<3; j++)
vecStartKeywords.push_back(_pfp[j] + ” ” + _s[0] + ” ” + _sfpt[i]);

//Termination keywords “end if”, “next”, “end [sub | function | property | type],” end with “,” loop “,” end select “
vector<string> vecEndKeywords;
vecEndKeywords.push_back(“end if”);
vecEndKeywords.push_back(“next”);
vecEndKeywords.push_back(“end with”);
vecEndKeywords.push_back(“loop”);
vecEndKeywords.push_back(“end select”);
for(auto i=0; i<4; i++)
vecEndKeywords.push_back(“end ” + _sfpt[i]);

//Intermediate keywords “else”, “else if”, “case”
vector<string> vecMiddleKeywords;
vecMiddleKeywords.push_back(“else”);
vecMiddleKeywords.push_back(“elseif”);
vecMiddleKeywords.push_back(“case”);

auto mark = 0;
char c;
auto n=0;
string line;
auto quote = false; // Double quote status
/*
Rules:
Single quotation marks inside double quotation marks are not considered, otherwise the following contents become comments
*/
auto space = true; // Whitespace status false indicates that no whitespace was encountered
while((c=strCodeLine[n++]))
{
switch(c)
{
case ‘ ‘:
case ‘\t’:
if(quote)
{
line += c;
}
else
{
if(!space)
{
line += c;
space = true;
}
}
break;
case ‘”‘:
space = false;
quote = !quote;
line += c;
break;
case ‘\”:
space = false;
if(quote)
line += c;
else
{
line += ” ‘”; // Msgbox (“itianda”) ‘there is a space before the single quotation mark
While ((C = strcodeline [n + +]) / / directly append the contents after single quotation marks
line += c;
continue;
}
break;
case ‘_’: // Continuation character
space = false;
line += c;
if(!quote && n==(int)strCodeLine.length() && n-2>=0 && strCodeLine[n-2]==’ ‘)
mark |= 0x80; //10000000
break;
default:
space = false;
line += c;
}
}
strCodeLine = line;
if(startWith(vecStartKeywords,line) && !checkForIfThen(line))
mark += 1;
if(startWith(vecEndKeywords,line))
mark += 2;
if(startWith(vecMiddleKeywords,line))
mark += 3;
return mark;
}

//Split code by line
void splitToLines(const string& strCode, vector<string>& vecCodeLines)
{
vecCodeLines.clear();
char c;
auto n=0;
string line;
while((c=strCode[n++]))
{
if(c!=’\n’)
line += c;
else
{
vecCodeLines.push_back(line);
line.clear();
}
}
If (line. Length()) / / if the last line is empty, it will be rounded off
vecCodeLines.push_back(line);
}

//Format the given code
void formatCode(string& strCode,const string& strIndentString)
{
vector<string> vecLines; // All code lines
splitToLines(strCode,vecLines); // Get all lines of code
if(vecLines.size()==0)
{
return;
}
auto indentLevel = 0; // Indent level
auto incompleteLine = false; // Is it an open line
for(auto line=vecLines.begin(); line!=vecLines.end(); line++)
{
auto indent = indentLevel;
auto mask = formatAndMarkLine(*line);
switch(mask & ~0x80)
{
case 0:
break;
case 1:
indentLevel++;
break;
case 2:
indent–;
indentLevel–;
break;
case 3:
indent–;
break;
}
if(incompleteLine)
indent++;
incompleteLine = mask & 0x80;
if(indent<0)
indent = 0;
if(indentLevel<0)
indentLevel = 0;
string strIndent;
for(auto i=0; i<indent; i++)
strIndent += strIndentString;
*line = strIndent + *line;
}
strCode.clear();
for(auto line=vecLines.begin(); line!=vecLines.end(); line++)
strCode+= trim(*line).length() ? “\n” + *line : “”;
}

int main()
{
string indentString = ” “;
string code;
ifstream inputFile(“in.txt”);
string line;
while(getline(inputFile,line))
{
code += line + “\n”;
}
formatCode(code,indentString);
ofstream outputFile(“out.txt”);
outputFile<<“Your beautiful code:”<<endl<<
“——————————————————————-“
<<endl<<code<<endl<<endl<<
“——————————————————————-“
<<endl<<
” Formatted by itianda’s PUVBFormatter”
<<endl<<
” http://www.programup.com/blog”
<<endl;
return 0;
}


After reading the code, you should know how basic this is. Many details are not handled carefully. For example, colon connecting multiple lines is not considered, so if you want to use this tool, please do not write multiple lines into one line!

to update:
Add the keyword select case… End select. Thank jww2999 netizens for their feedback.
This article is from itianda’s blog

Recommended Today

Seven Python code review tools recommended

althoughPythonLanguage is one of the most flexible development languages at present, but developers often abuse its flexibility and even violate relevant standards. So PythoncodeThe following common quality problems often occur: Some unused modules have been imported Function is missing arguments in various calls The appropriate format indentation is missing Missing appropriate spaces before and after […]