public void TestAttributeSortingOptionHandling() { string testInput = MethodBase.GetCurrentMethod().Name + ".xaml"; var stylerOptions = new StylerOptions { AttributeOrderClass = "x:Class", AttributeOrderWpfNamespace = "xmlns, xmlns:x", AttributeOrderKey = "Key, x:Key, Uid, x:Uid", AttributeOrderName = "Name, x:Name, Title", AttributeOrderAttachedLayout = "Grid.Column, Grid.ColumnSpan, Grid.Row, Grid.RowSpan, Canvas.Right, Canvas.Bottom, Canvas.Left, Canvas.Top", AttributeOrderCoreLayout = "MinWidth, MinHeight, Width, Height, MaxWidth, MaxHeight, Margin", AttributeOrderAlignmentLayout = "Panel.ZIndex, HorizontalAlignment, VerticalAlignment, HorizontalContentAlignment, VerticalContentAlignment", AttributeOrderOthers = "Offset, Color, TargetName, Property, Value, StartPoint, EndPoint, PageSource, PageIndex", AttributeOrderBlendRelated = "mc:Ignorable, d:IsDataSource, d:LayoutOverrides, d:IsStaticText" }; var styler = StylerService.CreateInstance(stylerOptions); DoTest(testInput, styler); }
private void BatchProcessSolution(Solution sln, StylerService styler) { foreach (var prj in sln.GetAllProjects()) { BatchProcessProject(prj, styler); } }
private RdTask <RdXamlStylerFormattingResult> PerformReformatHandler( Lifetime requestLifetime, RdXamlStylerFormattingRequest request) { return(Task.Run(() => { _lifetime.ThrowIfNotAlive(); // Fetch settings var settings = _solution.GetSettingsStore().SettingsStore.BindToContextLive(_lifetime, ContextRange.Smart(_solution.ToDataContext())); var stylerOptions = StylerOptionsFactory.FromSettings( settings, _solution, null, request.FilePath); // Bail out early if needed if (stylerOptions.SuppressProcessing || !stylerOptions.FormatOnSave) { return new RdXamlStylerFormattingResult(false, false, ""); } // Perform styling var styler = new StylerService(stylerOptions); var formattedText = styler.StyleDocument(request.DocumentText).Replace("\r\n", "\n"); if (request.DocumentText == formattedText) { return new RdXamlStylerFormattingResult(true, false, ""); } return new RdXamlStylerFormattingResult(true, true, formattedText); }, requestLifetime).ToRdTask()); }
private static Func <Action> SetupExecuteContinuation(Document document, IStylerOptions stylerOptions) { ThreadHelper.ThrowIfNotOnUIThread(); var textDocument = (TextDocument)document.Object("TextDocument"); EditPoint startPoint = textDocument.StartPoint.CreateEditPoint(); EditPoint endPoint = textDocument.EndPoint.CreateEditPoint(); string xamlSource = startPoint.GetText(endPoint); return(() => { // this part can be executed in parallel. StylerService styler = new StylerService(stylerOptions); xamlSource = styler.StyleDocument(xamlSource); return () => { // this part should be executed sequentially. ThreadHelper.ThrowIfNotOnUIThread(); const int vsEPReplaceTextKeepMarkers = 1; startPoint.ReplaceText(endPoint, xamlSource, vsEPReplaceTextKeepMarkers); }; }); }
protected override void Run() { var document = IdeApp.Workbench.ActiveDocument; if (!StylerOptionsConfiguration.IsFormatableDocument(document)) { return; } var stylerOptions = StylerOptionsConfiguration.GetOptionsForDocument(document.FileName, document.Owner as Project); var styler = new StylerService(stylerOptions); if (document.Editor is null) { var textBuffer = document.TextBuffer; var currentSnapshot = textBuffer.CurrentSnapshot; var rawText = currentSnapshot.GetText(); var styledText = styler.StyleDocument(rawText); var replaceSpan = new Span(0, rawText.Length); textBuffer.Replace(replaceSpan, styledText); } else { var editor = document.Editor; using (editor.OpenUndoGroup()) { var styledText = styler.StyleDocument(editor.Text); editor.Text = styledText; } } document.IsDirty = true; }
private void Execute(Document document) { if (!IsFormatableDocument(document)) { return; } Properties xamlEditorProps = _dte.Properties["TextEditor", "XAML"]; var stylerOptions = GetDialogPage(typeof(PackageOptions)).AutomationObject as IStylerOptions; var solutionPath = String.IsNullOrEmpty(_dte.Solution?.FullName) ? String.Empty : Path.GetDirectoryName(_dte.Solution.FullName); var configPath = GetConfigPathForItem(document.Path, solutionPath); if (configPath != null) { stylerOptions = ((StylerOptions)stylerOptions).Clone(); stylerOptions.ConfigPath = configPath; } if (stylerOptions.UseVisualStudioIndentSize) { int outIndentSize; if (Int32.TryParse(xamlEditorProps.Item("IndentSize").Value.ToString(), out outIndentSize) && (outIndentSize > 0)) { stylerOptions.IndentSize = outIndentSize; } } stylerOptions.IndentWithTabs = (bool)xamlEditorProps.Item("InsertTabs").Value; StylerService styler = new StylerService(stylerOptions); var textDocument = (TextDocument)document.Object("TextDocument"); TextPoint currentPoint = textDocument.Selection.ActivePoint; int originalLine = currentPoint.Line; int originalOffset = currentPoint.LineCharOffset; EditPoint startPoint = textDocument.StartPoint.CreateEditPoint(); EditPoint endPoint = textDocument.EndPoint.CreateEditPoint(); string xamlSource = startPoint.GetText(endPoint); xamlSource = styler.StyleDocument(xamlSource); startPoint.ReplaceText(endPoint, xamlSource, 0); if (originalLine <= textDocument.EndPoint.Line) { textDocument.Selection.MoveToLineAndOffset(originalLine, originalOffset); } else { textDocument.Selection.GotoLine(textDocument.EndPoint.Line); } }
private void BatchProcessProject(Project prj, StylerService styler) { LoggingService.LogDebug($"Processing {prj.Name} project..."); foreach (var file in prj.Files.Where(f => f.Name.EndsWith(".xaml", System.StringComparison.OrdinalIgnoreCase)).ToArray()) { ProcessFileInPlace(file, styler); } }
private static void DoTest(StylerOptions stylerOptions, string testFileBaseName, string expectedSuffix) { var stylerService = new StylerService(stylerOptions, new XamlLanguageOptions() { IsFormatable = true }); DoTest(stylerService, stylerOptions, testFileBaseName, expectedSuffix); }
private void DoTest(string testInput, StylerService styler) { string actualOutputFile = testInput.Replace(".xaml", "_output.xaml"); string expectedOutputFile = testInput.Replace(".xaml", "_output_expected.xaml"); string output = styler.ManipulateTreeAndFormatFile(testInput); File.WriteAllText(actualOutputFile, output); Assert.IsTrue(FileCompare(actualOutputFile, expectedOutputFile)); }
public void TestMarkupExtensionHandling() { string testInput = MethodBase.GetCurrentMethod().Name + ".xaml"; var stylerOptions = new StylerOptions { FormatMarkupExtension = true }; var styler = StylerService.CreateInstance(stylerOptions); DoTest(testInput, styler); }
/// <summary> /// Parse input document and verify output against /// </summary> /// <param name="styler"></param> /// <param name="callerMemberName"></param> private void DoTest(StylerService styler, [System.Runtime.CompilerServices.CallerMemberName] string callerMemberName = "") { var testFileBaseName = Path.Combine("TestFiles", callerMemberName); // Excercise stylerService using supplied test xaml data string actualOutput = styler.ManipulateTreeAndFormatInput(File.ReadAllText(testFileBaseName + ".testxaml")); // Write output to ".actual" file for further investigation File.WriteAllText(testFileBaseName + ".actual", actualOutput, Encoding.UTF8); // Check result Assert.That(actualOutput, Is.EqualTo(File.ReadAllText(testFileBaseName + ".expected"))); }
public XamlStylerConsole(Options options) { this.options = options; IStylerOptions stylerOptions = new StylerOptions(); if (this.options.Configuration != null) { stylerOptions = this.LoadConfiguration(this.options.Configuration); } this.stylerService = new StylerService(stylerOptions); }
public bool TryFormatXaml(ref string xamlText, IStylerOptions stylerOptions) { var stylerService = new StylerService(stylerOptions); var styledText = stylerService.StyleDocument(xamlText); if (xamlText == styledText) { return(false); } xamlText = styledText; return(true); }
private void Execute(Document document) { if (!IsFormatableDocument(document)) { return; } Properties xamlEditorProps = _dte.Properties["TextEditor", "XAML"]; var stylerOptions = GetDialogPage(typeof(PackageOptions)).AutomationObject as IStylerOptions; var solutionPath = String.IsNullOrEmpty(_dte.Solution?.FullName) ? String.Empty : Path.GetDirectoryName(_dte.Solution.FullName); var project = _dte.ActiveDocument?.ProjectItem?.ContainingProject; var configPath = GetConfigPathForItem(document.Path, solutionPath, project); if (configPath != null) { stylerOptions = ((StylerOptions)stylerOptions).Clone(); stylerOptions.ConfigPath = configPath; } if (stylerOptions.UseVisualStudioIndentSize) { int outIndentSize; if (Int32.TryParse(xamlEditorProps.Item("IndentSize").Value.ToString(), out outIndentSize) && (outIndentSize > 0)) { stylerOptions.IndentSize = outIndentSize; } } stylerOptions.IndentWithTabs = (bool)xamlEditorProps.Item("InsertTabs").Value; StylerService styler = new StylerService(stylerOptions); var textDocument = (TextDocument)document.Object("TextDocument"); EditPoint startPoint = textDocument.StartPoint.CreateEditPoint(); EditPoint endPoint = textDocument.EndPoint.CreateEditPoint(); string xamlSource = startPoint.GetText(endPoint); xamlSource = styler.StyleDocument(xamlSource); const int vsEPReplaceTextKeepMarkers = 1; startPoint.ReplaceText(endPoint, xamlSource, vsEPReplaceTextKeepMarkers); }
protected override Action <ITextControl> ExecutePsiTransaction( [NotNull] ISolution solution, [NotNull] IProgressIndicator progress) { // Fetch settings var lifetime = solution.GetLifetime(); var settings = solution.GetSettingsStore().SettingsStore.BindToContextLive(lifetime, ContextRange.Smart(solution.ToDataContext())); var stylerOptions = StylerOptionsFactory.FromSettings( settings, solution, _dataProvider.Project, _actionAppliesTo == ActionAppliesTo.File ? _dataProvider.SourceFile as IPsiSourceFileWithLocation // Traverse config chain from file path : null // Traverse config chain from project path ); // Bail out early if needed if (stylerOptions.SuppressProcessing) { return(null); } // Perform styling var styler = new StylerService(stylerOptions, new XamlLanguageOptions { IsFormatable = true }); var psiSourceFiles = _actionAppliesTo == ActionAppliesTo.File ? _dataProvider.Document.GetPsiSourceFiles(solution).AsIReadOnlyList() : _actionAppliesTo == ActionAppliesTo.Project ? _dataProvider.Project.GetAllProjectFiles(it => it.LanguageType.Is <XamlProjectFileType>()).SelectMany(file => file.ToSourceFiles().AsIReadOnlyList()) : _dataProvider.Solution.GetAllProjects().SelectMany(project => project.GetAllProjectFiles(it => it.LanguageType.Is <XamlProjectFileType>()).SelectMany(file => file.ToSourceFiles().AsIReadOnlyList())); foreach (var prjItem in psiSourceFiles) { foreach (var file in prjItem.GetPsiFiles <XamlLanguage>()) { var sourceFile = file.GetSourceFile(); if (sourceFile?.Document != null) { var oldText = sourceFile.Document.GetText(); var newText = styler.StyleDocument(oldText).Replace("\r\n", "\n"); file.ReParse(new TreeTextRange(new TreeOffset(0), new TreeOffset(oldText.Length)), newText); } } } return(null); }
/// <summary> /// Style input document and verify output against expected /// </summary> /// <param name="stylerOptions"></param> /// <param name="testFileBaseName"></param> /// <param name="expectedSuffix"></param> private static void DoTest(StylerOptions stylerOptions, string testFileBaseName, string expectedSuffix) { var stylerService = new StylerService(stylerOptions); var testFileResultBaseName = expectedSuffix != null ? testFileBaseName + "_" + expectedSuffix : testFileBaseName; // Excercise stylerService using supplied test xaml data string actualOutput = stylerService.StyleDocument(File.ReadAllText(testFileBaseName + ".testxaml")); // Write output to ".actual" file for further investigation File.WriteAllText(testFileResultBaseName + ".actual", actualOutput, Encoding.UTF8); // Check result Assert.That(actualOutput, Is.EqualTo(File.ReadAllText(testFileResultBaseName + ".expected"))); }
public void TestAxamlNoEscaping() { var stylerOptions = this.GetLegacyStylerOptions(); var stylerService = new StylerService(stylerOptions, new XamlLanguageOptions() { IsFormatable = true, UnescapedAttributeCharacters = { '>' } }); FileHandlingIntegrationTests.DoTest(stylerService, stylerOptions, Path.Combine("TestFiles", "TestAxamlNoEscaping"), null); }
public XamlStylerConsole(CommandLineOptions options) { this.options = options; IStylerOptions stylerOptions = new StylerOptions(); if (this.options.Configuration != null) { stylerOptions = this.LoadConfiguration(this.options.Configuration); } ApplyOptionOverrides(options, stylerOptions); this.stylerService = new StylerService(stylerOptions); }
public void TestAttributeThresholdHandling() { string testInput = MethodBase.GetCurrentMethod().Name + ".xaml"; var stylerOptions = new StylerOptions { AttributesTolerance = 0, MaxAttributeCharatersPerLine = 80, MaxAttributesPerLine = 3, PutEndingBracketOnNewLine = true }; var styler = StylerService.CreateInstance(stylerOptions); DoTest(testInput, styler); }
private static void DoTest(StylerService stylerService, StylerOptions stylerOptions, string testFileBaseName, string expectedSuffix) { var activeDir = Path.GetDirectoryName(new Uri(typeof(FileHandlingIntegrationTests).Assembly.CodeBase).LocalPath); var testFile = Path.Combine(activeDir, testFileBaseName); var testFileResultBaseName = (expectedSuffix != null) ? $"{testFile}_{expectedSuffix}" : testFile; // Exercise stylerService using supplied test XAML data string actualOutput = stylerService.StyleDocument(File.ReadAllText($"{testFile}.testxaml")); // Write output to ".actual" file for further investigation File.WriteAllText($"{testFileResultBaseName}.actual", actualOutput, Encoding.UTF8); // Check result Assert.That(actualOutput, Is.EqualTo(File.ReadAllText($"{testFileResultBaseName}.expected"))); }
public XamlStylerConsole(CommandLineOptions options) { this.options = options; IStylerOptions stylerOptions = new StylerOptions(); if (this.options.Configuration != null) { stylerOptions = this.LoadConfiguration(this.options.Configuration); } this.ApplyOptionOverrides(options, stylerOptions); this.stylerService = new StylerService(stylerOptions, new XamlLanguageOptions { IsFormatable = true }); }
protected override void Run() { var options = StylerOptionsConfiguration.ReadFromUserProfile(); var styler = new StylerService(options); var item = IdeApp.ProjectOperations.CurrentSelectedItem; if (item is Solution sln) { BatchProcessSolution(sln, styler); return; } if (item is Project prj) { BatchProcessProject(prj, styler); } }
private void ProcessFileInPlace(ProjectFile file, StylerService styler) { LoggingService.LogDebug($"Processing {file.FilePath} in-place"); var content = System.IO.File.ReadAllText(file.FilePath); var styledXaml = styler.StyleDocument(content); System.IO.File.WriteAllText(file.FilePath, styledXaml); var openedFile = IdeApp.Workbench.Documents.FirstOrDefault(f => f.FileName.FullPath == file.FilePath); if (openedFile != null) { LoggingService.LogDebug($"Reloading {file.FilePath} in editor window"); openedFile.Reload(); } }
/// <summary> /// Style input document and verify output against expected /// </summary> private static void DoTest(StylerOptions stylerOptions, string testFileBaseName, string expectedSuffix) { var stylerService = StylerService.CreateInstance(stylerOptions); var testFileResultBaseName = (expectedSuffix != null) ? (testFileBaseName + "_" + expectedSuffix) : testFileBaseName; // Exercise stylerService using supplied test XAML data string actualOutput = stylerService.ManipulateTreeAndFormatInput(File.ReadAllText(testFileBaseName + ".testxaml")); // Write output to ".actual" file for further investigation File.WriteAllText((testFileResultBaseName + ".actual"), actualOutput, Encoding.UTF8); // Check result Assert.That(actualOutput, Is.EqualTo(File.ReadAllText(testFileResultBaseName + ".expected"))); }
protected override void Run() { var options = StylerOptionsConfiguration.ReadFromUserProfile(); var styler = new StylerService(options); var doc = IdeApp.Workbench.ActiveDocument; var edit = doc.Editor; if (edit != null) { var styledXaml = styler.StyleDocument(edit.Text); using (edit.OpenUndoGroup()) { edit.RemoveText(0, edit.Text.Length); edit.InsertText(0, styledXaml); } doc.IsDirty = true; } }
protected override void Run() { var document = IdeApp.Workbench.ActiveDocument; if (!StylerOptionsConfiguration.IsFormatableDocument(document)) { return; } var stylerOptions = StylerOptionsConfiguration.GetOptionsForDocument(document.FileName, document.Owner as Project); var styler = new StylerService(stylerOptions); var editor = document.Editor; using (editor.OpenUndoGroup()) { var styledText = styler.StyleDocument(editor.Text); editor.Text = styledText; } document.IsDirty = true; }
public XamlMagicConsole(Options options) { this.options = options; StylerOptions stylerOptions = new StylerOptions(); if (this.options.Configuration != null) { var config = File.ReadAllText(this.options.Configuration); stylerOptions = JsonConvert.DeserializeObject <StylerOptions>(config); if (this.options.LogLevel == LogLevel.Insanity) { this.Log(JsonConvert.SerializeObject(stylerOptions), LogLevel.Insanity); } this.Log(JsonConvert.SerializeObject(stylerOptions.AttributeOrderingRuleGroups), LogLevel.Debug); } this.stylerService = StylerService.CreateInstance(stylerOptions); }
private void Execute(Document document) { if (!IsFormatableDocument(document)) { return; } Properties xamlEditorProps = _dte.Properties["TextEditor", "XAML"]; var stylerOptions = GetDialogPage(typeof(PackageOptions)).AutomationObject as IStylerOptions; stylerOptions.IndentSize = Int32.Parse(xamlEditorProps.Item("IndentSize").Value.ToString()); stylerOptions.IndentWithTabs = (bool)xamlEditorProps.Item("InsertTabs").Value; StylerService styler = StylerService.CreateInstance(stylerOptions); var textDocument = (TextDocument)document.Object("TextDocument"); TextPoint currentPoint = textDocument.Selection.ActivePoint; int originalLine = currentPoint.Line; int originalOffset = currentPoint.LineCharOffset; EditPoint startPoint = textDocument.StartPoint.CreateEditPoint(); EditPoint endPoint = textDocument.EndPoint.CreateEditPoint(); string xamlSource = startPoint.GetText(endPoint); xamlSource = styler.Format(xamlSource); startPoint.ReplaceText(endPoint, xamlSource, 0); if (originalLine <= textDocument.EndPoint.Line) { textDocument.Selection.MoveToLineAndOffset(originalLine, originalOffset); } else { textDocument.Selection.GotoLine(textDocument.EndPoint.Line); } }
private void AnalyzeXaml(CompilationAnalysisContext context) { var additionalFiles = context.Options.AdditionalFiles; var xamlFiles = additionalFiles.Where(file => Path.GetExtension(file.Path) == "xaml"); var stylerOptions = new StylerOptions(); var styleService = new StylerService(stylerOptions); foreach (var xamlFile in xamlFiles) { // Process each XAML file var originalContents = xamlFile.GetText().ToString(); var originalContentsHash = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(originalContents)); var styledContents = styleService.StyleDocument(originalContents); var styledContentsHash = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(originalContents)); if (originalContentsHash != styledContentsHash) { context.ReportDiagnostic(Diagnostic.Create( new DiagnosticDescriptor( "id", "title", "msg format", "category", DiagnosticSeverity.Warning, true ), Location.Create( xamlFile.Path, TextSpan.FromBounds(0, originalContents.Length - 1), new LinePositionSpan( new LinePosition(0, 0), new LinePosition(0, 0) ) ) )); } } }
private void DoTest(StylerOptions stylerOptions, int testNumber, [System.Runtime.CompilerServices.CallerMemberName] string callerMemberName = "") { // ReSharper disable once ExplicitCallerInfoArgument DoTest(StylerService.CreateInstance(stylerOptions), testNumber, callerMemberName); }