Beispiel #1
0
        private static void RemoveDeclarationOnly(this ICodeModule module, Declaration target)
        {
            var multipleDeclarations = target.DeclarationType == DeclarationType.Variable && target.HasMultipleDeclarationsInStatement();
            var context         = GetStmtContext(target);
            var declarationText = context.GetText().Replace(" _" + Environment.NewLine, Environment.NewLine);
            var selection       = GetStmtContextSelection(target);

            Debug.Assert(selection.StartColumn > 0);

            var oldLines = module.GetLines(selection);
            var indent   = oldLines.IndexOf(oldLines.FirstOrDefault(c => c != ' ')) + 1;

            var newLines = oldLines
                           .Replace(" _" + Environment.NewLine, Environment.NewLine)
                           .Remove(selection.StartColumn - 1, declarationText.Length - selection.StartColumn + indent);

            if (multipleDeclarations)
            {
                selection = GetStmtContextSelection(target);
                newLines  = RemoveExtraComma(module.GetLines(selection).Replace(oldLines, newLines),
                                             target.CountOfDeclarationsInStatement(), target.IndexOfVariableDeclarationInStatement());
            }

            var newLinesWithoutExcessSpaces = newLines.Split(new[] { Environment.NewLine }, StringSplitOptions.None);

            for (var i = 0; i < newLinesWithoutExcessSpaces.Length; i++)
            {
                newLinesWithoutExcessSpaces[i] = newLinesWithoutExcessSpaces[i].RemoveExtraSpacesLeavingIndentation();
            }

            for (var i = newLinesWithoutExcessSpaces.Length - 1; i >= 0; i--)
            {
                if (newLinesWithoutExcessSpaces[i].Trim() == string.Empty)
                {
                    continue;
                }

                if (newLinesWithoutExcessSpaces[i].EndsWith(" _"))
                {
                    newLinesWithoutExcessSpaces[i] =
                        newLinesWithoutExcessSpaces[i].Remove(newLinesWithoutExcessSpaces[i].Length - 2);
                }
                break;
            }

            // remove all lines with only whitespace
            newLinesWithoutExcessSpaces = newLinesWithoutExcessSpaces.Where(str => str.Any(c => !char.IsWhiteSpace(c))).ToArray();

            module.DeleteLines(selection);
            if (newLinesWithoutExcessSpaces.Any())
            {
                module.InsertLines(selection.StartLine, string.Join(Environment.NewLine, newLinesWithoutExcessSpaces));
            }
        }
Beispiel #2
0
        public static void ReplaceIdentifierReferenceName(this ICodeModule module, IdentifierReference identifierReference, string replacement)
        {
            var original = module.GetLines(identifierReference.Selection.StartLine, 1);
            var result   = ReplaceStringAtIndex(original, identifierReference.IdentifierName, replacement, identifierReference.Context.Start.Column);

            module.ReplaceLine(identifierReference.Selection.StartLine, result);
        }
        public virtual string ConstructLinesOfProc(ICodeModule codeModule, IExtractMethodModel model)
        {
            var newLine      = Environment.NewLine;
            var method       = model.Method;
            var keyword      = Tokens.Sub;
            var asTypeClause = string.Empty;
            var selection    = model.RowsToRemove;

            var access          = method.Accessibility.ToString();
            var extractedParams = method.Parameters.Select(p => ExtractedParameter.PassedBy.ByRef + " " + p.Name + " " + Tokens.As + " " + p.TypeName);
            var parameters      = "(" + string.Join(", ", extractedParams) + ")";
            //method signature
            var result = access + ' ' + keyword + ' ' + method.MethodName + parameters + ' ' + asTypeClause + newLine;
            // method body
            string textToMove = "";

            foreach (var item in selection)
            {
                textToMove += codeModule.GetLines(item.StartLine, item.EndLine - item.StartLine + 1);
                textToMove += Environment.NewLine;
            }
            // method end;
            result += textToMove;
            result += Tokens.End + " " + Tokens.Sub;
            return(result);
        }
Beispiel #4
0
        public static void ReplaceToken(this ICodeModule module, IToken token, string replacement)
        {
            var original = module.GetLines(token.Line, 1);
            var result   = ReplaceStringAtIndex(original, token.Text, replacement, token.Column);

            module.ReplaceLine(token.Line, result);
        }
