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 int CursorData::countInsetsInSelection(InsetCode const & inset_code)
504 DocIterator from, to;
505 from = selectionBegin();
510 if (!from.nextInset()) //move to closest inset
513 while (!from.empty() && from < to) {
514 Inset * inset = from.nextInset();
517 if (inset->lyxCode() == inset_code)
525 bool CursorData::insetInSelection(InsetCode const & inset_code)
530 DocIterator from, to;
531 from = selectionBegin();
534 if (!from.nextInset()) //move to closest inset
537 while (!from.empty() && from < to) {
538 Inset * inset = from.nextInset();
541 if (inset->lyxCode() == inset_code)
549 bool CursorData::fixIfBroken()
551 bool const broken_cursor = DocIterator::fixIfBroken();
552 bool const broken_anchor = anchor_.fixIfBroken();
554 if (broken_cursor || broken_anchor) {
555 clearNewWordPosition();
563 void CursorData::sanitize()
565 DocIterator::sanitize();
566 new_word_.sanitize();
574 bool CursorData::isInside(Inset const * p) const
576 for (size_t i = 0; i != depth(); ++i)
577 if (&operator[](i).inset() == p)
583 void CursorData::leaveInset(Inset const & inset)
585 for (size_t i = 0; i != depth(); ++i) {
586 if (&operator[](i).inset() == &inset) {
594 bool CursorData::textUndo()
596 if (!buffer()->undo().textUndo(*this))
603 bool CursorData::textRedo()
605 if (!buffer()->undo().textRedo(*this))
612 void CursorData::finishUndo() const
614 buffer()->undo().finishUndo();
618 void CursorData::beginUndoGroup() const
620 buffer()->undo().beginUndoGroup(*this);
624 void CursorData::endUndoGroup() const
626 buffer()->undo().endUndoGroup(*this);
630 void CursorData::recordUndo(pit_type from, pit_type to) const
632 buffer()->undo().recordUndo(*this, from, to);
636 void CursorData::recordUndo(pit_type from) const
638 buffer()->undo().recordUndo(*this, from, pit());
642 void CursorData::recordUndo(UndoKind kind) const
644 buffer()->undo().recordUndo(*this, kind);
648 void CursorData::recordUndoInset(Inset const * in) const
650 buffer()->undo().recordUndoInset(*this, in);
654 void CursorData::recordUndoFullBuffer() const
656 buffer()->undo().recordUndoFullBuffer(*this);
660 void CursorData::recordUndoBufferParams() const
662 buffer()->undo().recordUndoBufferParams(*this);
666 void CursorData::recordUndoSelection() const
669 if (cap::multipleCellsSelected(*this))
674 buffer()->undo().recordUndo(*this,
675 selBegin().pit(), selEnd().pit());
680 int CursorData::currentMode()
682 LASSERT(!empty(), return Inset::UNDECIDED_MODE);
683 for (int i = depth() - 1; i >= 0; --i) {
684 int res = operator[](i).inset().currentMode();
685 bool locked_mode = operator[](i).inset().lockedMode();
686 // Also return UNDECIDED_MODE when the mode is locked,
687 // as in this case it is treated the same as TEXT_MODE
688 if (res != Inset::UNDECIDED_MODE || locked_mode)
691 return Inset::TEXT_MODE;
695 bool CursorData::confirmDeletion(bool const before) const
698 if (Inset const * inset = before ? prevInset() : nextInset())
699 return inset->confirmDeletion();
701 DocIterator dit = selectionBegin();
702 CursorSlice const end = selectionEnd().top();
703 for (; dit.top() < end; dit.top().forwardPos())
704 if (Inset const * inset = dit.nextInset())
705 if (inset->confirmDeletion())
718 // be careful: this is called from the bv's constructor, too, so
719 // bv functions are not yet available!
720 Cursor::Cursor(BufferView & bv)
721 : CursorData(&bv.buffer()), bv_(&bv),
722 x_target_(-1), textTargetOffset_(0),
723 beforeDispatchPosX_(0), beforeDispatchPosY_(0)
734 void Cursor::setCursorData(CursorData const & data)
736 CursorData::operator=(data);
740 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
744 // Try to fix cursor in case it is broken.
747 // Is this a function that acts on inset at point?
748 Inset * inset = cur.nextInset();
749 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
750 && inset && inset->getStatus(cur, cmd, status))
753 // This is, of course, a mess. Better create a new doc iterator and use
754 // this in Inset::getStatus. This might require an additional
755 // BufferView * arg, though (which should be avoided)
756 //Cursor safe = *this;
758 for ( ; cur.depth(); cur.pop()) {
759 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
760 // LASSERT: Is it safe to continue here, or should we return?
761 LASSERT(cur.idx() <= cur.lastidx(), /**/);
762 LASSERT(cur.pit() <= cur.lastpit(), /**/);
763 LASSERT(cur.pos() <= cur.lastpos(), /**/);
765 // The inset's getStatus() will return 'true' if it made
766 // a definitive decision on whether it want to handle the
767 // request or not. The result of this decision is put into
768 // the 'status' parameter.
769 if (cur.inset().getStatus(cur, cmd, status)) {
778 void Cursor::saveBeforeDispatchPosXY()
780 getPos(beforeDispatchPosX_, beforeDispatchPosY_);
784 void Cursor::dispatch(FuncRequest const & cmd0)
786 LYXERR(Debug::ACTION, "Cursor::dispatch: cmd: " << cmd0 << '\n' << *this);
791 FuncRequest cmd = cmd0;
794 disp_ = DispatchResult();
798 // Is this a function that acts on inset at point?
799 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
801 disp_.dispatched(true);
802 disp_.screenUpdate(Update::FitCursor | Update::Force);
803 FuncRequest tmpcmd = cmd;
804 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
805 << cmd0 << endl << *this);
806 nextInset()->dispatch(*this, tmpcmd);
807 if (disp_.dispatched()) {
813 // store some values to be used inside of the handlers
814 beforeDispatchCursor_ = *this;
815 for (; depth(); pop(), boundary(false)) {
816 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
817 << cmd0 << endl << *this);
819 // In any of these cases, the cursor is invalid, and we should
820 // try to save this document rather than crash.
821 LBUFERR(pos() <= lastpos());
822 LBUFERR(idx() <= lastidx());
823 LBUFERR(pit() <= lastpit());
825 // The common case is 'LFUN handled, need update', so make the
826 // LFUN handler's life easier by assuming this as default value.
827 // The handler can reset the update and val flags if necessary.
828 disp_.screenUpdate(Update::FitCursor | Update::Force);
829 disp_.dispatched(true);
830 inset().dispatch(*this, cmd);
831 if (disp_.dispatched())
835 // it completely to get a 'bomb early' behaviour in case this
836 // object will be used again.
837 if (!disp_.dispatched()) {
838 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
839 // We might have invalidated the cursor when removing an empty
840 // paragraph while the cursor could not be moved out the inset
841 // while we initially thought we could. This might happen when
842 // a multiline inset becomes an inline inset when the second
843 // paragraph is removed.
844 if (safe.pit() > safe.lastpit()) {
845 safe.pit() = safe.lastpit();
846 safe.pos() = safe.lastpos();
849 disp_.screenUpdate(Update::None);
850 disp_.dispatched(false);
852 // restore the previous one because nested Cursor::dispatch calls
853 // are possible which would change it
854 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
858 // NOTE: The code below has been copied to BufferView::dispatch.
859 // If you need to modify this, please update the other one too.
861 // notify insets we just left
863 old.beginUndoGroup();
865 bool badcursor = notifyCursorLeavesOrEnters(old, *this);
868 bv().resetInlineCompletionPos();
875 DispatchResult const & Cursor::result() const
881 void Cursor::message(docstring const & msg) const
883 disp_.setMessage(msg);
887 void Cursor::errorMessage(docstring const & msg) const
889 disp_.setMessage(msg);
890 disp_.setError(true);
894 BufferView & Cursor::bv() const
903 LBUFERR(depth() >= 1);
908 void Cursor::push(Inset & p)
910 push_back(CursorSlice(p));
911 p.setBuffer(*buffer());
915 void Cursor::pushBackward(Inset & p)
917 LASSERT(!empty(), return);
918 //lyxerr << "Entering inset " << t << " front" << endl;
924 bool Cursor::popBackward()
926 LASSERT(!empty(), return false);
934 bool Cursor::popForward()
936 LASSERT(!empty(), return false);
937 //lyxerr << "Leaving inset from in back" << endl;
938 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
942 pos() += lastpos() - lp + 1;
947 void Cursor::getPos(int & x, int & y) const
949 Point p = bv().getPos(*this);
955 Row const & Cursor::textRow() const
957 CursorSlice const & cs = innerTextSlice();
958 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
959 return pm.getRow(pos(), boundary());
963 bool Cursor::posVisRight(bool skip_inset)
965 Cursor new_cur = *this; // where we will move to
966 pos_type left_pos; // position visually left of current cursor
967 pos_type right_pos; // position visually right of current cursor
969 getSurroundingPos(left_pos, right_pos);
971 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
973 // Are we at an inset?
974 new_cur.pos() = right_pos;
975 new_cur.boundary(false);
977 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
978 // we actually move the cursor at the end of this
979 // function, for now we just keep track of the new
980 // position in new_cur...
981 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
984 // Are we already at rightmost pos in row?
985 else if (text()->empty() || right_pos == -1) {
988 if (!new_cur.posVisToNewRow(false)) {
989 LYXERR(Debug::RTL, "not moving!");
993 // we actually move the cursor at the end of this
994 // function, for now just keep track of the new
995 // position in new_cur...
996 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
997 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
1000 // normal movement to the right
1003 // Recall, if the cursor is at position 'x', that
1004 // means *before* the character at position 'x'. In
1005 // RTL, "before" means "to the right of", in LTR, "to
1006 // the left of". So currently our situation is this:
1007 // the position to our right is 'right_pos' (i.e.,
1008 // we're currently to the left of 'right_pos'). In
1009 // order to move to the right, it depends whether or
1010 // not the character at 'right_pos' is RTL.
1011 bool const new_pos_is_RTL = paragraph().getFontSettings(
1012 buffer()->params(), right_pos).isVisibleRightToLeft();
1013 // If the character at 'right_pos' *is* LTR, then in
1014 // order to move to the right of it, we need to be
1015 // *after* 'right_pos', i.e., move to position
1017 if (!new_pos_is_RTL) {
1018 new_cur.pos() = right_pos + 1;
1019 // set the boundary to true in two situations:
1021 // 1. if new_pos is now lastpos, and we're in
1022 // an RTL paragraph (this means that we're
1023 // moving right to the end of an LTR chunk
1024 // which is at the end of an RTL paragraph);
1025 (new_cur.pos() == lastpos()
1026 && paragraph().isRTL(buffer()->params()))
1027 // 2. if the position *after* right_pos is RTL
1028 // (we want to be *after* right_pos, not
1029 // before right_pos + 1!)
1030 || paragraph().getFontSettings(buffer()->params(),
1031 new_cur.pos()).isVisibleRightToLeft()
1033 new_cur.boundary(true);
1034 else // set the boundary to false
1035 new_cur.boundary(false);
1037 // Otherwise (if the character at position 'right_pos'
1038 // is RTL), then moving to the right of it is as easy
1039 // as setting the new position to 'right_pos'.
1041 new_cur.pos() = right_pos;
1042 new_cur.boundary(false);
1047 bool const moved = new_cur != *this || new_cur.boundary() != boundary();
1050 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
1051 << (new_cur.boundary() ? " (boundary)" : ""));
1059 bool Cursor::posVisLeft(bool skip_inset)
1061 Cursor new_cur = *this; // where we will move to
1062 pos_type left_pos; // position visually left of current cursor
1063 pos_type right_pos; // position visually right of current cursor
1065 getSurroundingPos(left_pos, right_pos);
1067 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
1069 // Are we at an inset?
1070 new_cur.pos() = left_pos;
1071 new_cur.boundary(false);
1073 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
1074 // we actually move the cursor at the end of this
1075 // function, for now we just keep track of the new
1076 // position in new_cur...
1077 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
1080 // Are we already at leftmost pos in row?
1081 else if (text()->empty() || left_pos == -1) {
1084 if (!new_cur.posVisToNewRow(true)) {
1085 LYXERR(Debug::RTL, "not moving!");
1089 // we actually move the cursor at the end of this
1090 // function, for now just keep track of the new
1091 // position in new_cur...
1092 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
1093 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
1096 // normal movement to the left
1099 // Recall, if the cursor is at position 'x', that
1100 // means *before* the character at position 'x'. In
1101 // RTL, "before" means "to the right of", in LTR, "to
1102 // the left of". So currently our situation is this:
1103 // the position to our left is 'left_pos' (i.e., we're
1104 // currently to the right of 'left_pos'). In order to
1105 // move to the left, it depends whether or not the
1106 // character at 'left_pos' is RTL.
1107 bool const new_pos_is_RTL = paragraph().getFontSettings(
1108 buffer()->params(), left_pos).isVisibleRightToLeft();
1109 // If the character at 'left_pos' *is* RTL, then in
1110 // order to move to the left of it, we need to be
1111 // *after* 'left_pos', i.e., move to position
1113 if (new_pos_is_RTL) {
1114 new_cur.pos() = left_pos + 1;
1115 // set the boundary to true in two situations:
1117 // 1. if new_pos is now lastpos and we're in
1118 // an LTR paragraph (this means that we're
1119 // moving left to the end of an RTL chunk
1120 // which is at the end of an LTR paragraph);
1121 (new_cur.pos() == lastpos()
1122 && !paragraph().isRTL(buffer()->params()))
1123 // 2. if the position *after* left_pos is not
1124 // RTL (we want to be *after* left_pos, not
1125 // before left_pos + 1!)
1126 || !paragraph().getFontSettings(buffer()->params(),
1127 new_cur.pos()).isVisibleRightToLeft()
1129 new_cur.boundary(true);
1130 else // set the boundary to false
1131 new_cur.boundary(false);
1133 // Otherwise (if the character at position 'left_pos'
1134 // is LTR), then moving to the left of it is as easy
1135 // as setting the new position to 'left_pos'.
1137 new_cur.pos() = left_pos;
1138 new_cur.boundary(false);
1143 bool const moved = new_cur != *this || new_cur.boundary() != boundary();
1146 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
1147 << (new_cur.boundary() ? " (boundary)" : ""));
1157 // Return true on success
1158 bool findNonVirtual(Row const & row, Row::const_iterator & cit, bool onleft)
1161 while (cit != row.begin() && cit->isVirtual())
1164 while (cit != row.end() && cit->isVirtual())
1167 return cit != row.end() && !cit->isVirtual();
1172 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos) const
1174 // by default, we know nothing.
1178 Row const & row = textRow();
1180 Row::const_iterator cit = row.findElement(pos(), boundary(), dummy);
1181 // Handle the case of empty row
1182 if (cit == row.end()) {
1184 right_pos = row.pos();
1186 left_pos = row.pos() - 1;
1190 // skip virtual elements and exit if no non-virtual one exists
1191 if (!findNonVirtual(row, cit, !cit->isRTL()))
1194 // if the position is at the left side of the element, we have to
1195 // look at the previous element
1196 if (pos() == cit->left_pos()) {
1197 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1198 << "), AT LEFT of *cit=" << *cit);
1199 // this one is easy (see common case below)
1200 right_pos = pos() - (cit->isRTL() ? 1 : 0);
1201 // at the left of the row
1202 if (cit == row.begin())
1205 if (!findNonVirtual(row, cit, true))
1207 // [...[ is the row element, | is cursor position (! with boundary)
1208 // [ 1 2 [ is a ltr row element with pos=1 and endpos=3
1209 // ] 2 1] is an rtl row element with pos=1 and endpos=3
1210 // [ 1 2 [ [|3 4 [ => (2, 3)
1211 // or [ 1 2 [ ]!4 3 ] => (2, 4)
1212 // or ] 2 1 ] [|3 4 [ => (1, 3)
1213 // or ] 4 3 ] ]!2 1 ] => (3, 2)
1214 left_pos = cit->right_pos() - (cit->isRTL() ? 0 : 1);
1215 // happens with consecutive row of same direction
1216 if (left_pos == right_pos) {
1217 left_pos += cit->isRTL() ? 1 : -1;
1220 // same code but with the element at the right
1221 else if (pos() == cit->right_pos()) {
1222 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1223 << "), AT RIGHT of *cit=" << *cit);
1224 // this one is easy (see common case below)
1225 left_pos = pos() - (cit->isRTL() ? 0 : 1);
1226 // at the right of the row
1227 if (cit + 1 == row.end())
1230 if (!findNonVirtual(row, cit, false))
1232 // [ 1 2![ [ 3 4 [ => (2, 3)
1233 // or [ 1 2![ ] 4 3 ] => (2, 4)
1234 // or ] 2 1|] [ 3 4 [ => (1, 3)
1235 // or ] 4 3|] ] 2 1 ] => (3, 2)
1236 right_pos = cit->left_pos() - (cit->isRTL() ? 1 : 0);
1237 // happens with consecutive row of same direction
1238 if (right_pos == left_pos)
1239 right_pos += cit->isRTL() ? -1 : 1;
1241 // common case: both positions are inside the row element
1243 // [ 1 2|3 [ => (2, 3)
1244 // or ] 3|2 1 ] => (3, 2)
1245 left_pos = pos() - (cit->isRTL() ? 0 : 1);
1246 right_pos = pos() - (cit->isRTL() ? 1 : 0);
1249 // Note that debug message does not catch all early returns above
1250 LYXERR(Debug::RTL,"getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1251 << ") => (" << left_pos << ", " << right_pos <<")");
1255 bool Cursor::posVisToNewRow(bool movingLeft)
1257 Row const & row = textRow();
1258 bool par_is_LTR = !row.isRTL();
1260 // Inside a table, determining whether to move to the next or
1261 // previous row should be done based on the table's direction.
1262 if (inset().asInsetTabular()) {
1263 par_is_LTR = !inset().asInsetTabular()->isRightToLeft(*this);
1264 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
1267 // if moving left in an LTR paragraph or moving right in an
1268 // RTL one, move to previous row
1269 if (par_is_LTR == movingLeft) {
1270 if (row.pos() == 0) { // we're at first row in paragraph
1271 if (pit() == 0) // no previous paragraph! don't move
1273 // move to last pos in previous par
1277 } else { // move to previous row in this par
1278 pos() = row.pos() - 1; // this is guaranteed to be in previous row
1282 // if moving left in an RTL paragraph or moving right in an
1283 // LTR one, move to next row
1285 if (row.endpos() == lastpos()) { // we're at last row in paragraph
1286 if (pit() == lastpit()) // last paragraph! don't move
1288 // move to first row in next par
1292 } else { // move to next row in this par
1293 pos() = row.endpos();
1298 // make sure we're at left-/right-most pos in new row
1299 posVisToRowExtremity(!movingLeft);
1305 void Cursor::posVisToRowExtremity(bool left)
1307 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
1308 << (boundary() ? 1 : 0));
1310 TextMetrics const & tm = bv_->textMetrics(text());
1311 // Looking for extremities is like clicking on the left or the
1312 // right of the row.
1313 int x = tm.origin().x_ + (left ? 0 : textRow().width());
1315 pos() = tm.getPosNearX(textRow(), x, b);
1318 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
1319 << (boundary() ? 1 : 0));
1323 bool Cursor::reverseDirectionNeeded() const
1326 * We determine the directions based on the direction of the
1327 * bottom() --- i.e., outermost --- paragraph, because that is
1328 * the only way to achieve consistency of the arrow's movements
1329 * within a paragraph, and thus avoid situations in which the
1330 * cursor gets stuck.
1332 return bottom().paragraph().isRTL(bv().buffer().params());
1336 void Cursor::setTargetX(int x)
1339 textTargetOffset_ = 0;
1343 int Cursor::x_target() const
1349 void Cursor::clearTargetX()
1352 textTargetOffset_ = 0;
1356 void Cursor::updateTextTargetOffset()
1361 textTargetOffset_ = x - x_target_;
1365 bool Cursor::selHandle(bool sel)
1367 //lyxerr << "Cursor::selHandle" << endl;
1370 if (sel == selection())
1374 cap::saveSelection(*this);
1382 bool Cursor::atFirstOrLastRow(bool up)
1384 TextMetrics const & tm = bv_->textMetrics(text());
1385 ParagraphMetrics const & pm = tm.parMetrics(pit());
1388 if (pos() && boundary())
1389 row = pm.pos2row(pos() - 1);
1391 row = pm.pos2row(pos());
1394 if (pit() == 0 && row == 0)
1397 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1398 row + 1 >= int(pm.rows().size()))
1408 ///////////////////////////////////////////////////////////////////
1411 // The part below is the non-integrated rest of the original math
1412 // cursor. This should be either generalized for texted or moved
1413 // back to mathed (in most cases to InsetMathNest).
1415 ///////////////////////////////////////////////////////////////////
1417 #include "mathed/InsetMathChar.h"
1418 #include "mathed/InsetMathGrid.h"
1419 #include "mathed/InsetMathScript.h"
1420 #include "mathed/InsetMathUnknown.h"
1421 #include "mathed/MathFactory.h"
1422 #include "mathed/MathStream.h"
1423 #include "mathed/MathSupport.h"
1428 bool Cursor::openable(MathAtom const & t) const
1439 // we can't move into anything new during selection
1440 if (depth() >= realAnchor().depth())
1442 if (t.nucleus() != &realAnchor()[depth()].inset())
1449 void Cursor::plainErase()
1451 cell().erase(pos());
1455 void Cursor::plainInsert(MathAtom const & t)
1457 cell().insert(pos(), t);
1459 inset().setBuffer(bv_->buffer());
1461 checkBufferStructure();
1465 void Cursor::insert(char_type c)
1467 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1468 LASSERT(!empty(), return);
1470 cap::selClearOrDel(*this);
1471 insert(new InsetMathChar(c));
1473 text()->insertChar(*this, c);
1478 void Cursor::insert(docstring const & str)
1480 for (char_type c : str)
1485 void Cursor::insert(Inset * inset0)
1487 LASSERT(inset0, return);
1489 insert(MathAtom(inset0->asInsetMath()));
1491 text()->insertInset(*this, inset0);
1492 inset0->setBuffer(bv_->buffer());
1494 if (inset0->isLabeled())
1495 forceBufferUpdate();
1500 void Cursor::insert(MathAtom const & t)
1502 LATTEST(inMathed());
1503 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1505 cap::selClearOrDel(*this);
1510 void Cursor::insert(MathData const & ar)
1512 LATTEST(inMathed());
1515 cap::eraseSelection(*this);
1516 cell().insert(pos(), ar);
1518 // FIXME audit setBuffer calls
1519 inset().setBuffer(bv_->buffer());
1523 int Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1525 LATTEST(inMathed());
1526 MathData ar(buffer());
1528 if (ar.size() == 1 && (enter || selection()))
1536 void Cursor::niceInsert(MathAtom const & t)
1538 LATTEST(inMathed());
1540 docstring const safe = cap::grabAndEraseSelection(*this);
1542 // If possible, enter the new inset and move the contents of the selection
1543 if (t->isActive()) {
1545 // be careful here: don't use 'pushBackward(t)' as this we need to
1546 // push the clone, not the original
1547 pushBackward(*nextInset());
1548 // We may not use niceInsert here (recursion)
1549 MathData ar(buffer());
1552 } else if (t->asMacro() && !safe.empty()) {
1553 MathData ar(buffer());
1555 docstring const name = t->asMacro()->name();
1556 MacroData const * data = buffer()->getMacro(name);
1557 if (data && data->numargs() - data->optionals() > 0) {
1558 plainInsert(MathAtom(new InsetMathBrace(ar)));
1565 bool Cursor::backspace(bool const force)
1568 cap::eraseSelection(*this);
1573 // If empty cell, and not part of a big cell
1574 if (lastpos() == 0 && inset().nargs() == 1) {
1576 // Directly delete empty cell: [|[]] => [|]
1582 // [|], can not delete from inside
1593 if (inMacroMode()) {
1594 InsetMathUnknown * p = activeMacro();
1595 if (p->name().size() > 1) {
1596 p->setName(p->name().substr(0, p->name().size() - 1));
1601 if (pos() != 0 && !force && prevAtom()->confirmDeletion()) {
1602 // let's require two backspaces for 'big stuff' and
1603 // highlight on the first
1615 bool Cursor::erase(bool const force)
1621 cap::eraseSelection(*this);
1625 // delete empty cells if possible
1626 if (pos() == lastpos() && inset().idxDelete(idx()))
1629 // special behaviour when in last position of cell
1630 if (pos() == lastpos()) {
1631 bool one_cell = inset().nargs() == 1;
1632 if (one_cell && lastpos() == 0) {
1634 // Directly delete empty cell: [|[]] => [|]
1640 // [|], can not delete from inside
1645 inset().idxGlue(idx());
1649 // 'clever' UI hack: only erase large items if previously slected
1650 if (pos() != lastpos() && !force && nextAtom()->confirmDeletion()) {
1665 DocIterator save = *this;
1666 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1667 this->dispatch(cmd);
1668 if (disp_.dispatched())
1678 DocIterator save = *this;
1679 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1680 this->dispatch(cmd);
1681 if (disp_.dispatched())
1688 void Cursor::handleNest(MathAtom const & a, int c)
1690 //lyxerr << "Cursor::handleNest: " << c << endl;
1692 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1695 pushBackward(*nextInset());
1699 void Cursor::handleNest(MathAtom const & a)
1701 handleNest(a, a.nucleus()->asNestInset()->firstIdx());
1705 int Cursor::targetX() const
1707 if (x_target() != -1)
1716 int Cursor::textTargetOffset() const
1718 return textTargetOffset_;
1722 void Cursor::setTargetX()
1731 bool Cursor::macroModeClose(bool cancel)
1735 InsetMathUnknown * p = activeMacro();
1737 MathData selection(buffer());
1738 asArray(p->selection(), selection);
1739 docstring const s = p->name();
1741 cell().erase(pos());
1743 // trigger updates of macros, at least, if no full
1744 // updates take place anyway
1745 screenUpdateFlags(Update::Force);
1747 // do nothing if the macro name is empty
1748 if (s == "\\" || cancel) {
1752 docstring const name = s.substr(1);
1753 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1754 if (in && in->interpretString(*this, s))
1756 bool const user_macro = buffer()->getMacro(name, *this, false);
1757 MathAtom atom = user_macro ? MathAtom(new InsetMathMacro(buffer(), name))
1758 : createInsetMath(name, buffer());
1760 // try to put argument into macro, if we just inserted a macro
1761 bool macroArg = false;
1762 InsetMathMacro * atomAsMacro = atom.nucleus()->asMacro();
1763 InsetMathNest * atomAsNest = atom.nucleus()->asNestInset();
1765 // macros here are still unfolded (in init mode in fact). So
1766 // we have to resolve the macro here manually and check its arity
1767 // to put the selection behind it if arity > 0.
1768 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1769 if (!selection.empty() && data && data->numargs() - data->optionals() > 0) {
1771 atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1773 // non-greedy case. Do not touch the arguments behind
1774 atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1777 // insert remembered selection into first argument of a non-macro
1778 else if (atomAsNest && atomAsNest->nargs() > 0)
1779 atomAsNest->cell(atomAsNest->firstIdx()).append(selection);
1781 MathWordList const & words = mathedWordList();
1782 MathWordList::const_iterator it = words.find(name);
1783 bool keep_mathmode = user_macro
1784 || (it != words.end() && (it->second.inset == "font"
1785 || it->second.inset == "oldfont"
1786 || it->second.inset == "mbox"));
1787 bool ert_macro = !user_macro && it == words.end() && atomAsMacro;
1789 if (in && in->currentMode() == Inset::TEXT_MODE
1790 && atom.nucleus()->currentMode() == Inset::MATH_MODE
1791 && name != from_ascii("ensuremath") && !ert_macro) {
1792 MathAtom at(new InsetMathEnsureMath(buffer()));
1793 at.nucleus()->cell(0).push_back(atom);
1796 } else if (in && in->currentMode() == Inset::MATH_MODE
1797 && atom.nucleus()->currentMode() == Inset::TEXT_MODE
1798 && !keep_mathmode) {
1799 MathAtom at = createInsetMath("text", buffer());
1800 at.nucleus()->cell(0).push_back(atom);
1806 // finally put the macro argument behind, if needed
1808 if (selection.size() > 1 || selection[0]->asScriptInset())
1809 plainInsert(MathAtom(new InsetMathBrace(selection)));
1818 bool Cursor::inMacroMode() const
1822 if (pos() == 0 || cell().empty())
1824 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1825 return p && !p->final();
1829 InsetMathUnknown * Cursor::activeMacro()
1831 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1835 InsetMathUnknown const * Cursor::activeMacro() const
1837 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1841 docstring Cursor::macroName()
1843 return inMacroMode() ? activeMacro()->name() : docstring();
1847 void Cursor::pullArg()
1850 MathData ar = cell();
1851 if (popBackward() && inMathed()) {
1853 cell().insert(pos(), ar);
1856 //formula()->mutateToText();
1861 void Cursor::normalize()
1863 if (idx() > lastidx()) {
1864 lyxerr << "this should not really happen - 1: "
1865 << idx() << ' ' << nargs()
1866 << " in: " << &inset() << endl;
1870 if (pos() > lastpos()) {
1871 lyxerr << "this should not really happen - 2: "
1872 << pos() << ' ' << lastpos() << " in idx: " << idx()
1874 odocstringstream os;
1875 otexrowstream ots(os);
1876 WriteStream wi(ots, false, true, WriteStream::wsDefault);
1877 inset().asInsetMath()->write(wi);
1878 lyxerr << to_utf8(os.str()) << endl;
1884 bool Cursor::upDownInMath(bool up)
1886 // Be warned: The 'logic' implemented in this function is highly
1887 // fragile. A distance of one pixel or a '<' vs '<=' _really
1888 // matters. So fiddle around with it only if you think you know
1889 // what you are doing!
1893 xo = beforeDispatchPosX_;
1895 // check if we had something else in mind, if not, this is the future
1897 if (x_target_ == -1)
1899 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1900 // In text mode inside the line (not left or right) possibly set a new target_x,
1901 // but only if we are somewhere else than the previous target-offset.
1903 // We want to keep the x-target on subsequent up/down movements
1904 // that cross beyond the end of short lines. Thus a special
1905 // handling when the cursor is at the end of line: Use the new
1906 // x-target only if the old one was before the end of line
1907 // or the old one was after the beginning of the line
1908 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
1912 left = pos() == textRow().endpos();
1913 right = pos() == textRow().pos();
1915 left = pos() == textRow().pos();
1916 right = pos() == textRow().endpos();
1918 if ((!left && !right) ||
1919 (left && !right && xo < x_target_) ||
1920 (!left && right && x_target_ < xo))
1927 // try neigbouring script insets
1929 if (inMathed() && !selection()) {
1932 InsetMathScript const * p = prevAtom()->asScriptInset();
1933 if (p && p->has(up)) {
1935 push(*const_cast<InsetMathScript*>(p));
1936 idx() = p->idxOfScript(up);
1939 // we went in the right direction? Otherwise don't jump into the script
1943 int oy = beforeDispatchPosY_;
1944 if ((!up && y <= oy) ||
1953 if (pos() != lastpos()) {
1954 InsetMathScript const * p = nextAtom()->asScriptInset();
1955 if (p && p->has(up)) {
1956 push(*const_cast<InsetMathScript*>(p));
1957 idx() = p->idxOfScript(up);
1960 // we went in the right direction? Otherwise don't jump into the script
1964 int oy = beforeDispatchPosY_;
1965 if ((!up && y <= oy) ||
1974 // try to find an inset that knows better then we,
1975 if (inset().idxUpDown(*this, up)) {
1976 //lyxerr << "idxUpDown triggered" << endl;
1977 // try to find best position within this inset
1979 setCursor(bruteFind(*this, xo, yo));
1983 // any improvement going just out of inset?
1984 if (popBackward() && inMathed()) {
1985 //lyxerr << "updown: popBackward succeeded" << endl;
1988 int yold = beforeDispatchPosY_;
1990 if (up ? ynew < yold : ynew > yold)
1994 // no success, we are probably at the document top or bottom
2000 bool Cursor::mathForward(bool word)
2002 LASSERT(inMathed(), return false);
2003 if (pos() < lastpos()) {
2005 // word: skip a group of insets of the form X*(B*|R*|P*) (greedy
2006 // match) where X is any math class, B is mathbin, R is mathrel, and
2007 // P is mathpunct. Make sure that the following remains true:
2008 // mathForward(true); mathBackward(true); mathForward(true)
2009 // is the same as mathForward(true) and
2010 // mathBackward(true); mathForward(true); mathBackward(true)
2011 // is the same as mathBackward(true).
2012 MathClass mc = nextMath().mathClass();
2015 while (pos() < lastpos() && mc == nextMath().mathClass());
2016 if (pos() < lastpos() &&
2017 ((mc = nextMath().mathClass()) == MC_BIN ||
2018 mc == MC_REL || mc == MC_PUNCT))
2021 while (pos() < lastpos() && mc == nextMath().mathClass());
2022 } else if (openable(nextAtom())) {
2023 // single step: try to enter the next inset
2024 pushBackward(nextMath());
2025 inset().idxFirst(*this);
2030 if (inset().idxForward(*this))
2032 // try to pop forwards --- but don't pop out of math! leave that to
2034 int s = depth() - 2;
2035 if (s >= 0 && operator[](s).inset().asInsetMath())
2036 return popForward();
2041 bool Cursor::mathBackward(bool word)
2043 LASSERT(inMathed(), return false);
2046 // word: skip a group of insets. See the comment in mathForward.
2047 MathClass mc = prevMath().mathClass();
2050 while (pos() > 0 && mc == prevMath().mathClass());
2051 if (pos() > 0 && (mc == MC_BIN || mc == MC_REL || mc == MC_PUNCT)) {
2052 mc = prevMath().mathClass();
2055 while (pos() > 0 && mc == prevMath().mathClass());
2057 } else if (openable(prevAtom())) {
2058 // single step: try to enter the preceding inset
2061 inset().idxLast(*this);
2066 if (inset().idxBackward(*this))
2068 // try to pop backwards --- but don't pop out of math! leave that to
2070 int s = depth() - 2;
2071 if (s >= 0 && operator[](s).inset().asInsetMath())
2072 return popBackward();
2077 bool Cursor::upDownInText(bool up, bool & updateNeeded)
2079 LASSERT(text(), return false);
2085 xo = beforeDispatchPosX_;
2087 // update the targetX - this is here before the "return false"
2088 // to set a new target which can be used by InsetTexts above
2089 // if we cannot move up/down inside this inset anymore
2090 if (x_target_ == -1)
2092 else if (xo - textTargetOffset() != x_target() &&
2093 depth() == beforeDispatchCursor_.depth()) {
2094 // In text mode inside the line (not left or right)
2095 // possibly set a new target_x, but only if we are
2096 // somewhere else than the previous target-offset.
2098 // We want to keep the x-target on subsequent up/down
2099 // movements that cross beyond the end of short lines.
2100 // Thus a special handling when the cursor is at the
2101 // end of line: Use the new x-target only if the old
2102 // one was before the end of line or the old one was
2103 // after the beginning of the line
2104 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
2108 left = pos() == textRow().endpos();
2109 right = pos() == textRow().pos();
2111 left = pos() == textRow().pos();
2112 right = pos() == textRow().endpos();
2114 if ((!left && !right) ||
2115 (left && !right && xo < x_target_) ||
2116 (!left && right && x_target_ < xo))
2123 // first get the current line
2124 TextMetrics & tm = bv_->textMetrics(text());
2125 ParagraphMetrics const & pm = tm.parMetrics(pit());
2127 if (pos() && boundary())
2128 row = pm.pos2row(pos() - 1);
2130 row = pm.pos2row(pos());
2132 if (atFirstOrLastRow(up)) {
2133 // Is there a place for the cursor to go ? If yes, we
2134 // can execute the DEPM, otherwise we should keep the
2135 // paragraph to host the cursor.
2136 Cursor dummy = *this;
2137 bool valid_destination = false;
2138 for(; dummy.depth(); dummy.pop())
2139 if (!dummy.atFirstOrLastRow(up)) {
2140 valid_destination = true;
2144 // will a next dispatch follow and if there is a new
2145 // dispatch will it move the cursor out ?
2146 if (depth() > 1 && valid_destination) {
2147 // The cursor hasn't changed yet. This happens when
2148 // you e.g. move out of an inset. And to give the
2149 // DEPM the possibility of doing something we must
2150 // provide it with two different cursors. (Lgb, vfr)
2152 dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
2153 dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
2155 updateNeeded |= bv().checkDepm(dummy, *this);
2156 updateTextTargetOffset();
2158 forceBufferUpdate();
2163 // with and without selection are handled differently
2165 int yo1 = bv().getPos(*this).y_;
2167 // To next/previous row
2168 // FIXME: the y position is often guessed wrongly across styles and
2169 // insets, which leads to weird behaviour.
2171 tm.editXY(*this, xo, yo1 - textRow().ascent() - 1);
2173 tm.editXY(*this, xo, yo1 + textRow().descent() + 1);
2174 x_target_ = old.x_target_;
2177 // This happens when you move out of an inset.
2178 // And to give the DEPM the possibility of doing
2179 // something we must provide it with two different
2181 Cursor dummy = *this;
2184 if (bv().checkDepm(dummy, old)) {
2185 updateNeeded = true;
2186 // Make sure that cur gets back whatever happened to dummy (Lgb)
2189 if (inTexted() && pos() && paragraph().isEnvSeparator(pos() - 1))
2192 // if there is a selection, we stay out of any inset,
2193 // and just jump to the right position:
2199 } else if (pit() > 0) {
2201 TextMetrics & tm2 = bv_->textMetrics(text());
2202 if (!tm2.contains(pit()))
2203 tm2.newParMetricsUp();
2204 ParagraphMetrics const & pmcur = tm2.parMetrics(pit());
2205 next_row = pmcur.rows().size() - 1;
2208 if (row + 1 < int(pm.rows().size())) {
2210 } else if (pit() + 1 < int(text()->paragraphs().size())) {
2212 TextMetrics & tm2 = bv_->textMetrics(text());
2213 if (!tm2.contains(pit()))
2214 tm2.newParMetricsDown();
2219 Row const & real_next_row = tm.parMetrics(pit()).rows()[next_row];
2221 top().pos() = tm.getPosNearX(real_next_row, xo, bound);
2223 // When selection==false, this is done by TextMetrics::editXY
2226 updateNeeded |= bv().checkDepm(*this, old);
2230 forceBufferUpdate();
2231 updateTextTargetOffset();
2236 void Cursor::handleFont(string const & font)
2238 LYXERR(Debug::DEBUG, font);
2242 safe = cap::grabAndEraseSelection(*this);
2247 if (lastpos() != 0) {
2248 // something left in the cell
2250 // cursor in first position
2252 } else if (pos() == lastpos()) {
2253 // cursor in last position
2256 // cursor in between. split cell
2257 MathData::iterator bt = cell().begin();
2258 MathAtom at = createInsetMath(from_utf8(font), buffer());
2259 at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
2260 cell().erase(bt, bt + pos());
2265 // nothing left in the cell
2274 void Cursor::undispatched() const
2276 disp_.dispatched(false);
2280 void Cursor::dispatched() const
2282 disp_.dispatched(true);
2286 void Cursor::screenUpdateFlags(Update::flags f) const
2288 disp_.screenUpdate(f);
2292 void Cursor::noScreenUpdate() const
2294 disp_.screenUpdate(Update::None);
2298 void Cursor::forceBufferUpdate() const
2300 disp_.forceBufferUpdate();
2304 void Cursor::clearBufferUpdate() const
2306 disp_.clearBufferUpdate();
2310 bool Cursor::needBufferUpdate() const
2312 return disp_.needBufferUpdate();
2316 Font Cursor::getFont() const
2318 // The logic here should more or less match to the
2319 // Cursor::setCurrentFont logic, i.e. the cursor height should
2320 // give a hint what will happen if a character is entered.
2321 // FIXME: this is not the case, what about removing this method ? (see #10478).
2323 // HACK. far from being perfect...
2325 CursorSlice const & sl = innerTextSlice();
2326 Text const & text = *sl.text();
2327 Paragraph const & par = text.getPar(sl.pit());
2329 // on boundary, so we are really at the character before
2330 pos_type pos = sl.pos();
2331 if (pos > 0 && boundary())
2334 // on space? Take the font before (only for RTL boundary stay)
2336 TextMetrics const & tm = bv().textMetrics(&text);
2337 if (pos == sl.lastpos()
2338 || (par.isSeparator(pos)
2339 && !tm.isRTLBoundary(sl.pit(), pos)))
2343 // get font at the position
2344 Font font = par.getFont(buffer()->params(), pos,
2345 text.outerFont(sl.pit()));
2351 void Cursor::sanitize()
2353 setBuffer(&bv_->buffer());
2354 CursorData::sanitize();
2358 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2360 // find inset in common
2362 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2363 if (&old[i].inset() != &cur[i].inset())
2367 // update words if we just moved to another paragraph
2368 if (i == old.depth() && i == cur.depth()
2369 && !cur.buffer()->isClean()
2370 && cur.inTexted() && old.inTexted()
2371 && cur.pit() != old.pit()) {
2372 old.paragraph().updateWords();
2375 // notify everything on top of the common part in old cursor,
2376 // but stop if the inset claims the cursor to be invalid now
2377 for (size_type j = i; j < old.depth(); ++j) {
2378 Cursor inset_pos = old;
2379 inset_pos.cutOff(j);
2380 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2384 // notify everything on top of the common part in new cursor,
2385 // but stop if the inset claims the cursor to be invalid now
2386 for (; i < cur.depth(); ++i) {
2387 if (cur[i].inset().notifyCursorEnters(cur))
2395 void Cursor::setCurrentFont()
2397 CursorSlice const & cs = innerTextSlice();
2398 Paragraph const & par = cs.paragraph();
2399 pos_type cpit = cs.pit();
2400 pos_type cpos = cs.pos();
2401 Text const & ctext = *cs.text();
2402 TextMetrics const & tm = bv().textMetrics(&ctext);
2404 // are we behind previous char in fact? -> go to that char
2405 if (cpos > 0 && boundary())
2408 // find position to take the font from
2410 // paragraph end? -> font of last char
2411 if (cpos == lastpos())
2413 // on space? -> look at the words in front of space
2414 else if (cpos > 0 && par.isSeparator(cpos)) {
2415 // abc| def -> font of c
2416 // abc |[WERBEH], i.e. boundary==true -> font of c
2417 // abc [WERBEH]| def, font of the space
2418 if (!tm.isRTLBoundary(cpit, cpos))
2424 BufferParams const & bufparams = buffer()->params();
2425 current_font = par.getFontSettings(bufparams, cpos);
2426 real_current_font = tm.displayFont(cpit, cpos);
2428 // special case for paragraph end
2429 if (cs.pos() == lastpos()
2430 && tm.isRTLBoundary(cpit, cs.pos())
2432 Language const * lang = par.getParLanguage(bufparams);
2433 current_font.setLanguage(lang);
2434 current_font.fontInfo().setNumber(FONT_OFF);
2435 real_current_font.setLanguage(lang);
2436 real_current_font.fontInfo().setNumber(FONT_OFF);
2441 void Cursor::checkBufferStructure()
2443 Buffer const * master = buffer()->masterBuffer();
2444 master->tocBackend().updateItem(*this);
2445 if (master != buffer() && !master->hasGuiDelegate())
2446 // In case the master has no gui associated with it,
2447 // the TocItem is not updated (part of bug 5699).
2448 buffer()->tocBackend().updateItem(*this);
2450 // If the last tracked change of the paragraph has just been
2451 // deleted, then we need to recompute the buffer flag
2452 // tracked_changes_present_.
2453 if (inTexted() && paragraph().isChangeUpdateRequired())
2454 disp_.forceChangesUpdate();
2458 void Cursor::moveToClosestEdge(int const x, bool const edit)
2460 if (Inset const * inset = nextInset()) {
2461 // stay in front of insets for which we want to open the dialog
2462 // (e.g. InsetMathSpace).
2463 if (edit && (inset->hasSettings() || !inset->contextMenuName().empty()))
2465 CoordCache::Insets const & insetCache = bv().coordCache().getInsets();
2466 if (!insetCache.has(inset))
2468 int const wid = insetCache.dim(inset).wid;
2469 Point p = insetCache.xy(inset);
2470 if (x > p.x_ + (wid + 1) / 2)