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), current_font(inherit_font), autocorrect_(false)
128 CursorData::CursorData(Buffer * buffer)
129 : DocIterator(buffer), anchor_(), selection_(false), mark_(false),
130 word_selection_(false), current_font(inherit_font), autocorrect_(false)
134 CursorData::CursorData(DocIterator const & dit)
135 : DocIterator(dit), anchor_(), selection_(false), mark_(false),
136 word_selection_(false), current_font(inherit_font), autocorrect_(false)
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())
461 clearNewWordPosition();
463 // forget the position of the current new word if
464 // 1) the paragraph changes or
465 // 2) the count of nested insets changes or
466 // 3) the cursor pos is out of paragraph bound
467 if (pit() != new_word_.pit() ||
468 depth() != new_word_.depth() ||
469 new_word_.pos() > new_word_.lastpos()) {
470 clearNewWordPosition();
471 } else if (new_word_.fixIfBroken())
472 // 4) or the remembered position was "broken"
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();
492 void CursorData::clearSelection()
495 setWordSelection(false);
501 bool CursorData::fixIfBroken()
503 bool const broken_cursor = DocIterator::fixIfBroken();
504 bool const broken_anchor = anchor_.fixIfBroken();
506 if (broken_cursor || broken_anchor) {
507 clearNewWordPosition();
515 void CursorData::sanitize()
517 DocIterator::sanitize();
525 bool CursorData::isInside(Inset const * p) const
527 for (size_t i = 0; i != depth(); ++i)
528 if (&operator[](i).inset() == p)
534 void CursorData::leaveInset(Inset const & inset)
536 for (size_t i = 0; i != depth(); ++i) {
537 if (&operator[](i).inset() == &inset) {
545 bool CursorData::textUndo()
547 if (!buffer()->undo().textUndo(*this))
554 bool CursorData::textRedo()
556 if (!buffer()->undo().textRedo(*this))
563 void CursorData::finishUndo() const
565 buffer()->undo().finishUndo();
569 void CursorData::beginUndoGroup() const
571 buffer()->undo().beginUndoGroup(*this);
575 void CursorData::endUndoGroup() const
577 buffer()->undo().endUndoGroup(*this);
581 void CursorData::recordUndo(pit_type from, pit_type to) const
583 buffer()->undo().recordUndo(*this, from, to);
587 void CursorData::recordUndo(pit_type from) const
589 buffer()->undo().recordUndo(*this, from, pit());
593 void CursorData::recordUndo(UndoKind kind) const
595 buffer()->undo().recordUndo(*this, kind);
599 void CursorData::recordUndoInset(Inset const * in) const
601 buffer()->undo().recordUndoInset(*this, in);
605 void CursorData::recordUndoFullBuffer() const
607 buffer()->undo().recordUndoFullBuffer(*this);
611 void CursorData::recordUndoBufferParams() const
613 buffer()->undo().recordUndoBufferParams(*this);
617 void CursorData::recordUndoSelection() const
620 if (cap::multipleCellsSelected(*this))
625 buffer()->undo().recordUndo(*this,
626 selBegin().pit(), selEnd().pit());
631 int CursorData::currentMode()
633 LASSERT(!empty(), return Inset::UNDECIDED_MODE);
634 for (int i = depth() - 1; i >= 0; --i) {
635 int res = operator[](i).inset().currentMode();
636 bool locked_mode = operator[](i).inset().lockedMode();
637 // Also return UNDECIDED_MODE when the mode is locked,
638 // as in this case it is treated the same as TEXT_MODE
639 if (res != Inset::UNDECIDED_MODE || locked_mode)
642 return Inset::TEXT_MODE;
646 bool CursorData::confirmDeletion(bool const before) const
649 if (Inset const * inset = before ? prevInset() : nextInset())
650 return inset->confirmDeletion();
652 DocIterator dit = selectionBegin();
653 CursorSlice const end = selectionEnd().top();
654 for (; dit.top() < end; dit.top().forwardPos())
655 if (Inset const * inset = dit.nextInset())
656 if (inset->confirmDeletion())
669 // be careful: this is called from the bv's constructor, too, so
670 // bv functions are not yet available!
671 Cursor::Cursor(BufferView & bv)
672 : CursorData(&bv.buffer()), bv_(&bv),
673 x_target_(-1), textTargetOffset_(0),
674 beforeDispatchPosX_(0), beforeDispatchPosY_(0)
685 void Cursor::setCursorData(CursorData const & data)
687 CursorData::operator=(data);
691 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
695 // Try to fix cursor in case it is broken.
698 // Is this a function that acts on inset at point?
699 Inset * inset = cur.nextInset();
700 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
701 && inset && inset->getStatus(cur, cmd, status))
704 // This is, of course, a mess. Better create a new doc iterator and use
705 // this in Inset::getStatus. This might require an additional
706 // BufferView * arg, though (which should be avoided)
707 //Cursor safe = *this;
709 for ( ; cur.depth(); cur.pop()) {
710 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
711 // LASSERT: Is it safe to continue here, or should we return?
712 LASSERT(cur.idx() <= cur.lastidx(), /**/);
713 LASSERT(cur.pit() <= cur.lastpit(), /**/);
714 LASSERT(cur.pos() <= cur.lastpos(), /**/);
716 // The inset's getStatus() will return 'true' if it made
717 // a definitive decision on whether it want to handle the
718 // request or not. The result of this decision is put into
719 // the 'status' parameter.
720 if (cur.inset().getStatus(cur, cmd, status)) {
729 void Cursor::saveBeforeDispatchPosXY()
731 getPos(beforeDispatchPosX_, beforeDispatchPosY_);
735 void Cursor::dispatch(FuncRequest const & cmd0)
737 LYXERR(Debug::ACTION, "Cursor::dispatch: cmd: " << cmd0 << '\n' << *this);
742 FuncRequest cmd = cmd0;
745 disp_ = DispatchResult();
749 // Is this a function that acts on inset at point?
750 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
752 disp_.dispatched(true);
753 disp_.screenUpdate(Update::FitCursor | Update::Force);
754 FuncRequest tmpcmd = cmd;
755 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
756 << cmd0 << endl << *this);
757 nextInset()->dispatch(*this, tmpcmd);
758 if (disp_.dispatched()) {
764 // store some values to be used inside of the handlers
765 beforeDispatchCursor_ = *this;
766 for (; depth(); pop(), boundary(false)) {
767 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
768 << cmd0 << endl << *this);
770 // In any of these cases, the cursor is invalid, and we should
771 // try to save this document rather than crash.
772 LBUFERR(pos() <= lastpos());
773 LBUFERR(idx() <= lastidx());
774 LBUFERR(pit() <= lastpit());
776 // The common case is 'LFUN handled, need update', so make the
777 // LFUN handler's life easier by assuming this as default value.
778 // The handler can reset the update and val flags if necessary.
779 disp_.screenUpdate(Update::FitCursor | Update::Force);
780 disp_.dispatched(true);
781 inset().dispatch(*this, cmd);
782 if (disp_.dispatched())
786 // it completely to get a 'bomb early' behaviour in case this
787 // object will be used again.
788 if (!disp_.dispatched()) {
789 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
790 // We might have invalidated the cursor when removing an empty
791 // paragraph while the cursor could not be moved out the inset
792 // while we initially thought we could. This might happen when
793 // a multiline inset becomes an inline inset when the second
794 // paragraph is removed.
795 if (safe.pit() > safe.lastpit()) {
796 safe.pit() = safe.lastpit();
797 safe.pos() = safe.lastpos();
800 disp_.screenUpdate(Update::None);
801 disp_.dispatched(false);
803 // restore the previous one because nested Cursor::dispatch calls
804 // are possible which would change it
805 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
809 // NOTE: The code below has been copied to BufferView::dispatch.
810 // If you need to modify this, please update the other one too.
812 // notify insets we just left
814 old.beginUndoGroup();
816 bool badcursor = notifyCursorLeavesOrEnters(old, *this);
819 bv().resetInlineCompletionPos();
826 DispatchResult const & Cursor::result() const
832 void Cursor::message(docstring const & msg) const
834 disp_.setMessage(msg);
838 void Cursor::errorMessage(docstring const & msg) const
840 disp_.setMessage(msg);
841 disp_.setError(true);
845 BufferView & Cursor::bv() const
854 LBUFERR(depth() >= 1);
859 void Cursor::push(Inset & p)
861 push_back(CursorSlice(p));
862 p.setBuffer(*buffer());
866 void Cursor::pushBackward(Inset & p)
868 LASSERT(!empty(), return);
869 //lyxerr << "Entering inset " << t << " front" << endl;
875 bool Cursor::popBackward()
877 LASSERT(!empty(), return false);
885 bool Cursor::popForward()
887 LASSERT(!empty(), return false);
888 //lyxerr << "Leaving inset from in back" << endl;
889 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
893 pos() += lastpos() - lp + 1;
898 void Cursor::getPos(int & x, int & y) const
900 Point p = bv().getPos(*this);
906 Row const & Cursor::textRow() const
908 CursorSlice const & cs = innerTextSlice();
909 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
910 return pm.getRow(pos(), boundary());
914 bool Cursor::posVisRight(bool skip_inset)
916 Cursor new_cur = *this; // where we will move to
917 pos_type left_pos; // position visually left of current cursor
918 pos_type right_pos; // position visually right of current cursor
920 getSurroundingPos(left_pos, right_pos);
922 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
924 // Are we at an inset?
925 new_cur.pos() = right_pos;
926 new_cur.boundary(false);
928 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
929 // we actually move the cursor at the end of this
930 // function, for now we just keep track of the new
931 // position in new_cur...
932 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
935 // Are we already at rightmost pos in row?
936 else if (text()->empty() || right_pos == -1) {
939 if (!new_cur.posVisToNewRow(false)) {
940 LYXERR(Debug::RTL, "not moving!");
944 // we actually move the cursor at the end of this
945 // function, for now just keep track of the new
946 // position in new_cur...
947 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
948 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
951 // normal movement to the right
954 // Recall, if the cursor is at position 'x', that
955 // means *before* the character at position 'x'. In
956 // RTL, "before" means "to the right of", in LTR, "to
957 // the left of". So currently our situation is this:
958 // the position to our right is 'right_pos' (i.e.,
959 // we're currently to the left of 'right_pos'). In
960 // order to move to the right, it depends whether or
961 // not the character at 'right_pos' is RTL.
962 bool const new_pos_is_RTL = paragraph().getFontSettings(
963 buffer()->params(), right_pos).isVisibleRightToLeft();
964 // If the character at 'right_pos' *is* LTR, then in
965 // order to move to the right of it, we need to be
966 // *after* 'right_pos', i.e., move to position
968 if (!new_pos_is_RTL) {
969 new_cur.pos() = right_pos + 1;
970 // set the boundary to true in two situations:
972 // 1. if new_pos is now lastpos, and we're in
973 // an RTL paragraph (this means that we're
974 // moving right to the end of an LTR chunk
975 // which is at the end of an RTL paragraph);
976 (new_cur.pos() == lastpos()
977 && paragraph().isRTL(buffer()->params()))
978 // 2. if the position *after* right_pos is RTL
979 // (we want to be *after* right_pos, not
980 // before right_pos + 1!)
981 || paragraph().getFontSettings(buffer()->params(),
982 new_cur.pos()).isVisibleRightToLeft()
984 new_cur.boundary(true);
985 else // set the boundary to false
986 new_cur.boundary(false);
988 // Otherwise (if the character at position 'right_pos'
989 // is RTL), then moving to the right of it is as easy
990 // as setting the new position to 'right_pos'.
992 new_cur.pos() = right_pos;
993 new_cur.boundary(false);
998 bool const moved = new_cur != *this || new_cur.boundary() != boundary();
1001 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
1002 << (new_cur.boundary() ? " (boundary)" : ""));
1010 bool Cursor::posVisLeft(bool skip_inset)
1012 Cursor new_cur = *this; // where we will move to
1013 pos_type left_pos; // position visually left of current cursor
1014 pos_type right_pos; // position visually right of current cursor
1016 getSurroundingPos(left_pos, right_pos);
1018 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
1020 // Are we at an inset?
1021 new_cur.pos() = left_pos;
1022 new_cur.boundary(false);
1024 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
1025 // we actually move the cursor at the end of this
1026 // function, for now we just keep track of the new
1027 // position in new_cur...
1028 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
1031 // Are we already at leftmost pos in row?
1032 else if (text()->empty() || left_pos == -1) {
1035 if (!new_cur.posVisToNewRow(true)) {
1036 LYXERR(Debug::RTL, "not moving!");
1040 // we actually move the cursor at the end of this
1041 // function, for now just keep track of the new
1042 // position in new_cur...
1043 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
1044 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
1047 // normal movement to the left
1050 // Recall, if the cursor is at position 'x', that
1051 // means *before* the character at position 'x'. In
1052 // RTL, "before" means "to the right of", in LTR, "to
1053 // the left of". So currently our situation is this:
1054 // the position to our left is 'left_pos' (i.e., we're
1055 // currently to the right of 'left_pos'). In order to
1056 // move to the left, it depends whether or not the
1057 // character at 'left_pos' is RTL.
1058 bool const new_pos_is_RTL = paragraph().getFontSettings(
1059 buffer()->params(), left_pos).isVisibleRightToLeft();
1060 // If the character at 'left_pos' *is* RTL, then in
1061 // order to move to the left of it, we need to be
1062 // *after* 'left_pos', i.e., move to position
1064 if (new_pos_is_RTL) {
1065 new_cur.pos() = left_pos + 1;
1066 // set the boundary to true in two situations:
1068 // 1. if new_pos is now lastpos and we're in
1069 // an LTR paragraph (this means that we're
1070 // moving left to the end of an RTL chunk
1071 // which is at the end of an LTR paragraph);
1072 (new_cur.pos() == lastpos()
1073 && !paragraph().isRTL(buffer()->params()))
1074 // 2. if the position *after* left_pos is not
1075 // RTL (we want to be *after* left_pos, not
1076 // before left_pos + 1!)
1077 || !paragraph().getFontSettings(buffer()->params(),
1078 new_cur.pos()).isVisibleRightToLeft()
1080 new_cur.boundary(true);
1081 else // set the boundary to false
1082 new_cur.boundary(false);
1084 // Otherwise (if the character at position 'left_pos'
1085 // is LTR), then moving to the left of it is as easy
1086 // as setting the new position to 'left_pos'.
1088 new_cur.pos() = left_pos;
1089 new_cur.boundary(false);
1094 bool const moved = new_cur != *this || new_cur.boundary() != boundary();
1097 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
1098 << (new_cur.boundary() ? " (boundary)" : ""));
1108 // Return true on success
1109 bool findNonVirtual(Row const & row, Row::const_iterator & cit, bool onleft)
1112 while (cit != row.begin() && cit->isVirtual())
1115 while (cit != row.end() && cit->isVirtual())
1118 return cit != row.end() && !cit->isVirtual();
1123 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos) const
1125 // by default, we know nothing.
1129 Row const & row = textRow();
1131 Row::const_iterator cit = row.findElement(pos(), boundary(), dummy);
1132 // Handle the case of empty row
1133 if (cit == row.end()) {
1135 right_pos = row.pos();
1137 left_pos = row.pos() - 1;
1141 // skip virtual elements and exit if no non-virtual one exists
1142 if (!findNonVirtual(row, cit, !cit->isRTL()))
1145 // if the position is at the left side of the element, we have to
1146 // look at the previous element
1147 if (pos() == cit->left_pos()) {
1148 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1149 << "), AT LEFT of *cit=" << *cit);
1150 // this one is easy (see common case below)
1151 right_pos = pos() - (cit->isRTL() ? 1 : 0);
1152 // at the left of the row
1153 if (cit == row.begin())
1156 if (!findNonVirtual(row, cit, true))
1158 // [...[ is the row element, | is cursor position (! with boundary)
1159 // [ 1 2 [ is a ltr row element with pos=1 and endpos=3
1160 // ] 2 1] is an rtl row element with pos=1 and endpos=3
1161 // [ 1 2 [ [|3 4 [ => (2, 3)
1162 // or [ 1 2 [ ]!4 3 ] => (2, 4)
1163 // or ] 2 1 ] [|3 4 [ => (1, 3)
1164 // or ] 4 3 ] ]!2 1 ] => (3, 2)
1165 left_pos = cit->right_pos() - (cit->isRTL() ? 0 : 1);
1166 // happens with consecutive row of same direction
1167 if (left_pos == right_pos) {
1168 left_pos += cit->isRTL() ? 1 : -1;
1171 // same code but with the element at the right
1172 else if (pos() == cit->right_pos()) {
1173 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1174 << "), AT RIGHT of *cit=" << *cit);
1175 // this one is easy (see common case below)
1176 left_pos = pos() - (cit->isRTL() ? 0 : 1);
1177 // at the right of the row
1178 if (cit + 1 == row.end())
1181 if (!findNonVirtual(row, cit, false))
1183 // [ 1 2![ [ 3 4 [ => (2, 3)
1184 // or [ 1 2![ ] 4 3 ] => (2, 4)
1185 // or ] 2 1|] [ 3 4 [ => (1, 3)
1186 // or ] 4 3|] ] 2 1 ] => (3, 2)
1187 right_pos = cit->left_pos() - (cit->isRTL() ? 1 : 0);
1188 // happens with consecutive row of same direction
1189 if (right_pos == left_pos)
1190 right_pos += cit->isRTL() ? -1 : 1;
1192 // common case: both positions are inside the row element
1194 // [ 1 2|3 [ => (2, 3)
1195 // or ] 3|2 1 ] => (3, 2)
1196 left_pos = pos() - (cit->isRTL() ? 0 : 1);
1197 right_pos = pos() - (cit->isRTL() ? 1 : 0);
1200 // Note that debug message does not catch all early returns above
1201 LYXERR(Debug::RTL,"getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1202 << ") => (" << left_pos << ", " << right_pos <<")");
1206 bool Cursor::posVisToNewRow(bool movingLeft)
1208 Row const & row = textRow();
1209 bool par_is_LTR = !row.isRTL();
1211 // Inside a table, determining whether to move to the next or
1212 // previous row should be done based on the table's direction.
1213 if (inset().asInsetTabular()) {
1214 par_is_LTR = !inset().asInsetTabular()->isRightToLeft(*this);
1215 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
1218 // if moving left in an LTR paragraph or moving right in an
1219 // RTL one, move to previous row
1220 if (par_is_LTR == movingLeft) {
1221 if (row.pos() == 0) { // we're at first row in paragraph
1222 if (pit() == 0) // no previous paragraph! don't move
1224 // move to last pos in previous par
1228 } else { // move to previous row in this par
1229 pos() = row.pos() - 1; // this is guaranteed to be in previous row
1233 // if moving left in an RTL paragraph or moving right in an
1234 // LTR one, move to next row
1236 if (row.endpos() == lastpos()) { // we're at last row in paragraph
1237 if (pit() == lastpit()) // last paragraph! don't move
1239 // move to first row in next par
1243 } else { // move to next row in this par
1244 pos() = row.endpos();
1249 // make sure we're at left-/right-most pos in new row
1250 posVisToRowExtremity(!movingLeft);
1256 void Cursor::posVisToRowExtremity(bool left)
1258 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
1259 << (boundary() ? 1 : 0));
1261 TextMetrics const & tm = bv_->textMetrics(text());
1262 // Looking for extremities is like clicking on the left or the
1263 // right of the row.
1264 int x = tm.origin().x_ + (left ? 0 : textRow().width());
1266 pos() = tm.getPosNearX(textRow(), x, b);
1269 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
1270 << (boundary() ? 1 : 0));
1274 bool Cursor::reverseDirectionNeeded() const
1277 * We determine the directions based on the direction of the
1278 * bottom() --- i.e., outermost --- paragraph, because that is
1279 * the only way to achieve consistency of the arrow's movements
1280 * within a paragraph, and thus avoid situations in which the
1281 * cursor gets stuck.
1283 return bottom().paragraph().isRTL(bv().buffer().params());
1287 void Cursor::setTargetX(int x)
1290 textTargetOffset_ = 0;
1294 int Cursor::x_target() const
1300 void Cursor::clearTargetX()
1303 textTargetOffset_ = 0;
1307 void Cursor::updateTextTargetOffset()
1312 textTargetOffset_ = x - x_target_;
1316 bool Cursor::selHandle(bool sel)
1318 //lyxerr << "Cursor::selHandle" << endl;
1321 if (sel == selection())
1325 cap::saveSelection(*this);
1333 bool Cursor::atFirstOrLastRow(bool up)
1335 TextMetrics const & tm = bv_->textMetrics(text());
1336 ParagraphMetrics const & pm = tm.parMetrics(pit());
1339 if (pos() && boundary())
1340 row = pm.pos2row(pos() - 1);
1342 row = pm.pos2row(pos());
1345 if (pit() == 0 && row == 0)
1348 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1349 row + 1 >= int(pm.rows().size()))
1359 ///////////////////////////////////////////////////////////////////
1362 // The part below is the non-integrated rest of the original math
1363 // cursor. This should be either generalized for texted or moved
1364 // back to mathed (in most cases to InsetMathNest).
1366 ///////////////////////////////////////////////////////////////////
1368 #include "mathed/InsetMathChar.h"
1369 #include "mathed/InsetMathGrid.h"
1370 #include "mathed/InsetMathScript.h"
1371 #include "mathed/InsetMathUnknown.h"
1372 #include "mathed/MathFactory.h"
1373 #include "mathed/MathStream.h"
1374 #include "mathed/MathSupport.h"
1379 bool Cursor::openable(MathAtom const & t) const
1390 // we can't move into anything new during selection
1391 if (depth() >= anchor_.depth())
1393 if (t.nucleus() != &anchor_[depth()].inset())
1400 void Cursor::plainErase()
1402 cell().erase(pos());
1406 void Cursor::plainInsert(MathAtom const & t)
1408 cell().insert(pos(), t);
1410 inset().setBuffer(bv_->buffer());
1412 checkBufferStructure();
1416 void Cursor::insert(char_type c)
1418 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1419 LASSERT(!empty(), return);
1421 cap::selClearOrDel(*this);
1422 insert(new InsetMathChar(c));
1424 text()->insertChar(*this, c);
1429 void Cursor::insert(docstring const & str)
1431 for (char_type c : str)
1436 void Cursor::insert(Inset * inset0)
1438 LASSERT(inset0, return);
1440 insert(MathAtom(inset0->asInsetMath()));
1442 text()->insertInset(*this, inset0);
1443 inset0->setBuffer(bv_->buffer());
1445 if (inset0->isLabeled())
1446 forceBufferUpdate();
1451 void Cursor::insert(MathAtom const & t)
1453 LATTEST(inMathed());
1454 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1456 cap::selClearOrDel(*this);
1461 void Cursor::insert(MathData const & ar)
1463 LATTEST(inMathed());
1466 cap::eraseSelection(*this);
1467 cell().insert(pos(), ar);
1469 // FIXME audit setBuffer calls
1470 inset().setBuffer(bv_->buffer());
1474 int Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1476 LATTEST(inMathed());
1477 MathData ar(buffer());
1479 if (ar.size() == 1 && (enter || selection()))
1487 void Cursor::niceInsert(MathAtom const & t)
1489 LATTEST(inMathed());
1491 docstring const safe = cap::grabAndEraseSelection(*this);
1493 // If possible, enter the new inset and move the contents of the selection
1494 if (t->isActive()) {
1496 // be careful here: don't use 'pushBackward(t)' as this we need to
1497 // push the clone, not the original
1498 pushBackward(*nextInset());
1499 // We may not use niceInsert here (recursion)
1500 MathData ar(buffer());
1503 } else if (t->asMacro() && !safe.empty()) {
1504 MathData ar(buffer());
1506 docstring const name = t->asMacro()->name();
1507 MacroData const * data = buffer()->getMacro(name);
1508 if (data && data->numargs() - data->optionals() > 0) {
1509 plainInsert(MathAtom(new InsetMathBrace(ar)));
1516 bool Cursor::backspace(bool const force)
1519 cap::eraseSelection(*this);
1524 // If empty cell, and not part of a big cell
1525 if (lastpos() == 0 && inset().nargs() == 1) {
1527 // Directly delete empty cell: [|[]] => [|]
1533 // [|], can not delete from inside
1544 if (inMacroMode()) {
1545 InsetMathUnknown * p = activeMacro();
1546 if (p->name().size() > 1) {
1547 p->setName(p->name().substr(0, p->name().size() - 1));
1552 if (pos() != 0 && !force && prevAtom()->confirmDeletion()) {
1553 // let's require two backspaces for 'big stuff' and
1554 // highlight on the first
1566 bool Cursor::erase(bool const force)
1572 cap::eraseSelection(*this);
1576 // delete empty cells if possible
1577 if (pos() == lastpos() && inset().idxDelete(idx()))
1580 // special behaviour when in last position of cell
1581 if (pos() == lastpos()) {
1582 bool one_cell = inset().nargs() == 1;
1583 if (one_cell && lastpos() == 0) {
1585 // Directly delete empty cell: [|[]] => [|]
1591 // [|], can not delete from inside
1596 inset().idxGlue(idx());
1600 // 'clever' UI hack: only erase large items if previously slected
1601 if (pos() != lastpos() && !force && nextAtom()->confirmDeletion()) {
1616 DocIterator save = *this;
1617 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1618 this->dispatch(cmd);
1619 if (disp_.dispatched())
1629 DocIterator save = *this;
1630 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1631 this->dispatch(cmd);
1632 if (disp_.dispatched())
1639 void Cursor::handleNest(MathAtom const & a, int c)
1641 //lyxerr << "Cursor::handleNest: " << c << endl;
1643 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1646 pushBackward(*nextInset());
1650 int Cursor::targetX() const
1652 if (x_target() != -1)
1661 int Cursor::textTargetOffset() const
1663 return textTargetOffset_;
1667 void Cursor::setTargetX()
1676 bool Cursor::macroModeClose()
1680 InsetMathUnknown * p = activeMacro();
1682 MathData selection(buffer());
1683 asArray(p->selection(), selection);
1684 docstring const s = p->name();
1686 cell().erase(pos());
1688 // do nothing if the macro name is empty
1692 // trigger updates of macros, at least, if no full
1693 // updates take place anyway
1694 screenUpdateFlags(Update::Force);
1696 docstring const name = s.substr(1);
1697 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1698 if (in && in->interpretString(*this, s))
1700 bool const user_macro = buffer()->getMacro(name, *this, false);
1701 MathAtom atom = user_macro ? MathAtom(new InsetMathMacro(buffer(), name))
1702 : createInsetMath(name, buffer());
1704 // try to put argument into macro, if we just inserted a macro
1705 bool macroArg = false;
1706 InsetMathMacro * atomAsMacro = atom.nucleus()->asMacro();
1708 // macros here are still unfolded (in init mode in fact). So
1709 // we have to resolve the macro here manually and check its arity
1710 // to put the selection behind it if arity > 0.
1711 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1712 if (!selection.empty() && data && data->numargs() - data->optionals() > 0) {
1714 atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1716 // non-greedy case. Do not touch the arguments behind
1717 atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1720 // insert remembered selection into first argument of a non-macro
1721 else if (atom.nucleus()->nargs() > 0)
1722 atom.nucleus()->cell(0).append(selection);
1724 MathWordList const & words = mathedWordList();
1725 MathWordList::const_iterator it = words.find(name);
1726 bool keep_mathmode = user_macro
1727 || (it != words.end() && (it->second.inset == "font"
1728 || it->second.inset == "oldfont"
1729 || it->second.inset == "mbox"));
1730 bool ert_macro = !user_macro && it == words.end() && atomAsMacro;
1732 if (in && in->currentMode() == Inset::TEXT_MODE
1733 && atom.nucleus()->currentMode() == Inset::MATH_MODE
1734 && name != from_ascii("ensuremath") && !ert_macro) {
1735 MathAtom at(new InsetMathEnsureMath(buffer()));
1736 at.nucleus()->cell(0).push_back(atom);
1739 } else if (in && in->currentMode() == Inset::MATH_MODE
1740 && atom.nucleus()->currentMode() == Inset::TEXT_MODE
1741 && !keep_mathmode) {
1742 MathAtom at = createInsetMath("text", buffer());
1743 at.nucleus()->cell(0).push_back(atom);
1749 // finally put the macro argument behind, if needed
1751 if (selection.size() > 1 || selection[0]->asScriptInset())
1752 plainInsert(MathAtom(new InsetMathBrace(selection)));
1761 bool Cursor::inMacroMode() const
1765 if (pos() == 0 || cell().empty())
1767 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1768 return p && !p->final();
1772 InsetMathUnknown * Cursor::activeMacro()
1774 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1778 InsetMathUnknown const * Cursor::activeMacro() const
1780 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1784 docstring Cursor::macroName()
1786 return inMacroMode() ? activeMacro()->name() : docstring();
1790 void Cursor::pullArg()
1793 MathData ar = cell();
1794 if (popBackward() && inMathed()) {
1796 cell().insert(pos(), ar);
1799 //formula()->mutateToText();
1804 void Cursor::normalize()
1806 if (idx() > lastidx()) {
1807 lyxerr << "this should not really happen - 1: "
1808 << idx() << ' ' << nargs()
1809 << " in: " << &inset() << endl;
1813 if (pos() > lastpos()) {
1814 lyxerr << "this should not really happen - 2: "
1815 << pos() << ' ' << lastpos() << " in idx: " << idx()
1817 odocstringstream os;
1818 otexrowstream ots(os);
1819 WriteStream wi(ots, false, true, WriteStream::wsDefault);
1820 inset().asInsetMath()->write(wi);
1821 lyxerr << to_utf8(os.str()) << endl;
1827 bool Cursor::upDownInMath(bool up)
1829 // Be warned: The 'logic' implemented in this function is highly
1830 // fragile. A distance of one pixel or a '<' vs '<=' _really
1831 // matters. So fiddle around with it only if you think you know
1832 // what you are doing!
1836 xo = beforeDispatchPosX_;
1838 // check if we had something else in mind, if not, this is the future
1840 if (x_target_ == -1)
1842 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1843 // In text mode inside the line (not left or right) possibly set a new target_x,
1844 // but only if we are somewhere else than the previous target-offset.
1846 // We want to keep the x-target on subsequent up/down movements
1847 // that cross beyond the end of short lines. Thus a special
1848 // handling when the cursor is at the end of line: Use the new
1849 // x-target only if the old one was before the end of line
1850 // or the old one was after the beginning of the line
1851 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
1855 left = pos() == textRow().endpos();
1856 right = pos() == textRow().pos();
1858 left = pos() == textRow().pos();
1859 right = pos() == textRow().endpos();
1861 if ((!left && !right) ||
1862 (left && !right && xo < x_target_) ||
1863 (!left && right && x_target_ < xo))
1870 // try neigbouring script insets
1872 if (inMathed() && !selection()) {
1875 InsetMathScript const * p = prevAtom()->asScriptInset();
1876 if (p && p->has(up)) {
1878 push(*const_cast<InsetMathScript*>(p));
1879 idx() = p->idxOfScript(up);
1882 // we went in the right direction? Otherwise don't jump into the script
1886 int oy = beforeDispatchPosY_;
1887 if ((!up && y <= oy) ||
1896 if (pos() != lastpos()) {
1897 InsetMathScript const * p = nextAtom()->asScriptInset();
1898 if (p && p->has(up)) {
1899 push(*const_cast<InsetMathScript*>(p));
1900 idx() = p->idxOfScript(up);
1903 // we went in the right direction? Otherwise don't jump into the script
1907 int oy = beforeDispatchPosY_;
1908 if ((!up && y <= oy) ||
1917 // try to find an inset that knows better then we,
1918 if (inset().idxUpDown(*this, up)) {
1919 //lyxerr << "idxUpDown triggered" << endl;
1920 // try to find best position within this inset
1922 setCursor(bruteFind(*this, xo, yo));
1926 // any improvement going just out of inset?
1927 if (popBackward() && inMathed()) {
1928 //lyxerr << "updown: popBackward succeeded" << endl;
1931 int yold = beforeDispatchPosY_;
1933 if (up ? ynew < yold : ynew > yold)
1937 // no success, we are probably at the document top or bottom
1943 bool Cursor::mathForward(bool word)
1945 LASSERT(inMathed(), return false);
1946 if (pos() < lastpos()) {
1948 // word: skip a group of insets of the form X*(B*|R*|P*) (greedy
1949 // match) where X is any math class, B is mathbin, R is mathrel, and
1950 // P is mathpunct. Make sure that the following remains true:
1951 // mathForward(true); mathBackward(true); mathForward(true)
1952 // is the same as mathForward(true) and
1953 // mathBackward(true); mathForward(true); mathBackward(true)
1954 // is the same as mathBackward(true).
1955 MathClass mc = nextMath().mathClass();
1958 while (pos() < lastpos() && mc == nextMath().mathClass());
1959 if (pos() < lastpos() &&
1960 ((mc = nextMath().mathClass()) == MC_BIN ||
1961 mc == MC_REL || mc == MC_PUNCT))
1964 while (pos() < lastpos() && mc == nextMath().mathClass());
1965 } else if (openable(nextAtom())) {
1966 // single step: try to enter the next inset
1967 pushBackward(nextMath());
1968 inset().idxFirst(*this);
1973 if (inset().idxForward(*this))
1975 // try to pop forwards --- but don't pop out of math! leave that to
1977 int s = depth() - 2;
1978 if (s >= 0 && operator[](s).inset().asInsetMath())
1979 return popForward();
1984 bool Cursor::mathBackward(bool word)
1986 LASSERT(inMathed(), return false);
1989 // word: skip a group of insets. See the comment in mathForward.
1990 MathClass mc = prevMath().mathClass();
1993 while (pos() > 0 && mc == prevMath().mathClass());
1994 if (pos() > 0 && (mc == MC_BIN || mc == MC_REL || mc == MC_PUNCT)) {
1995 mc = prevMath().mathClass();
1998 while (pos() > 0 && mc == prevMath().mathClass());
2000 } else if (openable(prevAtom())) {
2001 // single step: try to enter the preceding inset
2004 inset().idxLast(*this);
2009 if (inset().idxBackward(*this))
2011 // try to pop backwards --- but don't pop out of math! leave that to
2013 int s = depth() - 2;
2014 if (s >= 0 && operator[](s).inset().asInsetMath())
2015 return popBackward();
2020 bool Cursor::upDownInText(bool up, bool & updateNeeded)
2022 LASSERT(text(), return false);
2028 xo = beforeDispatchPosX_;
2030 // update the targetX - this is here before the "return false"
2031 // to set a new target which can be used by InsetTexts above
2032 // if we cannot move up/down inside this inset anymore
2033 if (x_target_ == -1)
2035 else if (xo - textTargetOffset() != x_target() &&
2036 depth() == beforeDispatchCursor_.depth()) {
2037 // In text mode inside the line (not left or right)
2038 // possibly set a new target_x, but only if we are
2039 // somewhere else than the previous target-offset.
2041 // We want to keep the x-target on subsequent up/down
2042 // movements that cross beyond the end of short lines.
2043 // Thus a special handling when the cursor is at the
2044 // end of line: Use the new x-target only if the old
2045 // one was before the end of line or the old one was
2046 // after the beginning of the line
2047 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
2051 left = pos() == textRow().endpos();
2052 right = pos() == textRow().pos();
2054 left = pos() == textRow().pos();
2055 right = pos() == textRow().endpos();
2057 if ((!left && !right) ||
2058 (left && !right && xo < x_target_) ||
2059 (!left && right && x_target_ < xo))
2066 // first get the current line
2067 TextMetrics & tm = bv_->textMetrics(text());
2068 ParagraphMetrics const & pm = tm.parMetrics(pit());
2070 if (pos() && boundary())
2071 row = pm.pos2row(pos() - 1);
2073 row = pm.pos2row(pos());
2075 if (atFirstOrLastRow(up)) {
2076 // Is there a place for the cursor to go ? If yes, we
2077 // can execute the DEPM, otherwise we should keep the
2078 // paragraph to host the cursor.
2079 Cursor dummy = *this;
2080 bool valid_destination = false;
2081 for(; dummy.depth(); dummy.pop())
2082 if (!dummy.atFirstOrLastRow(up)) {
2083 valid_destination = true;
2087 // will a next dispatch follow and if there is a new
2088 // dispatch will it move the cursor out ?
2089 if (depth() > 1 && valid_destination) {
2090 // The cursor hasn't changed yet. This happens when
2091 // you e.g. move out of an inset. And to give the
2092 // DEPM the possibility of doing something we must
2093 // provide it with two different cursors. (Lgb, vfr)
2095 dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
2096 dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
2098 updateNeeded |= bv().checkDepm(dummy, *this);
2099 updateTextTargetOffset();
2101 forceBufferUpdate();
2106 // with and without selection are handled differently
2108 int yo = bv().getPos(*this).y_;
2110 // To next/previous row
2111 // FIXME: the y position is often guessed wrongly across styles and
2112 // insets, which leads to weird behaviour.
2114 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
2116 tm.editXY(*this, xo, yo + textRow().descent() + 1);
2117 x_target_ = old.x_target_;
2120 // This happens when you move out of an inset.
2121 // And to give the DEPM the possibility of doing
2122 // something we must provide it with two different
2124 Cursor dummy = *this;
2127 if (bv().checkDepm(dummy, old)) {
2128 updateNeeded = true;
2129 // Make sure that cur gets back whatever happened to dummy (Lgb)
2132 if (inTexted() && pos() && paragraph().isEnvSeparator(pos() - 1))
2135 // if there is a selection, we stay out of any inset,
2136 // and just jump to the right position:
2142 } else if (pit() > 0) {
2144 TextMetrics & tm = bv_->textMetrics(text());
2145 if (!tm.contains(pit()))
2146 tm.newParMetricsUp();
2147 ParagraphMetrics const & pmcur = tm.parMetrics(pit());
2148 next_row = pmcur.rows().size() - 1;
2151 if (row + 1 < int(pm.rows().size())) {
2153 } else if (pit() + 1 < int(text()->paragraphs().size())) {
2155 TextMetrics & tm = bv_->textMetrics(text());
2156 if (!tm.contains(pit()))
2157 tm.newParMetricsDown();
2162 Row const & real_next_row = tm.parMetrics(pit()).rows()[next_row];
2164 top().pos() = tm.getPosNearX(real_next_row, xo, bound);
2166 // When selection==false, this is done by TextMetrics::editXY
2169 updateNeeded |= bv().checkDepm(*this, old);
2173 forceBufferUpdate();
2174 updateTextTargetOffset();
2179 void Cursor::handleFont(string const & font)
2181 LYXERR(Debug::DEBUG, font);
2185 safe = cap::grabAndEraseSelection(*this);
2190 if (lastpos() != 0) {
2191 // something left in the cell
2193 // cursor in first position
2195 } else if (pos() == lastpos()) {
2196 // cursor in last position
2199 // cursor in between. split cell
2200 MathData::iterator bt = cell().begin();
2201 MathAtom at = createInsetMath(from_utf8(font), buffer());
2202 at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
2203 cell().erase(bt, bt + pos());
2208 // nothing left in the cell
2217 void Cursor::undispatched() const
2219 disp_.dispatched(false);
2223 void Cursor::dispatched() const
2225 disp_.dispatched(true);
2229 void Cursor::screenUpdateFlags(Update::flags f) const
2231 disp_.screenUpdate(f);
2235 void Cursor::forceBufferUpdate() const
2237 disp_.forceBufferUpdate();
2241 void Cursor::clearBufferUpdate() const
2243 disp_.clearBufferUpdate();
2247 bool Cursor::needBufferUpdate() const
2249 return disp_.needBufferUpdate();
2253 void Cursor::noScreenUpdate() const
2255 disp_.screenUpdate(Update::None);
2259 Font Cursor::getFont() const
2261 // The logic here should more or less match to the
2262 // Cursor::setCurrentFont logic, i.e. the cursor height should
2263 // give a hint what will happen if a character is entered.
2264 // FIXME: this is not the case, what about removing this method ? (see #10478).
2266 // HACK. far from being perfect...
2268 CursorSlice const & sl = innerTextSlice();
2269 Text const & text = *sl.text();
2270 Paragraph const & par = text.getPar(sl.pit());
2272 // on boundary, so we are really at the character before
2273 pos_type pos = sl.pos();
2274 if (pos > 0 && boundary())
2277 // on space? Take the font before (only for RTL boundary stay)
2279 TextMetrics const & tm = bv().textMetrics(&text);
2280 if (pos == sl.lastpos()
2281 || (par.isSeparator(pos)
2282 && !tm.isRTLBoundary(sl.pit(), pos)))
2286 // get font at the position
2287 Font font = par.getFont(buffer()->params(), pos,
2288 text.outerFont(sl.pit()));
2294 void Cursor::sanitize()
2296 setBuffer(buffer());
2297 CursorData::sanitize();
2298 new_word_.sanitize();
2302 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2304 // find inset in common
2306 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2307 if (&old[i].inset() != &cur[i].inset())
2311 // update words if we just moved to another paragraph
2312 if (i == old.depth() && i == cur.depth()
2313 && !cur.buffer()->isClean()
2314 && cur.inTexted() && old.inTexted()
2315 && cur.pit() != old.pit()) {
2316 old.paragraph().updateWords();
2319 // notify everything on top of the common part in old cursor,
2320 // but stop if the inset claims the cursor to be invalid now
2321 for (size_type j = i; j < old.depth(); ++j) {
2322 Cursor inset_pos = old;
2323 inset_pos.cutOff(j);
2324 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2328 // notify everything on top of the common part in new cursor,
2329 // but stop if the inset claims the cursor to be invalid now
2330 for (; i < cur.depth(); ++i) {
2331 if (cur[i].inset().notifyCursorEnters(cur))
2339 void Cursor::setCurrentFont()
2341 CursorSlice const & cs = innerTextSlice();
2342 Paragraph const & par = cs.paragraph();
2343 pos_type cpit = cs.pit();
2344 pos_type cpos = cs.pos();
2345 Text const & ctext = *cs.text();
2346 TextMetrics const & tm = bv().textMetrics(&ctext);
2348 // are we behind previous char in fact? -> go to that char
2349 if (cpos > 0 && boundary())
2352 // find position to take the font from
2354 // paragraph end? -> font of last char
2355 if (cpos == lastpos())
2357 // on space? -> look at the words in front of space
2358 else if (cpos > 0 && par.isSeparator(cpos)) {
2359 // abc| def -> font of c
2360 // abc |[WERBEH], i.e. boundary==true -> font of c
2361 // abc [WERBEH]| def, font of the space
2362 if (!tm.isRTLBoundary(cpit, cpos))
2368 BufferParams const & bufparams = buffer()->params();
2369 current_font = par.getFontSettings(bufparams, cpos);
2370 real_current_font = tm.displayFont(cpit, cpos);
2372 // special case for paragraph end
2373 if (cs.pos() == lastpos()
2374 && tm.isRTLBoundary(cpit, cs.pos())
2376 Language const * lang = par.getParLanguage(bufparams);
2377 current_font.setLanguage(lang);
2378 current_font.fontInfo().setNumber(FONT_OFF);
2379 real_current_font.setLanguage(lang);
2380 real_current_font.fontInfo().setNumber(FONT_OFF);
2385 void Cursor::checkBufferStructure()
2387 Buffer const * master = buffer()->masterBuffer();
2388 master->tocBackend().updateItem(*this);
2389 if (master != buffer() && !master->hasGuiDelegate())
2390 // In case the master has no gui associated with it,
2391 // the TocItem is not updated (part of bug 5699).
2392 buffer()->tocBackend().updateItem(*this);
2394 // If the last tracked change of the paragraph has just been
2395 // deleted, then we need to recompute the buffer flag
2396 // tracked_changes_present_.
2397 if (inTexted() && paragraph().isChangeUpdateRequired())
2398 disp_.forceChangesUpdate();
2402 void Cursor::moveToClosestEdge(int const x, bool const edit)
2404 if (Inset const * inset = nextInset()) {
2405 // stay in front of insets for which we want to open the dialog
2406 // (e.g. InsetMathSpace).
2407 if (edit && (inset->hasSettings() || !inset->contextMenuName().empty()))
2409 CoordCache::Insets const & insetCache = bv().coordCache().getInsets();
2410 if (!insetCache.has(inset))
2412 int const wid = insetCache.dim(inset).wid;
2413 Point p = insetCache.xy(inset);
2414 if (x > p.x_ + (wid + 1) / 2)