Beispiel #5
0
        public static (string context, Selection highlight) HighlightSelection(this ArgumentReference reference, ICodeModule module)
        {
            const int maxLength = 255;
            var       selection = reference.Selection;

            var lines = module.GetLines(selection.StartLine, selection.LineCount).Split('\n');

            var line   = lines[0];
            var indent = line.TakeWhile(c => c.Equals(' ')).Count();

            var highlight = new Selection(
                1, Math.Max(selection.StartColumn - indent, 1),
                1, Math.Max(selection.EndColumn - indent, 1))
                            .ToZeroBased();

            var trimmed = line.Trim();

            if (trimmed.Length > maxLength || lines.Length > 1)
            {
                trimmed   = trimmed.Substring(0, Math.Min(trimmed.Length, maxLength)) + " …";
                highlight = new Selection(1, highlight.StartColumn, 1, trimmed.Length);
            }

            if (highlight.IsSingleCharacter && highlight.StartColumn == 0)
            {
                trimmed   = " " + trimmed;
                highlight = new Selection(0, 0, 0, 1);
            }
            else if (highlight.IsSingleCharacter)
            {
                highlight = new Selection(0, selection.StartColumn - 1 - indent - 1, 0, selection.StartColumn - 1 - indent);
            }
            return(trimmed, highlight);
        }
        private void SetFieldToPrivate(ICodeModule module)
        {
            if (_model.TargetDeclaration.Accessibility == Accessibility.Private)
            {
                return;
            }

            RemoveField(_model.TargetDeclaration);

            var newField = "Private " + _model.TargetDeclaration.IdentifierName + " As " +
                           _model.TargetDeclaration.AsTypeName;

            module.InsertLines(module.CountOfDeclarationLines + 1, newField);
            var pane = module.CodePane;

            {
                pane.Selection = _model.TargetDeclaration.QualifiedSelection.Selection;
            }

            for (var index = 1; index <= module.CountOfDeclarationLines; index++)
            {
                if (module.GetLines(index, 1).Trim() == string.Empty)
                {
                    module.DeleteLines(new Selection(index, 0, index, 0));
                }
            }
        }
        private string GetSurroundingCode(ICodeModule module, Selection selection)
        {
            // throws AccessViolationException!
            var declarationLines = module.CountOfDeclarationLines;

            if (selection.StartLine <= declarationLines)
            {
                return(module.GetLines(1, declarationLines));
            }

            var currentProc = module.GetProcOfLine(selection.StartLine);
            var procKind    = module.GetProcKindOfLine(selection.StartLine);
            var procStart   = module.GetProcStartLine(currentProc, procKind);
            var lineCount   = module.GetProcCountLines(currentProc, procKind);

            return(module.GetLines(procStart, lineCount));
        }
        private IEnumerable <RegexSearchResult> GetResultsFromModule(ICodeModule module, string searchPattern, Selection selection)
        {
            var startLine = selection.StartLine > 1
                ? selection.StartLine
                : 1;

            var moduleLines = module.CountOfLines;
            var stopLine    = selection.EndLine < moduleLines
                ? selection.EndLine
                : moduleLines;

            if (startLine > stopLine)
            {
                return(new List <RegexSearchResult>());
            }

            if (startLine == stopLine)
            {
                return(LineMatches(module.GetLines(startLine, 1), selection.StartColumn, null, searchPattern)
                       .Select(m => new RegexSearchResult(m, module, startLine, selection.StartColumn - 1))
                       .ToList());
            }

            var results = new List <RegexSearchResult>();

            var firstLineMatches = LineMatches(module.GetLines(startLine, 1), selection.StartColumn, selection.EndColumn, searchPattern)
                                   .Select(m => new RegexSearchResult(m, module, startLine));

            results.AddRange(firstLineMatches);

            for (var lineIndex = startLine + 1; lineIndex < stopLine; lineIndex++)
            {
                var codeLine = module.GetLines(lineIndex, 1);
                var matches  = LineMatches(codeLine, searchPattern)
                               .Select(m => new RegexSearchResult(m, module, lineIndex));

                results.AddRange(matches);
            }

            var lastLineMatches = LineMatches(module.GetLines(stopLine, 1), 1, selection.EndColumn, searchPattern)
                                  .Select(m => new RegexSearchResult(m, module, stopLine));

            results.AddRange(lastLineMatches);

            return(results);
        }
