internal async void RequestPopup (Xwt.Rectangle rect) { var token = popupSrc.Token; diff = await Task.Run (async delegate { try { foreach (var op in await codeAction.GetPreviewOperationsAsync (token)) { var ac = op as ApplyChangesOperation; if (ac == null) { continue; } var changedDocument = ac.ChangedSolution.GetDocument (documentContext.AnalysisDocument.Id); changedTextDocument = TextEditorFactory.CreateNewDocument (new StringTextSource ((await changedDocument.GetTextAsync (token)).ToString ()), editor.FileName); try { var list = new List<DiffHunk> (editor.GetDiff (changedTextDocument, new DiffOptions (false, true))); if (list.Count > 0) return list; } catch (Exception e) { LoggingService.LogError ("Error while getting preview list diff.", e); } } } catch (OperationCanceledException) {} return new List<DiffHunk> (); }); if (diff.Count > 0 && !token.IsCancellationRequested) ShowPopup (rect, PopupPosition.Left); }
/// <summary> /// Initializes a new instance of the <see cref="ParserContext"/> class. /// </summary> /// <param name="source">The source.</param> /// <param name="parser">The parser.</param> /// <param name="errorSink">The error sink.</param> public ParserContext(ITextDocument source, ParserBase parser, ParserErrorSink errorSink, TagProvidersCollection providers) { Source = new TextDocumentReader(source); Parser = parser; _errorSink = errorSink; TagProviders = providers; }
public MouseClickProcessor(IWpfTextView TextView, ITextDocument Document) { this.TextView = TextView; this.Document = Document; SetupFolderSettings(); }
public IEnumerable<HunkRangeInfo> GetGitDiffFor(ITextDocument textDocument, ITextSnapshot snapshot) { string fileName = textDocument.FilePath; GitFileStatusTracker tracker = new GitFileStatusTracker(Path.GetDirectoryName(fileName)); if (!tracker.IsGit) yield break; GitFileStatus status = tracker.GetFileStatus(fileName); if (status == GitFileStatus.New || status == GitFileStatus.Added) yield break; HistogramDiff diff = new HistogramDiff(); diff.SetFallbackAlgorithm(null); string currentText = snapshot.GetText(); byte[] preamble = textDocument.Encoding.GetPreamble(); byte[] content = textDocument.Encoding.GetBytes(currentText); if (preamble.Length > 0) { byte[] completeContent = new byte[preamble.Length + content.Length]; Buffer.BlockCopy(preamble, 0, completeContent, 0, preamble.Length); Buffer.BlockCopy(content, 0, completeContent, preamble.Length, content.Length); content = completeContent; } byte[] previousContent = null; //GetPreviousRevision(tracker, fileName); RawText b = new RawText(content); RawText a = new RawText(previousContent ?? new byte[0]); EditList edits = diff.Diff(RawTextComparator.DEFAULT, a, b); foreach (Edit edit in edits) yield return new HunkRangeInfo(snapshot, edit, a, b); }
public RoslynCodeAnalysisHelper(IWpfTextView view, ITextDocument document, IVsTaskList tasks, DTE2 dte, SVsServiceProvider serviceProvider, IVsActivityLog log) { _view = view; _document = document; _text = new Adornment(); _tasks = tasks; _serviceProvider = serviceProvider; _log = log; _dispatcher = Dispatcher.CurrentDispatcher; _adornmentLayer = view.GetAdornmentLayer(RoslynCodeAnalysisFactory.LayerName); _view.ViewportHeightChanged += SetAdornmentLocation; _view.ViewportWidthChanged += SetAdornmentLocation; _text.MouseUp += (s, e) => dte.ExecuteCommand("View.ErrorList"); _timer = new Timer(750); _timer.Elapsed += (s, e) => { _timer.Stop(); System.Threading.Tasks.Task.Run(() => { _dispatcher.Invoke(new Action(() => Update(false)), DispatcherPriority.ApplicationIdle, null); }); }; _timer.Start(); }
protected internal virtual ParserResults ParseTemplateCore(ITextDocument input, CancellationToken? cancelToken) { // Construct the parser RazorParser parser = CreateParser(); Debug.Assert(parser != null); return parser.Parse(input); }
public ParserContext(ITextDocument source, ParserBase codeParser, ParserBase markupParser, ParserBase activeParser) { if (source == null) { throw new ArgumentNullException("source"); } if (codeParser == null) { throw new ArgumentNullException("codeParser"); } if (markupParser == null) { throw new ArgumentNullException("markupParser"); } if (activeParser == null) { throw new ArgumentNullException("activeParser"); } if (activeParser != codeParser && activeParser != markupParser) { throw new ArgumentException(RazorResources.ActiveParser_Must_Be_Code_Or_Markup_Parser, "activeParser"); } CaptureOwnerTask(); Source = new TextDocumentReader(source); CodeParser = codeParser; MarkupParser = markupParser; ActiveParser = activeParser; Errors = new List<RazorError>(); }
public PreviewWindowUpdateListener(IWpfTextView wpfTextView, MarkdownPackage package, ITextDocument document) { this.textView = wpfTextView; this.package = package; this.document = document; if (textView.HasAggregateFocus) UpdatePreviewWindow(false); updateHandler = (sender, args) => { UpdatePreviewWindow(async: true); }; BufferIdleEventUtil.AddBufferIdleEventListener(wpfTextView.TextBuffer, updateHandler); textView.Closed += (sender, args) => { ClearPreviewWindow(); BufferIdleEventUtil.RemoveBufferIdleEventListener(wpfTextView.TextBuffer, updateHandler); }; textView.GotAggregateFocus += (sender, args) => { var window = GetPreviewWindow(false); if (window != null) { if (window.CurrentSource == null || window.CurrentSource != this) UpdatePreviewWindow(false); } }; }
//copied from base impl in RazorTemplateEngine.ParseTemplateCore, only change is that it actually calls ParseTemplateCore protected override GeneratorResults GenerateCodeCore (ITextDocument input, string className, string rootNamespace, string sourceFileName, CancellationToken? cancelToken) { className = (className ?? Host.DefaultClassName) ?? DefaultClassName; rootNamespace = (rootNamespace ?? Host.DefaultNamespace) ?? DefaultNamespace; ParserResults results = ParseTemplateCore (input, cancelToken); // Generate code RazorCodeGenerator generator = CreateCodeGenerator(className, rootNamespace, sourceFileName); generator.DesignTimeMode = Host.DesignTimeMode; generator.Visit(results); // Post process code Host.PostProcessGeneratedCode(generator.Context); // Extract design-time mappings IDictionary<int, GeneratedCodeMapping> designTimeLineMappings = null; if (Host.DesignTimeMode) { designTimeLineMappings = generator.Context.CodeMappings; } // Collect results and return return new GeneratorResults(results, generator.Context.CompileUnit, designTimeLineMappings); }
public InformationBarMargin(IWpfTextView textView, ITextDocument document, IEditorOperations editorOperations, ITextUndoHistory undoHistory, DTE dte) { _textView = textView; _document = document; _operations = editorOperations; _undoHistory = undoHistory; _dte = dte; _informationBarControl = new InformationBarControl(); _informationBarControl.Hide.Click += Hide; _informationBarControl.DontShowAgain.Click += DontShowAgain; var format = new Action(() => this.FormatDocument()); _informationBarControl.Tabify.Click += (s, e) => this.Dispatcher.Invoke(format); this.Height = 0; this.Content = _informationBarControl; this.Name = MarginName; document.FileActionOccurred += FileActionOccurred; textView.Closed += TextViewClosed; // Delay the initial check until the view gets focus textView.GotAggregateFocus += GotAggregateFocus; this._tabDirectiveParser = new TabDirectiveParser(textView, document, dte); this._fileHeuristics = new FileHeuristics(textView, document, dte); var fix = new Action(() => this.FixFile()); this._tabDirectiveParser.Change += (s, e) => this.Dispatcher.Invoke(fix); }
public EditorCompilerInvoker(ITextDocument doc, CompilerRunnerBase compilerRunner) { Document = doc; CompilerRunner = compilerRunner; Document.FileActionOccurred += Document_FileActionOccurred; }
public RemoveWhitespaceOnSave(IVsTextView textViewAdapter, IWpfTextView view, DTE2 dte, ITextDocument document) { textViewAdapter.AddCommandFilter(this, out _nextCommandTarget); _view = view; _dte = dte; _document = document; }
public PreviewWindowUpdateListener(IWpfTextView wpfTextView, MarkdownPackage package, ITextDocument document) { this.textView = wpfTextView; this.package = package; this.document = document; EventHandler updateHandler = (sender, args) => UDNDocRunningTableMonitor.CurrentUDNDocView.ParsingResultsCache.AsyncForceReparse(); BufferIdleEventUtil.AddBufferIdleEventListener(wpfTextView.TextBuffer, updateHandler); document.FileActionOccurred += (sender, args) => UDNDocRunningTableMonitor.CurrentUDNDocView.ParsingResultsCache.AsyncForceReparse(); textView.Closed += (sender, args) => { ClearPreviewWindow(); BufferIdleEventUtil.RemoveBufferIdleEventListener(wpfTextView.TextBuffer, updateHandler); }; //On updating the publish flags re-run the preview package.PublishFlags.CollectionChanged += (sender, args) => UDNDocRunningTableMonitor.CurrentUDNDocView.ParsingResultsCache.AsyncForceReparse(); DoxygenHelper.TrackedFilesChanged += () => UDNDocRunningTableMonitor.CurrentUDNDocView.ParsingResultsCache.AsyncForceReparse(); Templates.TemplatesChanged += () => UpdatePreviewWindow(UDNDocRunningTableMonitor.CurrentUDNDocView.ParsingResultsCache.Results); UDNDocRunningTableMonitor.CurrentOutputIsChanged += UpdatePreviewWindow; }
public ErrorHighlighter(IWpfTextView view, ITextDocument document, IVsTaskList tasks, DTE2 dte) { _view = view; _document = document; _text = new Adornment(); _tasks = tasks; _dispatcher = Dispatcher.CurrentDispatcher; _adornmentLayer = view.GetAdornmentLayer(ErrorHighlighterFactory.LayerName); _view.ViewportHeightChanged += SetAdornmentLocation; _view.ViewportWidthChanged += SetAdornmentLocation; _text.MouseUp += (s, e) => { dte.ExecuteCommand("View.ErrorList"); }; _timer = new Timer(750); _timer.Elapsed += (s, e) => { _timer.Stop(); Task.Run(() => { _dispatcher.Invoke(new Action(() => { Update(false); }), DispatcherPriority.ApplicationIdle, null); }); }; _timer.Start(); }
/// <summary> /// Load the ruleset file according to the document file path. /// </summary> /// <param name="document">The specified document file.</param> private void LoadRuleset(ITextDocument document) { try { for (string path = Path.GetDirectoryName(document.FilePath); path != null; path = Path.GetDirectoryName(path)) { string[] rulesetFiles = Directory.GetFiles(path, "*.ruleset"); if (rulesetFiles.Length == 1) { this.ruleset = DirectiveRuleset.LoadFromRulesetFile(rulesetFiles[0]); this.RulesetFilePath = Path.GetFullPath(rulesetFiles[0]); this.NoRulesetFileReason = null; } else if (rulesetFiles.Length > 1) { this.RulesetFilePath = null; this.NoRulesetFileReason = string.Format("Folder \"{0}\" contains more than one \"*.ruleset\" files", path); } if (rulesetFiles.Length > 0) break; } if (this.ruleset == null) this.NoRulesetFileReason = "No \"*.ruleset\" file was found in the directory hierarchy"; } catch (Exception ex) { this.RulesetFilePath = null; this.NoRulesetFileReason = ex.ToString(); } }
public SourceDocument(IEditorController controller, ITextDocument document, Project.IProject proj) { _controller = controller; _document = document; _project = proj; if(_project != null) _changeTracker = new DocChangeTracker(this, _project.Index); }
public TextViewDocument(ITextDocument document, ICaret caret, IClassifier classifier, IClassificationStyler classificationStyler) { _document = document; _classifier = classifier; _classificationStyler = classificationStyler; Buffer.Changed += OnBufferChange; Caret = caret; }
public override ParserContext CreateParserContext( ITextDocument input, ParserBase codeParser, ParserBase markupParser, ErrorSink errorSink) { return base.CreateParserContext(input, codeParser, markupParser, errorSink); }
internal SettingsManager(IWpfTextView view, ITextDocument document, ErrorListProvider messageList) { _view = view; _messageList = messageList; _message = null; LoadSettings(document.FilePath); }
public TextViewDocument(ITextDocument document, ICaret caret, IClassifier classifier, IClassificationStyler classificationStyler) { _document = document; _classifier = classifier; _classificationStyler = classificationStyler; _classificationStyler.Changed += (Sender, Args) => RemoveCachedLinesFrom(0); Buffer.Changed += OnBufferChange; Caret = caret; }
private void UninitBuffer(ITextBuffer subjectBuffer) { if (_document != null) { _document.EncodingChanged -= EncodingChanged; _document = null; } subjectBuffer.Properties.RemoveProperty(typeof(IProjectEntry)); subjectBuffer.Properties.RemoveProperty(typeof(BufferParser)); subjectBuffer.ChangedLowPriority -= BufferChangedLowPriority; }
public TabDirectiveParser(IWpfTextView textView, ITextDocument document, DTE dte) { this._document = document; this._textView = textView; this._dte = dte; if (this.SetDirectiveFile()) this.SetWatcher(); }
public PreviewWindowBackgroundParser(ITextBuffer textBuffer, TaskScheduler taskScheduler, ITextDocumentFactoryService textDocumentFactoryService) : base(textBuffer, taskScheduler, textDocumentFactoryService) { ReparseDelay = TimeSpan.FromMilliseconds(1000); if (!textDocumentFactoryService.TryGetTextDocument(textBuffer, out document)) { document = null; } markdownTransform.DocumentToTransformPath = document == null ? null : document.FilePath; }
public Plugin(IWpfTextView view, ITextDocument document, DTE dte) { this.view = view; this.dte = dte; document.FileActionOccurred += FileActionOccurred; view.GotAggregateFocus += GotAggregateFocus; LoadSettings(document.FilePath); }
internal InitialCleanup(ITextDocument textDocument, _DTE ide, FileConfiguration settings) { _doc = ide.Documents.OfType<Document>() .FirstOrDefault(x => x.FullName == textDocument.FilePath); if (_doc != null) _textDoc = (TextDocument) _doc.Object("TextDocument"); _ide = ide; _settings = settings; _eol = settings.EndOfLine(); }
public void UnregisterTextDocument(ITextDocument document) { SendUnregisterFileRequest(document.FilePath); TextDocumentEventHandlers handlers; if (_documents.TryRemove(document, out handlers)) { document.TextBuffer.ChangedLowPriority -= handlers.ChangedHandler; document.FileActionOccurred -= handlers.FileActionOccurred; TextDocumentOnClosed(document, new EventArgs()); } }
public FileNameMonitor(ITextDocument document) { if (document == null) return; _document = document; FileName = _document.FilePath; _document.FileActionOccurred += FileChanged; }
public IEnumerable<HunkRangeInfo> GetGitDiffFor(ITextDocument textDocument, ITextSnapshot snapshot) { var content = GetCompleteContent(textDocument, snapshot); if (content == null) yield break; var filename = textDocument.FilePath; var discoveredPath = Repository.Discover(Path.GetFullPath(filename)); if (!Repository.IsValid(discoveredPath)) yield break; using (var repo = new Repository(discoveredPath)) { var retrieveStatus = repo.Index.RetrieveStatus(filename); if (retrieveStatus == FileStatus.Untracked || retrieveStatus == FileStatus.Added) yield break; content = AdaptCrlf(repo, content, textDocument); using (var currentContent = new MemoryStream(content)) { var newBlob = repo.ObjectDatabase.CreateBlob(currentContent); var directoryInfo = new DirectoryInfo(discoveredPath).Parent; if (directoryInfo == null) yield break; var relativeFilepath = filename.Replace(directoryInfo.FullName + "\\", string.Empty); // Determine 'from' and 'to' trees. var currentBranch = repo.Head.Name; var baseCommitEntry = repo.Config.Get<string>(string.Format("branch.{0}.diffmarginbase", currentBranch)); Tree tree = null; if (baseCommitEntry != null) { var baseCommit = repo.Lookup<Commit>(baseCommitEntry.Value); if (baseCommit != null) { // Found a merge base to diff from. tree = baseCommit.Tree; } } tree = tree ?? repo.Head.Tip.Tree; var from = TreeDefinition.From(tree); var treeDefinition = from.Add(relativeFilepath, newBlob, Mode.NonExecutableFile); var to = repo.ObjectDatabase.CreateTree(treeDefinition); var treeChanges = repo.Diff.Compare(tree, to, compareOptions: new CompareOptions { ContextLines = ContextLines, InterhunkLines = 0 }); var gitDiffParser = new GitDiffParser(treeChanges.Patch, ContextLines); var hunkRangeInfos = gitDiffParser.Parse(); foreach (var hunkRangeInfo in hunkRangeInfos) { yield return hunkRangeInfo; } } } }
public void StopMonitoring() { foreach (var buffer in _buffers) { buffer.ChangedLowPriority -= BufferChangedLowPriority; buffer.Properties.RemoveProperty(typeof(BufferParser)); if (_document != null) { _document.EncodingChanged -= EncodingChanged; _document = null; } } _timer.Dispose(); }
public virtual ParserContext CreateParserContext(ITextDocument input, ParserBase codeParser, ParserBase markupParser, ErrorSink errorSink) { return new ParserContext(input, codeParser, markupParser, SelectActiveParser(codeParser, markupParser), errorSink); }
static string GetSearchResultItemText(SearchResult result) { ITextDocument document = TextFileProvider.Instance.GetTextEditorData(result.FileName); return(document.GetTextAt(result.Offset, result.Length)); }
public ICompilationNotifier GetCompilationNotifier(ITextDocument doc) { return(doc.TextBuffer.Properties.GetOrCreateSingletonProperty <ErrorReportingCompilerInvoker>( () => new ErrorReportingCompilerInvoker(doc, new NodeCompilerRunner(doc.TextBuffer.ContentType)) )); }
protected CompilingMarginBase(IMarginSettings settings, ITextDocument document) : base(settings, document) { Notifier = Mef.GetImport <ICompilationNotifierProvider>(Document.TextBuffer.ContentType).GetCompilationNotifier(document); Notifier.CompilationReady += (s, e) => UpdateMargin(e.CompilerResult); }
private void UpdateWordAdornments(object threadContext) { if (!Enabled) { return; } Enabled = false; SnapshotPoint currentRequest = RequestedPoint; List <SnapshotSpan> wordSpans = new List <SnapshotSpan>(); // Find all words in the buffer like the one the caret is on TextExtent word = TextStructureNavigator.GetExtentOfWord(currentRequest); bool foundWord = true; // If we've selected something not worth highlighting, we might have // missed a "word" by a little bit if (!WordExtentIsValid(currentRequest, word)) { // Before we retry, make sure it is worthwhile if (word.Span.Start != currentRequest || currentRequest == currentRequest.GetContainingLine().Start || char.IsWhiteSpace((currentRequest - 1).GetChar())) { foundWord = false; } else { // Try again, one character previous. If the caret is at the end of a word, then // this will pick up the word we are at the end of. word = TextStructureNavigator.GetExtentOfWord(currentRequest - 1); // If we still aren't valid the second time around, we're done if (!WordExtentIsValid(currentRequest, word)) { foundWord = false; } } } if (!foundWord) { // If we couldn't find a word, just clear out the existing markers SynchronousUpdate(currentRequest, new NormalizedSnapshotSpanCollection(), null); return; } SnapshotSpan currentWord = word.Span; // If this is the same word we currently have, we're done (e.g. caret moved within a word). if (CurrentWord.HasValue && currentWord == CurrentWord) { return; } /* Find spans using simple text search.... * FindData findData = new FindData(currentWord.GetText(), currentWord.Snapshot); * findData.FindOptions = FindOptions.WholeWord | FindOptions.MatchCase; * wordSpans.AddRange(TextSearchService.FindAll(findData)); */ // Verify current word is a grammar symbol. // Now, check for valid classification type. string classification = null; ClassificationSpan[] c1 = _aggregator.GetClassificationSpans(currentWord).ToArray(); foreach (ClassificationSpan cl in c1) { classification = cl.ClassificationType.Classification.ToLower(); if (classification == AntlrVSIX.Constants.ClassificationNameTerminal) { break; } else if (classification == AntlrVSIX.Constants.ClassificationNameNonterminal) { break; } } if (classification == null) { return; } SnapshotSpan span = currentWord; ITextView view = this.View; // First, find out what this view is, and what the file is. ITextBuffer buffer = view.TextBuffer; ITextDocument doc = buffer.GetTextDocument(); string path = doc.FilePath; List <IToken> where = new List <IToken>(); List <ParserDetails> where_details = new List <ParserDetails>(); IToken token = null; foreach (var kvp in ParserDetails._per_file_parser_details) { string file_name = kvp.Key; ParserDetails details = kvp.Value; if (classification == AntlrVSIX.Constants.ClassificationNameNonterminal) { var it = details._ant_nonterminals.Where( (t) => t.Text == span.GetText()); where.AddRange(it); foreach (var i in it) { where_details.Add(details); } } else if (classification == AntlrVSIX.Constants.ClassificationNameTerminal) { var it = details._ant_terminals.Where( (t) => t.Text == span.GetText()); where.AddRange(it); foreach (var i in it) { where_details.Add(details); } } else if (classification == AntlrVSIX.Constants.ClassificationNameLiteral) { var it = details._ant_literals.Where( (t) => t.Text == span.GetText()); where.AddRange(it); foreach (var i in it) { where_details.Add(details); } } } if (!where.Any()) { return; } // Populate the Antlr find results model/window with file/line/col info // for each occurrence. var results = new List <Entry>(); for (int i = 0; i < where.Count; ++i) { IToken x = where[i]; ParserDetails y = where_details[i]; var w = new Entry() { FileName = y.full_file_name, LineNumber = x.Line, ColumnNumber = x.Column, Token = x }; results.Add(w); } // Now, for all entries which are in this buffer, highlight. //wordSpans.Add(currentWord); for (int i = 0; i < results.Count; ++i) { var w = results[i]; if (w.FileName == path) { // Create new span in the appropriate view. ITextSnapshot cc = buffer.CurrentSnapshot; SnapshotSpan ss = new SnapshotSpan(cc, w.Token.StartIndex, 1 + w.Token.StopIndex - w.Token.StartIndex); SnapshotPoint sp = ss.Start; wordSpans.Add(ss); } } // If we are still up-to-date (another change hasn't happened yet), do a real update if (currentRequest == RequestedPoint) { SynchronousUpdate(currentRequest, new NormalizedSnapshotSpanCollection(wordSpans), currentWord); } // Call up the rename dialog box. In another thread because // of "The calling thread must be STA, because many UI components require this." // error. Application.Current.Dispatcher.Invoke((Action) delegate { RenameDialogBox inputDialog = new RenameDialogBox(currentWord.GetText()); if (inputDialog.ShowDialog() == true) { results.Reverse(); var new_name = inputDialog.Answer; // Replace all occurrences of symbol, working backwards. foreach (Entry e in results) { string file_name = e.FileName; var pd = ParserDetails._per_file_parser_details[file_name]; IVsTextView vstv = IVsTextViewExtensions.GetIVsTextView(file_name); IWpfTextView wpftv = vstv.GetIWpfTextView(); if (wpftv == null) { // File has not been opened before! Open file in editor. IVsTextViewExtensions.ShowFrame(file_name); vstv = IVsTextViewExtensions.GetIVsTextView(file_name); wpftv = vstv.GetIWpfTextView(); } ITextBuffer tb = wpftv.TextBuffer; ITextSnapshot cc = tb.CurrentSnapshot; SnapshotSpan ss = new SnapshotSpan(cc, e.Token.StartIndex, 1 + e.Token.StopIndex - e.Token.StartIndex); SnapshotPoint sp = ss.Start; tb.Replace(ss, new_name); } // Reparse everything. foreach (string f in results.Select((e) => e.FileName).Distinct()) { ParserDetails foo = new ParserDetails(); ParserDetails._per_file_parser_details[f] = foo; IVsTextView vstv = IVsTextViewExtensions.GetIVsTextView(f); IWpfTextView wpftv = vstv.GetIWpfTextView(); if (wpftv == null) { continue; } ITextBuffer tb = wpftv.TextBuffer; foo.Parse(tb.GetBufferText(), f); } } }); }
public GoToDefinitionInterceptor(IEnumerable <IReferenceSourceProvider> references, IServiceProvider sp, IVsTextView adapter, IWpfTextView textView, ITextDocument doc) : base(adapter, textView, VSConstants.VSStd97CmdID.GotoDefn) { this.references = references; dte = (DTE)sp.GetService(typeof(DTE)); this.doc = doc; }
protected override void ReParseImpl() { Stopwatch stopwatch = Stopwatch.StartNew(); ITextSnapshot snapshot = TextBuffer.CurrentSnapshot; try { ITextDocument textDocument = TextDocument; string fileName = textDocument != null ? textDocument.FilePath : null; Document document = snapshot.GetOpenDocumentInCurrentContextWithChanges(); SourceTextContainer textContainer = document != null?document.GetTextAsync().Result.Container : null; Project project = document != null ? document.Project : null; Solution solution = project.Solution; List <ITagSpan <IInheritanceTag> > tags = new List <ITagSpan <IInheritanceTag> >(); if (document != null && !string.IsNullOrEmpty(fileName)) { SyntaxTree syntaxTree = document.GetSyntaxTreeAsync().Result; SyntaxNode syntaxRoot = syntaxTree.GetRoot(); SemanticModel semanticModel = document.GetSemanticModelAsync().Result; Compilation compilation = semanticModel.Compilation; IDictionary <ISymbol, ISet <ISymbol> > interfaceImplementations = new Dictionary <ISymbol, ISet <ISymbol> >(); List <CSharpSyntaxNode> allMembers = new List <CSharpSyntaxNode>(); IEnumerable <BaseTypeDeclarationSyntax> typeNodes = syntaxRoot.DescendantNodes().OfType <BaseTypeDeclarationSyntax>(); foreach (var typeNode in typeNodes) { ISymbol symbol = semanticModel.GetDeclaredSymbol(typeNode); if (symbol == null) { MarkDirty(true); return; } INamedTypeSymbol typeSymbol = symbol as INamedTypeSymbol; if (typeSymbol == null) { continue; } // get implemented interface symbols foreach (INamedTypeSymbol namedTypeSymbol in typeSymbol.AllInterfaces) { foreach (ISymbol member in namedTypeSymbol.GetMembers()) { ISymbol implementation = typeSymbol.FindImplementationForInterfaceMember(member); if (implementation == null || !(implementation.ContainingSymbol.Equals(typeSymbol))) { continue; } ISet <ISymbol> symbols; if (!interfaceImplementations.TryGetValue(implementation, out symbols)) { symbols = new HashSet <ISymbol>(); interfaceImplementations[implementation] = symbols; } symbols.Add(member); } } TypeDeclarationSyntax typeDeclarationSyntax = typeNode as TypeDeclarationSyntax; if (typeDeclarationSyntax != null) { allMembers.AddRange(typeDeclarationSyntax.Members); } if (typeSymbol.IsSealed) { continue; } // types which implement or derive from this type ISet <ITypeSymbol> derivedTypes = new HashSet <ITypeSymbol>(); derivedTypes.UnionWith(FindDerivedClassesAsync.Value(typeSymbol, solution, null, CancellationToken.None).Result); derivedTypes.UnionWith(FindDerivedInterfacesAsync.Value(typeSymbol, solution, null, CancellationToken.None).Result); derivedTypes.UnionWith(FindImplementingTypesAsync.Value(typeSymbol, solution, null, CancellationToken.None).Result); if (derivedTypes.Count == 0) { continue; } StringBuilder builder = new StringBuilder(); string elementKindDisplayName = "types"; builder.AppendLine("Derived " + elementKindDisplayName + ":"); foreach (var derived in derivedTypes) { builder.AppendLine(" " + derived.ToString()); } SyntaxToken identifier = typeNode.Accept(IdentifierSyntaxVisitor.Instance); SnapshotSpan span = new SnapshotSpan(snapshot, new Span(identifier.SpanStart, identifier.Span.Length)); InheritanceGlyph tag = typeSymbol.TypeKind == TypeKind.Interface ? InheritanceGlyph.HasImplementations : InheritanceGlyph.Overridden; var targets = derivedTypes.Select(i => new TypeTarget(textContainer, i, solution)); tags.Add(new TagSpan <IInheritanceTag>(span, _tagFactory.CreateTag(tag, builder.ToString().TrimEnd(), targets))); } foreach (var eventFieldDeclarationSyntax in allMembers.OfType <EventFieldDeclarationSyntax>().ToArray()) { allMembers.AddRange(eventFieldDeclarationSyntax.Declaration.Variables); } foreach (CSharpSyntaxNode memberNode in allMembers) { if (!(memberNode is MethodDeclarationSyntax) && !(memberNode is PropertyDeclarationSyntax) && !(memberNode is EventDeclarationSyntax) && !(memberNode is VariableDeclaratorSyntax)) { continue; } ISymbol symbol = semanticModel.GetDeclaredSymbol(memberNode); if (symbol == null) { MarkDirty(true); return; } // members which this member implements ISet <ISymbol> implementedMethods = new HashSet <ISymbol>(); if (!interfaceImplementations.TryGetValue(symbol, out implementedMethods)) { implementedMethods = new HashSet <ISymbol>(); } ISet <ISymbol> overriddenMethods = new HashSet <ISymbol>(); IMethodSymbol methodSymbol = symbol as IMethodSymbol; if (methodSymbol != null) { // methods which this method overrides for (IMethodSymbol current = methodSymbol.OverriddenMethod; current != null; current = current.OverriddenMethod) { overriddenMethods.Add(current); } } else { IPropertySymbol propertySymbol = symbol as IPropertySymbol; if (propertySymbol != null) { // properties which this property overrides for (IPropertySymbol current = propertySymbol.OverriddenProperty; current != null; current = current.OverriddenProperty) { overriddenMethods.Add(current); } } else { IEventSymbol eventSymbol = symbol as IEventSymbol; if (eventSymbol != null) { // events which this event overrides for (IEventSymbol current = eventSymbol.OverriddenEvent; current != null; current = current.OverriddenEvent) { overriddenMethods.Add(current); } } } } ISet <ISymbol> implementingMethods = new HashSet <ISymbol>(SymbolFinder.FindImplementationsAsync(symbol, solution).Result); ISet <ISymbol> overridingMethods = new HashSet <ISymbol>(SymbolFinder.FindOverridesAsync(symbol, solution).Result); if (implementingMethods.Count == 0 && implementedMethods.Count == 0 && overriddenMethods.Count == 0 && overridingMethods.Count == 0) { continue; } StringBuilder builder = new StringBuilder(); string elementKindDisplayName = symbol is IPropertySymbol ? "properties" : symbol is IEventSymbol ? "events" : "methods"; if (implementedMethods.Count > 0) { builder.AppendLine("Implemented " + elementKindDisplayName + ":"); foreach (var methodId in implementedMethods) { builder.AppendLine(" " + methodId.ToString()); } } if (overriddenMethods.Count > 0) { builder.AppendLine("Overridden " + elementKindDisplayName + ":"); foreach (var methodId in overriddenMethods) { builder.AppendLine(" " + methodId.ToString()); } } if (implementingMethods.Count > 0) { builder.AppendLine("Implementing " + elementKindDisplayName + " in derived types:"); foreach (var methodId in implementingMethods) { builder.AppendLine(" " + methodId.ToString()); } } if (overridingMethods.Count > 0) { builder.AppendLine("Overriding " + elementKindDisplayName + " in derived types:"); foreach (var methodId in overridingMethods) { builder.AppendLine(" " + methodId.ToString()); } } SyntaxToken identifier = memberNode.Accept(IdentifierSyntaxVisitor.Instance); SnapshotSpan span = new SnapshotSpan(snapshot, new Span(identifier.SpanStart, identifier.Span.Length)); InheritanceGlyph tag; if (implementedMethods.Count > 0) { if (overridingMethods.Count > 0) { tag = InheritanceGlyph.ImplementsAndOverridden; } else if (implementingMethods.Count > 0) { tag = InheritanceGlyph.ImplementsAndHasImplementations; } else { tag = InheritanceGlyph.Implements; } } else if (implementingMethods.Count > 0) { tag = InheritanceGlyph.HasImplementations; } else if (overriddenMethods.Count > 0) { if (overridingMethods.Count > 0) { tag = InheritanceGlyph.OverridesAndOverridden; } else { tag = InheritanceGlyph.Overrides; } } else { tag = InheritanceGlyph.Overridden; } List <ISymbol> members = new List <ISymbol>(); members.AddRange(implementedMethods); members.AddRange(overriddenMethods); members.AddRange(implementingMethods); members.AddRange(overridingMethods); var targets = members.Select(i => new MemberTarget(textContainer, i, project, solution)); tags.Add(new TagSpan <IInheritanceTag>(span, _tagFactory.CreateTag(tag, builder.ToString().TrimEnd(), targets))); } } InheritanceParseResultEventArgs result = new InheritanceParseResultEventArgs(snapshot, stopwatch.Elapsed, tags); OnParseComplete(result); } catch (InvalidOperationException) { base.MarkDirty(true); throw; } }
public CoffeeScriptMargin(string contentType, string source, bool showMargin, ITextDocument document) : base(source, MarginName, contentType, showMargin, document) { _compiler = new CoffeeScriptCompiler(Dispatcher); _compiler.Completed += _compiler_Completed; //+= (s, e) => { OnCompilationDone(e.Result, e.State); }; }
public static void ToHtml(ITextDocument doc) { // Takes a RichEditBox control and returns a // simple HTML-formatted version of its contents string strHTML, strFont, strColour, strBold, strFntName; float shtSize; int lngOriginalStart, lngOriginalLength; int intCount = 0; ITextRange tr = doc.GetRange(0, 9999999); // If nothing in the box, exit if (tr.Length == 0) { //App.Current.Exit(); } // Store original selections, then select first character lngOriginalStart = 0; lngOriginalLength = tr.Length; tr.SetRange(0, 1); // Add HTML header strHTML = "<html>"; // Set up initial parameters strColour = tr.CharacterFormat.ForegroundColor.ToString(); strFont = tr.CharacterFormat.FontStyle.ToString(); shtSize = tr.CharacterFormat.Size; strBold = tr.CharacterFormat.Bold.ToString(); strFntName = tr.CharacterFormat.Name; Debug.WriteLine("Colour: " + strColour); // Include first 'style' parameters in the HTML strHTML += "<span style=\"font-family:" + strFntName + "; font-size: " + shtSize + "pt; color: #" + strColour.Substring(3) + "\">"; // Include bold tag, if required if (strBold.ToLower() == "on") { strHTML += "<b>"; } // Include italic tag, if required if (strFont.ToLower() == "italic") { strHTML += "<i>"; } // Finally, add our first character strHTML += tr.Character; // Loop around all remaining characters for (intCount = 2; intCount < lngOriginalLength; intCount++) { // Select current character tr.SetRange(intCount - 1, intCount + 1); // If this is a line break, add HTML tag if (tr.Character == Convert.ToChar(13)) { strHTML += "<br />"; } // ' Check/implement any changes in style if (tr.CharacterFormat.ForegroundColor.ToString() != strColour || tr.CharacterFormat.Name != strFntName || tr.CharacterFormat.Size != shtSize) { strHTML += "</span><span style=\"font-family: " + tr.CharacterFormat.Name + "; font size: " + tr.CharacterFormat.Size + "pt; color: #" + tr.CharacterFormat.ForegroundColor.ToString().Substring(3) + "\">"; } // Check for bold changes if (tr.CharacterFormat.Bold.ToString().ToLower() != strBold.ToLower()) { if (tr.CharacterFormat.Bold.ToString().ToLower() != "on") { strHTML += "</b>"; } else { strHTML += "<b>"; } } // Check for italic changes if (tr.CharacterFormat.FontStyle.ToString().ToLower() != strFont.ToLower()) { if (tr.CharacterFormat.FontStyle.ToString().ToLower() != "italic") { strHTML += "</i>"; } else { strHTML += "<i>"; } } // ' Add the actual character strHTML += tr.Character; // ' Update variables with current style strColour = tr.CharacterFormat.ForegroundColor.ToString(); strFont = tr.CharacterFormat.FontStyle.ToString(); shtSize = tr.CharacterFormat.Size; strFntName = tr.CharacterFormat.Name; strBold = tr.CharacterFormat.Bold.ToString(); } // Close off any open bold/italic tags if (strBold == "on") { strHTML += ""; } if (strFont.ToLower() == "italic") { strHTML += ""; } // Terminate outstanding HTML tags strHTML += "</span></html>"; //' Restore original RichTextBox selection tr.SetRange(lngOriginalStart, lngOriginalLength); doc.SetText(TextSetOptions.FormatRtf, strHTML); }
public ErrorReportingCompilerInvoker(ITextDocument doc, CompilerRunnerBase compilerRunner) : base(doc, compilerRunner) { _provider = new ErrorListProvider(EditorExtensionsPackage.Instance); }
public DirectiveHtmlTokenizer(ITextDocument source) : base(source) { }
public TextDocumentReader(ITextDocument source) { Document = source; }
public static void Replace(this ITextDocument document, ISegment segment, string text) { document.Replace(segment.Offset, segment.Length, text); }
public static string GetText(this ITextDocument document, ISegment segment) { return(document.GetText(segment.Offset, segment.Length)); }
public ICompilationNotifier GetCompilationNotifier(ITextDocument doc) { return(new TypeScriptCompilationNotifier(doc)); }
public HtmlTokenizer(ITextDocument source) : base(source) { base.CurrentState = StartState; }
protected DirectMarginBase(IMarginSettings settings, ITextDocument document) : base(settings, document) { Document.FileActionOccurred += Document_FileActionOccurred; }
internal override object CreateTokenizer(ITextDocument source) { return(new DirectiveHtmlTokenizer(source)); }
/// <summary> /// Constructor /// </summary> /// <param name="source">The source document</param> public CSharpRazorTokenizer(ITextDocument source) : base(source) { }
public override CSharpTokenizer CreateTokenizer(ITextDocument source) { return(new CSharpTokenizer(source)); }
public ICompilationNotifier GetCompilationNotifier(ITextDocument doc) { return(doc.TextBuffer.Properties.GetOrCreateSingletonProperty <EditorCompilerInvoker>( () => new EditorCompilerInvoker(doc, new MarkdownCompilerRunner(doc.TextBuffer.ContentType, doc)) )); }
protected MarginBase(string source, string name, string contentType, bool showMargin, ITextDocument document) { Document = document; _marginName = name; _settingsKey = _marginName + "_width"; _showMargin = showMargin; _dispatcher = Dispatcher.CurrentDispatcher; _provider = new ErrorListProvider(EditorExtensionsPackage.Instance); Document.FileActionOccurred += Document_FileActionOccurred; if (showMargin) { _dispatcher.BeginInvoke( new Action(() => Initialize(contentType, source)), DispatcherPriority.ApplicationIdle, null); } }
protected abstract Tokenizer <TSymbol, TSymbolType> CreateTokenizer(ITextDocument source);
public HtmlTokenizer(ITextDocument source) : base(source) { CurrentState = Data; }
public virtual ParserResults Parse(ITextDocument input) { return(ParseCore(input)); }
protected override Tokenizer <HtmlSymbol, HtmlSymbolType> CreateTokenizer(ITextDocument source) { return(new HtmlTokenizer(source)); }
public static void TrimTrailingWhiteSpace(this ITextDocument document, ISegment line) { document.Replace(line, document.GetText(line).TrimEnd()); }
public TestableTextBufferIssueTracker(DTE dte, TaggerProvider provider, ITextDocument document, IEnumerable <AnalysisLanguage> detectedLanguages, IIssuesFilter issuesFilter, ISonarErrorListDataSource sonarErrorDataSource, IAnalysisIssueVisualizationConverter converter, IVsSolution5 vsSolution, ILogger logger) : base(dte, provider, document, detectedLanguages, issuesFilter, sonarErrorDataSource, converter, vsSolution, logger) { }
/// <inheritdoc/> protected override void ReParseImpl() { Stopwatch stopwatch = Stopwatch.StartNew(); ITextSnapshot snapshot = TextBuffer.CurrentSnapshot; try { ITextDocument textDocument = TextDocument; string fileName = textDocument != null ? textDocument.FilePath : null; IDECompilerHost host = new IDECompilerHost(); IProject project = null; ILangService languageService; LangService_GetInstance(out languageService); if (languageService != null) { ICSharpTextBuffer csharpBuffer = languageService.FindTextBuffer(fileName); if (csharpBuffer != null) { project = csharpBuffer.Project; } } List <ITagSpan <IInheritanceTag> > tags = new List <ITagSpan <IInheritanceTag> >(); if (host != null && project != null && !string.IsNullOrEmpty(fileName)) { Compilation compilation = host.CreateCompiler(project).GetCompilation(); SourceFile sourceFile; if (!compilation.SourceFiles.TryGetValue(new FileName(fileName), out sourceFile)) { InheritanceParseResultEventArgs errorResult = new InheritanceParseResultEventArgs(snapshot, stopwatch.Elapsed, tags); OnParseComplete(errorResult); return; } ParseTree parseTree = sourceFile.GetParseTree(); SpecializedMatchingMemberCollector collector = new SpecializedMatchingMemberCollector(host.Compilers.Select(i => i.GetCompilation()), false); IEnumerable <ParseTreeNode> nodes = SelectTypes(parseTree); foreach (var node in nodes) { CSharpType type = null; type = compilation.GetTypeFromTypeDeclaration(node); if (type == null) { MarkDirty(true); return; } if (type.IsSealed) { continue; } // types which implement or derive from this type ISet <CSharpType> derivedClasses = collector.GetDerivedTypes(type.SymbolicIdentifier); if (derivedClasses.Count == 0) { continue; } StringBuilder builder = new StringBuilder(); string elementKindDisplayName = "types"; builder.AppendLine("Derived " + elementKindDisplayName + ":"); foreach (var derived in derivedClasses) { builder.AppendLine(" " + derived.GetFullTypeName()); } int nameIndex = node.Token; Token token = parseTree.LexData.Tokens[nameIndex]; ITextSnapshotLine line = snapshot.GetLineFromLineNumber(token.StartPosition.Line); SnapshotSpan span = new SnapshotSpan(snapshot, new Span(line.Start + token.StartPosition.Character, token.EndPosition.Character - token.StartPosition.Character)); InheritanceGlyph tag = type.IsInterface ? InheritanceGlyph.HasImplementations : InheritanceGlyph.Overridden; var targets = derivedClasses.Select(i => new TypeTarget(i.GetFullTypeName(), i.SymbolicIdentifier)); tags.Add(new TagSpan <IInheritanceTag>(span, _tagFactory.CreateTag(tag, builder.ToString().TrimEnd(), targets))); } nodes = parseTree.SelectMethodsPropertiesAndFields(); nodes = nodes.SelectMany(SelectDeclaratorsFromFields); foreach (var node in nodes) { if (node is AccessorDeclarationNode) { // these nodes always result in an ArgumentException in GetMemberFromMemberDeclaration continue; } CSharpMember member; try { member = compilation.GetMemberFromMemberDeclaration(node); } catch (ArgumentException) { continue; } if (member == null) { MarkDirty(true); return; } if (!SpecializedMatchingMemberCollector.IsSupportedMemberType(member)) { continue; } // methods which this method implements ISet <CSharpMemberIdentifier> implementedMethods = collector.GetImplementedInterfaceMembers(member.SymbolicIdentifier); // methods which this method overrides ISet <CSharpMemberIdentifier> overriddenMethods = collector.GetOverriddenBaseMembers(member.SymbolicIdentifier); // methods which override this method ISet <CSharpMemberIdentifier> overridingMethods = collector.GetOverridersFromDerivedTypes(member.SymbolicIdentifier); // methods which implement this method ISet <CSharpMemberIdentifier> implementingMethods = collector.GetImplementorsForInterfaceMember(member.SymbolicIdentifier); if (implementingMethods.Count == 0 && implementedMethods.Count == 0 && overriddenMethods.Count == 0 && overridingMethods.Count == 0) { continue; } StringBuilder builder = new StringBuilder(); string elementKindDisplayName = member.IsProperty ? "properties" : member.IsEvent ? "events" : "methods"; if (implementedMethods.Count > 0) { builder.AppendLine("Implemented " + elementKindDisplayName + ":"); foreach (var methodId in implementedMethods) { builder.AppendLine(" " + methodId.ToString()); } } if (overriddenMethods.Count > 0) { builder.AppendLine("Overridden " + elementKindDisplayName + ":"); foreach (var methodId in overriddenMethods) { builder.AppendLine(" " + methodId.ToString()); } } if (implementingMethods.Count > 0) { builder.AppendLine("Implementing " + elementKindDisplayName + " in derived types:"); foreach (var methodId in implementingMethods) { builder.AppendLine(" " + methodId.ToString()); } } if (overridingMethods.Count > 0) { builder.AppendLine("Overriding " + elementKindDisplayName + " in derived types:"); foreach (var methodId in overridingMethods) { builder.AppendLine(" " + methodId.ToString()); } } int nameIndex = node.Token; Token token = parseTree.LexData.Tokens[nameIndex]; ITextSnapshotLine line = snapshot.GetLineFromLineNumber(token.StartPosition.Line); SnapshotSpan span = new SnapshotSpan(snapshot, new Span(line.Start + token.StartPosition.Character, token.EndPosition.Character - token.StartPosition.Character)); InheritanceGlyph tag; if (implementedMethods.Count > 0) { if (overridingMethods.Count > 0) { tag = InheritanceGlyph.ImplementsAndOverridden; } else if (implementingMethods.Count > 0) { tag = InheritanceGlyph.ImplementsAndHasImplementations; } else { tag = InheritanceGlyph.Implements; } } else if (implementingMethods.Count > 0) { tag = InheritanceGlyph.HasImplementations; } else if (overriddenMethods.Count > 0) { if (overridingMethods.Count > 0) { tag = InheritanceGlyph.OverridesAndOverridden; } else { tag = InheritanceGlyph.Overrides; } } else { tag = InheritanceGlyph.Overridden; } List <CSharpMemberIdentifier> members = new List <CSharpMemberIdentifier>(); members.AddRange(implementedMethods); members.AddRange(overriddenMethods); members.AddRange(implementingMethods); members.AddRange(overridingMethods); var targets = members.Select(i => new MemberTarget(i)); tags.Add(new TagSpan <IInheritanceTag>(span, _tagFactory.CreateTag(tag, builder.ToString().TrimEnd(), targets))); } } InheritanceParseResultEventArgs result = new InheritanceParseResultEventArgs(snapshot, stopwatch.Elapsed, tags); OnParseComplete(result); } catch (InvalidOperationException) { MarkDirty(true); throw; } }
public static void TrimTrailingWhiteSpace(this ITextDocument document, int lineNumber) { var line = document.GetLineByNumber(lineNumber); document.TrimTrailingWhiteSpace(line); }
private void ReParse() { try { _dirty = false; IOutputWindowPane outputWindow = null; if (_outputWindowService != null && !string.IsNullOrEmpty(_outputWindowName)) { outputWindow = _outputWindowService.TryGetPane(_outputWindowName); } Stopwatch stopwatch = Stopwatch.StartNew(); string message = "{0}: Background parse {1}{2} in {3}ms. {4}"; string name = Name; if (!string.IsNullOrEmpty(name)) { name = "(" + name + ") "; } string filename = "<Unknown File>"; ITextDocument textDocument = TextDocument; if (textDocument != null) { filename = textDocument.FilePath; if (filename != null) { filename = filename.Substring(filename.LastIndexOfAny(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }) + 1); } } try { ReParseImpl(); if (outputWindow != null) { long time = stopwatch.ElapsedMilliseconds; outputWindow.WriteLine(string.Format(message, filename, name, "succeeded", time, string.Empty)); } } catch (Exception e2) when(!ErrorHandler.IsCriticalException(e2)) { try { if (outputWindow != null) { long time = stopwatch.ElapsedMilliseconds; outputWindow.WriteLine(string.Format(message, filename, name, "failed", time, e2.Message + e2.StackTrace)); } } catch (Exception e3) when(!ErrorHandler.IsCriticalException(e3)) { } } } catch (Exception ex) when(!ErrorHandler.IsCriticalException(ex)) { } }