Example #1
0
        internal void MoveCaretToFirstLine(Rect rect)
        {
            TextPointer tp      = Document.ContentStart;
            TextPointer last_tp = tp;

            Rect r = tp.GetCharacterRect(LogicalDirection.Forward);

            while (tp != null && r.X < rect.X && tp.CompareTo(Document.ContentEnd) != 0)
            {
                tp = tp.GetNextInsertionPosition(LogicalDirection.Forward);
                if (tp == null)
                {
                    break;
                }
                r       = tp.GetCharacterRect(LogicalDirection.Forward);
                last_tp = tp;
            }

            if (last_tp != null)
            {
                CaretPosition = last_tp;
            }

            // Workaround for bug in .NET 3.0
            if (!CaretPosition.IsAtLineStartPosition)
            {
                EditingCommands.MoveLeftByCharacter.Execute(null, this);
                EditingCommands.MoveRightByCharacter.Execute(null, this);
            }
            else if (CaretPosition.CompareTo(Document.ContentEnd) != 0)
            {
                EditingCommands.MoveRightByCharacter.Execute(null, this);
                EditingCommands.MoveLeftByCharacter.Execute(null, this);
            }
        }
        private void UpdatePositionAndLength(CaretPosition pos)
        {
            SnapshotPoint?point = pos.Point.GetPoint(this.textBuffer, pos.Affinity);

            PositionText = point.HasValue ? point.Value.Position.ToString() : "-";
            LengthText   = this.textBuffer.CurrentSnapshot.Length.ToString();
        }
Example #3
0
 public CaretWriter(CaretWriter caret)
 {
     this.old     = caret;
     this.Builder = new StringBuilder();
     this.Start   = new CaretPosition(caret.End.X, caret.End.Y);
     this.End     = this.Start;
 }
Example #4
0
 /// <summary>
 /// CaretWriter. For specialized input. Still under testing/writing. Takes a StringBuilder as a parameter.
 /// </summary>
 /// <param name="b"></param>
 public CaretWriter()
 {
     this.old     = null;
     this.Builder = new StringBuilder();
     this.Start   = new CaretPosition(Cursor.X, Cursor.Y);
     this.End     = this.Start;
 }
Example #5
0
        private bool CompletionTrigger()
        {
            if (_session_sighelp != null)
            {
                _session_sighelp.Dismiss();
            }

            if (_session_completion != null)
            {
                _session_completion.Dismiss();
            }

            SnapshotPoint?caretPoint    = _textview.Caret.Position.Point.GetPoint(textBuffer => (!textBuffer.ContentType.IsOfType("projection")), PositionAffinity.Predecessor);
            CaretPosition curPosition   = _textview.Caret.Position;
            var           curTrackPoint = _textview.TextSnapshot.CreateTrackingPoint(curPosition.BufferPosition.Position, Microsoft.VisualStudio.Text.PointTrackingMode.Positive);

            if (!caretPoint.HasValue)
            {
                return(false);
            }
            _session_completion            = _nsicprovider._completionbroker.CreateCompletionSession(_textview, caretPoint.Value.Snapshot.CreateTrackingPoint(caretPoint.Value.Position, PointTrackingMode.Positive), false);
            _session_completion.Dismissed += CompletionDismiss;
            _session_completion.Committed += CompletionDismiss;
            _session_completion.Start();
            Debug.Print("NS - CompletionTrigger");
            return(true);
        }
Example #6
0
        private bool HandleCopyKeys(KeyEventArgs args)
        {
            if (args.Key == Key.C)
            {
                if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
                {
                    return(false);
                }

                var promptEnd = _promptInline.ContentEnd;

                var pos          = CaretPosition.CompareTo(promptEnd);
                var selectionPos = Selection.Start.CompareTo(CaretPosition);

                return(pos < 0 || selectionPos < 0);
            }

            if (args.Key == Key.X || args.Key == Key.V)
            {
                var promptEnd = _promptInline.ContentEnd;

                var pos          = CaretPosition.CompareTo(promptEnd);
                var selectionPos = Selection.Start.CompareTo(CaretPosition);

                return(pos < 0 || selectionPos < 0);
            }

            return(false);
        }
Example #7
0
        /// <summary>
        /// Check the caret position. If the caret is on a new word, update the CurrentWord value
        /// </summary>
        private void UpdateAtCaretPosition(CaretPosition caretPosition)
        {
            SnapshotPoint?point = caretPosition.Point.GetPoint(this.sourceBuffer_, caretPosition.Affinity);

            TextExtent?newWordExtend = this.textStructureNavigator_.GetExtentOfWord(point.Value);

            //AsmDudeToolsStatic.Output_INFO(string.Format(AsmDudeToolsStatic.CultureUI, "{0}:Update_Word_Adornments. word={1}", this.ToString(), newWordExtend.ToString()));

            // If the new cursor position is still within the current word (and on the same snapshot),
            // we don't need to check it.
            if (newWordExtend.HasValue)
            {
                string newWord = newWordExtend.Value.Span.GetText().Trim();
                //AsmDudeToolsStatic.Output_INFO(string.Format(AsmDudeToolsStatic.CultureUI, "{0}:Update_Word_Adornments. caretPoisition={1}; point={2}; newWordExtend={3}", this.ToString(), caretPosition, point, newWordExtend));

                if ((this.CurrentWord != null) && newWord.Equals(this.CurrentWord, StringComparison.Ordinal))
                {
                    return;
                }
                else
                {
                    this.RequestedPoint = point.Value;
                    this.NewWord        = newWord;
                    this.NewWordSpan    = newWordExtend.Value.Span;
                    //AsmDudeToolsStatic.Output_INFO(string.Format(AsmDudeToolsStatic.CultureUI, "{0}:Update_Word_Adornments. RequestedPoint={1}; NewWord=\"{2}\"; NewWordSpan={3}", this.ToString(), this.RequestedPoint, this.NewWord, this.NewWordSpan));

                    AsmDudeTools.Instance.Thread_Pool.QueueWorkItem(this.Update_Word_Adornments);
                }
            }
        }