Beispiel #9
0
 public AutoCompleteEventArgs(ICodeModule module, KeyPressEventArgs e)
 {
     Character        = e.Character;
     CodeModule       = module;
     CurrentSelection = module.GetQualifiedSelection().Value.Selection;
     CurrentLine      = module.GetLines(CurrentSelection);
     ControlDown      = e.ControlDown;
     IsDelete         = e.IsDelete;
 }
Beispiel #10
0
        private void RewriteCall(VBAParser.ArgumentListContext paramList, ICodeModule module)
        {
            var argValues = new List <string>();

            if (paramList.positionalOrNamedArgumentList().positionalArgumentOrMissing() != null)
            {
                argValues.AddRange(paramList.positionalOrNamedArgumentList().positionalArgumentOrMissing().Select(p =>
                {
                    if (p is VBAParser.SpecifiedPositionalArgumentContext)
                    {
                        return(((VBAParser.SpecifiedPositionalArgumentContext)p).positionalArgument().GetText());
                    }

                    return(string.Empty);
                }).ToList());
            }
            if (paramList.positionalOrNamedArgumentList().namedArgumentList() != null)
            {
                argValues.AddRange(paramList.positionalOrNamedArgumentList().namedArgumentList().namedArgument().Select(p => p.GetText()).ToList());
            }
            if (paramList.positionalOrNamedArgumentList().requiredPositionalArgument() != null)
            {
                argValues.Add(paramList.positionalOrNamedArgumentList().requiredPositionalArgument().GetText());
            }

            var lineCount = paramList.Stop.Line - paramList.Start.Line + 1; // adjust for total line count

            var newContent = module.GetLines(paramList.Start.Line, lineCount);

            newContent = newContent.Remove(paramList.Start.Column, paramList.GetText().Length);

            var reorderedArgValues = new List <string>();

            foreach (var param in _model.Parameters)
            {
                var argAtIndex = argValues.ElementAtOrDefault(param.Index);
                if (argAtIndex != null)
                {
                    reorderedArgValues.Add(argAtIndex);
                }
            }

            // property let/set and paramarrays
            for (var index = reorderedArgValues.Count; index < argValues.Count; index++)
            {
                reorderedArgValues.Add(argValues[index]);
            }

            newContent = newContent.Insert(paramList.Start.Column, string.Join(", ", reorderedArgValues));

            module.ReplaceLine(paramList.Start.Line, newContent.Replace(" _" + Environment.NewLine, string.Empty));
            module.DeleteLines(paramList.Start.Line + 1, lineCount - 1);
        }
        private void FixTypeHintUsage(string hint, ICodeModule module, Selection selection, bool isDeclaration = false)
        {
            var line = module.GetLines(selection.StartLine, 1);

            var asTypeClause = ' ' + Tokens.As + ' ' + SymbolList.TypeHintToTypeName[hint];

            string fix;

            if (isDeclaration && Context is VBAParser.FunctionStmtContext)
            {
                var typeHint  = Identifier.GetTypeHintContext(((VBAParser.FunctionStmtContext)Context).functionName().identifier());
                var argList   = ((VBAParser.FunctionStmtContext)Context).argList();
                var endLine   = argList.Stop.Line;
                var endColumn = argList.Stop.Column;

                var oldLine = module.GetLines(endLine, selection.LineCount);
                fix = oldLine.Insert(endColumn + 1, asTypeClause).Remove(typeHint.Start.Column, 1);  // adjust for VBA 0-based indexing

                module.ReplaceLine(endLine, fix);
            }
            else if (isDeclaration && Context is VBAParser.PropertyGetStmtContext)
            {
                var typeHint  = Identifier.GetTypeHintContext(((VBAParser.PropertyGetStmtContext)Context).functionName().identifier());
                var argList   = ((VBAParser.PropertyGetStmtContext)Context).argList();
                var endLine   = argList.Stop.Line;
                var endColumn = argList.Stop.Column;

                var oldLine = module.GetLines(endLine, selection.LineCount);
                fix = oldLine.Insert(endColumn + 1, asTypeClause).Remove(typeHint.Start.Column, 1);  // adjust for VBA 0-based indexing

                module.ReplaceLine(endLine, fix);
            }
            else
            {
                var pattern = "\\b" + _declaration.IdentifierName + "\\" + hint;
                fix = Regex.Replace(line, pattern, _declaration.IdentifierName + (isDeclaration ? asTypeClause : string.Empty));
                module.ReplaceLine(selection.StartLine, fix);
            }
        }
