static Document Setup (string input) { TestWorkbenchWindow tww = new TestWorkbenchWindow (); var content = new TestViewContent (); tww.ViewContent = content; content.ContentName = "a.cs"; content.GetTextEditorData ().Document.MimeType = "text/x-csharp"; Document doc = new Document (tww); var text = input; int endPos = text.IndexOf ('$'); if (endPos >= 0) text = text.Substring (0, endPos) + text.Substring (endPos + 1); content.Text = text; content.CursorPosition = System.Math.Max (0, endPos); var compExt = new CSharpCompletionTextEditorExtension (); compExt.Initialize (doc); content.Contents.Add (compExt); doc.UpdateParseDocument (); return doc; }
public void Initialize (Document document) { if (this.document != null) throw new InvalidOperationException ("Extension is already initialized."); this.document = document; Initialize (); }
CSharpCompletionTextEditorExtension CreateCompletionAndUpdate (Document realDocument, UnderlyingDocumentInfo docInfo, out CodeCompletionContext codeCompletionContext) { var completion = CreateCompletion (realDocument, docInfo, out codeCompletionContext); completion.UpdateParsedDocument (); return completion; }
public void AddToLine(Mono.TextEditor.Document doc) { if (Line != null) { doc.AddMarker(Line, marker); } }
public ICompletionDataList HandleCompletion (Document realDocument, CodeCompletionContext completionContext, UnderlyingDocumentInfo docInfo, char currentChar, ref int triggerWordLength) { CodeCompletionContext ccc; var completion = CreateCompletionAndUpdate (realDocument, docInfo, out ccc); return completion.HandleCodeCompletion (completionContext, currentChar, ref triggerWordLength); }
void SetLocationTextData(Gtk.TreeViewColumn tree_column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter) { CellRendererText cellRendererText = (CellRendererText)cell; Change change = store.GetValue(iter, objColumn) as Change; cellRendererText.Visible = (bool)store.GetValue(iter, statusVisibleColumn); TextReplaceChange replaceChange = change as TextReplaceChange; if (replaceChange == null) { cellRendererText.Text = ""; return; } Mono.TextEditor.Document doc = new Mono.TextEditor.Document(); doc.Text = System.IO.File.ReadAllText(replaceChange.FileName); DocumentLocation loc = doc.OffsetToLocation(replaceChange.Offset); string text = string.Format(GettextCatalog.GetString("(Line:{0}, Column:{1})"), loc.Line, loc.Column); if (treeviewPreview.Selection.IterIsSelected(iter)) { cellRendererText.Text = text; } else { cellRendererText.Markup = "<span foreground=\"" + MonoDevelop.Components.PangoCairoHelper.GetColorString(Style.Text(StateType.Insensitive)) + "\">" + text + "</span>"; } }
void SetDiffCellData(Gtk.TreeViewColumn tree_column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter) { try { CellRendererDiff cellRendererDiff = (CellRendererDiff)cell; Change change = store.GetValue(iter, objColumn) as Change; cellRendererDiff.Visible = !(bool)store.GetValue(iter, statusVisibleColumn); if (change == null || !cellRendererDiff.Visible) { cellRendererDiff.InitCell(treeviewPreview, false, "", ""); return; } TextReplaceChange replaceChange = change as TextReplaceChange; if (replaceChange == null) { return; } Mono.TextEditor.Document originalDocument = new Mono.TextEditor.Document(); originalDocument.FileName = replaceChange.FileName; originalDocument.Text = System.IO.File.ReadAllText(replaceChange.FileName); Mono.TextEditor.Document changedDocument = new Mono.TextEditor.Document(); changedDocument.FileName = replaceChange.FileName; changedDocument.Text = originalDocument.Text; ((Mono.TextEditor.IBuffer)changedDocument).Replace(replaceChange.Offset, replaceChange.RemovedChars, replaceChange.InsertedText); string diffString = Mono.TextEditor.Utils.Diff.GetDiffString(originalDocument, changedDocument); cellRendererDiff.InitCell(treeviewPreview, true, diffString, replaceChange.FileName); } catch (Exception e) { Console.WriteLine(e); } }
void TestCreateMethod (string input, string outputString, bool returnWholeFile) { var generator = new CSharpCodeGeneratorNode (); MonoDevelop.Projects.CodeGeneration.CodeGenerator.AddGenerator (generator); var refactoring = new CreateMethodCodeGenerator (); RefactoringOptions options = ExtractMethodTests.CreateRefactoringOptions (input); Assert.IsTrue (refactoring.IsValid (options)); if (returnWholeFile) { refactoring.SetInsertionPoint (CodeGenerationService.GetInsertionPoints (options.Document, refactoring.DeclaringType).First ()); } else { DocumentLocation loc = new DocumentLocation (1, 1); refactoring.SetInsertionPoint (new InsertionPoint (loc, NewLineInsertion.Eol, NewLineInsertion.Eol)); } List<Change> changes = refactoring.PerformChanges (options, null); // changes.ForEach (c => Console.WriteLine (c)); // get just the generated method. string output = ExtractMethodTests.GetOutput (options, changes); if (returnWholeFile) { Assert.IsTrue (ExtractMethodTests.CompareSource (output, outputString), "Expected:" + Environment.NewLine + outputString + Environment.NewLine + "was:" + Environment.NewLine + output); return; } output = output.Substring (0, output.IndexOf ('}') + 1).Trim (); // crop 1 level of indent Document doc = new Document (output); foreach (LineSegment line in doc.Lines) { if (doc.GetCharAt (line.Offset) == '\t') ((IBuffer)doc).Remove (line.Offset, 1); } output = doc.Text; Assert.IsTrue (ExtractMethodTests.CompareSource (output, outputString), "Expected:" + Environment.NewLine + outputString + Environment.NewLine + "was:" + Environment.NewLine + output); MonoDevelop.Projects.CodeGeneration.CodeGenerator.RemoveGenerator (generator); }
static CSharpTextEditorIndentation Setup (string input, out TestViewContent content) { TestWorkbenchWindow tww = new TestWorkbenchWindow (); content = new TestViewContent (); content.Data.Options.IndentStyle = IndentStyle.Auto; tww.ViewContent = content; content.ContentName = "a.cs"; content.GetTextEditorData ().Document.MimeType = "text/x-csharp"; Document doc = new Document (tww); var text = input; int endPos = text.IndexOf ('$'); if (endPos >= 0) text = text.Substring (0, endPos) + text.Substring (endPos + 1); content.Text = text; content.CursorPosition = System.Math.Max (0, endPos); var compExt = new CSharpCompletionTextEditorExtension (); compExt.Initialize (doc); content.Contents.Add (compExt); var ext = new CSharpTextEditorIndentation (); CSharpTextEditorIndentation.OnTheFlyFormatting = true; ext.Initialize (doc); content.Contents.Add (ext); doc.UpdateParseDocument (); return ext; }
public CSharpChunkParser(SpanParser spanParser, Mono.TextEditor.Document doc, Style style, SyntaxMode mode, LineSegment line) : base(spanParser, doc, style, mode, line) { foreach (var tag in ProjectDomService.SpecialCommentTags) { tags.Add(tag.Tag); } }
public FoldSegment (Document doc, string description, int offset, int length, FoldingType foldingType) : base (offset, length) { this.doc = doc; this.IsFolded = false; this.Description = description; this.FoldingType = foldingType; }
MonoDevelop.Projects.Project GetProject(Mono.TextEditor.Document doc) { // There is no reference between document & higher level infrastructure, // therefore it's a bit tricky to find the right project. MonoDevelop.Projects.Project project = null; var view = doc.Annotation <MonoDevelop.SourceEditor.SourceEditorView> (); if (view != null) { project = view.Project; } if (project == null) { var ideDocument = IdeApp.Workbench.GetDocument(doc.FileName); if (ideDocument != null) { project = ideDocument.Project; } } if (project == null) { project = IdeApp.Workspace.GetProjectContainingFile(doc.FileName); } return(project); }
public CSharpChunkParser(SpanParser spanParser, Mono.TextEditor.Document doc, ColorSheme style, SyntaxMode mode, LineSegment line) : base(spanParser, doc, style, mode, line) { document = IdeApp.Workbench.GetDocument(doc.FileName); foreach (var tag in ProjectDomService.SpecialCommentTags) { tags.Add(tag.Tag); } // ICSharpCode.OldNRefactory.Ast.CompilationUnit unit = null; // if (document != null && document.ParsedDocument != null && MonoDevelop.Core.PropertyService.Get ("EnableSemanticHighlighting", false)) { // resolver = document.GetResolver (); // if (!document.ParsedDocument.TryGetTag (out unit)) { // try { // using (ICSharpCode.OldNRefactory.IParser parser = ICSharpCode.OldNRefactory.ParserFactory.CreateParser (ICSharpCode.OldNRefactory.SupportedLanguage.CSharp, document.Editor.Document.OpenTextReader ())) { // parser.Parse (); // unit = parser.CompilationUnit; // document.ParsedDocument.SetTag (unit); // } // } catch (Exception) { // resolver = null; // return; // } // } // resolver.SetupParsedCompilationUnit (unit); // } }
static string GetIndent(string text) { Mono.TextEditor.Document doc = new Mono.TextEditor.Document(); doc.Text = text; StringBuilder result = null; for (int i = 1; i < doc.LineCount; i++) { LineSegment line = doc.GetLine(i); StringBuilder lineIndent = new StringBuilder(); foreach (char ch in doc.GetTextAt(line)) { if (!char.IsWhiteSpace(ch)) { break; } lineIndent.Append(ch); } if (line.EditableLength == lineIndent.Length) { continue; } if (result == null || lineIndent.Length < result.Length) { result = lineIndent; } } if (result == null) { return(""); } return(result.ToString()); }
CSharpTextEditorCompletion CreateCompletion(MonoDevelop.Ide.Gui.Document realDocument, DocumentInfo info, LocalDocumentInfo localInfo, out CodeCompletionContext codeCompletionContext) { var doc = new Mono.TextEditor.Document() { Text = localInfo.LocalDocument, }; var documentLocation = doc.OffsetToLocation(localInfo.CaretPosition); codeCompletionContext = new CodeCompletionContext() { TriggerOffset = localInfo.CaretPosition, TriggerLine = documentLocation.Line, TriggerLineOffset = documentLocation.Column - 1 }; var r = new System.IO.StringReader(localInfo.LocalDocument); using (var parser = ICSharpCode.NRefactory.ParserFactory.CreateParser(SupportedLanguage.CSharp, r)) { parser.Parse(); return(new CSharpTextEditorCompletion(localInfo.HiddenDocument) { ParsedUnit = parser.CompilationUnit, CompletionWidget = CreateCompletionWidget(realDocument, localInfo), Dom = localInfo.HiddenDocument.Dom }); } }
static Document Setup (string input) { var tww = new TestWorkbenchWindow (); var content = new TestViewContent (); var project = new DotNetAssemblyProject ("C#"); project.Name = "test"; project.References.Add (new ProjectReference (ReferenceType.Package, "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")); project.References.Add (new ProjectReference (ReferenceType.Package, "System.Core")); project.FileName = "test.csproj"; TypeSystemService.LoadProject (project); TypeSystemService.GetProjectContentWrapper (project).ReconnectAssemblyReferences (); content.Project = project; tww.ViewContent = content; content.ContentName = "a.cs"; content.GetTextEditorData ().Document.MimeType = "text/x-csharp"; var doc = new Document (tww); var text = input; int endPos = text.IndexOf ('$'); if (endPos >= 0) text = text.Substring (0, endPos) + text.Substring (endPos + 1); content.Text = text; content.CursorPosition = Math.Max (0, endPos); var compExt = new CSharpCompletionTextEditorExtension (); compExt.Initialize (doc); content.Contents.Add (compExt); doc.UpdateParseDocument (); return doc; }
public void CopySelection() { TreeModel model; StringBuilder sb = new StringBuilder(); foreach (Gtk.TreePath p in treeviewSearchResults.Selection.GetSelectedRows(out model)) { TreeIter iter; if (!model.GetIter(out iter, p)) { continue; } SearchResult result = store.GetValue(iter, SearchResultColumn) as SearchResult; if (result == null) { continue; } DocumentLocation loc = GetLocation(result); Mono.TextEditor.Document doc = GetDocument(result); LineSegment line = doc.GetLine(loc.Line - 1); sb.AppendFormat("{0} ({1}, {2}):{3}", result.FileName, loc.Line, loc.Column, doc.GetTextAt(line.Offset, line.EditableLength)); sb.AppendLine(); } Gtk.Clipboard clipboard = Clipboard.Get(Gdk.Atom.Intern("CLIPBOARD", false)); clipboard.Text = sb.ToString(); clipboard = Clipboard.Get(Gdk.Atom.Intern("PRIMARY", false)); clipboard.Text = sb.ToString(); }
static int GetNextOffset (Document document, int lineNumber) { int startLineNumber = lineNumber + 1; if (startLineNumber > document.Length) startLineNumber = 0; var line = document.GetLinesStartingAt (startLineNumber).FirstOrDefault (l => l.IsBookmarked); return line != null ? line.Offset : -1; }
static int GetPrevOffset (Document document, int lineNumber) { int startLineNumber = lineNumber - 1; if (startLineNumber < 0) startLineNumber = document.Length - 1; var line = document.GetLinesReverseStartingAt (startLineNumber - 1).FirstOrDefault (l => l.IsBookmarked); return line != null ? line.Offset : -1; }
DocumentLocation GetLocation(SearchResult searchResult) { Mono.TextEditor.Document doc = GetDocument(searchResult); int lineNr = doc.OffsetToLineNumber(searchResult.Offset); LineSegment line = doc.GetLine(lineNr); return(new DocumentLocation(lineNr + 1, searchResult.Offset - line.Offset + 1)); }
public SourceEditorPrintOperation (Document doc, FilePath filename) { this.doc = doc; this.filename = filename; this.settings = SourceEditorPrintSettings.Load (); this.Unit = Unit.Mm; }
public MDRefactoringScript (MDRefactoringContext context, Document document, CSharpFormattingOptions formattingOptions) : base(document.Editor.Document, formattingOptions, document.Editor.CreateNRefactoryTextEditorOptions ()) { this.context = context; this.document = document; undoGroup = this.document.Editor.OpenUndoGroup (); this.startVersion = this.document.Editor.Version; }
// Span preprocessorSpan; // Rule preprocessorRule; public CSharpSpanParser(Mono.TextEditor.Document doc, SyntaxMode mode, CloneableStack <Span> spanStack) : base(doc, mode, spanStack) { // foreach (Span span in mode.Spans) { // if (span.Rule == "text.preprocessor") { // preprocessorSpan = span; // preprocessorRule = GetRule (span); // } // } }
// Span preprocessorSpan; // Rule preprocessorRule; public CSharpSpanParser(Mono.TextEditor.Document doc, SyntaxMode mode, LineSegment line, Stack <Span> spanStack) : base(doc, mode, line, spanStack) { /* foreach (Span span in mode.Spans) { * if (span.Rule == "text.preprocessor") { * preprocessorSpan = span; * preprocessorRule = GetRule (span); * } * }*/ }
public ConditinalExpressionEvaluator(Mono.TextEditor.Document doc) { var project = GetProject(doc); if (project == null) { var ideDocument = IdeApp.Workbench.GetDocument(doc.FileName); if (ideDocument != null) { project = ideDocument.Project; } } if (project == null) { project = IdeApp.Workspace.GetProjectContainingFile(doc.FileName); } if (project != null) { var configuration = project.GetConfiguration(IdeApp.Workspace.ActiveConfiguration) as DotNetProjectConfiguration; if (configuration != null) { var cparams = configuration.CompilationParameters as CSharpCompilerParameters; if (cparams != null) { string[] syms = cparams.DefineSymbols.Split(';', ',', ' ', '\t'); foreach (string s in syms) { string ss = s.Trim(); if (ss.Length > 0 && !symbols.Contains(ss)) { symbols.Add(ss); } } } } else { Console.WriteLine("NO CONFIGURATION"); } } var dom = ProjectDomService.GetProjectDom(project); var parsedDocument = ProjectDomService.GetParsedDocument(dom, doc.FileName); /* if (parsedDocument == null) * parsedDocument = ProjectDomService.ParseFile (dom, doc.FileName ?? "a.cs", delegate { return doc.Text; });*/ if (parsedDocument != null) { foreach (PreProcessorDefine define in parsedDocument.Defines) { symbols.Add(define.Define); } } }
// Mono.TextEditor.Document document; // MonoDevelop.Ide.Gui.Document doc; // IParser parser; // IResolver resolver; // IExpressionFinder expressionFinder; /* void Init (Mono.TextEditor.Document document) * { * * // parser = ProjectDomService.GetParser (document.FileName, document.MimeType); * // expressionFinder = ProjectDomService.GetExpressionFinder (document.FileName); * }*/ ProjectDom GetParserContext(Mono.TextEditor.Document document) { var project = IdeApp.ProjectOperations.CurrentSelectedProject; if (project != null) { return(ProjectDomService.GetProjectDom(project)); } return(ProjectDom.Empty); }
internal static CodeFormatter GetFormatter (out Document doc) { doc = IdeApp.Workbench.ActiveDocument; if (doc == null) return null; var editor = doc.Editor; if (editor == null) return null; return editor == null ? null : CodeFormatterService.GetFormatter (editor.MimeType); }
static int StartsWithListMember (Document document, List<string> list, int offset) { for (int i = 0; i < list.Count; i++) { string item = list[i]; if (offset + item.Length < document.Length) { if (document.GetTextAt (offset, item.Length) == item) return i; } } return -1; }
static int GetPrevOffset (Document document, int lineNumber) { LineSegment startLine = document.GetLine (lineNumber); RedBlackTree<LineSegmentTree.TreeNode>.RedBlackTreeIterator iter = startLine.Iter; while (iter.MoveBack ()) { LineSegment line = iter.Current; if (line.IsBookmarked) { return line.Offset; } } return -1; }
public static IEnumerable<Result> Check (Document input, CancellationToken cancellationToken) { if (!QuickTaskStrip.EnableFancyFeatures) return Enumerable.Empty<Result> (); // var now = DateTime.Now; var editor = input.Editor; if (editor == null) return Enumerable.Empty<Result> (); var loc = editor.Caret.Location; var result = new BlockingCollection<Result> (); var codeIssueProvider = RefactoringService.GetInspectors (editor.Document.MimeType).ToArray (); var context = input.ParsedDocument.CreateRefactoringContext != null ? input.ParsedDocument.CreateRefactoringContext (input, cancellationToken) : null; // Console.WriteLine ("start check:"+ (DateTime.Now - now).TotalMilliseconds); Parallel.ForEach (codeIssueProvider, (parentProvider) => { try { foreach (var provider in EnumerateProvider (parentProvider)){ var severity = provider.GetSeverity (); if (severity == Severity.None) return; // var now2 = DateTime.Now; foreach (var r in provider.GetIssues (context, cancellationToken)) { var fixes = new List<GenericFix> (r.Actions.Where (a => a != null).Select (a => new GenericFix ( a.Title, new System.Action (() => a.Run (input, loc))) { DocumentRegion = new DocumentRegion (r.Region.Begin, r.Region.End) })); result.Add (new InspectorResults ( provider, r.Region, r.Description, severity, provider.IssueMarker, fixes.ToArray () )); } } /* var ms = (DateTime.Now - now2).TotalMilliseconds; if (ms > 1000) Console.WriteLine (ms +"\t\t"+ provider.Title);*/ } catch (OperationCanceledException) { //ignore } catch (Exception e) { LoggingService.LogError ("CodeAnalysis: Got exception in inspector '" + parentProvider + "'", e); } }); // Console.WriteLine ("END check:"+ (DateTime.Now - now).TotalMilliseconds); return result; }
public static void EvaluateComplexityMetrics(MetricsContext ctx, ProjectProperties project) { mctx = ctx; PrefixName = new Stack <string>(0); lock (mctx) { foreach (var file in project.Project.Files) { /*if(file.BuildAction != BuildAction.Compile) * continue;*/ // Files not set to compile are sometimes not accessible if (file.Name.Contains("svn-base")) { continue; } string text = ""; try { text = System.IO.File.ReadAllText(file.FilePath); } catch (System.UnauthorizedAccessException uae) { continue; } catch (System.IO.FileNotFoundException fnf) { // This exception arises in Nrefactory...WTF? 0_0 continue; } ProjProp = project; File = file; Mono.TextEditor.Document doc = new Mono.TextEditor.Document(); doc.Text = text; FileDoc = doc; FileText = new List <LineSegment>(); foreach (LineSegment segment in doc.Lines) { FileText.Add(segment); } using (ICSharpCode.OldNRefactory.IParser parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader(text))) { parser.Parse(); if (parser.Errors.Count > 0) { //Error handling TODO } else { foreach (var it in parser.CompilationUnit.Children) { ProcessNode(ctx, it); } } } } } }
public void AddToLine(Mono.TextEditor.Document doc) { if (Line != null) { DocumentLocation dl = doc.OffsetToLocation(marker.StartCol); marker.StartCol = dl.Column; dl = doc.OffsetToLocation(marker.EndCol); marker.EndCol = dl.Column; doc.AddMarker(Line, marker); } }
public void AttachToDocument(Document document) { if (document == null) { throw new ArgumentNullException("document"); } document.Editor.Parent.ButtonReleaseEvent -= this.HandleButtonReleaseEvent; document.Editor.Parent.MotionNotifyEvent -= this.HandleMotionNotifyEvent; document.Editor.Parent.ButtonReleaseEvent += this.HandleButtonReleaseEvent; document.Editor.Parent.MotionNotifyEvent += this.HandleMotionNotifyEvent; }
static string RemoveIndent(string text, string indent) { Mono.TextEditor.Document doc = new Mono.TextEditor.Document(); doc.Text = text; StringBuilder result = new StringBuilder(); foreach (LineSegment line in doc.Lines) { string curLineIndent = line.GetIndentation(doc); int offset = Math.Min(curLineIndent.Length, indent.Length); result.Append(doc.GetTextBetween(line.Offset + offset, line.EndOffset)); } return(result.ToString()); }
public override void Initialize () { base.Initialize (); defaultCompletionWidget = CompletionWidget; defaultDocument = Document; completionBuilder = RazorCompletionBuilderService.GetBuilder ("C#"); defaultDocument.Editor.Document.TextReplacing += UnderlyingDocument_TextReplacing; defaultDocument.Editor.Caret.PositionChanged += delegate { OnCompletionContextChanged (CompletionWidget, EventArgs.Empty); }; }
Mono.TextEditor.Document GetDocument(SearchResult result) { Mono.TextEditor.Document doc; if (!documents.TryGetValue(result.FileName, out doc)) { doc = new Mono.TextEditor.Document(); doc.MimeType = DesktopService.GetMimeTypeForUri(result.FileName); TextReader reader = result.FileProvider.Open(); doc.Text = reader.ReadToEnd(); reader.Close(); documents[result.FileName] = doc; } return(doc); }
static string StripDoubleBlankLines(string content) { var doc = new Mono.TextEditor.Document(content); for (int i = 1; i + 1 <= doc.LineCount; i++) { if (IsBlankLine(doc, i) && IsBlankLine(doc, i + 1)) { ((IBuffer)doc).Remove(doc.GetLine(i)); i--; continue; } } return(doc.Text); }
CSharpCompletionTextEditorExtension CreateCompletion (Document realDocument, UnderlyingDocumentInfo docInfo, out CodeCompletionContext codeCompletionContext) { var documentLocation = docInfo.UnderlyingDocument.Editor.OffsetToLocation (docInfo.CaretPosition); codeCompletionContext = new CodeCompletionContext () { TriggerOffset = docInfo.CaretPosition, TriggerLine = documentLocation.Line, TriggerLineOffset = documentLocation.Column - 1 }; return new CSharpCompletionTextEditorExtension (docInfo.UnderlyingDocument) { CompletionWidget = CreateCompletionWidget (realDocument, docInfo) }; }
public override void Analyze (Document doc, LineSegment line, Chunk startChunk, int startOffset, int endOffset) { if (endOffset <= startOffset || startOffset >= doc.Length) return; string text = doc.GetTextAt (startOffset, endOffset - startOffset); int startColumn = startOffset - line.Offset; line.RemoveMarker (typeof(UrlMarker)); foreach (System.Text.RegularExpressions.Match m in urlRegex.Matches (text)) { line.AddMarker (new UrlMarker (line, m.Value, UrlType.Url, syntax, startColumn + m.Index, startColumn + m.Index + m.Length)); } foreach (System.Text.RegularExpressions.Match m in mailRegex.Matches (text)) { line.AddMarker (new UrlMarker (line, m.Value, UrlType.Email, syntax, startColumn + m.Index, startColumn + m.Index + m.Length)); } }
static int GetNextOffset (Document document, int lineNumber) { int startLineNumber = lineNumber + 1; if (startLineNumber > document.Length) startLineNumber = 0; LineSegment startLine = document.GetLine (startLineNumber); RedBlackTree<LineSegmentTree.TreeNode>.RedBlackTreeIterator iter = startLine.Iter; do { LineSegment line = iter.Current; if (line.IsBookmarked) return line.Offset; } while (iter.MoveNext ()); return -1; }
int FindPrevWordOffset (Document doc, int offset, bool subword) { int lineNumber = doc.OffsetToLineNumber (offset); LineSegment line = doc.GetLine (lineNumber); if (line == null) return offset; int result = offset; if (result == line.Offset) { line = doc.GetLine (lineNumber - 1); if (line != null) result = line.Offset + line.EditableLength; return result; } CharacterClass current = GetCharacterClass (doc.GetCharAt (result - 1), subword, false); if (current == CharacterClass.Whitespace && result - 1 > line.Offset) { result--; current = GetCharacterClass (doc.GetCharAt (result - 2), subword, false); } while (result > line.Offset) { CharacterClass prev = GetCharacterClass (doc.GetCharAt (result - 1), subword, false); if (prev != current) { // camelCase and PascalCase handling bool camelSkip = false; if (prev == CharacterClass.UppercaseLetter && current == CharacterClass.LowercaseLetter) { if (result-2 > line.Offset) { CharacterClass back2 = GetCharacterClass (doc.GetCharAt (result-2), subword, false); if (back2 == CharacterClass.UppercaseLetter) result--; else camelSkip = true; } } if (!camelSkip) break; } current = prev; result--; } return result; }
static string AddIndent(string text, string indent) { Mono.TextEditor.Document doc = new Mono.TextEditor.Document(); doc.Text = text; StringBuilder result = new StringBuilder(); foreach (LineSegment line in doc.Lines) { if (result.Length > 0) { result.Append(indent); } result.Append(doc.GetTextAt(line)); } return(result.ToString()); }
static CSharpSyntaxMode() { MonoDevelop.Debugger.DebuggingService.DisableConditionalCompilation += (EventHandler <DocumentEventArgs>)DispatchService.GuiDispatch(new EventHandler <DocumentEventArgs> (OnDisableConditionalCompilation)); IdeApp.Workspace.ActiveConfigurationChanged += delegate { foreach (var doc in IdeApp.Workbench.Documents) { TextEditorData data = doc.Editor; if (data == null) { continue; } Mono.TextEditor.Document document = data.Document; doc.UpdateParseDocument(); } }; }
public static void GotoToPreviousReferenceAtCaret(Document document) { var searchTarget = CodeDomHelpers.GetEntityAtCaret(document, true); if (searchTarget != null) { var nextItem = ReferenceNavigationLoop.GetPreviousSearchTarget(searchTarget); if (!nextItem.Equals(NavigationItem.Empty)) { IdeApp.Workbench.OpenDocument(nextItem.FileName, nextItem.Line, nextItem.Col); } else if (searchTarget is IVariable || searchTarget is IEntity) { FindReferencesForNavigation(searchTarget, false); } } }
public RazorSyntaxMode (Document doc) { this.guiDocument = doc; guiDocument.DocumentParsed += HandleDocumentParsed; ResourceStreamProvider provider = new ResourceStreamProvider (typeof (ResourceStreamProvider).Assembly, "RazorSyntaxMode.xml"); using (var reader = provider.Open ()) { SyntaxMode baseMode = SyntaxMode.Read (reader); this.rules = new List<Rule> (baseMode.Rules); this.keywords = new List<Keywords> (baseMode.Keywords); this.spans = baseMode.Spans; this.matches = baseMode.Matches; this.prevMarker = baseMode.PrevMarker; this.SemanticRules = new List<SemanticRule> (baseMode.SemanticRules); this.keywordTable = baseMode.keywordTable; this.keywordTableIgnoreCase = baseMode.keywordTableIgnoreCase; } }
NavigationPoint GetLocation(TreeIter iter) { this.treeviewSearchResults.Selection.UnselectAll(); if (!store.IterIsValid(iter)) { return(null); } this.treeviewSearchResults.Selection.SelectIter(iter); this.treeviewSearchResults.ScrollToCell(store.GetPath(iter), this.treeviewSearchResults.Columns[0], false, 0, 0); SearchResult searchResult = (SearchResult)store.GetValue(iter, SearchResultColumn); Mono.TextEditor.Document doc = GetDocument(searchResult); DocumentLocation location = doc.OffsetToLocation(searchResult.Offset); return(new SearchTextFileNavigationPoint(searchResult.FileName, location.Line + 1, location.Column + 1)); }
public void Draw(Document document, double mouseX, double mouseY) { if (document == null) throw new ArgumentNullException("document"); var segment = FindSegment(mouseX, mouseY, document.Editor); var selectedWord = document.Editor.Parent.GetTextAt(segment); if (!IsNeedDrawForWord(selectedWord)) return; var newMarker = CreateMarker(segment, document.Editor.ColorStyle.KeywordNamespace.Foreground); SetTextDocument(document); SetMarker(newMarker); }
int FindNextWordOffset (Document doc, int offset, bool subword) { int lineNumber = doc.OffsetToLineNumber (offset); LineSegment line = doc.GetLine (lineNumber); if (line == null) return offset; int result = offset; int endOffset = line.Offset + line.EditableLength; if (result == endOffset) { line = doc.GetLine (lineNumber + 1); if (line != null) result = line.Offset; return result; } CharacterClass current = GetCharacterClass (doc.GetCharAt (result), subword, false); while (result < endOffset) { CharacterClass next = GetCharacterClass (doc.GetCharAt (result), subword, false); if (next != current) { // camelCase and PascalCase handling bool camelSkip = false; if (next == CharacterClass.LowercaseLetter && current == CharacterClass.UppercaseLetter) { if (result-2 > line.Offset) { CharacterClass previous = GetCharacterClass (doc.GetCharAt (result-2), subword, false); if (previous == CharacterClass.UppercaseLetter && result-2 > offset) result--; else camelSkip = true; } } if (!camelSkip) break; } current = next; result++; } while (result < endOffset && GetCharacterClass (doc.GetCharAt (result), subword, false) == CharacterClass.Whitespace) { result++; } return result; }
public static bool ResolveAt (Document doc, out ResolveResult resolveResult, out AstNode node, CancellationToken token = default (CancellationToken)) { if (doc == null) throw new ArgumentNullException ("doc"); if (!InternalResolveAt (doc, out resolveResult, out node)) { var editor = doc.Editor; if (editor == null) return false; var location = RefactoringService.GetCorrectResolveLocation (doc, editor.Caret.Location); resolveResult = GetHeuristicResult (doc, location, ref node); if (resolveResult == null) return false; } var oce = node as ObjectCreateExpression; if (oce != null) node = oce.Type; return true; }
int FindNextWordOffset (Document doc, int offset, bool subword) { if (offset + 1 >= doc.Length) return doc.Length; int result = offset + 1; CC previous = SW.GetCharacterClass (doc.GetCharAt (result), subword, treat_); bool inIndentifier = previous != CC.Unknown && previous != CC.Whitespace; while (result < doc.Length) { char ch = doc.GetCharAt (result); CC current = SW.GetCharacterClass (ch, subword, treat_); //camelCase / PascalCase splitting if (subword) { if (current == CC.Digit && (previous != CC.Digit || (result-1 == offset && !Char.IsDigit (doc.GetCharAt (result-1))))) { break; } else if (previous == CC.Digit && current != CC.Digit) { break; } else if (current == CC.UppercaseLetter && previous != CC.UppercaseLetter) { break; } else if (current == CC.LowercaseLetter && previous == CC.UppercaseLetter && result - 2 > 0 && SW.GetCharacterClass (doc.GetCharAt (result - 2), subword, treat_) != CC.LowercaseLetter) { result--; break; } } //else break at end of identifiers if (previous != CC.Unknown && previous != CC.Whitespace) { inIndentifier = true; } else if (inIndentifier) { result--; break; } previous = current; result++; } foreach (FoldSegment segment in doc.GetFoldingsFromOffset (result)) { if (segment.IsFolded) result = System.Math.Max (result, segment.EndLine.Offset + segment.EndColumn); } return result; }
void SetDiffCellData(Gtk.TreeViewColumn tree_column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter) { try { CellRendererDiff cellRendererDiff = (CellRendererDiff)cell; Change change = store.GetValue(iter, objColumn) as Change; cellRendererDiff.Visible = !(bool)store.GetValue(iter, statusVisibleColumn); if (change == null || !cellRendererDiff.Visible) { cellRendererDiff.InitCell(treeviewPreview, false, "", ""); return; } TextReplaceChange replaceChange = change as TextReplaceChange; if (replaceChange == null) { return; } Mono.TextEditor.Document doc = new Mono.TextEditor.Document(); doc.Text = System.IO.File.ReadAllText(replaceChange.FileName); List <string> before = new List <string> (); foreach (var line in doc.Lines) { before.Add(doc.GetTextAt(line.Offset, line.EditableLength)); } ((Mono.TextEditor.IBuffer)doc).Replace(replaceChange.Offset, replaceChange.RemovedChars, replaceChange.InsertedText); List <string> after = new List <string> (); foreach (var line in doc.Lines) { after.Add(doc.GetTextAt(line.Offset, line.EditableLength)); } Diff diff = new Diff(before.ToArray(), after.ToArray(), true, true); System.IO.StringWriter w = new System.IO.StringWriter(); UnifiedDiff.WriteUnifiedDiff(diff, w, replaceChange.FileName, replaceChange.FileName, 2); cellRendererDiff.InitCell(treeviewPreview, true, w.ToString().Trim(), replaceChange.FileName); } catch (Exception e) { Console.WriteLine(e); } }
public override void Analyze (Document doc, LineSegment line, Chunk startChunk, int startOffset, int endOffset) { if (endOffset <= startOffset || startOffset >= doc.Length || inUpdate) return; inUpdate = true; try { string text = doc.GetTextAt (startOffset, endOffset - startOffset); int startColumn = startOffset - line.Offset; var markers = new List <UrlMarker> (line.Markers.Where (m => m is UrlMarker).Cast<UrlMarker> ()); markers.ForEach (m => doc.RemoveMarker (m, false)); foreach (System.Text.RegularExpressions.Match m in urlRegex.Matches (text)) { doc.AddMarker (line, new UrlMarker (doc, line, m.Value, UrlType.Url, syntax, startColumn + m.Index, startColumn + m.Index + m.Length), false); } foreach (System.Text.RegularExpressions.Match m in mailRegex.Matches (text)) { doc.AddMarker (line, new UrlMarker (doc, line, m.Value, UrlType.Email, syntax, startColumn + m.Index, startColumn + m.Index + m.Length), false); } } finally { inUpdate = false; } }
static string StripHeader(string content) { var doc = new Mono.TextEditor.Document(content); while (true) { string lineText = doc.GetLineText(1); if (lineText == null) { break; } if (lineText.StartsWith("//")) { ((IBuffer)doc).Remove(doc.GetLine(1)); continue; } break; } return(doc.Text); }
static string ResolveExpression (Document doc, int offset) { var editor = doc.Editor; var unit = doc.ParsedDocument.GetAst<SyntaxTree> (); if (unit == null) return null; var file = doc.ParsedDocument.ParsedFile as CSharpUnresolvedFile; if (file == null) return null; ResolveResult result; AstNode node; var loc = editor.OffsetToLocation (offset); if (!doc.TryResolveAt (loc, out result, out node)) return null; if (result is LocalResolveResult) return ((LocalResolveResult)result).Variable.Name; return editor.GetTextBetween (node.StartLocation, node.EndLocation); }
static string GetIndent(string text) { Mono.TextEditor.Document doc = new Mono.TextEditor.Document(); doc.Text = text; string result = null; for (int i = 1; i < doc.LineCount; i++) { string lineIndent = doc.GetLineIndent(i); if (doc.GetLine(i).EditableLength == lineIndent.Length) { continue; } if (result == null || lineIndent.Length < result.Length) { result = lineIndent; } } return(result ?? ""); }
void ResultLineDataFunc(Gtk.TreeViewColumn column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter) { if (TreeIter.Zero.Equals(iter)) { return; } CellRendererText lineRenderer = (CellRendererText)cell; SearchResult searchResult = (SearchResult)store.GetValue(iter, SearchResultColumn); if (searchResult == null) { return; } Mono.TextEditor.Document doc = GetDocument(searchResult); int lineNr = doc.OffsetToLineNumber(searchResult.Offset) + 1; bool didRead = (bool)store.GetValue(iter, DidReadColumn); bool isSelected = treeviewSearchResults.Selection.IterIsSelected(iter); lineRenderer.Markup = MarkupText(lineNr.ToString(), didRead, isSelected); }
// todo: move to version control backend IEnumerable <Conflict> Conflicts(Mono.TextEditor.Document doc) { foreach (int mergeStart in doc.SearchForward("<<<<<<<", 0)) { LineSegment start = doc.GetLineByOffset(mergeStart); if (start.Offset != mergeStart) { continue; } int dividerOffset = doc.SearchForward("=======", mergeStart).First(); LineSegment divider = doc.GetLineByOffset(dividerOffset); int endOffset = doc.SearchForward(">>>>>>>", dividerOffset).First(); LineSegment end = doc.GetLineByOffset(endOffset); yield return(new Conflict(new Mono.TextEditor.Segment(start.EndOffset, divider.Offset - start.EndOffset), new Mono.TextEditor.Segment(divider.EndOffset, end.Offset - divider.EndOffset), new Mono.TextEditor.Segment(start), new Mono.TextEditor.Segment(divider), new Mono.TextEditor.Segment(end))); } }
public ExtensibleTextEditor(SourceEditorView view, ISourceEditorOptions options, Mono.TextEditor.Document doc) : base(doc, options) { Initialize(view); }
static IEnumerable <KeyValuePair <char, int> > GetTextWithoutCommentsAndStrings(Mono.TextEditor.Document doc, int start, int end) { bool isInString = false, isInChar = false; bool isInLineComment = false, isInBlockComment = false; for (int pos = start; pos < end; pos++) { char ch = doc.GetCharAt(pos); switch (ch) { case '\r': case '\n': isInLineComment = false; break; case '/': if (isInBlockComment) { if (pos > 0 && doc.GetCharAt(pos - 1) == '*') { isInBlockComment = false; } } else if (!isInString && !isInChar && pos + 1 < doc.Length) { char nextChar = doc.GetCharAt(pos + 1); if (nextChar == '/') { isInLineComment = true; } if (!isInLineComment && nextChar == '*') { isInBlockComment = true; } } break; case '"': if (!(isInChar || isInLineComment || isInBlockComment)) { isInString = !isInString; } break; case '\'': if (!(isInString || isInLineComment || isInBlockComment)) { isInChar = !isInChar; } break; default: if (!(isInString || isInChar || isInLineComment || isInBlockComment)) { yield return(new KeyValuePair <char, int> (ch, pos)); } break; } } }
// string expression; /* IMember GetLanguageItem (Mono.TextEditor.Document document, LineSegment line, int offset, string expression) * { * string txt = document.Text; * ExpressionResult expressionResult = new ExpressionResult (expression); * // ExpressionResult expressionResult = expressionFinder.FindFullExpression (txt, offset); * int lineNumber = document.OffsetToLineNumber (offset); * expressionResult.Region = new DomRegion (lineNumber, offset - line.Offset, lineNumber, offset + expression.Length - line.Offset); * expressionResult.ExpressionContext = ExpressionContext.IdentifierExpected; * * resolver = new NRefactoryResolver (ctx, doc.CompilationUnit, doc.TextEditor, document.FileName); * ResolveResult result = resolver.Resolve (expressionResult, expressionResult.Region.Start); * * if (result is MemberResolveResult) * return ((MemberResolveResult)result).ResolvedMember; * return null; * }*/ public override void Analyze(Mono.TextEditor.Document doc, LineSegment line, Chunk startChunk, int startOffset, int endOffset) { if (!MonoDevelop.Core.PropertyService.Get("EnableSemanticHighlighting", false) || doc == null || line == null || startChunk == null) { return; } ctx = GetParserContext(doc); int lineNumber = doc.OffsetToLineNumber(line.Offset); ParsedDocument parsedDocument = ProjectDomService.GetParsedDocument(ctx, doc.FileName); ICompilationUnit unit = parsedDocument != null ? parsedDocument.CompilationUnit : null; if (unit == null) { return; } for (Chunk chunk = startChunk; chunk != null; chunk = chunk.Next) { if (chunk.Style != "text") { continue; } for (int i = chunk.Offset; i < chunk.EndOffset; i++) { char charBefore = i > 0 ? doc.GetCharAt(i - 1) : '}'; if (Char.IsLetter(doc.GetCharAt(i)) && !Char.IsLetterOrDigit(charBefore)) { } else { continue; } int start = i; bool wasWhitespace = false; bool wasDot = false; int bracketCount = 0; while (start > 0) { char ch = doc.GetCharAt(start); if (ch == '\n' || ch == '\r') { break; } if (wasWhitespace && IsNamePart(ch)) { start++; if (start < chunk.Offset) { start = Int32.MaxValue; } break; } if (ch == '<') { bracketCount--; if (bracketCount < 0) { start++; break; } start--; wasWhitespace = false; continue; } if (ch == '>') { if (wasWhitespace && !wasDot) { break; } bracketCount++; start--; wasWhitespace = false; continue; } if (!IsNamePart(ch) && !Char.IsWhiteSpace(ch) && ch != '.') { start++; break; } wasWhitespace = Char.IsWhiteSpace(ch); wasDot = ch == '.' || wasDot && wasWhitespace; start--; } int end = i; int genericCount = 0; wasWhitespace = false; List <Segment> nameSegments = new List <Segment> (); while (end < chunk.EndOffset) { char ch = doc.GetCharAt(end); if (wasWhitespace && IsNamePart(ch)) { break; } if (ch == '<') { genericCount = 1; while (end < doc.Length) { ch = doc.GetCharAt(end); if (ch == ',') { genericCount++; } if (ch == '>') { nameSegments.Add(new Segment(end, 1)); break; } end++; } break; } if (!IsNamePart(ch) && !Char.IsWhiteSpace(ch)) { break; } wasWhitespace = Char.IsWhiteSpace(ch); end++; } if (start >= end) { continue; } string typeString = doc.GetTextBetween(start, end); IReturnType returnType = NRefactoryResolver.ParseReturnType(new ExpressionResult(typeString)); int nameEndOffset = start; for (; nameEndOffset < end; nameEndOffset++) { char ch = doc.GetCharAt(nameEndOffset); if (nameEndOffset >= i && ch == '<') { nameEndOffset++; break; } } nameSegments.Add(new Segment(i, nameEndOffset - i)); int column = i - line.Offset; IType callingType = unit.GetTypeAt(lineNumber, column); List <IReturnType> genericParams = null; if (genericCount > 0) { genericParams = new List <IReturnType> (); for (int n = 0; n < genericCount; n++) { genericParams.Add(new DomReturnType("A")); } } IType type = null; if (ctx != null) { type = ctx.SearchType((MonoDevelop.Projects.Dom.INode)callingType ?? unit, returnType); } if (type == null && unit != null && returnType != null) { type = unit.GetType(returnType.FullName, returnType.GenericArguments.Count); } if (ctx != null && type == null && returnType != null) { returnType.Name += "Attribute"; type = ctx.SearchType((MonoDevelop.Projects.Dom.INode)callingType ?? unit, returnType); } if (type != null) { nameSegments.ForEach(segment => HighlightSegment(startChunk, segment, "keyword.semantic.type")); } } } }