Example #8
0
        private bool HandleCopyKeys(KeyEventArgs args)
        {
            switch (args.Key)
            {
            case Key.C:
            {
                if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
                {
                    return(false);
                }

                var pos          = CaretPosition.CompareTo(_promptInline.ContentEnd);
                var selectionPos = Selection.Start.CompareTo(CaretPosition);

                return(pos < 0 || selectionPos < 0);
            }

            case Key.X:
            case Key.V:
            {
                var end          = _promptInline.ContentEnd;
                var pos          = CaretPosition.CompareTo(end);
                var selectionPos = Selection.Start.CompareTo(CaretPosition);

                return(pos < 0 || selectionPos < 0);
            }
            }
            return(false);
        }
Example #9
0
        public TextCaret(IWpfTextView textView, IAdornmentLayer caretLayer, ISmartIndentationService smartIndentationService, IClassificationFormatMap classificationFormatMap)
        {
            if (textView == null)
            {
                throw new ArgumentNullException(nameof(textView));
            }
            if (caretLayer == null)
            {
                throw new ArgumentNullException(nameof(caretLayer));
            }
            if (smartIndentationService == null)
            {
                throw new ArgumentNullException(nameof(smartIndentationService));
            }
            this.textView = textView;
            this.imeState = new ImeState();
            this.smartIndentationService = smartIndentationService;
            this.preferredXCoordinate    = 0;
            this.__preferredYCoordinate  = 0;
            Affinity = PositionAffinity.Successor;
            var bufferPos = new VirtualSnapshotPoint(textView.TextSnapshot, 0);

            this.currentPosition = new CaretPosition(bufferPos, new MappingPoint(bufferPos.Position, PointTrackingMode.Negative), Affinity);
            textView.TextBuffer.ChangedHighPriority += TextBuffer_ChangedHighPriority;
            textView.TextBuffer.ContentTypeChanged  += TextBuffer_ContentTypeChanged;
            textView.Options.OptionChanged          += Options_OptionChanged;
            textView.VisualElement.AddHandler(UIElement.GotKeyboardFocusEvent, new KeyboardFocusChangedEventHandler(VisualElement_GotKeyboardFocus), true);
            textView.VisualElement.AddHandler(UIElement.LostKeyboardFocusEvent, new KeyboardFocusChangedEventHandler(VisualElement_LostKeyboardFocus), true);
            textView.LayoutChanged += TextView_LayoutChanged;
            this.textCaretLayer     = new TextCaretLayer(this, caretLayer, classificationFormatMap);
            InputMethod.SetIsInputMethodSuspended(textView.VisualElement, true);
        }
        public override int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            //the snippet picker code starts here
            if (nCmdID == (uint)VSConstants.VSStd2KCmdID.INSERTSNIPPET)
            {
                _manager.InvokeInsertionUI(
                    _vsTextView,
                    this,                   //the expansion client
                    new Guid(_guid),
                    null,                   //use all snippet types
                    0,                      //number of types (0 for all)
                    0,                      //ignored if iCountTypes == 0
                    null,                   //use all snippet kinds
                    0,                      //use all snippet kinds
                    0,                      //ignored if iCountTypes == 0
                    Constants.LanguageName, //the text to show in the prompt
                    string.Empty);          //only the ENTER key causes insert

                return(VSConstants.S_OK);
            }

            if (_session != null)
            {
                if (nCmdID == (uint)VSConstants.VSStd2KCmdID.BACKTAB)
                {
                    _session.GoToPreviousExpansionField();
                    return(VSConstants.S_OK);
                }
                else if (nCmdID == (uint)VSConstants.VSStd2KCmdID.TAB)
                {
                    _session.GoToNextExpansionField(0); //false to support cycling through all the fields
                    return(VSConstants.S_OK);
                }
                else if (nCmdID == (uint)VSConstants.VSStd2KCmdID.RETURN || nCmdID == (uint)VSConstants.VSStd2KCmdID.CANCEL)
                {
                    if (_session.EndCurrentExpansion(0) == VSConstants.S_OK)
                    {
                        _session = null;
                        return(VSConstants.S_OK);
                    }
                }
            }

            if (_session == null && nCmdID == (uint)VSConstants.VSStd2KCmdID.TAB)
            {
                CaretPosition pos        = _view.Caret.Position;
                TextExtent    word       = _navigator.GetTextStructureNavigator(_view.TextBuffer).GetExtentOfWord(pos.BufferPosition - 1);
                string        textString = word.Span.GetText();

                if (InsertAnyExpansion(textString, null, null))
                {
                    EndSession();
                    return(VSConstants.S_OK);
                }
            }

            ThreadHelper.ThrowIfNotOnUIThread();

            return(Next.Exec(pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut));
        }
