public override void ShowTooltipWindow(Ide.Editor.TextEditor editor, Components.Window tipWindow, TooltipItem item, Xwt.ModifierKeys modifierState, int mouseX, int mouseY) { base.ShowTooltipWindow(editor, tipWindow, item, modifierState, mouseX, mouseY); var info = (TaggedTooltipInformation <CodeActions.CodeActionContainer>)item.Item; var sourceEditorView = editor.GetContent <SourceEditorView> (); var codeActionEditorExtension = editor.GetContent <CodeActionEditorExtension> (); var loc = editor.OffsetToLocation(info.Tag.Span.Start); if (info.Tag?.FloatingWidgetShown == true) { var point = sourceEditorView.TextEditor.TextArea.LocationToPoint(loc.Line, loc.Column); point.Y += (int)editor.GetLineHeight(loc.Line); var window = (LanguageItemWindow)tipWindow; if (floatingWidget != null) { floatingWidget.Destroy(); floatingWidget = null; } floatingWidget = new FloatingQuickFixIconWidget(codeActionEditorExtension, window, sourceEditorView, info.Tag, point); sourceEditorView.TextEditor.GdkWindow.GetOrigin(out int ox, out int oy); floatingWidget.Move(ox + (int)point.X, oy + (int)(point.Y + 4)); window.Tag = floatingWidget; window.EnterNotifyEvent += delegate { floatingWidget.CancelDestroy(); }; window.LeaveNotifyEvent += delegate { floatingWidget.QueueDestroy(); }; } }
public override void GetRequiredPosition(Ide.Editor.TextEditor editor, Components.Window tipWindow, out int requiredWidth, out double xalign) { var win = (TooltipInformationWindow)tipWindow; requiredWidth = (int)win.Width; xalign = 0.5; }
internal CodeGenerationOptions(Ide.Editor.TextEditor editor, DocumentContext ctx) { Editor = editor; DocumentContext = ctx; if (ctx.AnalysisDocument != null) { CurrentState = ctx.AnalysisDocument.GetSemanticModelAsync().WaitAndGetResult(); } offset = editor.CaretOffset; var tree = CurrentState.SyntaxTree; EnclosingPart = tree.GetContainingTypeDeclaration(offset, default(CancellationToken)); if (EnclosingPart != null) { EnclosingType = CurrentState.GetDeclaredSymbol(EnclosingPart) as ITypeSymbol; foreach (var member in EnclosingPart.Members) { if (member.Span.Contains(offset)) { EnclosingMemberSyntax = member; break; } } if (EnclosingMemberSyntax != null) { EnclosingMember = CurrentState.GetDeclaredSymbol(EnclosingMemberSyntax); } } }
public override void GetRequiredPosition(Ide.Editor.TextEditor editor, Window tipWindow, out int requiredWidth, out double xalign) { var win = (LanguageItemWindow)tipWindow; requiredWidth = win.SetMaxWidth(win.Screen.Width / 4); xalign = 0.5; }
public JSonIndentEngine(Ide.Editor.TextEditor editor) { if (editor == null) { throw new ArgumentNullException("editor"); } this.editor = editor; Reset(); }
protected AbstractOptionPreviewViewModel(OptionSet options, IServiceProvider serviceProvider, string language) { this.Options = options; _originalOptions = options; this.Items = new List <object> (); this.CodeStyleItems = new ObservableCollection <AbstractCodeStyleOptionViewModel> (); this.Language = language; _textViewHost = TextEditorFactory.CreateNewEditor(); _textViewHost.Options = DefaultSourceEditorOptions.PlainEditor; }
public static async Task <ImmutableArray <string> > GetUsedNamespacesAsync(Ide.Editor.TextEditor editor, DocumentContext doc, int offset, CancellationToken cancellationToken = default(CancellationToken)) { if (editor == null) { throw new System.ArgumentNullException(nameof(editor)); } var parsedDocument = doc.ParsedDocument; if (parsedDocument == null) { return(ImmutableArray <string> .Empty); } var result = ImmutableArray <string> .Empty.ToBuilder(); var sm = await doc.AnalysisDocument.GetSemanticModelAsync(cancellationToken); if (sm == null) { return(ImmutableArray <string> .Empty); } var node = (await sm.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false)).FindNode(TextSpan.FromBounds(offset, offset)); while (node != null) { var cu = node as CompilationUnitSyntax; if (cu != null) { foreach (var u in cu.Usings) { if (u.Kind() == Microsoft.CodeAnalysis.CSharp.SyntaxKind.UsingDirective) { result.Add(u.Name.ToString()); } } } var ns = node as NamespaceDeclarationSyntax; if (ns != null) { var name = ns.Name.ToString(); result.Add(name); foreach (var u in ns.Usings) { if (u.Kind() == Microsoft.CodeAnalysis.CSharp.SyntaxKind.UsingDirective) { result.Add(u.Name.ToString()); } } } node = node.Parent; } return(result.ToImmutable()); }
static void AddNestedFixMenu(Ide.Editor.TextEditor editor, CodeFixMenu menu, CodeFixMenu fixAllMenu, CodeAction.CodeActionWithNestedActions fixes, FixAllState fixState, CancellationToken token) { int subMnemonic = 0; var subMenu = new CodeFixMenu(fixes.Title); foreach (var fix in fixes.NestedCodeActions) { AddFixMenuItem(editor, subMenu, fixAllMenu, ref subMnemonic, fix, fixState, token); } menu.Add(subMenu); }
static void Rollback(Ide.Editor.TextEditor editor, List <MonoDevelop.Core.Text.TextChangeEventArgs> textChanges) { for (int i = textChanges.Count - 1; i >= 0; i--) { for (int j = 0; j < textChanges [i].TextChanges.Count; ++j) { var v = textChanges [i].TextChanges [j]; editor.ReplaceText(v.Offset, v.InsertionLength, v.RemovedText); } } }
protected async override Task CorrectIndentingImplementationAsync(Ide.Editor.TextEditor editor, DocumentContext context, int startLine, int endLine, CancellationToken cancellationToken) { if (editor.IndentationTracker == null) { return; } var startSegment = editor.GetLine(startLine); if (startSegment == null) { return; } var endSegment = startLine != endLine?editor.GetLine(endLine) : startSegment; if (endSegment == null) { return; } try { var document = context.AnalysisDocument; var formattingService = document.GetLanguageService <IEditorFormattingService> (); if (formattingService == null || !formattingService.SupportsFormatSelection) { return; } var formattingRules = new List <AbstractFormattingRule> (); formattingRules.Add(ContainedDocumentPreserveFormattingRule.Instance); formattingRules.AddRange(Formatter.GetDefaultFormattingRules(document)); var workspace = document.Project.Solution.Workspace; var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var changes = Formatter.GetFormattedTextChanges( root, new TextSpan [] { new TextSpan(startSegment.Offset, endSegment.EndOffset - startSegment.Offset) }, workspace, options, formattingRules, cancellationToken); if (changes == null) { return; } await Runtime.RunInMainThread(delegate { editor.ApplyTextChanges(changes); editor.FixVirtualIndentation(); }); } catch (Exception e) { LoggingService.LogError("Error while indenting", e); } }
public CodeRulePanelWidget() { TextEditor = TextEditorFactory.CreateNewEditor(); TextEditor.MimeType = "application/xml"; TextEditor.Options = DefaultSourceEditorOptions.PlainEditor; try { TextEditor.Text = TextFileUtility.GetText(IdeApp.TypeSystemService.RuleSetManager.GlobalRulesetFileName, out encoding); } catch (Exception e) { LoggingService.LogError("Error while loading global rule set file " + IdeApp.TypeSystemService.RuleSetManager, e); loadingError = true; } }
JSonIndentEngine(JSonIndentEngine jSonIndentEngine) { this.editor = jSonIndentEngine.editor; this.offset = jSonIndentEngine.offset; this.line = jSonIndentEngine.line; this.column = jSonIndentEngine.column; this.thisLineIndent = jSonIndentEngine.thisLineIndent; this.nextLineIndent = jSonIndentEngine.nextLineIndent; this.currentIndent = jSonIndentEngine.currentIndent != null ? new StringBuilder(jSonIndentEngine.currentIndent.ToString()) : null; this.previousChar = jSonIndentEngine.previousChar; this.isLineStart = jSonIndentEngine.isLineStart; this.isInString = jSonIndentEngine.isInString; }
//private static List<LineSpan> GetExposedLineSpans (ITextSnapshot textSnapshot) //{ // const string start = "//["; // const string end = "//]"; // var bufferText = textSnapshot.GetText ().ToString (); // var lineSpans = new List<LineSpan> (); // var lastEndIndex = 0; // while (true) { // var startIndex = bufferText.IndexOf (start, lastEndIndex, StringComparison.Ordinal); // if (startIndex == -1) { // break; // } // var endIndex = bufferText.IndexOf (end, lastEndIndex, StringComparison.Ordinal); // var startLine = textSnapshot.GetLineNumberFromPosition (startIndex) + 1; // var endLine = textSnapshot.GetLineNumberFromPosition (endIndex); // lineSpans.Add (LineSpan.FromBounds (startLine, endLine)); // lastEndIndex = endIndex + end.Length; // } // return lineSpans; //} public void Dispose() { if (_textViewHost != null) { _textViewHost.Dispose(); _textViewHost = null; } if (curWorkspace != null) { curWorkspace.Dispose(); curWorkspace = null; } }
public RefactoringOptions(Ide.Editor.TextEditor editor, DocumentContext doc) { this.DocumentContext = doc; this.Editor = editor; /*if (doc != null && doc.ParsedDocument != null) { * var sharedResolver = doc.GetSharedResolver (); * if (sharedResolver == null) * return; * resolver = sharedResolver; * //Unit = resolver != null ? resolver.RootNode as SyntaxTree : null; * }*/ }
static CodeFixMenuEntry CreateFixMenuEntry(Ide.Editor.TextEditor editor, CodeAction fix, ref int mnemonic) { var label = mnemonic < 0 ? fix.Title : CreateLabel(fix.Title, ref mnemonic); var item = new CodeFixMenuEntry(label, async delegate { await new ContextActionRunner(editor, fix).Run(); }); item.ShowPreviewTooltip = delegate(Xwt.Rectangle rect) { RefactoringPreviewTooltipWindow.ShowPreviewTooltip(editor, fix, rect); }; return(item); }
static CodeFixMenuEntry CreateFixAllMenuEntry(Ide.Editor.TextEditor editor, FixAllState fixState, ref int mnemonic, CancellationToken token) { var provider = fixState?.FixAllProvider; if (provider == null) { return(null); } var doc = editor.DocumentContext; var workspace = doc?.RoslynWorkspace; if (workspace == null) { return(null); } var title = fixState.GetDefaultFixAllTitle(); var label = mnemonic < 0 ? title : CreateLabel(title, ref mnemonic); var item = new CodeFixMenuEntry(label, async delegate { // Task.Run here so we don't end up binding the whole document on popping the menu, also there is no cancellation token support Microsoft.CodeAnalysis.Text.TextChange[] result = await Task.Run(async() => { var context = fixState.CreateFixAllContext(new RoslynProgressTracker(), token); var fix = await provider.GetFixAsync(context); var previewOperations = await fix.GetPreviewOperationsAsync(token); return(await Runtime.RunInMainThread(() => { var engine = Xwt.Toolkit.CurrentEngine; // NativeEngine return engine.Invoke(async() => { using (var dialog = new FixAllPreviewDialog(string.Join(", ", fixState.DiagnosticIds), doc.Name, fixState.Scope, previewOperations, editor)) { await dialog.InitializeEditor(); var parent = Xwt.Toolkit.CurrentEngine.WrapWindow(IdeApp.Workbench.RootWindow); var changes = dialog.Run(parent) == Xwt.Command.Apply ? dialog.GetApplicableChanges().ToArray() : Array.Empty <Microsoft.CodeAnalysis.Text.TextChange> (); return changes; } }); })); }); if (result.Length == 0) { return; } editor.ApplyTextChanges(result); }); return(item); }
RefactoringPreviewTooltipWindow(Ide.Editor.TextEditor editor, CodeAction codeAction) { this.editor = editor; this.documentContext = documentContext = editor.DocumentContext; this.codeAction = codeAction; TransientFor = IdeApp.Workbench.RootWindow; fontDescription = Pango.FontDescription.FromString(DefaultSourceEditorOptions.Instance.FontName); fontDescription.Size = (int)(fontDescription.Size * 0.8f); using (var metrics = PangoContext.GetMetrics(fontDescription, PangoContext.Language)) { lineHeight = (int)Math.Ceiling(0.5 + (metrics.Ascent + metrics.Descent) / Pango.Scale.PangoScale); } }
public override async Task <TooltipItem> GetItem(Ide.Editor.TextEditor editor, DocumentContext ctx, int offset, CancellationToken token = default(CancellationToken)) { if (ctx == null) { return(null); } var analysisDocument = ctx.AnalysisDocument; if (analysisDocument == null) { return(null); } var unit = await analysisDocument.GetSemanticModelAsync(token); if (unit == null) { return(null); } int caretOffset = editor.CaretOffset; EditorTheme theme = SyntaxHighlightingService.GetIdeFittingTheme(editor.Options.GetEditorTheme()); return(await Task.Run(async() => { var root = unit.SyntaxTree.GetRoot(token); SyntaxToken syntaxToken; try { syntaxToken = root.FindToken(offset); } catch (ArgumentOutOfRangeException) { return null; } if (!syntaxToken.Span.Contains(offset)) { return null; } var node = GetBestFitResolveableNode(syntaxToken.Parent); var symbolInfo = unit.GetSymbolInfo(node, token); var symbol = symbolInfo.Symbol; if (symbol == null && syntaxToken.IsKind(SyntaxKind.IdentifierToken)) { symbol = unit.GetDeclaredSymbol(node, token); } var tooltipInformation = await CreateTooltip(symbol, syntaxToken, caretOffset, theme, ctx, offset); if (tooltipInformation == null || string.IsNullOrEmpty(tooltipInformation.SignatureMarkup)) { return null; } return new TooltipItem(tooltipInformation, syntaxToken.Span.Start, syntaxToken.Span.Length); })); }
internal async Task Run(Ide.Editor.TextEditor editor, DocumentContext ctx) { var cts = new CancellationTokenSource(); var getSymbolTask = RenameLocations.ReferenceProcessing.GetRenamableSymbolAsync(ctx.AnalysisDocument, editor.CaretOffset, cts.Token); var message = GettextCatalog.GetString("Resolving symbol…"); var info = await MessageService.ExecuteTaskAndShowWaitDialog(getSymbolTask, message, cts); var sym = info.Symbol; if (!CanRename(sym)) { return; } await new RenameRefactoring().Rename(sym); }
public override Components.Window CreateTooltipWindow(Ide.Editor.TextEditor editor, DocumentContext ctx, TooltipItem item, int offset, Xwt.ModifierKeys modifierState) { var doc = ctx; if (doc == null) { return(null); } var result = new TooltipInformationWindow(); result.ShowArrow = true; result.AddOverload((TooltipInformation)item.Item); result.RepositionWindow(); return(result); }
protected override Xwt.Point CalculateWindowLocation(Ide.Editor.TextEditor editor, TooltipItem item, Xwt.WindowFrame xwtWindow, int mouseX, int mouseY, Xwt.Point origin) { int w; double xalign; GetRequiredPosition(editor, xwtWindow, out w, out xalign); w += 10; var allocation = GetAllocation(editor); var info = (TaggedTooltipInformation <CodeActions.CodeActionContainer>)item.Item; var loc = editor.OffsetToLocation(info.Tag.Span.Start); var p = editor.LocationToPoint(loc); var view = editor.GetContent <SourceEditorView> (); int x = (int)(p.X + origin.X + allocation.X + xPadding); int y = (int)(p.Y + view.TextEditor.GetLineHeight(loc.Line) + origin.Y + allocation.Y + yPadding); Gtk.Widget widget = editor; var geometry = widget.Screen.GetUsableMonitorGeometry(widget.Screen.GetMonitorAtPoint(x, y)); if (x + w >= geometry.X + geometry.Width) { x = geometry.X + geometry.Width - w; } if (x < geometry.Left) { x = geometry.Left; } if (info.Tag?.FloatingWidgetShown == true) { x += windowSize; } int h = (int)xwtWindow.Size.Height; if (y + h >= geometry.Y + geometry.Height) { y = geometry.Y + geometry.Height - h; } if (y < geometry.Top) { y = geometry.Top; } return(new Xwt.Point(x, y)); }
public static string GetWhitespaces(Ide.Editor.TextEditor editor, int insertionOffset) { StringBuilder result = new StringBuilder(); for (int i = insertionOffset; i < editor.Length; i++) { char ch = editor.GetCharAt(i); if (ch == ' ' || ch == '\t') { result.Append(ch); } else { break; } } return(result.ToString()); }
static Cairo.Color GetColor(Ide.Editor.TextEditor editor, Result result) { switch (result.Level) { case DiagnosticSeverity.Hidden: return(SyntaxHighlightingService.GetColor(DefaultSourceEditorOptions.Instance.GetEditorTheme(), EditorThemeColors.Background)); case DiagnosticSeverity.Error: return(SyntaxHighlightingService.GetColor(DefaultSourceEditorOptions.Instance.GetEditorTheme(), EditorThemeColors.UnderlineError)); case DiagnosticSeverity.Warning: return(SyntaxHighlightingService.GetColor(DefaultSourceEditorOptions.Instance.GetEditorTheme(), EditorThemeColors.UnderlineWarning)); case DiagnosticSeverity.Info: return(SyntaxHighlightingService.GetColor(DefaultSourceEditorOptions.Instance.GetEditorTheme(), EditorThemeColors.UnderlineSuggestion)); default: throw new System.ArgumentOutOfRangeException(); } }
protected override async void OnTheFlyFormatImplementation(Ide.Editor.TextEditor editor, DocumentContext context, int startOffset, int length) { var doc = context.AnalysisDocument; var formattingService = doc.GetLanguageService <IEditorFormattingService> (); if (formattingService == null || !formattingService.SupportsFormatSelection) { return; } var changes = await formattingService.GetFormattingChangesAsync(doc, new TextSpan (startOffset, length), default(System.Threading.CancellationToken)); if (changes == null) { return; } editor.ApplyTextChanges(changes); editor.FixVirtualIndentation(); }
public static void ShowIfValid(Ide.Editor.TextEditor editor, DocumentContext context, MonoDevelop.Ide.CodeCompletion.CodeCompletionContext completionContext) { var options = CodeGenerationOptions.CreateCodeGenerationOptions(editor, context); var validGenerators = new List <ICodeGenerator> (); foreach (var generator in CodeGenerationService.CodeGenerators) { if (generator.IsValid(options)) { validGenerators.Add(generator); } } if (validGenerators.Count < 1) { return; } var window = new GenerateCodeWindow(options, completionContext); window.Populate(validGenerators); }
public override Window CreateTooltipWindow(Ide.Editor.TextEditor editor, DocumentContext ctx, TooltipItem item, int offset, Xwt.ModifierKeys modifierState) { var result = item.Item as TooltipInformation; if (result == null) { return(null); } var window = new LanguageItemWindow(CompileErrorTooltipProvider.GetExtensibleTextEditor(editor), modifierState, null, result.SignatureMarkup, null); window.Destroyed += delegate { if (window.Tag is FloatingQuickFixIconWidget widget) { widget.QueueDestroy(); } }; if (window.IsEmpty) { return(null); } return(window); }
RefactoringPreviewTooltipWindow(Ide.Editor.TextEditor editor, CodeAction codeAction) { this.editor = editor; this.documentContext = documentContext = editor.DocumentContext; this.codeAction = codeAction; TransientFor = IdeApp.Workbench.RootWindow; var font = Xwt.Drawing.Font.FromName(DefaultSourceEditorOptions.Instance.FontName); if (font != null) { fontDescription = font.ToPangoFont(); fontDescription.Size = (int)(fontDescription.Size * 0.8f); } else { LoggingService.LogError("Error loading font : " + DefaultSourceEditorOptions.Instance.FontName); } using (var metrics = PangoContext.GetMetrics(fontDescription, PangoContext.Language)) { lineHeight = (int)Math.Ceiling(0.5 + (metrics.Ascent + metrics.Descent) / Pango.Scale.PangoScale); } }
static void AddFixMenuItem(Ide.Editor.TextEditor editor, CodeFixMenu menu, CodeFixMenu fixAllMenu, ref int mnemonic, CodeAction fix, FixAllState fixState, CancellationToken token) { if (fix is CodeAction.CodeActionWithNestedActions nested) { // Inline code actions if they are, otherwise add a nested fix menu if (nested.IsInlinable) { int actionCount = nested.NestedCodeActions.Length; foreach (var nestedFix in nested.NestedCodeActions) { var nestedFixState = actionCount > 1 && nestedFix.EquivalenceKey == null ? null : fixState; AddFixMenuItem(editor, menu, fixAllMenu, ref mnemonic, nestedFix, nestedFixState, token); } return; } if (nested.NestedCodeActions.Length > 0) { AddNestedFixMenu(editor, menu, fixAllMenu, nested, fixState, token); } return; } menu.Add(CreateFixMenuEntry(editor, fix, ref mnemonic)); // TODO: Add support for more than doc when we have global undo. fixState = fixState?.WithScopeAndEquivalenceKey(FixAllScope.Document, fix.EquivalenceKey); var fixAllMenuEntry = CreateFixAllMenuEntry(editor, fixState, ref mnemonic, token); if (fixAllMenuEntry != null) { fixAllMenu.Add(new CodeFixMenuEntry(fix.Message, null)); fixAllMenu.Add(fixAllMenuEntry); } }
public CSharpIndentationTracker(Ide.Editor.TextEditor editor, DocumentContext context) { this.editor = editor; this.context = context; smartIndentationService = CompositionManager.Instance.ExportProvider.GetExportedValue <ISmartIndentationService> (); }
protected override void CorrectIndentingImplementation(PolicyContainer policyParent, Ide.Editor.TextEditor editor, int line) { var doc = IdeApp.Workbench.ActiveDocument; if (doc == null) { return; } CorrectIndentingImplementationAsync(editor, doc.DocumentContext, line, line, default).Ignore(); }