Esempio n. 1
0
        public static string Format(this string source)
        {
            var builder   = new StringBuilder();
            var formatter = XamlFormatterFactory.Create(new XamlFormatterOptions {
                IndentSize = 4
            });

            formatter.Format(source, builder);

            var target = builder.ToString();

            return(target);
        }
Esempio n. 2
0
        /// <summary>
        /// Executes the format document command.
        /// </summary>
        /// <param name="document">
        /// The document to format.
        /// </param>
        public virtual void Execute(Document document)
        {
            Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
            if (document == null)
            {
                throw new ArgumentNullException(nameof(document));
            }

            var textDocument = (TextDocument)document.Object("TextDocument");

            var startPoint = textDocument.StartPoint.CreateEditPoint();
            var endPoint   = textDocument.EndPoint.CreateEditPoint();

            var currentPoint   = textDocument.Selection.ActivePoint;
            var originalLine   = currentPoint.Line;
            var originalOffset = currentPoint.LineCharOffset;

            var unformatted = startPoint.GetText(endPoint);

            var options = this.CreateOptions();
            var builder = new StringBuilder();

            XamlFormatterFactory.Create(options).Format(unformatted, builder);

            startPoint.ReplaceText(endPoint, builder.ToString(), 0);

            if (originalLine <= textDocument.EndPoint.Line)
            {
                var linePoint = startPoint.CreateEditPoint();
                if (originalLine > 0)
                {
                    linePoint.LineDown(originalLine - 1);
                }

                originalOffset = Math.Min(originalOffset, linePoint.LineLength + 1);
                if (originalOffset > 0)
                {
                    textDocument.Selection.MoveToLineAndOffset(originalLine, originalOffset);
                }
                else
                {
                    textDocument.Selection.GotoLine(originalLine);
                }
            }
            else
            {
                var linePoint = startPoint.CreateEditPoint();
                linePoint.EndOfDocument();
                textDocument.Selection.MoveToPoint(linePoint);
            }
        }