Example #11
0
        /// <summary>
        /// Check the caret position. If the caret is on a new word, update the CurrentWord value
        /// </summary>
        private void UpdateAtCaretPosition(CaretPosition caretPoisition)
        {
            SnapshotPoint?point = caretPoisition.Point.GetPoint(this._sourceBuffer, caretPoisition.Affinity);

            // If the new cursor position is still within the current word (and on the same snapshot),
            // we don't need to check it.
            TextExtent?newWordExtend = AsmDudeToolsStatic.Get_Keyword(point);

            if (newWordExtend.HasValue)
            {
                string newWord = newWordExtend.Value.Span.GetText();

                if ((this.CurrentWord != null) && newWord.Equals(this.CurrentWord))
                {
                    return;
                }
                else
                {
                    this.RequestedPoint = point.Value;
                    this.NewWord        = newWord;
                    this.NewWordSpan    = newWordExtend.Value.Span;

                    AsmDudeTools.Instance.Thread_Pool.QueueWorkItem(this.Update_Word_Adornments);
                }
            }
        }
        /// <summary>
        /// Gets the current word at the cursor
        /// </summary>
        ///<param name="key">key currently pressed</param>
        private void SetWordAtPointer()
        {
            MergeRuns();
            string textRunBack       = CaretPosition.GetTextInRun(LogicalDirection.Backward); //text from CaretPosition backwards
            string textRunForward    = CaretPosition.GetTextInRun(LogicalDirection.Forward);  //text from CaretPosition forwards
            string wordBeforePointer = new string(textRunBack.Reverse().TakeWhile(c => char.IsLetterOrDigit(c) || (c == '_')).Reverse().ToArray());
            string wordAfterPointer  = new string(textRunForward.TakeWhile(c => char.IsLetterOrDigit(c) || (c == '_')).ToArray());

            _wordAtPointer = wordBeforePointer + wordAfterPointer;
            _wordAtPointer = _wordAtPointer.ToUpper();
            _startWord     = CaretPosition.GetPositionAtOffset(-wordBeforePointer.Length);
            _endWord       = CaretPosition.GetPositionAtOffset(wordAfterPointer.Length);
            if (_isInserting)
            {
                //CaretPosition = _endWord;
            }

#if DEBUG
            Debug.Print("-----SetWordAtPointer()------");
            Debug.Print("textRunBack = {0}", textRunBack);
            Debug.Print("textRunForward = {0}", textRunForward);
            Debug.Print("wordCharactersBeforePointer = {0}", wordBeforePointer);
            Debug.Print("wordCharactersAfterPointer = {0}", wordAfterPointer);
            Debug.Print("wordAtPointer = {0}", _wordAtPointer);
#endif
        }
 /// <summary>
 /// Shows popup, filters assist list based on the last word. Place popup just at the current CaretPosition within RichTextBox
 /// </summary>
 /// <param name="lastWord"></param>
 private void ShowPopup(string lastWord)
 {
     m_assistListPopup.DataContext        = ContentAssistTriggers.FindAll(item => item.StartsWith(lastWord, StringComparison.CurrentCultureIgnoreCase));
     m_assistListPopup.PlacementTarget    = this;
     m_assistListPopup.PlacementRectangle = CaretPosition.GetCharacterRect(LogicalDirection.Forward);
     m_assistListPopup.IsOpen             = true;
 }
        /// <summary>
        /// Determines whether or not the user just entered a triple slash (///) on a blank line.
        /// </summary>
        /// <returns>True if a triple slash occurred on an otherwise blank line, false if it
        /// didn't.</returns>
        /// <remarks>
        /// I tried to make this implementation as robust as possible; it actually figures out where
        /// in the current line the caret lives and adds the "/" character to the line at that location
        /// before checking to see if a triple slash occurred or not. This should get rid of any weird
        /// behavior where a triple slash gets incorrectly triggered when there isn't actually one
        /// on the line (e.g. if there's whitespace between the forward slash characters). As far as
        /// I can tell, this really does only get triggered if there are three contiguous slashes on
        /// an otherwise blank line (leading or trailing whitespace doesn't count).
        /// </remarks>
        private bool UserTypedTripleSlash()
        {
            // Convert the caret's location in screen (pixel) space to the corresponding character index in the editor text box's
            // buffer. We need this to figure out the location of the caret in the current line.
            CaretPosition caretPosition        = TextView.Caret.Position;
            SnapshotPoint?snapshotPointWrapper = caretPosition.Point.GetPoint(TextView.TextSnapshot, caretPosition.Affinity);

            if (snapshotPointWrapper == null)
            {
                return(false);
            }
            SnapshotPoint snapshotPoint = snapshotPointWrapper.Value;

            // Get the current line being edited, along with its starting position in the text snapshot
            ITextSnapshotLine currentLine = snapshotPoint.GetContainingLine();
            string            lineText    = currentLine.GetTextIncludingLineBreak();
            int lineStart = currentLine.Start;

            // Add the forward slash to the line, based on where the caret is
            int caretIndexInLine = snapshotPoint - lineStart;

            lineText = lineText.Insert(caretIndexInLine, "/");

            // Return whether or not the new line is a triple slash
            return(lineText.Trim().Equals("///"));
        }
