protected override void Modify(ITextEdit edit, ITextSnapshotLine line) { if (line.GetText().StartsWith("#")) { edit.Delete(line.Start, 1); } }
//===================================================================== /// <summary> /// Constructor /// </summary> /// <param name="line">The line snapshot</param> /// <param name="state">The starting state</param> /// <param name="naturalTextSpans">The collection of natural text spans</param> public LineProgress(ITextSnapshotLine line, State state, List<SnapshotSpan> naturalTextSpans) { _snapshotLine = line; _lineText = line.GetText(); _linePosition = 0; _naturalTextSpans = naturalTextSpans; this.State = state; }
internal static bool CommentLine(ITextSnapshotLine line) { string lineText = line.GetText(); if (!string.IsNullOrWhiteSpace(lineText)) { int leadingWsLength = lineText.Length - lineText.TrimStart().Length; line.Snapshot.TextBuffer.Insert(line.Start + leadingWsLength, "#"); return true; } return false; }
internal static bool UncommentLine(ITextSnapshotLine line) { string lineText = line.GetText(); if (!string.IsNullOrWhiteSpace(lineText)) { int leadingWsLength = lineText.Length - lineText.TrimStart().Length; if (leadingWsLength < lineText.Length) { if (lineText[leadingWsLength] == '#') { line.Snapshot.TextBuffer.Delete(new Span(line.Start + leadingWsLength, 1)); return true; } } } return false; }
private static bool IsPropertyValueEligible(ITextSnapshotLine line, int position) { string text = line.GetText(); int diff = text.Length - text.TrimEnd().Length; if (line.End.Position - diff > position) { return(false); } if (text.IndexOf(';') > -1) { return(false); } return(true); }
private static void DeleteFirstCommentChar(ITextEdit edit, ITextSnapshotLine curLine) { var text = curLine.GetText(); for (int j = 0; j < text.Length - 1; j++) { if (!Char.IsWhiteSpace(text[j])) { if (text[j] == '/' && text[j + 1] == '/') { edit.Delete(curLine.Start.Position + j, 2); } break; } } }
/// <summary> /// Returns the last non-whitespace position on the given line, or null if /// the line is empty or contains only whitespace. /// </summary> public static int?GetLastNonWhitespacePosition(this ITextSnapshotLine line) { Contract.ThrowIfNull(line); int startPosition = line.Start; var text = line.GetText(); for (int i = text.Length - 1; i >= 0; i--) { if (!char.IsWhiteSpace(text[i])) { return(startPosition + i); } } return(null); }
public static bool HasReservedBlockKeywords(ITextSnapshotLine start, params string[] nativelySupportedTokens) { try { var tagger = start.Snapshot.TextBuffer.Properties.GetProperty <ITagger <ClassificationTag> >(jsTaggerType); var classifications = tagger.GetTags(new NormalizedSnapshotSpanCollection(start.Extent)); return(classifications.Any(tag => !tag.Tag.ClassificationType.IsOfType("comment") && tag.Tag.ClassificationType.IsOfType("keyword") && nativelySupportedTokens.Contains(tag.Span.GetText()))); } catch { return(start.GetText().Trim().Split(PunctuationCharacters) .Any(word => nativelySupportedTokens.Contains(word))); } }
private IList <IToken> getTokensInLine(ITextSnapshotLine line) { IList <IToken> tokens = new List <IToken>(); ITextBuffer textBuffer = line.Snapshot.TextBuffer; // Already been lexed ? if (getBufferedTokens(out var xTokens, textBuffer)) { var allTokens = xTokens.TokenStream.GetTokens(); if (allTokens != null) { if (xTokens.SnapShot.Version == textBuffer.CurrentSnapshot.Version) { // Ok, use it int startIndex = -1; // Move to the line position for (int i = 0; i < allTokens.Count; i++) { if (allTokens[i].StartIndex >= line.Start.Position) { startIndex = i; break; } } if (startIndex > -1) { // Move to the end of line int currentLine = allTokens[startIndex].Line; do { tokens.Add(allTokens[startIndex]); startIndex++; } while ((startIndex < allTokens.Count) && (currentLine == allTokens[startIndex].Line)); return(tokens); } } } } // Ok, do it now var text = line.GetText(); tokens = getTokens(text); return(tokens); // }
public async Task SendToReplTest() { string content = "x <- 1\r\ny <- 2\r\n"; var editorBuffer = new TextBufferMock(content, RContentTypeDefinition.ContentType); var tv = new TextViewMock(editorBuffer); var commandFactory = new VsRCommandFactory(_workflowProvider); var commands = UIThreadHelper.Instance.Invoke(() => commandFactory.GetCommands(tv, editorBuffer)); await _workflow.RSession.HostStarted.Should().BeCompletedAsync(); await UIThreadHelper.Instance.Invoke(() => _workflow.GetOrCreateVisualComponentAsync()); _workflow.ActiveWindow.Should().NotBeNull(); var command = commands.OfType <SendToReplCommand>() .Should().ContainSingle().Which; var replBuffer = _workflow.ActiveWindow.InteractiveWindow.CurrentLanguageBuffer; _workflow.ActiveWindow.Container.IsOnScreen.Should().BeFalse(); Guid group = VSConstants.VsStd11; int id = (int)VSConstants.VSStd11CmdID.ExecuteLineInInteractive; object o = new object(); command.Status(group, id).Should().Be(CommandStatus.SupportedAndEnabled); command.Invoke(group, id, null, ref o); replBuffer.CurrentSnapshot.GetText().Trim().Should().Be("x <- 1"); int caretPos = tv.Caret.Position.BufferPosition.Position; int lineNum = editorBuffer.CurrentSnapshot.GetLineNumberFromPosition(caretPos); lineNum.Should().Be(1); tv.Selection.Select(new SnapshotSpan(editorBuffer.CurrentSnapshot, new Span(0, 1)), false); command.Invoke(group, id, null, ref o); ITextSnapshotLine line = replBuffer.CurrentSnapshot.GetLineFromLineNumber(1); line.GetText().Trim().Should().Be("x"); _workflow.ActiveWindow.Dispose(); }
private SnapshotPoint GetCaretPositionFromCellPosition(ITextSnapshotLine line, int cellPosition) { var lineText = line.GetText(); var linePosition = 0; while (cellPosition > 0 && linePosition >= 0) { linePosition = lineText.IndexOf('|', linePosition) + 1; cellPosition--; } if (linePosition < 0) { return(line.End); } return(line.Start + linePosition); }
/// <summary> /// Determines whether the specified line is empty or contains whitespace only. /// </summary> public static bool IsEmptyOrWhitespace(this ITextSnapshotLine line) { if (line == null) { return(true); } var text = line.GetText(); for (int i = 0; i < text.Length; i++) { if (!char.IsWhiteSpace(text[i])) { return(false); } } return(true); }
private int?DoBlockIndent(ITextSnapshotLine line) { ITextSnapshotLine previousLine = null; for (int lineNumber = line.LineNumber - 1; lineNumber >= 0; --lineNumber) { previousLine = line.Snapshot.GetLineFromLineNumber(lineNumber); string text = previousLine.GetText(); if (text.Length > 0) { return(GetLeadingWhiteSpace(text)); } } return(null); }
private StructureTag CreateTag(Span outline) { ITextSnapshotLine line = _buffer.CurrentSnapshot.GetLineFromPosition(outline.Start); var firstLineText = line.GetText().Trim(); return(new StructureTag( _buffer.CurrentSnapshot, outliningSpan: outline, headerSpan: line.Extent, guideLineSpan: outline, guideLineHorizontalAnchor: outline.Start, type: PredefinedStructureTagTypes.Nonstructural, isCollapsible: true, collapsedForm: _isShortCollapsedForm ? _shortCollapsedForm : firstLineText, collapsedHintForm: firstLineText, isDefaultCollapsed: true )); }
/// <summary> /// Returns the first non-whitespace position on the given line as an offset /// from the start of the line, or null if the line is empty or contains only /// whitespace. /// </summary> public static int?GetFirstNonWhitespaceOffset(this ITextSnapshotLine line) { if (line == null) { return(null); } var text = line.GetText(); for (int i = 0; i < text.Length; i++) { if (!char.IsWhiteSpace(text[i])) { return(i); } } return(null); }
/// <summary> /// Gets the index of the first non-whitespace character on a line, or the length of the line if the line is /// empty or only contains whitespace. /// </summary> /// <param name="line">The line to examine.</param> /// <returns> /// <para>The index of the first non-whitespace character on a line.</para> /// <para>-or-</para> /// <para>The length of the line if the line is empty or only contains whitespace.</para> /// </returns> /// <exception cref="ArgumentNullException">If <paramref name="line"/> is <see langword="null"/>.</exception> protected static int ScanToNonWhitespaceChar(ITextSnapshotLine line) { if (line == null) { throw new ArgumentNullException(nameof(line)); } string text = line.GetText(); int len = text.Length; int i = 0; while (i < len && char.IsWhiteSpace(text[i])) { i++; } return(i); }
/// <summary> /// return insertion point for the ending string /// </summary> private static int?GetInsertionPositionForEndingString( Document document, ITextSnapshotLine line, CancellationToken cancellationToken ) { var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken); var text = root.SyntaxTree.GetText(cancellationToken); var syntaxFacts = document.GetRequiredLanguageService <ISyntaxFactsService>(); // find last token on the line var token = syntaxFacts.FindTokenOnLeftOfPosition(root, line.End); if (token.RawKind == 0) { return(null); } // bug # 16770 // don't do anything if token is multiline token such as verbatim string if (line.End < token.Span.End) { return(null); } // if there is only whitespace, token doesn't need to be on same line if ( string.IsNullOrWhiteSpace( text.ToString(TextSpan.FromBounds(token.Span.End, line.End)) ) ) { return(line.End); } // if token is on different line than caret but caret line is empty, we insert ending point at the end of the line if (text.Lines.IndexOf(token.Span.End) != text.Lines.IndexOf(line.End)) { return(string.IsNullOrWhiteSpace(line.GetText()) ? (int?)line.End : null); } return(token.Span.End); }
private static IKeywordScopeStatement GetFormatScope(ITextView textView, ITextBuffer textBuffer, AstRoot ast) { SnapshotPoint?caret = REditorDocument.MapCaretPositionFromView(textView); if (caret.HasValue) { try { int lineNumber = textBuffer.CurrentSnapshot.GetLineNumberFromPosition(caret.Value.Position); ITextSnapshotLine line = textBuffer.CurrentSnapshot.GetLineFromLineNumber(lineNumber); string lineText = line.GetText(); if (lineText.TrimEnd().EndsWith("}", StringComparison.Ordinal)) { IKeywordScopeStatement scopeStatement = ast.GetNodeOfTypeFromPosition <IKeywordScopeStatement>(caret.Value); return(scopeStatement); } } catch (Exception) { } } return(null); }
void ICompletionSource.AugmentCompletionSession(ICompletionSession session, IList <CompletionSet> completionSets) { //get tracking span ITrackingSpan trackingSpan = FindTokenSpanAtPosition(session.GetTriggerPoint(_textBuffer), session); //find current indent ITextSnapshot snapshot = session.TextView.TextSnapshot; SnapshotPoint currentPoint = trackingSpan.GetStartPoint(snapshot); ITextSnapshotLine snapshotLine = snapshot.GetLineFromPosition(currentPoint); string wordText = trackingSpan.GetText(snapshot); string lineText = snapshotLine.GetText(); int lineStartPos = snapshotLine.Start.Position; int lineEndPos = snapshotLine.End.Position; int currentPos = currentPoint.Position; int indent = currentPos - lineStartPos; if (wordText == ".") { indent++; } //build completion list List <Completion> completionList = new List <Completion>(); //insert snippets foreach (Snippet snippet in Session.Current.Settings.Snippets) { completionList.Add(new SnippetCompletion(snippet, indent)); } //add completion set if it contains any entries if (completionList.Count > 0) { completionSets.Add(new CompletionSet( "Snippets", //the non-localized title of the tab "Snippets", //the display title of the tab trackingSpan, completionList, null)); } }
internal static bool UncommentLine(ITextSnapshotLine line) { var lineText = line.GetText(); if (!string.IsNullOrWhiteSpace(lineText)) { int leadingWsLength = lineText.Length - lineText.TrimStart().Length; if (leadingWsLength < lineText.Length) { if (lineText[leadingWsLength] == '#') { line.Snapshot.TextBuffer.Delete(new Span(line.Start + leadingWsLength, 1)); return(true); } } } return(false); }
/// <summary> /// Tries to move region start point up to get C#-like outlining /// /// for (var k in obj) /// { -- from here /// /// for (var k in obj) -- to here /// { /// </summary> private void ExtendStartPoint() { //some are not extended if (!Complete || StartLine.LineNumber == EndLine.LineNumber || !string.IsNullOrWhiteSpace(TextBefore)) { return; } //how much can we move region start int upperLimit = 0; if (this.Parent != null) { int childPosition = Parent.Children.IndexOf(this); if (childPosition == 0) { //this region is first child of its parent //we can go until the parent's start upperLimit = Parent.RegionType != TextRegionType.None ? Parent.StartLine.LineNumber + 1 : 0; } else { //there is previous child //we can go until its end TextRegion prevRegion = Parent.Children[childPosition - 1]; upperLimit = prevRegion.EndLine.LineNumber + (prevRegion.EndLine.LineNumber == prevRegion.StartLine.LineNumber ? 0 : 1); } } //now looking up to calculated upper limit for non-empty line for (int i = StartLine.LineNumber - 1; i >= upperLimit; i--) { ITextSnapshotLine line = StartPoint.Snapshot.GetLineFromLineNumber(i); if (!string.IsNullOrWhiteSpace(line.GetText())) { //found such line, placing region start at its end StartPoint = line.End; return; } } }
public IEnumerable <ITagSpan <Visual64TassTokenTag> > GetTags(NormalizedSnapshotSpanCollection spans) { var tokenizer = new Tokenizer(); foreach (SnapshotSpan currentSpan in spans) { ITextSnapshotLine containingLine = currentSpan.Start.GetContainingLine(); int lineStartPos = containingLine.Start.Position; foreach (var token in tokenizer.Tokenize(containingLine.GetText())) { var tokenSpan = new SnapshotSpan(currentSpan.Snapshot, new Span(lineStartPos + token.StartPosition, token.Value.Length)); if (tokenSpan.IntersectsWith(currentSpan)) { yield return(new TagSpan <Visual64TassTokenTag>(tokenSpan, new Visual64TassTokenTag(token))); } } } }
private static void TrimTrailingWhitespace(IWpfTextView view) { ITextSnapshot snapshot = view.TextSnapshot; var lineCount = snapshot.LineCount; if (lineCount == 0) { return; } using (var edit = snapshot.TextBuffer.CreateEdit()) { for (int i = 0; i < lineCount; i++) { ITextSnapshotLine line = snapshot.GetLineFromLineNumber(i); int length = line.Length; if (length == 0) { continue; } string content = line.GetText(); int pos = length - 1; while (IsWhiteSpace(content[pos])) { pos--; } if (pos == length - 1) { continue; } edit.Delete(line.Start.Position + pos + 1, length - 1 - pos); } edit.Apply(); } }
private static string GetPaddingOrIndentation(ITextSnapshotLine currentLine, int caretPosition, int firstNonWhitespacePosition, string exteriorText) { Debug.Assert(caretPosition >= firstNonWhitespacePosition + exteriorText.Length); var firstNonWhitespaceOffset = firstNonWhitespacePosition - currentLine.Start; Debug.Assert(firstNonWhitespaceOffset > -1); var lineText = currentLine.GetText(); if ((lineText.Length == firstNonWhitespaceOffset + exteriorText.Length)) { // *| return(" "); } var interiorText = lineText.Substring(firstNonWhitespaceOffset + exteriorText.Length); var interiorFirstNonWhitespaceOffset = interiorText.GetFirstNonWhitespaceOffset() ?? -1; if (interiorFirstNonWhitespaceOffset == 0) { // /****| return(" "); } var interiorFirstWhitespacePosition = firstNonWhitespacePosition + exteriorText.Length; if (interiorFirstNonWhitespaceOffset == -1 || caretPosition <= interiorFirstWhitespacePosition + interiorFirstNonWhitespaceOffset) { // * | // or // * | 1. // ^^ return(currentLine.Snapshot.GetText(interiorFirstWhitespacePosition, caretPosition - interiorFirstWhitespacePosition)); } else { // * 1. | // ^^^ return(currentLine.Snapshot.GetText(interiorFirstWhitespacePosition, interiorFirstNonWhitespaceOffset)); } }
public IEnumerable <ITagSpan <SiTokenTag> > GetTags(NormalizedSnapshotSpanCollection spans) { foreach (SnapshotSpan curSpan in spans) { ITextSnapshotLine containingLine = curSpan.Start.GetContainingLine(); int position = containingLine.Start.Position; var tokens = new List <SiToken>(); tokenizer.getTokens(tokens, containingLine.GetText().ToLower(), position, IsSqlSection(containingLine)); foreach (SiToken token in tokens) { int pos = position + (token.position - token.value.Length); var tokenSpan = new SnapshotSpan(curSpan.Snapshot, new Span(pos, token.value.Length)); var tokenTag = new SiTokenTag(token.tokenType); if (tokenSpan.IntersectsWith(curSpan)) { yield return(new TagSpan <SiTokenTag>(tokenSpan, tokenTag)); } } } }
public IEnumerable <ITagSpan <PrologTokenTag> > GetTags(NormalizedSnapshotSpanCollection spans) { foreach (SnapshotSpan curSpan in spans) { ITextSnapshotLine containingLine = curSpan.Start.GetContainingLine(); int curLoc = containingLine.Start.Position; string formattedLine = containingLine.GetText(); foreach (SnapshotHelper item in PrologCodeHelper.GetTokens(curSpan)) { if (item.Snapshot.IntersectsWith(curSpan)) { yield return(new TagSpan <PrologTokenTag>(item.Snapshot, new PrologTokenTag(item.TokenType))); } } //add an extra char location because of the space curLoc += formattedLine.Length + 1; } }
/// <summary> /// Determines which <see cref="T:Microsoft.VisualStudio.Language.Intellisense.CompletionSet"/>s should be part of the specified <see cref="T:Microsoft.VisualStudio.Language.Intellisense.ICompletionSession"/>. /// </summary> /// <param name="session">The session for which completions are to be computed.</param><param name="completionSets">The set of the completionSets to be added to the session.</param> /// <remarks> /// Each applicable <see cref="M:Microsoft.VisualStudio.Language.Intellisense.ICompletionSource.AugmentCompletionSession(Microsoft.VisualStudio.Language.Intellisense.ICompletionSession,System.Collections.Generic.IList{Microsoft.VisualStudio.Language.Intellisense.CompletionSet})"/> instance will be called in-order to /// (re)calculate a <see cref="T:Microsoft.VisualStudio.Language.Intellisense.ICompletionSession"/>. <see cref="T:Microsoft.VisualStudio.Language.Intellisense.CompletionSet"/>s can be added to the session by adding /// them to the completionSets collection passed-in as a parameter. In addition, by removing items from the collection, a /// source may filter <see cref="T:Microsoft.VisualStudio.Language.Intellisense.CompletionSet"/>s provided by <see cref="T:Microsoft.VisualStudio.Language.Intellisense.ICompletionSource"/>s earlier in the calculation /// chain. /// </remarks> public void AugmentCompletionSession(ICompletionSession session, IList <CompletionSet> completionSets) { ITextSnapshot snapshot = session.TextView.TextBuffer.CurrentSnapshot; SnapshotPoint?triggerPoint = session.GetTriggerPoint(snapshot); if (!triggerPoint.HasValue) { return; } ITextSnapshotLine line = snapshot.GetLineFromPosition(triggerPoint.Value); string lineString = line.GetText(); SimpleExpansion expansion; expansion = GetExpansions(lineString, triggerPoint.Value); if (expansion == null) { return; } List <Completion> completions = new List <Completion>(); foreach (string str in expansion.Expansions) { completions.Add(new Completion(str, str, null, null, null)); } SnapshotPoint point = session.TextView.Caret.Position.BufferPosition; ITrackingSpan applicableTo = point.Snapshot.CreateTrackingSpan( (Span) new SnapshotSpan(point + expansion.Start, expansion.Length), SpanTrackingMode.EdgeInclusive); completionSets.Add(new CompletionSet(LanguageConfiguration.Name, LanguageConfiguration.Name, applicableTo, completions, null)); }
int ReParse_Procedure(ITextSnapshotLine line, List <Region> newRegions) { string text = line.GetText(); Region rgn = null; // PROC, open a new region if (CompareKeyword(text, ProcKeywords[0])) { // PROC can't be nested if (m_regionStack.Count > 0 && m_regionStack.Peek().Type == RegionType.RT_Procedure) { return(parse_skip); } m_regionStack.Push(new Region() { Type = RegionType.RT_Procedure, StartLine = line.LineNumber, StartOffset = line.Length }); } // ENDP, close current region else if (CompareKeyword(text, ProcKeywords[1])) { // ENDP must exist if (m_regionStack.Count == 0 || m_regionStack.Peek().Type != RegionType.RT_Procedure) { return(parse_skip); } rgn = m_regionStack.Pop(); rgn.EndLine = line.LineNumber; newRegions.Add(rgn); } else { return(parse_fail); } return(parse_success); }
public IList <ClassificationSpan> GetClassificationSpans(SnapshotSpan span) { if (span.IsEmpty || _view == null) { return(_empty); } IList <ClassificationSpan> list = new List <ClassificationSpan>(); ITextSnapshotLine line = span.Snapshot.GetLineFromPosition(span.Start.Position); if (_caret > 0 && (line.Extent.Contains(_caret.Position) || line.Extent.End.Position == _caret.Position)) { _span = span.Snapshot.CreateTrackingSpan(line.Extent, SpanTrackingMode.EdgeExclusive); return(_empty); } IProjectionBuffer projection = span.Snapshot.TextBuffer as IProjectionBuffer; if (projection != null) { SnapshotPoint point = projection.CurrentSnapshot.MapToSourceSnapshot(line.Start + line.Length); ITextSnapshotLine basePoint = point.Snapshot.GetLineFromPosition(point.Position); if (basePoint.Length > line.Length) { return(_empty); } } string text = line.GetText(); string trimmed = text.TrimEnd(); int diff = text.Length - trimmed.Length; if (diff > 0) { SnapshotSpan ss = new SnapshotSpan(span.Snapshot, line.Start + line.Length - diff, diff); list.Add(new ClassificationSpan(ss, _whitespace)); } return(list); }
/// <summary> /// Implement interface <seealso cref="ITagger{T}"/>. /// </summary> public IEnumerable <ITagSpan <StackdriverTag> > GetTags(NormalizedSnapshotSpanCollection spans) { // Note, keep a local copy of ActiveTagData.Current. // In case ActiveTagData.Current changes by other thread or by async re-entrancy. var activeData = ActiveTagData.Current; if (activeData?.TextView != _view || spans.Count == 0) { Debug.WriteLine($"TooltipSource.TextView != _view is {ActiveTagData.Current?.TextView != _view}, spans.Count is {spans.Count}"); HideTooltip(); yield break; } ITextSnapshotLine textLine = _sourceBuffer.CurrentSnapshot.GetLineFromLineNumber((int)activeData.SourceLine - 1); string text = textLine.GetText(); SnapshotSpan span; if (String.IsNullOrWhiteSpace(activeData.MethodName) || !text.Contains(activeData.MethodName)) { int begin = StringUtils.FirstNonSpaceIndex(text); int end = StringUtils.LastNonSpaceIndex(text); if (begin == -1 || end == -1) { yield break; } span = new SnapshotSpan(textLine.Start + begin, end - begin + 1); } else { int pos = text.IndexOf(activeData.MethodName); if (pos < 0) { HideTooltip(); yield break; } span = new SnapshotSpan(textLine.Start + pos, activeData.MethodName.Length); } yield return(new TagSpan <StackdriverTag>(span, s_emptyLoggerTag)); DisplayTooltip(new SnapshotSpan(textLine.Start, textLine.Length)); }
protected override void Run() { Document document = IdeApp.Workbench.ActiveDocument; if (document == null) { return; } var view = document.GetContent <ITextView> (); if (view == null) { return; } ITextSnapshotLine line = view.Caret.Position.BufferPosition.GetContainingLine(); string text = line.GetText(); CSharpInteractivePad.EvaluateText(text); }
private SnapshotSpan?MatchLine(ITextSnapshotLine snapshotLine) { var text = snapshotLine.GetText(); var match = s_commentRegex.Match(text); if (!match.Success) { return(null); } var group = match.Groups["word"]; if (!Constants.Words.Contains(group.Value)) { return(null); } var startPoint = snapshotLine.Start.Add(group.Index); return(new SnapshotSpan(startPoint, snapshotLine.End)); }
public void AssignParameterToField() { ITextSnapshot snapshot = view.TextBuffer.CurrentSnapshot; int pos = view.Caret.Position.BufferPosition.Position; Declaration declaration = FindDeclarationNear(snapshot, pos, new char[] { '(', ',' }, new char[] { ',', ')', '=' }); if (declaration == null) { throw new UnrecognisedParameterDeclarationException(); } int assignmentLineNumber = FindLineBeforeWhichToInsertMethodStatement(snapshot, declaration.Span.End); if (assignmentLineNumber < 0) { throw new FailedInsertionPointException("Failed to find insertion point before assignment."); } ITextSnapshotLine assignmentLine = snapshot.GetLineFromLineNumber(assignmentLineNumber); int lineNumber = FindLineAfterWhichToInsertFieldDeclaration(snapshot, assignmentLine.Start.Position); if (lineNumber < 0) { throw new FailedInsertionPointException(); } // add assignment of parameter to method. ITextEdit edit = snapshot.TextBuffer.CreateEdit(); int assignmentIndent = FindIndentOfLine(assignmentLine.GetText()) + TabSize; edit.Insert(assignmentLine.Start.Position, ("".PadLeft(assignmentIndent) + "this." + declaration.VariableName + " = " + declaration.VariableName + ";\n")); // Add declaration. int indentSize = GetIndentOfNextNonBlankLine(snapshot, lineNumber); edit.Insert(snapshot.GetLineFromLineNumber(lineNumber + 1).Start.Position, ("".PadLeft(indentSize) + "private " + declaration.ToString() + ";\n")); edit.Apply(); }
private int GetIndentLevelOfLine(ITextSnapshotLine line, int tabSize) { var indentLevel = 0; foreach (var c in line.GetText()) { if (!char.IsWhiteSpace(c)) { break; } else if (c == '\t') { indentLevel += tabSize; } else { indentLevel++; } } return(indentLevel); }
private bool IsCommented(ITextSnapshotLine line) { return line.GetText().TrimStart().StartsWith("#"); }
private int GetIndentLevelOfLine(ITextSnapshotLine line) { int optionValue = _textView.Options.GetOptionValue<int>(DefaultOptions.TabSizeOptionId); int num = 0; string text = line.GetText(); for (int i = 0; i < text.Length; i++) { char c = text[i]; if (!char.IsWhiteSpace(c)) { break; } if (c == '\t') { num += optionValue; } else { num++; } } return num; }
CodeLineType CurrentLineType(ITextSnapshotLine tsl) { if(tsl == null) { throw new NullReferenceException(); } string originStr = tsl.GetText(); //more types to be added, currently only normal or blank if(Regex.IsMatch(originStr, rx_nonwhite)) { //add more types here return CodeLineType.Normal; } else return CodeLineType.Blank; }
protected static int ScanToNonWhitespaceChar(ITextSnapshotLine line) { Contract.Requires<ArgumentNullException>(line != null, "line"); string text = line.GetText(); int len = text.Length; int i = 0; while (i < len && char.IsWhiteSpace(text[i])) { i++; } return i; }
private static int CalculateIndentation(string baseline, ITextSnapshotLine line, IEditorOptions options, IClassifier classifier, ITextView textView) { int indentation = GetIndentation(baseline, options.GetTabSize()); int tabSize = options.GetIndentSize(); var tokens = classifier.GetClassificationSpans(line.Extent); if (tokens.Count > 0 && !IsUnterminatedStringToken(tokens[tokens.Count - 1])) { int tokenIndex = tokens.Count - 1; while (tokenIndex >= 0 && (tokens[tokenIndex].ClassificationType.IsOfType(PredefinedClassificationTypeNames.Comment) || tokens[tokenIndex].ClassificationType.IsOfType(PredefinedClassificationTypeNames.WhiteSpace))) { tokenIndex--; } if (tokenIndex < 0) { return indentation; } if (ReverseExpressionParser.IsExplicitLineJoin(tokens[tokenIndex])) { // explicit line continuation, we indent 1 level for the continued line unless // we're already indented because of multiple line continuation characters. indentation = GetIndentation(line.GetText(), options.GetTabSize()); var joinedLine = tokens[tokenIndex].Span.Start.GetContainingLine(); if (joinedLine.LineNumber > 0) { var prevLineSpans = classifier.GetClassificationSpans(tokens[tokenIndex].Span.Snapshot.GetLineFromLineNumber(joinedLine.LineNumber - 1).Extent); if (prevLineSpans.Count == 0 || !ReverseExpressionParser.IsExplicitLineJoin(prevLineSpans[prevLineSpans.Count - 1])) { indentation += tabSize; } } else { indentation += tabSize; } return indentation; } string sline = tokens[tokenIndex].Span.GetText(); var lastChar = sline.Length == 0 ? '\0' : sline[sline.Length - 1]; // use the expression parser to figure out if we're in a grouping... var spans = textView.BufferGraph.MapDownToFirstMatch( tokens[tokenIndex].Span, SpanTrackingMode.EdgePositive, PythonContentTypePrediciate ); if (spans.Count == 0) { return indentation; } var revParser = new ReverseExpressionParser( spans[0].Snapshot, spans[0].Snapshot.TextBuffer, spans[0].Snapshot.CreateTrackingSpan( spans[0].Span, SpanTrackingMode.EdgePositive ) ); var tokenStack = new System.Collections.Generic.Stack<ClassificationSpan>(); tokenStack.Push(null); // end with an implicit newline bool endAtNextNull = false; foreach (var token in revParser) { tokenStack.Push(token); if (token == null && endAtNextNull) { break; } else if (token != null && token.ClassificationType == revParser.Classifier.Provider.Keyword && PythonKeywords.IsOnlyStatementKeyword(token.Span.GetText())) { endAtNextNull = true; } } var indentStack = new System.Collections.Generic.Stack<LineInfo>(); var current = LineInfo.Empty; while (tokenStack.Count > 0) { var token = tokenStack.Pop(); if (token == null) { current.NeedsUpdate = true; } else if (token.IsOpenGrouping()) { indentStack.Push(current); var start = token.Span.Start; var line2 = start.GetContainingLine(); var next = tokenStack.Count > 0 ? tokenStack.Peek() : null; if (next != null && next.Span.End <= line2.End) { current = new LineInfo { Indentation = start.Position - line2.Start.Position + 1 }; } else { current = new LineInfo { Indentation = GetIndentation(line2.GetText(), tabSize) + tabSize }; } } else if (token.IsCloseGrouping()) { if (indentStack.Count > 0) { current = indentStack.Pop(); } else { current.NeedsUpdate = true; } } else if (ReverseExpressionParser.IsExplicitLineJoin(token)) { while (token != null && tokenStack.Count > 0) { token = tokenStack.Pop(); } } else if (current.NeedsUpdate == true) { var line2 = token.Span.Start.GetContainingLine(); current = new LineInfo { Indentation = GetIndentation(line2.GetText(), tabSize) }; } if (token != null && ShouldDedentAfterKeyword(token)) { // dedent after some statements current.ShouldDedentAfter = true; } if (token != null && token.Span.GetText() == ":" && // indent after a colon indentStack.Count == 0) { // except in a grouping current.ShouldIndentAfter = true; // If the colon isn't at the end of the line, cancel it out. // If the following is a ShouldDedentAfterKeyword, only one dedent will occur. current.ShouldDedentAfter = (tokenStack.Count != 0 && tokenStack.Peek() != null); } } indentation = current.Indentation + (current.ShouldIndentAfter ? tabSize : 0) - (current.ShouldDedentAfter ? tabSize : 0); } // Map indentation back to the view's text buffer. int offset = 0; var viewLineStart = textView.BufferGraph.MapUpToSnapshot(line.Start, PointTrackingMode.Positive, PositionAffinity.Successor, textView.TextSnapshot); if (viewLineStart.HasValue) { offset = viewLineStart.Value.Position - viewLineStart.Value.GetContainingLine().Start.Position; } return offset + indentation; }
public static string GetItemAtPosition(ITextSnapshotLine line, int position, Func<RTokenType, bool> tokenTypeCheck, out Span span) { string lineText = line.GetText(); var offset = 0; var positionInTokens = position - line.Start; var tokenizer = new RTokenizer(); var tokens = tokenizer.Tokenize(lineText); var tokenIndex = tokens.GetItemContaining(positionInTokens); if (tokenIndex >= 0) { var token = tokens[tokenIndex]; if (token.TokenType == RTokenType.Comment) { // Tokenize inside comment since we do want F1 to work inside // commented out code, code samples or Roxygen blocks. positionInTokens -= token.Start; offset = token.Start + 1; tokens = tokenizer.Tokenize(lineText.Substring(offset, token.Length - 1)); tokenIndex = tokens.GetItemContaining(positionInTokens); if (tokenIndex >= 0) { token = tokens[tokenIndex]; } } if (tokenTypeCheck(token.TokenType)) { var start = token.Start + offset; var end = Math.Min(start + token.Length, line.End); span = Span.FromBounds(line.Start + start, line.Start + end); // return view span return lineText.Substring(start, end - start); } } span = Span.FromBounds(0, 0); return string.Empty; }
private string GetCommentText(CommentType commentType, ITextSnapshotLine line) { return line.GetText().Substring(GetCommentIndent(commentType, line) + commentType.Token.Length).Trim(); }
private static bool IsPropertyNameEligible(ITextSnapshotLine line) { return !line.GetText().Contains(":"); }
private static bool IsPropertyValueEligible(ITextSnapshotLine line, int position) { string text = line.GetText(); int diff = text.Length - text.TrimEnd().Length; if (line.End.Position - diff > position) return false; if (text.IndexOf(';') > -1) return false; return true; }
public static int OuterIndentSizeFromLine(ITextSnapshotLine line, RFormatOptions options) { string lineText = line.GetText(); string leadingWhitespace = lineText.Substring(0, lineText.Length - lineText.TrimStart().Length); return IndentBuilder.TextIndentInSpaces(leadingWhitespace, options.TabSize); }
private static string GetPaddingOrIndentation(ITextSnapshotLine currentLine, int caretPosition, int firstNonWhitespacePosition, string exteriorText) { Debug.Assert(caretPosition >= firstNonWhitespacePosition + exteriorText.Length); var firstNonWhitespaceOffset = firstNonWhitespacePosition - currentLine.Start; Debug.Assert(firstNonWhitespaceOffset > -1); var lineText = currentLine.GetText(); if ((lineText.Length == firstNonWhitespaceOffset + exteriorText.Length)) { // *| return " "; } var interiorText = lineText.Substring(firstNonWhitespaceOffset + exteriorText.Length); var interiorFirstNonWhitespaceOffset = interiorText.GetFirstNonWhitespaceOffset() ?? -1; if (interiorFirstNonWhitespaceOffset == 0) { // /****| return " "; } var interiorFirstWhitespacePosition = firstNonWhitespacePosition + exteriorText.Length; if (interiorFirstNonWhitespaceOffset == -1 || caretPosition <= interiorFirstWhitespacePosition + interiorFirstNonWhitespaceOffset) { // * | // or // * | 1. // ^^ return currentLine.Snapshot.GetText(interiorFirstWhitespacePosition, caretPosition - interiorFirstWhitespacePosition); } else { // * 1. | // ^^^ return currentLine.Snapshot.GetText(interiorFirstWhitespacePosition, interiorFirstNonWhitespaceOffset); } }
private int? DoSmartIndent(ITextSnapshotLine line) { if (line.LineNumber == 0) { return null; } int? indentation = GetLeadingWhiteSpace(line.GetText()); var classifications = EnumerateClassificationsInReverse( _classifier, line.Snapshot.GetLineFromLineNumber(line.LineNumber - 1).End ); if (classifications.MoveNext()) { var starting = classifications.Current; // first check to see if we're in an unterminated multiline token if (starting != null) { if (starting.Tag.ClassificationType.Classification == "comment" && starting.Span.GetText().StartsWith("/*") && (!starting.Span.GetText().EndsWith("*/") || starting.Span.End.GetContainingLine() == line)) { // smart indent in comment, dont indent return null; } else if (starting.Tag.ClassificationType.Classification == "string") { var text = starting.Span.GetText(); if (!text.EndsWith("\"") && !text.EndsWith("'")) { // smart indent in multiline string, no indent return null; } } } // walk backwards and collect all of the possible tokens that could // be useful here... var tokenStack = new System.Collections.Generic.Stack<ITagSpan<ClassificationTag>>(); tokenStack.Push(null); // end with an implicit newline bool endAtNextNull = false; do { var token = classifications.Current; tokenStack.Push(token); if (token == null && endAtNextNull) { break; } else if (token != null && token.Span.GetText() == "{") { endAtNextNull = true; } } while (classifications.MoveNext()); var indentStack = new System.Collections.Generic.Stack<LineInfo>(); var current = LineInfo.Empty; while (tokenStack.Count > 0) { var token = tokenStack.Pop(); bool didDedent = false; if (token == null) { current.NeedsUpdate = true; } else if (IsOpenGrouping(token)) { if (current.WasIndentKeyword && token.Span.GetText() == "{") { // the indentation statement is followed by braces, go ahead // and remove the level of indentation now current.WasIndentKeyword = false; current.Indentation -= _editorOptions.GetTabSize(); } indentStack.Push(current); var start = token.Span.Start; current = new LineInfo { Indentation = GetLeadingWhiteSpace(start.GetContainingLine().GetText()) + _editorOptions.GetTabSize() }; } else if (_indentKeywords.Contains(token.Span.GetText()) && !current.WasDoKeyword) { // if (foo) // console.log('hi') // We should indent here var start = token.Span.Start; int dedentTo = GetLeadingWhiteSpace(start.GetContainingLine().GetText()); if (current.DedentTo != null && token.Span.GetText() != "if") { // https://nodejstools.codeplex.com/workitem/1176 // if (true) // while (true) // ; // // We should dedent to the if (true) // But for: // if (true) // if (true) // ; // We still want to dedent to our current level for the else dedentTo = current.DedentTo.Value; } current = new LineInfo { Indentation = GetLeadingWhiteSpace(start.GetContainingLine().GetText()) + _editorOptions.GetTabSize(), DedentTo = dedentTo, WasIndentKeyword = true, WasDoKeyword = token.Span.GetText() == "do" }; } else if (IsCloseGrouping(token)) { if (indentStack.Count > 0) { current = indentStack.Pop(); } else { current = new LineInfo { Indentation = GetLeadingWhiteSpace(token.Span.Start.GetContainingLine().GetText()) }; } } else if (IsMultilineStringOrComment(token)) { while (token != null && tokenStack.Count > 0) { token = tokenStack.Pop(); } } else if (current.WasIndentKeyword) { // we've encountered a token after the opening of the indented // statement, go ahead and decrement our indentation level now. current = new LineInfo { Indentation = current.DedentTo, DedentTo = current.DedentTo - _editorOptions.GetTabSize(), WasDoKeyword = current.WasDoKeyword }; didDedent = true; } else if (current.NeedsUpdate) { var line2 = token.Span.Start.GetContainingLine(); current = new LineInfo { Indentation = GetLeadingWhiteSpace(line2.GetText()) }; } if (!didDedent && token != null && _dedentKeywords.Contains(token.Span.GetText())) { // dedent after some statements current.ShouldDedentAfter = true; } } return current.Indentation - (current.ShouldDedentAfter ? _editorOptions.GetTabSize() : 0); } return null; }
private static void DeleteFirstCommentChar(ITextEdit edit, ITextSnapshotLine curLine) { var text = curLine.GetText(); for (int j = 0; j < text.Length; j++) { if (!Char.IsWhiteSpace(text[j])) { if (text[j] == '#') { edit.Delete(curLine.Start.Position + j, 1); } break; } } }
private bool IsSelectorEligible(ITextSnapshotLine line, int position) { string text = line.GetText(); if (text.IndexOf('{') > -1) return false; if (text.Trim().EndsWith(",", StringComparison.Ordinal)) return false; if (line.LineNumber + 1 < line.Snapshot.LineCount) { var next = line.Snapshot.GetLineFromLineNumber(line.LineNumber + 1); if (next.GetText().Trim().StartsWith("{", StringComparison.Ordinal)) return false; } return true; }
/// <summary> /// find how many tabs are there /// </summary> /// <param name="tsl"></param> /// <returns></returns> int GetIndentation(ITextSnapshotLine tsl) { if(tsl == null) { throw new NullReferenceException(); } string originStr = tsl.GetText(); //position of first non-white int firstNonWhite = Regex.Match(originStr, rx_nonwhite).Index; string whiteString = originStr.Substring(0, firstNonWhite); int tabCount = Regex.Matches(whiteString, rx_tab).Count; int spaceCount = Regex.Matches(whiteString, rx_space).Count; tabCount += spaceCount / tab_count; return tabCount; }
private static bool IsSelectorEligible(ITextSnapshotLine line, int position) { string text = line.GetText(); if (text.IndexOf('{') > -1) return false; if (line.Snapshot.ContentType.DisplayName == "LESS") { var commentStart = text.IndexOf("//"); if (commentStart > position) return false; if (commentStart > 0) text = text.Remove(commentStart); } if (text.Trim().EndsWith(",", StringComparison.Ordinal)) return false; if (line.LineNumber + 1 < line.Snapshot.LineCount) { var next = line.Snapshot.GetLineFromLineNumber(line.LineNumber + 1); if (next.GetText().Trim().StartsWith("{", StringComparison.Ordinal)) return false; } return true; }
private static void DeleteCommentChars(ITextEdit edit, ITextSnapshotLine curLine) { var text = curLine.GetText(); for (int j = 0; j < text.Length; j++) { if (!Char.IsWhiteSpace(text[j])) { if (text.Substring(j, 2) == "//") { edit.Delete(curLine.Start.Position + j, 2); } break; } } }
private int InsertSemiColon(ITextSnapshotLine line) { string text = line.GetText(); using (ITextEdit edit = _textView.TextBuffer.CreateEdit()) { _dte.UndoContext.Open("Insert braces"); edit.Replace(line.Extent, text.TrimEnd() + ";\n\t"); edit.Apply(); _dte.UndoContext.Close(); } //SendKeys.Send("^( )"); return VSConstants.S_OK; }
private int GetCommentIndent(CommentType commentType, ITextSnapshotLine line) { return line.GetText().IndexOf(commentType.Token, StringComparison.Ordinal); }
public IEnumerable<SnapshotSpan> Match(ITextSnapshotLine line) { Regex regex = GetRegex(); if ( line.Length == 0 || regex == null ) { yield break; } ITextSnapshot snapshot = line.Snapshot; var matches = GetRegex().Matches(line.GetText()); foreach ( Match m in matches ) { switch ( Options ) { case ExpressionOptions.HideMatch: yield return new SnapshotSpan(snapshot, line.Start + m.Index, m.Length); break; case Util.ExpressionOptions.HideGroups: for ( int g = 1; g < m.Groups.Count; g++ ) { yield return new SnapshotSpan(snapshot, line.Start + m.Groups[g].Index, m.Groups[g].Length); } break; } } }
private CommentType GetCommentType(ITextSnapshotLine line) { var text = line.GetText().Trim(); if (text.StartsWith(_longCommentToken)) return new CommentType(_longCommentToken); if (text.StartsWith(_shortCommentToken)) return new CommentType(_shortCommentToken); return null; }
private static IToken GetActiveToken(int columnIndex, ITextSnapshotLine line) { var tokens = Utils.LexString(line.GetText()); if (columnIndex == line.Length) { var lastToken = tokens.Last(); if (lastToken.Type == RustLexer.RustLexer.IDENT) return lastToken; // fake token for an ident not yet started at the end of the line. return new CommonToken(new Tuple<ITokenSource, ICharStream>(lastToken.TokenSource, lastToken.TokenSource.InputStream), RustLexer.RustLexer.IDENT, 0, columnIndex, columnIndex); } IToken token = null; IToken previousToken = null; foreach (var currentToken in tokens) { if (currentToken.StartIndex <= columnIndex && columnIndex <= currentToken.StopIndex) { token = currentToken; break; } previousToken = currentToken; } if (token == null) { return null; } if (token.Type == RustLexer.RustLexer.IDENT) { return token; } // if current token isn't identifier and caret at end of ident token if (token.StartIndex == columnIndex && previousToken != null && previousToken.Type == RustLexer.RustLexer.IDENT) { return previousToken; } // fake token for position between 2 non-ident tokens return new CommonToken(new Tuple<ITokenSource, ICharStream>(token.TokenSource, token.TokenSource.InputStream), 1, 0, token.StartIndex, token.StartIndex - 1); }
private static void SkipPreceedingBlankLines(ITextSnapshotLine line, out string baselineText, out ITextSnapshotLine baseline) { string text; while (line.LineNumber > 0) { line = line.Snapshot.GetLineFromLineNumber(line.LineNumber - 1); text = line.GetText(); if (!IsBlankLine(text)) { baseline = line; baselineText = text; return; } } baselineText = line.GetText(); baseline = line; }
public void Parse(SnapshotSpan paragraph, IClassificationTypeRegistryService registry, List<ClassificationSpan> classifications) { _registry = registry; _classifications = classifications; var state = HeaderState.Start; var startLine = paragraph.Start.GetContainingLine().LineNumber; var endLine = paragraph.End.GetContainingLine().LineNumber; heading = '\0'; title = null; overline = null; underline = null; for (int i = startLine; i <= endLine; i++) { line = paragraph.Snapshot.GetLineFromLineNumber(i); lineText = line.GetText(); var match = Regex.Match(lineText, adornment); state = match.Success ? TransitionAdornmentLine(state) : TransitionTextLine(state); if (state == HeaderState.Text) { break; } } CreateClassificationSpan(); }
private static int GetFirstNonWhiteSpaceCharacterOnLine(ITextSnapshotLine line) { var text = line.GetText(); for (int i = 0; i < text.Length; i++) { if (!Char.IsWhiteSpace(text[i])) { return line.Start.Position + i; } } return line.End.Position; }
private static string GetItem(ITextSnapshotLine line, int position, Func<char, bool> charSelector, out Span span) { string lineText = line.GetText(); int linePosition = position - line.Start; int start = 0; int end = lineText.Length; for (int i = linePosition - 1; i >= 0; i--) { char ch = lineText[i]; if (!charSelector(ch)) { start = i + 1; break; } } for (int i = linePosition; i < lineText.Length; i++) { char ch = lineText[i]; if (!charSelector(ch)) { end = i; break; } } if (end > start) { span = Span.FromBounds(start + line.Start, end + line.Start); return lineText.Substring(start, end - start); } span = Span.FromBounds(0, 0); return string.Empty; }