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)
333 if (cur->inset().getLayout().parbreakIgnored())
337 // only add blank line if we're not in a ParbreakIsNewline situation
338 if (!cur->inset().getLayout().parbreakIsNewline()
339 && !cur->paragraph().layout().parbreak_is_newline)
347 docstring CursorData::selectionAsString(bool with_label) const
353 return cap::grabSelection(*this);
355 int const label = with_label
356 ? AS_STR_LABEL | AS_STR_INSETS : AS_STR_INSETS;
358 idx_type const startidx = selBegin().idx();
359 idx_type const endidx = selEnd().idx();
360 if (startidx != endidx) {
361 // multicell selection
362 InsetTabular * table = inset().asInsetTabular();
363 LASSERT(table, return docstring());
364 return table->asString(startidx, endidx);
367 ParagraphList const & pars = text()->paragraphs();
369 pit_type const startpit = selBegin().pit();
370 pit_type const endpit = selEnd().pit();
371 size_t const startpos = selBegin().pos();
372 size_t const endpos = selEnd().pos();
374 if (startpit == endpit)
375 return pars[startpit].asString(startpos, endpos, label);
377 // First paragraph in selection
378 docstring result = pars[startpit].
379 asString(startpos, pars[startpit].size(), label)
382 // The paragraphs in between (if any)
383 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
384 Paragraph const & par = pars[pit];
385 result += par.asString(0, par.size(), label)
389 // Last paragraph in selection
390 result += pars[endpit].asString(0, endpos, label);
396 void CursorData::info(odocstream & os, bool devel_mode) const
398 for (int i = 1, n = depth(); i < n; ++i) {
399 operator[](i).inset().infoize(os);
403 Inset const * inset = prevInset();
404 // prevInset() can return 0 in certain case.
406 prevInset()->infoize2(os);
409 InsetMath * math = inset().asInsetMath();
411 os << _(", Inset: ") << math->id();
412 os << _(", Cell: ") << idx();
413 os << _(", Position: ") << pos();
418 docstring CursorData::currentState(bool devel_mode) const
422 info(os, devel_mode);
427 return text()->currentState(*this, devel_mode);
433 void CursorData::markNewWordPosition()
435 if (lyxrc.spellcheck_continuously && inTexted() && new_word_.empty()) {
436 FontSpan nw = locateWord(WHOLE_WORD);
437 if (nw.size() == 1) {
438 LYXERR(Debug::DEBUG, "start new word: "
440 << " pos: " << nw.first);
447 void CursorData::clearNewWordPosition()
449 if (!new_word_.empty()) {
450 LYXERR(Debug::DEBUG, "clear new word: "
452 << " pos: " << pos());
458 void CursorData::checkNewWordPosition()
460 if (!lyxrc.spellcheck_continuously || new_word_.empty())
462 // forget the position of the current new word if
463 // 1) or the remembered position was "broken"
464 // 2) or the count of nested insets changed
465 // 3) the top-level inset is not the same anymore
466 // 4) the cell index changed
467 // 5) or the paragraph changed
468 // 6) or the cursor pos is out of paragraph bound
469 if (new_word_.fixIfBroken()
470 || depth() != new_word_.depth()
471 || &inset() != &new_word_.inset()
472 || pit() != new_word_.pit()
473 || idx() != new_word_.idx()
474 || new_word_.pos() > new_word_.lastpos())
475 clearNewWordPosition();
477 FontSpan nw = locateWord(WHOLE_WORD);
479 FontSpan ow = new_word_.locateWord(WHOLE_WORD);
480 if (nw.intersect(ow).empty())
481 clearNewWordPosition();
483 LYXERR(Debug::DEBUG, "new word: "
485 << " pos: " << nw.first << ".." << nw.last);
487 clearNewWordPosition();
492 void CursorData::clearSelection()
495 setWordSelection(false);
501 int CursorData::countInsetsInSelection(InsetCode const & inset_code)
506 DocIterator from, to;
507 from = selectionBegin();
512 if (!from.nextInset()) //move to closest inset
515 while (!from.empty() && from < to) {
516 Inset * inset = from.nextInset();
519 if (inset->lyxCode() == inset_code)
527 bool CursorData::insetInSelection(InsetCode const & inset_code)
532 DocIterator from, to;
533 from = selectionBegin();
536 if (!from.nextInset()) //move to closest inset
539 while (!from.empty() && from < to) {
540 Inset * inset = from.nextInset();
543 if (inset->lyxCode() == inset_code)
551 bool CursorData::fixIfBroken()
553 bool const broken_cursor = DocIterator::fixIfBroken();
554 bool const broken_anchor = anchor_.fixIfBroken();
556 if (broken_cursor || broken_anchor) {
557 clearNewWordPosition();
565 void CursorData::sanitize()
567 DocIterator::sanitize();
568 new_word_.sanitize();
576 bool CursorData::undoAction()
578 if (!buffer()->undo().undoAction(*this))
585 bool CursorData::redoAction()
587 if (!buffer()->undo().redoAction(*this))
594 void CursorData::finishUndo() const
596 buffer()->undo().finishUndo();
600 void CursorData::beginUndoGroup() const
602 buffer()->undo().beginUndoGroup(*this);
606 void CursorData::endUndoGroup() const
608 buffer()->undo().endUndoGroup(*this);
612 void CursorData::recordUndo(pit_type from, pit_type to) const
614 buffer()->undo().recordUndo(*this, from, to);
618 void CursorData::recordUndo(pit_type from) const
620 buffer()->undo().recordUndo(*this, from, pit());
624 void CursorData::recordUndo(UndoKind kind) const
626 buffer()->undo().recordUndo(*this, kind);
630 void CursorData::recordUndoInset(Inset const * in) const
632 buffer()->undo().recordUndoInset(*this, in);
636 void CursorData::recordUndoFullBuffer() const
638 buffer()->undo().recordUndoFullBuffer(*this);
642 void CursorData::recordUndoBufferParams() const
644 buffer()->undo().recordUndoBufferParams(*this);
648 void CursorData::recordUndoSelection() const
651 if (cap::multipleCellsSelected(*this))
656 buffer()->undo().recordUndo(*this,
657 selBegin().pit(), selEnd().pit());
662 int CursorData::currentMode()
664 LASSERT(!empty(), return Inset::UNDECIDED_MODE);
665 for (int i = depth() - 1; i >= 0; --i) {
666 int res = operator[](i).inset().currentMode();
667 bool locked_mode = operator[](i).inset().lockedMode();
668 // Also return UNDECIDED_MODE when the mode is locked,
669 // as in this case it is treated the same as TEXT_MODE
670 if (res != Inset::UNDECIDED_MODE || locked_mode)
673 return Inset::TEXT_MODE;
677 bool CursorData::confirmDeletion(bool const before) const
680 if (Inset const * inset = before ? prevInset() : nextInset())
681 return inset->confirmDeletion();
683 DocIterator dit = selectionBegin();
684 CursorSlice const end = selectionEnd().top();
685 for (; dit.top() < end; dit.top().forwardPos())
686 if (Inset const * inset = dit.nextInset())
687 if (inset->confirmDeletion())
700 // be careful: this is called from the bv's constructor, too, so
701 // bv functions are not yet available!
702 Cursor::Cursor(BufferView & bv)
703 : CursorData(&bv.buffer()), bv_(&bv),
704 x_target_(-1), textTargetOffset_(0),
705 beforeDispatchPosX_(0), beforeDispatchPosY_(0)
716 void Cursor::setCursorData(CursorData const & data)
718 CursorData::operator=(data);
722 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
726 // Try to fix cursor in case it is broken.
729 // Is this a function that acts on inset at point?
730 Inset * inset = cur.nextInset();
731 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
732 && inset && inset->getStatus(cur, cmd, status))
735 // This is, of course, a mess. Better create a new doc iterator and use
736 // this in Inset::getStatus. This might require an additional
737 // BufferView * arg, though (which should be avoided)
738 //Cursor safe = *this;
740 for ( ; cur.depth(); cur.pop()) {
741 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
742 // LASSERT: Is it safe to continue here, or should we return?
743 LASSERT(cur.idx() <= cur.lastidx(), /**/);
744 LASSERT(cur.pit() <= cur.lastpit(), /**/);
745 LASSERT(cur.pos() <= cur.lastpos(), /**/);
747 // The inset's getStatus() will return 'true' if it made
748 // a definitive decision on whether it want to handle the
749 // request or not. The result of this decision is put into
750 // the 'status' parameter.
751 if (cur.inset().getStatus(cur, cmd, status)) {
760 void Cursor::saveBeforeDispatchPosXY()
762 getPos(beforeDispatchPosX_, beforeDispatchPosY_);
766 void Cursor::dispatch(FuncRequest const & cmd0)
768 LYXERR(Debug::ACTION, "Cursor::dispatch: cmd: " << cmd0 << '\n' << *this);
773 FuncRequest cmd = cmd0;
776 disp_ = DispatchResult();
780 // Is this a function that acts on inset at point?
781 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
783 disp_.dispatched(true);
784 disp_.screenUpdate(Update::FitCursor | Update::Force);
785 FuncRequest tmpcmd = cmd;
786 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
787 << cmd0 << endl << *this);
788 nextInset()->dispatch(*this, tmpcmd);
789 if (disp_.dispatched()) {
795 // store some values to be used inside of the handlers
796 beforeDispatchCursor_ = *this;
797 for (; depth(); pop(), boundary(false)) {
798 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
799 << cmd0 << endl << *this);
801 // In any of these cases, the cursor is invalid, and we should
802 // try to save this document rather than crash.
803 LBUFERR(pos() <= lastpos());
804 LBUFERR(idx() <= lastidx());
805 LBUFERR(pit() <= lastpit());
807 // The common case is 'LFUN handled, need update', so make the
808 // LFUN handler's life easier by assuming this as default value.
809 // The handler can reset the update and val flags if necessary.
810 disp_.screenUpdate(Update::FitCursor | Update::Force);
811 disp_.dispatched(true);
812 inset().dispatch(*this, cmd);
813 if (disp_.dispatched())
817 // it completely to get a 'bomb early' behaviour in case this
818 // object will be used again.
819 if (!disp_.dispatched()) {
820 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
821 // We might have invalidated the cursor when removing an empty
822 // paragraph while the cursor could not be moved out the inset
823 // while we initially thought we could. This might happen when
824 // a multiline inset becomes an inline inset when the second
825 // paragraph is removed.
826 if (safe.pit() > safe.lastpit()) {
827 safe.pit() = safe.lastpit();
828 safe.pos() = safe.lastpos();
831 disp_.screenUpdate(Update::None);
832 disp_.dispatched(false);
834 // restore the previous one because nested Cursor::dispatch calls
835 // are possible which would change it
836 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
840 // NOTE: The code below has been copied to BufferView::dispatch.
841 // If you need to modify this, please update the other one too.
843 // notify insets we just left
845 old.beginUndoGroup();
847 bool badcursor = notifyCursorLeavesOrEnters(old, *this);
850 bv().resetInlineCompletionPos();
857 DispatchResult const & Cursor::result() const
863 void Cursor::message(docstring const & msg) const
865 disp_.setMessage(msg);
869 void Cursor::errorMessage(docstring const & msg) const
871 disp_.setMessage(msg);
872 disp_.setError(true);
876 BufferView & Cursor::bv() const
885 LBUFERR(depth() >= 1);
890 void Cursor::push(Inset & p)
892 push_back(CursorSlice(p));
893 p.setBuffer(*buffer());
897 void Cursor::pushBackward(Inset & p)
899 LASSERT(!empty(), return);
900 //lyxerr << "Entering inset " << t << " front" << endl;
906 void Cursor::editInsertedInset()
908 LASSERT(!empty(), return);
912 InsetMath &p = prevMath();
919 // this could be a while() loop, but only one cell is not empty in
920 // cases we are interested in. The cell is not empty because we
921 // have inserted the selection in there.
922 if (!cell().empty()) {
923 // if it is not empty, move to the next one.
924 if (!inset().idxNext(*this))
925 // If there is no next one, exit the inset.
931 bool Cursor::popBackward()
933 LASSERT(!empty(), return false);
941 bool Cursor::popForward()
943 LASSERT(!empty(), return false);
944 //lyxerr << "Leaving inset from in back" << endl;
945 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
949 pos() += lastpos() - lp + 1;
954 void Cursor::getPos(int & x, int & y) const
956 Point p = bv().getPos(*this);
962 Row const & Cursor::textRow() const
964 CursorSlice const & cs = innerTextSlice();
965 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
966 return pm.getRow(pos(), boundary());
970 bool Cursor::posVisRight(bool skip_inset)
972 Cursor new_cur = *this; // where we will move to
973 pos_type left_pos; // position visually left of current cursor
974 pos_type right_pos; // position visually right of current cursor
976 getSurroundingPos(left_pos, right_pos);
978 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
980 // Are we at an inset?
981 new_cur.pos() = right_pos;
982 new_cur.boundary(false);
984 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
985 // we actually move the cursor at the end of this
986 // function, for now we just keep track of the new
987 // position in new_cur...
988 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
991 // Are we already at rightmost pos in row?
992 else if (text()->empty() || right_pos == -1) {
995 if (!new_cur.posVisToNewRow(false)) {
996 LYXERR(Debug::RTL, "not moving!");
1000 // we actually move the cursor at the end of this
1001 // function, for now just keep track of the new
1002 // position in new_cur...
1003 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
1004 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
1007 // normal movement to the right
1010 // Recall, if the cursor is at position 'x', that
1011 // means *before* the character at position 'x'. In
1012 // RTL, "before" means "to the right of", in LTR, "to
1013 // the left of". So currently our situation is this:
1014 // the position to our right is 'right_pos' (i.e.,
1015 // we're currently to the left of 'right_pos'). In
1016 // order to move to the right, it depends whether or
1017 // not the character at 'right_pos' is RTL.
1018 bool const new_pos_is_RTL = paragraph().getFontSettings(
1019 buffer()->params(), right_pos).isVisibleRightToLeft();
1020 // If the character at 'right_pos' *is* LTR, then in
1021 // order to move to the right of it, we need to be
1022 // *after* 'right_pos', i.e., move to position
1024 if (!new_pos_is_RTL) {
1025 new_cur.pos() = right_pos + 1;
1026 // set the boundary to true in two situations:
1028 // 1. if new_pos is now lastpos, and we're in
1029 // an RTL paragraph (this means that we're
1030 // moving right to the end of an LTR chunk
1031 // which is at the end of an RTL paragraph);
1032 (new_cur.pos() == lastpos()
1033 && paragraph().isRTL(buffer()->params()))
1034 // 2. if the position *after* right_pos is RTL
1035 // (we want to be *after* right_pos, not
1036 // before right_pos + 1!)
1037 || paragraph().getFontSettings(buffer()->params(),
1038 new_cur.pos()).isVisibleRightToLeft()
1040 new_cur.boundary(true);
1041 else // set the boundary to false
1042 new_cur.boundary(false);
1044 // Otherwise (if the character at position 'right_pos'
1045 // is RTL), then moving to the right of it is as easy
1046 // as setting the new position to 'right_pos'.
1048 new_cur.pos() = right_pos;
1049 new_cur.boundary(false);
1054 bool const moved = new_cur != *this || new_cur.boundary() != boundary();
1057 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
1058 << (new_cur.boundary() ? " (boundary)" : ""));
1066 bool Cursor::posVisLeft(bool skip_inset)
1068 Cursor new_cur = *this; // where we will move to
1069 pos_type left_pos; // position visually left of current cursor
1070 pos_type right_pos; // position visually right of current cursor
1072 getSurroundingPos(left_pos, right_pos);
1074 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
1076 // Are we at an inset?
1077 new_cur.pos() = left_pos;
1078 new_cur.boundary(false);
1080 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
1081 // we actually move the cursor at the end of this
1082 // function, for now we just keep track of the new
1083 // position in new_cur...
1084 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
1087 // Are we already at leftmost pos in row?
1088 else if (text()->empty() || left_pos == -1) {
1091 if (!new_cur.posVisToNewRow(true)) {
1092 LYXERR(Debug::RTL, "not moving!");
1096 // we actually move the cursor at the end of this
1097 // function, for now just keep track of the new
1098 // position in new_cur...
1099 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
1100 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
1103 // normal movement to the left
1106 // Recall, if the cursor is at position 'x', that
1107 // means *before* the character at position 'x'. In
1108 // RTL, "before" means "to the right of", in LTR, "to
1109 // the left of". So currently our situation is this:
1110 // the position to our left is 'left_pos' (i.e., we're
1111 // currently to the right of 'left_pos'). In order to
1112 // move to the left, it depends whether or not the
1113 // character at 'left_pos' is RTL.
1114 bool const new_pos_is_RTL = paragraph().getFontSettings(
1115 buffer()->params(), left_pos).isVisibleRightToLeft();
1116 // If the character at 'left_pos' *is* RTL, then in
1117 // order to move to the left of it, we need to be
1118 // *after* 'left_pos', i.e., move to position
1120 if (new_pos_is_RTL) {
1121 new_cur.pos() = left_pos + 1;
1122 // set the boundary to true in two situations:
1124 // 1. if new_pos is now lastpos and we're in
1125 // an LTR paragraph (this means that we're
1126 // moving left to the end of an RTL chunk
1127 // which is at the end of an LTR paragraph);
1128 (new_cur.pos() == lastpos()
1129 && !paragraph().isRTL(buffer()->params()))
1130 // 2. if the position *after* left_pos is not
1131 // RTL (we want to be *after* left_pos, not
1132 // before left_pos + 1!)
1133 || !paragraph().getFontSettings(buffer()->params(),
1134 new_cur.pos()).isVisibleRightToLeft()
1136 new_cur.boundary(true);
1137 else // set the boundary to false
1138 new_cur.boundary(false);
1140 // Otherwise (if the character at position 'left_pos'
1141 // is LTR), then moving to the left of it is as easy
1142 // as setting the new position to 'left_pos'.
1144 new_cur.pos() = left_pos;
1145 new_cur.boundary(false);
1150 bool const moved = new_cur != *this || new_cur.boundary() != boundary();
1153 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
1154 << (new_cur.boundary() ? " (boundary)" : ""));
1164 // Return true on success
1165 bool findNonVirtual(Row const & row, Row::const_iterator & cit, bool onleft)
1168 while (cit != row.begin() && cit->isVirtual())
1171 while (cit != row.end() && cit->isVirtual())
1174 return cit != row.end() && !cit->isVirtual();
1179 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos) const
1181 // by default, we know nothing.
1185 Row const & row = textRow();
1187 Row::const_iterator cit = row.findElement(pos(), boundary(), dummy);
1188 // Handle the case of empty row
1189 if (cit == row.end()) {
1191 right_pos = row.pos();
1193 left_pos = row.pos() - 1;
1197 // skip virtual elements and exit if no non-virtual one exists
1198 if (!findNonVirtual(row, cit, !cit->isRTL()))
1201 // if the position is at the left side of the element, we have to
1202 // look at the previous element
1203 if (pos() == cit->left_pos()) {
1204 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1205 << "), AT LEFT of *cit=" << *cit);
1206 // this one is easy (see common case below)
1207 right_pos = pos() - (cit->isRTL() ? 1 : 0);
1208 // at the left of the row
1209 if (cit == row.begin())
1212 if (!findNonVirtual(row, cit, true))
1214 // [...[ is the row element, | is cursor position (! with boundary)
1215 // [ 1 2 [ is a ltr row element with pos=1 and endpos=3
1216 // ] 2 1] is an rtl row element with pos=1 and endpos=3
1217 // [ 1 2 [ [|3 4 [ => (2, 3)
1218 // or [ 1 2 [ ]!4 3 ] => (2, 4)
1219 // or ] 2 1 ] [|3 4 [ => (1, 3)
1220 // or ] 4 3 ] ]!2 1 ] => (3, 2)
1221 left_pos = cit->right_pos() - (cit->isRTL() ? 0 : 1);
1222 // happens with consecutive row of same direction
1223 if (left_pos == right_pos) {
1224 left_pos += cit->isRTL() ? 1 : -1;
1227 // same code but with the element at the right
1228 else if (pos() == cit->right_pos()) {
1229 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1230 << "), AT RIGHT of *cit=" << *cit);
1231 // this one is easy (see common case below)
1232 left_pos = pos() - (cit->isRTL() ? 0 : 1);
1233 // at the right of the row
1234 if (cit + 1 == row.end())
1237 if (!findNonVirtual(row, cit, false))
1239 // [ 1 2![ [ 3 4 [ => (2, 3)
1240 // or [ 1 2![ ] 4 3 ] => (2, 4)
1241 // or ] 2 1|] [ 3 4 [ => (1, 3)
1242 // or ] 4 3|] ] 2 1 ] => (3, 2)
1243 right_pos = cit->left_pos() - (cit->isRTL() ? 1 : 0);
1244 // happens with consecutive row of same direction
1245 if (right_pos == left_pos)
1246 right_pos += cit->isRTL() ? -1 : 1;
1248 // common case: both positions are inside the row element
1250 // [ 1 2|3 [ => (2, 3)
1251 // or ] 3|2 1 ] => (3, 2)
1252 left_pos = pos() - (cit->isRTL() ? 0 : 1);
1253 right_pos = pos() - (cit->isRTL() ? 1 : 0);
1256 // Note that debug message does not catch all early returns above
1257 LYXERR(Debug::RTL,"getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1258 << ") => (" << left_pos << ", " << right_pos <<")");
1262 bool Cursor::posVisToNewRow(bool movingLeft)
1264 Row const & row = textRow();
1265 bool par_is_LTR = !row.isRTL();
1267 // Inside a table, determining whether to move to the next or
1268 // previous row should be done based on the table's direction.
1269 if (inset().asInsetTabular()) {
1270 par_is_LTR = !inset().asInsetTabular()->isRightToLeft(*this);
1271 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
1274 // if moving left in an LTR paragraph or moving right in an
1275 // RTL one, move to previous row
1276 if (par_is_LTR == movingLeft) {
1277 if (row.pos() == 0) { // we're at first row in paragraph
1278 if (pit() == 0) // no previous paragraph! don't move
1280 // move to last pos in previous par
1284 } else { // move to previous row in this par
1285 pos() = row.pos() - 1; // this is guaranteed to be in previous row
1289 // if moving left in an RTL paragraph or moving right in an
1290 // LTR one, move to next row
1292 if (row.endpos() == lastpos()) { // we're at last row in paragraph
1293 if (pit() == lastpit()) // last paragraph! don't move
1295 // move to first row in next par
1299 } else { // move to next row in this par
1300 pos() = row.endpos();
1305 // make sure we're at left-/right-most pos in new row
1306 posVisToRowExtremity(!movingLeft);
1312 void Cursor::posVisToRowExtremity(bool left)
1314 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
1315 << (boundary() ? 1 : 0));
1317 TextMetrics const & tm = bv_->textMetrics(text());
1318 // Looking for extremities is like clicking on the left or the
1319 // right of the row.
1320 int x = tm.origin().x_ + (left ? 0 : textRow().width());
1322 pos() = tm.getPosNearX(textRow(), x, b);
1325 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
1326 << (boundary() ? 1 : 0));
1330 bool Cursor::reverseDirectionNeeded() const
1333 * We determine the directions based on the direction of the
1334 * bottom() --- i.e., outermost --- paragraph, because that is
1335 * the only way to achieve consistency of the arrow's movements
1336 * within a paragraph, and thus avoid situations in which the
1337 * cursor gets stuck.
1339 return bottom().paragraph().isRTL(bv().buffer().params());
1343 void Cursor::setTargetX(int x)
1346 textTargetOffset_ = 0;
1350 int Cursor::x_target() const
1356 void Cursor::clearTargetX()
1359 textTargetOffset_ = 0;
1363 void Cursor::updateTextTargetOffset()
1368 textTargetOffset_ = x - x_target_;
1372 bool Cursor::selHandle(bool sel)
1374 //lyxerr << "Cursor::selHandle" << endl;
1377 if (sel == selection())
1381 cap::saveSelection(*this);
1389 bool Cursor::atFirstOrLastRow(bool up)
1391 TextMetrics const & tm = bv_->textMetrics(text());
1392 ParagraphMetrics const & pm = tm.parMetrics(pit());
1395 if (pos() && boundary())
1396 row = pm.pos2row(pos() - 1);
1398 row = pm.pos2row(pos());
1401 if (pit() == 0 && row == 0)
1404 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1405 row + 1 >= int(pm.rows().size()))
1415 ///////////////////////////////////////////////////////////////////
1418 // The part below is the non-integrated rest of the original math
1419 // cursor. This should be either generalized for texted or moved
1420 // back to mathed (in most cases to InsetMathNest).
1422 ///////////////////////////////////////////////////////////////////
1424 #include "mathed/InsetMathChar.h"
1425 #include "mathed/InsetMathGrid.h"
1426 #include "mathed/InsetMathScript.h"
1427 #include "mathed/InsetMathUnknown.h"
1428 #include "mathed/MathFactory.h"
1429 #include "mathed/MathStream.h"
1430 #include "mathed/MathSupport.h"
1435 bool Cursor::openable(MathAtom const & t) const
1446 // we can't move into anything new during selection
1447 if (depth() >= realAnchor().depth())
1449 if (t.nucleus() != &realAnchor()[depth()].inset())
1456 void Cursor::plainErase()
1458 cell().erase(pos());
1462 void Cursor::plainInsert(MathAtom const & t)
1464 cell().insert(pos(), t);
1466 inset().setBuffer(bv_->buffer());
1468 checkBufferStructure();
1472 void Cursor::insert(char_type c)
1474 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1475 LASSERT(!empty(), return);
1477 cap::selClearOrDel(*this);
1478 insert(new InsetMathChar(c));
1480 text()->insertChar(*this, c);
1485 void Cursor::insert(docstring const & str)
1487 for (char_type c : str)
1492 void Cursor::insert(Inset * inset0)
1494 LASSERT(inset0, return);
1496 insert(MathAtom(inset0->asInsetMath()));
1498 text()->insertInset(*this, inset0);
1499 inset0->setBuffer(bv_->buffer());
1501 if (inset0->isLabeled())
1502 forceBufferUpdate();
1507 void Cursor::insert(MathAtom const & t)
1509 LATTEST(inMathed());
1510 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1512 cap::selClearOrDel(*this);
1517 void Cursor::insert(MathData const & ar)
1519 LATTEST(inMathed());
1522 cap::eraseSelection(*this);
1523 cell().insert(pos(), ar);
1525 // FIXME audit setBuffer calls
1526 inset().setBuffer(bv_->buffer());
1530 int Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1532 LATTEST(inMathed());
1533 MathData ar(buffer());
1535 if (ar.size() == 1 && (enter || selection()))
1543 void Cursor::niceInsert(MathAtom const & t)
1545 LATTEST(inMathed());
1547 docstring const safe = cap::grabAndEraseSelection(*this);
1549 // If possible, enter the new inset and move the contents of the selection
1550 if (t->isActive()) {
1551 idx_type const idx = prevMath().asNestInset()->firstIdx();
1552 MathData ar(buffer());
1554 prevMath().cell(idx).insert(0, ar);
1555 editInsertedInset();
1556 } else if (t->asMacro() && !safe.empty()) {
1557 MathData ar(buffer());
1559 docstring const name = t->asMacro()->name();
1560 MacroData const * data = buffer()->getMacro(name);
1561 if (data && data->numargs() - data->optionals() > 0) {
1562 plainInsert(MathAtom(new InsetMathBrace(ar)));
1569 bool Cursor::backspace(bool const force)
1572 cap::eraseSelection(*this);
1577 // If empty cell, and not part of a big cell
1578 if (lastpos() == 0 && inset().nargs() == 1) {
1580 // Directly delete empty cell: [|[]] => [|]
1586 // [|], can not delete from inside
1597 if (inMacroMode()) {
1598 InsetMathUnknown * p = activeMacro();
1599 if (p->name().size() > 1) {
1600 p->setName(p->name().substr(0, p->name().size() - 1));
1605 if (pos() != 0 && !force && prevAtom()->confirmDeletion()) {
1606 // let's require two backspaces for 'big stuff' and
1607 // highlight on the first
1619 bool Cursor::erase(bool const force)
1625 cap::eraseSelection(*this);
1629 // delete empty cells if possible
1630 if (pos() == lastpos() && inset().idxDelete(idx()))
1633 // special behaviour when in last position of cell
1634 if (pos() == lastpos()) {
1635 bool one_cell = inset().nargs() == 1;
1636 if (one_cell && lastpos() == 0) {
1638 // Directly delete empty cell: [|[]] => [|]
1644 // [|], can not delete from inside
1649 inset().idxGlue(idx());
1653 // 'clever' UI hack: only erase large items if previously slected
1654 if (pos() != lastpos() && !force && nextAtom()->confirmDeletion()) {
1669 DocIterator save = *this;
1670 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1671 this->dispatch(cmd);
1672 if (disp_.dispatched())
1682 DocIterator save = *this;
1683 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1684 this->dispatch(cmd);
1685 if (disp_.dispatched())
1692 void Cursor::handleNest(MathAtom const & a)
1694 idx_type const idx = a.nucleus()->asNestInset()->firstIdx();
1695 //lyxerr << "Cursor::handleNest: " << idx << endl;
1697 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(idx));
1699 editInsertedInset();
1703 int Cursor::targetX() const
1705 if (x_target() != -1)
1714 int Cursor::textTargetOffset() const
1716 return textTargetOffset_;
1720 void Cursor::setTargetX()
1729 bool Cursor::macroModeClose(bool cancel)
1733 InsetMathUnknown * p = activeMacro();
1735 MathData selection(buffer());
1736 asArray(p->selection(), selection);
1737 docstring const s = p->name();
1739 cell().erase(pos());
1741 // trigger updates of macros, at least, if no full
1742 // updates take place anyway
1743 screenUpdateFlags(Update::Force);
1745 // do nothing if the macro name is empty
1746 if (s == "\\" || cancel) {
1750 docstring const name = s.substr(1);
1751 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1752 if (in && in->interpretString(*this, s))
1754 bool const user_macro = buffer()->getMacro(name, *this, false);
1755 MathAtom atom = user_macro ? MathAtom(new InsetMathMacro(buffer(), name))
1756 : createInsetMath(name, buffer());
1758 // try to put argument into macro, if we just inserted a macro
1759 bool macroArg = false;
1760 InsetMathMacro * atomAsMacro = atom.nucleus()->asMacro();
1761 InsetMathNest * atomAsNest = atom.nucleus()->asNestInset();
1763 // macros here are still unfolded (in init mode in fact). So
1764 // we have to resolve the macro here manually and check its arity
1765 // to put the selection behind it if arity > 0.
1766 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1767 if (!selection.empty() && data && data->numargs()) {
1769 atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1771 // non-greedy case. Do not touch the arguments behind
1772 atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1775 // insert remembered selection into first argument of a non-macro
1776 else if (atomAsNest && atomAsNest->nargs() > 0)
1777 atomAsNest->cell(atomAsNest->firstIdx()).append(selection);
1779 MathWordList const & words = mathedWordList();
1780 MathWordList::const_iterator it = words.find(name);
1781 bool keep_mathmode = user_macro
1782 || (it != words.end() && (it->second.inset == "font"
1783 || it->second.inset == "oldfont"
1784 || it->second.inset == "mbox"));
1785 bool ert_macro = !user_macro && it == words.end() && atomAsMacro;
1787 if (in && in->currentMode() == Inset::TEXT_MODE
1788 && atom.nucleus()->currentMode() == Inset::MATH_MODE
1789 && name != from_ascii("ensuremath") && !ert_macro) {
1790 MathAtom at(new InsetMathEnsureMath(buffer()));
1791 at.nucleus()->cell(0).push_back(atom);
1794 } else if (in && in->currentMode() == Inset::MATH_MODE
1795 && atom.nucleus()->currentMode() == Inset::TEXT_MODE
1796 && !keep_mathmode) {
1797 MathAtom at = createInsetMath("text", buffer());
1798 at.nucleus()->cell(0).push_back(atom);
1804 // finally put the macro argument behind, if needed
1806 if (selection.size() > 1 || selection[0]->asScriptInset())
1807 plainInsert(MathAtom(new InsetMathBrace(selection)));
1816 bool Cursor::inMacroMode() const
1820 if (pos() == 0 || cell().empty())
1822 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1823 return p && !p->final();
1827 InsetMathUnknown * Cursor::activeMacro()
1829 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1833 InsetMathUnknown const * Cursor::activeMacro() const
1835 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1839 docstring Cursor::macroName()
1841 return inMacroMode() ? activeMacro()->name() : docstring();
1845 void Cursor::pullArg()
1848 MathData ar = cell();
1849 if (popBackward() && inMathed()) {
1851 cell().insert(pos(), ar);
1854 //formula()->mutateToText();
1859 void Cursor::normalize()
1861 if (idx() > lastidx()) {
1862 lyxerr << "this should not really happen - 1: "
1863 << idx() << ' ' << nargs()
1864 << " in: " << &inset() << endl;
1868 if (pos() > lastpos()) {
1869 lyxerr << "this should not really happen - 2: "
1870 << pos() << ' ' << lastpos() << " in idx: " << idx()
1872 odocstringstream os;
1873 otexrowstream ots(os);
1874 WriteStream wi(ots, false, true, WriteStream::wsDefault);
1875 inset().asInsetMath()->write(wi);
1876 lyxerr << to_utf8(os.str()) << endl;
1882 bool Cursor::upDownInMath(bool up)
1884 // Be warned: The 'logic' implemented in this function is highly
1885 // fragile. A distance of one pixel or a '<' vs '<=' _really
1886 // matters. So fiddle around with it only if you think you know
1887 // what you are doing!
1891 xo = beforeDispatchPosX_;
1893 // check if we had something else in mind, if not, this is the future
1895 if (x_target_ == -1)
1897 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1898 // In text mode inside the line (not left or right) possibly set a new target_x,
1899 // but only if we are somewhere else than the previous target-offset.
1901 // We want to keep the x-target on subsequent up/down movements
1902 // that cross beyond the end of short lines. Thus a special
1903 // handling when the cursor is at the end of line: Use the new
1904 // x-target only if the old one was before the end of line
1905 // or the old one was after the beginning of the line
1906 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
1910 left = pos() == textRow().endpos();
1911 right = pos() == textRow().pos();
1913 left = pos() == textRow().pos();
1914 right = pos() == textRow().endpos();
1916 if ((!left && !right) ||
1917 (left && !right && xo < x_target_) ||
1918 (!left && right && x_target_ < xo))
1925 // try neigbouring script insets
1927 if (inMathed() && !selection()) {
1930 InsetMathScript const * p = prevAtom()->asScriptInset();
1931 if (p && p->has(up)) {
1933 push(*const_cast<InsetMathScript*>(p));
1934 idx() = p->idxOfScript(up);
1937 // we went in the right direction? Otherwise don't jump into the script
1941 int oy = beforeDispatchPosY_;
1942 if ((!up && y <= oy) ||
1951 if (pos() != lastpos()) {
1952 InsetMathScript const * p = nextAtom()->asScriptInset();
1953 if (p && p->has(up)) {
1954 push(*const_cast<InsetMathScript*>(p));
1955 idx() = p->idxOfScript(up);
1958 // we went in the right direction? Otherwise don't jump into the script
1962 int oy = beforeDispatchPosY_;
1963 if ((!up && y <= oy) ||
1972 // try to find an inset that knows better then we,
1973 if (inset().idxUpDown(*this, up)) {
1974 //lyxerr << "idxUpDown triggered" << endl;
1975 // try to find best position within this inset
1977 setCursor(bruteFind(*this, xo, yo));
1981 // any improvement going just out of inset?
1982 if (popBackward() && inMathed()) {
1983 //lyxerr << "updown: popBackward succeeded" << endl;
1986 int yold = beforeDispatchPosY_;
1988 if (up ? ynew < yold : ynew > yold)
1992 // no success, we are probably at the document top or bottom
1998 bool Cursor::mathForward(bool word)
2000 LASSERT(inMathed(), return false);
2001 if (pos() < lastpos()) {
2003 // word: skip a group of insets of the form X*(B*|R*|P*) (greedy
2004 // match) where X is any math class, B is mathbin, R is mathrel, and
2005 // P is mathpunct. Make sure that the following remains true:
2006 // mathForward(true); mathBackward(true); mathForward(true)
2007 // is the same as mathForward(true) and
2008 // mathBackward(true); mathForward(true); mathBackward(true)
2009 // is the same as mathBackward(true).
2010 MathClass mc = nextMath().mathClass();
2013 while (pos() < lastpos() && mc == nextMath().mathClass());
2014 if (pos() < lastpos() &&
2015 ((mc = nextMath().mathClass()) == MC_BIN ||
2016 mc == MC_REL || mc == MC_PUNCT))
2019 while (pos() < lastpos() && mc == nextMath().mathClass());
2020 } else if (openable(nextAtom())) {
2021 // single step: try to enter the next inset
2022 pushBackward(nextMath());
2023 inset().idxFirst(*this);
2028 if (inset().idxForward(*this))
2030 // try to pop forwards --- but don't pop out of math! leave that to
2032 int s = depth() - 2;
2033 if (s >= 0 && operator[](s).inset().asInsetMath())
2034 return popForward();
2039 bool Cursor::mathBackward(bool word)
2041 LASSERT(inMathed(), return false);
2044 // word: skip a group of insets. See the comment in mathForward.
2045 MathClass mc = prevMath().mathClass();
2048 while (pos() > 0 && mc == prevMath().mathClass());
2049 if (pos() > 0 && (mc == MC_BIN || mc == MC_REL || mc == MC_PUNCT)) {
2050 mc = prevMath().mathClass();
2053 while (pos() > 0 && mc == prevMath().mathClass());
2055 } else if (openable(prevAtom())) {
2056 // single step: try to enter the preceding inset
2059 inset().idxLast(*this);
2064 if (inset().idxBackward(*this))
2066 // try to pop backwards --- but don't pop out of math! leave that to
2068 int s = depth() - 2;
2069 if (s >= 0 && operator[](s).inset().asInsetMath())
2070 return popBackward();
2075 bool Cursor::upDownInText(bool up, bool & updateNeeded)
2077 LASSERT(text(), return false);
2083 xo = beforeDispatchPosX_;
2085 // update the targetX - this is here before the "return false"
2086 // to set a new target which can be used by InsetTexts above
2087 // if we cannot move up/down inside this inset anymore
2088 if (x_target_ == -1)
2090 else if (xo - textTargetOffset() != x_target() &&
2091 depth() == beforeDispatchCursor_.depth()) {
2092 // In text mode inside the line (not left or right)
2093 // possibly set a new target_x, but only if we are
2094 // somewhere else than the previous target-offset.
2096 // We want to keep the x-target on subsequent up/down
2097 // movements that cross beyond the end of short lines.
2098 // Thus a special handling when the cursor is at the
2099 // end of line: Use the new x-target only if the old
2100 // one was before the end of line or the old one was
2101 // after the beginning of the line
2102 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
2106 left = pos() == textRow().endpos();
2107 right = pos() == textRow().pos();
2109 left = pos() == textRow().pos();
2110 right = pos() == textRow().endpos();
2112 if ((!left && !right) ||
2113 (left && !right && xo < x_target_) ||
2114 (!left && right && x_target_ < xo))
2121 // first get the current line
2122 TextMetrics & tm = bv_->textMetrics(text());
2123 ParagraphMetrics const & pm = tm.parMetrics(pit());
2125 if (pos() && boundary())
2126 row = pm.pos2row(pos() - 1);
2128 row = pm.pos2row(pos());
2130 if (atFirstOrLastRow(up)) {
2131 // Is there a place for the cursor to go ? If yes, we
2132 // can execute the DEPM, otherwise we should keep the
2133 // paragraph to host the cursor.
2134 Cursor dummy = *this;
2135 bool valid_destination = false;
2136 for(; dummy.depth(); dummy.pop())
2137 if (!dummy.atFirstOrLastRow(up)) {
2138 valid_destination = true;
2142 // will a next dispatch follow and if there is a new
2143 // dispatch will it move the cursor out ?
2144 if (depth() > 1 && valid_destination) {
2145 // The cursor hasn't changed yet. This happens when
2146 // you e.g. move out of an inset. And to give the
2147 // DEPM the possibility of doing something we must
2148 // provide it with two different cursors. (Lgb, vfr)
2150 dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
2151 dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
2153 updateNeeded |= bv().checkDepm(dummy, *this);
2154 updateTextTargetOffset();
2156 forceBufferUpdate();
2161 // with and without selection are handled differently
2163 int yo1 = bv().getPos(*this).y_;
2165 // To next/previous row
2166 // FIXME: the y position is often guessed wrongly across styles and
2167 // insets, which leads to weird behaviour.
2169 tm.editXY(*this, xo, yo1 - textRow().ascent() - 1);
2171 tm.editXY(*this, xo, yo1 + textRow().descent() + 1);
2172 x_target_ = old.x_target_;
2175 // This happens when you move out of an inset.
2176 // And to give the DEPM the possibility of doing
2177 // something we must provide it with two different
2179 Cursor dummy = *this;
2182 if (bv().checkDepm(dummy, old)) {
2183 updateNeeded = true;
2184 // Make sure that cur gets back whatever happened to dummy (Lgb)
2187 if (inTexted() && pos() && paragraph().isEnvSeparator(pos() - 1))
2190 // if there is a selection, we stay out of any inset,
2191 // and just jump to the right position:
2197 } else if (pit() > 0) {
2199 TextMetrics & tm2 = bv_->textMetrics(text());
2200 if (!tm2.contains(pit()))
2201 tm2.newParMetricsUp();
2202 ParagraphMetrics const & pmcur = tm2.parMetrics(pit());
2203 next_row = pmcur.rows().size() - 1;
2206 if (row + 1 < int(pm.rows().size())) {
2208 } else if (pit() + 1 < int(text()->paragraphs().size())) {
2210 TextMetrics & tm2 = bv_->textMetrics(text());
2211 if (!tm2.contains(pit()))
2212 tm2.newParMetricsDown();
2217 Row const & real_next_row = tm.parMetrics(pit()).rows()[next_row];
2219 top().pos() = tm.getPosNearX(real_next_row, xo, bound);
2221 // When selection==false, this is done by TextMetrics::editXY
2224 updateNeeded |= bv().checkDepm(*this, old);
2228 forceBufferUpdate();
2229 updateTextTargetOffset();
2234 void Cursor::handleFont(string const & font)
2236 LYXERR(Debug::DEBUG, font);
2240 safe = cap::grabAndEraseSelection(*this);
2245 if (lastpos() != 0) {
2246 // something left in the cell
2248 // cursor in first position
2250 } else if (pos() == lastpos()) {
2251 // cursor in last position
2254 // cursor in between. split cell
2255 MathData::iterator bt = cell().begin();
2256 MathAtom at = createInsetMath(from_utf8(font), buffer());
2257 at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
2258 cell().erase(bt, bt + pos());
2263 // nothing left in the cell
2272 void Cursor::undispatched() const
2274 disp_.dispatched(false);
2278 void Cursor::dispatched() const
2280 disp_.dispatched(true);
2284 void Cursor::screenUpdateFlags(Update::flags f) const
2286 disp_.screenUpdate(f);
2290 void Cursor::noScreenUpdate() const
2292 disp_.screenUpdate(Update::None);
2296 void Cursor::forceBufferUpdate() const
2298 disp_.forceBufferUpdate();
2302 void Cursor::clearBufferUpdate() const
2304 disp_.clearBufferUpdate();
2308 bool Cursor::needBufferUpdate() const
2310 return disp_.needBufferUpdate();
2314 Font Cursor::getFont() const
2316 // The logic here should more or less match to the
2317 // Cursor::setCurrentFont logic, i.e. the cursor height should
2318 // give a hint what will happen if a character is entered.
2319 // FIXME: this is not the case, what about removing this method ? (see #10478).
2321 // HACK. far from being perfect...
2323 CursorSlice const & sl = innerTextSlice();
2324 Text const & text = *sl.text();
2325 Paragraph const & par = text.getPar(sl.pit());
2327 // on boundary, so we are really at the character before
2328 pos_type pos = sl.pos();
2329 if (pos > 0 && boundary())
2332 // on space? Take the font before (only for RTL boundary stay)
2334 TextMetrics const & tm = bv().textMetrics(&text);
2335 if (pos == sl.lastpos()
2336 || (par.isSeparator(pos)
2337 && !tm.isRTLBoundary(sl.pit(), pos)))
2341 // get font at the position
2342 Font font = par.getFont(buffer()->params(), pos,
2343 text.outerFont(sl.pit()));
2349 void Cursor::sanitize()
2351 setBuffer(&bv_->buffer());
2352 CursorData::sanitize();
2356 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2358 // find inset in common
2360 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2361 if (&old[i].inset() != &cur[i].inset())
2365 // update words if we just moved to another paragraph
2366 if (i == old.depth() && i == cur.depth()
2367 && !cur.buffer()->isClean()
2368 && cur.inTexted() && old.inTexted()
2369 && cur.pit() != old.pit()) {
2370 old.paragraph().updateWords();
2373 // notify everything on top of the common part in old cursor,
2374 // but stop if the inset claims the cursor to be invalid now
2375 for (size_type j = i; j < old.depth(); ++j) {
2376 Cursor inset_pos = old;
2377 inset_pos.cutOff(j);
2378 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2382 // notify everything on top of the common part in new cursor,
2383 // but stop if the inset claims the cursor to be invalid now
2384 for (; i < cur.depth(); ++i) {
2385 if (cur[i].inset().notifyCursorEnters(cur))
2393 void Cursor::setCurrentFont()
2395 CursorSlice const & cs = innerTextSlice();
2396 Paragraph const & par = cs.paragraph();
2397 pos_type cpit = cs.pit();
2398 pos_type cpos = cs.pos();
2399 Text const & ctext = *cs.text();
2400 TextMetrics const & tm = bv().textMetrics(&ctext);
2402 // are we behind previous char in fact? -> go to that char
2403 if (cpos > 0 && boundary())
2406 // find position to take the font from
2408 // paragraph end? -> font of last char
2409 if (cpos == lastpos())
2411 // on space? -> look at the words in front of space
2412 else if (cpos > 0 && par.isSeparator(cpos)) {
2413 // abc| def -> font of c
2414 // abc |[WERBEH], i.e. boundary==true -> font of c
2415 // abc [WERBEH]| def, font of the space
2416 if (!tm.isRTLBoundary(cpit, cpos))
2422 BufferParams const & bufparams = buffer()->params();
2423 current_font = par.getFontSettings(bufparams, cpos);
2424 real_current_font = tm.displayFont(cpit, cpos);
2426 // special case for paragraph end
2427 if (cs.pos() == lastpos()
2428 && tm.isRTLBoundary(cpit, cs.pos())
2430 Language const * lang = par.getParLanguage(bufparams);
2431 current_font.setLanguage(lang);
2432 current_font.fontInfo().setNumber(FONT_OFF);
2433 real_current_font.setLanguage(lang);
2434 real_current_font.fontInfo().setNumber(FONT_OFF);
2439 void Cursor::checkBufferStructure()
2441 Buffer const * master = buffer()->masterBuffer();
2442 master->tocBackend().updateItem(*this);
2443 if (master != buffer() && !master->hasGuiDelegate())
2444 // In case the master has no gui associated with it,
2445 // the TocItem is not updated (part of bug 5699).
2446 buffer()->tocBackend().updateItem(*this);
2448 // If the last tracked change of the paragraph has just been
2449 // deleted, then we need to recompute the buffer flag
2450 // tracked_changes_present_.
2451 if (inTexted() && paragraph().isChangeUpdateRequired())
2452 disp_.forceChangesUpdate();
2456 void Cursor::moveToClosestEdge(int const x, bool const edit)
2458 if (Inset const * inset = nextInset()) {
2459 // stay in front of insets for which we want to open the dialog
2460 // (e.g. InsetMathSpace).
2461 if (edit && (inset->hasSettings() || !inset->contextMenuName().empty()))
2463 CoordCache::Insets const & insetCache = bv().coordCache().getInsets();
2464 if (!insetCache.has(inset))
2466 int const wid = insetCache.dim(inset).wid;
2467 Point p = insetCache.xy(inset);
2468 if (x > p.x_ + (wid + 1) / 2)