Ejemplo n.º 1
0
        public override void Regenerate(IndependentInjectedNodeContext nodeContext)
        {
            var htmlAttributeValue = nodeContext.OriginalContextNode as IHtmlAttributeValue;

            if (htmlAttributeValue == null)
            {
                Logger.Fail("Original node is not IHtmlAttributeValue");
                return;
            }

            if (htmlAttributeValue.LeadingQuote == null)
            {
                Logger.Fail("No leading quote");
                return;
            }

            var buffer = nodeContext.GeneratedNode.GetTextAsBuffer();

            var token =
                htmlAttributeValue.LeadingQuote.TokenTypes.ATTRIBUTE_VALUE.Create(buffer, TreeOffset.Zero,
                                                                                  new TreeOffset(buffer.Length)) as IHtmlToken;

            var list = htmlAttributeValue.ValueElements.ToArray();

            if (list.Any())
            {
                LowLevelModificationUtil.DeleteChildRange(list.First(), list.Last());
            }

            LowLevelModificationUtil.AddChildAfter(htmlAttributeValue.LeadingQuote, token);
        }
        private void MakeFormat(FormattingRange range, IEnumerable <string> space)
        {
            PsiFormatterHelper.ReplaceSpaces(range.First, range.Last, space);

            // TODO: Move antiglueing logic into CalcSpaces()
            ITokenNode nextToken;
            ITokenNode prevToken = range.First.FindLastTokenIn();

            if (prevToken != null)
            {
                nextToken = prevToken.GetNextToken();
            }
            else
            {
                nextToken = range.First.NextSibling.FindFirstTokenIn();
                if (nextToken != null)
                {
                    prevToken = nextToken.GetPrevToken();
                }
            }

            if (prevToken != null && nextToken != null)
            {
                ITokenNode separator = Context.CodeFormatter.GetMinimalSeparator(prevToken, nextToken);
                if (separator != null)
                {
                    LowLevelModificationUtil.AddChildAfter(range.First, separator);
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Inserts a newline after the Node provided.
        /// </summary>
        /// <param name="currentNode">
        /// The node to insert after.
        /// </param>
        /// <returns>
        /// An ITreeNode that has been inserted.
        /// </returns>
        public static ITreeNode InsertNewLineAfter(this ITreeNode currentNode)
        {
            LeafElementBase leafElement = GetLeafElement();

            using (WriteLockCookie.Create(true))
            {
                LowLevelModificationUtil.AddChildAfter(currentNode, new[] { leafElement });
            }

            return(leafElement);
        }
        public void AdjustLeadingAndTrailingWhitespaces(CppCodeFormatter cppCodeFormatter, CppFile cppFile)
        {
            var cgProgram = (cppFile.Parent as IInjectedFileHolder)?.OriginalNode.PrevSibling;

            var s = ShaderLabCppFormatterExtension.GetIndentInCgProgram(cgProgram);

            cppCodeFormatter.RemoveLeadingSpacesInFile(cppFile);
            cppCodeFormatter.RemoveTrailingSpaces(cppFile);

            var lineEnding = cppFile.DetectLineEnding(cppFile.GetPsiServices());

            LowLevelModificationUtil.AddChildBefore(cppFile.firstChild, cppCodeFormatter.CreateNewLine(lineEnding), cppCodeFormatter.CreateSpace(s, null));
            LowLevelModificationUtil.AddChildAfter(cppFile.lastChild, cppCodeFormatter.CreateNewLine(lineEnding), cppCodeFormatter.CreateSpace(s, null));
        }
        protected override ITreeNode Move(Direction direction)
        {
            using (PsiTransactionCookie.CreateAutoCommitCookieWithCachesUpdate(myRuleDeclaration.GetPsiServices(), "Rearrange code"))
            {
                if (direction == Direction.Up)
                {
                    var sibling = myRuleDeclaration.PrevSibling;
                    while (sibling is IWhitespaceNode)
                    {
                        sibling = sibling.PrevSibling;
                    }

                    var ruleDeclaration = sibling as IRuleDeclaration;
                    if (ruleDeclaration != null)
                    {
                        using (WriteLockCookie.Create())
                        {
                            LowLevelModificationUtil.AddChildBefore(ruleDeclaration, myRuleDeclaration);
                            LowLevelModificationUtil.AddChildBefore(ruleDeclaration, new NewLine("\r\n"));
                        }
                    }
                }

                if (direction == Direction.Down)
                {
                    var sibling = myRuleDeclaration.NextSibling;
                    while (sibling is IWhitespaceNode)
                    {
                        sibling = sibling.NextSibling;
                    }

                    var ruleDeclaration = sibling as IRuleDeclaration;
                    if (ruleDeclaration != null)
                    {
                        using (WriteLockCookie.Create())
                        {
                            LowLevelModificationUtil.AddChildAfter(ruleDeclaration, myRuleDeclaration);
                            LowLevelModificationUtil.AddChildAfter(ruleDeclaration, new NewLine("\r\n"));
                        }
                    }
                }
            }
            return(myRuleDeclaration);
        }
Ejemplo n.º 6
0
        /// <summary>Creates a try-catch block around this block. </summary>
        /// <param name="exceptionType">The exception type to catch. </param>
        /// <returns><c>true</c> if the try-catch block could be created; otherwise, <c>false</c>. </returns>
        public bool SurroundWithTryBlock(IDeclaredType exceptionType)
        {
            var containingStatement = Node.GetContainingStatement();

            if (containingStatement != null && containingStatement.LastChild != null)
            {
                var codeElementFactory    = new CodeElementFactory(GetElementFactory());
                var exceptionVariableName = NameFactory.CatchVariableName(Node, exceptionType);
                var tryStatement          = codeElementFactory.CreateTryStatement(exceptionType, exceptionVariableName, Node);

                var spaces = GetElementFactory().CreateWhitespaces(Environment.NewLine);

                LowLevelModificationUtil.AddChildAfter(containingStatement.LastChild, spaces[0]);

                var block = codeElementFactory.CreateBlock(containingStatement);
                tryStatement.SetTry(block);

                containingStatement.ReplaceBy(tryStatement);
                return(true);
            }
            return(false);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Moves the comment token specified after the next available non whitespace char (normally an open curly bracket).
        /// </summary>
        /// <param name="commentTokenNode">
        /// The comment token to move.
        /// </param>
        public static void MoveCommentInsideNextOpenCurlyBracket(ITokenNode commentTokenNode)
        {
            using (WriteLockCookie.Create(true))
            {
                // move comment inside block curly bracket here
                // we copy it, then insert it and then delete the copied one
                ITokenNode startOfTokensToDelete = Utils.GetFirstNonWhitespaceTokenToLeft(commentTokenNode).GetNextToken();
                ITokenNode endOfTokensToDelete   = Utils.GetFirstNewLineTokenToRight(commentTokenNode);
                ITokenNode startOfTokensToFormat = startOfTokensToDelete.GetPrevToken();

                ITokenNode openCurlyBracketTokenNode = Utils.GetFirstNonWhitespaceTokenToRight(commentTokenNode);
                ITokenNode newCommentTokenNode       = commentTokenNode.Copy(null);
                ITokenNode tokenNodeToInsertAfter    = Utils.GetFirstNewLineTokenToRight(openCurlyBracketTokenNode);
                LowLevelModificationUtil.AddChildAfter(tokenNodeToInsertAfter, new[] { newCommentTokenNode });
                LowLevelModificationUtil.AddChildAfter(newCommentTokenNode, newCommentTokenNode.InsertNewLineAfter());

                DeleteChildRange(startOfTokensToDelete, endOfTokensToDelete);
                ITokenNode endOfTokensToFormat = newCommentTokenNode;

                CSharpFormatterHelper.FormatterInstance.Format(startOfTokensToFormat, endOfTokensToFormat);
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Fixes the spacing of the using directives in a given file or namespace block
        /// to match the specified configuration. (The directives must already be in
        /// the correct order.)
        /// </summary>
        /// <param name="holder">The file or namespace block in which to fix the spacing
        /// of using directives (if any are present).</param>
        /// <param name="configuration">The configuration determining the correct spacing.</param>
        public static void FixSpacing(
            ICSharpTypeAndNamespaceHolderDeclaration holder,
            OrderUsingsConfiguration configuration)
        {
            // The reordering proceeds one item at a time, so we just keep reapplying it
            // until there's nothing left to do.
            // To avoid hanging VS in the event that an error in the logic causes the
            // sequence of modifications not to terminate, we ensure we don't try to
            // apply more changes than there are either using directives or blank
            // lines in the usings list.
            int tries     = 0;
            int itemCount = 0;

            while (tries == 0 || tries <= itemCount)
            {
                List <UsingDirectiveOrSpace> items = ImportReader.ReadImports(holder);
                if (items == null)
                {
                    return;
                }

                itemCount = items.Count;
                List <UsingDirective>         imports;
                List <List <UsingDirective> > requiredOrderByGroups;
                ImportInspector.FlattenImportsAndDetermineOrderAndSpacing(
                    configuration, items, out imports, out requiredOrderByGroups);

                SpaceChange nextChange = ImportInspector.GetNextSpacingModification(requiredOrderByGroups, items);
                if (nextChange != null)
                {
                    IUsingDirective usingBeforeSpace = holder.Imports[nextChange.Index - 1];
                    if (nextChange.ShouldInsert)
                    {
                        using (WriteLockCookie.Create())
                        {
                            var newLineText = new StringBuffer("\r\n");

                            LeafElementBase newLine = TreeElementFactory.CreateLeafElement(
                                CSharpTokenType.NEW_LINE, newLineText, 0, newLineText.Length);
                            LowLevelModificationUtil.AddChildAfter(usingBeforeSpace, newLine);
                        }
                    }
                    else
                    {
                        var syb = usingBeforeSpace.NextSibling;
                        for (; syb != null && !(syb is IUsingDirective); syb = syb.NextSibling)
                        {
                            if (syb.NodeType == CSharpTokenType.NEW_LINE)
                            {
                                LowLevelModificationUtil.DeleteChild(syb);
                            }
                        }
                    }
                }
                else
                {
                    break;
                }

                tries += 1;
            }
        }