Beispiel #12
0
        private static string GetCode(ICodeModule module)
        {
            var lines = module.CountOfLines;

            if (lines == 0)
            {
                return(string.Empty);
            }

            var codeLines = module.GetLines(1, lines);
            var code      = string.Concat(codeLines);

            return(code);
        }
Beispiel #13
0
        private static string[] GetSanitizedCode(ICodeModule module)
        {
            var lines = module.CountOfLines;

            if (lines == 0)
            {
                return(new string[] { });
            }

            var code = module.GetLines(1, lines).Replace("\r", string.Empty).Split('\n');

            StripLineNumbers(code);
            return(code);
        }
Beispiel #14
0
        public static void Remove(this ICodeModule module, Selection selection, ParserRuleContext instruction)
        {
            var originalCodeLines   = module.GetLines(selection.StartLine, selection.LineCount);
            var originalInstruction = instruction.GetText();

            module.DeleteLines(selection.StartLine, selection.LineCount);

            var newCodeLines = originalCodeLines.Replace(originalInstruction, string.Empty);

            if (!string.IsNullOrEmpty(newCodeLines))
            {
                module.InsertLines(selection.StartLine, newCodeLines);
            }
        }
        protected bool IsBlockCompleted(ICodeModule module, Selection selection)
        {
            string content;
            var    proc = module.GetProcOfLine(selection.StartLine);

            if (proc == null)
            {
                content = module.GetLines(1, module.CountOfDeclarationLines).StripStringLiterals();
            }
            else
            {
                var procKind  = module.GetProcKindOfLine(selection.StartLine);
                var startLine = module.GetProcStartLine(proc, procKind);
                var lineCount = module.GetProcCountLines(proc, procKind);
                content = module.GetLines(startLine, lineCount);
            }

            var options       = RegexOptions.IgnoreCase;
            var inputPattern  = $"(?<!{OutputToken.Replace(InputToken, string.Empty)})\\b{InputToken}\\b";
            var inputMatches  = Regex.Matches(content, inputPattern, options).Count;
            var outputMatches = Regex.Matches(content, $"\\b{OutputToken}\\b", options).Count;

            return(inputMatches > 0 && inputMatches == outputMatches);
        }
        private IEnumerable <RegexSearchResult> GetResultsFromModule(ICodeModule module, string searchPattern)
        {
            var results = new List <RegexSearchResult>();

            // VBA uses 1-based indexing
            for (var i = 1; i <= module.CountOfLines; i++)
            {
                var codeLine = module.GetLines(i, 1);
                var matches  = LineMatches(codeLine, searchPattern)
                               .Select(m => new RegexSearchResult(m, module, i));

                results.AddRange(matches);
            }
            return(results);
        }
 public AutoCompleteEventArgs(ICodeModule module, KeyPressEventArgs e)
 {
     if (e.Key == Keys.Delete ||
         e.Key == Keys.Back ||
         e.Key == Keys.Enter ||
         e.Key == Keys.Tab)
     {
         Keys = e.Key;
     }
     else
     {
         Character = e.Character;
     }
     CodeModule       = module;
     CurrentSelection = module.GetQualifiedSelection().Value.Selection;
     CurrentLine      = module.GetLines(CurrentSelection);
 }
