public static async Task<RefactoringSymbolInfo> GetSymbolInfoAsync (DocumentContext document, int offset, CancellationToken cancellationToken = default(CancellationToken)) { if (document == null) throw new ArgumentNullException (nameof (document)); if (document.ParsedDocument == null) return RefactoringSymbolInfo.Empty; var unit = await document.AnalysisDocument.GetSemanticModelAsync (cancellationToken).ConfigureAwait (false); if (unit != null) { var root = await unit.SyntaxTree.GetRootAsync (cancellationToken).ConfigureAwait (false); try { var token = root.FindToken (offset); if (!token.Span.IntersectsWith (offset)) return RefactoringSymbolInfo.Empty; var symbol = unit.GetSymbolInfo (token.Parent); return new RefactoringSymbolInfo (symbol) { DeclaredSymbol = token.IsKind (SyntaxKind.IdentifierToken) ? unit.GetDeclaredSymbol (token.Parent) : null, Node = token.Parent, Model = unit }; } catch (Exception) { return RefactoringSymbolInfo.Empty; } } return RefactoringSymbolInfo.Empty; }
public override bool CheckOpeningPoint(TextEditor editor, DocumentContext ctx, CancellationToken cancellationToken) { var snapshot = CurrentSnapshot; var position = StartOffset; var token = FindToken(snapshot, position, cancellationToken); // check token at the opening point first if (!IsValidToken(token) || token.RawKind != OpeningTokenKind || token.SpanStart != position || token.Parent == null) { return false; } // now check whether parser think whether there is already counterpart closing parenthesis var pair = token.Parent.GetParentheses(); // if pair is on the same line, then the closing parenthesis must belong to other tracker. // let it through if (Editor.GetLineByOffset (pair.Item1.SpanStart).LineNumber == Editor.GetLineByOffset(pair.Item2.Span.End).LineNumber) { return true; } return (int)pair.Item2.Kind() != ClosingTokenKind || pair.Item2.Span.Length == 0; }
public ProjectedDocumentContext (TextEditor projectedEditor, DocumentContext originalContext) { if (projectedEditor == null) throw new ArgumentNullException ("projectedEditor"); if (originalContext == null) throw new ArgumentNullException ("originalContext"); this.projectedEditor = projectedEditor; this.originalContext = originalContext; if (originalContext.Project != null) { var originalProjectId = TypeSystemService.GetProjectId (originalContext.Project); if (originalProjectId != null) { var originalProject = TypeSystemService.Workspace.CurrentSolution.GetProject (originalProjectId); if (originalProject != null) { projectedDocument = originalProject.AddDocument ( projectedEditor.FileName, projectedEditor ); } } } projectedEditor.TextChanged += delegate(object sender, TextChangeEventArgs e) { if (projectedDocument != null) projectedDocument = projectedDocument.WithText (projectedEditor); ReparseDocument (); }; ReparseDocument (); }
void HandleDocumentContextChanged (object sender, EventArgs e) { if (currentContext != null) currentContext.DocumentParsed -= HandleDocumentParsed; currentContext = textEditor.DocumentContext; currentContext.DocumentParsed += HandleDocumentParsed; }
public override bool IsValidInContext (DocumentContext context) { var pctx = context as ProjectedDocumentContext; if (pctx == null) return false; return pctx.ProjectedEditor.GetContent<CompletionTextEditorExtension> () != null; }
public ProjectedCompletionExtension (DocumentContext ctx, IReadOnlyList<Projection> projections) { if (projections == null) throw new ArgumentNullException ("projections"); this.ctx = ctx; this.projections = projections; }
public NavigationVisitor (DocumentContext documentContext, SemanticModel model, TextSpan region, CancellationToken token) { this.documentContext = documentContext; this.model = model; this.region = region; this.token = token; }
public override async Task<TooltipItem> GetItem (TextEditor editor, DocumentContext ctx, int offset, CancellationToken token = default(CancellationToken)) { if (ctx == null) return null; var analysisDocument = ctx.ParsedDocument; if (analysisDocument == null) return null; var unit = analysisDocument.GetAst<SemanticModel> (); if (unit == null) return null; var root = unit.SyntaxTree.GetRoot (token); SyntaxToken syntaxToken; try { syntaxToken = root.FindToken (offset); } catch (ArgumentOutOfRangeException) { return null; } if (!syntaxToken.Span.IntersectsWith (offset)) return null; var symbolInfo = unit.GetSymbolInfo (syntaxToken.Parent, token); var symbol = symbolInfo.Symbol ?? unit.GetDeclaredSymbol (syntaxToken.Parent, token); var tooltipInformation = await CreateTooltip (symbol, syntaxToken, editor, ctx, offset); if (tooltipInformation == null || string.IsNullOrEmpty (tooltipInformation.SignatureMarkup)) return null; return new TooltipItem (tooltipInformation, syntaxToken.Span.Start, syntaxToken.Span.Length); }
public override Control CreateTooltipWindow (TextEditor editor, DocumentContext ctx, TooltipItem item, int offset, Xwt.ModifierKeys modifierState) { var result = new LanguageItemWindow (GetExtensibleTextEditor (editor), modifierState, null, (string)item.Item, null); if (result.IsEmpty) return null; return result; }
public static bool IsContext(TextEditor editor, DocumentContext ctx, int position, CancellationToken cancellationToken) { // Check to see if we're to the right of an $ or an @$ var start = position - 1; if (start < 0) { return false; } if (editor[start] == '@') { start--; if (start < 0) { return false; } } if (editor[start] != '$') { return false; } var tree = ctx.AnalysisDocument.GetSyntaxTreeAsync (cancellationToken).WaitAndGetResult(cancellationToken); var token = tree.GetRoot(cancellationToken).FindTokenOnLeftOfPosition(start); return tree.IsExpressionContext(start, token, attributes: false, cancellationToken: cancellationToken) || tree.IsStatementContext(start, token, cancellationToken); }
CSharpCompletionTextEditorExtension CreateCompletionAndUpdate (MonoDevelop.Ide.Editor.TextEditor editor, DocumentContext context, UnderlyingDocumentInfo docInfo, out CodeCompletionContext codeCompletionContext) { var completion = CreateCompletion (editor, context, docInfo, out codeCompletionContext); completion.UpdateParsedDocument (); return completion; }
public static void FormatStatmentAt (TextEditor editor, DocumentContext context, MonoDevelop.Ide.Editor.DocumentLocation location, OptionSet optionSet = null) { var offset = editor.LocationToOffset (location); var policyParent = context.Project != null ? context.Project.Policies : PolicyService.DefaultPolicies; var mimeTypeChain = DesktopService.GetMimeTypeInheritanceChain (CSharpFormatter.MimeType); Format (policyParent, mimeTypeChain, editor, context, offset, offset, false, true, optionSet: optionSet); }
public Task<ICompletionDataList> HandleCompletion (MonoDevelop.Ide.Editor.TextEditor editor, DocumentContext context, CodeCompletionContext completionContext, UnderlyingDocumentInfo docInfo, char currentChar, CancellationToken token) { CodeCompletionContext ccc; var completion = CreateCompletionAndUpdate (editor, context, docInfo, out ccc); return completion.HandleCodeCompletionAsync (completionContext, currentChar, token); }
static void Format (PolicyContainer policyParent, IEnumerable<string> mimeTypeChain, TextEditor editor, DocumentContext context, int startOffset, int endOffset, bool exact, bool formatLastStatementOnly = false, OptionSet optionSet = null) { TextSpan span; if (exact) { span = new TextSpan (startOffset, endOffset - startOffset); } else { span = new TextSpan (0, endOffset); } var analysisDocument = context.AnalysisDocument; if (analysisDocument == null) return; using (var undo = editor.OpenUndoGroup (/*OperationType.Format*/)) { try { var syntaxTree = analysisDocument.GetSyntaxTreeAsync ().Result; if (formatLastStatementOnly) { var root = syntaxTree.GetRoot (); var token = root.FindToken (endOffset); var tokens = ICSharpCode.NRefactory6.CSharp.FormattingRangeHelper.FindAppropriateRange (token); if (tokens.HasValue) { span = new TextSpan (tokens.Value.Item1.SpanStart, tokens.Value.Item2.Span.End - tokens.Value.Item1.SpanStart); } else { var parent = token.Parent; if (parent != null) span = parent.FullSpan; } } if (optionSet == null) { var policy = policyParent.Get<CSharpFormattingPolicy> (mimeTypeChain); var textPolicy = policyParent.Get<TextStylePolicy> (mimeTypeChain); optionSet = policy.CreateOptions (textPolicy); } var doc = Formatter.FormatAsync (analysisDocument, span, optionSet).Result; var newTree = doc.GetSyntaxTreeAsync ().Result; var caretOffset = editor.CaretOffset; int delta = 0; foreach (var change in newTree.GetChanges (syntaxTree)) { if (!exact && change.Span.Start + delta >= caretOffset) continue; var newText = change.NewText; editor.ReplaceText (delta + change.Span.Start, change.Span.Length, newText); delta = delta - change.Span.Length + newText.Length; } var caretEndOffset = caretOffset + delta; if (0 <= caretEndOffset && caretEndOffset < editor.Length) editor.CaretOffset = caretEndOffset; if (editor.CaretColumn == 1) editor.CaretColumn = editor.GetVirtualIndentationColumn (editor.CaretLine); } catch (Exception e) { LoggingService.LogError ("Error in on the fly formatter", e); } } }
protected AbstractTokenBraceCompletionSession (DocumentContext ctx, int openingTokenKind, int closingTokenKind, char ch) { this.closingChar = ch; this.ctx = ctx; this.OpeningTokenKind = openingTokenKind; this.ClosingTokenKind = closingTokenKind; }
public CodeGenerator(TemplateLoader templateLoader, DocumentContext context, GeneratorConfig config, DirectoryInfo outputFolder) { this.outputFolder = outputFolder; this.templateLoader = templateLoader; this.contextGenerator = context.TemplateContextGenerator; this.config = config; }
public async static Task<IEnumerable<CodeRefactoringDescriptor>> GetCodeRefactoringsAsync (DocumentContext documentContext, string language, CancellationToken cancellationToken = default (CancellationToken)) { var result = new List<CodeRefactoringDescriptor> (); foreach (var provider in providers) { result.AddRange (await provider.GetCodeRefactoringDescriptorsAsync (documentContext, language, cancellationToken).ConfigureAwait (false)); } return result; }
internal void Run (TextEditor editor, DocumentContext ctx) { var info = RefactoringSymbolInfo.GetSymbolInfoAsync (ctx, editor.CaretOffset).Result; var sym = info.DeclaredSymbol ?? info.Symbol; if (!CanRename (sym)) return; new RenameRefactoring ().Rename (sym); }
public ProjectedSemanticHighlighting (TextEditor editor, DocumentContext documentContext, IEnumerable<Projection> projections) : base (editor, documentContext) { this.projections = new List<Projection> (projections); foreach (var p in this.projections) { if (p.ProjectedEditor.SemanticHighlighting == null) continue; p.ProjectedEditor.SemanticHighlighting.SemanticHighlightingUpdated += HandleSemanticHighlightingUpdated; } }
public override Control CreateTooltipWindow (TextEditor editor, DocumentContext ctx, TooltipItem item, int offset, Xwt.ModifierKeys modifierState) { var result = item.Item as Result; var window = new LanguageItemWindow (CompileErrorTooltipProvider.GetExtensibleTextEditor (editor), modifierState, null, result.Message, null); if (window.IsEmpty) return null; return window; }
public override Control CreateTooltipWindow (TextEditor editor, DocumentContext ctx, TooltipItem item, int offset, Xwt.ModifierKeys modifierState) { foreach (var pseg in projection.ProjectedSegments) { if (pseg.ContainsOriginal (offset)) { return projectedTooltipProvider.CreateTooltipWindow (projection.ProjectedEditor, projection.ProjectedContext, item, pseg.FromOriginalToProjected (offset), modifierState); } } return null; }
public override async Task<TooltipItem> GetItem (TextEditor editor, DocumentContext ctx, int offset, CancellationToken token = default(CancellationToken)) { if (offset >= editor.Length) return null; if (!DebuggingService.IsDebugging || DebuggingService.IsRunning) return null; StackFrame frame = DebuggingService.CurrentFrame; if (frame == null) return null; var ed = CompileErrorTooltipProvider.GetExtensibleTextEditor (editor); if (ed == null) return null; string expression = null; int startOffset; if (ed.IsSomethingSelected && offset >= ed.SelectionRange.Offset && offset <= ed.SelectionRange.EndOffset) { startOffset = ed.SelectionRange.Offset; expression = ed.SelectedText; } else { var doc = ctx; if (doc == null || doc.ParsedDocument == null) return null; var resolver = doc.GetContent<IDebuggerExpressionResolver> (); var data = doc.GetContent<SourceEditorView> (); if (resolver != null) { var result = await resolver.ResolveExpressionAsync (editor, doc, offset, token); expression = result.Text; startOffset = result.Span.Start; } else { int endOffset = data.GetTextEditorData ().FindCurrentWordEnd (offset); startOffset = data.GetTextEditorData ().FindCurrentWordStart (offset); expression = editor.GetTextAt (startOffset, endOffset - startOffset); } } if (string.IsNullOrEmpty (expression)) return null; var options = DebuggingService.DebuggerSession.EvaluationOptions.Clone (); options.AllowMethodEvaluation = true; options.AllowTargetInvoke = true; var val = frame.GetExpressionValue (expression, options); if (val == null || val.IsUnknown || val.IsNotSupported) return null; val.Name = expression; return new TooltipItem (val, startOffset, expression.Length); }
public bool CheckOpeningPoint(TextEditor editor, DocumentContext ctx, CancellationToken cancellationToken) { var snapshot = ctx.AnalysisDocument.GetSyntaxTreeAsync (cancellationToken).WaitAndGetResult(cancellationToken); var position = editor.CaretOffset - 1; var token = AbstractTokenBraceCompletionSession.FindToken(snapshot, position, cancellationToken); return token.IsKind(SyntaxKind.OpenBraceToken) && token.SpanStart == position; }
public TextEditor CreateProjectedEditor (DocumentContext originalContext) { if (projectedEditor == null) { projectedEditor = TextEditorFactory.CreateNewEditor (Document, TextEditorType.Projection); projectedDocumentContext = new ProjectedDocumentContext (projectedEditor, originalContext); projectedEditor.InitializeExtensionChain (projectedDocumentContext); projectedProjections.InstallListener (projectedEditor); } return projectedEditor; }
public override Task<TooltipItem> GetItem (TextEditor editor, DocumentContext ctx, int offset, CancellationToken token = default (CancellationToken)) { foreach (var marker in editor.GetTextSegmentMarkersAt (offset)) { var result = marker.Tag as Result; if (result != null) return Task.FromResult(new TooltipItem (result, marker.Offset, marker.Length)); } return Task.FromResult<TooltipItem> (null); }
public JSonIndentEngine (TextEditor editor, DocumentContext ctx) { if (editor == null) throw new ArgumentNullException ("editor"); if (ctx == null) throw new ArgumentNullException ("ctx"); this.editor = editor; this.ctx = ctx; Reset (); }
internal async Task Run (TextEditor editor, DocumentContext ctx) { var cts = new CancellationTokenSource (); var getSymbolTask = RefactoringSymbolInfo.GetSymbolInfoAsync (ctx, editor, cts.Token); var message = GettextCatalog.GetString ("Resolving symbol…"); var info = await MessageService.ExecuteTaskAndShowWaitDialog (getSymbolTask, message, cts); var sym = info.DeclaredSymbol ?? info.Symbol; if (!CanRename (sym)) return; await new RenameRefactoring ().Rename (sym); }
public async static Task<IEnumerable<CodeDiagnosticDescriptor>> GetCodeDiagnosticsAsync (DocumentContext documentContext, string language, CancellationToken cancellationToken = default (CancellationToken)) { var result = new List<CodeDiagnosticDescriptor> (); foreach (var provider in providers) { if (cancellationToken.IsCancellationRequested) return Enumerable.Empty<CodeDiagnosticDescriptor> (); result.AddRange (await provider.GetCodeDiagnosticDescriptorsAsync (documentContext, language, cancellationToken).ConfigureAwait (false)); } return result; }
public override async Task<BraceMatchingResult?> GetMatchingBracesAsync (IReadonlyTextDocument editor, DocumentContext context, int offset, CancellationToken cancellationToken = default(CancellationToken)) { if (context.ParsedDocument == null) return await fallback.GetMatchingBracesAsync (editor, context, offset, cancellationToken); var analysisDocument = context.AnalysisDocument; if (analysisDocument == null) return null; var partialDoc = await CSharpCompletionTextEditorExtension.WithFrozenPartialSemanticsAsync (analysisDocument, cancellationToken).ConfigureAwait (false); var root = await partialDoc.GetSyntaxRootAsync (cancellationToken).ConfigureAwait (false); if (offset < 0 || root.Span.End <= offset) return null; var token = root.FindToken (offset); var tokenSpan = token.Span; if (offset < tokenSpan.Start || offset >= tokenSpan.End) return null; for (int i = 0; i < tokenPairs.Length / 2; i++) { var open = tokenPairs [i * 2]; var close = tokenPairs [i * 2 + 1]; SyntaxToken match; if (token.IsKind (open)) { if (TryFindMatchingToken (token, out match, open, close)) { return new BraceMatchingResult (new TextSegment (tokenSpan.Start, tokenSpan.Length), new TextSegment (match.Span.Start, match.Span.Length), true); } } else if (token.IsKind (close)) { if (TryFindMatchingToken (token, out match, open, close)) { return new BraceMatchingResult (new TextSegment (match.Span.Start, match.Span.Length), new TextSegment (tokenSpan.Start, tokenSpan.Length), false); } } } if (token.IsKind (SyntaxKind.StringLiteralToken) && token.ToString().EndsWith ("\"", StringComparison.Ordinal)) { if (token.IsVerbatimStringLiteral ()) { if (offset <= tokenSpan.Start) return new BraceMatchingResult (new TextSegment (tokenSpan.Start, 2), new TextSegment (tokenSpan.End - 1, 1), true); if (offset >= tokenSpan.End - 1) return new BraceMatchingResult (new TextSegment (tokenSpan.Start, 2), new TextSegment (tokenSpan.End - 1, 1), false); } else { if (offset <= tokenSpan.Start) return new BraceMatchingResult (new TextSegment (tokenSpan.Start, 1), new TextSegment (tokenSpan.End - 1, 1), true); if (offset >= tokenSpan.End - 1) return new BraceMatchingResult (new TextSegment (tokenSpan.Start, 1), new TextSegment (tokenSpan.End - 1, 1), false); } } if (token.IsKind (SyntaxKind.CharacterLiteralToken) && token.ToString().EndsWith ("\'", StringComparison.Ordinal)) { if (offset <= tokenSpan.Start) return new BraceMatchingResult (new TextSegment (tokenSpan.Start, 1), new TextSegment (tokenSpan.End - 1, 1), true); if (offset >= tokenSpan.End - 1) return new BraceMatchingResult (new TextSegment (tokenSpan.Start, 1), new TextSegment (tokenSpan.End - 1, 1), false); } return null; }
public override Task<TooltipItem> GetItem (TextEditor editor, DocumentContext ctx, int offset, CancellationToken token = default(CancellationToken)) { var ed = GetExtensibleTextEditor (editor); if (ed == null) return Task.FromResult<TooltipItem> (null); string errorInformation = ed.GetErrorInformationAt (offset); if (string.IsNullOrEmpty (errorInformation)) return Task.FromResult<TooltipItem> (null); return Task.FromResult (new TooltipItem (errorInformation, editor.GetLineByOffset (offset))); }
public override async Task <BraceMatchingResult?> GetMatchingBracesAsync(IReadonlyTextDocument editor, DocumentContext context, int offset, CancellationToken cancellationToken = default(CancellationToken)) { if (context.ParsedDocument == null) { return(await fallback.GetMatchingBracesAsync(editor, context, offset, cancellationToken)); } var analysisDocument = context.AnalysisDocument; if (analysisDocument == null) { return(null); } var partialDoc = analysisDocument.WithFrozenPartialSemantics(cancellationToken); var root = await partialDoc.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (offset < 0 || root.Span.End <= offset) { return(null); } var trivia = root.FindTrivia(offset).GetStructure() as DirectiveTriviaSyntax; if (trivia != null && (trivia.IsKind(SyntaxKind.RegionDirectiveTrivia) || trivia.IsKind(SyntaxKind.EndRegionDirectiveTrivia))) { var matching = trivia.GetMatchingDirective(cancellationToken); if (matching == null) { return(null); } if (trivia.IsKind(SyntaxKind.RegionDirectiveTrivia)) { return(new BraceMatchingResult( new TextSegment(trivia.Span.Start, trivia.Span.Length), new TextSegment(matching.Span.Start, matching.Span.Length), true, BraceMatchingProperties.Hidden)); } else { return(new BraceMatchingResult( new TextSegment(matching.Span.Start, matching.Span.Length), new TextSegment(trivia.Span.Start, trivia.Span.Length), false, BraceMatchingProperties.Hidden)); } } var token = root.FindToken(offset); var tokenSpan = token.Span; if (offset < tokenSpan.Start || offset >= tokenSpan.End) { return(null); } for (int i = 0; i < tokenPairs.Length / 2; i++) { var open = tokenPairs [i * 2]; var close = tokenPairs [i * 2 + 1]; SyntaxToken match; if (token.IsKind(open)) { if (TryFindMatchingToken(token, out match, open, close)) { return(new BraceMatchingResult(new TextSegment(tokenSpan.Start, tokenSpan.Length), new TextSegment(match.Span.Start, match.Span.Length), true)); } } else if (token.IsKind(close)) { if (TryFindMatchingToken(token, out match, open, close)) { return(new BraceMatchingResult(new TextSegment(match.Span.Start, match.Span.Length), new TextSegment(tokenSpan.Start, tokenSpan.Length), false)); } } } if (token.IsKind(SyntaxKind.StringLiteralToken) && token.ToString().EndsWith("\"", StringComparison.Ordinal)) { if (token.IsVerbatimStringLiteral()) { if (offset <= tokenSpan.Start) { return(new BraceMatchingResult(new TextSegment(tokenSpan.Start, 2), new TextSegment(tokenSpan.End - 1, 1), true)); } if (offset >= tokenSpan.End - 1) { return(new BraceMatchingResult(new TextSegment(tokenSpan.Start, 2), new TextSegment(tokenSpan.End - 1, 1), false)); } } else { if (offset <= tokenSpan.Start) { return(new BraceMatchingResult(new TextSegment(tokenSpan.Start, 1), new TextSegment(tokenSpan.End - 1, 1), true)); } if (offset >= tokenSpan.End - 1) { return(new BraceMatchingResult(new TextSegment(tokenSpan.Start, 1), new TextSegment(tokenSpan.End - 1, 1), false)); } } } if (token.IsKind(SyntaxKind.CharacterLiteralToken) && token.ToString().EndsWith("\'", StringComparison.Ordinal)) { if (offset <= tokenSpan.Start) { return(new BraceMatchingResult(new TextSegment(tokenSpan.Start, 1), new TextSegment(tokenSpan.End - 1, 1), true)); } if (offset >= tokenSpan.End - 1) { return(new BraceMatchingResult(new TextSegment(tokenSpan.Start, 1), new TextSegment(tokenSpan.End - 1, 1), false)); } } return(null); }
public void CheckShowCodeGenerationWindow(CommandInfo info) { info.Enabled = Editor != null && DocumentContext.GetContent <ICompletionWidget> () != null; }
protected virtual void OnTheFlyFormatImplementation(TextEditor editor, DocumentContext context, int startOffset, int length) { throw new NotSupportedException("On the fly formatting not supported"); }
async Task <DebugDataTipInfo> IDebuggerExpressionResolver.ResolveExpressionAsync(IReadonlyTextDocument editor, DocumentContext doc, int offset, CancellationToken cancellationToken) { return(await Resolver.DebuggerExpressionResolver.ResolveAsync(editor, doc, offset, cancellationToken).ConfigureAwait(false)); }
public IndexController() { _context = new DocumentContext(); _context.Database.Migrate(); }
public override bool IsValidInContext(DocumentContext context) { return(LanguageBindingService.GetBindingPerFileName(context.Name) != null); }
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 override bool IsValidInContext(DocumentContext context) { return(IsFileNameHandled(context.Name) && base.IsValidInContext(context)); }
public OCCodeGenerator(TemplateLoader templateLoader, DocumentContext context, GeneratorConfig config, DirectoryInfo outputFolder) : base(templateLoader, context, config, outputFolder) { }
public CompilationUnitDataProvider(TextEditor editor, DocumentContext documentContext) { this.editor = editor; this.DocumentContext = documentContext; }
public override bool IsValidInContext(DocumentContext context) { return(context.GetContent <CSharpCompletionTextEditorExtension> () != null); }
void EnableExtension() { enabled = true; DocumentContext.ReparseDocument(); }
public ContextActionRunner(TextEditor editor, CodeAction act) { this.editor = editor; this.act = act; documentContext = editor.DocumentContext; }
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(); }
static bool SkipContext(DocumentContext ctx) { return(ctx.IsAdHocProject || !(ctx.Project is MonoDevelop.Projects.DotNetProject)); }
public override async Task <TooltipItem> GetItem(TextEditor editor, DocumentContext ctx, int offset, CancellationToken token = default(CancellationToken)) { if (offset >= editor.Length) { return(null); } if (!DebuggingService.IsDebugging || DebuggingService.IsRunning) { return(null); } StackFrame frame = DebuggingService.CurrentFrame; if (frame == null) { return(null); } var ed = CompileErrorTooltipProvider.GetExtensibleTextEditor(editor); if (ed == null) { return(null); } string expression = null; int startOffset; if (ed.IsSomethingSelected && offset >= ed.SelectionRange.Offset && offset <= ed.SelectionRange.EndOffset) { startOffset = ed.SelectionRange.Offset; expression = ed.SelectedText; } else { var doc = ctx; if (doc == null || doc.ParsedDocument == null) { return(null); } var resolver = doc.GetContent <IDebuggerExpressionResolver> (); var data = doc.GetContent <SourceEditorView> (); if (resolver != null) { var result = await resolver.ResolveExpressionAsync(editor, doc, offset, token); expression = result.Text; startOffset = result.Span.Start; } else { int endOffset = data.GetTextEditorData().FindCurrentWordEnd(offset); startOffset = data.GetTextEditorData().FindCurrentWordStart(offset); expression = editor.GetTextAt(startOffset, endOffset - startOffset); } } if (string.IsNullOrEmpty(expression)) { return(null); } var options = DebuggingService.DebuggerSession.EvaluationOptions.Clone(); options.AllowMethodEvaluation = true; options.AllowTargetInvoke = true; var val = frame.GetExpressionValue(expression, options); if (val == null || val.IsUnknown || val.IsNotSupported) { return(null); } val.Name = expression; return(new TooltipItem(val, startOffset, expression.Length)); }
// public static void SetText (this CompletionData data, string text) // { // if (data is CompletionData) { // ((CompletionData)data).CompletionText = text; // } else if (data is IEntityCompletionData) { // ((IEntityCompletionData)data).CompletionText = text; // } else { // System.Console.WriteLine("Unknown completion data:" + data); // } // } // public static ICSharpCode.NRefactory.CSharp.SyntaxTree Parse (this ICSharpCode.NRefactory.CSharp.CSharpParser parser, IReadonlyTextDocument data) // { // return parser.Parse (new ICSharpCode.NRefactory.Editor.StringTextSource (data.Text), data.FileName); // } // public static AstNode ParseSnippet (this ICSharpCode.NRefactory.CSharp.CSharpParser parser, TextEditorData data) // { // using (var stream = new StreamReader (data.OpenStream ())) { // var result = parser.ParseExpression (stream); // if (!parser.HasErrors) // return result; // } // parser.ErrorPrinter.Reset (); // using (var stream = new StreamReader (data.OpenStream ())) { // var result = parser.ParseStatements (stream); // if (!parser.HasErrors) // return result.FirstOrDefault (); // } // parser.ErrorPrinter.Reset (); // using (var stream = data.OpenStream ()) { // return parser.Parse (stream, data.Document.FileName); // } // } internal static MonoDevelop.CSharp.Formatting.CSharpFormattingPolicy GetFormattingPolicy(this DocumentContext doc) { var policyParent = doc?.Project?.Policies; var types = MonoDevelop.Ide.DesktopService.GetMimeTypeInheritanceChain(MonoDevelop.CSharp.Formatting.CSharpFormatter.MimeType); var codePolicy = policyParent != null?policyParent.Get <MonoDevelop.CSharp.Formatting.CSharpFormattingPolicy> (types) : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy <MonoDevelop.CSharp.Formatting.CSharpFormattingPolicy> (types); return(codePolicy); }
public TypeVisitor(string javaNamespace, DocumentContext documentContext) { this.javaNamespace = javaNamespace; this.documentContext = documentContext; }
public static OptionSet GetFormattingOptions(this DocumentContext doc) { return(doc.AnalysisDocument.GetOptionsAsync().WaitAndGetResult(default(CancellationToken))); }
public override Control CreateTooltipWindow(TextEditor editor, DocumentContext ctx, TooltipItem item, int offset, Gdk.ModifierType modifierState) { return(new DebugValueWindow(editor, offset, DebuggingService.CurrentFrame, (ObjectValue)item.Item, null)); }
public static async Task <TooltipInformation> GetQuickInfoAsync(TextEditor editor, DocumentContext ctx, ISymbol symbol, CancellationToken cancellationToken = default(CancellationToken)) { var tooltipInfo = new TooltipInformation(); var model = await ctx.AnalysisDocument.GetSemanticModelAsync(); var descriptionService = ctx.RoslynWorkspace.Services.GetLanguageServices(model.Language).GetService <ISymbolDisplayService> (); var sections = await descriptionService.ToDescriptionGroupsAsync(ctx.RoslynWorkspace, model, editor.CaretOffset, new [] { symbol }.AsImmutable(), default(CancellationToken)).ConfigureAwait(false); ImmutableArray <TaggedText> parts; var sb = new StringBuilder(); var theme = editor.Options.GetEditorTheme(); if (sections.TryGetValue(SymbolDescriptionGroups.MainDescription, out parts)) { TaggedTextUtil.AppendTaggedText(sb, theme, parts); } // if generating quick info for an attribute, bind to the class instead of the constructor if (symbol.ContainingType?.IsAttribute() == true) { symbol = symbol.ContainingType; } var formatter = ctx.RoslynWorkspace.Services.GetLanguageServices(model.Language).GetService <IDocumentationCommentFormattingService> (); var documentation = symbol.GetDocumentationParts(model, editor.CaretOffset, formatter, cancellationToken); sb.Append("<span font='" + FontService.SansFontName + "' size='small'>"); if (documentation != null) { sb.AppendLine(); sb.AppendLine(); TaggedTextUtil.AppendTaggedText(sb, theme, documentation); } if (sections.TryGetValue(SymbolDescriptionGroups.AnonymousTypes, out parts)) { if (!parts.IsDefaultOrEmpty) { sb.AppendLine(); TaggedTextUtil.AppendTaggedText(sb, theme, parts); } } if (sections.TryGetValue(SymbolDescriptionGroups.AwaitableUsageText, out parts)) { if (!parts.IsDefaultOrEmpty) { sb.AppendLine(); TaggedTextUtil.AppendTaggedText(sb, theme, parts); } } if (sections.TryGetValue(SymbolDescriptionGroups.Exceptions, out parts)) { if (!parts.IsDefaultOrEmpty) { sb.AppendLine(); TaggedTextUtil.AppendTaggedText(sb, theme, parts); } } sb.Append("</span>"); tooltipInfo.SignatureMarkup = sb.ToString(); return(tooltipInfo); }
static void Format(PolicyContainer policyParent, IEnumerable <string> mimeTypeChain, TextEditor editor, DocumentContext context, int startOffset, int endOffset, bool exact, bool formatLastStatementOnly = false, OptionSet optionSet = null) { TextSpan span; if (exact) { span = new TextSpan(startOffset, endOffset - startOffset); } else { span = new TextSpan(0, endOffset); } var analysisDocument = context.AnalysisDocument; if (analysisDocument == null) { return; } using (var undo = editor.OpenUndoGroup(/*OperationType.Format*/)) { try { var syntaxTree = analysisDocument.GetSyntaxTreeAsync().WaitAndGetResult(default(CancellationToken)); var root = syntaxTree.GetRoot(); if (formatLastStatementOnly) { var token = root.FindToken(endOffset); var tokens = Microsoft.CodeAnalysis.CSharp.Utilities.FormattingRangeHelper.FindAppropriateRange(token); if (tokens.HasValue) { span = new TextSpan(tokens.Value.Item1.SpanStart, editor.CaretOffset - tokens.Value.Item1.SpanStart); } else { var parent = token.Parent; if (parent != null) { span = new TextSpan(parent.FullSpan.Start, editor.CaretOffset - parent.FullSpan.Start); } } } if (optionSet == null) { optionSet = context.GetOptionsAsync().WaitAndGetResult(default(CancellationToken)); } var rules = Formatter.GetDefaultFormattingRules(analysisDocument); var changes = Formatter.GetFormattedTextChanges(root, Roslyn.Utilities.SpecializedCollections.SingletonEnumerable(span), context.RoslynWorkspace, optionSet, rules, default(CancellationToken)); editor.ApplyTextChanges(changes.Where(c => { if (!exact) { return(true); } return(span.Contains(c.Span.Start)); })); } catch (Exception e) { LoggingService.LogError("Error in on the fly formatter", e); } } }
public TestCompletionWidget(TextEditor editor, DocumentContext document) { this.editor = editor; documentContext = document; }
public static void Format(TextEditor editor, DocumentContext context) { Format(editor, context, 0, editor.Length); }
public override bool IsValidInContext(DocumentContext context) { //can only attach if there is not already an attached BaseXmlEditorExtension return(context.GetContent <BaseXmlEditorExtension> () == null); }
public async static Task <IEnumerable <CodeRefactoringDescriptor> > GetCodeRefactoringsAsync(DocumentContext documentContext, string language, CancellationToken cancellationToken = default(CancellationToken)) { var result = new List <CodeRefactoringDescriptor> (); foreach (var provider in providers) { result.AddRange(await provider.GetCodeRefactoringDescriptorsAsync(documentContext, language, cancellationToken).ConfigureAwait(false)); } return(result); }
protected virtual Task CorrectIndentingImplementationAsync(TextEditor editor, DocumentContext context, int startLine, int endLine, CancellationToken cancellationToken) { for (int i = startLine; i <= endLine; i++) { CorrectIndentingImplementation(context.Project.Policies, editor, i); } return(Task.CompletedTask); }
public static async Task <IEnumerable <ValidCodeAction> > GetValidActionsAsync(TextEditor editor, DocumentContext doc, TextSpan span, CancellationToken cancellationToken = default(CancellationToken)) { if (editor == null) { throw new ArgumentNullException("editor"); } if (doc == null) { throw new ArgumentNullException("doc"); } var parsedDocument = doc.ParsedDocument; var actions = new List <ValidCodeAction> (); if (parsedDocument == null) { return(actions); } var model = parsedDocument.GetAst <SemanticModel> (); if (model == null) { return(actions); } var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); if (span.End > root.Span.End) { return(actions); } TextSpan tokenSegment = span; var token = root.FindToken(span.Start); if (!token.IsMissing) { tokenSegment = token.Span; } try { if (codeRefactoringCache == null) { codeRefactoringCache = (await GetCodeRefactoringsAsync(doc, MimeTypeToLanguage(editor.MimeType), cancellationToken).ConfigureAwait(false)).ToList(); } foreach (var descriptor in codeRefactoringCache) { var analysisDocument = doc.AnalysisDocument; if (cancellationToken.IsCancellationRequested || analysisDocument == null) { return(Enumerable.Empty <ValidCodeAction> ()); } try { await descriptor.GetProvider().ComputeRefactoringsAsync( new CodeRefactoringContext(analysisDocument, span, delegate(CodeAction ca) { var nrca = ca as NRefactoryCodeAction; var validSegment = tokenSegment; if (nrca != null) { validSegment = nrca.TextSpan; } actions.Add(new ValidCodeAction(ca, validSegment)); }, cancellationToken) ).ConfigureAwait(false); } catch (OperationCanceledException) { if (cancellationToken.IsCancellationRequested) { return(Enumerable.Empty <ValidCodeAction> ()); } } catch (AggregateException) { if (cancellationToken.IsCancellationRequested) { return(Enumerable.Empty <ValidCodeAction> ()); } } catch (Exception e) { LoggingService.LogError("Error while getting refactorings from " + descriptor.IdString, e); continue; } } } catch (OperationCanceledException) { if (cancellationToken.IsCancellationRequested) { return(Enumerable.Empty <ValidCodeAction> ()); } } catch (AggregateException) { if (cancellationToken.IsCancellationRequested) { return(Enumerable.Empty <ValidCodeAction> ()); } } return(actions); }
public AnalysisDocument(TextEditor editor, DocumentContext documentContext) { this.Editor = editor; this.CaretLocation = editor.CaretLocation; this.DocumentContext = documentContext; }
public DocumentQueries(DocumentContext dbContext) { _dbContext = dbContext; }