ソース整形2

  • 目的:

ソースコードのインデントを変更し、見やすくする。

  • 実現方法:

ソースファイルのデータを一行ずつ取得し、
中かっこの有無でインデントを進めるか判断するようにした。

  • 成果物:
using System;
using System.IO;
using System.Linq;
using EnvDTE; //Add Reference to EnvDTE,EnvDTE80
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string data = "";
            StringBuilder result = new StringBuilder();
            List<string> indexIncreaseData = new List<string> { "{", "if" };
            List<string> indexDecreaseData = new List<string> { "}"};
            int indentCount = 0;

            StreamReader sr = new StreamReader(@"C:\test\src.txt");
            while (!sr.EndOfStream)
            {
                data = sr.ReadLine();

                // 先頭の空白を除去
                data = Regex.Replace(data, "^ +", "");

                if (data.Split(new char[] { ' ' }).Where(n => indexDecreaseData.Contains(n)).Count() == 0)
                {
                    data = new String(' ', (indentCount * 4)) + data;
                }

                if (data.Split(new char[] { ' ' }).Where(n => indexIncreaseData.Contains(n)).Count() > 0)
                {
                    // indent proceed
                    indentCount++;
                }

                if (data.Split(new char[] { ' ' }).Where(n => indexDecreaseData.Contains(n)).Count() > 0)
                {
                    // indent back
                    data = new String(' ', (--indentCount * 4)) + data;
                }

                result.AppendLine(data);
            }

            StreamWriter sw = new StreamWriter(@"C:\test\src1.cs");

            sw.Write(result.ToString());

            sw.Close();

        }
    }
}
  • ナレッジ:
  1. using EnvDTE; //Add Reference to EnvDTE,EnvDTE80

 DTE:"Development Tools Extensibility" の略語
 →Visual Studioコアオートメーションのオブジェクトとメンバを含むアセンブリラップCOMライブラリです。
  →Visual Studioからアクティブなウインドウやアプリケーションを制御可能。

  1. COM:Component Object Modelの略語

 →特定のプログラミングに依存せず利用できる、バイナリコード単位のインターフェース。
 

  1. List indexIncreaseData = new List { "{", "if" };

 Listの初期化でいつも間違える。new Listの後に()は不要。

  1. 同じ文字列を指定回数繰り返した文字の作成方法

  一文字の場合:new String('a', 10)
 複数文字の場合:(new string('a', 10)).Replace("a", "hoge");

  • お世話になったサイト:
  1. DTEの意味

ttps://stackoverflow.com/questions/17239760/what-is-the-visual-studio-dte
ttps://docs.microsoft.com/en-us/dotnet/api/envdte.document?view=visualstudiosdk-2017

  1. 正規表現による置換

ttps://dobon.net/vb/dotnet/string/replace.html

  1. 同じ文字列を指定回数繰り返した文字の作成方法

ttps://dobon.net/vb/dotnet/string/repeat.html