Beispiel #18
0
        public CodeString GetCurrentLogicalLine(ICodeModule module)
        {
            Selection pSelection;

            using (var pane = module.CodePane)
            {
                pSelection = pane.Selection;
            }

            var selectedContent = module.GetLines(pSelection.StartLine, pSelection.LineCount);
            var selectedLines   = selectedContent.Replace("\r", string.Empty).Split('\n');
            var currentLine     = selectedLines[0];

            var caretStartLine = (pSelection.StartLine, currentLine);
            var lines          = new List <(int pLine, string Content)> {
                caretStartLine
            };

            // selection line may not be the only physical line in the complete logical line; accounts for line continuations.
            InsertPhysicalLinesAboveSelectionStart(lines, module, pSelection.StartLine);
            AppendPhysicalLinesBelowSelectionStart(lines, module, pSelection.StartLine, currentLine);

            var logicalLine = string.Join("\r\n", lines.Select(e => e.Content));

            var zCaretLine    = lines.IndexOf(caretStartLine);
            var zCaretColumn  = pSelection.StartColumn - 1;
            var caretPosition = new Selection(
                zCaretLine, zCaretColumn, zCaretLine + pSelection.LineCount - 1, pSelection.EndColumn - 1);

            var pStartLine      = lines[0].pLine;
            var pEndLine        = lines[lines.Count - 1].pLine;
            var snippetPosition = new Selection(pStartLine, 1, pEndLine, 1);

            if (pStartLine > pSelection.StartLine || pEndLine > pSelection.EndLine)
            {
                // selection spans more than a single logical line
                return(null);
            }

            var result = new CodeString(logicalLine, caretPosition, snippetPosition);

            return(result);
        }
Beispiel #19
0
        public void Refactor()
        {
            // TODO : move all this presenter code out

            /*
             * var presenter = _factory.Create();
             * if (presenter == null)
             * {
             *  OnInvalidSelection();
             *  return;
             * }
             *
             */
            var qualifiedSelection = _codeModule.GetQualifiedSelection();

            if (!qualifiedSelection.HasValue)
            {
                return;
            }

            var selection    = qualifiedSelection.Value.Selection;
            var selectedCode = _codeModule.GetLines(selection);
            var model        = _createMethodModel(qualifiedSelection, selectedCode);

            if (model == null)
            {
                return;
            }

            /*
             * var success = presenter.Show(model,_createProc);
             * if (!success)
             * {
             *  return;
             * }
             */

            _extraction.Apply(_codeModule, model, selection);

            _onParseRequest(this);
        }
Beispiel #20
0
        public static (string context, Selection highlight) HighlightSelection(this IdentifierReference reference, ICodeModule module)
        {
            const int maxLength = 255;
            var       selection = reference.Selection;

            var lines = module.GetLines(selection.StartLine, selection.LineCount).Split('\n');

            var line   = lines[0];
            var indent = line.TakeWhile(c => c.Equals(' ')).Count();

            var highlight = new Selection(
                1, Math.Max(selection.StartColumn - indent, 1),
                1, Math.Max(selection.EndColumn - indent, 1))
                            .ToZeroBased();

            var trimmed = line.Trim();

            if (trimmed.Length > maxLength || lines.Length > 1)
            {
                trimmed = trimmed.Substring(0, maxLength) + " …";
            }
            return(trimmed, highlight);
        }
        public bool IsSpacingUnchanged(CodeString code, CodeString original)
        {
            using (var pane = _module.CodePane)
            {
                using (var window = pane.Window)
                {
                    //window.ScreenUpdating = false;
                    _module.DeleteLines(code.SnippetPosition);
                    _module.InsertLines(code.SnippetPosition.StartLine, code.Code);
                    //window.ScreenUpdating = true;

                    pane.Selection = code.SnippetPosition.Offset(code.CaretPosition);

                    var lines = _module.GetLines(code.SnippetPosition);
                    if (lines.Equals(code.Code, StringComparison.InvariantCultureIgnoreCase))
                    {
                        return(true);
                    }
                }

                _module.ReplaceLine(code.SnippetPosition.StartLine, original.Code);
            }
            return(false);
        }
