static void RemoveCharBeforCaret (TextEditorData data) { if (!data.IsSomethingSelected && MonoDevelop.Ide.Editor.DefaultSourceEditorOptions.Instance.AutoInsertMatchingBracket) { if (data.Caret.Offset > 0) { var line = data.GetLine (data.Caret.Line); var stack = line.StartSpan.Clone(); if (stack.Any (s => s.Color == "string.other")) { DeleteActions.Backspace (data); return; } stack = line.StartSpan.Clone(); if (stack.Any (s => s.Color == "string.other")) { DeleteActions.Backspace (data); return; } char ch = data.Document.GetCharAt (data.Caret.Offset - 1); int idx = open.IndexOf (ch); if (idx >= 0) { int nextCharOffset = GetNextNonWsCharOffset (data, data.Caret.Offset); if (nextCharOffset >= 0 && closing[idx] == data.Document.GetCharAt (nextCharOffset)) { data.Remove (data.Caret.Offset, nextCharOffset - data.Caret.Offset + 1); } } } } DeleteActions.Backspace (data); }
public static CommandRange QuotedString(TextEditorData editor, char quotationChar) { var start = editor.Caret.Offset; var end = editor.Caret.Offset; var lineOffset = editor.GetLine(editor.Caret.Line).Offset; var lineEndOffset = editor.GetLine(editor.Caret.Line).EndOffset - 1; // Line includes \n if (editor.Text[start] == quotationChar) { // Check if we're on closing char start = lineOffset; var openingCandidate = -1; while (start < end) { if (editor.Text[start] == quotationChar & openingCandidate != -1) openingCandidate = -1; else if (editor.Text[start] == quotationChar) openingCandidate = start; start = start + 1; } if (openingCandidate != -1) { start = openingCandidate; } else { // not on closing char, let's find closing one start = editor.Caret.Offset; end = start + 1; while (end < lineEndOffset & editor.Text[end] != quotationChar) end++; } } else { while (start >= lineOffset & editor.Text[start] != quotationChar) start--; while (end < lineEndOffset & editor.Text[end] != quotationChar) end++; } if (start < 0 || end > lineEndOffset || start == end) return CommandRange.Empty; var endIncludingTrailingWhiteSpace = end; var startIncludingTrailingWhiteSpace = start; // expand to include all trailing white space while (endIncludingTrailingWhiteSpace < lineEndOffset && Char.IsWhiteSpace(editor.Text[endIncludingTrailingWhiteSpace + 1])) endIncludingTrailingWhiteSpace++; // if there's no trailing white space then include leading if (endIncludingTrailingWhiteSpace == end) { while (startIncludingTrailingWhiteSpace > lineOffset && Char.IsWhiteSpace(editor.Text[startIncludingTrailingWhiteSpace - 1])) startIncludingTrailingWhiteSpace--; } return new CommandRange(Math.Min(start, startIncludingTrailingWhiteSpace), Math.Max(end, endIncludingTrailingWhiteSpace) + 1); }
public void TestNamespaceBraceStyle () { TextEditorData data = new TextEditorData (); data.Document.FileName = "a.cs"; data.Document.Text = @"namespace A { namespace B { class Test {} } }"; CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); policy.NamespaceBraceStyle = BraceStyle.EndOfLine; policy.ClassBraceStyle = BraceStyle.DoNotChange; CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); Assert.AreEqual (@"namespace A { namespace B { class Test {} } }", data.Document.Text); policy.NamespaceBraceStyle = BraceStyle.NextLineShifted; compilationUnit = new CSharpParser ().Parse (data); compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); Assert.AreEqual (@"namespace A { namespace B { class Test {} } }", data.Document.Text); }
public static CommandRange InnerBlock(TextEditorData editor, char openingChar, char closingChar) { var range = Block(editor, openingChar, closingChar); if (range.Length == 0) return CommandRange.Empty; return new CommandRange(range.Start + 1, range.End - 1); }
public static CommandRange InnerQuotedString(TextEditorData editor, char enclosingChar) { var range = QuotedString(editor, enclosingChar); if (range.Length == 0) return CommandRange.Empty; return new CommandRange(range.Start + 1, range.End - 1); }
public static int RemoveTabInLine (TextEditorData data, DocumentLine line) { if (line.LengthIncludingDelimiter == 0) return 0; char ch = data.Document.GetCharAt (line.Offset); if (ch == '\t') { data.Remove (line.Offset, 1); data.Document.CommitLineUpdate (line); return 1; } else if (ch == ' ') { int removeCount = 0; for (int i = 0; i < data.Options.IndentationSize;) { ch = data.Document.GetCharAt (line.Offset + i); if (ch == ' ') { removeCount ++; i++; } else if (ch == '\t') { removeCount ++; i += data.Options.TabSize; } else { break; } } data.Remove (line.Offset, removeCount); data.Document.CommitLineUpdate (line); return removeCount; } return 0; }
public void TestBlankLinesBeforeUsings () { TextEditorData data = new TextEditorData (); data.Document.FileName = "a.cs"; data.Document.Text = @"using System; using System.Text; namespace Test { }"; CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); policy.BlankLinesAfterUsings = 0; policy.BlankLinesBeforeUsings = 2; var compilationUnit = new CSharpParser ().Parse (data); compilationUnit.AcceptVisitor (new AstIndentationVisitor (policy, data), null); Assert.AreEqual (@" using System; using System.Text; namespace Test { }", data.Document.Text); policy.BlankLinesBeforeUsings = 0; compilationUnit = new CSharpParser ().Parse (data); compilationUnit.AcceptVisitor (new AstIndentationVisitor (policy, data), null); Assert.AreEqual (@"using System; using System.Text; namespace Test { }", data.Document.Text); }
public override void CorrectIndenting (PolicyContainer policyParent, IEnumerable<string> mimeTypeChain, TextEditorData data, int line) { LineSegment lineSegment = data.Document.GetLine (line); if (lineSegment == null) return; var policy = policyParent.Get<CFormattingPolicy> (mimeTypeChain); var tracker = new DocumentStateTracker<CIndentEngine> (new CIndentEngine (policy), data); tracker.UpdateEngine (lineSegment.Offset); for (int i = lineSegment.Offset; i < lineSegment.Offset + lineSegment.EditableLength; i++) { tracker.Engine.Push (data.Document.GetCharAt (i)); } string curIndent = lineSegment.GetIndentation (data.Document); int nlwsp = curIndent.Length; if (!tracker.Engine.LineBeganInsideMultiLineComment || (nlwsp < lineSegment.Length && data.Document.GetCharAt (lineSegment.Offset + nlwsp) == '*')) { // Possibly replace the indent string newIndent = tracker.Engine.ThisLineIndent; if (newIndent != curIndent) data.Replace (lineSegment.Offset, nlwsp, newIndent); } tracker.Dispose (); }
static void RemoveCharBeforCaret (TextEditorData data) { if (((ISourceEditorOptions)data.Options).AutoInsertMatchingBracket) { if (data.Caret.Offset > 0) { var line = data.GetLine (data.Caret.Line); var stack = line.StartSpan.Clone(); if (stack.Any (s => s.Color == "string.other")) { DeleteActions.Backspace (data); return; } stack = line.StartSpan.Clone(); if (stack.Any (s => s.Color == "string.other")) { DeleteActions.Backspace (data); return; } char ch = data.Document.GetCharAt (data.Caret.Offset - 1); int idx = open.IndexOf (ch); if (idx >= 0) { int nextCharOffset = GetNextNonWsCharOffset (data, data.Caret.Offset); if (nextCharOffset >= 0 && closing[idx] == data.Document.GetCharAt (nextCharOffset)) { bool updateToEnd = data.Document.OffsetToLineNumber (nextCharOffset) != data.Caret.Line; data.Remove (data.Caret.Offset, nextCharOffset - data.Caret.Offset + 1); } } } } DeleteActions.Backspace (data); }
public override void CorrectIndenting (PolicyContainer policyParent, IEnumerable<string> mimeTypeChain, TextEditorData data, int line) { DocumentLine lineSegment = data.Document.GetLine (line); if (lineSegment == null) return; try { var policy = policyParent.Get<CSharpFormattingPolicy> (mimeTypeChain); var tracker = new CSharpIndentEngine (data.Document, data.CreateNRefactoryTextEditorOptions (), policy.CreateOptions ()); tracker.Update (lineSegment.Offset); for (int i = lineSegment.Offset; i < lineSegment.Offset + lineSegment.Length; i++) { tracker.Push (data.Document.GetCharAt (i)); } string curIndent = lineSegment.GetIndentation (data.Document); int nlwsp = curIndent.Length; if (!tracker.LineBeganInsideMultiLineComment || (nlwsp < lineSegment.LengthIncludingDelimiter && data.Document.GetCharAt (lineSegment.Offset + nlwsp) == '*')) { // Possibly replace the indent string newIndent = tracker.ThisLineIndent; if (newIndent != curIndent) data.Replace (lineSegment.Offset, nlwsp, newIndent); } } catch (Exception e) { LoggingService.LogError ("Error while indenting", e); } }
public string FormatText (CSharpFormattingPolicy policy, TextStylePolicy textPolicy, string mimeType, string input, int startOffset, int endOffset) { var data = new TextEditorData (); data.Document.SuppressHighlightUpdate = true; data.Document.MimeType = mimeType; data.Document.FileName = "toformat.cs"; if (textPolicy != null) { data.Options.TabsToSpaces = textPolicy.TabsToSpaces; data.Options.TabSize = textPolicy.TabWidth; data.Options.IndentationSize = textPolicy.IndentWidth; data.Options.IndentStyle = textPolicy.RemoveTrailingWhitespace ? IndentStyle.Virtual : IndentStyle.Smart; } data.Text = input; // System.Console.WriteLine ("-----"); // System.Console.WriteLine (data.Text.Replace (" ", ".").Replace ("\t", "->")); // System.Console.WriteLine ("-----"); var parser = new CSharpParser (); var compilationUnit = parser.Parse (data); bool hadErrors = parser.HasErrors; if (hadErrors) { // foreach (var e in parser.ErrorReportPrinter.Errors) // Console.WriteLine (e.Message); return input.Substring (startOffset, Math.Max (0, Math.Min (endOffset, input.Length) - startOffset)); } var originalVersion = data.Document.Version; var textEditorOptions = data.CreateNRefactoryTextEditorOptions (); var formattingVisitor = new ICSharpCode.NRefactory.CSharp.CSharpFormatter ( policy.CreateOptions (), textEditorOptions ) { FormattingMode = FormattingMode.Intrusive }; var changes = formattingVisitor.AnalyzeFormatting (data.Document, compilationUnit); try { changes.ApplyChanges (startOffset, endOffset - startOffset); } catch (Exception e) { LoggingService.LogError ("Error in code formatter", e); return input.Substring (startOffset, Math.Max (0, Math.Min (endOffset, input.Length) - startOffset)); } // check if the formatter has produced errors parser = new CSharpParser (); parser.Parse (data); if (parser.HasErrors) { LoggingService.LogError ("C# formatter produced source code errors. See console for output."); return input.Substring (startOffset, Math.Max (0, Math.Min (endOffset, input.Length) - startOffset)); } var currentVersion = data.Document.Version; string result = data.GetTextBetween (startOffset, originalVersion.MoveOffsetTo (currentVersion, endOffset, ICSharpCode.NRefactory.Editor.AnchorMovementType.Default)); data.Dispose (); return result; }
public static void Left (TextEditorData data) { if (Platform.IsMac && data.IsSomethingSelected && !data.Caret.PreserveSelection) { data.Caret.Offset = System.Math.Min (data.SelectionAnchor, data.Caret.Offset); data.ClearSelection (); return; } LineSegment line = data.Document.GetLine (data.Caret.Line); IEnumerable<FoldSegment> foldings = data.Document.GetEndFoldings (line); FoldSegment segment = null; foreach (FoldSegment folding in foldings) { if (folding.IsFolded && folding.EndColumn == data.Caret.Column) { segment = folding; break; } } if (segment != null) { data.Caret.Location = data.Document.OffsetToLocation (segment.StartLine.Offset + segment.Column); return; } if (data.Caret.Column > 0) { if (data.Caret.Column > line.EditableLength) { data.Caret.Column = line.EditableLength; } else { data.Caret.Column--; } } else if (data.Caret.Line > 0) { LineSegment prevLine = data.Document.GetLine (data.Caret.Line - 1); data.Caret.Location = new DocumentLocation (data.Caret.Line - 1, prevLine.EditableLength); } }
public void LoadMark(TextEditorData data) { // remember where the caret currently is int lineNumber = data.Caret.Line; int colNumber = data.Caret.Column; // get the line number stored with this mark int x = (base.LineSegment == null)? 1 : base.LineSegment.LineNumber; // reposition the caret on the stored line data.Caret.Line = x; int len = base.LineSegment.LengthIncludingDelimiter; if (ColumnNumber >= len) { // Check if the line has been truncated after the setting the mark data.Caret.Column = len - 1; } else { data.Caret.Column = ColumnNumber; } if (MarkCharacter == '`') { data.Document.RemoveMarker (this); base.LineSegment = data.Document.GetLine(lineNumber); ColumnNumber = colNumber; Console.WriteLine ("Line before jump: {0}", lineNumber); data.Document.AddMarker (lineNumber, this); data.Document.RequestUpdate (new UpdateAll ()); data.Document.CommitDocumentUpdate (); } }
public HeightTree (TextEditorData editor) { this.editor = editor; this.editor.Document.Splitter.LineRemoved += HandleLineRemoved; this.editor.Document.Splitter.LineInserted += HandleLineInserted; this.editor.Document.FoldTreeUpdated += HandleFoldTreeUpdated; }
public static CommandRange InnerBlock(TextEditorData editor, char openingChar, char closingChar) { var range = Block(editor, openingChar, closingChar); if (range.Length == 0) return CommandRange.Empty; int start = range.Start + 1; int end = range.End - 2; var line = editor.GetLine(editor.OffsetToLineNumber(range.Start)); // exclude newline if it comes just after opening char if (line.EndOffsetIncludingDelimiter - start <= line.DelimiterLength) start += line.DelimiterLength; // exclude whitespace that comes just before the closing char... line = editor.GetLine(editor.OffsetToLineNumber(range.End)); while (Char.IsWhiteSpace(editor.Text[end]) && end >= line.Offset) end--; //.. but only if newline comes after it if (end >= line.Offset) end = range.End - 2; else end -= line.PreviousLine.DelimiterLength; if (start > end + 1) return new CommandRange(start, start); return new CommandRange(start, end+1); }
/// <summary> /// Used for formatting the entire document /// </summary> public override string FormatText(PolicyContainer policyParent, IEnumerable<string> mimeTypeChain, string input, int startOffset, int endOffset) { var policy = policyParent.Get<DFormattingPolicy> (mimeTypeChain); var textPolicy = policyParent.Get<TextStylePolicy> (mimeTypeChain); var data = new TextEditorData{ Text = input }; if(IndentCorrectionOnly) { using(var s = data.OpenStream()) using(var r = new StreamReader(s)) D_Parser.Formatting.Indent.IndentEngineWrapper.CorrectIndent(r, startOffset, endOffset, data.Document.Replace, policy.Options, new TextStyleAdapter(textPolicy)); return data.Text; } var ast = DParser.ParseString(input, false, true) as DModule; var formattingVisitor = new DFormattingVisitor(policy.Options, new DocAdapt(data.Document), ast, new TextStyleAdapter(textPolicy)); // Only clip to a region if it's necessary if(startOffset > 0 || endOffset < input.Length-1) { formattingVisitor.CheckFormattingBoundaries = true; var dl = data.Document.OffsetToLocation(startOffset); formattingVisitor.FormattingStartLocation = new D_Parser.Dom.CodeLocation(dl.Column, dl.Line); dl = data.Document.OffsetToLocation(endOffset); formattingVisitor.FormattingEndLocation = new D_Parser.Dom.CodeLocation(dl.Column, dl.Line); } formattingVisitor.WalkThroughAst(); formattingVisitor.ApplyChanges(data.Document.Replace); return data.Text; }
public GenerateNamespaceImport GetResult (ProjectDom dom, ICompilationUnit unit, IType type, TextEditorData data) { GenerateNamespaceImport result; if (cache.TryGetValue (type.Namespace, out result)) return result; result = new GenerateNamespaceImport (); cache[type.Namespace] = result; result.InsertNamespace = false; DomLocation location = new DomLocation (data.Caret.Line, data.Caret.Column); foreach (IUsing u in unit.Usings.Where (u => u.ValidRegion.Contains (location))) { if (u.Namespaces.Any (ns => type.Namespace == ns)) { result.GenerateUsing = false; return result; } } result.GenerateUsing = true; string name = type.DecoratedFullName.Substring (type.Namespace.Length + 1); foreach (IUsing u in unit.Usings.Where (u => u.ValidRegion.Contains (location))) { foreach (string ns in u.Namespaces) { if (dom.SearchType (unit, unit.GetTypeAt (location), unit.GetMemberAt (location), ns + "." + name) != null) { result.GenerateUsing = false; result.InsertNamespace = true; return result; } } } return result; }
static void TestInsertionPoints (string text) { TextEditorData data = new TextEditorData (); List<InsertionPoint> loc = new List<InsertionPoint> (); for (int i = 0; i < text.Length; i++) { char ch = text[i]; if (ch == '@') { i++; ch = text[i]; loc.Add (new InsertionPoint (data.Document.OffsetToLocation (data.Document.Length), ch == '3' || ch == '2', ch == '3' || ch == '1')); } else { data.Insert (data.Document.Length, ch.ToString ()); } } var parseResult = new NRefactoryParser ().Parse (null, "a.cs", data.Document.Text); var foundPoints = HelperMethods.GetInsertionPoints (data.Document, parseResult.CompilationUnit.Types[0]); Assert.AreEqual (loc.Count, foundPoints.Count, "point count doesn't match"); for (int i = 0; i < loc.Count; i++) { Console.WriteLine (loc[i] + "/" + foundPoints[i]); Assert.AreEqual (loc[i].Location, foundPoints[i].Location, "point " + i + " doesn't match"); Assert.AreEqual (loc[i].ShouldInsertNewLineAfter, foundPoints[i].ShouldInsertNewLineAfter, "point " + i + " ShouldInsertNewLineAfter doesn't match"); Assert.AreEqual (loc[i].ShouldInsertNewLineBefore, foundPoints[i].ShouldInsertNewLineBefore, "point " + i + " ShouldInsertNewLineBefore doesn't match"); } }
List<ReferenceSegment> IAssemblyBrowserNodeBuilder.Disassemble (TextEditorData data, ITreeNavigator navigator) { if (DomMethodNodeBuilder.HandleSourceCodeEntity (navigator, data)) return null; var field = CecilLoader.GetCecilObject ((IUnresolvedField)navigator.DataItem); return DomMethodNodeBuilder.Disassemble (data, rd => rd.DisassembleField (field)); }
public void TestIndentClassBody () { TextEditorData data = new TextEditorData (); data.Document.FileName = "a.cs"; data.Document.Text = @"class Test { Test a; }"; CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); policy.IndentClassBody = true; CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); Assert.AreEqual (@"class Test { Test a; }", data.Document.Text); policy.IndentClassBody = false; compilationUnit = new CSharpParser ().Parse (data); compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); Assert.AreEqual (@"class Test { Test a; }", data.Document.Text); }
public static void Format (TextEditorData data, ProjectDom dom, DomLocation location, bool correctBlankLines) { PolicyContainer policyParent = dom != null && dom.Project != null? dom.Project.Policies : PolicyService.DefaultPolicies; var mimeTypeChain = DesktopService.GetMimeTypeInheritanceChain (CSharpFormatter.MimeType); Format (policyParent, mimeTypeChain, data, dom, location, correctBlankLines); }
public virtual bool GetSelectionSurroundings (TextEditorData textEditorData, uint unicodeKey, out string start, out string end) { switch ((char)unicodeKey) { case '"': start = end = "\""; return true; case '\'': start = end = "'"; return true; case '(': start = "("; end = ")"; return true; case '<': start = "<"; end = ">"; return true; case '[': start = "["; end = "]"; return true; case '{': start = "{"; end = "}"; return true; default: start = end = ""; return false; } }
public NRefactoryIndexerParameterDataProvider (TextEditorData editor, IType type, string resolvedExpression) { // this.editor = editor; // this.type = type; this.resolvedExpression = resolvedExpression; indexers = new List<IProperty> (type.Properties.Where (p => p.IsIndexer && !p.Name.Contains ('.'))); }
public static void Left (TextEditorData data) { if (Platform.IsMac && data.IsSomethingSelected && !data.Caret.PreserveSelection) { data.Caret.Offset = System.Math.Min (data.SelectionAnchor, data.Caret.Offset); data.ClearSelection (); return; } if (data.Caret.Column > DocumentLocation.MinColumn) { DocumentLine line = data.Document.GetLine (data.Caret.Line); if (data.Caret.Column > line.Length + 1) { if (data.Caret.AllowCaretBehindLineEnd) { data.Caret.Column--; } else { data.Caret.Column = line.Length + 1; } } else { int offset = data.Caret.Offset - 1; foreach (var folding in data.Document.GetFoldingsFromOffset (offset).Where (f => f.IsFolded && f.Offset < offset)) { offset = System.Math.Min (offset, folding.Offset); } data.Caret.Offset = offset; } } else if (data.Caret.Line > DocumentLocation.MinLine) { DocumentLine prevLine = data.Document.GetLine (data.Caret.Line - 1); var nextLocation = new DocumentLocation (data.Caret.Line - 1, prevLine.Length + 1); if (data.HasIndentationTracker && data.Options.IndentStyle == IndentStyle.Virtual && nextLocation.Column == DocumentLocation.MinColumn) nextLocation = new DocumentLocation (data.Caret.Line - 1, data.GetVirtualIndentationColumn (nextLocation)); data.Caret.Location = nextLocation; } }
public static void GotoPrevious (TextEditorData data) { int offset = GetPrevOffset (data.Document, data.Caret.Line); if (offset < 0) offset = GetPrevOffset (data.Document, data.Document.LineCount); if (offset >= 0) data.Caret.Offset = offset; }
DocumentStateTracker<CSharpIndentEngine> CreateTracker (TextEditorData data) { var policy = PolicyService.InvariantPolicies.Get <CSharpFormattingPolicy> ("text/x-csharp"); var textStylePolicy = PolicyService.InvariantPolicies.Get <TextStylePolicy> ("text/x-csharp"); var result = new DocumentStateTracker<CSharpIndentEngine> (new CSharpIndentEngine (policy, textStylePolicy), data); result.UpdateEngine (); return result; }
public static void GotoNext (TextEditorData data) { int offset = GetNextOffset (data.Document, data.Caret.Line); if (offset < 0) offset = GetNextOffset (data.Document, -1); if (offset >= 0) data.Caret.Offset = offset; }
public static void StartSelection (TextEditorData data) { data.Caret.PreserveSelection = true; if (!data.IsSomethingSelected) { data.MainSelection = new Selection (data.Caret.Location, data.Caret.Location); } data.Caret.AutoScrollToCaret = false; }
InvocationExpression GetInvocation (MonoDevelop.CSharp.Dom.CompilationUnit unit, TextEditorData data) { var containingNode = unit.GetNodeAt (data.Caret.Line, data.Caret.Column); var curNode = containingNode; while (curNode != null && !(curNode is InvocationExpression)) { curNode = curNode.Parent; } return curNode as InvocationExpression; }
public static void GotoMatchingBracket (TextEditorData data) { int matchingBracketOffset = data.Document.GetMatchingBracketOffset (data.Caret.Offset); if (matchingBracketOffset == -1 && data.Caret.Offset > 0) matchingBracketOffset = data.Document.GetMatchingBracketOffset (data.Caret.Offset - 1); if (matchingBracketOffset != -1) data.Caret.Offset = matchingBracketOffset; }
public static void MoveRight(TextEditorData data) { Select(data, CaretMoveActions.Right); }
public TextEditorDataEventArgs(TextEditorData data) { this.data = data; }
MemberReference GetReference(ResolveResult result, AstNode node, string fileName, Mono.TextEditor.TextEditorData editor) { if (result == null) { return(null); } object valid = null; if (result is MethodGroupResolveResult) { valid = ((MethodGroupResolveResult)result).Methods.FirstOrDefault( m => searchedMembers.Any(member => member is IMethod && ((IMethod)member).Region == m.Region)); } else if (result is MemberResolveResult) { var foundMember = ((MemberResolveResult)result).Member; valid = searchedMembers.FirstOrDefault( member => member is IMember && ((IMember)member).Region == foundMember.Region); } else if (result is NamespaceResolveResult) { var ns = ((NamespaceResolveResult)result).NamespaceName; valid = searchedMembers.FirstOrDefault(n => n is string && n.ToString() == ns); } else if (result is LocalResolveResult) { var ns = ((LocalResolveResult)result).Variable; valid = searchedMembers.FirstOrDefault(n => n is IVariable && ((IVariable)n).Region == ns.Region); } else if (result is TypeResolveResult) { valid = searchedMembers.FirstOrDefault(n => n is IType); } else { valid = searchedMembers.FirstOrDefault(); } if (node is ConstructorInitializer) { return(null); } if (node is ObjectCreateExpression) { node = ((ObjectCreateExpression)node).Type; } if (node is InvocationExpression) { node = ((InvocationExpression)node).Target; } if (node is MemberReferenceExpression) { node = ((MemberReferenceExpression)node).MemberNameToken; } if (node is SimpleType) { node = ((SimpleType)node).IdentifierToken; } if (node is MemberType) { node = ((MemberType)node).MemberNameToken; } if (node is TypeDeclaration && (searchedMembers.First() is IType)) { node = ((TypeDeclaration)node).NameToken; } if (node is DelegateDeclaration) { node = ((DelegateDeclaration)node).NameToken; } if (node is EntityDeclaration && (searchedMembers.First() is IMember)) { node = ((EntityDeclaration)node).NameToken; } if (node is ParameterDeclaration && (searchedMembers.First() is IParameter)) { node = ((ParameterDeclaration)node).NameToken; } if (node is ConstructorDeclaration) { node = ((ConstructorDeclaration)node).NameToken; } if (node is DestructorDeclaration) { node = ((DestructorDeclaration)node).NameToken; } if (node is NamedArgumentExpression) { node = ((NamedArgumentExpression)node).NameToken; } if (node is NamedExpression) { node = ((NamedExpression)node).NameToken; } if (node is VariableInitializer) { node = ((VariableInitializer)node).NameToken; } if (node is IdentifierExpression) { node = ((IdentifierExpression)node).IdentifierToken; } var region = new DomRegion(fileName, node.StartLocation, node.EndLocation); var length = node is PrimitiveType ? keywordName.Length : node.EndLocation.Column - node.StartLocation.Column; return(new MemberReference(valid, region, editor.LocationToOffset(region.Begin), length)); }
protected virtual void OnRemovedFromEditor(TextEditorData data) { }
protected virtual void OnAddedToEditor(TextEditorData data) { }
public static void MoveDownLineEnd(TextEditorData data) { Select(data, CaretMoveActions.DownLineEnd); }
public static void SelectAll(TextEditorData data) { data.Caret.PreserveSelection = true; data.MainSelection = new Selection(new DocumentLocation(DocumentLocation.MinLine, DocumentLocation.MinColumn), data.OffsetToLocation(data.Length)); data.Caret.PreserveSelection = false; }
public static void EndSelection(TextEditorData data) { data.ExtendSelectionTo(data.Caret.Location); data.Caret.AutoScrollToCaret = true; data.Caret.PreserveSelection = false; }
public static void ClearSelection(TextEditorData data) { data.ClearSelection(); }
public void HandleSpecialSelectionKey(TextEditorData textEditorData, uint unicodeKey) { throw new NotSupportedException(); }
public int GetAnchorOffset(TextEditorData data) { return(data.Document.LocationToOffset(Anchor)); }
public DIndentationTracker(Mono.TextEditor.TextEditorData data, DocumentStateTracker <DIndentEngine> stateTracker) { this.data = data; this.stateTracker = stateTracker; }
public static void MovePreviousSubword(TextEditorData data) { Select(data, CaretMoveActions.PreviousSubword); }
public static void MoveUpLineStart(TextEditorData data) { Select(data, CaretMoveActions.UpLineStart); }
public static void MoveLeft(TextEditorData data) { Select(data, CaretMoveActions.Left); }
public static void MovePageDown(TextEditorData data) { Select(data, CaretMoveActions.PageDown); }
MemberReference GetReference(Project project, ResolveResult result, AstNode node, SyntaxTree syntaxTree, string fileName, Mono.TextEditor.TextEditorData editor) { AstNode originalNode = node; if (result == null) { return(null); } object valid = null; if (result is MethodGroupResolveResult) { valid = ((MethodGroupResolveResult)result).Methods.FirstOrDefault( m => searchedMembers.Any(member => member is IMethod && ((IMethod)member).Region == m.Region)); } else if (result is MemberResolveResult) { var foundMember = ((MemberResolveResult)result).Member; valid = searchedMembers.FirstOrDefault( member => member is IMember && ((IMember)member).Region == foundMember.Region); } else if (result is NamespaceResolveResult) { var ns = ((NamespaceResolveResult)result).Namespace; valid = searchedMembers.FirstOrDefault(n => n is INamespace && ns.FullName.StartsWith(((INamespace)n).FullName, StringComparison.Ordinal)); if (!(node is NamespaceDeclaration)) { goto skip; } } else if (result is LocalResolveResult) { var ns = ((LocalResolveResult)result).Variable; valid = searchedMembers.FirstOrDefault(n => n is IVariable && ((IVariable)n).Region == ns.Region); } else if (result is TypeResolveResult) { valid = searchedMembers.FirstOrDefault(n => n is IType); } if (node is ConstructorInitializer) { return(null); } if (node is ObjectCreateExpression) { node = ((ObjectCreateExpression)node).Type; } if (node is IndexerDeclaration) { node = ((IndexerDeclaration)node).ThisToken; } if (node is InvocationExpression) { node = ((InvocationExpression)node).Target; } if (node is MemberReferenceExpression) { node = ((MemberReferenceExpression)node).MemberNameToken; } if (node is SimpleType) { node = ((SimpleType)node).IdentifierToken; } if (node is MemberType) { node = ((MemberType)node).MemberNameToken; } if (node is NamespaceDeclaration) { var nsd = ((NamespaceDeclaration)node); node = nsd.NamespaceName; if (node == null) { return(null); } } if (node is TypeDeclaration && (searchedMembers.First() is IType)) { node = ((TypeDeclaration)node).NameToken; } if (node is DelegateDeclaration) { node = ((DelegateDeclaration)node).NameToken; } if (node is EntityDeclaration && (searchedMembers.First() is IMember)) { node = ((EntityDeclaration)node).NameToken; } if (node is ParameterDeclaration && (searchedMembers.First() is IParameter)) { node = ((ParameterDeclaration)node).NameToken; } if (node is ConstructorDeclaration) { node = ((ConstructorDeclaration)node).NameToken; } if (node is DestructorDeclaration) { node = ((DestructorDeclaration)node).NameToken; } if (node is NamedArgumentExpression) { node = ((NamedArgumentExpression)node).NameToken; } if (node is NamedExpression) { node = ((NamedExpression)node).NameToken; } if (node is VariableInitializer) { node = ((VariableInitializer)node).NameToken; } if (node is IdentifierExpression) { node = ((IdentifierExpression)node).IdentifierToken; } skip: var region = new DomRegion(fileName, node.StartLocation, node.EndLocation); var length = node is PrimitiveType ? keywordName.Length : node.EndLocation.Column - node.StartLocation.Column; if (valid == null) { valid = searchedMembers.FirstOrDefault(); } var reference = new CSharpMemberReference(project, originalNode, syntaxTree, valid, region, editor.LocationToOffset(region.Begin), length); reference.ReferenceUsageType = GetUsage(originalNode); return(reference); }
public static void MoveToDocumentEnd(TextEditorData data) { Select(data, CaretMoveActions.ToDocumentEnd); }
internal void RemovedFromEditor(TextEditorData data) { OnRemovedFromEditor(data); }
public static void MoveLineHome(TextEditorData data) { Select(data, CaretMoveActions.LineHome); }
internal void AddedToEditor(TextEditorData data) { OnAddedToEditor(data); }
public static void MoveUp(TextEditorData data) { Select(data, CaretMoveActions.Up); }
void CopyData(TextEditorData data, Selection selection) { copiedDocument = null; monoDocument = null; if (!selection.IsEmpty && data != null && data.Document != null) { copiedDocument = new TextDocument(); monoDocument = new TextDocument(); this.docStyle = data.ColorStyle; this.options = data.Options; copyData = null; copiedColoredChunks = ColoredSegment.GetChunks(data, data.SelectionRange); switch (selection.SelectionMode) { case SelectionMode.Normal: isBlockMode = false; var segment = selection.GetSelectionRange(data); var pasteHandler = data.TextPasteHandler; if (pasteHandler != null) { copyData = pasteHandler.GetCopyData(segment); } var text = data.GetTextAt(segment); copiedDocument.Text = text; monoDocument.Text = text; var line = data.Document.GetLineByOffset(segment.Offset); var spanStack = line.StartSpan.Clone(); this.copiedDocument.GetLine(DocumentLocation.MinLine).StartSpan = spanStack; break; case SelectionMode.Block: isBlockMode = true; DocumentLocation visStart = data.LogicalToVisualLocation(selection.Anchor); DocumentLocation visEnd = data.LogicalToVisualLocation(selection.Lead); int startCol = System.Math.Min(visStart.Column, visEnd.Column); int endCol = System.Math.Max(visStart.Column, visEnd.Column); for (int lineNr = selection.MinLine; lineNr <= selection.MaxLine; lineNr++) { DocumentLine curLine = data.Document.GetLine(lineNr); int col1 = curLine.GetLogicalColumn(data, startCol) - 1; int col2 = System.Math.Min(curLine.GetLogicalColumn(data, endCol) - 1, curLine.Length); if (col1 < col2) { copiedDocument.Insert(copiedDocument.TextLength, data.Document.GetTextAt(curLine.Offset + col1, col2 - col1)); monoDocument.Insert(monoDocument.TextLength, data.Document.GetTextAt(curLine.Offset + col1, col2 - col1)); } if (lineNr < selection.MaxLine) { // Clipboard line end needs to be system dependend and not the document one. copiedDocument.Insert(copiedDocument.TextLength, Environment.NewLine); // \r in mono document stands for block selection line end. monoDocument.Insert(monoDocument.TextLength, "\r"); } } line = data.Document.GetLine(selection.MinLine); spanStack = line.StartSpan.Clone(); this.copiedDocument.GetLine(DocumentLocation.MinLine).StartSpan = spanStack; break; } } else { copiedDocument = null; } }
public static void MoveNextSubword(TextEditorData data) { Select(data, CaretMoveActions.NextSubword); }
public int GetLeadOffset(TextEditorData data) { return(data.Document.LocationToOffset(Lead)); }
public PositionChangedHandler(TextEditorData data) { this.data = data; }
static int PasteFrom(Clipboard clipboard, TextEditorData data, bool preserveSelection, int insertionOffset, bool preserveState) { int result = -1; if (!data.CanEdit(data.Document.OffsetToLineNumber(insertionOffset))) { return(result); } if (clipboard.WaitIsTargetAvailable(CopyOperation.MD_ATOM)) { clipboard.RequestContents(CopyOperation.MD_ATOM, delegate(Clipboard clp, SelectionData selectionData) { if (selectionData.Length > 0) { byte[] selBytes = selectionData.Data; var upperBound = System.Math.Max(0, System.Math.Min(selBytes [1], selBytes.Length - 2)); byte[] copyData = new byte[upperBound]; Array.Copy(selBytes, 2, copyData, 0, copyData.Length); var rawTextOffset = 1 + 1 + copyData.Length; string text = Encoding.UTF8.GetString(selBytes, rawTextOffset, selBytes.Length - rawTextOffset); bool pasteBlock = (selBytes [0] & 1) == 1; bool pasteLine = (selBytes [0] & 2) == 2; if (pasteBlock) { using (var undo = data.OpenUndoGroup()) { var version = data.Document.Version; if (!preserveSelection) { data.DeleteSelectedText(!data.IsSomethingSelected || data.MainSelection.SelectionMode != SelectionMode.Block); } int startLine = data.Caret.Line; data.EnsureCaretIsNotVirtual(); insertionOffset = version.MoveOffsetTo(data.Document.Version, insertionOffset); data.Caret.PreserveSelection = true; var lines = new List <string> (); int offset = 0; while (true) { var delimiter = LineSplitter.NextDelimiter(text, offset); if (delimiter.IsInvalid) { break; } int delimiterEndOffset = delimiter.EndOffset; lines.Add(text.Substring(offset, delimiter.Offset - offset)); offset = delimiterEndOffset; } if (offset < text.Length) { lines.Add(text.Substring(offset, text.Length - offset)); } int lineNr = data.Document.OffsetToLineNumber(insertionOffset); int col = insertionOffset - data.Document.GetLine(lineNr).Offset; int visCol = data.Document.GetLine(lineNr).GetVisualColumn(data, col); DocumentLine curLine; int lineCol = col; result = 0; for (int i = 0; i < lines.Count; i++) { while (data.Document.LineCount <= lineNr + i) { data.Insert(data.Document.TextLength, Environment.NewLine); result += Environment.NewLine.Length; } curLine = data.Document.GetLine(lineNr + i); if (lines [i].Length > 0) { lineCol = curLine.GetLogicalColumn(data, visCol); if (curLine.Length + 1 < lineCol) { result += lineCol - curLine.Length; data.Insert(curLine.Offset + curLine.Length, new string (' ', lineCol - curLine.Length)); } data.Insert(curLine.Offset + lineCol, lines [i]); result += lines [i].Length; } if (!preserveState) { data.Caret.Offset = curLine.Offset + lineCol + lines [i].Length; } } if (!preserveState) { data.ClearSelection(); } data.FixVirtualIndentation(startLine); data.Caret.PreserveSelection = false; } } else if (pasteLine) { using (var undo = data.OpenUndoGroup()) { if (!preserveSelection) { data.DeleteSelectedText(!data.IsSomethingSelected || data.MainSelection.SelectionMode != SelectionMode.Block); } data.EnsureCaretIsNotVirtual(); data.Caret.PreserveSelection = true; result = text.Length; DocumentLine curLine = data.Document.GetLine(data.Caret.Line); result = PastePlainText(data, curLine.Offset, text + data.EolMarker, preserveSelection, copyData); if (!preserveState) { data.ClearSelection(); } data.Caret.PreserveSelection = false; data.FixVirtualIndentation(curLine.LineNumber); } } else { result = PastePlainText(data, insertionOffset, text, preserveSelection, copyData); } } }); // we got MD_ATOM text - no need to request text. (otherwise buffer may get copied twice). return(result); } if (result < 0 && clipboard.WaitIsTextAvailable()) { clipboard.RequestText(delegate(Clipboard clp, string text) { if (string.IsNullOrEmpty(text)) { return; } result = PastePlainText(data, insertionOffset, text, preserveSelection); }); } return(result); }
public bool GetSelectionSurroundings(TextEditorData textEditorData, uint unicodeKey, out string start, out string end) { start = end = ""; return(false); }
static int PasteFrom(Clipboard clipboard, TextEditorData data, bool preserveSelection, int insertionOffset) { return(PasteFrom(clipboard, data, preserveSelection, insertionOffset, false)); }
public MonoDevelop.Projects.Dom.ResolveResult GetLanguageItem(ProjectDom dom, Mono.TextEditor.TextEditorData data, int offset) { if (offset < 0) { return(null); } string fileName = data.Document.FileName; IParser parser = ProjectDomService.GetParser(fileName); if (parser == null) { return(null); } MonoDevelop.Ide.Gui.Document doc = IdeApp.Workbench.ActiveDocument; if (doc == null) { return(null); } IResolver resolver = parser.CreateResolver(dom, doc, fileName); if (resolver == null) { return(null); } var expressionFinder = new NewCSharpExpressionFinder(dom); int wordEnd = Math.Min(offset, data.Length - 1); if (wordEnd < 0) { return(null); } if (data.GetCharAt(wordEnd) == '@') { wordEnd++; } while (wordEnd < data.Length && (Char.IsLetterOrDigit(data.GetCharAt(wordEnd)) || data.GetCharAt(wordEnd) == '_')) { wordEnd++; } while (wordEnd < data.Length - 1 && Char.IsWhiteSpace(data.GetCharAt(wordEnd))) { wordEnd++; } /* is checked at the end. * int saveEnd = wordEnd; * if (wordEnd < data.Length && data.GetCharAt (wordEnd) == '<') { * int matchingBracket = data.Document.GetMatchingBracketOffset (wordEnd); * if (matchingBracket > 0) * wordEnd = matchingBracket; * while (wordEnd < data.Length - 1 && Char.IsWhiteSpace (data.GetCharAt (wordEnd))) * wordEnd++; * } * * bool wasMethodCall = false; * if (data.GetCharAt (wordEnd) == '(') { * int matchingBracket = data.Document.GetMatchingBracketOffset (wordEnd); * if (matchingBracket > 0) { * wordEnd = matchingBracket; * wasMethodCall = true; * } * } * if (!wasMethodCall) * wordEnd = saveEnd;*/ ExpressionResult expressionResult = expressionFinder.FindExpression(data, wordEnd); if (expressionResult == null) { return(null); } ResolveResult resolveResult; DocumentLocation loc = data.Document.OffsetToLocation(offset); string savedExpression = null; // special handling for 'var' "keyword" if (expressionResult.ExpressionContext == ExpressionContext.IdentifierExpected && expressionResult.Expression != null && expressionResult.Expression.Trim() == "var") { int endOffset = data.Document.LocationToOffset(expressionResult.Region.End.Line, expressionResult.Region.End.Column); StringBuilder identifer = new StringBuilder(); for (int i = endOffset; i >= 0 && i < data.Document.Length; i++) { char ch = data.Document.GetCharAt(i); if (Char.IsWhiteSpace(ch)) { if (identifer.Length > 0) { break; } continue; } if (ch == '=' || ch == ';') { break; } if (Char.IsLetterOrDigit(ch) || ch == '_') { identifer.Append(ch); continue; } identifer.Length = 0; break; } if (identifer.Length > 0) { expressionResult.Expression = identifer.ToString(); resolveResult = resolver.Resolve(expressionResult, new DomLocation(loc.Line, int.MaxValue)); if (resolveResult != null) { resolveResult = new MemberResolveResult(dom.GetType(resolveResult.ResolvedType)); resolveResult.ResolvedExpression = expressionResult; return(resolveResult); } } } if (expressionResult.ExpressionContext == ExpressionContext.Attribute && !string.IsNullOrEmpty(expressionResult.Expression)) { savedExpression = expressionResult.Expression; expressionResult.Expression = expressionResult.Expression.Trim() + "Attribute"; expressionResult.ExpressionContext = ExpressionContext.ObjectCreation; } resolveResult = resolver.Resolve(expressionResult, new DomLocation(loc.Line, loc.Column)); if (savedExpression != null && resolveResult == null) { expressionResult.Expression = savedExpression; resolveResult = resolver.Resolve(expressionResult, new DomLocation(loc.Line, loc.Column)); } // identifier may not be valid at that point, try to resolve it at line end (ex. foreach loop variable) if (resolveResult != null && (resolveResult.ResolvedType == null || string.IsNullOrEmpty(resolveResult.ResolvedType.FullName))) { resolveResult = resolver.Resolve(expressionResult, new DomLocation(loc.Line, int.MaxValue)); } // Search for possible generic parameters. // if (this.resolveResult == null || this.resolveResult.ResolvedType == null || String.IsNullOrEmpty (this.resolveResult.ResolvedType.Name)) { if (!expressionResult.Region.IsEmpty) { int j = data.Document.LocationToOffset(expressionResult.Region.End.Line, expressionResult.Region.End.Column); int bracket = 0; for (int i = j; i >= 0 && i < data.Document.Length; i++) { char ch = data.Document.GetCharAt(i); if (Char.IsWhiteSpace(ch)) { continue; } if (ch == '<') { bracket++; } else if (ch == '>') { bracket--; if (bracket == 0) { expressionResult.Expression += data.Document.GetTextBetween(j, i + 1); expressionResult.ExpressionContext = ExpressionContext.ObjectCreation; resolveResult = resolver.Resolve(expressionResult, new DomLocation(loc.Line, loc.Column)); break; } } else { if (bracket == 0) { break; } } } } // To resolve method overloads the full expression must be parsed. // ex.: Overload (1)/ Overload("one") - parsing "Overload" gives just a MethodResolveResult // and for constructor initializers it's tried too to to resolve constructor overloads. if (resolveResult is ThisResolveResult || resolveResult is BaseResolveResult || resolveResult is MethodResolveResult && ((MethodResolveResult)resolveResult).Methods.Count > 1) { // put the search offset at the end of the invocation to be able to find the full expression // the resolver finds it itself if spaces are between the method name and the argument opening parentheses. while (wordEnd < data.Length - 1 && Char.IsWhiteSpace(data.GetCharAt(wordEnd))) { wordEnd++; } if (data.GetCharAt(wordEnd) == '(') { int matchingBracket = data.Document.GetMatchingBracketOffset(wordEnd); if (matchingBracket > 0) { wordEnd = matchingBracket; } } //Console.WriteLine (expressionFinder.FindFullExpression (txt, wordEnd)); ResolveResult possibleResult = resolver.Resolve(expressionFinder.FindFullExpression(data, wordEnd), new DomLocation(loc.Line, loc.Column)) ?? resolveResult; //Console.WriteLine ("possi:" + resolver.Resolve (expressionFinder.FindFullExpression (txt, wordEnd), new DomLocation (loc.Line, loc.Column))); if (possibleResult is MethodResolveResult) { resolveResult = possibleResult; } } return(resolveResult); }