Example #1
0
        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;
        }
Example #2
0
        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 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());
        }
Example #4
0
            public void Process()
            {
                int successCount = 0;

                foreach (string file in this.options.Files)
                {
                    this.Log($"Processing: {file}");

                    if (!options.Ignore)
                    {
                        var extension = Path.GetExtension(file);
                        this.Log($"Extension: {extension}", LogLevel.Debug);

                        if (!extension.Equals(".xaml", StringComparison.OrdinalIgnoreCase))
                        {
                            this.Log("Skipping... Can only process XAML files. Use the --ignore parameter to override.");
                            continue;
                        }
                    }

                    var path = Path.GetFullPath(file);
                    this.Log($"Full Path: {file}", LogLevel.Debug);

                    // If the options already has a configuration file set, we don't need to go hunting for one
                    string configurationPath = string.IsNullOrEmpty(this.options.Configuration) ? this.GetConfigurationFromPath(path) : null;

                    string   originalContent = null;
                    Encoding encoding        = Encoding.UTF8; // Visual Studio by default uses UTF8
                    using (var reader = new StreamReader(path))
                    {
                        originalContent = reader.ReadToEnd();
                        encoding        = reader.CurrentEncoding;
                        this.Log($"\nOriginal Content:\n\n{originalContent}\n", LogLevel.Insanity);
                    }

                    var formattedOutput = String.IsNullOrWhiteSpace(configurationPath)
                        ? stylerService.StyleDocument(originalContent)
                        : new StylerService(this.LoadConfiguration(configurationPath)).StyleDocument(originalContent);

                    this.Log($"\nFormatted Output:\n\n{formattedOutput}\n", LogLevel.Insanity);

                    using (var writer = new StreamWriter(path, false, encoding))
                    {
                        try
                        {
                            writer.Write(formattedOutput);
                            this.Log($"Finished Processing: {file}", LogLevel.Verbose);
                            successCount++;
                        }
                        catch (Exception e)
                        {
                            this.Log("Skipping... Error formatting XAML. Increase log level for more details.");
                            this.Log($"Exception: {e.Message}", LogLevel.Verbose);
                            this.Log($"StackTrace: {e.StackTrace}", LogLevel.Debug);
                        }
                    }
                }

                this.Log($"Processed {successCount} of {this.options.Files.Count} files.", LogLevel.Minimal);
            }
Example #5
0
        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);
                };
            });
        }
Example #6
0
        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);
        }
Example #7
0
        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);
        }
Example #9
0
        /// <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")));
        }
Example #10
0
        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")));
        }
        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();
            }
        }
Example #12
0
        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;
        }
Example #14
0
        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 = 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 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)
                                                         )
                                                     )
                                                 ));
                }
            }
        }
Example #16
0
        private void DisplayXamlCode(XmlNode node)
        {
            if (node.LocalName.Contains(nameof(XamlDisplayerPanel)))
            {
                for (var i = 0; i < node.ChildNodes.Count; i++)
                {
                    XmlNode child             = node.ChildNodes[i];
                    string  xamlToBeDisplayed = Beautify(child.OuterXml);
                    _xamlDisplayers[i].CodeToBeDisplayed = xamlToBeDisplayed;
                }
            }
            else if (node.HasChildNodes)
            {
                foreach (XmlNode child in node.ChildNodes)
                {
                    DisplayXamlCode(child);
                }
            }
            string Beautify(string fullXaml)
            {
                var styler = new StylerService(new StylerOptions()
                {
                    IndentWithTabs = true
                });
                string result = styler.StyleDocument(fullXaml);

                result = RemoveIrrelaventAttributes(result);
                result = RemoveEmptyLines(result);
                return(result);

                string RemoveIrrelaventAttributes(string input)
                {
                    if (_attributesToBeRemoved == null)
                    {
                        return(input);
                    }
                    string cleansed = input;

                    foreach (var s in _attributesToBeRemoved)
                    {
                        cleansed = cleansed.Replace(s, "");
                    }
                    return(cleansed);
                }

                string RemoveEmptyLines(string xaml)
                {
                    var  sb           = new StringBuilder(xaml.Length);
                    char previousChar = '\0';

                    for (int i = 0; i < xaml.Length; i++)
                    {
                        char currentChar = xaml[i];
                        if (currentChar == '\r' && previousChar == '\n')
                        {
                            //skip \r,\n,\t
                            while (i + 1 < xaml.Length &&
                                   (xaml[i + 1] == '\r' ||
                                    xaml[i + 1] == '\n' ||
                                    xaml[i + 1] == '\t'))
                            {
                                i++;
                            }
                        }
                        else
                        {
                            sb.Append(currentChar);
                        }
                        if (currentChar != ' ' && currentChar != '\t')
                        {
                            previousChar = currentChar;
                        }
                    }
                    return(sb.ToString());
                }
            }
        }