Beispiel #22
0
        private void RemoveCallParameter(VBAParser.ArgumentListContext paramList, ICodeModule module)
        {
            var paramNames = new List <string>();

            if (paramList.positionalOrNamedArgumentList().positionalArgumentOrMissing() != null)
            {
                paramNames.AddRange(paramList.positionalOrNamedArgumentList().positionalArgumentOrMissing().Select(p =>
                {
                    if (p is VBAParser.SpecifiedPositionalArgumentContext)
                    {
                        return(((VBAParser.SpecifiedPositionalArgumentContext)p).positionalArgument().GetText());
                    }

                    return(string.Empty);
                }).ToList());
            }
            if (paramList.positionalOrNamedArgumentList().namedArgumentList() != null)
            {
                paramNames.AddRange(paramList.positionalOrNamedArgumentList().namedArgumentList().namedArgument().Select(p => p.GetText()).ToList());
            }
            if (paramList.positionalOrNamedArgumentList().requiredPositionalArgument() != null)
            {
                paramNames.Add(paramList.positionalOrNamedArgumentList().requiredPositionalArgument().GetText());
            }
            var lineCount = paramList.Stop.Line - paramList.Start.Line + 1; // adjust for total line count

            var newContent = module.GetLines(paramList.Start.Line, lineCount);

            newContent = newContent.Remove(paramList.Start.Column, paramList.GetText().Length);

            var savedParamNames = paramNames;

            for (var index = _model.Parameters.Count - 1; index >= 0; index--)
            {
                var param = _model.Parameters[index];
                if (!param.IsRemoved)
                {
                    continue;
                }

                if (param.Name.Contains("ParamArray"))
                {
                    // handle param arrays
                    while (savedParamNames.Count > index)
                    {
                        savedParamNames.RemoveAt(index);
                    }
                }
                else
                {
                    if (index < savedParamNames.Count && !savedParamNames[index].StripStringLiterals().Contains(":="))
                    {
                        savedParamNames.RemoveAt(index);
                    }
                    else
                    {
                        var paramIndex = savedParamNames.FindIndex(s => s.StartsWith(param.Declaration.IdentifierName + ":="));
                        if (paramIndex != -1 && paramIndex < savedParamNames.Count)
                        {
                            savedParamNames.RemoveAt(paramIndex);
                        }
                    }
                }
            }

            newContent = newContent.Insert(paramList.Start.Column, string.Join(", ", savedParamNames));

            module.ReplaceLine(paramList.Start.Line, newContent.Replace(" _" + Environment.NewLine, string.Empty));
            module.DeleteLines(paramList.Start.Line + 1, lineCount - 1);
        }
Beispiel #23
0
        public CodeString Prettify(ICodeModule module, CodeString original)
        {
            var originalCode      = original.Code.Replace("\r", string.Empty).Split('\n');
            var originalPosition  = original.CaretPosition.StartColumn;
            var isAtLastCharacter = originalPosition == original.CaretLine.Length;

            var originalNonWhitespaceCharacters = 0;
            var isAllWhitespace = !isAtLastCharacter;

            if (!isAtLastCharacter)
            {
                for (var i = 0; i <= Math.Min(originalPosition - 1, original.CaretLine.Length - 1); i++)
                {
                    if (originalCode[original.CaretPosition.StartLine][i] != ' ')
                    {
                        originalNonWhitespaceCharacters++;
                        isAllWhitespace = false;
                    }
                }
            }

            var indent = original.CaretLine.TakeWhile(c => c == ' ').Count();

            module.DeleteLines(original.SnippetPosition.StartLine, original.SnippetPosition.LineCount);
            module.InsertLines(original.SnippetPosition.StartLine, string.Join("\r\n", originalCode));

            var prettifiedCode = module.GetLines(original.SnippetPosition)
                                 .Replace("\r", string.Empty)
                                 .Split('\n');

            var prettifiedNonWhitespaceCharacters = 0;
            var prettifiedCaretCharIndex          = 0;

            if (!isAtLastCharacter)
            {
                for (var i = 0; i < prettifiedCode[original.CaretPosition.StartLine].Length; i++)
                {
                    if (prettifiedCode[original.CaretPosition.StartLine][i] != ' ')
                    {
                        prettifiedNonWhitespaceCharacters++;
                        if (prettifiedNonWhitespaceCharacters == originalNonWhitespaceCharacters ||
                            i == prettifiedCode[original.CaretPosition.StartLine].Length - 1)
                        {
                            prettifiedCaretCharIndex = i;
                            break;
                        }
                    }
                }
            }
            else
            {
                prettifiedCaretCharIndex = prettifiedCode[original.CaretPosition.StartLine].Length;
            }

            var prettifiedPosition = new Selection(
                original.SnippetPosition.ToZeroBased().StartLine + original.CaretPosition.StartLine,
                prettifiedCode[original.CaretPosition.StartLine].Trim().Length == 0 || (isAllWhitespace && !string.IsNullOrEmpty(original.CaretLine.Substring(original.CaretPosition.StartColumn).Trim()))
                        ? Math.Min(indent, original.CaretPosition.StartColumn)
                        : Math.Min(prettifiedCode[original.CaretPosition.StartLine].Length, prettifiedCaretCharIndex + 1))
                                     .ToOneBased();

            SetSelection(module, prettifiedPosition);

            return(GetPrettifiedCodeString(original, prettifiedPosition, prettifiedCode));
        }