Example #15
0
        private void UpdateAtCaretPosition(CaretPosition caretPosition)
        {
#pragma warning disable 420 // 'field name': a reference to a volatile field will not be treated as volatile
            var revision = Interlocked.Increment(ref _requestNumber);
#pragma warning restore 420

            CurrentChar = caretPosition.Point.GetPoint(SourceBuffer, caretPosition.Affinity);
            if (!CurrentChar.HasValue)
            {
                if (!TryClearResults(revision))
                {
                    return;
                }
            }
            else
            {
                if (!TrySynchronousUpdate(revision))
                {
                    if (!TryClearResults(revision))
                    {
                        return;
                    }

                    QueueAsynchronousUpdate(revision, CurrentChar.Value);
                }
            }

            var t = TagsChanged;
            if (t != null)
            {
                t(this, new SnapshotSpanEventArgs(new SnapshotSpan(SourceBuffer.CurrentSnapshot, 0, SourceBuffer.CurrentSnapshot.Length)));
            }
        }
Example #16
0
        private TableCaretPosition GetCaretPosition(CaretPosition caretPosition, IHasRows hasRows)
        {
            var line        = caretPosition.BufferPosition.GetContainingLine();
            var caretColumn = caretPosition.BufferPosition.Position - line.Start.Position;
            var row         = hasRows.Rows.FirstOrDefault(r => r.Location.Line == line.LineNumber + 1);

            if (row == null || row.Cells.Any(c => c.Location.Column <= 0))
            {
                return(TableCaretPosition.CreateUnknown(line.LineNumber, caretColumn));
            }

            var cellIndex = FindCellIndex(caretColumn, row, line.GetText(), out var cell);

            if (cellIndex < 0) // before first cell
            {
                return(TableCaretPosition.CreateBeforeFirstCell(line.LineNumber, caretColumn));
            }
            if (cellIndex == int.MaxValue) // after last cell
            {
                return(TableCaretPosition.CreateAfterLastCell(line.LineNumber));
            }

            return(TableCaretPosition.CreateInCell(line.LineNumber, cellIndex,
                                                   Math.Max(caretColumn - (cell.Location.Column - 1), 0)));
        }
Example #17
0
        private bool HandleUpDownKeys(KeyEventArgs args)
        {
            var pos = CaretPosition.CompareTo(_promptInline.ContentEnd);

            if (pos < 0)
            {
                return(false);
            }

            if (!_buffer.Any())
            {
                return(true);
            }

            ClearAfterPrompt();

            string existingLine;

            if (args.Key == Key.Down)
            {
                existingLine = _buffer[_buffer.Count - 1];
                _buffer.RemoveAt(_buffer.Count - 1);
                _buffer.Insert(0, existingLine);
            }
            else
            {
                existingLine = _buffer[0];
                _buffer.RemoveAt(0);
                _buffer.Add(existingLine);
            }

            AddLine(existingLine);

            return(true);
        }
Example #18
0
        private bool HandleLeftKey()
        {
            var promptEnd = _promptInline.ContentEnd;

            var textPointer = GetTextPointer(promptEnd, LogicalDirection.Forward);

            if (textPointer == null)
            {
                var pos = CaretPosition.CompareTo(promptEnd);

                if (pos == 0)
                {
                    return(true);
                }
            }
            else
            {
                var pos = CaretPosition.CompareTo(textPointer);
                if (pos == 0)
                {
                    return(true);
                }
            }

            return(false);
        }
Example #19
0
        private void UpdateClassifications(CaretPosition caretPosition)
        {
            var bufferPosition    = caretPosition.BufferPosition;
            var snapshot          = bufferPosition.Snapshot;
            var position          = bufferPosition.Position;
            var oldMatchingBraces = _matchingBraces;

            if (HasBraceAtPosition(snapshot, position))
            {
                MatchingBraces            newMatchingBraces = null;
                ClassificationParseResult parseResult;
                if (ParseUtil.TryParse(_textBuffer, out parseResult) && snapshot.Version == parseResult.Snapshot.Version)
                {
                    SearchMatchingBraces(parseResult.Tokens, parseResult.Snapshot, position, ref newMatchingBraces);
                }

                _matchingBraces = newMatchingBraces;

                if (null != oldMatchingBraces)
                {
                    NotifyTagsChanged(oldMatchingBraces);
                }

                if (null != newMatchingBraces)
                {
                    NotifyTagsChanged(newMatchingBraces);
                }
            }
            else if (oldMatchingBraces != null)
            {
                _matchingBraces = null;
                NotifyTagsChanged(oldMatchingBraces);
            }
        }
