インデントを入れる。
とあるプログラムを拾ってきて頑張って読んでいるのだが激烈に読みにくい。いろいろ理由はあるがその理由の一つとしてインデントが全くない。ずれているとかでなく本当に全くない。しかし逆に中途半端にあるわけでないので簡単に自動化出来た。折角作ったので公開。
void insertIndent( std::istream& in, std::ostream& out ) { int indentLevel(0); bool bReturn(false); char c0(0),c(0); bool bInComment1(false);// bool bInComment2(false);/**/ bool bInString(false); while( in.get( c ) ){ if( bInComment1 ){ if( c == '\n' ){ bInComment1 = false; } }else{ if( c == '/' && c0 == '/' ){ bInComment1 = true; } } if( bInComment2 ){ if( c0 == '*' && c == '/' ){ bInComment2 = false; } }else{ if( c0 == '/' && c == '*' ){ bInComment2 = true; } } const bool bInComment = bInComment1 || bInComment2; if( !bInComment && c == '\"' ){ bInString = !bInString; } if( !bInComment && !bInString && c == '}' ){ --indentLevel; } if( bReturn ){ for( int indent = 0; indent < indentLevel; ++indent ){ out << '\t'; } bReturn = false; } if( !bInComment && !bInString && c == '{' ){ ++indentLevel; } out << c; if( c == '\n' ){ bReturn = true; } c0 = c; } }
考え方は単純で、'{'が来たらインデントを増やして'}'が来たらインデントを減らす。入れるタイミングは改行後に挿入する。ただし、コメント内部と文字列内部は無視する。
本当ならもっと気をつけることもありそうだがとりあえず欲しい結果は得られたので作り込み(?)は終了。
なお、製作時間は30分もかかっていないので品質の程は全く保証できません(^^;