//to be modified //constructor public OvLine(Canvas canvas, ITextSnapshotLine itv, float bzCurvArea, OvCollection parent) { _bzCurvArea = bzCurvArea; lnNumber = itv.LineNumber; lnStart = 0.0f; lnTextStart = (float)Find1stChar(itv); //if (lnNumber == 65) System.Diagnostics.Trace.WriteLine("%%% REGEX: " + lnTextStart ); lnEnd = (float)itv.Length; lnHeight = 1.0f; lnLength = itv.Length; lnColor = new System.Windows.Media.Color(); //get the color of the textview lnFocus = false; myCanvas = canvas; myPath = new Path(); myParent = parent; IsSeleted = false; this.myPath.MouseEnter += new System.Windows.Input.MouseEventHandler(myPath_MouseEnter); this.myPath.MouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(myPath_MouseLeftButtonDown); this.myPath.MouseLeave += new System.Windows.Input.MouseEventHandler(myPath_MouseLeave); }
public int PerformMove(IWpfTextView view, ITextSnapshotLine lineToSwap, int insertPosition) { var insertedText = lineToSwap.GetTextIncludingLineBreak(); if(insertPosition == view.TextSnapshot.Length) { // We don't want ot move the line break if the insert position is the last character of the // document but also the first character of the line (i.e. an empty line at the end of the document) var lineUnderInsertPosition = view.TextSnapshot.GetLineFromPosition(insertPosition); if (lineUnderInsertPosition.Length > 0) { // Move the line break to the start of the text to insert insertedText = (Environment.NewLine + insertedText).Substring(0, insertedText.Length); } } using (var edit = view.TextBuffer.CreateEdit()) { edit.Delete(lineToSwap.Start, lineToSwap.LengthIncludingLineBreak); edit.Insert(insertPosition, insertedText); edit.Apply(); } return -lineToSwap.LengthIncludingLineBreak; }
public int? GetDesiredIndentation(ITextSnapshotLine line) { // get point at the subject buffer var mappingPoint = _view.BufferGraph.CreateMappingPoint(line.Start, PointTrackingMode.Negative); // TODO (https://github.com/dotnet/roslyn/issues/5281): Remove try-catch. SnapshotPoint? point = null; try { point = mappingPoint.GetInsertionPoint(b => b.ContentType.IsOfType(_contentType.TypeName)); } catch (ArgumentOutOfRangeException) { // 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; } if (!point.HasValue) { return null; } // Currently, interactive smart indenter returns indentation based // solely on subject buffer's information and doesn't consider spaces // in interactive window itself. Note: This means the ITextBuffer passed // to ISmartIndent.GetDesiredIndentation is not this.view.TextBuffer. return _indenter.GetDesiredIndentation(point.Value.GetContainingLine()); }
int? ISmartIndent.GetDesiredIndentation(ITextSnapshotLine line) { var snap = _textView.TextSnapshot; // get all of the previous lines var lines = snap.Lines.Reverse().Skip(snap.LineCount - line.LineNumber); foreach (ITextSnapshotLine prevLine in lines) { var text = prevLine.GetText(); if (text.All(c2 => System.Char.IsWhiteSpace(c2))) { continue; } var toks = Utils.LexString(text).ToList(); if (toks.Last().Type == RustLexer.RustLexer.LBRACE) { return prevLine.GetText().TakeWhile(c2 => c2 == ' ').Count() + 4; } else if (toks.Any(tok => tok.Type == RustLexer.RustLexer.RBRACE)) { ed.MoveLineUp(false); ed.DecreaseLineIndent(); ed.MoveLineDown(false); return prevLine.GetText().TakeWhile(c2 => c2 == ' ').Count(); } } // otherwise, there are no lines ending in braces before us. return null; }
public IEnumerable<TextLineCheckerError> CheckLine(ITextSnapshotLine line) { if (_chromiumSourceFiles.ApplyCodingStyle(_fileSystem, line)) { int indent = 0; var fragment = line.GetFragment(line.Start, line.End, TextLineFragment.Options.Default); foreach (var point in fragment.GetPoints()) { if (WhitespaceCharacters.IndexOf(point.GetChar()) >= 0) { // continue as long as we find whitespaces indent++; } else if (GetMarker(line, fragment, point) != null) { if (indent % 2 == 0) // even indentation is not ok { var marker = GetMarker(line, fragment, point); yield return new TextLineCheckerError { Span = new SnapshotSpan(point, marker.Length), Message = string.Format("Accessor \"{0}\" should always be indented 1 character less than rest of class body.", marker) }; } } else { // Stop at the first non-whitespace character. yield break; } } } }
private async Task<int?> GetDesiredIndentationAsync(ITextSnapshotLine lineToBeIndented, CancellationToken cancellationToken) { if (lineToBeIndented == null) { throw new ArgumentNullException(@"line"); } using (Logger.LogBlock(FunctionId.SmartIndentation_Start, cancellationToken)) { var document = lineToBeIndented.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return null; } var service = document.GetLanguageService<IIndentationService>(); if (service == null) { return null; } var result = await service.GetDesiredIndentationAsync(document, lineToBeIndented.LineNumber, cancellationToken).ConfigureAwait(false); if (result == null) { return null; } return result.Value.GetIndentation(_textView, lineToBeIndented); } }
protected IndentationResult GetIndentationOfLine(ITextSnapshotLine lineToMatch, int addedSpaces) { var firstNonWhitespace = lineToMatch.GetFirstNonWhitespacePosition(); firstNonWhitespace = firstNonWhitespace ?? lineToMatch.End.Position; return GetIndentationOfPosition(new SnapshotPoint(lineToMatch.Snapshot, firstNonWhitespace.Value), addedSpaces); }
protected override void Modify(ITextEdit edit, ITextSnapshotLine line) { if (line.GetText().StartsWith("#")) { edit.Delete(line.Start, 1); } }
/// <summary> /// Gets the desired indentation /// </summary> /// <param name="textView">Text view</param> /// <param name="smartIndentationService">Smart indentation service</param> /// <param name="line">Line</param> /// <returns></returns> public static int? GetDesiredIndentation(ITextView textView, ISmartIndentationService smartIndentationService, ITextSnapshotLine line) { if (textView == null) throw new ArgumentNullException(nameof(textView)); if (smartIndentationService == null) throw new ArgumentNullException(nameof(smartIndentationService)); if (line == null) throw new ArgumentNullException(nameof(line)); var indentStyle = textView.Options.GetIndentStyle(); switch (indentStyle) { case IndentStyle.None: return 0; case IndentStyle.Block: return GetDesiredBlockIndentation(textView, line); case IndentStyle.Smart: var indentSize = smartIndentationService.GetDesiredIndentation(textView, line); Debug.Assert(indentSize == null || indentSize.Value >= 0); return indentSize; default: Debug.Fail($"Invalid {nameof(IndentStyle)}: {indentStyle}"); return null; } }
private int? GetDesiredIndentation(ITextSnapshotLine lineToBeIndented, CancellationToken cancellationToken) { if (lineToBeIndented == null) { throw new ArgumentNullException(@"line"); } using (Logger.LogBlock(FunctionId.SmartIndentation_Start, cancellationToken)) { var document = lineToBeIndented.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); var syncService = document?.GetLanguageService<ISynchronousIndentationService>(); if (syncService != null) { var result = syncService.GetDesiredIndentation(document, lineToBeIndented.LineNumber, cancellationToken); return result?.GetIndentation(_textView, lineToBeIndented); } var asyncService = document?.GetLanguageService<IIndentationService>(); if (asyncService != null) { var result = asyncService.GetDesiredIndentation(document, lineToBeIndented.LineBreakLength, cancellationToken).WaitAndGetResult(cancellationToken); return result?.GetIndentation(_textView, lineToBeIndented); } return null; } }
public virtual int? GetDesiredIndentation(ITextSnapshotLine line) { try { vsIndentStyle indentStyle = IndentStyle; if (indentStyle == vsIndentStyle.vsIndentStyleNone) return 0; int? result = null; if (indentStyle == vsIndentStyle.vsIndentStyleSmart) result = GetSmartIndentation(line); if (result == null) result = GetFallbackIndentation(line); return result; } catch (Exception ex) { // Throwing an exception from here will crash the IDE. if (ErrorHandler.IsCriticalException(ex)) throw; return null; } }
public int? GetDesiredIndentation(ITextSnapshotLine line) { // If we're on the first line, we can't really do anything clever. if (line.LineNumber == 0) return 0; var snapshot = line.Snapshot; // Walk up previous lines trying to find the first non-blank one. var previousNonBlankLine = snapshot.GetLineFromLineNumber(line.LineNumber - 1); while (previousNonBlankLine.LineNumber >= 1 && previousNonBlankLine.GetText().Trim().Length == 0) previousNonBlankLine = snapshot.GetLineFromLineNumber(previousNonBlankLine.LineNumber - 1); // If we didn't find an actual non-blank line, we can't really do anything clever. if (previousNonBlankLine.GetText().Trim() == "") return 0; var previousLineText = previousNonBlankLine.GetText(); var previousLineIndent = previousLineText.Replace("\t", new string(' ', tabSize)).TakeWhile(char.IsWhiteSpace).Count(); // If we started a block on the previous line; then add indent. if (previousLineText.TrimEnd().EndsWith("{")) return previousLineIndent + tabSize; else return previousLineIndent; }
public int? GetDesiredIndentation(ITextSnapshotLine line) { if (JToolsPackage.Instance.LangPrefs.IndentMode == vsIndentStyle.vsIndentStyleSmart) { return AutoIndent.GetLineIndentation(line, _textView); } else { return null; } }
private int? DoSmartIndent(ITextSnapshotLine line) { var syntaxTree = line.Snapshot.GetSyntaxTree(CancellationToken.None); var root = syntaxTree.Root; var lineStartPosition = line.Start.Position; var indent = FindTotalParentChainIndent(root, lineStartPosition, 0); return indent; }
internal static int? GetLineIndentation(ITextSnapshotLine line, ITextView textView) { var options = textView.Options; ITextSnapshotLine baseline; string baselineText; SkipPreceedingBlankLines(line, out baselineText, out baseline); ITextBuffer targetBuffer = textView.TextBuffer; if (!targetBuffer.ContentType.IsOfType(JCoreConstants.ContentType)) { var match = textView.BufferGraph.MapDownToFirstMatch(line.Start, PointTrackingMode.Positive, JContentTypePrediciate, PositionAffinity.Successor); if (match == null) { return 0; } targetBuffer = match.Value.Snapshot.TextBuffer; } var classifier = targetBuffer.GetJClassifier(); if (classifier == null) { // workaround debugger canvas bug - they wire our auto-indent provider up to a C# buffer // (they query MEF for extensions by hand and filter incorrectly) and we don't have a J classifier. // So now the user's auto-indent is broken in C# but returning null is better than crashing. return null; } var desiredIndentation = CalculateIndentation(baselineText, baseline, options, classifier, textView); var caretLine = textView.Caret.Position.BufferPosition.GetContainingLine(); // VS will get the white space when the user is moving the cursor or when the user is doing an edit which // introduces a new line. When the user is moving the cursor the caret line differs from the line // we're querying. When editing the lines are the same and so we want to account for the white space of // non-blank lines. An alternate strategy here would be to watch for the edit and fix things up after // the fact which is what would happen pre-Dev10 when the language would not get queried for non-blank lines // (and is therefore what C# and other languages are doing). if (caretLine.LineNumber == line.LineNumber) { var lineText = caretLine.GetText(); int indentationUpdate = 0; for (int i = textView.Caret.Position.BufferPosition.Position - caretLine.Start; i < lineText.Length; i++) { if (lineText[i] == ' ') { indentationUpdate++; } else if (lineText[i] == '\t') { indentationUpdate += textView.Options.GetIndentSize(); } else { if (indentationUpdate > desiredIndentation) { // we would dedent this line (e.g. there's a return on the previous line) but the user is // hitting enter with a statement to the right of the caret and they're in the middle of white space. // So we need to instead just maintain the existing indentation level. desiredIndentation = Math.Max(GetIndentation(baselineText, options.GetTabSize()) - indentationUpdate, 0); } else { desiredIndentation -= indentationUpdate; } break; } } } return desiredIndentation; }
//===================================================================== /// <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; }
private string GetMarker(ITextSnapshotLine line, TextLineFragment fragment, SnapshotPoint point) { string[] markers = { "for(", }; return markers .Where(marker => fragment.GetText(point - line.Start, marker.Length) == marker) .FirstOrDefault(); }
public int? GetDesiredIndentation(ITextView textView, ITextSnapshotLine line) { if (textView == null) throw new ArgumentNullException(nameof(textView)); if (line == null) throw new ArgumentNullException(nameof(line)); var smartIndent = textView.Properties.GetOrCreateSingletonProperty(typeof(SmartIndentationService), () => new Helper(this, textView).SmartIndent); return smartIndent.GetDesiredIndentation(line); }
protected override bool ShouldUseSmartTokenFormatterInsteadOfIndenter( IEnumerable<IFormattingRule> formattingRules, SyntaxNode root, ITextSnapshotLine line, OptionSet optionSet, CancellationToken cancellationToken) { return ShouldUseSmartTokenFormatterInsteadOfIndenter(formattingRules, (CompilationUnitSyntax)root, line, optionSet, cancellationToken); }
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; }
private ITextSnapshotLine GetSelectionEndLine(ITextSnapshotLine selectionStartLine, IWpfTextView textView) { var selectionEndLine = textView.Selection.End.Position.GetContainingLine(); // if the selection ends exactly at the beginning of a new line (ie line select), we do not comment out the last line if (selectionStartLine.LineNumber != selectionEndLine.LineNumber && selectionEndLine.Start.Equals(textView.Selection.End.Position)) { selectionEndLine = selectionEndLine.Snapshot.GetLineFromLineNumber(selectionEndLine.LineNumber - 1); } return selectionEndLine; }
// From https://github.com/dotnet/roslyn/blob/e39a3aeb1185ef0b349cad96a105969423065eac/src/EditorFeatures/Core/Shared/Extensions/ITextViewExtensions.cs#L278 public static int? GetDesiredIndentation(this ITextView textView, ISmartIndentationService smartIndentService, ITextSnapshotLine line) { var pointInView = textView.BufferGraph.MapUpToSnapshot(line.Start, PointTrackingMode.Positive, PositionAffinity.Successor, textView.TextSnapshot); if (!pointInView.HasValue) return null; var lineInView = textView.TextSnapshot.GetLineFromPosition(pointInView.Value.Position); return smartIndentService.GetDesiredIndentation(textView, lineInView); }
public int? GetDesiredIndentation(ITextSnapshotLine line) { try { return GetDesiredIndentationImp(line); } catch { return null; } }
public int? GetDesiredIndentation(ITextSnapshotLine line, IndentStyle indentStyle) { if (line != null) { if (indentStyle == IndentStyle.Block) { return GetBlockIndent(line); } else if (indentStyle == IndentStyle.Smart) { return GetSmartIndent(line); } } return null; }
static SnapshotPoint GetStartSpanBefore(ITextSnapshotLine line, int column, WordKind kind) { int position = line.Start.Position + column; var snapshot = line.Snapshot; for (;;) { if (position == line.Start.Position) return line.Start; position--; if (GetWordKind(snapshot[position]) != kind) return new SnapshotPoint(snapshot, position + 1); } }
static SnapshotPoint GetEndSpanAfter(ITextSnapshotLine line, int column, WordKind kind) { int position = line.Start.Position + column; var snapshot = line.Snapshot; for (;;) { if (position + 1 >= line.End.Position) return new SnapshotPoint(snapshot, line.End.Position); position++; if (GetWordKind(snapshot[position]) != kind) return new SnapshotPoint(snapshot, position); } }
internal static bool TryGetDirectorySpan(ITextSnapshotLine line, out SnapshotSpan span) { var snapshot = line.Snapshot; if (line.Length > 0 && snapshot[line.End.Position - 1] == '/') { span = new SnapshotSpan(line.Start, line.Length - 1); return true; } span = default(SnapshotSpan); return false; }
public ReverseExpressionParser(ITextSnapshot snapshot, ITextBuffer buffer, ITrackingSpan span) { _snapshot = snapshot; _buffer = buffer; _span = span; var loc = span.GetSpan(snapshot); var line = _curLine = snapshot.GetLineFromPosition(loc.Start); var targetSpan = new Span(line.Start.Position, span.GetEndPoint(snapshot).Position - line.Start.Position); _tokens = Classifier.GetClassificationSpans(new SnapshotSpan(snapshot, targetSpan)); }
public int? GetDesiredIndentation(ITextSnapshotLine line) { switch (NodejsPackage.Instance.LangPrefs.IndentMode) { case VisualStudio.TextManager.Interop.vsIndentStyle.vsIndentStyleNone: return null; case VisualStudio.TextManager.Interop.vsIndentStyle.vsIndentStyleDefault: return DoBlockIndent(line); case VisualStudio.TextManager.Interop.vsIndentStyle.vsIndentStyleSmart: return DoSmartIndent(line); default: return null; } }
private bool IsAllowedOverflow(ITextSnapshotLine line) { var keywords = new string[] { "#include", "#define", "#if", "#endif", }; var text = line.GetFragment(line.Start.Position, line.Start.Position + 30, TextLineFragment.Options.Default) .SnapshotSpan.GetText(); return keywords.Any(k => text.Contains(k)); }
public AbstractIndenter(Document document, IEnumerable <IFormattingRule> rules, OptionSet optionSet, ITextSnapshotLine lineToBeIndented, CancellationToken cancellationToken) { this.OptionSet = optionSet; this.Document = SyntacticDocument.CreateAsync(document, cancellationToken).WaitAndGetResult(cancellationToken); this.LineToBeIndented = lineToBeIndented; this.TabSize = this.OptionSet.GetOption(FormattingOptions.TabSize, this.Document.Root.Language); this.CancellationToken = cancellationToken; this.Rules = rules; this.Tree = this.Document.SyntaxTree; this.Finder = new BottomUpBaseIndentationFinder( new ChainedFormattingRules(this.Rules, OptionSet), this.TabSize, this.OptionSet.GetOption(FormattingOptions.IndentationSize, this.Document.Root.Language), tokenStream: null, lastToken: default(SyntaxToken)); }
public void AugmentCompletionSession(ICompletionSession session, IList <CompletionSet> completionSets) { //AsmDudeToolsStatic.Output(string.Format("INFO: {0}:AugmentCompletionSession", this.ToString())); if (_disposed) { return; } 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) && !AsmTools.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.isAllUpper(partialKeyword); SortedSet <Completion> completions = null; string lineStr = line.GetText(); var t = AsmSourceTools.parseLine(lineStr); Mnemonic mnemonic = t.Item2; if (mnemonic == Mnemonic.UNKNOWN) { ISet <AsmTokenType> selected = new HashSet <AsmTokenType> { AsmTokenType.Directive, AsmTokenType.Jump, AsmTokenType.Misc, AsmTokenType.Mnemonic /*, AsmTokenType.Register */ }; completions = this.selectedCompletions(useCapitals, selected); } else // the current line contains a mnemonic { string previousKeyword = AsmDudeToolsStatic.getPreviousKeyword(line.Start, start); //AsmDudeToolsStatic.Output("INFO: AsmCompletionSource:AugmentCompletionSession; mnemonic=" + mnemonic+ "; previousKeyword="+ previousKeyword); if (AsmSourceTools.isJump(AsmSourceTools.parseMnemonic(previousKeyword))) { //AsmDudeToolsStatic.Output("INFO: AsmCompletionSource:AugmentCompletionSession; previous keyword is a jump mnemonic"); // previous keyword is jump (or call) mnemonic. Suggest "SHORT" or a label completions = this.labelCompletions(); completions.Add(new Completion("SHORT", (useCapitals) ? "SHORT" : "short", null, this._icons[AsmTokenType.Misc], "")); completions.Add(new Completion("NEAR", (useCapitals) ? "NEAR" : "near", null, this._icons[AsmTokenType.Misc], "")); } else if (previousKeyword.Equals("SHORT") || previousKeyword.Equals("NEAR")) { // previous keyword is SHORT. Suggest a label completions = this.labelCompletions(); } else { IList <Operand> operands = AsmSourceTools.makeOperands(t.Item3); ISet <AsmSignatureEnum> allowed = new HashSet <AsmSignatureEnum>(); int commaCount = AsmSignature.countCommas(lineStr); IList <AsmSignatureElement> allSignatures = this._asmDudeTools.mnemonicStore.getSignatures(mnemonic); ISet <Arch> selectedArchitectures = AsmDudeToolsStatic.getArchSwithedOn(); foreach (AsmSignatureElement se in AsmSignatureHelpSource.constrainSignatures(allSignatures, operands, selectedArchitectures)) { if (commaCount < se.operands.Count) { foreach (AsmSignatureEnum s in se.operands[commaCount]) { allowed.Add(s); } } } completions = this.mnemonicOperandCompletions(useCapitals, allowed); } } //AsmDudeToolsStatic.Output("INFO: AsmCompletionSource:AugmentCompletionSession; nCompletions=" + completions.Count); #endregion completionSets.Add(new CompletionSet("Tokens", "Tokens", applicableTo, completions, Enumerable.Empty <Completion>())); AsmDudeToolsStatic.printSpeedWarning(time1, "Code Completion"); } catch (Exception e) { AsmDudeToolsStatic.Output(string.Format("ERROR: {0}:AugmentCompletionSession; e={1}", this.ToString(), e.ToString())); } }
FSharpOption <int> IVimHost.GetNewLineIndent(ITextView textView, ITextSnapshotLine contextLine, ITextSnapshotLine newLine, IVimLocalSettings localSettings) { return(GetNewLineIndent(textView, contextLine, newLine, localSettings)); }
public static SnapshotPoint GetPointInLine(this ITextSnapshot snapshot, int line, int column) { ITextSnapshotLine snapshotLine = snapshot.GetLineFromLineNumber(line); return(snapshotLine.Start.Add(column)); }
private unsafe PooledStructEnumerable <TeXCommentBlockSpan> GenerateTexCommentBlocks(ITextSnapshot snapshot) { var texCommentBlocks = blockListsPool.Get(); Debug.Assert(texCommentBlocks.Count == 0); var contentName = snapshot.ContentType.TypeName; if (!CommentPrefixPerContentType.TryGetValue(contentName, out var commentPrefix) || !TeXCommentPrefixPerContentType.TryGetValue(contentName, out var teXCommentPrefix)) { return(new PooledStructEnumerable <TeXCommentBlockSpan>(texCommentBlocks, blockListsPool)); } Debug.Assert(teXCommentPrefix.Length > commentPrefix.Length); Span <char> lineStartingCharactersBuffer = stackalloc char[teXCommentPrefix.Length]; var atTexBlock = false; var texBlockSpanBuilder = default(TeXCommentBlockSpanBuilder); ITextSnapshotLine lastBlockLine = null; foreach (var line in snapshot.Lines) { var lineStartPos = line.Start.Position; var numberOfWhiteSpaceCharsOnStartOfLine = snapshot.NumberOfWhiteSpaceCharsOnStartOfLine(lineStartPos, line.Length); lineStartPos += numberOfWhiteSpaceCharsOnStartOfLine; var lineStartingCharacters = lineStartingCharactersBuffer.Slice(0, Math.Min(lineStartingCharactersBuffer.Length, line.End.Position - lineStartPos)); //line can be shorter than prefix that we are lookin for for (int pos = 0; pos < lineStartingCharacters.Length; pos++) { lineStartingCharacters[pos] = snapshot[lineStartPos + pos]; } if (atTexBlock) { if (lineStartingCharacters.StartsWith(teXCommentPrefix)) { texBlockSpanBuilder.EndBlock(lastBlockLine); texCommentBlocks.Add(texBlockSpanBuilder.Build(snapshot)); //end of current block texBlockSpanBuilder = new TeXCommentBlockSpanBuilder(line.ExtentIncludingLineBreak, numberOfWhiteSpaceCharsOnStartOfLine, line, line.GetLineBreakText(), teXCommentPrefix, contentName); //start of new block lastBlockLine = line; } else if (lineStartingCharacters.StartsWith(commentPrefix)) { //continuation of current block texBlockSpanBuilder.Add(line.LengthIncludingLineBreak); lastBlockLine = line; } else { //end of current block texBlockSpanBuilder.EndBlock(lastBlockLine); texCommentBlocks.Add(texBlockSpanBuilder.Build(snapshot)); atTexBlock = false; } } else if (lineStartingCharacters.StartsWith(teXCommentPrefix)) { //start of new block atTexBlock = true; texBlockSpanBuilder = new TeXCommentBlockSpanBuilder(line.ExtentIncludingLineBreak, numberOfWhiteSpaceCharsOnStartOfLine, line, line.GetLineBreakText(), teXCommentPrefix, contentName); lastBlockLine = line; } } if (atTexBlock) { texBlockSpanBuilder.EndBlock(lastBlockLine); texCommentBlocks.Add(texBlockSpanBuilder.Build(snapshot)); } return(new PooledStructEnumerable <TeXCommentBlockSpan>(texCommentBlocks, blockListsPool)); }
private void AddSingleLineComments(SnapshotSpan span, List <TextChange> textChanges, List <ITrackingSpan> trackingSpans, ITextSnapshotLine firstLine, ITextSnapshotLine lastLine, CommentSelectionInfo commentInfo) { // Select the entirety of the lines, so that another comment operation will add more // comments, not insert block comments. trackingSpans.Add(span.Snapshot.CreateTrackingSpan(Span.FromBounds(firstLine.Start.Position, lastLine.End.Position), SpanTrackingMode.EdgeInclusive)); var indentToCommentAt = DetermineSmallestIndent(span, firstLine, lastLine); ApplySingleLineCommentToNonBlankLines(commentInfo, textChanges, firstLine, lastLine, indentToCommentAt); }
public IEnumerable <ITagSpan <IUrlTag> > GetTags(NormalizedSnapshotSpanCollection spans) { if (!enableLinks) { yield break; } ITextSnapshotLine line = null; foreach (var span in spans) { int pos = span.Start; // We check full lines so make sure we don't re-check the same line again if (line != null && line.ExtentIncludingLineBreak.End.Position > pos) { continue; } for (;;) { if (line != null && line.ExtentIncludingLineBreak.End.Position == pos) { if (line.Snapshot.LineCount == line.LineNumber + 1) { break; } line = line.Snapshot.GetLineFromLineNumber(line.LineNumber + 1); } else { Debug.Assert(line == null || pos > line.ExtentIncludingLineBreak.End.Position); line = span.Snapshot.GetLineFromPosition(pos); } if (line.Length != 0 && line.Length <= maxLineLength) { var lineText = line.GetText(); var uriFinder = new UriFinder(lineText); for (;;) { var res = uriFinder.GetNext(); if (res == null) { break; } Debug.Assert(res.Value.Length != 0); if (res.Value.Length == 0) { break; } int start = line.Start.Position + res.Value.Start; int end = start + res.Value.Length; Debug.Assert(end <= line.Snapshot.Length); if (end > line.Snapshot.Length) { break; } var uriSpan = new SnapshotSpan(line.Snapshot, start, res.Value.Length); var uri = TryCreateUri(uriSpan.GetText()); if (uri == null) { continue; } yield return(new TagSpan <IUrlTag>(uriSpan, new UrlTag(uri))); } } pos = line.ExtentIncludingLineBreak.End; if (pos >= span.End) { break; } } } }
public abstract int?GetDesiredIndentation(RazorSyntaxTree syntaxTree, ITextSnapshot syntaxTreeSnapshot, ITextSnapshotLine line, int indentSize, int tabSize);
public LineTokenization(IEnumerable <TokenInfo> tokens, object state, ITextSnapshotLine line) { Tokens = tokens.Select(t => new LineToken(t, line.EndIncludingLineBreak)).ToArray(); State = state; Line = line.Snapshot.CreateTrackingSpan(line.ExtentIncludingLineBreak, SpanTrackingMode.EdgeNegative); }
protected virtual int?GetSmartIndentation(ITextSnapshotLine line) { ITextSnapshot snapshot = line.Snapshot; SnapshotPoint contextEndPosition = line.Start; SnapshotPoint endPosition = line.EndIncludingLineBreak; SnapshotPoint endPositionOnLine = line.End; IReferenceAnchors anchors = FindNearestAnchors(contextEndPosition); IAnchor previous = anchors.Previous; int spanEnd = Math.Min(line.Snapshot.Length, endPosition.Position + 1); Span span; IAnchor enclosing = anchors.Enclosing; if (enclosing != null) { span = Span.FromBounds(enclosing.TrackingSpan.GetStartPoint(snapshot).Position, spanEnd); } else if (previous != null) { // at least for now, include the previous span due to the way error handling places bounds on an anchor span = Span.FromBounds(previous.TrackingSpan.GetStartPoint(snapshot).Position, spanEnd); } else { span = Span.FromBounds(0, spanEnd); } var diagnosticsPane = DiagnosticsPane; if (diagnosticsPane != null) { diagnosticsPane.WriteLine(string.Format("Smart indent from anchor span: {0}", span)); } ITokenSource bufferTokenSource = GetTokenSource(new SnapshotSpan(snapshot, span)); ITokenSource tokenSource = new CodeCompletionTokenSource(bufferTokenSource, endPosition); ITokenStream tokenStream = new CommonTokenStream(tokenSource); IDictionary <RuleContext, CaretReachedException> parseTrees = GetParseTrees(tokenStream, anchors); if (parseTrees == null) { return(null); } var indentLevels = new SortedDictionary <int, IList <KeyValuePair <RuleContext, CaretReachedException> > >(); foreach (var parseTree in parseTrees) { if (parseTree.Value == null) { continue; } IParseTree firstNodeOnLine = FindFirstNodeAfterOffset(parseTree.Key, line.Start.Position); if (firstNodeOnLine == null) { firstNodeOnLine = parseTree.Value.FinalContext; } if (firstNodeOnLine == null) { continue; } int?indentationLevel = GetIndent(parseTree, firstNodeOnLine, line.Start); if (indentationLevel == null) { continue; } IList <KeyValuePair <RuleContext, CaretReachedException> > indentList; if (!indentLevels.TryGetValue(indentationLevel.Value, out indentList)) { indentList = new List <KeyValuePair <RuleContext, CaretReachedException> >(); indentLevels[indentationLevel.Value] = indentList; } indentList.Add(parseTree); } if (indentLevels.Count == 0) { return(null); } int indentLevel = indentLevels.First().Key; if (indentLevels.Count > 1) { // TODO: resolve multiple possibilities } return(indentLevel); }
public WpfTextViewLine(IBufferGraph bufferGraph, LinePartsCollection linePartsCollection, int linePartsIndex, int linePartsLength, int startColumn, int endColumn, ITextSnapshotLine bufferLine, SnapshotSpan span, ITextSnapshot visualSnapshot, TextLine textLine, double indentation, double virtualSpaceWidth) { if (linePartsCollection == null) { throw new ArgumentNullException(nameof(linePartsCollection)); } if (linePartsIndex < 0) { throw new ArgumentOutOfRangeException(nameof(linePartsIndex)); } if (linePartsLength < 0) { throw new ArgumentOutOfRangeException(nameof(linePartsLength)); } if (linePartsIndex + linePartsLength > linePartsCollection.LineParts.Count) { throw new ArgumentOutOfRangeException(nameof(linePartsLength)); } if (bufferLine == null) { throw new ArgumentNullException(nameof(bufferLine)); } if (span.Snapshot != bufferLine.Snapshot) { throw new ArgumentException(); } if (textLine == null) { throw new ArgumentNullException(nameof(textLine)); } IsValid = true; this.linePartsIndex = linePartsIndex; this.linePartsLength = linePartsLength; this.bufferGraph = bufferGraph ?? throw new ArgumentNullException(nameof(bufferGraph)); this.linePartsCollection = linePartsCollection; this.startColumn = startColumn; this.endColumn = endColumn; this.visualSnapshot = visualSnapshot ?? throw new ArgumentNullException(nameof(visualSnapshot)); textLines = new ReadOnlyCollection <TextLine>(new[] { textLine }); Debug.Assert(textLines.Count == 1); // Assumed by all code accessing TextLine prop realTopSpace = 0; realBottomSpace = 0; realBaseline = TextLine.Baseline; double baseLineHeight = TextLine.TextHeight - TextLine.Baseline; var lineParts = linePartsCollection.LineParts; for (int i = 0; i < linePartsLength; i++) { var adornmentElement = lineParts[linePartsIndex + i].AdornmentElement; if (adornmentElement == null) { continue; } double adornmentBaseLineHeight = adornmentElement.TextHeight - adornmentElement.Baseline; if (adornmentBaseLineHeight > baseLineHeight) { baseLineHeight = adornmentBaseLineHeight; } if (adornmentElement.Baseline > realBaseline) { realBaseline = adornmentElement.Baseline; } if (adornmentElement.TopSpace > realTopSpace) { realTopSpace = adornmentElement.TopSpace; } if (adornmentElement.BottomSpace > realBottomSpace) { realBottomSpace = adornmentElement.BottomSpace; } } realTextHeight = Math.Ceiling(baseLineHeight + realBaseline); isFirstTextViewLineForSnapshotLine = span.Start == bufferLine.Start; isLastTextViewLineForSnapshotLine = span.End == bufferLine.EndIncludingLineBreak; IsLastVisualLine = bufferLine.LineNumber + 1 == bufferLine.Snapshot.LineCount && IsLastTextViewLineForSnapshotLine; lineBreakLength = isLastTextViewLineForSnapshotLine ? bufferLine.LineBreakLength : 0; this.virtualSpaceWidth = virtualSpaceWidth; textLeft = indentation; textWidth = TextLine.WidthIncludingTrailingWhitespace; extentIncludingLineBreak = span; endOfLineWidth = Math.Floor(realTextHeight * 0.58333333333333337); // Same as VS width = textWidth + (lineBreakLength == 0 ? 0 : endOfLineWidth); change = TextViewLineChange.NewOrReformatted; SetLineTransform(DefaultLineTransform); }
public int?GetDesiredIndentation(ITextSnapshotLine line) { return(null); }
FSharpOption <int> IVimHost.GetNewLineIndent(ITextView textView, ITextSnapshotLine contextLine, ITextSnapshotLine newLine) { return(GetNewLineIndent(textView, contextLine, newLine)); }
public IEnumerable <ITagSpan <AsmTokenTag> > GetTags(NormalizedSnapshotSpanCollection spans) { DateTime time1 = DateTime.Now; if (spans.Count == 0) { //there is no content in the buffer yield break; } foreach (SnapshotSpan curSpan in spans) { ITextSnapshotLine containingLine = curSpan.Start.GetContainingLine(); string line_upcase = containingLine.GetText().ToUpperInvariant(); List <(int beginPos, int length, bool isLabel)> pos = new List <(int beginPos, int length, bool isLabel)>(AsmSourceTools.SplitIntoKeywordPos(line_upcase)); int offset = containingLine.Start.Position; int nKeywords = pos.Count; #region Check if the current line is a line of source code if (IsSourceCode(line_upcase, pos)) { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span((0, line_upcase.Length, false), offset, curSpan), this.remark_)); continue; // go to the next line } #endregion for (int k = 0; k < nKeywords; k++) { string asmToken = AsmSourceTools.Keyword(pos[k], line_upcase); // keyword starts with a remark char if (AsmSourceTools.IsRemarkChar(asmToken[0])) { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this.remark_)); continue; } // keyword k is a label definition if (pos[k].isLabel) { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this.labelDef_)); continue; } AsmTokenType keywordType = this.asmDudeTools_.Get_Token_Type_Att(asmToken); switch (keywordType) { case AsmTokenType.Jump: { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this.jump_)); k++; // goto the next word if (k == nKeywords) { break; // there are no next words } string asmToken2 = AsmSourceTools.Keyword(pos[k], line_upcase); switch (asmToken2) { case "WORD": case "DWORD": case "QWORD": case "SHORT": case "NEAR": { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this.misc_)); k++; if (k == nKeywords) { break; } string asmToken3 = AsmSourceTools.Keyword(pos[k], line_upcase); switch (asmToken3) { case "PTR": { yield return(new TagSpan <AsmTokenTag>(New_Span(pos[k], offset, curSpan), this.misc_)); break; } yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this.label_)); break; } break; } default: { if (RegisterTools.IsRegister(asmToken2)) { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this.register_)); } else if (AsmSourceTools.Evaluate_Constant(asmToken2, true).valid) { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this.constant_)); } else { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this.label_)); } break; } } break; } case AsmTokenType.UNKNOWN: // asmToken is not a known keyword, check if it is numerical { if (AsmSourceTools.Evaluate_Constant(asmToken, true).valid) { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this.constant_)); } else if (asmToken.StartsWith("$", StringComparison.Ordinal)) { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this.constant_)); } else if (asmToken.StartsWith("\"", StringComparison.Ordinal) && asmToken.EndsWith("\"", StringComparison.Ordinal)) { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this.constant_)); } else { //yield return new TagSpan<AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this._UNKNOWN); } break; } case AsmTokenType.Directive: { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this.directive_)); break; } case AsmTokenType.Mnemonic: { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this.mnemonic_)); break; } case AsmTokenType.Register: { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this.register_)); break; } default: break; } } } AsmDudeToolsStatic.Print_Speed_Warning(time1, "NasmAttDisassemblyTokenTagger"); }
protected abstract bool HasPreprocessorCharacter(ITextSnapshotLine currentLine);
static bool StartsWithRegionTag(ITextSnapshotLine line) { var start = line.GetFirstNonWhitespacePosition(); return(start != null && line.StartsWith(start.Value, "#region", ignoreCase: true)); }
/// <summary> /// Adds edits to comment out each non-blank line, at the given indent. /// </summary> private void ApplySingleLineCommentToNonBlankLines( CommentSelectionInfo info, List <TextChange> textChanges, ITextSnapshotLine firstLine, ITextSnapshotLine lastLine, int indentToCommentAt) { var snapshot = firstLine.Snapshot; for (var lineNumber = firstLine.LineNumber; lineNumber <= lastLine.LineNumber; ++lineNumber) { var line = snapshot.GetLineFromLineNumber(lineNumber); if (!line.IsEmptyOrWhitespace()) { InsertText(textChanges, line.Start + indentToCommentAt, info.SingleLineCommentString); } } }
public static void HandleAutoformat(ITextView textView, ICoreShell shell, char typedChar) { var settings = shell.GetService <IREditorSettings>(); if (!settings.AutoFormat || (!settings.FormatScope && typedChar == '}')) { return; } SnapshotPoint?rPoint = GetCaretPointInBuffer(textView); if (!rPoint.HasValue) { return; } var document = REditorDocument.FromTextBuffer(textView.TextBuffer); var ast = document.EditorTree.AstRoot; // Make sure we are not formatting damaging the projected range in R Markdown // which looks like ```{r. 'r' should not separate from {. var host = ContainedLanguageHost.GetHost(textView, document.TextBuffer, shell); if (host != null && !host.CanFormatLine(textView, document.TextBuffer, document.TextBuffer.CurrentSnapshot.GetLineNumberFromPosition(rPoint.Value))) { return; } // We don't want to auto-format inside strings if (ast.IsPositionInsideString(rPoint.Value.Position)) { return; } ITextBuffer subjectBuffer = rPoint.Value.Snapshot.TextBuffer; if (typedChar.IsLineBreak()) { // Special case for hitting caret after } and before 'else'. We do want to format // the construct as '} else {' but if user types Enter after } and we auto-format // it will look as if the editor just eats the Enter. Instead, we will not be // autoformatting in this specific case. User can always format either the document // or select the block and reformat it. if (!IsBetweenCurlyAndElse(subjectBuffer, rPoint.Value.Position)) { var scopeStatement = GetFormatScope(textView, subjectBuffer, ast); // Do not format large scope blocks for performance reasons if (scopeStatement != null && scopeStatement.Length < 200) { FormatOperations.FormatNode(textView, subjectBuffer, shell, scopeStatement); } else if (CanFormatLine(textView, subjectBuffer, -1)) { FormatOperations.FormatViewLine(textView, subjectBuffer, -1, shell); } } } else if (typedChar == ';') { // Verify we are at the end of the string and not in a middle // of another string or inside a statement. ITextSnapshotLine line = subjectBuffer.CurrentSnapshot.GetLineFromPosition(rPoint.Value.Position); int positionInLine = rPoint.Value.Position - line.Start; string lineText = line.GetText(); if (positionInLine >= lineText.TrimEnd().Length) { FormatOperations.FormatViewLine(textView, subjectBuffer, 0, shell); } } else if (typedChar == '}') { FormatOperations.FormatCurrentStatement(textView, subjectBuffer, shell, limitAtCaret: true, caretOffset: -1); } }
public override async void DoCommand(object sender, EventArgs args) { var activeView = CommonPackage.GetActiveTextView(_serviceProvider); var project = activeView.GetProjectAtCaret(_serviceProvider); var analyzer = activeView.GetAnalyzerAtCaret(_serviceProvider); ITextSelection selection = activeView.Selection; ITextSnapshot snapshot = activeView.TextBuffer.CurrentSnapshot; var workspace = _serviceProvider.GetWorkspace(); IVsInteractiveWindow repl; try { repl = ExecuteInReplCommand.EnsureReplWindow(_serviceProvider, analyzer, project, workspace); } catch (MissingInterpreterException ex) { MessageBox.Show(ex.Message, Strings.ProductTitle); return; } string input; bool focusRepl = false, alwaysSubmit = false; if (selection.StreamSelectionSpan.Length > 0) { // Easy, just send the selection to the interactive window. input = activeView.Selection.StreamSelectionSpan.GetText(); if (!input.EndsWithOrdinal("\n") && !input.EndsWithOrdinal("\r")) { input += activeView.Options.GetNewLineCharacter(); } focusRepl = true; } else if (!activeView.Properties.ContainsProperty(_executedLastLine)) { // No selection, and we haven't hit the end of the file in line-by-line mode. // Send the current line, and then move the caret to the next non-blank line. ITextSnapshotLine targetLine = snapshot.GetLineFromPosition(selection.Start.Position); var targetSpan = targetLine.Extent; // If the line is inside a code cell, expand the target span to // contain the entire cell. var cellStart = CodeCellAnalysis.FindStartOfCell(targetLine); if (cellStart != null) { var cellEnd = CodeCellAnalysis.FindEndOfCell(cellStart, targetLine); targetSpan = new SnapshotSpan(cellStart.Start, cellEnd.End); targetLine = CodeCellAnalysis.FindEndOfCell(cellEnd, targetLine, includeWhitespace: true); alwaysSubmit = true; } input = targetSpan.GetText(); bool moved = false; while (targetLine.LineNumber < snapshot.LineCount - 1) { targetLine = snapshot.GetLineFromLineNumber(targetLine.LineNumber + 1); // skip over blank lines, unless it's the last line, in which case we want to land on it no matter what if (!string.IsNullOrWhiteSpace(targetLine.GetText()) || targetLine.LineNumber == snapshot.LineCount - 1) { activeView.Caret.MoveTo(new SnapshotPoint(snapshot, targetLine.Start)); activeView.Caret.EnsureVisible(); moved = true; break; } } if (!moved) { // There's no where for the caret to go, don't execute the line if // we've already executed it. activeView.Caret.PositionChanged += Caret_PositionChanged; activeView.Properties[_executedLastLine] = _executedLastLine; } } else if ((repl.InteractiveWindow.CurrentLanguageBuffer?.CurrentSnapshot.Length ?? 0) != 0) { // We reached the end of the file but have some text buffered. Execute it now. input = activeView.Options.GetNewLineCharacter(); } else { // We've hit the end of the current text view and executed everything input = null; } if (input != null) { repl.Show(focusRepl); var inputs = repl.InteractiveWindow.Properties.GetOrCreateSingletonProperty( () => new InteractiveInputs(repl.InteractiveWindow, _serviceProvider, alwaysSubmit) ); await inputs.EnqueueAsync(input); } // Take focus back if REPL window has stolen it and we're in line-by-line mode. if (!focusRepl && !activeView.HasAggregateFocus) { var adapterService = _serviceProvider.GetComponentModel().GetService <VisualStudio.Editor.IVsEditorAdaptersFactoryService>(); var tv = adapterService.GetViewAdapter(activeView); tv.SendExplicitFocus(); } }
public static ITextSnapshotLine GetNonEmptyPreviousLine(ITextSnapshot snapshot, ITextSnapshotLine currentLine) { do { var previousLine = snapshot.GetLineFromLineNumber(Math.Max(currentLine.LineNumber - 1, 0)); // first line in the file if (previousLine.LineNumber == currentLine.LineNumber) { return(currentLine); } if (previousLine.IsEmptyOrWhitespace()) { // keep goes up until it find non empty previous line currentLine = previousLine; continue; } return(previousLine); }while (true); }
public override bool Indent() { bool singleLineSelection = (GetStartPoint().LineNumber == GetEndPoint().LineNumber); bool entireLastLineSelected = (GetStartPoint().CurrentPosition != GetEndPoint().CurrentPosition&& GetStartPoint().CurrentPosition == TextBuffer.GetEndPoint().StartOfLine&& GetEndPoint().CurrentPosition == TextBuffer.GetEndPoint().EndOfLine); if (singleLineSelection && !entireLastLineSelected) { TextPoint endPoint = GetEndPoint(); if (!Delete()) { return(false); } if (!endPoint.InsertIndent()) { return(false); } TextView.AdvancedTextView.Caret.MoveTo(endPoint.AdvancedTextPoint); } else // indent the selected lines { VirtualSnapshotPoint oldStartPoint = TextSelection.Start; VirtualSnapshotPoint oldEndPoint = TextSelection.End; bool isReversed = TextSelection.IsReversed; ITextSnapshotLine startLine = AdvancedTextRange.Snapshot.GetLineFromPosition(oldStartPoint.Position); ITextSnapshotLine endLine = AdvancedTextRange.Snapshot.GetLineFromPosition(oldEndPoint.Position); // If the selection span initially starts at the whitespace at the beginning of the line in the startLine or // ends at the whitespace at the beginning of the line in the endLine, restore selection and caret position, // *unless* the selection was in box mode. bool startAtStartLineWhitespace = oldStartPoint.Position <= _textView.GetTextPoint(startLine.Start).GetFirstNonWhiteSpaceCharacterOnLine().CurrentPosition; bool endAtEndLineWhitespace = oldEndPoint.Position < _textView.GetTextPoint(endLine.Start).GetFirstNonWhiteSpaceCharacterOnLine().CurrentPosition; bool isBoxSelection = AdvancedSelection.Mode == TextSelectionMode.Box; if (isBoxSelection) { if (!this.BoxIndent()) { return(false); } } else { if (!TextRange.Indent()) { return(false); } } // Computing the new selection and caret position VirtualSnapshotPoint newStartPoint = TextSelection.Start; VirtualSnapshotPoint newEndPoint = TextSelection.End; if (!isBoxSelection && (startAtStartLineWhitespace || endAtEndLineWhitespace)) { // After indent selection span should start at the start of startLine and end at the start of endLine if (startAtStartLineWhitespace) { newStartPoint = new VirtualSnapshotPoint(AdvancedTextRange.Snapshot, oldStartPoint.Position.Position); } if (endAtEndLineWhitespace && oldEndPoint.Position.Position != endLine.Start && endLine.Length != 0) { int insertedTextSize = _editorOptions.IsConvertTabsToSpacesEnabled() ? _editorOptions.GetTabSize() : 1; newEndPoint = new VirtualSnapshotPoint(AdvancedTextRange.Snapshot, newEndPoint.Position.Position - insertedTextSize); } if (!isReversed) { TextSelection.Select(newStartPoint, newEndPoint); } else { TextSelection.Select(newEndPoint, newStartPoint); } TextView.AdvancedTextView.Caret.MoveTo(TextSelection.ActivePoint, PositionAffinity.Successor); } } TextView.AdvancedTextView.Caret.EnsureVisible(); return(true); }
internal static void GetLineAndColumn(this SnapshotPoint point, out ITextSnapshotLine line, out int column) { line = point.GetContainingLine(); column = point.Position - line.Start.Position; }
private static ITextSnapshotLine GetPreviousLine(ITextSnapshotLine line) { return(line.LineNumber > 0 ? line.Snapshot.GetLineFromLineNumber(line.LineNumber - 1) : null); }
protected IndentationResult GetIndentationOfLine(ITextSnapshotLine lineToMatch) { return(GetIndentationOfLine(lineToMatch, addedSpaces: 0)); }
internal static bool FindMatchingOpenChar(SnapshotPoint startPoint, char open, char close, int maxLines, out SnapshotSpan pairSpan, bool forInsert = false) { pairSpan = new SnapshotSpan(startPoint, startPoint); ITextSnapshotLine line = startPoint.GetContainingLine(); int lineNumber = line.LineNumber; int offset = startPoint - line.Start - 1; //move the offset to the character before this one //if the offset is negative, move to the previous line if (offset < 0) { if (lineNumber <= 0) { return(false); } line = line.Snapshot.GetLineFromLineNumber(--lineNumber); offset = line.Length - 1; } string lineText = line.GetText(); int stopLineNumber = 0; if (maxLines > 0) { stopLineNumber = Math.Max(stopLineNumber, lineNumber - maxLines); } int closeCount = forInsert ? -1 : 0; while (true) { // Walk the entire line while (offset >= 0) { char currentChar = lineText[offset]; if (currentChar == open) { if (closeCount > 0) { closeCount--; } else // We've found the open character { pairSpan = new SnapshotSpan(line.Start + offset, 1); //we just want the character itself return(true); } } else if (currentChar == close) { closeCount++; } offset--; } // Move to the previous line if (--lineNumber < stopLineNumber) { break; } line = line.Snapshot.GetLineFromLineNumber(lineNumber); lineText = line.GetText(); offset = line.Length - 1; } return(false); }
public IEnumerable <ITagSpan <AsmTokenTag> > GetTags(NormalizedSnapshotSpanCollection spans) { DateTime time1 = DateTime.Now; if (spans.Count == 0) { //there is no content in the buffer yield break; } foreach (SnapshotSpan curSpan in spans) { ITextSnapshotLine containingLine = curSpan.Start.GetContainingLine(); string line = containingLine.GetText().ToUpper(); var pos = new List <(int BeginPos, int Length, bool IsLabel)>(AsmSourceTools.SplitIntoKeywordPos(line)); int offset = containingLine.Start.Position; int nKeywords = pos.Count; for (int k = 0; k < nKeywords; k++) { string asmToken = NasmIntelTokenTagger.Keyword(pos[k], line); // keyword starts with a remark char if (AsmSourceTools.IsRemarkChar(asmToken[0])) { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this._remark)); continue; } // keyword k is a label definition if (pos[k].IsLabel) { SnapshotSpan labelDefSpan = NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan); //AsmDudeToolsStatic.Output_INFO("MasmTokenTagger:GetTags: found label " + asmToken +" at line "+containingLine.LineNumber); if (asmToken.Equals("@@")) { // TODO: special MASM label, for the moment, ignore it, later: check whether it is used etc. } else { var v = this.Make_AsmTokenTag_LabelDef(containingLine.LineNumber); yield return(new TagSpan <AsmTokenTag>(labelDefSpan, v)); } continue; } AsmTokenType keywordType = this._asmDudeTools.Get_Token_Type_Intel(asmToken); switch (keywordType) { case AsmTokenType.Jump: { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this._jump)); k++; // goto the next word if (k == nKeywords) { break; } string asmToken2 = NasmIntelTokenTagger.Keyword(pos[k], line); switch (asmToken2) { case "$": case "@B": case "@F": { // TODO: special MASM label, for the moment, ignore it, later: check whether it is used etc. break; } case "WORD": case "DWORD": case "QWORD": case "SHORT": case "NEAR": { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this._misc)); k++; if (k == nKeywords) { break; } string asmToken3 = NasmIntelTokenTagger.Keyword(pos[k], line); switch (asmToken3) { case "$": case "@B": case "@F": { // TODO: special MASM label, for the moment, ignore it, later: check whether it is used etc. break; } case "PTR": { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this._misc)); break; } default: { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this.Make_AsmTokenTag_Label(containingLine.LineNumber))); break; } } break; } default: { if (RegisterTools.IsRegister(asmToken2)) { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this._register)); } else { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this.Make_AsmTokenTag_Label(containingLine.LineNumber))); } break; } } break; } case AsmTokenType.UNKNOWN: // asmToken is not a known keyword, check if it is numerical { if (AsmSourceTools.Evaluate_Constant(asmToken, true).Valid) //if (AsmTools.AsmSourceTools.Parse_Constant(asmToken, true).Valid) { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this._constant)); } else if (asmToken.StartsWith("\"") && asmToken.EndsWith("\"")) { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this._constant)); } else { bool isUnknown = true; // do one word lookahead; see whether we can understand the current unknown word if ((k + 1) < nKeywords) { k++; string nextKeyword = NasmIntelTokenTagger.Keyword(pos[k], line); switch (nextKeyword) { case "PROC": case "EQU": case "LABEL": { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k - 1], offset, curSpan), this._labelDef)); yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this._directive)); isUnknown = false; break; } case "PROTO": { // a proto is considered a label definition but it should not clash with other label definitions yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k - 1], offset, curSpan), this._labelDef_PROTO)); yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this._directive)); isUnknown = false; break; } default: { k--; break; } } } // do one word look back; see whether we can understand the current unknown word if (k > 0) { string previousKeyword = NasmIntelTokenTagger.Keyword(pos[k - 1], line); switch (previousKeyword) { case "ALIAS": { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this._labelDef)); isUnknown = false; break; } case "INCLUDE": { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this._constant)); isUnknown = false; break; } default: { break; } } } if (isUnknown) { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this._UNKNOWN)); } } break; } case AsmTokenType.Directive: { AssemblerEnum assember = this._asmDudeTools.Get_Assembler(asmToken); if (assember.HasFlag(AssemblerEnum.MASM)) // this MASM token-tagger only tags MASM directives { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this._directive)); switch (asmToken) { case "INVOKE": { k++; // goto the next word if (k == nKeywords) { break; } string asmToken2 = NasmIntelTokenTagger.Keyword(pos[k], line); yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this.Make_AsmTokenTag_Label(containingLine.LineNumber))); break; } case "EXTRN": case "EXTERN": { k++; // goto the next word if (k == nKeywords) { break; } string asmToken2 = NasmIntelTokenTagger.Keyword(pos[k], line); yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), this._labelDef_PROTO)); break; } } } } break; default: { yield return(new TagSpan <AsmTokenTag>(NasmIntelTokenTagger.New_Span(pos[k], offset, curSpan), new AsmTokenTag(keywordType))); break; } } } } AsmDudeToolsStatic.Print_Speed_Warning(time1, "MasmTokenTagger"); }
public void AugmentCompletionSession(ICompletionSession session, IList <CompletionSet> completionSets) { Contract.Requires(session != null); Contract.Requires(completionSets != null); try { //AsmDudeToolsStatic.Output_INFO(string.Format(AsmDudeToolsStatic.CultureUI, "{0}:AugmentCompletionSession", this.ToString())); if (!Settings.Default.CodeCompletion_On) { return; } 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_upcase(partialKeyword); string lineStr = line.GetText(); (string label, Mnemonic mnemonic, string[] args, string remark)t = AsmSourceTools.ParseLine(lineStr); Mnemonic mnemonic = t.mnemonic; string previousKeyword_upcase = AsmDudeToolsStatic.Get_Previous_Keyword(line.Start, start).ToUpperInvariant(); //AsmDudeToolsStatic.Output_INFO(string.Format(AsmDudeToolsStatic.CultureUI, "{0}:AugmentCompletionSession. lineStr=\"{1}\"; previousKeyword=\"{2}\"", this.ToString(), lineStr, previousKeyword)); if (mnemonic == Mnemonic.NONE) { if (previousKeyword_upcase.Equals("INVOKE", StringComparison.Ordinal)) //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_upcase, 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_upcase.Equals("SHORT", StringComparison.Ordinal) || previousKeyword_upcase.Equals("NEAR", StringComparison.Ordinal)) { // 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(AsmDudeToolsStatic.CultureUI, "{0}:AugmentCompletionSession; e={1}", this.ToString(), e.ToString())); } }
public override LinePosition GetLinePosition(int position) { ITextSnapshotLine textLine = _text.EditorSnapshot.GetLineFromPosition(position); return(new LinePosition(textLine.LineNumber, position - textLine.Start)); }
public virtual FSharpOption <int> GetNewLineIndent(ITextView textView, ITextSnapshotLine contextLine, ITextSnapshotLine newLine) { return(FSharpOption <int> .None); }
public override FSharpOption <int> GetNewLineIndent(ITextView textView, ITextSnapshotLine contextLine, ITextSnapshotLine newLine) { if (_vimApplicationSettings.UseEditorIndent) { var indent = _smartIndentationService.GetDesiredIndentation(textView, newLine); if (indent.HasValue) { return(FSharpOption.Create(indent.Value)); } else { // If the user wanted editor indentation but the editor doesn't support indentation // even though it proffers an indentation service then fall back to what auto // indent would do if it were enabled (don't care if it actually is) // // Several editors like XAML offer the indentation service but don't actually // provide information. User clearly wants indent there since the editor indent // is enabled. Do a best effort and us Vim style indenting return(FSharpOption.Create(EditUtil.GetAutoIndent(contextLine))); } } return(FSharpOption <int> .None); }