private bool IsCaretOutsideItemBounds( Model model, SnapshotPoint caretPoint, CompletionItem item, Dictionary<TextSpan, string> textSpanToText, Dictionary<TextSpan, ViewTextSpan> textSpanToViewSpan) { // Easy first check. See if the caret point is before the start of the item. if (!textSpanToViewSpan.TryGetValue(item.Span, out var filterSpanInViewBuffer)) { filterSpanInViewBuffer = model.GetViewBufferSpan(item.Span); textSpanToViewSpan[item.Span] = filterSpanInViewBuffer; } if (caretPoint < filterSpanInViewBuffer.TextSpan.Start) { return true; } var textSnapshot = caretPoint.Snapshot; var currentText = model.GetCurrentTextInSnapshot(item.Span, textSnapshot, textSpanToText); var currentTextSpan = new TextSpan(filterSpanInViewBuffer.TextSpan.Start, currentText.Length); return !currentTextSpan.IntersectsWith(caretPoint); }
private bool CompleteComment() { int position = TextView.Caret.Position.BufferPosition.Position; if (position < 1) return false; SnapshotSpan span = new SnapshotSpan(TextView.TextBuffer.CurrentSnapshot, position - 1, 1); bool isComment = _classifier.GetClassificationSpans(span).Any(c => c.ClassificationType.IsOfType("comment")); if (isComment) return false; char prevChar = TextView.TextBuffer.CurrentSnapshot.ToCharArray(position - 1, 1)[0]; // Abort if the previous characters isn't a forward-slash if (prevChar != '/' || isComment) return false; // Insert the typed character TextView.TextBuffer.Insert(position, "*"); using (EditorExtensionsPackage.UndoContext("Comment completion")) { // Use separate undo context for this, so it can be undone separately. TextView.TextBuffer.Insert(position + 1, "*/"); } // Move the caret to the correct point SnapshotPoint point = new SnapshotPoint(TextView.TextBuffer.CurrentSnapshot, position + 1); TextView.Caret.MoveTo(point); return true; }
public TextExtent GetExtentOfWord(SnapshotPoint currentPosition) { if (currentPosition.Snapshot?.TextBuffer != textBuffer) throw new ArgumentException(); WordParser.WordKind kind; var span = WordParser.GetWordSpan(currentPosition, out kind); return new TextExtent(span, kind != WordParser.WordKind.Whitespace); }
public void CreateForAllPoints_Line_EndOfSnapshot() { Create("cat", "dog"); var point = new SnapshotPoint(_textBuffer.CurrentSnapshot, _textBuffer.CurrentSnapshot.Length); var visualSpan = VisualSpan.CreateForAllPoints(VisualKind.Line, point, point); Assert.AreEqual(1, visualSpan.AsLine().LineRange.LastLineNumber); }
protected override bool Execute(uint commandId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { if (_broker.IsCompletionActive(TextView) || !IsValidTextBuffer() || !WESettings.GetBoolean(WESettings.Keys.EnableEnterFormat)) return false; int position = TextView.Caret.Position.BufferPosition.Position; SnapshotPoint point = new SnapshotPoint(TextView.TextBuffer.CurrentSnapshot, position); IWpfTextViewLine line = TextView.GetTextViewLineContainingBufferPosition(point); ElementNode element = null; AttributeNode attr = null; _tree.GetPositionElement(position, out element, out attr); if (element == null || _tree.IsDirty || element.Parent == null || line.End.Position == position || // caret at end of line (TODO: add ignore whitespace logic) TextView.TextBuffer.CurrentSnapshot.GetText(element.InnerRange.Start, element.InnerRange.Length).Trim().Length == 0) return false; UpdateTextBuffer(element, position); return false; }
// Statement completion public bool EnableFullIntelliSense(ITextBuffer buffer, SnapshotPoint point) { var tokens = GetSemanticModel(buffer); var type = tokens.GetContextSpan(point).Type; return type == ContextType.CodeBlock || type == ContextType.Lambda; }
public override Span? GetInvocationSpan(string text, int linePosition, SnapshotPoint position) { // If this isn't the beginning of the line, stop immediately. var quote = text.SkipWhile(Char.IsWhiteSpace).FirstOrDefault(); if (quote != '"' && quote != '\'') return null; // If it is, make sure it's also the beginning of a function. var prevLine = EnumeratePrecedingLineTokens(position).GetEnumerator(); // If we are at the beginning of the file, that is also fine. if (prevLine.MoveNext()) { // Check that the previous line contains "function", then // eventually ") {" followed by the end of the line. if (!ConsumeToToken(prevLine, "function", "keyword") || !ConsumeToToken(prevLine, ")", "operator")) return null; if (!prevLine.MoveNext() || prevLine.Current.Span.GetText() != "{") return null; // If there is non-comment code after the function, stop if (prevLine.MoveNext() && SkipComments(prevLine)) return null; } var startIndex = text.TakeWhile(Char.IsWhiteSpace).Count(); var endIndex = linePosition; // Consume the auto-added close quote, if present. // If range ends at the end of the line, we cannot // check this. if (endIndex < text.Length && text[endIndex] == quote) endIndex++; return Span.FromBounds(startIndex, endIndex); }
public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets) { var caretPosition = session.TextView.Caret.Position.BufferPosition.Position; var tokenTriggeringIntellisense = _tokenizedBuffer.CurrentState.FindTokenAtIndex(caretPosition); if (caretPosition == tokenTriggeringIntellisense.IndexToken.StartIndex) tokenTriggeringIntellisense = tokenTriggeringIntellisense.Previous(); var numberOfCharactersBeforeCursor = caretPosition - tokenTriggeringIntellisense.IndexToken.StartIndex; var textFromSymbolBeforeCursor = tokenTriggeringIntellisense.IndexToken.Token.Text.Substring(0, numberOfCharactersBeforeCursor); var currentIndexToken = _tokenizedBuffer.CurrentState.FindTokenAtIndex(0); var completions = new List<Completion>(); while (currentIndexToken != null) { if (currentIndexToken.IndexToken.StartIndex != tokenTriggeringIntellisense.IndexToken.StartIndex) { if (currentIndexToken.Node.Value.Type == TokenType.Symbol && currentIndexToken.Node.Value.Text.StartsWith(textFromSymbolBeforeCursor)) { if (completions.Find(c => c.DisplayText == currentIndexToken.Node.Value.Text) == null) { completions.Add(new Completion(currentIndexToken.Node.Value.Text)); } } } currentIndexToken = currentIndexToken.Next(); } var snapshot = session.TextView.TextSnapshot; var start = new SnapshotPoint(snapshot, tokenTriggeringIntellisense.IndexToken.StartIndex); var end = new SnapshotPoint(snapshot, start.Position + tokenTriggeringIntellisense.IndexToken.Token.Text.Length); var applicableTo = snapshot.CreateTrackingSpan(new SnapshotSpan(start, end), SpanTrackingMode.EdgeInclusive); completionSets.Add(new CompletionSet("All", "All", applicableTo, completions, new List<Completion>())); }
public override Span? GetInvocationSpan(string text, int linePosition, SnapshotPoint position) { // Find the quoted string inside function call int startIndex = text.LastIndexOf(FunctionName + "(", linePosition, StringComparison.Ordinal); if (startIndex < 0) return null; startIndex += FunctionName.Length + 1; startIndex += text.Skip(startIndex).TakeWhile(Char.IsWhiteSpace).Count(); if (linePosition <= startIndex || (text[startIndex] != '"' && text[startIndex] != '\'')) return null; var endIndex = text.IndexOf(text[startIndex] + ")", startIndex, StringComparison.OrdinalIgnoreCase); if (endIndex < 0) endIndex = startIndex + text.Skip(startIndex + 1).TakeWhile(c => Char.IsLetterOrDigit(c) || Char.IsWhiteSpace(c) || c == '-' || c == '_').Count() + 1; else if (linePosition > endIndex + 1) return null; // Consume the auto-added close quote, if present. // If range ends at the end of the line, we cannot // check this. if (endIndex < text.Length && text[endIndex] == text[startIndex]) endIndex++; return Span.FromBounds(startIndex, endIndex); }
public SnapshotPoint GetCaretPositionInSubjectBuffer(SnapshotPoint viewCaretPosition, ITextSnapshot bufferSnapshot) { var currentModelSpanInView = GetCurrentSpanInView(viewCaretPosition.Snapshot); SnapshotSpan currentModelSpanInSubjectBuffer = GetCurrentSpanInSubjectBuffer(bufferSnapshot); return currentModelSpanInSubjectBuffer.Start + (viewCaretPosition - currentModelSpanInView.Start); }
/// <summary> /// Removes a token using the enhanced token stream class. /// </summary> /// <param name="sql"></param> /// <param name="position"></param> /// <returns></returns> private CommonTokenStream RemoveToken(string sql, SnapshotPoint snapPos) { MemoryStream ms = new MemoryStream(ASCIIEncoding.ASCII.GetBytes(sql)); CaseInsensitiveInputStream input = new CaseInsensitiveInputStream(ms); //ANTLRInputStream input = new ANTLRInputStream(ms); Version ver = LanguageServiceUtil.GetVersion(LanguageServiceUtil.GetConnection().ServerVersion); MySQLLexer lexer = new MySQLLexer(input); lexer.MySqlVersion = ver; TokenStreamRemovable tokens = new TokenStreamRemovable(lexer); IToken tr = null; int position = snapPos.Position; tokens.Fill(); if (!char.IsWhiteSpace(snapPos.GetChar())) { foreach (IToken t in tokens.GetTokens()) { if ((t.StartIndex <= position) && (t.StopIndex >= position)) { tr = t; break; } } tokens.Remove(tr); } return tokens; }
internal static CompletionSet Create(List<DesignerNode> nodes, SnapshotPoint point) { DesignerNode node = nodes.FindLast(n => n.NodeType == NDjango.Interfaces.NodeType.ParsingContext); if (node == null) return null; return new TagCompletionSet(node, point); }
public FakeTextSnapshotLine(ITextSnapshot snapshot, string text, int position, int lineNumber) { Snapshot = snapshot; this._text = text; LineNumber = lineNumber; Start = new SnapshotPoint(snapshot, position); }
public SymbolInfo GetSymbolAt(string sourceFileName, SnapshotPoint point) { var result = GetGoToDefLocations(sourceFileName, point).FirstOrDefault(); if (result == null) return null; return new SymbolInfo(RQNameTranslator.ToIndexId(result.RQName), !result.IsMetadata, result.AssemblyBinaryName); }
/// <summary> /// Is the provided SnapshotPoint preceded by the '+= SomeEventType(Some_HandlerName' line /// </summary> private bool IsPreceededByEventAddSyntax(SnapshotSpan span) { // First find the last + character var snapshot = span.Snapshot; SnapshotPoint? plusPoint = null; for (int i = span.Length - 1; i >= 0; i--) { var position = span.Start.Position + i; var point = new SnapshotPoint(snapshot, position); if (point.GetChar() == '+') { plusPoint = point; break; } } if (plusPoint == null) { return false; } var eventSpan = new SnapshotSpan(plusPoint.Value, span.End); var eventText = eventSpan.GetText(); return s_fullEventSyntaxRegex.IsMatch(eventText) || s_shortEventSyntaxRegex.IsMatch(eventText); }
private static bool IsValidBraceCompletionContext(SnapshotPoint openingPoint) { Debug.Assert(openingPoint.Position >= 0, "SnapshotPoint.Position should always be zero or positive."); if (openingPoint.Position > 0) { var classifier = openingPoint.Snapshot.TextBuffer.GetSyntaxTagger(); var snapshotSpan = new SnapshotSpan(openingPoint - 1, 1); var classificationSpans = classifier.GetTags(new NormalizedSnapshotSpanCollection(snapshotSpan)); foreach (var span in classificationSpans) { if (!span.Span.OverlapsWith(snapshotSpan)) continue; if (span.Tag.ClassificationType.IsOfType("comment")) return false; if (span.Tag.ClassificationType.IsOfType("literal")) return false; } } // If we haven't stopped this, go ahead and start the completion session. // Either we were at position 0 (a safe place to be placing a brace completion) // or we were in a classification that is safe for brace completion. return true; }
/// <summary> /// Restores saved selection /// </summary> public override void EndTracking() { int position = PositionFromTokens(TextBuffer.CurrentSnapshot, _index, _offset); if (position >= 0) { PositionAfterChanges = new SnapshotPoint(TextBuffer.CurrentSnapshot, position); } MoveToAfterChanges(VirtualSpaces); }
private bool HandleVariables(IList<object> qiContent, ref ITrackingSpan applicableToSpan, IList<ClassificationSpan> spans, SnapshotPoint? point) { ClassificationSpan span; string text = GetText(spans, point, PredefinedClassificationTypeNames.SymbolDefinition, out span); if (string.IsNullOrWhiteSpace(text)) return false; string value = Environment.GetEnvironmentVariable(text.Trim('%')); if (string.IsNullOrEmpty(value)) return false; string displayText = value; if (value.Equals("path", StringComparison.OrdinalIgnoreCase)) displayText = string.Join(Environment.NewLine, value.Split(';')); applicableToSpan = _buffer.CurrentSnapshot.CreateTrackingSpan(span.Span, SpanTrackingMode.EdgeNegative); qiContent.Add(displayText); string expanded = Environment.ExpandEnvironmentVariables(value); if (expanded != value) qiContent.Add(expanded); return true; }
private static void CommentRegion(ITextView view, SnapshotPoint start, SnapshotPoint end) { using (var edit = view.TextBuffer.CreateEdit()) { int minColumn = Int32.MaxValue; // first pass, determine the position to place the comment for (int i = start.GetContainingLine().LineNumber; i <= end.GetContainingLine().LineNumber; i++) { var curLine = view.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(i); var text = curLine.GetText(); minColumn = Math.Min(GetMinimumColumn(text), minColumn); } // second pass, place the comment for (int i = start.GetContainingLine().LineNumber; i <= end.GetContainingLine().LineNumber; i++) { var curLine = view.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(i); if (curLine.Length < minColumn) { // need extra white space edit.Insert(curLine.Start.Position + curLine.Length, new String(' ', minColumn - curLine.Length) + "#"); } else { edit.Insert(curLine.Start.Position + minColumn, "#"); } } edit.Apply(); } // select the full region we just commented UpdateSelection(view, start, end); }
public static Position ToPosition(SnapshotPoint corePoint, ITextSnapshot snapshot = null) { SnapshotPoint snapshotPoint = corePoint.TranslateTo(snapshot ?? corePoint.Snapshot, PointTrackingMode.Positive); ITextSnapshotLine containingLine = snapshotPoint.GetContainingLine(); int charIndex = Math.Max(snapshotPoint.Position - containingLine.Start.Position, 0); return new Position(containingLine.LineNumber, charIndex); }
/// <summary> /// Activates a text view for a text buffer, and sets the cursor to a specific location /// </summary> public static bool NavigateToTextBuffer(ITextBuffer textBuffer, int start, int length) { IProjectionSnapshot projectionSnapshot = textBuffer.CurrentSnapshot as IProjectionSnapshot; if (projectionSnapshot != null) { // Find the main buffer for the view SnapshotPoint sourcePoint = new SnapshotPoint(); bool success = true; try { sourcePoint = projectionSnapshot.MapToSourceSnapshot(start, PositionAffinity.Successor); } catch (ArgumentOutOfRangeException) { success = false; } catch (InvalidOperationException) { success = false; } if (success) { return NavigateToTextBuffer(sourcePoint.Snapshot.TextBuffer, sourcePoint.Position, length); } } else { // This is the main buffer for the view IVsTextManager textManager = VsAppShell.Current.GetGlobalService<IVsTextManager>(typeof(SVsTextManager)); IVsTextBuffer vsTextBuffer = textBuffer.QueryInterface<IVsTextBuffer>(); Guid viewType = VSConstants.LOGVIEWID_TextView; if (vsTextBuffer != null && ErrorHandler.Succeeded(textManager.NavigateToPosition(vsTextBuffer, ref viewType, start, length))) { return true; } } return false; }
protected override bool Execute(uint commandId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { int position = TextView.Caret.Position.BufferPosition.Position; SnapshotPoint point = new SnapshotPoint(TextView.TextBuffer.CurrentSnapshot, position); IWpfTextViewLine line = TextView.GetTextViewLineContainingBufferPosition(point); string text = TextView.TextBuffer.CurrentSnapshot.GetText(line.Start, line.Length); Match match = _indent.Match(text); if (match.Success) { try { EditorExtensionsPackage.DTE.UndoContext.Open("Smart Indent"); TextView.TextBuffer.Insert(position, Environment.NewLine + match.Value); } finally { EditorExtensionsPackage.DTE.UndoContext.Close(); } return true; } return false; }
public bool TryCreateSession(ITextView textView, SnapshotPoint openingPoint, char openingBrace, char closingBrace, out IBraceCompletionSession session) { this.AssertIsForeground(); var textSnapshot = openingPoint.Snapshot; var document = textSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { var editorSessionFactory = document.GetLanguageService<IEditorBraceCompletionSessionFactory>(); if (editorSessionFactory != null) { // Brace completion is (currently) not cancellable. var cancellationToken = CancellationToken.None; var editorSession = editorSessionFactory.TryCreateSession(document, openingPoint, openingBrace, cancellationToken); if (editorSession != null) { var undoHistory = _undoManager.GetTextBufferUndoManager(textView.TextBuffer).TextBufferUndoHistory; session = new BraceCompletionSession( textView, openingPoint.Snapshot.TextBuffer, openingPoint, openingBrace, closingBrace, undoHistory, _editorOperationsFactoryService, editorSession); return true; } } } session = null; return false; }
// returns true if brace is actually a brace. private bool FindOtherBrace(SnapshotPoint possibleBrace, out SnapshotPoint? otherBrace) { otherBrace = null; var rainbow = this.textBuffer.Get<RainbowProvider>(); if ( rainbow == null ) { return false; } if ( !possibleBrace.IsValid() ) { return false; } if ( !rainbow.BraceCache.Language.BraceList.Contains(possibleBrace.GetChar()) ) { return false; } var bracePair = rainbow.BraceCache.GetBracePair(possibleBrace); if ( bracePair == null ) { return true; } if ( possibleBrace.Position == bracePair.Item1.Position ) { otherBrace = bracePair.Item2.ToPoint(possibleBrace.Snapshot); } else { otherBrace = bracePair.Item1.ToPoint(possibleBrace.Snapshot); } return true; }
private bool Indent() { int position = _textView.Caret.Position.BufferPosition.Position; if (position == 0 || position == _textView.TextBuffer.CurrentSnapshot.Length || _textView.Selection.SelectedSpans[0].Length > 0) return false; char before = _textView.TextBuffer.CurrentSnapshot.GetText(position - 1, 1)[0]; char after = _textView.TextBuffer.CurrentSnapshot.GetText(position, 1)[0]; if (before == '{' && after == '}') { EditorExtensionsPackage.DTE.UndoContext.Open("Smart indent"); _textView.TextBuffer.Insert(position, Environment.NewLine + '\t'); SnapshotPoint point = new SnapshotPoint(_textView.TextBuffer.CurrentSnapshot, position); _textView.Selection.Select(new SnapshotSpan(point, 4), true); EditorExtensionsPackage.ExecuteCommand("Edit.FormatSelection"); _textView.Selection.Clear(); SendKeys.Send("{ENTER}"); EditorExtensionsPackage.DTE.UndoContext.Close(); return true; } return false; }
public static string PeekString(this ITextSnapshot snapshot, SnapshotPoint point, int length) { if (point >= snapshot.Length) return null; return new SnapshotSpan(point, Math.Min(length, snapshot.Length - point)).GetText(); }
public TextExtent GetExtentOfWord(SnapshotPoint currentPosition) { if (currentPosition.Snapshot?.TextBuffer != textBuffer) throw new ArgumentException(); if (currentPosition.Position >= currentPosition.Snapshot.Length) return new TextExtent(new SnapshotSpan(currentPosition, currentPosition), true); return new TextExtent(new SnapshotSpan(currentPosition, currentPosition + 1), true); }
public static SnapshotPoint? MapUpOrDownToBuffer(this IBufferGraph bufferGraph, SnapshotPoint point, ITextBuffer targetBuffer) { var direction = ClassifyBufferMapDirection(point.Snapshot.TextBuffer, targetBuffer); switch (direction) { case BufferMapDirection.Identity: return point; case BufferMapDirection.Down: { // TODO (https://github.com/dotnet/roslyn/issues/5281): Remove try-catch. try { return bufferGraph.MapDownToInsertionPoint(point, PointTrackingMode.Positive, s => s == targetBuffer.CurrentSnapshot); } catch (ArgumentOutOfRangeException) when (bufferGraph.TopBuffer.ContentType.TypeName == "Interactive Content") { // Suppress this to work around DevDiv #144964. // Note: Other callers might be affected, but this is the narrowest workaround for the observed problems. // A fix is already being reviewed, so a broader change is not required. return null; } } case BufferMapDirection.Up: { return bufferGraph.MapUpToBuffer(point, PointTrackingMode.Positive, PositionAffinity.Predecessor, targetBuffer); } default: return null; } }
private ScenarioBlock? GetCurrentScenarioBlock(SnapshotPoint triggerPoint) { var parsingResult = gherkinProcessorServices.GetParsingResult(textBuffer); if (parsingResult == null) return null; var triggerLineNumber = triggerPoint.Snapshot.GetLineNumberFromPosition(triggerPoint.Position); var scenarioInfo = parsingResult.ScenarioEditorInfos.LastOrDefault(si => si.KeywordLine < triggerLineNumber); if (scenarioInfo == null) return null; for (var lineNumer = triggerLineNumber; lineNumer > scenarioInfo.KeywordLine; lineNumer--) { StepKeyword? stepKeyword = GetStepKeyword(triggerPoint.Snapshot, lineNumer, parsingResult.LanguageService); if (stepKeyword != null) { var scenarioBlock = stepKeyword.Value.ToScenarioBlock(); if (scenarioBlock != null) return scenarioBlock; } } return ScenarioBlock.Given; }
public CaretPosition MoveTo(SnapshotPoint bufferPosition, PositionAffinity caretAffinity) { _position = bufferPosition.Position; return new CaretPosition(new VirtualSnapshotPoint(bufferPosition), new MappingPointMock(bufferPosition.Snapshot.TextBuffer, bufferPosition.Position), caretAffinity); }
protected override string GetExteriorTextForNextLine(SnapshotPoint caretPosition) { var currentLine = caretPosition.GetContainingLine(); var firstNonWhitespacePosition = currentLine.GetFirstNonWhitespacePosition() ?? -1; if (firstNonWhitespacePosition == -1) { return(null); } var currentLineStartsWithBlockCommentStartString = currentLine.StartsWith(firstNonWhitespacePosition, "/*", ignoreCase: false); var currentLineStartsWithBlockCommentEndString = currentLine.StartsWith(firstNonWhitespacePosition, "*/", ignoreCase: false); var currentLineStartsWithBlockCommentMiddleString = currentLine.StartsWith(firstNonWhitespacePosition, "*", ignoreCase: false); if (!currentLineStartsWithBlockCommentStartString && !currentLineStartsWithBlockCommentMiddleString) { return(null); } if (!IsCaretInsideBlockCommentSyntax(caretPosition)) { return(null); } if (currentLineStartsWithBlockCommentStartString) { if (BlockCommentEndsRightAfterCaret(caretPosition)) { // /*|*/ return(" "); } else if (caretPosition == firstNonWhitespacePosition + 1) { // /|* return(null); // The newline inserted could break the syntax in a way that this handler cannot fix, let's leave it. } else { // /*| return(" *" + GetPaddingOrIndentation(currentLine, caretPosition, firstNonWhitespacePosition, "/*")); } } if (currentLineStartsWithBlockCommentEndString) { if (BlockCommentEndsRightAfterCaret(caretPosition)) { // /* // |*/ return(" "); } else if (caretPosition == firstNonWhitespacePosition + 1) { // *|/ return("*"); } else { // /* // | */ return(" * "); } } if (currentLineStartsWithBlockCommentMiddleString) { if (BlockCommentEndsRightAfterCaret(caretPosition)) { // *|*/ return(""); } else if (caretPosition > firstNonWhitespacePosition) { // *| return("*" + GetPaddingOrIndentation(currentLine, caretPosition, firstNonWhitespacePosition, "*")); } else { // /* // | * return(" * "); } } return(null); }
internal static void RestoreCaretTo(int caretPosition, ITextView textView) { var currentSnapshotPoint = new SnapshotPoint(textView.TextBuffer.CurrentSnapshot, caretPosition); textView.Caret.MoveTo(currentSnapshotPoint); }
protected override bool TryGetRazorSnapshotPoint(CompletionContext context, out SnapshotPoint snapshotPoint) { if (!_canGetSnapshotPoint) { snapshotPoint = default(SnapshotPoint); return(false); } var snapshot = new Mock <ITextSnapshot>(MockBehavior.Strict); snapshot.Setup(s => s.Length) .Returns(context.CompletionListSpan.End); snapshotPoint = new SnapshotPoint(snapshot.Object, context.CompletionListSpan.Start); return(true); }
private Model FilterModelInBackgroundWorker( Document document, Model model, int id, SnapshotPoint caretPosition, CompletionFilterReason filterReason, ImmutableDictionary <CompletionItemFilter, bool> filterState) { if (model == null) { return(null); } // We want to dismiss the session if the caret ever moved outside our bounds. // Do this before we check the _filterId. We don't want this work to not happen // just because the user typed more text and added more filter items. if (filterReason == CompletionFilterReason.CaretPositionChanged && Controller.IsCaretOutsideAllItemBounds(model, caretPosition)) { return(null); } // If the UI specified an updated filter state, then incorporate that // into our model. Do this before we check the _filterId. We don't // want this work to not happen just because the user typed more text // and added more filter items. if (filterState != null) { model = model.WithFilterState(filterState); } // If there's another request in the queue to filter items, then just // bail out immediately. No point in doing extra work that's just // going to be overridden by the next filter task. if (id != _filterId) { return(model); } var textSnapshot = caretPosition.Snapshot; var textSpanToText = new Dictionary <TextSpan, string>(); var helper = this.Controller.GetCompletionHelper(document); var recentItems = this.Controller.GetRecentItems(); var filterResults = new List <FilterResult>(); var filterText = model.GetCurrentTextInSnapshot( model.OriginalList.Span, textSnapshot, textSpanToText); // Check if the user is typing a number. If so, only proceed if it's a number // directly after a <dot>. That's because it is actually reasonable for completion // to be brought up after a <dot> and for the user to want to filter completion // items based on a number that exists in the name of the item. However, when // we are not after a dot (i.e. we're being brought up after <space> is typed) // then we don't want to filter things. Consider the user writing: // // dim i =<space> // // We'll bring up the completion list here (as VB has completion on <space>). // If the user then types '3', we don't want to match against Int32. var filterTextStartsWithANumber = filterText.Length > 0 && char.IsNumber(filterText[0]); if (filterTextStartsWithANumber) { if (!IsAfterDot(model, model.TriggerSnapshot, textSpanToText)) { return(null); } } var effectiveFilterItemState = ComputeEffectiveFilterItemState(model); foreach (var currentItem in model.TotalItems) { // Check if something new has happened and there's a later on filter operation // in the chain. If so, there's no need for us to do any more work (as it will // just be superceded by the later work). if (id != _filterId) { return(model); } if (CompletionItemFilter.ShouldBeFilteredOutOfCompletionList( currentItem, effectiveFilterItemState)) { continue; } // Check if the item matches the filter text typed so far. var matchesFilterText = MatchesFilterText(helper, currentItem, filterText, model.Trigger, filterReason, recentItems); if (matchesFilterText) { filterResults.Add(new FilterResult( currentItem, filterText, matchedFilterText: true)); } else { // The item didn't match the filter text. We'll still keep it in the list // if one of two things is true: // // 1. The user has only typed a single character. In this case they might // have just typed the character to get completion. Filtering out items // here is not desirable. // // 2. They brough up completion with ctrl-j or through deletion. In these // cases we just always keep all the items in the list. var wasTriggeredByDeleteOrSimpleInvoke = model.Trigger.Kind == CompletionTriggerKind.Deletion || model.Trigger.Kind == CompletionTriggerKind.Invoke; var shouldKeepItem = filterText.Length <= 1 || wasTriggeredByDeleteOrSimpleInvoke; if (shouldKeepItem) { filterResults.Add(new FilterResult( currentItem, filterText, matchedFilterText: false)); } } } model = model.WithFilterText(filterText); // If no items matched the filter text then determine what we should do. if (filterResults.Count == 0) { return(HandleAllItemsFilteredOut(model, filterReason)); } // If this was deletion, then we control the entire behavior of deletion // ourselves. if (model.Trigger.Kind == CompletionTriggerKind.Deletion) { return(HandleDeletionTrigger(model, filterReason, filterResults)); } return(HandleNormalFiltering( model, document, filterReason, caretPosition, helper, recentItems, filterText, filterResults)); }
public void OnCommitted(ICssCompletionListEntry entry, ITrackingSpan contextSpan, SnapshotPoint caret, ITextView textView) { if (entry.DisplayText == "Add region...") { Dispatcher.CurrentDispatcher.BeginInvoke( new Action(() => System.Windows.Forms.SendKeys.Send("{TAB}")), DispatcherPriority.Normal); } }
public AbstractCommandHandlerTestState( XElement workspaceElement, ExportProvider exportProvider, string?workspaceKind, bool makeSeparateBufferForCursor = false, ImmutableArray <string> roles = default) { this.Workspace = TestWorkspace.CreateWorkspace( workspaceElement, exportProvider : exportProvider, workspaceKind : workspaceKind); if (makeSeparateBufferForCursor) { var languageName = Workspace.Projects.First().Language; var contentType = Workspace.Services.GetLanguageServices(languageName).GetRequiredService <IContentTypeLanguageService>().GetDefaultContentType(); _createdTextView = EditorFactory.CreateView(exportProvider, contentType, roles); _textView = _createdTextView.TextView; _subjectBuffer = _textView.TextBuffer; } else { var cursorDocument = this.Workspace.Documents.First(d => d.CursorPosition.HasValue); _textView = cursorDocument.GetTextView(); _subjectBuffer = cursorDocument.GetTextBuffer(); if (cursorDocument.AnnotatedSpans.TryGetValue("Selection", out var selectionSpanList)) { var firstSpan = selectionSpanList.First(); var lastSpan = selectionSpanList.Last(); var cursorPosition = cursorDocument.CursorPosition !.Value; Assert.True(cursorPosition == firstSpan.Start || cursorPosition == firstSpan.End || cursorPosition == lastSpan.Start || cursorPosition == lastSpan.End, "cursorPosition wasn't at an endpoint of the 'Selection' annotated span"); _textView.Selection.Mode = selectionSpanList.Length > 1 ? TextSelectionMode.Box : TextSelectionMode.Stream; SnapshotPoint boxSelectionStart, boxSelectionEnd; bool isReversed; if (cursorPosition == firstSpan.Start || cursorPosition == lastSpan.End) { // Top-left and bottom-right corners used as anchor points. boxSelectionStart = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, firstSpan.Start); boxSelectionEnd = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, lastSpan.End); isReversed = cursorPosition == firstSpan.Start; } else { // Top-right and bottom-left corners used as anchor points. boxSelectionStart = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, firstSpan.End); boxSelectionEnd = new SnapshotPoint(_subjectBuffer.CurrentSnapshot, lastSpan.Start); isReversed = cursorPosition == firstSpan.End; } _textView.Selection.Select( new SnapshotSpan(boxSelectionStart, boxSelectionEnd), isReversed: isReversed); } } this.EditorOperations = GetService <IEditorOperationsFactoryService>().GetEditorOperations(_textView); this.UndoHistoryRegistry = GetService <ITextUndoHistoryRegistry>(); }
private StepDefinitionType?GetCurrentBindingType(SnapshotPoint triggerPoint, out string parsedKeyword) { parsedKeyword = null; var fileScope = languageService.GetFileScope(waitForParsingSnapshot: triggerPoint.Snapshot); if (fileScope == null) { return(null); } var triggerLineNumber = triggerPoint.Snapshot.GetLineNumberFromPosition(triggerPoint.Position); var step = fileScope.GetStepAtPosition(triggerLineNumber); if (step != null) { parsedKeyword = step.Keyword.TrimEnd(); return(step.StepDefinitionType); } if (!IsStepLine(triggerPoint, languageService)) { return(null); } // this is a step line that just started. we need to calculate the binding type from // the keyword and the context var keywordCandidate = GetFirstWord(triggerPoint); if (keywordCandidate == null) { return(null); } GherkinDialect dialect = GetDialect(languageService); var stepKeyword = dialect.TryParseStepKeyword(keywordCandidate); if (stepKeyword == null) { keywordCandidate = GetFirstTwoWords(triggerPoint); if (keywordCandidate != null) { stepKeyword = dialect.TryParseStepKeyword(keywordCandidate); } if (stepKeyword == null) { return(null); } } parsedKeyword = keywordCandidate; if (stepKeyword == StepKeyword.Given) { return(StepDefinitionType.Given); } if (stepKeyword == StepKeyword.When) { return(StepDefinitionType.When); } if (stepKeyword == StepKeyword.Then) { return(StepDefinitionType.Then); } parsedKeyword = null; // now we need the context var stepBlock = fileScope.GetStepBlockFromStepPosition(triggerLineNumber); var lastStep = stepBlock.Steps.LastOrDefault(s => s.BlockRelativeLine + stepBlock.KeywordLine < triggerLineNumber); if (lastStep == null) { return(StepDefinitionType.Given); } return(lastStep.StepDefinitionType); }
private async Task <Model> ComputeModelInBackgroundAsync( Model currentModel, ImmutableArray <ISignatureHelpProvider> providers, SnapshotPoint caretPosition, DisconnectedBufferGraph disconnectedBufferGraph, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.SignatureHelp_ModelComputation_ComputeModelInBackground, cancellationToken)) { AssertIsBackground(); cancellationToken.ThrowIfCancellationRequested(); var document = await Controller.DocumentProvider.GetDocumentAsync(caretPosition.Snapshot, cancellationToken).ConfigureAwait(false); if (document == null) { return(currentModel); } if (triggerInfo.TriggerReason == SignatureHelpTriggerReason.RetriggerCommand) { if (currentModel == null) { return(null); } if (triggerInfo.TriggerCharacter.HasValue && !currentModel.Provider.IsRetriggerCharacter(triggerInfo.TriggerCharacter.Value)) { return(currentModel); } } // first try to query the providers that can trigger on the specified character var(provider, items) = await ComputeItemsAsync( providers, caretPosition, triggerInfo, document, cancellationToken).ConfigureAwait(false); if (provider == null) { // No provider produced items. So we can't produce a model return(null); } if (currentModel != null && currentModel.Provider == provider && currentModel.GetCurrentSpanInSubjectBuffer(disconnectedBufferGraph.SubjectBufferSnapshot).Span.Start == items.ApplicableSpan.Start && currentModel.Items.IndexOf(currentModel.SelectedItem) == items.SelectedItemIndex && currentModel.ArgumentIndex == items.ArgumentIndex && currentModel.ArgumentCount == items.ArgumentCount && currentModel.ArgumentName == items.ArgumentName) { // The new model is the same as the current model. Return the currentModel // so we keep the active selection. return(currentModel); } var selectedItem = GetSelectedItem(currentModel, items, provider, out bool userSelected); var model = new Model(disconnectedBufferGraph, items.ApplicableSpan, provider, items.Items, selectedItem, items.ArgumentIndex, items.ArgumentCount, items.ArgumentName, selectedParameter: 0, userSelected); var syntaxFactsService = document.GetLanguageService <ISyntaxFactsService>(); var isCaseSensitive = syntaxFactsService == null || syntaxFactsService.IsCaseSensitive; var selection = DefaultSignatureHelpSelector.GetSelection(model.Items, model.SelectedItem, model.UserSelected, model.ArgumentIndex, model.ArgumentCount, model.ArgumentName, isCaseSensitive); return(model.WithSelectedItem(selection.SelectedItem, selection.UserSelected) .WithSelectedParameter(selection.SelectedParameter)); } } catch (Exception e) when(FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } }
public Task <CompletionContext> GetCompletionContextAsync(IAsyncCompletionSession session, CompletionTrigger trigger, SnapshotPoint triggerLocation, SnapshotSpan applicableToSpan, CancellationToken token) { if (_parser.TryGetCompletionList(triggerLocation, _attributeName, out IEnumerable <CompletionItem> completions)) { return(Task.FromResult(new CompletionContext(completions.ToImmutableArray()))); } return(Task.FromResult(CompletionContext.Empty)); }
private static bool BlockCommentEndsRightAfterCaret(SnapshotPoint caretPosition) { var snapshot = caretPosition.Snapshot; return(((int)caretPosition + 2 <= snapshot.Length) ? snapshot.GetText(caretPosition, 2) == "*/" : false); }
public CaretPosition MoveTo(SnapshotPoint bufferPosition) { this.InternalMoveTo(new VirtualSnapshotPoint(bufferPosition), PositionAffinity.Successor, true, true, true); return(this.Position); }
public void AugmentCompletionSession(ICompletionSession session, IList <CompletionSet> completionSets) { //AsmDudeToolsStatic.Output_INFO(string.Format("{0}:AugmentCompletionSession", this.ToString())); if (!Settings.Default.CodeCompletion_On) { return; } try { DateTime time1 = DateTime.Now; ITextSnapshot snapshot = this._buffer.CurrentSnapshot; SnapshotPoint triggerPoint = (SnapshotPoint)session.GetTriggerPoint(snapshot); if (triggerPoint == null) { return; } ITextSnapshotLine line = triggerPoint.GetContainingLine(); //1] check if current position is in a remark; if we are in a remark, no code completion #region if (triggerPoint.Position > 1) { char currentTypedChar = (triggerPoint - 1).GetChar(); //AsmDudeToolsStatic.Output_INFO("CodeCompletionSource:AugmentCompletionSession: current char = "+ currentTypedChar); if (!currentTypedChar.Equals('#')) { //TODO UGLY since the user can configure this starting character int pos = triggerPoint.Position - line.Start; if (AsmSourceTools.IsInRemark(pos, line.GetText())) { //AsmDudeToolsStatic.Output_INFO("CodeCompletionSource:AugmentCompletionSession: currently in a remark section"); return; } else { // AsmDudeToolsStatic.Output_INFO("CodeCompletionSource:AugmentCompletionSession: not in a remark section"); } } } #endregion //2] find the start of the current keyword #region SnapshotPoint start = triggerPoint; while ((start > line.Start) && !AsmSourceTools.IsSeparatorChar((start - 1).GetChar())) { start -= 1; } #endregion //3] get the word that is currently being typed #region ITrackingSpan applicableTo = snapshot.CreateTrackingSpan(new SnapshotSpan(start, triggerPoint), SpanTrackingMode.EdgeInclusive); string partialKeyword = applicableTo.GetText(snapshot); bool useCapitals = AsmDudeToolsStatic.Is_All_Upper(partialKeyword); string lineStr = line.GetText(); (string Label, Mnemonic Mnemonic, string[] Args, string Remark)t = AsmSourceTools.ParseLine(lineStr); Mnemonic mnemonic = t.Mnemonic; //AsmDudeToolsStatic.Output_INFO("CodeCompletionSource:AugmentCompletionSession; lineStr="+ lineStr+ "; t.Item1="+t.Item1); string previousKeyword = AsmDudeToolsStatic.Get_Previous_Keyword(line.Start, start).ToUpper(); if (mnemonic == Mnemonic.NONE) { //AsmDudeToolsStatic.Output_INFO("CodeCompletionSource:AugmentCompletionSession; lineStr=" + lineStr + "; previousKeyword=" + previousKeyword); if (previousKeyword.Equals("INVOKE")) //TODO INVOKE is a MASM keyword not a NASM one... { // Suggest a label IEnumerable <Completion> completions = this.Label_Completions(useCapitals, false); if (completions.Any()) { completionSets.Add(new CompletionSet("Labels", "Labels", applicableTo, completions, Enumerable.Empty <Completion>())); } } else { { ISet <AsmTokenType> selected1 = new HashSet <AsmTokenType> { AsmTokenType.Directive, AsmTokenType.Jump, AsmTokenType.Misc, AsmTokenType.Mnemonic }; IEnumerable <Completion> completions1 = this.Selected_Completions(useCapitals, selected1, true); if (completions1.Any()) { completionSets.Add(new CompletionSet("All", "All", applicableTo, completions1, Enumerable.Empty <Completion>())); } } if (false) { ISet <AsmTokenType> selected2 = new HashSet <AsmTokenType> { AsmTokenType.Jump, AsmTokenType.Mnemonic }; IEnumerable <Completion> completions2 = this.Selected_Completions(useCapitals, selected2, false); if (completions2.Any()) { completionSets.Add(new CompletionSet("Instr", "Instr", applicableTo, completions2, Enumerable.Empty <Completion>())); } } if (false) { ISet <AsmTokenType> selected3 = new HashSet <AsmTokenType> { AsmTokenType.Directive, AsmTokenType.Misc }; IEnumerable <Completion> completions3 = this.Selected_Completions(useCapitals, selected3, true); if (completions3.Any()) { completionSets.Add(new CompletionSet("Directive", "Directive", applicableTo, completions3, Enumerable.Empty <Completion>())); } } } } else { // the current line contains a mnemonic //AsmDudeToolsStatic.Output_INFO("CodeCompletionSource:AugmentCompletionSession; mnemonic=" + mnemonic+ "; previousKeyword="+ previousKeyword); if (AsmSourceTools.IsJump(AsmSourceTools.ParseMnemonic(previousKeyword, true))) { //AsmDudeToolsStatic.Output_INFO("CodeCompletionSource:AugmentCompletionSession; previous keyword is a jump mnemonic"); // previous keyword is jump (or call) mnemonic. Suggest "SHORT" or a label IEnumerable <Completion> completions = this.Label_Completions(useCapitals, true); if (completions.Any()) { completionSets.Add(new CompletionSet("Labels", "Labels", applicableTo, completions, Enumerable.Empty <Completion>())); } } else if (previousKeyword.Equals("SHORT") || previousKeyword.Equals("NEAR")) { // Suggest a label IEnumerable <Completion> completions = this.Label_Completions(useCapitals, false); if (completions.Any()) { completionSets.Add(new CompletionSet("Labels", "Labels", applicableTo, completions, Enumerable.Empty <Completion>())); } } else { IList <Operand> operands = AsmSourceTools.MakeOperands(t.Args); ISet <AsmSignatureEnum> allowed = new HashSet <AsmSignatureEnum>(); int commaCount = AsmSignature.Count_Commas(lineStr); IEnumerable <AsmSignatureElement> allSignatures = this._asmDudeTools.Mnemonic_Store.GetSignatures(mnemonic); ISet <Arch> selectedArchitectures = AsmDudeToolsStatic.Get_Arch_Swithed_On(); foreach (AsmSignatureElement se in AsmSignatureHelpSource.Constrain_Signatures(allSignatures, operands, selectedArchitectures)) { if (commaCount < se.Operands.Count) { foreach (AsmSignatureEnum s in se.Operands[commaCount]) { allowed.Add(s); } } } IEnumerable <Completion> completions = this.Mnemonic_Operand_Completions(useCapitals, allowed, line.LineNumber); if (completions.Any()) { completionSets.Add(new CompletionSet("All", "All", applicableTo, completions, Enumerable.Empty <Completion>())); } } } #endregion AsmDudeToolsStatic.Print_Speed_Warning(time1, "Code Completion"); } catch (Exception e) { AsmDudeToolsStatic.Output_ERROR(string.Format("{0}:AugmentCompletionSession; e={1}", this.ToString(), e.ToString())); } }
private bool IsValidBraceCompletionContext(SnapshotPoint openingPoint) { Debug.Assert(openingPoint.Position >= 0, "SnapshotPoint.Position should always be zero or positive."); return(true); }
public CaretPosition MoveTo(SnapshotPoint bufferPosition, PositionAffinity caretAffinity, bool captureHorizontalPosition) { this.InternalMoveTo(new VirtualSnapshotPoint(bufferPosition), caretAffinity, captureHorizontalPosition, true, true); return(this.Position); }
/// <summary> /// Indicates that the drag and drop operation has completed, and that the final tasks, if any, should be performed now. /// </summary> /// <param name="dragDropInfo"> /// Information about the drag and drop operation in progress. /// </param> /// <returns> /// The drag and drop effects of this drop operation. For example, if the drop operation has moved data, /// DragDropPointerEffects.Move should be returned. /// </returns> /// <remarks>This method is called when the user drops the data onto the editor. /// This marks the end of a drag and drop operation. /// The <see cref="IDropHandler"/> is expected to perform the final tasks of the operation. /// </remarks> public virtual DragDropPointerEffects HandleDataDropped(DragDropInfo dragDropInfo) { if (dragDropInfo == null) { throw new ArgumentNullException(nameof(dragDropInfo)); } ITextSelection selection = _cocoaTextView.Selection; //keeps track of the result of this operation DragDropPointerEffects result = DragDropPointerEffects.None; //tracks the location at which the data was dropped VirtualSnapshotPoint dropLocation = dragDropInfo.VirtualBufferPosition; //convert the drag/drop data to text string dragDropText = this.ExtractText(dragDropInfo); bool isReversed = selection.IsReversed; bool copyRequested = (dragDropInfo.KeyStates & NSEventModifierMask.AlternateKeyMask) == NSEventModifierMask.AlternateKeyMask; bool copyAllowed = (dragDropInfo.AllowedEffects & NSDragOperation.Copy) == NSDragOperation.Copy; ITextSnapshot preEditSnapshot = _cocoaTextView.TextSnapshot; // track the point where the data will be inserted ITrackingPoint insertionPoint = preEditSnapshot.CreateTrackingPoint(dropLocation.Position, PointTrackingMode.Negative); // track the currently selected spans before any edits are performed on the buffer List <ITrackingSpan> selectionSpans = new List <ITrackingSpan>(); foreach (SnapshotSpan selectedSpan in selection.SelectedSpans) { selectionSpans.Add(preEditSnapshot.CreateTrackingSpan(selectedSpan, SpanTrackingMode.EdgeExclusive)); } // perform any necessary pre edit actions this.PerformPreEditActions(dragDropInfo); // clear selection before data operations if (!selection.IsEmpty) { selection.Clear(); } // a reference to the snapshot resulting from the edits bool successfulEdit = false; // if the data is being dropped in virtual space, calculate how many whitespace characters will be inserted // to fill the gap between the dropped point and the closest buffer position int virtualSpaceLength = 0; if (dragDropInfo.VirtualBufferPosition.IsInVirtualSpace) { virtualSpaceLength = _editorOperations.GetWhitespaceForVirtualSpace(dragDropInfo.VirtualBufferPosition).Length; } if (copyRequested && copyAllowed) { //copy the data by inserting it in the buffer successfulEdit = this.InsertText(dropLocation, dragDropText); if (successfulEdit) { result = DragDropPointerEffects.Copy; } } else { //the data needs to be moved if (dragDropInfo.IsInternal) { //delete the existing selection, and add the data to the new location successfulEdit = this.MoveText(dropLocation, selectionSpans, dragDropText); } else { //the drag is not from this text view, just insert the data at dropLocation successfulEdit = this.InsertText(dropLocation, dragDropText); } //set the pointer effect to move if the edit was successful since that implies that the data was moved successfully if (successfulEdit) { result = DragDropPointerEffects.Move; } } // finally select the newly inserted data if the operation was successful if (result != DragDropPointerEffects.None) { SnapshotPoint textInsertionPoint = insertionPoint.GetPoint(_cocoaTextView.TextSnapshot); // if the data was inserted in virtual space, offset the selection's anchor point by the whitespace that was inserted // in virtual space if (virtualSpaceLength != 0) { textInsertionPoint = textInsertionPoint.Add(virtualSpaceLength); } this.SelectText(textInsertionPoint, dragDropText.Length, dragDropInfo, isReversed); } // perform any post edit actions as necessary this.PerformPostEditActions(dragDropInfo, successfulEdit); return(result); }
ITextViewLine ITextViewLineCollection.GetTextViewLineContainingBufferPosition(SnapshotPoint bufferPosition) => GetTextViewLineContainingBufferPosition(bufferPosition);
/// <summary> /// Determine if a given "word" should be highlighted /// </summary> private static bool WordExtentIsValid(SnapshotPoint currentRequest, TextExtent word) { return(word.IsSignificant && currentRequest.Snapshot.GetText(word.Span).Any(c => char.IsLetter(c))); }
// Brace matching public IEnumerable <ITagSpan <TextMarkerTag> > GetBraceTags(ITextBuffer buffer, SnapshotPoint point) { var tokens = GetSemanticModel(buffer); var token = tokens.GetToken(point.Position - 1); var tag = new TextMarkerTag(Classifications.BraceHighlight); if (token?.MatchingToken != null && token.IsOpen == false) { yield return(new TagSpan <TextMarkerTag>(new SnapshotSpan(point.Snapshot, token.Start, 1), tag)); yield return(new TagSpan <TextMarkerTag>(new SnapshotSpan(point.Snapshot, token.MatchingToken.Start, 1), tag)); } else { token = tokens.GetToken(point.Position); if (token?.MatchingToken != null && token.IsOpen) { yield return(new TagSpan <TextMarkerTag>(new SnapshotSpan(point.Snapshot, token.Start, 1), tag)); yield return(new TagSpan <TextMarkerTag>(new SnapshotSpan(point.Snapshot, token.MatchingToken.Start, 1), tag)); } } }
public ValueCompletionSet(DesignerNode node, SnapshotPoint point) : base(node, point) { }
void IVimHost.EnsureVisible(ITextView textView, SnapshotPoint value) { }
IWpfTextViewLine IWpfTextView.GetTextViewLineContainingBufferPosition(SnapshotPoint bufferPosition) => throw new NotImplementedException();
public SnapshotSpan GetSpanToTokenize(SnapshotPoint point) { return(this.stateManagement.GetSpanToTokenize(new SnapshotSpan(point.Snapshot, point.Position, 0))); }
private static bool IsInAString(SyntaxNode currentNode, SnapshotPoint caret) // If caret is at the end of the line, it is outside the string => currentNode.IsKind(SyntaxKind.InterpolatedStringExpression, SyntaxKind.StringLiteralExpression) && caret.Position != caret.GetContainingLine().End;
public IEnumerable <ITagSpan <TextMarkerTag> > GetTags(NormalizedSnapshotSpanCollection spans) { // Todo: the classifier is now marking open and close keywords with (invisible) classification // on another location the classifier is building regions based on Open/Close keywords. // During this process of building regions we can also 'remember' the open/close pairs // so we do not have to look for these in this code. DateTime oStart, oEnd; TimeSpan timeSpan; oStart = DateTime.Now; if (spans.Count == 0 || _currentChar == null) //there is no content in the buffer { yield break; } WriteOutputMessage($"GetTags() Spans: {spans.Count}"); //don't do anything if the current SnapshotPoint is not initialized or at the end of the buffer if (!_currentChar.HasValue || _currentChar.Value.Position >= _currentChar.Value.Snapshot.Length) { yield break; } //hold on to a snapshot of the current character SnapshotPoint currentChar = _currentChar.Value; //if the requested snapshot isn't the same as the one the brace is on, translate our spans to the expected snapshot if (spans[0].Snapshot != currentChar.Snapshot) { currentChar = currentChar.TranslateTo(spans[0].Snapshot, PointTrackingMode.Positive); } //get the current char and the previous char SnapshotSpan pairSpan = new SnapshotSpan(); // check to see if we are on a closing or opening keyword if (!cursorOnKwOpenClose(currentChar)) { yield break; } // Try to Match Keywords // Try to retrieve an already parsed list of Tags XSharpClassifier xsClassifier = _buffer.GetClassifier(); if (xsClassifier == null) { yield break; } else { ITagSpan <TextMarkerTag> result1 = null; ITagSpan <TextMarkerTag> result2 = null; ITagSpan <TextMarkerTag> result3 = null; ITagSpan <TextMarkerTag> result4 = null; try { WriteOutputMessage("Match Open/Close keywords : " + oStart.ToString("hh:mm:ss.fff")); ITextSnapshot snapshot = xsClassifier.Snapshot; if (snapshot.Version != currentChar.Snapshot.Version) { yield break; } SnapshotSpan Span = new SnapshotSpan(snapshot, 0, snapshot.Length); var classifications = xsClassifier.GetTags(); // We cannot use SortedList, because we may have several Classification that start at the same position List <ClassificationSpan> sortedTags = new List <ClassificationSpan>(); foreach (var tag in classifications) { // Only keep the Brace matching Tags if ((tag.ClassificationType.IsOfType(ColorizerConstants.XSharpKwOpenFormat)) || (tag.ClassificationType.IsOfType(ColorizerConstants.XSharpKwCloseFormat))) { sortedTags.Add(tag); } } sortedTags.Sort((a, b) => a.Span.Start.Position.CompareTo(b.Span.Start.Position) * 1000 + string.Compare(a.ClassificationType.Classification, b.ClassificationType.Classification)); // var tags = sortedTags.Where(x => currentChar.Position >= x.Span.Start.Position && currentChar.Position <= x.Span.End.Position); foreach (var currentTag in tags) { var index = sortedTags.IndexOf(currentTag); if (currentTag.ClassificationType.IsOfType(ColorizerConstants.XSharpKwOpenFormat) && result1 == null) { if (FindMatchingCloseTag(sortedTags, index, snapshot, out pairSpan)) { var span = currentTag.Span; result1 = new TagSpan <TextMarkerTag>(span, _tag); result2 = new TagSpan <TextMarkerTag>(pairSpan, _tag); } } else if (result3 == null) { if (FindMatchingOpenTag(sortedTags, index, snapshot, out pairSpan)) { var span = currentTag.Span; result3 = new TagSpan <TextMarkerTag>(pairSpan, _tag); result4 = new TagSpan <TextMarkerTag>(span, _tag); } } } } catch (Exception e) { XSettings.LogException(e, "KeywordMatchingTagger.GetTags failed"); } finally { oEnd = DateTime.Now; timeSpan = oEnd - oStart; WriteOutputMessage("Finished Match Open/Close keywords: " + oEnd.ToString("hh:mm:ss.fff")); WriteOutputMessage("Finished Match Open/Close keywords - total ms: " + timeSpan.TotalMilliseconds.ToString()); } if (result1 != null) { yield return(result1); } if (result2 != null) { yield return(result2); } if (result3 != null) { yield return(result3); } if (result4 != null) { yield return(result4); } } }
private static CompletionContext GetCompletionContext(PaketDocument paketDocument, ITextStructureNavigator navigator, SnapshotPoint position) { TextExtent endPosition = navigator.GetExtentOfWord(position - 1); TextExtent startPosition = endPosition; // try to extend the span over . while (!String.IsNullOrWhiteSpace(paketDocument.GetCharAt(startPosition.Span.Start.Position - 1))) { startPosition = navigator.GetExtentOfWord(startPosition.Span.Start - 2); } var startPos = startPosition.Span.Start.Position; var length = endPosition.Span.End.Position - startPos; var span = new Span(startPos, length); var snapShotSpan = new SnapshotSpan(position.Snapshot, span); var context = new CompletionContext(span); TextExtent previous = navigator.GetExtentOfWord(startPosition.Span.Start - 1); // try to extend the span over blanks while (paketDocument.GetCharAt(previous.Span.Start.Position) == " ") { previous = navigator.GetExtentOfWord(previous.Span.Start - 1); } var lastWord = previous.Span.GetText(); switch (lastWord) { case "nuget": context.ContextType = CompletionContextType.NuGet; break; case "source": context.ContextType = CompletionContextType.Source; break; case "strategy": context.ContextType = CompletionContextType.Strategy; break; default: context.ContextType = CompletionContextType.Keyword; break; } context.Snapshot = snapShotSpan.Snapshot; return(context); }
public CaretPosition MoveCaret(SnapshotPoint newPoint) { return(_vs.Invoke(() => _view.Caret.MoveTo(newPoint.TranslateTo(newPoint.Snapshot.TextBuffer.CurrentSnapshot, PointTrackingMode.Positive)))); }
public static IEnumerable <ICompletionListProvider> GetCompletionProviders(IIntellisenseSession session, ITextBuffer textBuffer, SnapshotPoint position, ITextStructureNavigator navigator, out CompletionContext context) { IEnumerable <ICompletionListProvider> providers = GetCompletionProviders(PaketDocument.FromTextBuffer(textBuffer), navigator, position, out context); if (context == null) { return(providers); } if (context.Snapshot == null) { context.Snapshot = textBuffer.CurrentSnapshot; } if (context.Session != null) { return(providers); } context.Session = session; return(providers); }
void IVimHost.EnsureVisible(ITextView textView, SnapshotPoint point) { EnsureVisible(textView, point); }
private static async Task PasteReplCode( IInteractiveWindow window, string pasting, PythonLanguageVersion version ) { // there's some text in the buffer... var view = window.TextView; var caret = view.Caret; if (view.Selection.IsActive && !view.Selection.IsEmpty) { foreach (var span in view.Selection.SelectedSpans) { foreach (var normalizedSpan in view.BufferGraph.MapDownToBuffer(span, SpanTrackingMode.EdgeInclusive, window.CurrentLanguageBuffer)) { normalizedSpan.Snapshot.TextBuffer.Delete(normalizedSpan); } } } var curBuffer = window.CurrentLanguageBuffer; if (curBuffer.CurrentSnapshot.Length > 0) { // There is existing content in the buffer, so let's just insert and // return. We do submit any statements. window.InsertCode(pasting); return; } var inputPoint = view.BufferGraph.MapDownToBuffer( caret.Position.BufferPosition, PointTrackingMode.Positive, curBuffer, PositionAffinity.Successor ); // if we didn't find a location then see if we're in a prompt, and if so, then we want // to insert after the prompt. if (caret.Position.BufferPosition != window.TextView.TextBuffer.CurrentSnapshot.Length) { for (int i = caret.Position.BufferPosition + 1; inputPoint == null && i <= window.TextView.TextBuffer.CurrentSnapshot.Length; i++) { inputPoint = view.BufferGraph.MapDownToBuffer( new SnapshotPoint(window.TextView.TextBuffer.CurrentSnapshot, i), PointTrackingMode.Positive, curBuffer, PositionAffinity.Successor ); } } bool submitLast = pasting.EndsWithOrdinal("\n"); if (inputPoint == null) { // we didn't find a point to insert, insert at the beginning. inputPoint = new SnapshotPoint(curBuffer.CurrentSnapshot, 0); } // we want to insert the pasted code at the caret, but we also want to // respect the stepping. So first grab the code before and after the caret. var splitCode = JoinToCompleteStatements(SplitAndDedent(pasting), version).ToList(); curBuffer.Delete(new Span(0, curBuffer.CurrentSnapshot.Length)); bool supportMultiple = await window.GetSupportsMultipleStatements(); if (supportMultiple) { window.InsertCode(string.Join(Environment.NewLine, splitCode)); } else if (splitCode.Count == 1) { curBuffer.Insert(0, splitCode[0]); var viewPoint = view.BufferGraph.MapUpToBuffer( new SnapshotPoint(curBuffer.CurrentSnapshot, Math.Min(inputPoint.Value.Position + pasting.Length, curBuffer.CurrentSnapshot.Length)), PointTrackingMode.Positive, PositionAffinity.Successor, view.TextBuffer ); if (viewPoint != null) { view.Caret.MoveTo(viewPoint.Value); } } else if (splitCode.Count != 0) { var lastCode = splitCode[splitCode.Count - 1]; splitCode.RemoveAt(splitCode.Count - 1); while (splitCode.Any()) { var code = splitCode[0]; splitCode.RemoveAt(0); await window.SubmitAsync(new[] { code }); supportMultiple = await window.GetSupportsMultipleStatements(); if (supportMultiple) { // Might have changed while we were executing break; } } if (supportMultiple) { // Insert all remaning lines of code lastCode = string.Join(Environment.NewLine, splitCode); } window.InsertCode(lastCode); } else { window.InsertCode(pasting); } if (submitLast) { if (window.Evaluator.CanExecuteCode(window.CurrentLanguageBuffer.CurrentSnapshot.GetText())) { window.Operations.ExecuteInput(); } else { window.InsertCode("\n"); } } }
private static IEnumerable <ICompletionListProvider> GetCompletionProviders(PaketDocument paketDocument, ITextStructureNavigator navigator, SnapshotPoint position, out CompletionContext context) { context = GetCompletionContext(paketDocument, navigator, position); return(GetCompletionProviders(context.ContextType)); }