3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alejandro Aguilar Sierra
7 * \author Alfredo Braunstein
8 * \author Dov Feldstern
10 * \author Stefan Schimanski
12 * Full author contact details are available in file CREDITS.
18 #include "BufferView.h"
19 #include "CoordCache.h"
21 #include "CutAndPaste.h"
22 #include "DispatchResult.h"
24 #include "FuncRequest.h"
26 #include "LyXAction.h"
28 #include "Paragraph.h"
29 #include "ParIterator.h"
31 #include "texstream.h"
33 #include "TextMetrics.h"
34 #include "TocBackend.h"
36 #include "support/debug.h"
37 #include "support/docstream.h"
38 #include "support/ExceptionMessage.h"
39 #include "support/gettext.h"
40 #include "support/lassert.h"
42 #include "insets/InsetTabular.h"
43 #include "insets/InsetText.h"
45 #include "mathed/InsetMath.h"
46 #include "mathed/InsetMathBrace.h"
47 #include "mathed/InsetMathEnsureMath.h"
48 #include "mathed/InsetMathScript.h"
49 #include "mathed/MacroTable.h"
50 #include "mathed/MathData.h"
51 #include "mathed/MathFactory.h"
52 #include "mathed/InsetMathMacro.h"
65 // Find position closest to (x, y) in cell given by iter.
66 // Used only in mathed
67 DocIterator bruteFind(Cursor const & c, int x, int y)
69 double best_dist = numeric_limits<double>::max();
76 et.pos() = et.lastpos();
77 for (size_t i = 0;; ++i) {
80 Inset const * inset = &it.inset();
81 CoordCache::Insets const & insetCache = c.bv().coordCache().getInsets();
83 // FIXME: in the case where the inset is not in the cache, this
84 // means that no part of it is visible on screen. In this case
85 // we don't do elaborate search and we just return the forwarded
86 // DocIterator at its beginning.
87 if (!insetCache.has(inset)) {
92 Point const o = insetCache.xy(inset);
93 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
94 // Convert to absolute
97 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
98 // '<=' in order to take the last possible position
99 // this is important for clicking behind \sum in e.g. '\sum_i a'
100 LYXERR(Debug::DEBUG, "i: " << i << " d: " << d
101 << " best: " << best_dist);
102 if (d <= best_dist) {
122 CursorData::CursorData()
123 : DocIterator(), anchor_(), selection_(false), mark_(false),
124 word_selection_(false), autocorrect_(false), current_font(inherit_font)
128 CursorData::CursorData(Buffer * buffer)
129 : DocIterator(buffer), anchor_(), selection_(false), mark_(false),
130 word_selection_(false), autocorrect_(false), current_font(inherit_font)
134 CursorData::CursorData(DocIterator const & dit)
135 : DocIterator(dit), anchor_(), selection_(false), mark_(false),
136 word_selection_(false), autocorrect_(false), current_font(inherit_font)
142 ostream & operator<<(ostream & os, CursorData const & cur)
144 os << "\n cursor: | anchor:\n";
145 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
146 os << " " << cur[i] << " | ";
147 if (i < cur.anchor_.depth())
148 os << cur.anchor_[i];
150 os << "-------------------------------";
153 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
154 os << "------------------------------- | " << cur.anchor_[i] << "\n";
156 os << " selection: " << cur.selection_
157 // << " x_target: " << cur.x_target_
158 << " boundary: " << cur.boundary() << endl;
163 LyXErr & operator<<(LyXErr & os, CursorData const & cur)
170 void CursorData::reset()
173 push_back(CursorSlice(buffer()->inset()));
174 anchor_ = doc_iterator_begin(buffer());
176 new_word_ = doc_iterator_begin(buffer());
183 void CursorData::setCursor(DocIterator const & cur)
185 DocIterator::operator=(cur);
189 void CursorData::setCursorSelectionTo(DocIterator dit)
193 while (i < dit.depth() && i < anchor_.depth() && dit[i] == anchor_[i])
195 if (i != dit.depth()) {
196 // otherwise the cursor is already normal
197 if (i == anchor_.depth())
198 // dit is a proper extension of the anchor_
200 else if (i + 1 < dit.depth()) {
201 // one has dit[i] != anchor_[i] but either dit[i-1] == anchor_[i-1]
202 // or i == 0. Remove excess.
204 if (dit[i] > anchor_[i])
205 // place dit after the inset it was in
214 void CursorData::setCursorToAnchor()
217 DocIterator normal = anchor_;
218 while (depth() < normal.depth())
220 if (depth() < anchor_.depth() && top() <= anchor_[depth() - 1])
227 CursorSlice CursorData::normalAnchor() const
231 // LASSERT: There have been several bugs around this code, that seem
232 // to involve failures to reset the anchor. We can at least not crash
233 // in release mode by resetting it ourselves.
234 if (anchor_.depth() < depth()) {
235 LYXERR0("Cursor is deeper than anchor. PLEASE REPORT.\nCursor is"
237 const_cast<DocIterator &>(anchor_) = *this;
240 CursorSlice normal = anchor_[depth() - 1];
241 if (depth() < anchor_.depth() && top() <= normal) {
242 // anchor is behind cursor -> move anchor behind the inset
249 void CursorData::setSelection()
252 if (idx() == normalAnchor().idx() &&
253 pit() == normalAnchor().pit() &&
254 pos() == normalAnchor().pos())
259 void CursorData::setSelection(DocIterator const & where, int n)
268 void CursorData::resetAnchor()
271 checkNewWordPosition();
275 CursorSlice CursorData::selBegin() const
279 return normalAnchor() < top() ? normalAnchor() : top();
283 CursorSlice CursorData::selEnd() const
287 return normalAnchor() > top() ? normalAnchor() : top();
291 DocIterator CursorData::selectionBegin() const
297 // FIXME: This is a work-around for the problem that
298 // CursorSlice doesn't keep track of the boundary.
299 if (normalAnchor() == top())
300 di = anchor_.boundary() > boundary() ? anchor_ : *this;
302 di = normalAnchor() < top() ? anchor_ : *this;
308 DocIterator CursorData::selectionEnd() const
314 // FIXME: This is a work-around for the problem that
315 // CursorSlice doesn't keep track of the boundary.
316 if (normalAnchor() == top())
317 di = anchor_.boundary() < boundary() ? anchor_ : *this;
319 di = normalAnchor() > top() ? anchor_ : *this;
321 if (di.depth() > depth()) {
331 docstring parbreak(CursorData const * cur)
335 // only add blank line if we're not in a ParbreakIsNewline situation
336 if (!cur->inset().getLayout().parbreakIsNewline()
337 && !cur->paragraph().layout().parbreak_is_newline)
345 docstring CursorData::selectionAsString(bool with_label) const
351 return cap::grabSelection(*this);
353 int const label = with_label
354 ? AS_STR_LABEL | AS_STR_INSETS : AS_STR_INSETS;
356 idx_type const startidx = selBegin().idx();
357 idx_type const endidx = selEnd().idx();
358 if (startidx != endidx) {
359 // multicell selection
360 InsetTabular * table = inset().asInsetTabular();
361 LASSERT(table, return docstring());
362 return table->asString(startidx, endidx);
365 ParagraphList const & pars = text()->paragraphs();
367 pit_type const startpit = selBegin().pit();
368 pit_type const endpit = selEnd().pit();
369 size_t const startpos = selBegin().pos();
370 size_t const endpos = selEnd().pos();
372 if (startpit == endpit)
373 return pars[startpit].asString(startpos, endpos, label);
375 // First paragraph in selection
376 docstring result = pars[startpit].
377 asString(startpos, pars[startpit].size(), label)
380 // The paragraphs in between (if any)
381 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
382 Paragraph const & par = pars[pit];
383 result += par.asString(0, par.size(), label)
387 // Last paragraph in selection
388 result += pars[endpit].asString(0, endpos, label);
394 void CursorData::info(odocstream & os, bool devel_mode) const
396 for (int i = 1, n = depth(); i < n; ++i) {
397 operator[](i).inset().infoize(os);
401 Inset const * inset = prevInset();
402 // prevInset() can return 0 in certain case.
404 prevInset()->infoize2(os);
407 InsetMath * math = inset().asInsetMath();
409 os << _(", Inset: ") << math->id();
410 os << _(", Cell: ") << idx();
411 os << _(", Position: ") << pos();
416 docstring CursorData::currentState(bool devel_mode) const
420 info(os, devel_mode);
425 return text()->currentState(*this, devel_mode);
431 void CursorData::markNewWordPosition()
433 if (lyxrc.spellcheck_continuously && inTexted() && new_word_.empty()) {
434 FontSpan nw = locateWord(WHOLE_WORD);
435 if (nw.size() == 1) {
436 LYXERR(Debug::DEBUG, "start new word: "
438 << " pos: " << nw.first);
445 void CursorData::clearNewWordPosition()
447 if (!new_word_.empty()) {
448 LYXERR(Debug::DEBUG, "clear new word: "
450 << " pos: " << pos());
456 void CursorData::checkNewWordPosition()
458 if (!lyxrc.spellcheck_continuously || new_word_.empty())
460 // forget the position of the current new word if
461 // 1) or the remembered position was "broken"
462 // 2) or the count of nested insets changed
463 // 3) the top-level inset is not the same anymore
464 // 4) the cell index changed
465 // 5) or the paragraph changed
466 // 6) or the cursor pos is out of paragraph bound
467 if (new_word_.fixIfBroken()
468 || depth() != new_word_.depth()
469 || &inset() != &new_word_.inset()
470 || pit() != new_word_.pit()
471 || idx() != new_word_.idx()
472 || new_word_.pos() > new_word_.lastpos())
473 clearNewWordPosition();
475 FontSpan nw = locateWord(WHOLE_WORD);
477 FontSpan ow = new_word_.locateWord(WHOLE_WORD);
478 if (nw.intersect(ow).empty())
479 clearNewWordPosition();
481 LYXERR(Debug::DEBUG, "new word: "
483 << " pos: " << nw.first << ".." << nw.last);
485 clearNewWordPosition();
490 void CursorData::clearSelection()
493 setWordSelection(false);
499 bool CursorData::fixIfBroken()
501 bool const broken_cursor = DocIterator::fixIfBroken();
502 bool const broken_anchor = anchor_.fixIfBroken();
504 if (broken_cursor || broken_anchor) {
505 clearNewWordPosition();
513 void CursorData::sanitize()
515 DocIterator::sanitize();
516 new_word_.sanitize();
524 bool CursorData::isInside(Inset const * p) const
526 for (size_t i = 0; i != depth(); ++i)
527 if (&operator[](i).inset() == p)
533 void CursorData::leaveInset(Inset const & inset)
535 for (size_t i = 0; i != depth(); ++i) {
536 if (&operator[](i).inset() == &inset) {
544 bool CursorData::textUndo()
546 if (!buffer()->undo().textUndo(*this))
553 bool CursorData::textRedo()
555 if (!buffer()->undo().textRedo(*this))
562 void CursorData::finishUndo() const
564 buffer()->undo().finishUndo();
568 void CursorData::beginUndoGroup() const
570 buffer()->undo().beginUndoGroup(*this);
574 void CursorData::endUndoGroup() const
576 buffer()->undo().endUndoGroup(*this);
580 void CursorData::recordUndo(pit_type from, pit_type to) const
582 buffer()->undo().recordUndo(*this, from, to);
586 void CursorData::recordUndo(pit_type from) const
588 buffer()->undo().recordUndo(*this, from, pit());
592 void CursorData::recordUndo(UndoKind kind) const
594 buffer()->undo().recordUndo(*this, kind);
598 void CursorData::recordUndoInset(Inset const * in) const
600 buffer()->undo().recordUndoInset(*this, in);
604 void CursorData::recordUndoFullBuffer() const
606 buffer()->undo().recordUndoFullBuffer(*this);
610 void CursorData::recordUndoBufferParams() const
612 buffer()->undo().recordUndoBufferParams(*this);
616 void CursorData::recordUndoSelection() const
619 if (cap::multipleCellsSelected(*this))
624 buffer()->undo().recordUndo(*this,
625 selBegin().pit(), selEnd().pit());
630 int CursorData::currentMode()
632 LASSERT(!empty(), return Inset::UNDECIDED_MODE);
633 for (int i = depth() - 1; i >= 0; --i) {
634 int res = operator[](i).inset().currentMode();
635 bool locked_mode = operator[](i).inset().lockedMode();
636 // Also return UNDECIDED_MODE when the mode is locked,
637 // as in this case it is treated the same as TEXT_MODE
638 if (res != Inset::UNDECIDED_MODE || locked_mode)
641 return Inset::TEXT_MODE;
645 bool CursorData::confirmDeletion(bool const before) const
648 if (Inset const * inset = before ? prevInset() : nextInset())
649 return inset->confirmDeletion();
651 DocIterator dit = selectionBegin();
652 CursorSlice const end = selectionEnd().top();
653 for (; dit.top() < end; dit.top().forwardPos())
654 if (Inset const * inset = dit.nextInset())
655 if (inset->confirmDeletion())
668 // be careful: this is called from the bv's constructor, too, so
669 // bv functions are not yet available!
670 Cursor::Cursor(BufferView & bv)
671 : CursorData(&bv.buffer()), bv_(&bv),
672 x_target_(-1), textTargetOffset_(0),
673 beforeDispatchPosX_(0), beforeDispatchPosY_(0)
684 void Cursor::setCursorData(CursorData const & data)
686 CursorData::operator=(data);
690 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
694 // Try to fix cursor in case it is broken.
697 // Is this a function that acts on inset at point?
698 Inset * inset = cur.nextInset();
699 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
700 && inset && inset->getStatus(cur, cmd, status))
703 // This is, of course, a mess. Better create a new doc iterator and use
704 // this in Inset::getStatus. This might require an additional
705 // BufferView * arg, though (which should be avoided)
706 //Cursor safe = *this;
708 for ( ; cur.depth(); cur.pop()) {
709 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
710 // LASSERT: Is it safe to continue here, or should we return?
711 LASSERT(cur.idx() <= cur.lastidx(), /**/);
712 LASSERT(cur.pit() <= cur.lastpit(), /**/);
713 LASSERT(cur.pos() <= cur.lastpos(), /**/);
715 // The inset's getStatus() will return 'true' if it made
716 // a definitive decision on whether it want to handle the
717 // request or not. The result of this decision is put into
718 // the 'status' parameter.
719 if (cur.inset().getStatus(cur, cmd, status)) {
728 void Cursor::saveBeforeDispatchPosXY()
730 getPos(beforeDispatchPosX_, beforeDispatchPosY_);
734 void Cursor::dispatch(FuncRequest const & cmd0)
736 LYXERR(Debug::ACTION, "Cursor::dispatch: cmd: " << cmd0 << '\n' << *this);
741 FuncRequest cmd = cmd0;
744 disp_ = DispatchResult();
748 // Is this a function that acts on inset at point?
749 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
751 disp_.dispatched(true);
752 disp_.screenUpdate(Update::FitCursor | Update::Force);
753 FuncRequest tmpcmd = cmd;
754 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
755 << cmd0 << endl << *this);
756 nextInset()->dispatch(*this, tmpcmd);
757 if (disp_.dispatched()) {
763 // store some values to be used inside of the handlers
764 beforeDispatchCursor_ = *this;
765 for (; depth(); pop(), boundary(false)) {
766 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
767 << cmd0 << endl << *this);
769 // In any of these cases, the cursor is invalid, and we should
770 // try to save this document rather than crash.
771 LBUFERR(pos() <= lastpos());
772 LBUFERR(idx() <= lastidx());
773 LBUFERR(pit() <= lastpit());
775 // The common case is 'LFUN handled, need update', so make the
776 // LFUN handler's life easier by assuming this as default value.
777 // The handler can reset the update and val flags if necessary.
778 disp_.screenUpdate(Update::FitCursor | Update::Force);
779 disp_.dispatched(true);
780 inset().dispatch(*this, cmd);
781 if (disp_.dispatched())
785 // it completely to get a 'bomb early' behaviour in case this
786 // object will be used again.
787 if (!disp_.dispatched()) {
788 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
789 // We might have invalidated the cursor when removing an empty
790 // paragraph while the cursor could not be moved out the inset
791 // while we initially thought we could. This might happen when
792 // a multiline inset becomes an inline inset when the second
793 // paragraph is removed.
794 if (safe.pit() > safe.lastpit()) {
795 safe.pit() = safe.lastpit();
796 safe.pos() = safe.lastpos();
799 disp_.screenUpdate(Update::None);
800 disp_.dispatched(false);
802 // restore the previous one because nested Cursor::dispatch calls
803 // are possible which would change it
804 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
808 // NOTE: The code below has been copied to BufferView::dispatch.
809 // If you need to modify this, please update the other one too.
811 // notify insets we just left
813 old.beginUndoGroup();
815 bool badcursor = notifyCursorLeavesOrEnters(old, *this);
818 bv().resetInlineCompletionPos();
825 DispatchResult const & Cursor::result() const
831 void Cursor::message(docstring const & msg) const
833 disp_.setMessage(msg);
837 void Cursor::errorMessage(docstring const & msg) const
839 disp_.setMessage(msg);
840 disp_.setError(true);
844 BufferView & Cursor::bv() const
853 LBUFERR(depth() >= 1);
858 void Cursor::push(Inset & p)
860 push_back(CursorSlice(p));
861 p.setBuffer(*buffer());
865 void Cursor::pushBackward(Inset & p)
867 LASSERT(!empty(), return);
868 //lyxerr << "Entering inset " << t << " front" << endl;
874 bool Cursor::popBackward()
876 LASSERT(!empty(), return false);
884 bool Cursor::popForward()
886 LASSERT(!empty(), return false);
887 //lyxerr << "Leaving inset from in back" << endl;
888 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
892 pos() += lastpos() - lp + 1;
897 void Cursor::getPos(int & x, int & y) const
899 Point p = bv().getPos(*this);
905 Row const & Cursor::textRow() const
907 CursorSlice const & cs = innerTextSlice();
908 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
909 return pm.getRow(pos(), boundary());
913 bool Cursor::posVisRight(bool skip_inset)
915 Cursor new_cur = *this; // where we will move to
916 pos_type left_pos; // position visually left of current cursor
917 pos_type right_pos; // position visually right of current cursor
919 getSurroundingPos(left_pos, right_pos);
921 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
923 // Are we at an inset?
924 new_cur.pos() = right_pos;
925 new_cur.boundary(false);
927 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
928 // we actually move the cursor at the end of this
929 // function, for now we just keep track of the new
930 // position in new_cur...
931 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
934 // Are we already at rightmost pos in row?
935 else if (text()->empty() || right_pos == -1) {
938 if (!new_cur.posVisToNewRow(false)) {
939 LYXERR(Debug::RTL, "not moving!");
943 // we actually move the cursor at the end of this
944 // function, for now just keep track of the new
945 // position in new_cur...
946 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
947 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
950 // normal movement to the right
953 // Recall, if the cursor is at position 'x', that
954 // means *before* the character at position 'x'. In
955 // RTL, "before" means "to the right of", in LTR, "to
956 // the left of". So currently our situation is this:
957 // the position to our right is 'right_pos' (i.e.,
958 // we're currently to the left of 'right_pos'). In
959 // order to move to the right, it depends whether or
960 // not the character at 'right_pos' is RTL.
961 bool const new_pos_is_RTL = paragraph().getFontSettings(
962 buffer()->params(), right_pos).isVisibleRightToLeft();
963 // If the character at 'right_pos' *is* LTR, then in
964 // order to move to the right of it, we need to be
965 // *after* 'right_pos', i.e., move to position
967 if (!new_pos_is_RTL) {
968 new_cur.pos() = right_pos + 1;
969 // set the boundary to true in two situations:
971 // 1. if new_pos is now lastpos, and we're in
972 // an RTL paragraph (this means that we're
973 // moving right to the end of an LTR chunk
974 // which is at the end of an RTL paragraph);
975 (new_cur.pos() == lastpos()
976 && paragraph().isRTL(buffer()->params()))
977 // 2. if the position *after* right_pos is RTL
978 // (we want to be *after* right_pos, not
979 // before right_pos + 1!)
980 || paragraph().getFontSettings(buffer()->params(),
981 new_cur.pos()).isVisibleRightToLeft()
983 new_cur.boundary(true);
984 else // set the boundary to false
985 new_cur.boundary(false);
987 // Otherwise (if the character at position 'right_pos'
988 // is RTL), then moving to the right of it is as easy
989 // as setting the new position to 'right_pos'.
991 new_cur.pos() = right_pos;
992 new_cur.boundary(false);
997 bool const moved = new_cur != *this || new_cur.boundary() != boundary();
1000 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
1001 << (new_cur.boundary() ? " (boundary)" : ""));
1009 bool Cursor::posVisLeft(bool skip_inset)
1011 Cursor new_cur = *this; // where we will move to
1012 pos_type left_pos; // position visually left of current cursor
1013 pos_type right_pos; // position visually right of current cursor
1015 getSurroundingPos(left_pos, right_pos);
1017 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
1019 // Are we at an inset?
1020 new_cur.pos() = left_pos;
1021 new_cur.boundary(false);
1023 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
1024 // we actually move the cursor at the end of this
1025 // function, for now we just keep track of the new
1026 // position in new_cur...
1027 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
1030 // Are we already at leftmost pos in row?
1031 else if (text()->empty() || left_pos == -1) {
1034 if (!new_cur.posVisToNewRow(true)) {
1035 LYXERR(Debug::RTL, "not moving!");
1039 // we actually move the cursor at the end of this
1040 // function, for now just keep track of the new
1041 // position in new_cur...
1042 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
1043 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
1046 // normal movement to the left
1049 // Recall, if the cursor is at position 'x', that
1050 // means *before* the character at position 'x'. In
1051 // RTL, "before" means "to the right of", in LTR, "to
1052 // the left of". So currently our situation is this:
1053 // the position to our left is 'left_pos' (i.e., we're
1054 // currently to the right of 'left_pos'). In order to
1055 // move to the left, it depends whether or not the
1056 // character at 'left_pos' is RTL.
1057 bool const new_pos_is_RTL = paragraph().getFontSettings(
1058 buffer()->params(), left_pos).isVisibleRightToLeft();
1059 // If the character at 'left_pos' *is* RTL, then in
1060 // order to move to the left of it, we need to be
1061 // *after* 'left_pos', i.e., move to position
1063 if (new_pos_is_RTL) {
1064 new_cur.pos() = left_pos + 1;
1065 // set the boundary to true in two situations:
1067 // 1. if new_pos is now lastpos and we're in
1068 // an LTR paragraph (this means that we're
1069 // moving left to the end of an RTL chunk
1070 // which is at the end of an LTR paragraph);
1071 (new_cur.pos() == lastpos()
1072 && !paragraph().isRTL(buffer()->params()))
1073 // 2. if the position *after* left_pos is not
1074 // RTL (we want to be *after* left_pos, not
1075 // before left_pos + 1!)
1076 || !paragraph().getFontSettings(buffer()->params(),
1077 new_cur.pos()).isVisibleRightToLeft()
1079 new_cur.boundary(true);
1080 else // set the boundary to false
1081 new_cur.boundary(false);
1083 // Otherwise (if the character at position 'left_pos'
1084 // is LTR), then moving to the left of it is as easy
1085 // as setting the new position to 'left_pos'.
1087 new_cur.pos() = left_pos;
1088 new_cur.boundary(false);
1093 bool const moved = new_cur != *this || new_cur.boundary() != boundary();
1096 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
1097 << (new_cur.boundary() ? " (boundary)" : ""));
1107 // Return true on success
1108 bool findNonVirtual(Row const & row, Row::const_iterator & cit, bool onleft)
1111 while (cit != row.begin() && cit->isVirtual())
1114 while (cit != row.end() && cit->isVirtual())
1117 return cit != row.end() && !cit->isVirtual();
1122 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos) const
1124 // by default, we know nothing.
1128 Row const & row = textRow();
1130 Row::const_iterator cit = row.findElement(pos(), boundary(), dummy);
1131 // Handle the case of empty row
1132 if (cit == row.end()) {
1134 right_pos = row.pos();
1136 left_pos = row.pos() - 1;
1140 // skip virtual elements and exit if no non-virtual one exists
1141 if (!findNonVirtual(row, cit, !cit->isRTL()))
1144 // if the position is at the left side of the element, we have to
1145 // look at the previous element
1146 if (pos() == cit->left_pos()) {
1147 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1148 << "), AT LEFT of *cit=" << *cit);
1149 // this one is easy (see common case below)
1150 right_pos = pos() - (cit->isRTL() ? 1 : 0);
1151 // at the left of the row
1152 if (cit == row.begin())
1155 if (!findNonVirtual(row, cit, true))
1157 // [...[ is the row element, | is cursor position (! with boundary)
1158 // [ 1 2 [ is a ltr row element with pos=1 and endpos=3
1159 // ] 2 1] is an rtl row element with pos=1 and endpos=3
1160 // [ 1 2 [ [|3 4 [ => (2, 3)
1161 // or [ 1 2 [ ]!4 3 ] => (2, 4)
1162 // or ] 2 1 ] [|3 4 [ => (1, 3)
1163 // or ] 4 3 ] ]!2 1 ] => (3, 2)
1164 left_pos = cit->right_pos() - (cit->isRTL() ? 0 : 1);
1165 // happens with consecutive row of same direction
1166 if (left_pos == right_pos) {
1167 left_pos += cit->isRTL() ? 1 : -1;
1170 // same code but with the element at the right
1171 else if (pos() == cit->right_pos()) {
1172 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1173 << "), AT RIGHT of *cit=" << *cit);
1174 // this one is easy (see common case below)
1175 left_pos = pos() - (cit->isRTL() ? 0 : 1);
1176 // at the right of the row
1177 if (cit + 1 == row.end())
1180 if (!findNonVirtual(row, cit, false))
1182 // [ 1 2![ [ 3 4 [ => (2, 3)
1183 // or [ 1 2![ ] 4 3 ] => (2, 4)
1184 // or ] 2 1|] [ 3 4 [ => (1, 3)
1185 // or ] 4 3|] ] 2 1 ] => (3, 2)
1186 right_pos = cit->left_pos() - (cit->isRTL() ? 1 : 0);
1187 // happens with consecutive row of same direction
1188 if (right_pos == left_pos)
1189 right_pos += cit->isRTL() ? -1 : 1;
1191 // common case: both positions are inside the row element
1193 // [ 1 2|3 [ => (2, 3)
1194 // or ] 3|2 1 ] => (3, 2)
1195 left_pos = pos() - (cit->isRTL() ? 0 : 1);
1196 right_pos = pos() - (cit->isRTL() ? 1 : 0);
1199 // Note that debug message does not catch all early returns above
1200 LYXERR(Debug::RTL,"getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1201 << ") => (" << left_pos << ", " << right_pos <<")");
1205 bool Cursor::posVisToNewRow(bool movingLeft)
1207 Row const & row = textRow();
1208 bool par_is_LTR = !row.isRTL();
1210 // Inside a table, determining whether to move to the next or
1211 // previous row should be done based on the table's direction.
1212 if (inset().asInsetTabular()) {
1213 par_is_LTR = !inset().asInsetTabular()->isRightToLeft(*this);
1214 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
1217 // if moving left in an LTR paragraph or moving right in an
1218 // RTL one, move to previous row
1219 if (par_is_LTR == movingLeft) {
1220 if (row.pos() == 0) { // we're at first row in paragraph
1221 if (pit() == 0) // no previous paragraph! don't move
1223 // move to last pos in previous par
1227 } else { // move to previous row in this par
1228 pos() = row.pos() - 1; // this is guaranteed to be in previous row
1232 // if moving left in an RTL paragraph or moving right in an
1233 // LTR one, move to next row
1235 if (row.endpos() == lastpos()) { // we're at last row in paragraph
1236 if (pit() == lastpit()) // last paragraph! don't move
1238 // move to first row in next par
1242 } else { // move to next row in this par
1243 pos() = row.endpos();
1248 // make sure we're at left-/right-most pos in new row
1249 posVisToRowExtremity(!movingLeft);
1255 void Cursor::posVisToRowExtremity(bool left)
1257 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
1258 << (boundary() ? 1 : 0));
1260 TextMetrics const & tm = bv_->textMetrics(text());
1261 // Looking for extremities is like clicking on the left or the
1262 // right of the row.
1263 int x = tm.origin().x_ + (left ? 0 : textRow().width());
1265 pos() = tm.getPosNearX(textRow(), x, b);
1268 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
1269 << (boundary() ? 1 : 0));
1273 bool Cursor::reverseDirectionNeeded() const
1276 * We determine the directions based on the direction of the
1277 * bottom() --- i.e., outermost --- paragraph, because that is
1278 * the only way to achieve consistency of the arrow's movements
1279 * within a paragraph, and thus avoid situations in which the
1280 * cursor gets stuck.
1282 return bottom().paragraph().isRTL(bv().buffer().params());
1286 void Cursor::setTargetX(int x)
1289 textTargetOffset_ = 0;
1293 int Cursor::x_target() const
1299 void Cursor::clearTargetX()
1302 textTargetOffset_ = 0;
1306 void Cursor::updateTextTargetOffset()
1311 textTargetOffset_ = x - x_target_;
1315 bool Cursor::selHandle(bool sel)
1317 //lyxerr << "Cursor::selHandle" << endl;
1320 if (sel == selection())
1324 cap::saveSelection(*this);
1332 bool Cursor::atFirstOrLastRow(bool up)
1334 TextMetrics const & tm = bv_->textMetrics(text());
1335 ParagraphMetrics const & pm = tm.parMetrics(pit());
1338 if (pos() && boundary())
1339 row = pm.pos2row(pos() - 1);
1341 row = pm.pos2row(pos());
1344 if (pit() == 0 && row == 0)
1347 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1348 row + 1 >= int(pm.rows().size()))
1358 ///////////////////////////////////////////////////////////////////
1361 // The part below is the non-integrated rest of the original math
1362 // cursor. This should be either generalized for texted or moved
1363 // back to mathed (in most cases to InsetMathNest).
1365 ///////////////////////////////////////////////////////////////////
1367 #include "mathed/InsetMathChar.h"
1368 #include "mathed/InsetMathGrid.h"
1369 #include "mathed/InsetMathScript.h"
1370 #include "mathed/InsetMathUnknown.h"
1371 #include "mathed/MathFactory.h"
1372 #include "mathed/MathStream.h"
1373 #include "mathed/MathSupport.h"
1378 bool Cursor::openable(MathAtom const & t) const
1389 // we can't move into anything new during selection
1390 if (depth() >= realAnchor().depth())
1392 if (t.nucleus() != &realAnchor()[depth()].inset())
1399 void Cursor::plainErase()
1401 cell().erase(pos());
1405 void Cursor::plainInsert(MathAtom const & t)
1407 cell().insert(pos(), t);
1409 inset().setBuffer(bv_->buffer());
1411 checkBufferStructure();
1415 void Cursor::insert(char_type c)
1417 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1418 LASSERT(!empty(), return);
1420 cap::selClearOrDel(*this);
1421 insert(new InsetMathChar(c));
1423 text()->insertChar(*this, c);
1428 void Cursor::insert(docstring const & str)
1430 for (char_type c : str)
1435 void Cursor::insert(Inset * inset0)
1437 LASSERT(inset0, return);
1439 insert(MathAtom(inset0->asInsetMath()));
1441 text()->insertInset(*this, inset0);
1442 inset0->setBuffer(bv_->buffer());
1444 if (inset0->isLabeled())
1445 forceBufferUpdate();
1450 void Cursor::insert(MathAtom const & t)
1452 LATTEST(inMathed());
1453 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1455 cap::selClearOrDel(*this);
1460 void Cursor::insert(MathData const & ar)
1462 LATTEST(inMathed());
1465 cap::eraseSelection(*this);
1466 cell().insert(pos(), ar);
1468 // FIXME audit setBuffer calls
1469 inset().setBuffer(bv_->buffer());
1473 int Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1475 LATTEST(inMathed());
1476 MathData ar(buffer());
1478 if (ar.size() == 1 && (enter || selection()))
1486 void Cursor::niceInsert(MathAtom const & t)
1488 LATTEST(inMathed());
1490 docstring const safe = cap::grabAndEraseSelection(*this);
1492 // If possible, enter the new inset and move the contents of the selection
1493 if (t->isActive()) {
1495 // be careful here: don't use 'pushBackward(t)' as this we need to
1496 // push the clone, not the original
1497 pushBackward(*nextInset());
1498 // We may not use niceInsert here (recursion)
1499 MathData ar(buffer());
1502 } else if (t->asMacro() && !safe.empty()) {
1503 MathData ar(buffer());
1505 docstring const name = t->asMacro()->name();
1506 MacroData const * data = buffer()->getMacro(name);
1507 if (data && data->numargs() - data->optionals() > 0) {
1508 plainInsert(MathAtom(new InsetMathBrace(ar)));
1515 bool Cursor::backspace(bool const force)
1518 cap::eraseSelection(*this);
1523 // If empty cell, and not part of a big cell
1524 if (lastpos() == 0 && inset().nargs() == 1) {
1526 // Directly delete empty cell: [|[]] => [|]
1532 // [|], can not delete from inside
1543 if (inMacroMode()) {
1544 InsetMathUnknown * p = activeMacro();
1545 if (p->name().size() > 1) {
1546 p->setName(p->name().substr(0, p->name().size() - 1));
1551 if (pos() != 0 && !force && prevAtom()->confirmDeletion()) {
1552 // let's require two backspaces for 'big stuff' and
1553 // highlight on the first
1565 bool Cursor::erase(bool const force)
1571 cap::eraseSelection(*this);
1575 // delete empty cells if possible
1576 if (pos() == lastpos() && inset().idxDelete(idx()))
1579 // special behaviour when in last position of cell
1580 if (pos() == lastpos()) {
1581 bool one_cell = inset().nargs() == 1;
1582 if (one_cell && lastpos() == 0) {
1584 // Directly delete empty cell: [|[]] => [|]
1590 // [|], can not delete from inside
1595 inset().idxGlue(idx());
1599 // 'clever' UI hack: only erase large items if previously slected
1600 if (pos() != lastpos() && !force && nextAtom()->confirmDeletion()) {
1615 DocIterator save = *this;
1616 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1617 this->dispatch(cmd);
1618 if (disp_.dispatched())
1628 DocIterator save = *this;
1629 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1630 this->dispatch(cmd);
1631 if (disp_.dispatched())
1638 void Cursor::handleNest(MathAtom const & a, int c)
1640 //lyxerr << "Cursor::handleNest: " << c << endl;
1642 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1645 pushBackward(*nextInset());
1649 void Cursor::handleNest(MathAtom const & a)
1651 handleNest(a, a.nucleus()->asNestInset()->firstIdx());
1655 int Cursor::targetX() const
1657 if (x_target() != -1)
1666 int Cursor::textTargetOffset() const
1668 return textTargetOffset_;
1672 void Cursor::setTargetX()
1681 bool Cursor::macroModeClose(bool cancel)
1685 InsetMathUnknown * p = activeMacro();
1687 MathData selection(buffer());
1688 asArray(p->selection(), selection);
1689 docstring const s = p->name();
1691 cell().erase(pos());
1693 // trigger updates of macros, at least, if no full
1694 // updates take place anyway
1695 screenUpdateFlags(Update::Force);
1697 // do nothing if the macro name is empty
1698 if (s == "\\" || cancel) {
1702 docstring const name = s.substr(1);
1703 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1704 if (in && in->interpretString(*this, s))
1706 bool const user_macro = buffer()->getMacro(name, *this, false);
1707 MathAtom atom = user_macro ? MathAtom(new InsetMathMacro(buffer(), name))
1708 : createInsetMath(name, buffer());
1710 // try to put argument into macro, if we just inserted a macro
1711 bool macroArg = false;
1712 InsetMathMacro * atomAsMacro = atom.nucleus()->asMacro();
1713 InsetMathNest * atomAsNest = atom.nucleus()->asNestInset();
1715 // macros here are still unfolded (in init mode in fact). So
1716 // we have to resolve the macro here manually and check its arity
1717 // to put the selection behind it if arity > 0.
1718 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1719 if (!selection.empty() && data && data->numargs() - data->optionals() > 0) {
1721 atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1723 // non-greedy case. Do not touch the arguments behind
1724 atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1727 // insert remembered selection into first argument of a non-macro
1728 else if (atomAsNest && atomAsNest->nargs() > 0)
1729 atomAsNest->cell(atomAsNest->firstIdx()).append(selection);
1731 MathWordList const & words = mathedWordList();
1732 MathWordList::const_iterator it = words.find(name);
1733 bool keep_mathmode = user_macro
1734 || (it != words.end() && (it->second.inset == "font"
1735 || it->second.inset == "oldfont"
1736 || it->second.inset == "mbox"));
1737 bool ert_macro = !user_macro && it == words.end() && atomAsMacro;
1739 if (in && in->currentMode() == Inset::TEXT_MODE
1740 && atom.nucleus()->currentMode() == Inset::MATH_MODE
1741 && name != from_ascii("ensuremath") && !ert_macro) {
1742 MathAtom at(new InsetMathEnsureMath(buffer()));
1743 at.nucleus()->cell(0).push_back(atom);
1746 } else if (in && in->currentMode() == Inset::MATH_MODE
1747 && atom.nucleus()->currentMode() == Inset::TEXT_MODE
1748 && !keep_mathmode) {
1749 MathAtom at = createInsetMath("text", buffer());
1750 at.nucleus()->cell(0).push_back(atom);
1756 // finally put the macro argument behind, if needed
1758 if (selection.size() > 1 || selection[0]->asScriptInset())
1759 plainInsert(MathAtom(new InsetMathBrace(selection)));
1768 bool Cursor::inMacroMode() const
1772 if (pos() == 0 || cell().empty())
1774 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1775 return p && !p->final();
1779 InsetMathUnknown * Cursor::activeMacro()
1781 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1785 InsetMathUnknown const * Cursor::activeMacro() const
1787 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1791 docstring Cursor::macroName()
1793 return inMacroMode() ? activeMacro()->name() : docstring();
1797 void Cursor::pullArg()
1800 MathData ar = cell();
1801 if (popBackward() && inMathed()) {
1803 cell().insert(pos(), ar);
1806 //formula()->mutateToText();
1811 void Cursor::normalize()
1813 if (idx() > lastidx()) {
1814 lyxerr << "this should not really happen - 1: "
1815 << idx() << ' ' << nargs()
1816 << " in: " << &inset() << endl;
1820 if (pos() > lastpos()) {
1821 lyxerr << "this should not really happen - 2: "
1822 << pos() << ' ' << lastpos() << " in idx: " << idx()
1824 odocstringstream os;
1825 otexrowstream ots(os);
1826 WriteStream wi(ots, false, true, WriteStream::wsDefault);
1827 inset().asInsetMath()->write(wi);
1828 lyxerr << to_utf8(os.str()) << endl;
1834 bool Cursor::upDownInMath(bool up)
1836 // Be warned: The 'logic' implemented in this function is highly
1837 // fragile. A distance of one pixel or a '<' vs '<=' _really
1838 // matters. So fiddle around with it only if you think you know
1839 // what you are doing!
1843 xo = beforeDispatchPosX_;
1845 // check if we had something else in mind, if not, this is the future
1847 if (x_target_ == -1)
1849 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1850 // In text mode inside the line (not left or right) possibly set a new target_x,
1851 // but only if we are somewhere else than the previous target-offset.
1853 // We want to keep the x-target on subsequent up/down movements
1854 // that cross beyond the end of short lines. Thus a special
1855 // handling when the cursor is at the end of line: Use the new
1856 // x-target only if the old one was before the end of line
1857 // or the old one was after the beginning of the line
1858 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
1862 left = pos() == textRow().endpos();
1863 right = pos() == textRow().pos();
1865 left = pos() == textRow().pos();
1866 right = pos() == textRow().endpos();
1868 if ((!left && !right) ||
1869 (left && !right && xo < x_target_) ||
1870 (!left && right && x_target_ < xo))
1877 // try neigbouring script insets
1879 if (inMathed() && !selection()) {
1882 InsetMathScript const * p = prevAtom()->asScriptInset();
1883 if (p && p->has(up)) {
1885 push(*const_cast<InsetMathScript*>(p));
1886 idx() = p->idxOfScript(up);
1889 // we went in the right direction? Otherwise don't jump into the script
1893 int oy = beforeDispatchPosY_;
1894 if ((!up && y <= oy) ||
1903 if (pos() != lastpos()) {
1904 InsetMathScript const * p = nextAtom()->asScriptInset();
1905 if (p && p->has(up)) {
1906 push(*const_cast<InsetMathScript*>(p));
1907 idx() = p->idxOfScript(up);
1910 // we went in the right direction? Otherwise don't jump into the script
1914 int oy = beforeDispatchPosY_;
1915 if ((!up && y <= oy) ||
1924 // try to find an inset that knows better then we,
1925 if (inset().idxUpDown(*this, up)) {
1926 //lyxerr << "idxUpDown triggered" << endl;
1927 // try to find best position within this inset
1929 setCursor(bruteFind(*this, xo, yo));
1933 // any improvement going just out of inset?
1934 if (popBackward() && inMathed()) {
1935 //lyxerr << "updown: popBackward succeeded" << endl;
1938 int yold = beforeDispatchPosY_;
1940 if (up ? ynew < yold : ynew > yold)
1944 // no success, we are probably at the document top or bottom
1950 bool Cursor::mathForward(bool word)
1952 LASSERT(inMathed(), return false);
1953 if (pos() < lastpos()) {
1955 // word: skip a group of insets of the form X*(B*|R*|P*) (greedy
1956 // match) where X is any math class, B is mathbin, R is mathrel, and
1957 // P is mathpunct. Make sure that the following remains true:
1958 // mathForward(true); mathBackward(true); mathForward(true)
1959 // is the same as mathForward(true) and
1960 // mathBackward(true); mathForward(true); mathBackward(true)
1961 // is the same as mathBackward(true).
1962 MathClass mc = nextMath().mathClass();
1965 while (pos() < lastpos() && mc == nextMath().mathClass());
1966 if (pos() < lastpos() &&
1967 ((mc = nextMath().mathClass()) == MC_BIN ||
1968 mc == MC_REL || mc == MC_PUNCT))
1971 while (pos() < lastpos() && mc == nextMath().mathClass());
1972 } else if (openable(nextAtom())) {
1973 // single step: try to enter the next inset
1974 pushBackward(nextMath());
1975 inset().idxFirst(*this);
1980 if (inset().idxForward(*this))
1982 // try to pop forwards --- but don't pop out of math! leave that to
1984 int s = depth() - 2;
1985 if (s >= 0 && operator[](s).inset().asInsetMath())
1986 return popForward();
1991 bool Cursor::mathBackward(bool word)
1993 LASSERT(inMathed(), return false);
1996 // word: skip a group of insets. See the comment in mathForward.
1997 MathClass mc = prevMath().mathClass();
2000 while (pos() > 0 && mc == prevMath().mathClass());
2001 if (pos() > 0 && (mc == MC_BIN || mc == MC_REL || mc == MC_PUNCT)) {
2002 mc = prevMath().mathClass();
2005 while (pos() > 0 && mc == prevMath().mathClass());
2007 } else if (openable(prevAtom())) {
2008 // single step: try to enter the preceding inset
2011 inset().idxLast(*this);
2016 if (inset().idxBackward(*this))
2018 // try to pop backwards --- but don't pop out of math! leave that to
2020 int s = depth() - 2;
2021 if (s >= 0 && operator[](s).inset().asInsetMath())
2022 return popBackward();
2027 bool Cursor::upDownInText(bool up, bool & updateNeeded)
2029 LASSERT(text(), return false);
2035 xo = beforeDispatchPosX_;
2037 // update the targetX - this is here before the "return false"
2038 // to set a new target which can be used by InsetTexts above
2039 // if we cannot move up/down inside this inset anymore
2040 if (x_target_ == -1)
2042 else if (xo - textTargetOffset() != x_target() &&
2043 depth() == beforeDispatchCursor_.depth()) {
2044 // In text mode inside the line (not left or right)
2045 // possibly set a new target_x, but only if we are
2046 // somewhere else than the previous target-offset.
2048 // We want to keep the x-target on subsequent up/down
2049 // movements that cross beyond the end of short lines.
2050 // Thus a special handling when the cursor is at the
2051 // end of line: Use the new x-target only if the old
2052 // one was before the end of line or the old one was
2053 // after the beginning of the line
2054 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
2058 left = pos() == textRow().endpos();
2059 right = pos() == textRow().pos();
2061 left = pos() == textRow().pos();
2062 right = pos() == textRow().endpos();
2064 if ((!left && !right) ||
2065 (left && !right && xo < x_target_) ||
2066 (!left && right && x_target_ < xo))
2073 // first get the current line
2074 TextMetrics & tm = bv_->textMetrics(text());
2075 ParagraphMetrics const & pm = tm.parMetrics(pit());
2077 if (pos() && boundary())
2078 row = pm.pos2row(pos() - 1);
2080 row = pm.pos2row(pos());
2082 if (atFirstOrLastRow(up)) {
2083 // Is there a place for the cursor to go ? If yes, we
2084 // can execute the DEPM, otherwise we should keep the
2085 // paragraph to host the cursor.
2086 Cursor dummy = *this;
2087 bool valid_destination = false;
2088 for(; dummy.depth(); dummy.pop())
2089 if (!dummy.atFirstOrLastRow(up)) {
2090 valid_destination = true;
2094 // will a next dispatch follow and if there is a new
2095 // dispatch will it move the cursor out ?
2096 if (depth() > 1 && valid_destination) {
2097 // The cursor hasn't changed yet. This happens when
2098 // you e.g. move out of an inset. And to give the
2099 // DEPM the possibility of doing something we must
2100 // provide it with two different cursors. (Lgb, vfr)
2102 dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
2103 dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
2105 updateNeeded |= bv().checkDepm(dummy, *this);
2106 updateTextTargetOffset();
2108 forceBufferUpdate();
2113 // with and without selection are handled differently
2115 int yo1 = bv().getPos(*this).y_;
2117 // To next/previous row
2118 // FIXME: the y position is often guessed wrongly across styles and
2119 // insets, which leads to weird behaviour.
2121 tm.editXY(*this, xo, yo1 - textRow().ascent() - 1);
2123 tm.editXY(*this, xo, yo1 + textRow().descent() + 1);
2124 x_target_ = old.x_target_;
2127 // This happens when you move out of an inset.
2128 // And to give the DEPM the possibility of doing
2129 // something we must provide it with two different
2131 Cursor dummy = *this;
2134 if (bv().checkDepm(dummy, old)) {
2135 updateNeeded = true;
2136 // Make sure that cur gets back whatever happened to dummy (Lgb)
2139 if (inTexted() && pos() && paragraph().isEnvSeparator(pos() - 1))
2142 // if there is a selection, we stay out of any inset,
2143 // and just jump to the right position:
2149 } else if (pit() > 0) {
2151 TextMetrics & tm2 = bv_->textMetrics(text());
2152 if (!tm2.contains(pit()))
2153 tm2.newParMetricsUp();
2154 ParagraphMetrics const & pmcur = tm2.parMetrics(pit());
2155 next_row = pmcur.rows().size() - 1;
2158 if (row + 1 < int(pm.rows().size())) {
2160 } else if (pit() + 1 < int(text()->paragraphs().size())) {
2162 TextMetrics & tm2 = bv_->textMetrics(text());
2163 if (!tm2.contains(pit()))
2164 tm2.newParMetricsDown();
2169 Row const & real_next_row = tm.parMetrics(pit()).rows()[next_row];
2171 top().pos() = tm.getPosNearX(real_next_row, xo, bound);
2173 // When selection==false, this is done by TextMetrics::editXY
2176 updateNeeded |= bv().checkDepm(*this, old);
2180 forceBufferUpdate();
2181 updateTextTargetOffset();
2186 void Cursor::handleFont(string const & font)
2188 LYXERR(Debug::DEBUG, font);
2192 safe = cap::grabAndEraseSelection(*this);
2197 if (lastpos() != 0) {
2198 // something left in the cell
2200 // cursor in first position
2202 } else if (pos() == lastpos()) {
2203 // cursor in last position
2206 // cursor in between. split cell
2207 MathData::iterator bt = cell().begin();
2208 MathAtom at = createInsetMath(from_utf8(font), buffer());
2209 at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
2210 cell().erase(bt, bt + pos());
2215 // nothing left in the cell
2224 void Cursor::undispatched() const
2226 disp_.dispatched(false);
2230 void Cursor::dispatched() const
2232 disp_.dispatched(true);
2236 void Cursor::screenUpdateFlags(Update::flags f) const
2238 disp_.screenUpdate(f);
2242 void Cursor::forceBufferUpdate() const
2244 disp_.forceBufferUpdate();
2248 void Cursor::clearBufferUpdate() const
2250 disp_.clearBufferUpdate();
2254 bool Cursor::needBufferUpdate() const
2256 return disp_.needBufferUpdate();
2260 void Cursor::noScreenUpdate() const
2262 disp_.screenUpdate(Update::None);
2266 Font Cursor::getFont() const
2268 // The logic here should more or less match to the
2269 // Cursor::setCurrentFont logic, i.e. the cursor height should
2270 // give a hint what will happen if a character is entered.
2271 // FIXME: this is not the case, what about removing this method ? (see #10478).
2273 // HACK. far from being perfect...
2275 CursorSlice const & sl = innerTextSlice();
2276 Text const & text = *sl.text();
2277 Paragraph const & par = text.getPar(sl.pit());
2279 // on boundary, so we are really at the character before
2280 pos_type pos = sl.pos();
2281 if (pos > 0 && boundary())
2284 // on space? Take the font before (only for RTL boundary stay)
2286 TextMetrics const & tm = bv().textMetrics(&text);
2287 if (pos == sl.lastpos()
2288 || (par.isSeparator(pos)
2289 && !tm.isRTLBoundary(sl.pit(), pos)))
2293 // get font at the position
2294 Font font = par.getFont(buffer()->params(), pos,
2295 text.outerFont(sl.pit()));
2301 void Cursor::sanitize()
2303 setBuffer(&bv_->buffer());
2304 CursorData::sanitize();
2308 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2310 // find inset in common
2312 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2313 if (&old[i].inset() != &cur[i].inset())
2317 // update words if we just moved to another paragraph
2318 if (i == old.depth() && i == cur.depth()
2319 && !cur.buffer()->isClean()
2320 && cur.inTexted() && old.inTexted()
2321 && cur.pit() != old.pit()) {
2322 old.paragraph().updateWords();
2325 // notify everything on top of the common part in old cursor,
2326 // but stop if the inset claims the cursor to be invalid now
2327 for (size_type j = i; j < old.depth(); ++j) {
2328 Cursor inset_pos = old;
2329 inset_pos.cutOff(j);
2330 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2334 // notify everything on top of the common part in new cursor,
2335 // but stop if the inset claims the cursor to be invalid now
2336 for (; i < cur.depth(); ++i) {
2337 if (cur[i].inset().notifyCursorEnters(cur))
2345 void Cursor::setCurrentFont()
2347 CursorSlice const & cs = innerTextSlice();
2348 Paragraph const & par = cs.paragraph();
2349 pos_type cpit = cs.pit();
2350 pos_type cpos = cs.pos();
2351 Text const & ctext = *cs.text();
2352 TextMetrics const & tm = bv().textMetrics(&ctext);
2354 // are we behind previous char in fact? -> go to that char
2355 if (cpos > 0 && boundary())
2358 // find position to take the font from
2360 // paragraph end? -> font of last char
2361 if (cpos == lastpos())
2363 // on space? -> look at the words in front of space
2364 else if (cpos > 0 && par.isSeparator(cpos)) {
2365 // abc| def -> font of c
2366 // abc |[WERBEH], i.e. boundary==true -> font of c
2367 // abc [WERBEH]| def, font of the space
2368 if (!tm.isRTLBoundary(cpit, cpos))
2374 BufferParams const & bufparams = buffer()->params();
2375 current_font = par.getFontSettings(bufparams, cpos);
2376 real_current_font = tm.displayFont(cpit, cpos);
2378 // special case for paragraph end
2379 if (cs.pos() == lastpos()
2380 && tm.isRTLBoundary(cpit, cs.pos())
2382 Language const * lang = par.getParLanguage(bufparams);
2383 current_font.setLanguage(lang);
2384 current_font.fontInfo().setNumber(FONT_OFF);
2385 real_current_font.setLanguage(lang);
2386 real_current_font.fontInfo().setNumber(FONT_OFF);
2391 void Cursor::checkBufferStructure()
2393 Buffer const * master = buffer()->masterBuffer();
2394 master->tocBackend().updateItem(*this);
2395 if (master != buffer() && !master->hasGuiDelegate())
2396 // In case the master has no gui associated with it,
2397 // the TocItem is not updated (part of bug 5699).
2398 buffer()->tocBackend().updateItem(*this);
2400 // If the last tracked change of the paragraph has just been
2401 // deleted, then we need to recompute the buffer flag
2402 // tracked_changes_present_.
2403 if (inTexted() && paragraph().isChangeUpdateRequired())
2404 disp_.forceChangesUpdate();
2408 void Cursor::moveToClosestEdge(int const x, bool const edit)
2410 if (Inset const * inset = nextInset()) {
2411 // stay in front of insets for which we want to open the dialog
2412 // (e.g. InsetMathSpace).
2413 if (edit && (inset->hasSettings() || !inset->contextMenuName().empty()))
2415 CoordCache::Insets const & insetCache = bv().coordCache().getInsets();
2416 if (!insetCache.has(inset))
2418 int const wid = insetCache.dim(inset).wid;
2419 Point p = insetCache.xy(inset);
2420 if (x > p.x_ + (wid + 1) / 2)