Beispiel #24
0
        private string GetReplacementLine(ICodeModule module, Declaration target, string newName)
        {
            var content = module.GetLines(target.Selection.StartLine, 1);

            if (target.DeclarationType == DeclarationType.Parameter)
            {
                var argContext = (VBAParser.ArgContext)target.Context;
                var rewriter   = _model.State.GetRewriter(target.QualifiedName.QualifiedModuleName.Component);
                rewriter.Replace(argContext.unrestrictedIdentifier().Start.TokenIndex, _model.NewName);

                // Target.Context is an ArgContext, its parent is an ArgsListContext;
                // the ArgsListContext's parent is the procedure context and it includes the body.
                var context         = (ParserRuleContext)target.Context.Parent.Parent;
                var firstTokenIndex = context.Start.TokenIndex;
                var lastTokenIndex  = -1; // will blow up if this code runs for any context other than below

                var subStmtContext = context as VBAParser.SubStmtContext;
                if (subStmtContext != null)
                {
                    lastTokenIndex = subStmtContext.argList().RPAREN().Symbol.TokenIndex;
                }

                var functionStmtContext = context as VBAParser.FunctionStmtContext;
                if (functionStmtContext != null)
                {
                    lastTokenIndex = functionStmtContext.asTypeClause() != null
                        ? functionStmtContext.asTypeClause().Stop.TokenIndex
                        : functionStmtContext.argList().RPAREN().Symbol.TokenIndex;
                }

                var propertyGetStmtContext = context as VBAParser.PropertyGetStmtContext;
                if (propertyGetStmtContext != null)
                {
                    lastTokenIndex = propertyGetStmtContext.asTypeClause() != null
                        ? propertyGetStmtContext.asTypeClause().Stop.TokenIndex
                        : propertyGetStmtContext.argList().RPAREN().Symbol.TokenIndex;
                }

                var propertyLetStmtContext = context as VBAParser.PropertyLetStmtContext;
                if (propertyLetStmtContext != null)
                {
                    lastTokenIndex = propertyLetStmtContext.argList().RPAREN().Symbol.TokenIndex;
                }

                var propertySetStmtContext = context as VBAParser.PropertySetStmtContext;
                if (propertySetStmtContext != null)
                {
                    lastTokenIndex = propertySetStmtContext.argList().RPAREN().Symbol.TokenIndex;
                }

                var declareStmtContext = context as VBAParser.DeclareStmtContext;
                if (declareStmtContext != null)
                {
                    lastTokenIndex = declareStmtContext.STRINGLITERAL().Last().Symbol.TokenIndex;
                    if (declareStmtContext.argList() != null)
                    {
                        lastTokenIndex = declareStmtContext.argList().RPAREN().Symbol.TokenIndex;
                    }
                    if (declareStmtContext.asTypeClause() != null)
                    {
                        lastTokenIndex = declareStmtContext.asTypeClause().Stop.TokenIndex;
                    }
                }

                var eventStmtContext = context as VBAParser.EventStmtContext;
                if (eventStmtContext != null)
                {
                    lastTokenIndex = eventStmtContext.argList().RPAREN().Symbol.TokenIndex;
                }

                return(rewriter.GetText(new Interval(firstTokenIndex, lastTokenIndex)));
            }
            return(GetReplacementLine(content, newName, target.Selection));
        }