Example #20
0
        private void OnTokenTextChanged(object sender, TextChangedEventArgs e)
        {
            var text = CaretPosition.GetTextInRun(LogicalDirection.Backward);

            if (TokenMatcher != null)
            {
                var token = TokenMatcher(text);
                if (token != null)
                {
                    ReplaceTextWithToken(text, token);
                }
                if (CaretPosition.Paragraph != null)
                {
                    _preventCallback = true;
                    Text             = string.Join(Splitter.ToString(), CaretPosition.Paragraph.Inlines.Where(x => x is InlineUIContainer).Cast
                                                   <InlineUIContainer>().Select(
                                                       x =>
                    {
                        var contentPresenter = x.Child as ContentPresenter;
                        return(contentPresenter != null ? contentPresenter.Content.ToString() : null);
                    }).ToArray());
                    _preventCallback = false;
                }
            }
        }
        /// <summary>
        /// determine last word typed in. Looks for list word until reaches space ' ', or any of the characters: '{', '}', '(', ')', '='
        /// </summary>
        /// <returns></returns>
        private string GetLastWord()
        {
            //Get the last word in the text from current Caret position
            string txtBefore = CaretPosition.GetTextInRun(LogicalDirection.Backward);
            string txtAfter  = CaretPosition.GetTextInRun(LogicalDirection.Forward);

            string[] tokens      = txtBefore.Split(SplitTokens);
            string[] tokensAfter = txtAfter.Split(SplitTokens);
            string   lastToken   = tokens[tokens.Length - 1];

            if (tokensAfter.Length > 0 && string.IsNullOrWhiteSpace(tokensAfter[0]) == false)
            {
                lastToken = lastToken + tokensAfter[0];
            }

            // Make sure that the previous character isn't whitespace - eg. we haven't moved past the last word.
            if (txtBefore.Length > 0)
            {
                string previousString = new string(txtBefore[txtBefore.Length - 1], 1);
                if (string.IsNullOrWhiteSpace(previousString))
                {
                    lastToken = string.Empty;
                }
            }

            return(lastToken);
        }
        void PositionChanged_ITextCaret(CaretLocationEventArgs args)
        {
            //Some unit tests don't initialize full UI representation of MonoTextEditor
            //which means they don't depend on ITextCaret implementation, so we can return here
            //If something is using MonoTextEditor directly(e.g. DiffView) and is not initializing ITextView
            //TextBuffer is null, in that case don't depend on ITextCaret implementation, so we can return here
            if (TextEditor?.TextBuffer == null)
            {
                return;
            }
            // MD doesn't fire textEditor.CaretPositionChanged until after the command has gone completely through the command chain.
            //   Too much VS stuff depends on it getting updated earlier, so we'll use this event which fires earlier.
            int position             = TextEditor.Caret.Offset;
            VirtualSnapshotPoint vsp = new VirtualSnapshotPoint(TextEditor.TextSnapshot, position);

            insertionPoint = vsp;
            if (args.CaretChangeReason == CaretChangeReason.Movement)
            {
                oldCaretLocation = args.Location;
                var oldOffset        = TextEditor.LocationToOffset(args.Location);
                var snapshotPoint    = new SnapshotPoint(TextEditor.TextSnapshot, oldOffset);
                var mappingPoint     = TextEditor.BufferGraph.CreateMappingPoint(snapshotPoint, PointTrackingMode.Positive);
                var oldCaretPosition = new CaretPosition(vsp, mappingPoint, _caretAffinity);
                var eventArgs        = new CaretPositionChangedEventArgs(TextEditor, oldCaretPosition, ((ITextCaret)this).Position);

                ITextCaret_PositionChanged?.Invoke(this, eventArgs);
            }
        }
        private void RemoveLastWord()
        {
            int         lastWordLength = GetLastWord().Length;
            TextPointer deletePosition = CaretPosition.GetPositionAtOffset(-lastWordLength, LogicalDirection.Forward);

            deletePosition.DeleteTextInRun(lastWordLength);
        }
        public void HandleClick(bool addCursor)
        {
            if (addCursor && m_textView.Selection.SelectedSpans.All(span => span.Length == 0))
            {
                if (m_textView.Selection.SelectedSpans.Count == 1)
                {
                    if (m_trackList.Count == 0)
                    {
                        AddSyncPoint(lastCaretPosition);
                    }

                    AddSyncPoint(m_textView.Caret.Position);
                    RedrawScreen();
                }
                else
                {
                    foreach (var span in m_textView.Selection.SelectedSpans)
                    {
                        AddSyncPoint(span.Start.Position);
                    }

                    m_textView.Selection.Clear();
                    RedrawScreen();
                }
            }
            else if (m_trackList.Any())
            {
                ClearSyncPoints();
                RedrawScreen();
            }

            lastCaretPosition = m_textView.Caret.Position;
        }
Example #25
0
    private Digit findAdjacentMathDigits(LogicalDirection direction)
    {
        Digit expr = null;

        if (Selection.Text.Length == 0)
        {
            DependencyObject dpObj = CaretPosition.GetAdjacentElement(
                direction);
            // is it contained in BlockUIContainer?
            expr = CaretPosition.GetAdjacentElement(
                direction) as Digit;
            // is it onctained in a InlineUIContainer?
            if (expr == null)
            {
                InlineUIContainer uiWrapper =
                    CaretPosition.GetAdjacentElement(
                        direction) as InlineUIContainer;
                if (uiWrapper != null)
                {
                    expr = uiWrapper.Child as Digit;
                }
            }
        }
        return(expr);
    }
