Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

autoformat code from command line

Tags:

Is it possible to run auto-format code for all or for specific file in solution, like (Ctrl+K, Ctrl+D) formatting in Visual Studio but from it`s command line? Or use Resharper's cleanup also from command line for solution files?

like image 693
Александр Киричек Avatar asked Mar 22 '13 22:03

Александр Киричек


People also ask

How do you autoformat codes?

Automatically reformat code on savePress Ctrl+Alt+S to open the IDE settings and select Tools | Actions on Save. Enable the Reformat code option.

What is the shortcut for beautify code?

VSCode – Code Formatting Shortcuts The code formatting is available in Visual Studio Code (VSCode) through the following shortcuts or key combinations: On Windows Shift + Alt + F. On macOS Shift + Option + F. On Linux Ctrl + Shift + I.

What is the command for formatting?

The format command is a Command Prompt command used to format a specified partition on a hard drive (internal or external), floppy disk, or flash drive to a specified file system. You can also format drives without using a command.

How do you autoformat in VS?

Click menu Edit → Advanced → *Format Selection, or press Ctrl + K , Ctrl + F . Format Selection applies the smart indenting rules for the language in which you are programming to the selected text.


2 Answers

Create your own tool. You can use EnvDTE, EnvDTE80 to create Visual Studio project and load the files you want to format on the fly. Once you are done delete the Visual Studio project. You can specify to not to show Visual Studio window while formatting. If you are interested let me know I can give you some code to make this work.

UPDATE: I am copying the code I have. I used it to format *.js files. I removed some code which you don't need. Feel free to ask if it doesn't work.

    //You need to make a reference to two dlls:     envdte     envdte80        void FormatFiles(List<FileInfo> files)     {                //If it throws exeption you may want to retry couple more times         EnvDTE.Solution soln = System.Activator.CreateInstance(Type.GetTypeFromProgID("VisualStudio.Solution.11.0")) as EnvDTE.Solution;         //try this if you have Visual Studio 2010         //EnvDTE.Solution soln = System.Activator.CreateInstance(Type.GetTypeFromProgID("VisualStudio.Solution.10.0")) as EnvDTE.Solution;         soln.DTE.MainWindow.Visible = false;         EnvDTE80.Solution2 soln2 = soln as EnvDTE80.Solution2;         //Creating Visual Studio project         string csTemplatePath = soln2.GetProjectTemplate("ConsoleApplication.zip", "CSharp");         soln.AddFromTemplate(csTemplatePath, tempPath, "FormattingFiles", false);         //If it throws exeption you may want to retry couple more times         Project project = soln.Projects.Item(1);          foreach (FileInfo file in files)         {             ProjectItem addedItem;             bool existingFile = false;             int _try = 0;             while (true)             {                             try                 {                     string fileName = file.Name;                     _try++;                     if (existingFile)                     {                         fileName = file.Name.Substring(0, (file.Name.Length - file.Extension.Length) - 1);                         fileName = fileName + "_" + _try + file.Extension;                     }                     addedItem = project.ProjectItems.AddFromTemplate(file.FullName, fileName);                     existingFile = false;                     break;                 }                 catch(Exception ex)                 {                     if (ex.Message.Contains(file.Name) && ex.Message.Contains("already a linked file"))                     {                         existingFile = true;                     }                 }             }             while (true)             {                 //sometimes formatting file might throw an exception. Thats why I am using loop.                 //usually first time will work                 try                 {                     addedItem.Open(Constants.vsViewKindCode);                     addedItem.Document.Activate();                     addedItem.Document.DTE.ExecuteCommand("Edit.FormatDocument");                     addedItem.SaveAs(file.FullName);                     break;                 }                 catch                 {                     //repeat                 }             }         }         try         {             soln.Close();             soln2.Close();             soln = null;             soln2 = null;         }         catch         {             //for some reason throws exception. Not all the times.             //if this doesn't closes the solution CleanUp() will take care of this thing         }         finally         {             CleanUp();         }     }         void CleanUp()     {         List<System.Diagnostics.Process> visualStudioProcesses = System.Diagnostics.Process.GetProcesses().Where(p => p.ProcessName.Contains("devenv")).ToList();         foreach (System.Diagnostics.Process process in visualStudioProcesses)         {             if (process.MainWindowTitle == "")             {                 process.Kill();                 break;             }         }         tempPath = System.IO.Path.GetTempPath();         tempPath = tempPath + "\\FormattingFiles";         new DirectoryInfo(tempPath).Delete(true);     }  

I hope this helps.

like image 72
Dilshod Avatar answered Sep 27 '22 19:09

Dilshod


To format net core c# source, use https://github.com/dotnet/format

Install the tool as per the project readme.

I had a need to format some code files I was generating from Razor templates. I created a shell .CSProj file in the root of my output folder, using dotnet new console which gives you this basic file:

<Project Sdk="Microsoft.NET.Sdk">    <PropertyGroup>     <OutputType>Exe</OutputType>     <TargetFramework>netcoreapp2.2</TargetFramework>     <RootNamespace>dotnet_format</RootNamespace>   </PropertyGroup>  </Project> 

Then run dotnet format from a VS command prompt in that folder. It will recurse into sub-directories and format everything it finds. To format specific files you can provide a list of filenames with the --files switch.

like image 26
Daz Avatar answered Sep 27 '22 20:09

Daz