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::undoAction()
576 if (!buffer()->undo().undoAction(*this))
583 bool CursorData::redoAction()
585 if (!buffer()->undo().redoAction(*this))
592 void CursorData::finishUndo() const
594 buffer()->undo().finishUndo();
598 void CursorData::beginUndoGroup() const
600 buffer()->undo().beginUndoGroup(*this);
604 void CursorData::endUndoGroup() const
606 buffer()->undo().endUndoGroup(*this);
610 void CursorData::recordUndo(pit_type from, pit_type to) const
612 buffer()->undo().recordUndo(*this, from, to);
616 void CursorData::recordUndo(pit_type from) const
618 buffer()->undo().recordUndo(*this, from, pit());
622 void CursorData::recordUndo(UndoKind kind) const
624 buffer()->undo().recordUndo(*this, kind);
628 void CursorData::recordUndoInset(Inset const * in) const
630 buffer()->undo().recordUndoInset(*this, in);
634 void CursorData::recordUndoFullBuffer() const
636 buffer()->undo().recordUndoFullBuffer(*this);
640 void CursorData::recordUndoBufferParams() const
642 buffer()->undo().recordUndoBufferParams(*this);
646 void CursorData::recordUndoSelection() const
649 if (cap::multipleCellsSelected(*this))
654 buffer()->undo().recordUndo(*this,
655 selBegin().pit(), selEnd().pit());
660 int CursorData::currentMode()
662 LASSERT(!empty(), return Inset::UNDECIDED_MODE);
663 for (int i = depth() - 1; i >= 0; --i) {
664 int res = operator[](i).inset().currentMode();
665 bool locked_mode = operator[](i).inset().lockedMode();
666 // Also return UNDECIDED_MODE when the mode is locked,
667 // as in this case it is treated the same as TEXT_MODE
668 if (res != Inset::UNDECIDED_MODE || locked_mode)
671 return Inset::TEXT_MODE;
675 bool CursorData::confirmDeletion(bool const before) const
678 if (Inset const * inset = before ? prevInset() : nextInset())
679 return inset->confirmDeletion();
681 DocIterator dit = selectionBegin();
682 CursorSlice const end = selectionEnd().top();
683 for (; dit.top() < end; dit.top().forwardPos())
684 if (Inset const * inset = dit.nextInset())
685 if (inset->confirmDeletion())
698 // be careful: this is called from the bv's constructor, too, so
699 // bv functions are not yet available!
700 Cursor::Cursor(BufferView & bv)
701 : CursorData(&bv.buffer()), bv_(&bv),
702 x_target_(-1), textTargetOffset_(0),
703 beforeDispatchPosX_(0), beforeDispatchPosY_(0)
714 void Cursor::setCursorData(CursorData const & data)
716 CursorData::operator=(data);
720 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
724 // Try to fix cursor in case it is broken.
727 // Is this a function that acts on inset at point?
728 Inset * inset = cur.nextInset();
729 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
730 && inset && inset->getStatus(cur, cmd, status))
733 // This is, of course, a mess. Better create a new doc iterator and use
734 // this in Inset::getStatus. This might require an additional
735 // BufferView * arg, though (which should be avoided)
736 //Cursor safe = *this;
738 for ( ; cur.depth(); cur.pop()) {
739 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
740 // LASSERT: Is it safe to continue here, or should we return?
741 LASSERT(cur.idx() <= cur.lastidx(), /**/);
742 LASSERT(cur.pit() <= cur.lastpit(), /**/);
743 LASSERT(cur.pos() <= cur.lastpos(), /**/);
745 // The inset's getStatus() will return 'true' if it made
746 // a definitive decision on whether it want to handle the
747 // request or not. The result of this decision is put into
748 // the 'status' parameter.
749 if (cur.inset().getStatus(cur, cmd, status)) {
758 void Cursor::saveBeforeDispatchPosXY()
760 getPos(beforeDispatchPosX_, beforeDispatchPosY_);
764 void Cursor::dispatch(FuncRequest const & cmd0)
766 LYXERR(Debug::ACTION, "Cursor::dispatch: cmd: " << cmd0 << '\n' << *this);
771 FuncRequest cmd = cmd0;
774 disp_ = DispatchResult();
778 // Is this a function that acts on inset at point?
779 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
781 disp_.dispatched(true);
782 disp_.screenUpdate(Update::FitCursor | Update::Force);
783 FuncRequest tmpcmd = cmd;
784 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
785 << cmd0 << endl << *this);
786 nextInset()->dispatch(*this, tmpcmd);
787 if (disp_.dispatched()) {
793 // store some values to be used inside of the handlers
794 beforeDispatchCursor_ = *this;
795 for (; depth(); pop(), boundary(false)) {
796 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
797 << cmd0 << endl << *this);
799 // In any of these cases, the cursor is invalid, and we should
800 // try to save this document rather than crash.
801 LBUFERR(pos() <= lastpos());
802 LBUFERR(idx() <= lastidx());
803 LBUFERR(pit() <= lastpit());
805 // The common case is 'LFUN handled, need update', so make the
806 // LFUN handler's life easier by assuming this as default value.
807 // The handler can reset the update and val flags if necessary.
808 disp_.screenUpdate(Update::FitCursor | Update::Force);
809 disp_.dispatched(true);
810 inset().dispatch(*this, cmd);
811 if (disp_.dispatched())
815 // it completely to get a 'bomb early' behaviour in case this
816 // object will be used again.
817 if (!disp_.dispatched()) {
818 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
819 // We might have invalidated the cursor when removing an empty
820 // paragraph while the cursor could not be moved out the inset
821 // while we initially thought we could. This might happen when
822 // a multiline inset becomes an inline inset when the second
823 // paragraph is removed.
824 if (safe.pit() > safe.lastpit()) {
825 safe.pit() = safe.lastpit();
826 safe.pos() = safe.lastpos();
829 disp_.screenUpdate(Update::None);
830 disp_.dispatched(false);
832 // restore the previous one because nested Cursor::dispatch calls
833 // are possible which would change it
834 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
838 // NOTE: The code below has been copied to BufferView::dispatch.
839 // If you need to modify this, please update the other one too.
841 // notify insets we just left
843 old.beginUndoGroup();
845 bool badcursor = notifyCursorLeavesOrEnters(old, *this);
848 bv().resetInlineCompletionPos();
855 DispatchResult const & Cursor::result() const
861 void Cursor::message(docstring const & msg) const
863 disp_.setMessage(msg);
867 void Cursor::errorMessage(docstring const & msg) const
869 disp_.setMessage(msg);
870 disp_.setError(true);
874 BufferView & Cursor::bv() const
883 LBUFERR(depth() >= 1);
888 void Cursor::push(Inset & p)
890 push_back(CursorSlice(p));
891 p.setBuffer(*buffer());
895 void Cursor::pushBackward(Inset & p)
897 LASSERT(!empty(), return);
898 //lyxerr << "Entering inset " << t << " front" << endl;
904 void Cursor::editInsertedInset()
906 LASSERT(!empty(), return);
910 InsetMath &p = prevMath();
917 // this could be a while() loop, but only one cell is not empty in
918 // cases we are interested in. The cell is not empty because we
919 // have inserted the selection in there.
920 if (!cell().empty()) {
921 // if it is not empty, move to the next one.
922 if (!inset().idxNext(*this))
923 // If there is no next one, exit the inset.
929 bool Cursor::popBackward()
931 LASSERT(!empty(), return false);
939 bool Cursor::popForward()
941 LASSERT(!empty(), return false);
942 //lyxerr << "Leaving inset from in back" << endl;
943 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
947 pos() += lastpos() - lp + 1;
952 void Cursor::getPos(int & x, int & y) const
954 Point p = bv().getPos(*this);
960 Row const & Cursor::textRow() const
962 CursorSlice const & cs = innerTextSlice();
963 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
964 return pm.getRow(pos(), boundary());
968 bool Cursor::posVisRight(bool skip_inset)
970 Cursor new_cur = *this; // where we will move to
971 pos_type left_pos; // position visually left of current cursor
972 pos_type right_pos; // position visually right of current cursor
974 getSurroundingPos(left_pos, right_pos);
976 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
978 // Are we at an inset?
979 new_cur.pos() = right_pos;
980 new_cur.boundary(false);
982 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
983 // we actually move the cursor at the end of this
984 // function, for now we just keep track of the new
985 // position in new_cur...
986 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
989 // Are we already at rightmost pos in row?
990 else if (text()->empty() || right_pos == -1) {
993 if (!new_cur.posVisToNewRow(false)) {
994 LYXERR(Debug::RTL, "not moving!");
998 // we actually move the cursor at the end of this
999 // function, for now just keep track of the new
1000 // position in new_cur...
1001 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
1002 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
1005 // normal movement to the right
1008 // Recall, if the cursor is at position 'x', that
1009 // means *before* the character at position 'x'. In
1010 // RTL, "before" means "to the right of", in LTR, "to
1011 // the left of". So currently our situation is this:
1012 // the position to our right is 'right_pos' (i.e.,
1013 // we're currently to the left of 'right_pos'). In
1014 // order to move to the right, it depends whether or
1015 // not the character at 'right_pos' is RTL.
1016 bool const new_pos_is_RTL = paragraph().getFontSettings(
1017 buffer()->params(), right_pos).isVisibleRightToLeft();
1018 // If the character at 'right_pos' *is* LTR, then in
1019 // order to move to the right of it, we need to be
1020 // *after* 'right_pos', i.e., move to position
1022 if (!new_pos_is_RTL) {
1023 new_cur.pos() = right_pos + 1;
1024 // set the boundary to true in two situations:
1026 // 1. if new_pos is now lastpos, and we're in
1027 // an RTL paragraph (this means that we're
1028 // moving right to the end of an LTR chunk
1029 // which is at the end of an RTL paragraph);
1030 (new_cur.pos() == lastpos()
1031 && paragraph().isRTL(buffer()->params()))
1032 // 2. if the position *after* right_pos is RTL
1033 // (we want to be *after* right_pos, not
1034 // before right_pos + 1!)
1035 || paragraph().getFontSettings(buffer()->params(),
1036 new_cur.pos()).isVisibleRightToLeft()
1038 new_cur.boundary(true);
1039 else // set the boundary to false
1040 new_cur.boundary(false);
1042 // Otherwise (if the character at position 'right_pos'
1043 // is RTL), then moving to the right of it is as easy
1044 // as setting the new position to 'right_pos'.
1046 new_cur.pos() = right_pos;
1047 new_cur.boundary(false);
1052 bool const moved = new_cur != *this || new_cur.boundary() != boundary();
1055 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
1056 << (new_cur.boundary() ? " (boundary)" : ""));
1064 bool Cursor::posVisLeft(bool skip_inset)
1066 Cursor new_cur = *this; // where we will move to
1067 pos_type left_pos; // position visually left of current cursor
1068 pos_type right_pos; // position visually right of current cursor
1070 getSurroundingPos(left_pos, right_pos);
1072 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
1074 // Are we at an inset?
1075 new_cur.pos() = left_pos;
1076 new_cur.boundary(false);
1078 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
1079 // we actually move the cursor at the end of this
1080 // function, for now we just keep track of the new
1081 // position in new_cur...
1082 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
1085 // Are we already at leftmost pos in row?
1086 else if (text()->empty() || left_pos == -1) {
1089 if (!new_cur.posVisToNewRow(true)) {
1090 LYXERR(Debug::RTL, "not moving!");
1094 // we actually move the cursor at the end of this
1095 // function, for now just keep track of the new
1096 // position in new_cur...
1097 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
1098 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
1101 // normal movement to the left
1104 // Recall, if the cursor is at position 'x', that
1105 // means *before* the character at position 'x'. In
1106 // RTL, "before" means "to the right of", in LTR, "to
1107 // the left of". So currently our situation is this:
1108 // the position to our left is 'left_pos' (i.e., we're
1109 // currently to the right of 'left_pos'). In order to
1110 // move to the left, it depends whether or not the
1111 // character at 'left_pos' is RTL.
1112 bool const new_pos_is_RTL = paragraph().getFontSettings(
1113 buffer()->params(), left_pos).isVisibleRightToLeft();
1114 // If the character at 'left_pos' *is* RTL, then in
1115 // order to move to the left of it, we need to be
1116 // *after* 'left_pos', i.e., move to position
1118 if (new_pos_is_RTL) {
1119 new_cur.pos() = left_pos + 1;
1120 // set the boundary to true in two situations:
1122 // 1. if new_pos is now lastpos and we're in
1123 // an LTR paragraph (this means that we're
1124 // moving left to the end of an RTL chunk
1125 // which is at the end of an LTR paragraph);
1126 (new_cur.pos() == lastpos()
1127 && !paragraph().isRTL(buffer()->params()))
1128 // 2. if the position *after* left_pos is not
1129 // RTL (we want to be *after* left_pos, not
1130 // before left_pos + 1!)
1131 || !paragraph().getFontSettings(buffer()->params(),
1132 new_cur.pos()).isVisibleRightToLeft()
1134 new_cur.boundary(true);
1135 else // set the boundary to false
1136 new_cur.boundary(false);
1138 // Otherwise (if the character at position 'left_pos'
1139 // is LTR), then moving to the left of it is as easy
1140 // as setting the new position to 'left_pos'.
1142 new_cur.pos() = left_pos;
1143 new_cur.boundary(false);
1148 bool const moved = new_cur != *this || new_cur.boundary() != boundary();
1151 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
1152 << (new_cur.boundary() ? " (boundary)" : ""));
1162 // Return true on success
1163 bool findNonVirtual(Row const & row, Row::const_iterator & cit, bool onleft)
1166 while (cit != row.begin() && cit->isVirtual())
1169 while (cit != row.end() && cit->isVirtual())
1172 return cit != row.end() && !cit->isVirtual();
1177 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos) const
1179 // by default, we know nothing.
1183 Row const & row = textRow();
1185 Row::const_iterator cit = row.findElement(pos(), boundary(), dummy);
1186 // Handle the case of empty row
1187 if (cit == row.end()) {
1189 right_pos = row.pos();
1191 left_pos = row.pos() - 1;
1195 // skip virtual elements and exit if no non-virtual one exists
1196 if (!findNonVirtual(row, cit, !cit->isRTL()))
1199 // if the position is at the left side of the element, we have to
1200 // look at the previous element
1201 if (pos() == cit->left_pos()) {
1202 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1203 << "), AT LEFT of *cit=" << *cit);
1204 // this one is easy (see common case below)
1205 right_pos = pos() - (cit->isRTL() ? 1 : 0);
1206 // at the left of the row
1207 if (cit == row.begin())
1210 if (!findNonVirtual(row, cit, true))
1212 // [...[ is the row element, | is cursor position (! with boundary)
1213 // [ 1 2 [ is a ltr row element with pos=1 and endpos=3
1214 // ] 2 1] is an rtl row element with pos=1 and endpos=3
1215 // [ 1 2 [ [|3 4 [ => (2, 3)
1216 // or [ 1 2 [ ]!4 3 ] => (2, 4)
1217 // or ] 2 1 ] [|3 4 [ => (1, 3)
1218 // or ] 4 3 ] ]!2 1 ] => (3, 2)
1219 left_pos = cit->right_pos() - (cit->isRTL() ? 0 : 1);
1220 // happens with consecutive row of same direction
1221 if (left_pos == right_pos) {
1222 left_pos += cit->isRTL() ? 1 : -1;
1225 // same code but with the element at the right
1226 else if (pos() == cit->right_pos()) {
1227 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1228 << "), AT RIGHT of *cit=" << *cit);
1229 // this one is easy (see common case below)
1230 left_pos = pos() - (cit->isRTL() ? 0 : 1);
1231 // at the right of the row
1232 if (cit + 1 == row.end())
1235 if (!findNonVirtual(row, cit, false))
1237 // [ 1 2![ [ 3 4 [ => (2, 3)
1238 // or [ 1 2![ ] 4 3 ] => (2, 4)
1239 // or ] 2 1|] [ 3 4 [ => (1, 3)
1240 // or ] 4 3|] ] 2 1 ] => (3, 2)
1241 right_pos = cit->left_pos() - (cit->isRTL() ? 1 : 0);
1242 // happens with consecutive row of same direction
1243 if (right_pos == left_pos)
1244 right_pos += cit->isRTL() ? -1 : 1;
1246 // common case: both positions are inside the row element
1248 // [ 1 2|3 [ => (2, 3)
1249 // or ] 3|2 1 ] => (3, 2)
1250 left_pos = pos() - (cit->isRTL() ? 0 : 1);
1251 right_pos = pos() - (cit->isRTL() ? 1 : 0);
1254 // Note that debug message does not catch all early returns above
1255 LYXERR(Debug::RTL,"getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1256 << ") => (" << left_pos << ", " << right_pos <<")");
1260 bool Cursor::posVisToNewRow(bool movingLeft)
1262 Row const & row = textRow();
1263 bool par_is_LTR = !row.isRTL();
1265 // Inside a table, determining whether to move to the next or
1266 // previous row should be done based on the table's direction.
1267 if (inset().asInsetTabular()) {
1268 par_is_LTR = !inset().asInsetTabular()->isRightToLeft(*this);
1269 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
1272 // if moving left in an LTR paragraph or moving right in an
1273 // RTL one, move to previous row
1274 if (par_is_LTR == movingLeft) {
1275 if (row.pos() == 0) { // we're at first row in paragraph
1276 if (pit() == 0) // no previous paragraph! don't move
1278 // move to last pos in previous par
1282 } else { // move to previous row in this par
1283 pos() = row.pos() - 1; // this is guaranteed to be in previous row
1287 // if moving left in an RTL paragraph or moving right in an
1288 // LTR one, move to next row
1290 if (row.endpos() == lastpos()) { // we're at last row in paragraph
1291 if (pit() == lastpit()) // last paragraph! don't move
1293 // move to first row in next par
1297 } else { // move to next row in this par
1298 pos() = row.endpos();
1303 // make sure we're at left-/right-most pos in new row
1304 posVisToRowExtremity(!movingLeft);
1310 void Cursor::posVisToRowExtremity(bool left)
1312 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
1313 << (boundary() ? 1 : 0));
1315 TextMetrics const & tm = bv_->textMetrics(text());
1316 // Looking for extremities is like clicking on the left or the
1317 // right of the row.
1318 int x = tm.origin().x_ + (left ? 0 : textRow().width());
1320 pos() = tm.getPosNearX(textRow(), x, b);
1323 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
1324 << (boundary() ? 1 : 0));
1328 bool Cursor::reverseDirectionNeeded() const
1331 * We determine the directions based on the direction of the
1332 * bottom() --- i.e., outermost --- paragraph, because that is
1333 * the only way to achieve consistency of the arrow's movements
1334 * within a paragraph, and thus avoid situations in which the
1335 * cursor gets stuck.
1337 return bottom().paragraph().isRTL(bv().buffer().params());
1341 void Cursor::setTargetX(int x)
1344 textTargetOffset_ = 0;
1348 int Cursor::x_target() const
1354 void Cursor::clearTargetX()
1357 textTargetOffset_ = 0;
1361 void Cursor::updateTextTargetOffset()
1366 textTargetOffset_ = x - x_target_;
1370 bool Cursor::selHandle(bool sel)
1372 //lyxerr << "Cursor::selHandle" << endl;
1375 if (sel == selection())
1379 cap::saveSelection(*this);
1387 bool Cursor::atFirstOrLastRow(bool up)
1389 TextMetrics const & tm = bv_->textMetrics(text());
1390 ParagraphMetrics const & pm = tm.parMetrics(pit());
1393 if (pos() && boundary())
1394 row = pm.pos2row(pos() - 1);
1396 row = pm.pos2row(pos());
1399 if (pit() == 0 && row == 0)
1402 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1403 row + 1 >= int(pm.rows().size()))
1413 ///////////////////////////////////////////////////////////////////
1416 // The part below is the non-integrated rest of the original math
1417 // cursor. This should be either generalized for texted or moved
1418 // back to mathed (in most cases to InsetMathNest).
1420 ///////////////////////////////////////////////////////////////////
1422 #include "mathed/InsetMathChar.h"
1423 #include "mathed/InsetMathGrid.h"
1424 #include "mathed/InsetMathScript.h"
1425 #include "mathed/InsetMathUnknown.h"
1426 #include "mathed/MathFactory.h"
1427 #include "mathed/MathStream.h"
1428 #include "mathed/MathSupport.h"
1433 bool Cursor::openable(MathAtom const & t) const
1444 // we can't move into anything new during selection
1445 if (depth() >= realAnchor().depth())
1447 if (t.nucleus() != &realAnchor()[depth()].inset())
1454 void Cursor::plainErase()
1456 cell().erase(pos());
1460 void Cursor::plainInsert(MathAtom const & t)
1462 cell().insert(pos(), t);
1464 inset().setBuffer(bv_->buffer());
1466 checkBufferStructure();
1470 void Cursor::insert(char_type c)
1472 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1473 LASSERT(!empty(), return);
1475 cap::selClearOrDel(*this);
1476 insert(new InsetMathChar(c));
1478 text()->insertChar(*this, c);
1483 void Cursor::insert(docstring const & str)
1485 for (char_type c : str)
1490 void Cursor::insert(Inset * inset0)
1492 LASSERT(inset0, return);
1494 insert(MathAtom(inset0->asInsetMath()));
1496 text()->insertInset(*this, inset0);
1497 inset0->setBuffer(bv_->buffer());
1499 if (inset0->isLabeled())
1500 forceBufferUpdate();
1505 void Cursor::insert(MathAtom const & t)
1507 LATTEST(inMathed());
1508 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1510 cap::selClearOrDel(*this);
1515 void Cursor::insert(MathData const & ar)
1517 LATTEST(inMathed());
1520 cap::eraseSelection(*this);
1521 cell().insert(pos(), ar);
1523 // FIXME audit setBuffer calls
1524 inset().setBuffer(bv_->buffer());
1528 int Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1530 LATTEST(inMathed());
1531 MathData ar(buffer());
1533 if (ar.size() == 1 && (enter || selection()))
1541 void Cursor::niceInsert(MathAtom const & t)
1543 LATTEST(inMathed());
1545 docstring const safe = cap::grabAndEraseSelection(*this);
1547 // If possible, enter the new inset and move the contents of the selection
1548 if (t->isActive()) {
1549 idx_type const idx = prevMath().asNestInset()->firstIdx();
1550 asArray(safe, prevMath().cell(idx));
1551 editInsertedInset();
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)
1690 idx_type const idx = a.nucleus()->asNestInset()->firstIdx();
1691 //lyxerr << "Cursor::handleNest: " << idx << endl;
1693 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(idx));
1695 editInsertedInset();
1699 int Cursor::targetX() const
1701 if (x_target() != -1)
1710 int Cursor::textTargetOffset() const
1712 return textTargetOffset_;
1716 void Cursor::setTargetX()
1725 bool Cursor::macroModeClose(bool cancel)
1729 InsetMathUnknown * p = activeMacro();
1731 MathData selection(buffer());
1732 asArray(p->selection(), selection);
1733 docstring const s = p->name();
1735 cell().erase(pos());
1737 // trigger updates of macros, at least, if no full
1738 // updates take place anyway
1739 screenUpdateFlags(Update::Force);
1741 // do nothing if the macro name is empty
1742 if (s == "\\" || cancel) {
1746 docstring const name = s.substr(1);
1747 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1748 if (in && in->interpretString(*this, s))
1750 bool const user_macro = buffer()->getMacro(name, *this, false);
1751 MathAtom atom = user_macro ? MathAtom(new InsetMathMacro(buffer(), name))
1752 : createInsetMath(name, buffer());
1754 // try to put argument into macro, if we just inserted a macro
1755 bool macroArg = false;
1756 InsetMathMacro * atomAsMacro = atom.nucleus()->asMacro();
1757 InsetMathNest * atomAsNest = atom.nucleus()->asNestInset();
1759 // macros here are still unfolded (in init mode in fact). So
1760 // we have to resolve the macro here manually and check its arity
1761 // to put the selection behind it if arity > 0.
1762 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1763 if (!selection.empty() && data && data->numargs() - data->optionals() > 0) {
1765 atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1767 // non-greedy case. Do not touch the arguments behind
1768 atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1771 // insert remembered selection into first argument of a non-macro
1772 else if (atomAsNest && atomAsNest->nargs() > 0)
1773 atomAsNest->cell(atomAsNest->firstIdx()).append(selection);
1775 MathWordList const & words = mathedWordList();
1776 MathWordList::const_iterator it = words.find(name);
1777 bool keep_mathmode = user_macro
1778 || (it != words.end() && (it->second.inset == "font"
1779 || it->second.inset == "oldfont"
1780 || it->second.inset == "mbox"));
1781 bool ert_macro = !user_macro && it == words.end() && atomAsMacro;
1783 if (in && in->currentMode() == Inset::TEXT_MODE
1784 && atom.nucleus()->currentMode() == Inset::MATH_MODE
1785 && name != from_ascii("ensuremath") && !ert_macro) {
1786 MathAtom at(new InsetMathEnsureMath(buffer()));
1787 at.nucleus()->cell(0).push_back(atom);
1790 } else if (in && in->currentMode() == Inset::MATH_MODE
1791 && atom.nucleus()->currentMode() == Inset::TEXT_MODE
1792 && !keep_mathmode) {
1793 MathAtom at = createInsetMath("text", buffer());
1794 at.nucleus()->cell(0).push_back(atom);
1800 // finally put the macro argument behind, if needed
1802 if (selection.size() > 1 || selection[0]->asScriptInset())
1803 plainInsert(MathAtom(new InsetMathBrace(selection)));
1812 bool Cursor::inMacroMode() const
1816 if (pos() == 0 || cell().empty())
1818 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1819 return p && !p->final();
1823 InsetMathUnknown * Cursor::activeMacro()
1825 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1829 InsetMathUnknown const * Cursor::activeMacro() const
1831 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1835 docstring Cursor::macroName()
1837 return inMacroMode() ? activeMacro()->name() : docstring();
1841 void Cursor::pullArg()
1844 MathData ar = cell();
1845 if (popBackward() && inMathed()) {
1847 cell().insert(pos(), ar);
1850 //formula()->mutateToText();
1855 void Cursor::normalize()
1857 if (idx() > lastidx()) {
1858 lyxerr << "this should not really happen - 1: "
1859 << idx() << ' ' << nargs()
1860 << " in: " << &inset() << endl;
1864 if (pos() > lastpos()) {
1865 lyxerr << "this should not really happen - 2: "
1866 << pos() << ' ' << lastpos() << " in idx: " << idx()
1868 odocstringstream os;
1869 otexrowstream ots(os);
1870 WriteStream wi(ots, false, true, WriteStream::wsDefault);
1871 inset().asInsetMath()->write(wi);
1872 lyxerr << to_utf8(os.str()) << endl;
1878 bool Cursor::upDownInMath(bool up)
1880 // Be warned: The 'logic' implemented in this function is highly
1881 // fragile. A distance of one pixel or a '<' vs '<=' _really
1882 // matters. So fiddle around with it only if you think you know
1883 // what you are doing!
1887 xo = beforeDispatchPosX_;
1889 // check if we had something else in mind, if not, this is the future
1891 if (x_target_ == -1)
1893 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1894 // In text mode inside the line (not left or right) possibly set a new target_x,
1895 // but only if we are somewhere else than the previous target-offset.
1897 // We want to keep the x-target on subsequent up/down movements
1898 // that cross beyond the end of short lines. Thus a special
1899 // handling when the cursor is at the end of line: Use the new
1900 // x-target only if the old one was before the end of line
1901 // or the old one was after the beginning of the line
1902 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
1906 left = pos() == textRow().endpos();
1907 right = pos() == textRow().pos();
1909 left = pos() == textRow().pos();
1910 right = pos() == textRow().endpos();
1912 if ((!left && !right) ||
1913 (left && !right && xo < x_target_) ||
1914 (!left && right && x_target_ < xo))
1921 // try neigbouring script insets
1923 if (inMathed() && !selection()) {
1926 InsetMathScript const * p = prevAtom()->asScriptInset();
1927 if (p && p->has(up)) {
1929 push(*const_cast<InsetMathScript*>(p));
1930 idx() = p->idxOfScript(up);
1933 // we went in the right direction? Otherwise don't jump into the script
1937 int oy = beforeDispatchPosY_;
1938 if ((!up && y <= oy) ||
1947 if (pos() != lastpos()) {
1948 InsetMathScript const * p = nextAtom()->asScriptInset();
1949 if (p && p->has(up)) {
1950 push(*const_cast<InsetMathScript*>(p));
1951 idx() = p->idxOfScript(up);
1954 // we went in the right direction? Otherwise don't jump into the script
1958 int oy = beforeDispatchPosY_;
1959 if ((!up && y <= oy) ||
1968 // try to find an inset that knows better then we,
1969 if (inset().idxUpDown(*this, up)) {
1970 //lyxerr << "idxUpDown triggered" << endl;
1971 // try to find best position within this inset
1973 setCursor(bruteFind(*this, xo, yo));
1977 // any improvement going just out of inset?
1978 if (popBackward() && inMathed()) {
1979 //lyxerr << "updown: popBackward succeeded" << endl;
1982 int yold = beforeDispatchPosY_;
1984 if (up ? ynew < yold : ynew > yold)
1988 // no success, we are probably at the document top or bottom
1994 bool Cursor::mathForward(bool word)
1996 LASSERT(inMathed(), return false);
1997 if (pos() < lastpos()) {
1999 // word: skip a group of insets of the form X*(B*|R*|P*) (greedy
2000 // match) where X is any math class, B is mathbin, R is mathrel, and
2001 // P is mathpunct. Make sure that the following remains true:
2002 // mathForward(true); mathBackward(true); mathForward(true)
2003 // is the same as mathForward(true) and
2004 // mathBackward(true); mathForward(true); mathBackward(true)
2005 // is the same as mathBackward(true).
2006 MathClass mc = nextMath().mathClass();
2009 while (pos() < lastpos() && mc == nextMath().mathClass());
2010 if (pos() < lastpos() &&
2011 ((mc = nextMath().mathClass()) == MC_BIN ||
2012 mc == MC_REL || mc == MC_PUNCT))
2015 while (pos() < lastpos() && mc == nextMath().mathClass());
2016 } else if (openable(nextAtom())) {
2017 // single step: try to enter the next inset
2018 pushBackward(nextMath());
2019 inset().idxFirst(*this);
2024 if (inset().idxForward(*this))
2026 // try to pop forwards --- but don't pop out of math! leave that to
2028 int s = depth() - 2;
2029 if (s >= 0 && operator[](s).inset().asInsetMath())
2030 return popForward();
2035 bool Cursor::mathBackward(bool word)
2037 LASSERT(inMathed(), return false);
2040 // word: skip a group of insets. See the comment in mathForward.
2041 MathClass mc = prevMath().mathClass();
2044 while (pos() > 0 && mc == prevMath().mathClass());
2045 if (pos() > 0 && (mc == MC_BIN || mc == MC_REL || mc == MC_PUNCT)) {
2046 mc = prevMath().mathClass();
2049 while (pos() > 0 && mc == prevMath().mathClass());
2051 } else if (openable(prevAtom())) {
2052 // single step: try to enter the preceding inset
2055 inset().idxLast(*this);
2060 if (inset().idxBackward(*this))
2062 // try to pop backwards --- but don't pop out of math! leave that to
2064 int s = depth() - 2;
2065 if (s >= 0 && operator[](s).inset().asInsetMath())
2066 return popBackward();
2071 bool Cursor::upDownInText(bool up, bool & updateNeeded)
2073 LASSERT(text(), return false);
2079 xo = beforeDispatchPosX_;
2081 // update the targetX - this is here before the "return false"
2082 // to set a new target which can be used by InsetTexts above
2083 // if we cannot move up/down inside this inset anymore
2084 if (x_target_ == -1)
2086 else if (xo - textTargetOffset() != x_target() &&
2087 depth() == beforeDispatchCursor_.depth()) {
2088 // In text mode inside the line (not left or right)
2089 // possibly set a new target_x, but only if we are
2090 // somewhere else than the previous target-offset.
2092 // We want to keep the x-target on subsequent up/down
2093 // movements that cross beyond the end of short lines.
2094 // Thus a special handling when the cursor is at the
2095 // end of line: Use the new x-target only if the old
2096 // one was before the end of line or the old one was
2097 // after the beginning of the line
2098 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
2102 left = pos() == textRow().endpos();
2103 right = pos() == textRow().pos();
2105 left = pos() == textRow().pos();
2106 right = pos() == textRow().endpos();
2108 if ((!left && !right) ||
2109 (left && !right && xo < x_target_) ||
2110 (!left && right && x_target_ < xo))
2117 // first get the current line
2118 TextMetrics & tm = bv_->textMetrics(text());
2119 ParagraphMetrics const & pm = tm.parMetrics(pit());
2121 if (pos() && boundary())
2122 row = pm.pos2row(pos() - 1);
2124 row = pm.pos2row(pos());
2126 if (atFirstOrLastRow(up)) {
2127 // Is there a place for the cursor to go ? If yes, we
2128 // can execute the DEPM, otherwise we should keep the
2129 // paragraph to host the cursor.
2130 Cursor dummy = *this;
2131 bool valid_destination = false;
2132 for(; dummy.depth(); dummy.pop())
2133 if (!dummy.atFirstOrLastRow(up)) {
2134 valid_destination = true;
2138 // will a next dispatch follow and if there is a new
2139 // dispatch will it move the cursor out ?
2140 if (depth() > 1 && valid_destination) {
2141 // The cursor hasn't changed yet. This happens when
2142 // you e.g. move out of an inset. And to give the
2143 // DEPM the possibility of doing something we must
2144 // provide it with two different cursors. (Lgb, vfr)
2146 dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
2147 dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
2149 updateNeeded |= bv().checkDepm(dummy, *this);
2150 updateTextTargetOffset();
2152 forceBufferUpdate();
2157 // with and without selection are handled differently
2159 int yo1 = bv().getPos(*this).y_;
2161 // To next/previous row
2162 // FIXME: the y position is often guessed wrongly across styles and
2163 // insets, which leads to weird behaviour.
2165 tm.editXY(*this, xo, yo1 - textRow().ascent() - 1);
2167 tm.editXY(*this, xo, yo1 + textRow().descent() + 1);
2168 x_target_ = old.x_target_;
2171 // This happens when you move out of an inset.
2172 // And to give the DEPM the possibility of doing
2173 // something we must provide it with two different
2175 Cursor dummy = *this;
2178 if (bv().checkDepm(dummy, old)) {
2179 updateNeeded = true;
2180 // Make sure that cur gets back whatever happened to dummy (Lgb)
2183 if (inTexted() && pos() && paragraph().isEnvSeparator(pos() - 1))
2186 // if there is a selection, we stay out of any inset,
2187 // and just jump to the right position:
2193 } else if (pit() > 0) {
2195 TextMetrics & tm2 = bv_->textMetrics(text());
2196 if (!tm2.contains(pit()))
2197 tm2.newParMetricsUp();
2198 ParagraphMetrics const & pmcur = tm2.parMetrics(pit());
2199 next_row = pmcur.rows().size() - 1;
2202 if (row + 1 < int(pm.rows().size())) {
2204 } else if (pit() + 1 < int(text()->paragraphs().size())) {
2206 TextMetrics & tm2 = bv_->textMetrics(text());
2207 if (!tm2.contains(pit()))
2208 tm2.newParMetricsDown();
2213 Row const & real_next_row = tm.parMetrics(pit()).rows()[next_row];
2215 top().pos() = tm.getPosNearX(real_next_row, xo, bound);
2217 // When selection==false, this is done by TextMetrics::editXY
2220 updateNeeded |= bv().checkDepm(*this, old);
2224 forceBufferUpdate();
2225 updateTextTargetOffset();
2230 void Cursor::handleFont(string const & font)
2232 LYXERR(Debug::DEBUG, font);
2236 safe = cap::grabAndEraseSelection(*this);
2241 if (lastpos() != 0) {
2242 // something left in the cell
2244 // cursor in first position
2246 } else if (pos() == lastpos()) {
2247 // cursor in last position
2250 // cursor in between. split cell
2251 MathData::iterator bt = cell().begin();
2252 MathAtom at = createInsetMath(from_utf8(font), buffer());
2253 at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
2254 cell().erase(bt, bt + pos());
2259 // nothing left in the cell
2268 void Cursor::undispatched() const
2270 disp_.dispatched(false);
2274 void Cursor::dispatched() const
2276 disp_.dispatched(true);
2280 void Cursor::screenUpdateFlags(Update::flags f) const
2282 disp_.screenUpdate(f);
2286 void Cursor::noScreenUpdate() const
2288 disp_.screenUpdate(Update::None);
2292 void Cursor::forceBufferUpdate() const
2294 disp_.forceBufferUpdate();
2298 void Cursor::clearBufferUpdate() const
2300 disp_.clearBufferUpdate();
2304 bool Cursor::needBufferUpdate() const
2306 return disp_.needBufferUpdate();
2310 Font Cursor::getFont() const
2312 // The logic here should more or less match to the
2313 // Cursor::setCurrentFont logic, i.e. the cursor height should
2314 // give a hint what will happen if a character is entered.
2315 // FIXME: this is not the case, what about removing this method ? (see #10478).
2317 // HACK. far from being perfect...
2319 CursorSlice const & sl = innerTextSlice();
2320 Text const & text = *sl.text();
2321 Paragraph const & par = text.getPar(sl.pit());
2323 // on boundary, so we are really at the character before
2324 pos_type pos = sl.pos();
2325 if (pos > 0 && boundary())
2328 // on space? Take the font before (only for RTL boundary stay)
2330 TextMetrics const & tm = bv().textMetrics(&text);
2331 if (pos == sl.lastpos()
2332 || (par.isSeparator(pos)
2333 && !tm.isRTLBoundary(sl.pit(), pos)))
2337 // get font at the position
2338 Font font = par.getFont(buffer()->params(), pos,
2339 text.outerFont(sl.pit()));
2345 void Cursor::sanitize()
2347 setBuffer(&bv_->buffer());
2348 CursorData::sanitize();
2352 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2354 // find inset in common
2356 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2357 if (&old[i].inset() != &cur[i].inset())
2361 // update words if we just moved to another paragraph
2362 if (i == old.depth() && i == cur.depth()
2363 && !cur.buffer()->isClean()
2364 && cur.inTexted() && old.inTexted()
2365 && cur.pit() != old.pit()) {
2366 old.paragraph().updateWords();
2369 // notify everything on top of the common part in old cursor,
2370 // but stop if the inset claims the cursor to be invalid now
2371 for (size_type j = i; j < old.depth(); ++j) {
2372 Cursor inset_pos = old;
2373 inset_pos.cutOff(j);
2374 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2378 // notify everything on top of the common part in new cursor,
2379 // but stop if the inset claims the cursor to be invalid now
2380 for (; i < cur.depth(); ++i) {
2381 if (cur[i].inset().notifyCursorEnters(cur))
2389 void Cursor::setCurrentFont()
2391 CursorSlice const & cs = innerTextSlice();
2392 Paragraph const & par = cs.paragraph();
2393 pos_type cpit = cs.pit();
2394 pos_type cpos = cs.pos();
2395 Text const & ctext = *cs.text();
2396 TextMetrics const & tm = bv().textMetrics(&ctext);
2398 // are we behind previous char in fact? -> go to that char
2399 if (cpos > 0 && boundary())
2402 // find position to take the font from
2404 // paragraph end? -> font of last char
2405 if (cpos == lastpos())
2407 // on space? -> look at the words in front of space
2408 else if (cpos > 0 && par.isSeparator(cpos)) {
2409 // abc| def -> font of c
2410 // abc |[WERBEH], i.e. boundary==true -> font of c
2411 // abc [WERBEH]| def, font of the space
2412 if (!tm.isRTLBoundary(cpit, cpos))
2418 BufferParams const & bufparams = buffer()->params();
2419 current_font = par.getFontSettings(bufparams, cpos);
2420 real_current_font = tm.displayFont(cpit, cpos);
2422 // special case for paragraph end
2423 if (cs.pos() == lastpos()
2424 && tm.isRTLBoundary(cpit, cs.pos())
2426 Language const * lang = par.getParLanguage(bufparams);
2427 current_font.setLanguage(lang);
2428 current_font.fontInfo().setNumber(FONT_OFF);
2429 real_current_font.setLanguage(lang);
2430 real_current_font.fontInfo().setNumber(FONT_OFF);
2435 void Cursor::checkBufferStructure()
2437 Buffer const * master = buffer()->masterBuffer();
2438 master->tocBackend().updateItem(*this);
2439 if (master != buffer() && !master->hasGuiDelegate())
2440 // In case the master has no gui associated with it,
2441 // the TocItem is not updated (part of bug 5699).
2442 buffer()->tocBackend().updateItem(*this);
2444 // If the last tracked change of the paragraph has just been
2445 // deleted, then we need to recompute the buffer flag
2446 // tracked_changes_present_.
2447 if (inTexted() && paragraph().isChangeUpdateRequired())
2448 disp_.forceChangesUpdate();
2452 void Cursor::moveToClosestEdge(int const x, bool const edit)
2454 if (Inset const * inset = nextInset()) {
2455 // stay in front of insets for which we want to open the dialog
2456 // (e.g. InsetMathSpace).
2457 if (edit && (inset->hasSettings() || !inset->contextMenuName().empty()))
2459 CoordCache::Insets const & insetCache = bv().coordCache().getInsets();
2460 if (!insetCache.has(inset))
2462 int const wid = insetCache.dim(inset).wid;
2463 Point p = insetCache.xy(inset);
2464 if (x > p.x_ + (wid + 1) / 2)