Example #26
0
        protected override void Execute()
        {
            var editorController = SdlTradosStudio.Application.GetController <EditorController>();
            var document         = editorController.ActiveDocument;

            if (document == null)
            {
                return;
            }
            var viewPartController =
                SdlTradosStudio.Application.GetController <RegexMatchAutoSuggestProviderViewPartController>();

            if (viewPartController == null)
            {
                return;
            }
            var regexPatternEntries = viewPartController.RegexPatternEntries;

            if (regexPatternEntries == null)
            {
                return;
            }

            var segmentPair = document.ActiveSegmentPair;

            if (segmentPair == null)
            {
                return;
            }
            if (document.FocusedDocumentContent != FocusedDocumentContent.Target)
            {
                return;
            }

            var activeProcess = CaretPosition.GetActiveProcess();

            if (activeProcess != "SDLTradosStudio")
            {
                return;
            }

            var text = string.Join("", segmentPair.Source.AllSubItems.OfType <IText>().Select(txt => txt.Properties.Text));

            Task <List <AutoSuggestEntry> > .Factory.StartNew(
                () =>
            {
                var variables = viewPartController.Variables;
                return(regexPatternEntries.GetAutoSuggestEntries(text, variables));
            })
            .ContinueWith(task =>
            {
                if (task.Result.Count > 0)
                {
                    var content       = new PopupWindowContent(task.Result);
                    var caretPosition = CaretPosition.EvaluateCarePosition();
                    _popupToolStrip.Show(caretPosition, content);
                }
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
Example #27
0
        private void OnDragOver(object sender, Telerik.Windows.DragDrop.DragEventArgs e)
        {
            Point mousepos = e.GetPosition(this.syntaxEditor.EditorPresenter);

            dropPos = this.syntaxEditor.EditorPresenter.GetPositionFromViewPoint(mousepos);
            this.syntaxEditor.CaretPosition.MoveToPosition(dropPos);
            this.syntaxEditor.Focus();
        }
 private void UpdateAtCaretPosition(CaretPosition caretPoisition)
 {
     // Check if the current caret position is within our region. If it is, raise the RegionSelected event.
     if (_trackingSpan.GetSpan(_trackingSpan.TextBuffer.CurrentSnapshot).Contains(caretPoisition.Point.GetPoint(_trackingSpan.TextBuffer, PositionAffinity.Predecessor).Value))
     {
         OnRaiseRegionSelected(new EventArgs());
     }
 }
Example #29
0
        private void UpdateAtCaretPosition(CaretPosition caretPos)
        {
            caretPosition = caretPos.VirtualBufferPosition.Position;

            ITextSnapshot currentSnapshot = this.textBuffer.CurrentSnapshot;

            TagsChanged?.Invoke(this, new SnapshotSpanEventArgs(new SnapshotSpan(currentSnapshot, 0, currentSnapshot.Length)));
        }
Example #30
0
        private void MakeSelection(CaretPosition topPoint, CaretPosition bottomPoint)
        {
            var selection = (EnvDTE.TextSelection)document.Selection;

            selection.MoveToLineAndOffset(topPoint.Line, topPoint.LineCharOffset);
            selection.SwapAnchor();
            selection.MoveToLineAndOffset(bottomPoint.Line, bottomPoint.LineCharOffset, true);
        }
 public MultiPointEditCommandFilter(IWpfTextView tv)
 {
     m_textView = tv;
     m_adornmentLayer = tv.GetAdornmentLayer("MultiEditLayer");
     m_trackList = new List<ITrackingPoint>();
     lastCaretPosition = m_textView.Caret.Position;
     m_textView.LayoutChanged += m_textView_LayoutChanged;
     m_dte = ServiceProvider.GlobalProvider.GetService(typeof(DTE)) as DTE2;
 }
Example #32
0
        private void Highlight(NodeProvider provider, CaretPosition position)
        {
            SnapshotPoint point = position.BufferPosition;

            List<DesignerNode> tags = provider.GetNodes(point, node => node.NodeType == NDjango.Interfaces.NodeType.TagName);
            DesignerNode selected = tags.Count == 0 ? null : tags[0];

            DesignerNode highlighted = null;
            point.Snapshot.TextBuffer.Properties.TryGetProperty<DesignerNode>(typeof(Highlighter), out highlighted);
            if (selected != highlighted)
            {
                point.Snapshot.TextBuffer.Properties[typeof(Highlighter)] = selected;
                provider.RaiseNodesChanged(point.Snapshot);
            }
        }
Example #33
0
        public ValueEditBox SwitchFocus(int nLineIndex,
            CaretPosition caretposition)
        {
            if (nLineIndex >= templateRoot.Lines.Count)
                return null; // 下标越界

            TemplateLine line = (TemplateLine)templateRoot.Lines[nLineIndex];

            ChangeFocusDisplay(line.TextBox_value);

            line.TextBox_value.Focus();
            // this.ScrollToControl(line.TextBox_value);


            if (caretposition == CaretPosition.FirstChar)
            {
                line.TextBox_value.SelectionStart = 0;
                line.TextBox_value.SelectionLength = 0;
            }

            if (caretposition == CaretPosition.LastChar)
            {
                line.TextBox_value.SelectionStart = line.TextBox_value.MaxLength - 1;
                line.TextBox_value.SelectionLength = 0;
            }

            return line.TextBox_value;
        }
        public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            Debug.WriteLine(nCmdID);

            if (pguidCmdGroup == typeof(VSConstants.VSStd2KCmdID).GUID)
            {
                switch (nCmdID)
                {
                    case ((uint)VSConstants.VSStd2KCmdID.ECMD_LEFTCLICK):
                        if (Keyboard.Modifiers == ModifierKeys.Alt && m_textView.Selection.SelectedSpans.Count == 1)
                        {

                            if (m_trackList.Count == 0)
                                AddSyncPoint(lastCaretPosition);
                            AddSyncPoint(m_textView.Caret.Position);
                            RedrawScreen();

                        }
                        else if (m_trackList.Any())
                        {
                            ClearSyncPoints();
                            RedrawScreen();
                        }
                        lastCaretPosition = m_textView.Caret.Position;
                        break;
                    case ((uint)VSConstants.VSStd2KCmdID.TYPECHAR):
                    case ((uint)VSConstants.VSStd2KCmdID.BACKSPACE):
                    case ((uint)VSConstants.VSStd2KCmdID.TAB):
                    case ((uint)VSConstants.VSStd2KCmdID.LEFT):
                    case ((uint)VSConstants.VSStd2KCmdID.RIGHT):
                    case ((uint)VSConstants.VSStd2KCmdID.UP):
                    case ((uint)VSConstants.VSStd2KCmdID.DOWN):
                    case ((uint)VSConstants.VSStd2KCmdID.END):
                    case ((uint)VSConstants.VSStd2KCmdID.HOME):
                    case ((uint)VSConstants.VSStd2KCmdID.PAGEDN):
                    case ((uint)VSConstants.VSStd2KCmdID.PAGEUP):
                    case ((uint)VSConstants.VSStd2KCmdID.PASTE):
                    case ((uint)VSConstants.VSStd2KCmdID.PASTEASHTML):
                    case ((uint)VSConstants.VSStd2KCmdID.BOL):
                    case ((uint)VSConstants.VSStd2KCmdID.EOL):
                    case ((uint)VSConstants.VSStd2KCmdID.RETURN):
                    case ((uint)VSConstants.VSStd2KCmdID.BACKTAB):

                        if (m_trackList.Count > 0)
                            return SyncedOperation(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
                        break;
                    default:
                        break;
                }
            }
            else if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97)
            {
                switch (nCmdID)
                {

                    case ((uint)VSConstants.VSStd97CmdID.Delete):
                    case ((uint)VSConstants.VSStd97CmdID.Paste):
                        if (m_trackList.Count > 0)
                            return SyncedOperation(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
                        break;
                    default:
                        break;
                }
            }

            switch (nCmdID)
            {

                // When ESC is used, cancel the Multi Edit mode
                case ((uint)VSConstants.VSStd2KCmdID.CANCEL):
                    ClearSyncPoints();
                    RedrawScreen();
                    break;
                default:
                    break;
            }

            return NextTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
        }
Example #35
0
        private void UpdateCaretPosition(CaretPosition caret)
        {
            ITextBuffer currentBuffer = GetSelectedBuffer();
              if ( currentBuffer == null ) {
            return;
              }
              SnapshotPoint? bufferPos = null;

              if ( currentBuffer == caret.BufferPosition.Snapshot.TextBuffer ) {
            bufferPos = caret.BufferPosition;
              } else {
            bufferPos = this.textView.BufferGraph.MapDownToBuffer(
               caret.BufferPosition, PointTrackingMode.Negative,
               currentBuffer, PositionAffinity.Predecessor
               );
            if ( !bufferPos.HasValue ) {
              bufferPos = this.textView.BufferGraph.MapUpToBuffer(
             caret.BufferPosition, PointTrackingMode.Negative,
             PositionAffinity.Predecessor, currentBuffer
             );
            }
              }
              if ( bufferPos.HasValue ) {
            this.model.BufferPosition = bufferPos.Value.Position.ToString();
              } else {
            this.model.BufferPosition = "--";
              }
        }
Example #36
0
        /// <summary>
        /// Function returning the index of the character whose origin is closest to the cursor.
        /// </summary>
        /// <param name="textComponent">A reference to the text object.</param>
        /// <param name="position">Position to check for intersection.</param>
        /// <param name="camera">The scene camera which may be assigned to a Canvas using ScreenSpace Camera or WorldSpace render mode. Set to null is using ScreenSpace Overlay.</param>
        /// <param name="cursor">The position of the cursor insertion position relative to the position.</param>
        /// <returns></returns>
        public static int GetCursorIndexFromPosition(TMP_Text textComponent, Vector3 position, Camera camera, out CaretPosition cursor)
        {
            int index = TMP_TextUtilities.FindNearestCharacter(textComponent, position, camera, false);

            RectTransform rectTransform = textComponent.rectTransform;

            // Convert position into Worldspace coordinates
            ScreenPointToWorldPointInRectangle(rectTransform, position, camera, out position);

            TMP_CharacterInfo cInfo = textComponent.textInfo.characterInfo[index];

            // Get Bottom Left and Top Right position of the current character
            Vector3 bl = rectTransform.TransformPoint(cInfo.bottomLeft);
            Vector3 tr = rectTransform.TransformPoint(cInfo.topRight);

            float insertPosition = (position.x - bl.x) / (tr.x - bl.x);

            if (insertPosition < 0.5f)
            {
                cursor = CaretPosition.Left;
                return index;
            }
            else
            {
                cursor = CaretPosition.Right;
                return index + 1;
            }
        }
Example #37
0
 public CaretInfo(int index, CaretPosition position)
 {
     this.index = index;
     this.position = position;
 }
Example #38
0
 private ITextViewLine GetLineByPos(CaretPosition pos)
 {
     return view.GetTextViewLineContainingBufferPosition(pos.BufferPosition);
 }
Example #39
0
        private static bool ShouldWrapPrelim(
            bool optionsAutoWrapEnabled,
            int optionsAvoidWrappingBeforeLine,
            INormalizedTextChangeCollection changes,
            ITextSnapshot snapshot,
            ITextBuffer buffer,
            CaretPosition caretPosition,
            out SnapshotPoint caretPoint,
            out int firstLine)
        {
            caretPoint = default(SnapshotPoint);
            firstLine = -1;

            if (!optionsAutoWrapEnabled)
            {
                return false;
            }

            if (!buffer.CheckEditAccess())
            {
                return false;
            }

            // The auto-wrap should only apply during simple typing.  Region
            // edits (simultaneous multi-line typing) could lead to truly bizarre
            // wrapping behavior, so it really doesn't make sense.
            if (changes.Count > 1)
            {
                return false;
            }

            // Need a better (more testable!) way to get the editing state
            // (change, caret, etc.) out.  Perhaps we just take the hit and get
            // all of these up front instead of only calculating them as needed?
            var change = changes[0];
            caretPoint = caretPosition.Point.GetPoint(snapshot, caretPosition.Affinity).GetValueOrDefault();

            // If the caret isn't near the change, this was an undo, or other operation
            // we shouldn't wrap on!
            if ((caretPoint.Snapshot != snapshot) ||
                (caretPoint < change.NewPosition) ||
                (caretPoint > change.NewEnd))
            {
                return false;
            }

            firstLine = snapshot.GetLineNumberFromPosition(change.NewPosition);

            // If we're in the "don't auto-wrap" leading lines, bail.
            if (firstLine < optionsAvoidWrappingBeforeLine)
            {
                return false;
            }

            return true;
        }
        private void AddSyncPoint(CaretPosition caretPosition)
        {
            CaretPosition curPosition = caretPosition;
            // We don't support Virtual Spaces [yet?]

            var curTrackPoint = m_textView.TextSnapshot.CreateTrackingPoint(curPosition.BufferPosition.Position, PointTrackingMode.Positive);
            // Check if the bounds are valid

            if (curTrackPoint.GetPosition(m_textView.TextSnapshot) >= 0)

                m_trackList.Add(curTrackPoint);
            else
            {
                curTrackPoint = m_textView.TextSnapshot.CreateTrackingPoint(0, PointTrackingMode.Positive);
                m_trackList.Add(curTrackPoint);
            }

            if (curPosition.VirtualSpaces > 0)
            {
                m_textView.Caret.MoveTo(curTrackPoint.GetPoint(m_textView.TextSnapshot));
            }
        }
        public void HandleClick(bool addCursor)
        {
            if (addCursor && m_textView.Selection.SelectedSpans.All(span => span.Length == 0))
            {
                if (m_textView.Selection.SelectedSpans.Count == 1)
                {
                    if (m_trackList.Count == 0)
                        AddSyncPoint(lastCaretPosition);

                    AddSyncPoint(m_textView.Caret.Position);
                    RedrawScreen();
                }
                else
                {
                    foreach (var span in m_textView.Selection.SelectedSpans)
                        AddSyncPoint(span.Start.Position);

                    m_textView.Selection.Clear();
                    RedrawScreen();
                }
            }
            else if (m_trackList.Any())
            {
                ClearSyncPoints();
                RedrawScreen();
            }

            lastCaretPosition = m_textView.Caret.Position;
        }
Example #42
0
 private ITextViewLine GetLineByPos(CaretPosition pos)
 {
     SnapshotPoint point = pos.BufferPosition;
       if ( point.Snapshot != view.TextSnapshot ) {
     point = point.TranslateTo(view.TextSnapshot, PointTrackingMode.Positive);
       }
       return view.GetTextViewLineContainingBufferPosition(point);
 }
Example #43
0
		bool IsRetriggerCharacter(CaretPosition caretPos) {
			Debug.Assert(session != null);
			if (session == null)
				return false;
			if (caretPos.VirtualSpaces > 0)
				return false;
			char c = caretPos.BufferPosition.GetChar();
			return session.IsTriggerCharacter(c) || session.IsRetriggerCharacter(c);
		}
Example #44
0
 private void UpdateAtCaretPosition(CaretPosition caretPoisition)
 {
     // Check if the current caret position is within our region. If it is, raise the RegionSelected event.
     if (m_trackingSpan.GetSpan(m_trackingSpan.TextBuffer.CurrentSnapshot).Contains(caretPoisition.Point.GetPoint(m_trackingSpan.TextBuffer, PositionAffinity.Predecessor).Value))
     {
         OnRaiseRegionSelected(new EventArgs());
     }
 }
Example #45
0
		bool IsInSignature(ISignature signature, CaretPosition caretPos) {
			if (caretPos.VirtualSpaces > 0)
				return false;
			var atSpan = signature.ApplicableToSpan;
			if (atSpan == null)
				return false;
			var span = atSpan.GetSpan(caretPos.BufferPosition.Snapshot);
			return span.IntersectsWith(new SnapshotSpan(caretPos.BufferPosition, 0));
		}