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::splitUndoGroup() const
612 buffer()->undo().splitUndoGroup(*this);
616 void CursorData::recordUndo(pit_type from, pit_type to) const
618 buffer()->undo().recordUndo(*this, from, to);
622 void CursorData::recordUndo(pit_type from) const
624 buffer()->undo().recordUndo(*this, from, pit());
628 void CursorData::recordUndo(UndoKind kind) const
630 buffer()->undo().recordUndo(*this, kind);
634 void CursorData::recordUndoInset(Inset const * in) const
636 buffer()->undo().recordUndoInset(*this, in);
640 void CursorData::recordUndoFullBuffer() const
642 buffer()->undo().recordUndoFullBuffer(*this);
646 void CursorData::recordUndoBufferParams() const
648 buffer()->undo().recordUndoBufferParams(*this);
652 void CursorData::recordUndoSelection() const
655 if (cap::multipleCellsSelected(*this))
660 buffer()->undo().recordUndo(*this,
661 selBegin().pit(), selEnd().pit());
666 int CursorData::currentMode()
668 LASSERT(!empty(), return Inset::UNDECIDED_MODE);
669 for (int i = depth() - 1; i >= 0; --i) {
670 int res = operator[](i).inset().currentMode();
671 bool locked_mode = operator[](i).inset().lockedMode();
672 // Also return UNDECIDED_MODE when the mode is locked,
673 // as in this case it is treated the same as TEXT_MODE
674 if (res != Inset::UNDECIDED_MODE || locked_mode)
677 return Inset::TEXT_MODE;
681 bool CursorData::confirmDeletion(bool const before) const
684 if (Inset const * inset = before ? prevInset() : nextInset())
685 return inset->confirmDeletion();
687 DocIterator dit = selectionBegin();
688 CursorSlice const end = selectionEnd().top();
689 for (; dit.top() < end; dit.top().forwardPos())
690 if (Inset const * inset = dit.nextInset())
691 if (inset->confirmDeletion())
704 // be careful: this is called from the bv's constructor, too, so
705 // bv functions are not yet available!
706 Cursor::Cursor(BufferView & bv)
707 : CursorData(&bv.buffer()), bv_(&bv),
708 x_target_(-1), textTargetOffset_(0),
709 beforeDispatchPosX_(0), beforeDispatchPosY_(0)
720 void Cursor::setCursorData(CursorData const & data)
722 CursorData::operator=(data);
726 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
730 // Try to fix cursor in case it is broken.
733 // Is this a function that acts on inset at point?
734 Inset * inset = cur.nextInset();
735 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
736 && inset && inset->getStatus(cur, cmd, status))
739 // This is, of course, a mess. Better create a new doc iterator and use
740 // this in Inset::getStatus. This might require an additional
741 // BufferView * arg, though (which should be avoided)
742 //Cursor safe = *this;
744 for ( ; cur.depth(); cur.pop()) {
745 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
746 // LASSERT: Is it safe to continue here, or should we return?
747 LASSERT(cur.idx() <= cur.lastidx(), /**/);
748 LASSERT(cur.pit() <= cur.lastpit(), /**/);
749 LASSERT(cur.pos() <= cur.lastpos(), /**/);
751 // The inset's getStatus() will return 'true' if it made
752 // a definitive decision on whether it want to handle the
753 // request or not. The result of this decision is put into
754 // the 'status' parameter.
755 if (cur.inset().getStatus(cur, cmd, status)) {
764 void Cursor::saveBeforeDispatchPosXY()
766 getPos(beforeDispatchPosX_, beforeDispatchPosY_);
770 void Cursor::dispatch(FuncRequest const & cmd0)
772 LYXERR(Debug::ACTION, "Cursor::dispatch: cmd: " << cmd0 << '\n' << *this);
777 FuncRequest cmd = cmd0;
780 disp_ = DispatchResult();
784 // Is this a function that acts on inset at point?
785 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
787 disp_.dispatched(true);
788 disp_.screenUpdate(Update::FitCursor | Update::Force);
789 FuncRequest tmpcmd = cmd;
790 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
791 << cmd0 << endl << *this);
792 nextInset()->dispatch(*this, tmpcmd);
793 if (disp_.dispatched()) {
799 // store some values to be used inside of the handlers
800 beforeDispatchCursor_ = *this;
801 for (; depth(); pop(), boundary(false)) {
802 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
803 << cmd0 << endl << *this);
805 // In any of these cases, the cursor is invalid, and we should
806 // try to save this document rather than crash.
807 LBUFERR(pos() <= lastpos());
808 LBUFERR(idx() <= lastidx());
809 LBUFERR(pit() <= lastpit());
811 // The common case is 'LFUN handled, need update', so make the
812 // LFUN handler's life easier by assuming this as default value.
813 // The handler can reset the update and val flags if necessary.
814 disp_.screenUpdate(Update::FitCursor | Update::Force);
815 disp_.dispatched(true);
816 inset().dispatch(*this, cmd);
817 if (disp_.dispatched())
821 // it completely to get a 'bomb early' behaviour in case this
822 // object will be used again.
823 if (!disp_.dispatched()) {
824 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
825 // We might have invalidated the cursor when removing an empty
826 // paragraph while the cursor could not be moved out the inset
827 // while we initially thought we could. This might happen when
828 // a multiline inset becomes an inline inset when the second
829 // paragraph is removed.
830 if (safe.pit() > safe.lastpit()) {
831 safe.pit() = safe.lastpit();
832 safe.pos() = safe.lastpos();
835 disp_.screenUpdate(Update::None);
836 disp_.dispatched(false);
838 // restore the previous one because nested Cursor::dispatch calls
839 // are possible which would change it
840 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
844 // NOTE: The code below has been copied to BufferView::dispatch.
845 // If you need to modify this, please update the other one too.
847 // notify insets we just left
849 old.beginUndoGroup();
851 bool badcursor = notifyCursorLeavesOrEnters(old, *this);
854 bv().resetInlineCompletionPos();
861 DispatchResult const & Cursor::result() const
867 void Cursor::message(docstring const & msg) const
869 disp_.setMessage(msg);
873 void Cursor::errorMessage(docstring const & msg) const
875 disp_.setMessage(msg);
876 disp_.setError(true);
880 BufferView & Cursor::bv() const
889 LBUFERR(depth() >= 1);
894 void Cursor::push(Inset & p)
896 push_back(CursorSlice(p));
897 p.setBuffer(*buffer());
901 void Cursor::pushBackward(Inset & p)
903 LASSERT(!empty(), return);
904 //lyxerr << "Entering inset " << t << " front" << endl;
910 void Cursor::editInsertedInset()
912 LASSERT(!empty(), return);
916 InsetMath &p = prevMath();
923 // this could be a while() loop, but only one cell is not empty in
924 // cases we are interested in. The cell is not empty because we
925 // have inserted the selection in there.
926 if (!cell().empty()) {
927 // if it is not empty, move to the next one.
928 if (!inset().idxNext(*this))
929 // If there is no next one, exit the inset.
935 bool Cursor::popBackward()
937 LASSERT(!empty(), return false);
945 bool Cursor::popForward()
947 LASSERT(!empty(), return false);
948 //lyxerr << "Leaving inset from in back" << endl;
949 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
953 pos() += lastpos() - lp + 1;
958 void Cursor::getPos(int & x, int & y) const
960 Point p = bv().getPos(*this);
966 Row const & Cursor::textRow() const
968 CursorSlice const & cs = innerTextSlice();
969 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
970 return pm.getRow(pos(), boundary());
974 bool Cursor::posVisRight(bool skip_inset)
976 Cursor new_cur = *this; // where we will move to
977 pos_type left_pos; // position visually left of current cursor
978 pos_type right_pos; // position visually right of current cursor
980 getSurroundingPos(left_pos, right_pos);
982 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
984 // Are we at an inset?
985 new_cur.pos() = right_pos;
986 new_cur.boundary(false);
988 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
989 // we actually move the cursor at the end of this
990 // function, for now we just keep track of the new
991 // position in new_cur...
992 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
995 // Are we already at rightmost pos in row?
996 else if (text()->empty() || right_pos == -1) {
999 if (!new_cur.posVisToNewRow(false)) {
1000 LYXERR(Debug::RTL, "not moving!");
1004 // we actually move the cursor at the end of this
1005 // function, for now just keep track of the new
1006 // position in new_cur...
1007 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
1008 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
1011 // normal movement to the right
1014 // Recall, if the cursor is at position 'x', that
1015 // means *before* the character at position 'x'. In
1016 // RTL, "before" means "to the right of", in LTR, "to
1017 // the left of". So currently our situation is this:
1018 // the position to our right is 'right_pos' (i.e.,
1019 // we're currently to the left of 'right_pos'). In
1020 // order to move to the right, it depends whether or
1021 // not the character at 'right_pos' is RTL.
1022 bool const new_pos_is_RTL = paragraph().getFontSettings(
1023 buffer()->params(), right_pos).isVisibleRightToLeft();
1024 // If the character at 'right_pos' *is* LTR, then in
1025 // order to move to the right of it, we need to be
1026 // *after* 'right_pos', i.e., move to position
1028 if (!new_pos_is_RTL) {
1029 new_cur.pos() = right_pos + 1;
1030 // set the boundary to true in two situations:
1032 // 1. if new_pos is now lastpos, and we're in
1033 // an RTL paragraph (this means that we're
1034 // moving right to the end of an LTR chunk
1035 // which is at the end of an RTL paragraph);
1036 (new_cur.pos() == lastpos()
1037 && paragraph().isRTL(buffer()->params()))
1038 // 2. if the position *after* right_pos is RTL
1039 // (we want to be *after* right_pos, not
1040 // before right_pos + 1!)
1041 || paragraph().getFontSettings(buffer()->params(),
1042 new_cur.pos()).isVisibleRightToLeft()
1044 new_cur.boundary(true);
1045 else // set the boundary to false
1046 new_cur.boundary(false);
1048 // Otherwise (if the character at position 'right_pos'
1049 // is RTL), then moving to the right of it is as easy
1050 // as setting the new position to 'right_pos'.
1052 new_cur.pos() = right_pos;
1053 new_cur.boundary(false);
1058 bool const moved = new_cur != *this || new_cur.boundary() != boundary();
1061 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
1062 << (new_cur.boundary() ? " (boundary)" : ""));
1070 bool Cursor::posVisLeft(bool skip_inset)
1072 Cursor new_cur = *this; // where we will move to
1073 pos_type left_pos; // position visually left of current cursor
1074 pos_type right_pos; // position visually right of current cursor
1076 getSurroundingPos(left_pos, right_pos);
1078 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
1080 // Are we at an inset?
1081 new_cur.pos() = left_pos;
1082 new_cur.boundary(false);
1084 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
1085 // we actually move the cursor at the end of this
1086 // function, for now we just keep track of the new
1087 // position in new_cur...
1088 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
1091 // Are we already at leftmost pos in row?
1092 else if (text()->empty() || left_pos == -1) {
1095 if (!new_cur.posVisToNewRow(true)) {
1096 LYXERR(Debug::RTL, "not moving!");
1100 // we actually move the cursor at the end of this
1101 // function, for now just keep track of the new
1102 // position in new_cur...
1103 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
1104 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
1107 // normal movement to the left
1110 // Recall, if the cursor is at position 'x', that
1111 // means *before* the character at position 'x'. In
1112 // RTL, "before" means "to the right of", in LTR, "to
1113 // the left of". So currently our situation is this:
1114 // the position to our left is 'left_pos' (i.e., we're
1115 // currently to the right of 'left_pos'). In order to
1116 // move to the left, it depends whether or not the
1117 // character at 'left_pos' is RTL.
1118 bool const new_pos_is_RTL = paragraph().getFontSettings(
1119 buffer()->params(), left_pos).isVisibleRightToLeft();
1120 // If the character at 'left_pos' *is* RTL, then in
1121 // order to move to the left of it, we need to be
1122 // *after* 'left_pos', i.e., move to position
1124 if (new_pos_is_RTL) {
1125 new_cur.pos() = left_pos + 1;
1126 // set the boundary to true in two situations:
1128 // 1. if new_pos is now lastpos and we're in
1129 // an LTR paragraph (this means that we're
1130 // moving left to the end of an RTL chunk
1131 // which is at the end of an LTR paragraph);
1132 (new_cur.pos() == lastpos()
1133 && !paragraph().isRTL(buffer()->params()))
1134 // 2. if the position *after* left_pos is not
1135 // RTL (we want to be *after* left_pos, not
1136 // before left_pos + 1!)
1137 || !paragraph().getFontSettings(buffer()->params(),
1138 new_cur.pos()).isVisibleRightToLeft()
1140 new_cur.boundary(true);
1141 else // set the boundary to false
1142 new_cur.boundary(false);
1144 // Otherwise (if the character at position 'left_pos'
1145 // is LTR), then moving to the left of it is as easy
1146 // as setting the new position to 'left_pos'.
1148 new_cur.pos() = left_pos;
1149 new_cur.boundary(false);
1154 bool const moved = new_cur != *this || new_cur.boundary() != boundary();
1157 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
1158 << (new_cur.boundary() ? " (boundary)" : ""));
1168 // Return true on success
1169 bool findNonVirtual(Row const & row, Row::const_iterator & cit, bool onleft)
1172 while (cit != row.begin() && cit->isVirtual())
1175 while (cit != row.end() && cit->isVirtual())
1178 return cit != row.end() && !cit->isVirtual();
1183 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos) const
1185 // by default, we know nothing.
1189 Row const & row = textRow();
1191 Row::const_iterator cit = row.findElement(pos(), boundary(), dummy);
1192 // Handle the case of empty row
1193 if (cit == row.end()) {
1195 right_pos = row.pos();
1197 left_pos = row.pos() - 1;
1201 // skip virtual elements and exit if no non-virtual one exists
1202 if (!findNonVirtual(row, cit, !cit->isRTL()))
1205 // if the position is at the left side of the element, we have to
1206 // look at the previous element
1207 if (pos() == cit->left_pos()) {
1208 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1209 << "), AT LEFT of *cit=" << *cit);
1210 // this one is easy (see common case below)
1211 right_pos = pos() - (cit->isRTL() ? 1 : 0);
1212 // at the left of the row
1213 if (cit == row.begin())
1216 if (!findNonVirtual(row, cit, true))
1218 // [...[ is the row element, | is cursor position (! with boundary)
1219 // [ 1 2 [ is a ltr row element with pos=1 and endpos=3
1220 // ] 2 1] is an rtl row element with pos=1 and endpos=3
1221 // [ 1 2 [ [|3 4 [ => (2, 3)
1222 // or [ 1 2 [ ]!4 3 ] => (2, 4)
1223 // or ] 2 1 ] [|3 4 [ => (1, 3)
1224 // or ] 4 3 ] ]!2 1 ] => (3, 2)
1225 left_pos = cit->right_pos() - (cit->isRTL() ? 0 : 1);
1226 // happens with consecutive row of same direction
1227 if (left_pos == right_pos) {
1228 left_pos += cit->isRTL() ? 1 : -1;
1231 // same code but with the element at the right
1232 else if (pos() == cit->right_pos()) {
1233 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1234 << "), AT RIGHT of *cit=" << *cit);
1235 // this one is easy (see common case below)
1236 left_pos = pos() - (cit->isRTL() ? 0 : 1);
1237 // at the right of the row
1238 if (cit + 1 == row.end())
1241 if (!findNonVirtual(row, cit, false))
1243 // [ 1 2![ [ 3 4 [ => (2, 3)
1244 // or [ 1 2![ ] 4 3 ] => (2, 4)
1245 // or ] 2 1|] [ 3 4 [ => (1, 3)
1246 // or ] 4 3|] ] 2 1 ] => (3, 2)
1247 right_pos = cit->left_pos() - (cit->isRTL() ? 1 : 0);
1248 // happens with consecutive row of same direction
1249 if (right_pos == left_pos)
1250 right_pos += cit->isRTL() ? -1 : 1;
1252 // common case: both positions are inside the row element
1254 // [ 1 2|3 [ => (2, 3)
1255 // or ] 3|2 1 ] => (3, 2)
1256 left_pos = pos() - (cit->isRTL() ? 0 : 1);
1257 right_pos = pos() - (cit->isRTL() ? 1 : 0);
1260 // Note that debug message does not catch all early returns above
1261 LYXERR(Debug::RTL,"getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1262 << ") => (" << left_pos << ", " << right_pos <<")");
1266 bool Cursor::posVisToNewRow(bool movingLeft)
1268 Row const & row = textRow();
1269 bool par_is_LTR = !row.isRTL();
1271 // Inside a table, determining whether to move to the next or
1272 // previous row should be done based on the table's direction.
1273 if (inset().asInsetTabular()) {
1274 par_is_LTR = !inset().asInsetTabular()->isRightToLeft(*this);
1275 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
1278 // if moving left in an LTR paragraph or moving right in an
1279 // RTL one, move to previous row
1280 if (par_is_LTR == movingLeft) {
1281 if (row.pos() == 0) { // we're at first row in paragraph
1282 if (pit() == 0) // no previous paragraph! don't move
1284 // move to last pos in previous par
1288 } else { // move to previous row in this par
1289 pos() = row.pos() - 1; // this is guaranteed to be in previous row
1293 // if moving left in an RTL paragraph or moving right in an
1294 // LTR one, move to next row
1296 if (row.endpos() == lastpos()) { // we're at last row in paragraph
1297 if (pit() == lastpit()) // last paragraph! don't move
1299 // move to first row in next par
1303 } else { // move to next row in this par
1304 pos() = row.endpos();
1309 // make sure we're at left-/right-most pos in new row
1310 posVisToRowExtremity(!movingLeft);
1316 void Cursor::posVisToRowExtremity(bool left)
1318 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
1319 << (boundary() ? 1 : 0));
1321 TextMetrics const & tm = bv_->textMetrics(text());
1322 // Looking for extremities is like clicking on the left or the
1323 // right of the row.
1324 int x = tm.origin().x_ + (left ? 0 : textRow().width());
1326 pos() = tm.getPosNearX(textRow(), x, b);
1329 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
1330 << (boundary() ? 1 : 0));
1334 bool Cursor::reverseDirectionNeeded() const
1337 * We determine the directions based on the direction of the
1338 * bottom() --- i.e., outermost --- paragraph, because that is
1339 * the only way to achieve consistency of the arrow's movements
1340 * within a paragraph, and thus avoid situations in which the
1341 * cursor gets stuck.
1343 return bottom().paragraph().isRTL(bv().buffer().params());
1347 void Cursor::setTargetX(int x)
1350 textTargetOffset_ = 0;
1354 int Cursor::x_target() const
1360 void Cursor::clearTargetX()
1363 textTargetOffset_ = 0;
1367 void Cursor::updateTextTargetOffset()
1372 textTargetOffset_ = x - x_target_;
1376 bool Cursor::selHandle(bool sel)
1378 //lyxerr << "Cursor::selHandle" << endl;
1381 if (sel == selection())
1385 cap::saveSelection(*this);
1393 bool Cursor::atFirstOrLastRow(bool up)
1395 TextMetrics const & tm = bv_->textMetrics(text());
1396 ParagraphMetrics const & pm = tm.parMetrics(pit());
1399 if (pos() && boundary())
1400 row = pm.pos2row(pos() - 1);
1402 row = pm.pos2row(pos());
1405 if (pit() == 0 && row == 0)
1408 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1409 row + 1 >= int(pm.rows().size()))
1419 ///////////////////////////////////////////////////////////////////
1422 // The part below is the non-integrated rest of the original math
1423 // cursor. This should be either generalized for texted or moved
1424 // back to mathed (in most cases to InsetMathNest).
1426 ///////////////////////////////////////////////////////////////////
1428 #include "mathed/InsetMathChar.h"
1429 #include "mathed/InsetMathGrid.h"
1430 #include "mathed/InsetMathScript.h"
1431 #include "mathed/InsetMathUnknown.h"
1432 #include "mathed/MathFactory.h"
1433 #include "mathed/MathStream.h"
1434 #include "mathed/MathSupport.h"
1439 bool Cursor::openable(MathAtom const & t) const
1450 // we can't move into anything new during selection
1451 if (depth() >= realAnchor().depth())
1453 if (t.nucleus() != &realAnchor()[depth()].inset())
1460 void Cursor::plainErase()
1462 cell().erase(pos());
1466 void Cursor::plainInsert(MathAtom const & t)
1468 cell().insert(pos(), t);
1470 inset().setBuffer(bv_->buffer());
1472 checkBufferStructure();
1476 void Cursor::insert(char_type c)
1478 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1479 LASSERT(!empty(), return);
1481 cap::selClearOrDel(*this);
1482 insert(new InsetMathChar(c));
1484 text()->insertChar(*this, c);
1489 void Cursor::insert(docstring const & str)
1491 for (char_type c : str)
1496 void Cursor::insert(Inset * inset0)
1498 LASSERT(inset0, return);
1500 insert(MathAtom(inset0->asInsetMath()));
1502 text()->insertInset(*this, inset0);
1503 inset0->setBuffer(bv_->buffer());
1505 if (inset0->isLabeled())
1506 forceBufferUpdate();
1511 void Cursor::insert(MathAtom const & t)
1513 LATTEST(inMathed());
1514 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1516 cap::selClearOrDel(*this);
1521 void Cursor::insert(MathData const & ar)
1523 LATTEST(inMathed());
1526 cap::eraseSelection(*this);
1527 cell().insert(pos(), ar);
1529 // FIXME audit setBuffer calls
1530 inset().setBuffer(bv_->buffer());
1534 int Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1536 LATTEST(inMathed());
1537 MathData ar(buffer());
1539 if (ar.size() == 1 && (enter || selection()))
1547 void Cursor::niceInsert(MathAtom const & t)
1549 LATTEST(inMathed());
1551 docstring const safe = cap::grabAndEraseSelection(*this);
1553 // If possible, enter the new inset and move the contents of the selection
1554 if (t->isActive()) {
1555 idx_type const idx = prevMath().asNestInset()->firstIdx();
1556 MathData ar(buffer());
1558 prevMath().cell(idx).insert(0, ar);
1559 editInsertedInset();
1560 } else if (t->asMacro() && !safe.empty()) {
1561 MathData ar(buffer());
1563 docstring const name = t->asMacro()->name();
1564 MacroData const * data = buffer()->getMacro(name);
1565 if (data && data->numargs() - data->optionals() > 0) {
1566 plainInsert(MathAtom(new InsetMathBrace(ar)));
1573 bool Cursor::backspace(bool const force)
1576 cap::eraseSelection(*this);
1581 // If empty cell, and not part of a big cell
1582 if (lastpos() == 0 && inset().nargs() == 1) {
1584 // Directly delete empty cell: [|[]] => [|]
1590 // [|], can not delete from inside
1601 if (inMacroMode()) {
1602 InsetMathUnknown * p = activeMacro();
1603 if (p->name().size() > 1) {
1604 p->setName(p->name().substr(0, p->name().size() - 1));
1609 if (pos() != 0 && !force && prevAtom()->confirmDeletion()) {
1610 // let's require two backspaces for 'big stuff' and
1611 // highlight on the first
1623 bool Cursor::erase(bool const force)
1629 cap::eraseSelection(*this);
1633 // delete empty cells if possible
1634 if (pos() == lastpos() && inset().idxDelete(idx()))
1637 // special behaviour when in last position of cell
1638 if (pos() == lastpos()) {
1639 bool one_cell = inset().nargs() == 1;
1640 if (one_cell && lastpos() == 0) {
1642 // Directly delete empty cell: [|[]] => [|]
1648 // [|], can not delete from inside
1653 inset().idxGlue(idx());
1657 // 'clever' UI hack: only erase large items if previously slected
1658 if (pos() != lastpos() && !force && nextAtom()->confirmDeletion()) {
1673 DocIterator save = *this;
1674 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1675 this->dispatch(cmd);
1676 if (disp_.dispatched())
1686 DocIterator save = *this;
1687 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1688 this->dispatch(cmd);
1689 if (disp_.dispatched())
1696 void Cursor::handleNest(MathAtom const & a)
1698 idx_type const idx = a.nucleus()->asNestInset()->firstIdx();
1699 //lyxerr << "Cursor::handleNest: " << idx << endl;
1701 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(idx));
1703 editInsertedInset();
1707 int Cursor::targetX() const
1709 if (x_target() != -1)
1718 int Cursor::textTargetOffset() const
1720 return textTargetOffset_;
1724 void Cursor::setTargetX()
1733 bool Cursor::macroModeClose(bool cancel)
1737 InsetMathUnknown * p = activeMacro();
1739 MathData selection(buffer());
1740 asArray(p->selection(), selection);
1741 docstring const s = p->name();
1743 cell().erase(pos());
1745 // trigger updates of macros, at least, if no full
1746 // updates take place anyway
1747 screenUpdateFlags(Update::Force);
1749 // do nothing if the macro name is empty
1750 if (s == "\\" || cancel) {
1754 docstring const name = s.substr(1);
1755 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1756 if (in && in->interpretString(*this, s))
1758 bool const user_macro = buffer()->getMacro(name, *this, false);
1759 MathAtom atom = user_macro ? MathAtom(new InsetMathMacro(buffer(), name))
1760 : createInsetMath(name, buffer());
1762 // try to put argument into macro, if we just inserted a macro
1763 bool macroArg = false;
1764 InsetMathMacro * atomAsMacro = atom.nucleus()->asMacro();
1765 InsetMathNest * atomAsNest = atom.nucleus()->asNestInset();
1767 // macros here are still unfolded (in init mode in fact). So
1768 // we have to resolve the macro here manually and check its arity
1769 // to put the selection behind it if arity > 0.
1770 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1771 if (!selection.empty() && data && data->numargs() - data->optionals() > 0) {
1773 atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1775 // non-greedy case. Do not touch the arguments behind
1776 atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1779 // insert remembered selection into first argument of a non-macro
1780 else if (atomAsNest && atomAsNest->nargs() > 0)
1781 atomAsNest->cell(atomAsNest->firstIdx()).append(selection);
1783 MathWordList const & words = mathedWordList();
1784 MathWordList::const_iterator it = words.find(name);
1785 bool keep_mathmode = user_macro
1786 || (it != words.end() && (it->second.inset == "font"
1787 || it->second.inset == "oldfont"
1788 || it->second.inset == "mbox"));
1789 bool ert_macro = !user_macro && it == words.end() && atomAsMacro;
1791 if (in && in->currentMode() == Inset::TEXT_MODE
1792 && atom.nucleus()->currentMode() == Inset::MATH_MODE
1793 && name != from_ascii("ensuremath") && !ert_macro) {
1794 MathAtom at(new InsetMathEnsureMath(buffer()));
1795 at.nucleus()->cell(0).push_back(atom);
1798 } else if (in && in->currentMode() == Inset::MATH_MODE
1799 && atom.nucleus()->currentMode() == Inset::TEXT_MODE
1800 && !keep_mathmode) {
1801 MathAtom at = createInsetMath("text", buffer());
1802 at.nucleus()->cell(0).push_back(atom);
1808 // finally put the macro argument behind, if needed
1810 if (selection.size() > 1 || selection[0]->asScriptInset())
1811 plainInsert(MathAtom(new InsetMathBrace(selection)));
1820 bool Cursor::inMacroMode() const
1824 if (pos() == 0 || cell().empty())
1826 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1827 return p && !p->final();
1831 InsetMathUnknown * Cursor::activeMacro()
1833 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1837 InsetMathUnknown const * Cursor::activeMacro() const
1839 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1843 docstring Cursor::macroName()
1845 return inMacroMode() ? activeMacro()->name() : docstring();
1849 void Cursor::pullArg()
1852 MathData ar = cell();
1853 if (popBackward() && inMathed()) {
1855 cell().insert(pos(), ar);
1858 //formula()->mutateToText();
1863 void Cursor::normalize()
1865 if (idx() > lastidx()) {
1866 lyxerr << "this should not really happen - 1: "
1867 << idx() << ' ' << nargs()
1868 << " in: " << &inset() << endl;
1872 if (pos() > lastpos()) {
1873 lyxerr << "this should not really happen - 2: "
1874 << pos() << ' ' << lastpos() << " in idx: " << idx()
1876 odocstringstream os;
1877 otexrowstream ots(os);
1878 WriteStream wi(ots, false, true, WriteStream::wsDefault);
1879 inset().asInsetMath()->write(wi);
1880 lyxerr << to_utf8(os.str()) << endl;
1886 bool Cursor::upDownInMath(bool up)
1888 // Be warned: The 'logic' implemented in this function is highly
1889 // fragile. A distance of one pixel or a '<' vs '<=' _really
1890 // matters. So fiddle around with it only if you think you know
1891 // what you are doing!
1895 xo = beforeDispatchPosX_;
1897 // check if we had something else in mind, if not, this is the future
1899 if (x_target_ == -1)
1901 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1902 // In text mode inside the line (not left or right) possibly set a new target_x,
1903 // but only if we are somewhere else than the previous target-offset.
1905 // We want to keep the x-target on subsequent up/down movements
1906 // that cross beyond the end of short lines. Thus a special
1907 // handling when the cursor is at the end of line: Use the new
1908 // x-target only if the old one was before the end of line
1909 // or the old one was after the beginning of the line
1910 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
1914 left = pos() == textRow().endpos();
1915 right = pos() == textRow().pos();
1917 left = pos() == textRow().pos();
1918 right = pos() == textRow().endpos();
1920 if ((!left && !right) ||
1921 (left && !right && xo < x_target_) ||
1922 (!left && right && x_target_ < xo))
1929 // try neigbouring script insets
1931 if (inMathed() && !selection()) {
1934 InsetMathScript const * p = prevAtom()->asScriptInset();
1935 if (p && p->has(up)) {
1937 push(*const_cast<InsetMathScript*>(p));
1938 idx() = p->idxOfScript(up);
1941 // we went in the right direction? Otherwise don't jump into the script
1945 int oy = beforeDispatchPosY_;
1946 if ((!up && y <= oy) ||
1955 if (pos() != lastpos()) {
1956 InsetMathScript const * p = nextAtom()->asScriptInset();
1957 if (p && p->has(up)) {
1958 push(*const_cast<InsetMathScript*>(p));
1959 idx() = p->idxOfScript(up);
1962 // we went in the right direction? Otherwise don't jump into the script
1966 int oy = beforeDispatchPosY_;
1967 if ((!up && y <= oy) ||
1976 // try to find an inset that knows better then we,
1977 if (inset().idxUpDown(*this, up)) {
1978 //lyxerr << "idxUpDown triggered" << endl;
1979 // try to find best position within this inset
1981 setCursor(bruteFind(*this, xo, yo));
1985 // any improvement going just out of inset?
1986 if (popBackward() && inMathed()) {
1987 //lyxerr << "updown: popBackward succeeded" << endl;
1990 int yold = beforeDispatchPosY_;
1992 if (up ? ynew < yold : ynew > yold)
1996 // no success, we are probably at the document top or bottom
2002 bool Cursor::mathForward(bool word)
2004 LASSERT(inMathed(), return false);
2005 if (pos() < lastpos()) {
2007 // word: skip a group of insets of the form X*(B*|R*|P*) (greedy
2008 // match) where X is any math class, B is mathbin, R is mathrel, and
2009 // P is mathpunct. Make sure that the following remains true:
2010 // mathForward(true); mathBackward(true); mathForward(true)
2011 // is the same as mathForward(true) and
2012 // mathBackward(true); mathForward(true); mathBackward(true)
2013 // is the same as mathBackward(true).
2014 MathClass mc = nextMath().mathClass();
2017 while (pos() < lastpos() && mc == nextMath().mathClass());
2018 if (pos() < lastpos() &&
2019 ((mc = nextMath().mathClass()) == MC_BIN ||
2020 mc == MC_REL || mc == MC_PUNCT))
2023 while (pos() < lastpos() && mc == nextMath().mathClass());
2024 } else if (openable(nextAtom())) {
2025 // single step: try to enter the next inset
2026 pushBackward(nextMath());
2027 inset().idxFirst(*this);
2032 if (inset().idxForward(*this))
2034 // try to pop forwards --- but don't pop out of math! leave that to
2036 int s = depth() - 2;
2037 if (s >= 0 && operator[](s).inset().asInsetMath())
2038 return popForward();
2043 bool Cursor::mathBackward(bool word)
2045 LASSERT(inMathed(), return false);
2048 // word: skip a group of insets. See the comment in mathForward.
2049 MathClass mc = prevMath().mathClass();
2052 while (pos() > 0 && mc == prevMath().mathClass());
2053 if (pos() > 0 && (mc == MC_BIN || mc == MC_REL || mc == MC_PUNCT)) {
2054 mc = prevMath().mathClass();
2057 while (pos() > 0 && mc == prevMath().mathClass());
2059 } else if (openable(prevAtom())) {
2060 // single step: try to enter the preceding inset
2063 inset().idxLast(*this);
2068 if (inset().idxBackward(*this))
2070 // try to pop backwards --- but don't pop out of math! leave that to
2072 int s = depth() - 2;
2073 if (s >= 0 && operator[](s).inset().asInsetMath())
2074 return popBackward();
2079 bool Cursor::upDownInText(bool up, bool & updateNeeded)
2081 LASSERT(text(), return false);
2087 xo = beforeDispatchPosX_;
2089 // update the targetX - this is here before the "return false"
2090 // to set a new target which can be used by InsetTexts above
2091 // if we cannot move up/down inside this inset anymore
2092 if (x_target_ == -1)
2094 else if (xo - textTargetOffset() != x_target() &&
2095 depth() == beforeDispatchCursor_.depth()) {
2096 // In text mode inside the line (not left or right)
2097 // possibly set a new target_x, but only if we are
2098 // somewhere else than the previous target-offset.
2100 // We want to keep the x-target on subsequent up/down
2101 // movements that cross beyond the end of short lines.
2102 // Thus a special handling when the cursor is at the
2103 // end of line: Use the new x-target only if the old
2104 // one was before the end of line or the old one was
2105 // after the beginning of the line
2106 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
2110 left = pos() == textRow().endpos();
2111 right = pos() == textRow().pos();
2113 left = pos() == textRow().pos();
2114 right = pos() == textRow().endpos();
2116 if ((!left && !right) ||
2117 (left && !right && xo < x_target_) ||
2118 (!left && right && x_target_ < xo))
2125 // first get the current line
2126 TextMetrics & tm = bv_->textMetrics(text());
2127 ParagraphMetrics const & pm = tm.parMetrics(pit());
2129 if (pos() && boundary())
2130 row = pm.pos2row(pos() - 1);
2132 row = pm.pos2row(pos());
2134 if (atFirstOrLastRow(up)) {
2135 // Is there a place for the cursor to go ? If yes, we
2136 // can execute the DEPM, otherwise we should keep the
2137 // paragraph to host the cursor.
2138 Cursor dummy = *this;
2139 bool valid_destination = false;
2140 for(; dummy.depth(); dummy.pop())
2141 if (!dummy.atFirstOrLastRow(up)) {
2142 valid_destination = true;
2146 // will a next dispatch follow and if there is a new
2147 // dispatch will it move the cursor out ?
2148 if (depth() > 1 && valid_destination) {
2149 // The cursor hasn't changed yet. This happens when
2150 // you e.g. move out of an inset. And to give the
2151 // DEPM the possibility of doing something we must
2152 // provide it with two different cursors. (Lgb, vfr)
2154 dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
2155 dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
2157 updateNeeded |= bv().checkDepm(dummy, *this);
2158 updateTextTargetOffset();
2160 forceBufferUpdate();
2165 // with and without selection are handled differently
2167 int yo1 = bv().getPos(*this).y_;
2169 // To next/previous row
2170 // FIXME: the y position is often guessed wrongly across styles and
2171 // insets, which leads to weird behaviour.
2173 tm.editXY(*this, xo, yo1 - textRow().ascent() - 1);
2175 tm.editXY(*this, xo, yo1 + textRow().descent() + 1);
2176 x_target_ = old.x_target_;
2179 // This happens when you move out of an inset.
2180 // And to give the DEPM the possibility of doing
2181 // something we must provide it with two different
2183 Cursor dummy = *this;
2186 if (bv().checkDepm(dummy, old)) {
2187 updateNeeded = true;
2188 // Make sure that cur gets back whatever happened to dummy (Lgb)
2191 if (inTexted() && pos() && paragraph().isEnvSeparator(pos() - 1))
2194 // if there is a selection, we stay out of any inset,
2195 // and just jump to the right position:
2201 } else if (pit() > 0) {
2203 TextMetrics & tm2 = bv_->textMetrics(text());
2204 if (!tm2.contains(pit()))
2205 tm2.newParMetricsUp();
2206 ParagraphMetrics const & pmcur = tm2.parMetrics(pit());
2207 next_row = pmcur.rows().size() - 1;
2210 if (row + 1 < int(pm.rows().size())) {
2212 } else if (pit() + 1 < int(text()->paragraphs().size())) {
2214 TextMetrics & tm2 = bv_->textMetrics(text());
2215 if (!tm2.contains(pit()))
2216 tm2.newParMetricsDown();
2221 Row const & real_next_row = tm.parMetrics(pit()).rows()[next_row];
2223 top().pos() = tm.getPosNearX(real_next_row, xo, bound);
2225 // When selection==false, this is done by TextMetrics::editXY
2228 updateNeeded |= bv().checkDepm(*this, old);
2232 forceBufferUpdate();
2233 updateTextTargetOffset();
2238 void Cursor::handleFont(string const & font)
2240 LYXERR(Debug::DEBUG, font);
2244 safe = cap::grabAndEraseSelection(*this);
2249 if (lastpos() != 0) {
2250 // something left in the cell
2252 // cursor in first position
2254 } else if (pos() == lastpos()) {
2255 // cursor in last position
2258 // cursor in between. split cell
2259 MathData::iterator bt = cell().begin();
2260 MathAtom at = createInsetMath(from_utf8(font), buffer());
2261 at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
2262 cell().erase(bt, bt + pos());
2267 // nothing left in the cell
2276 void Cursor::undispatched() const
2278 disp_.dispatched(false);
2282 void Cursor::dispatched() const
2284 disp_.dispatched(true);
2288 void Cursor::screenUpdateFlags(Update::flags f) const
2290 disp_.screenUpdate(f);
2294 void Cursor::noScreenUpdate() const
2296 disp_.screenUpdate(Update::None);
2300 void Cursor::forceBufferUpdate() const
2302 disp_.forceBufferUpdate();
2306 void Cursor::clearBufferUpdate() const
2308 disp_.clearBufferUpdate();
2312 bool Cursor::needBufferUpdate() const
2314 return disp_.needBufferUpdate();
2318 Font Cursor::getFont() const
2320 // The logic here should more or less match to the
2321 // Cursor::setCurrentFont logic, i.e. the cursor height should
2322 // give a hint what will happen if a character is entered.
2323 // FIXME: this is not the case, what about removing this method ? (see #10478).
2325 // HACK. far from being perfect...
2327 CursorSlice const & sl = innerTextSlice();
2328 Text const & text = *sl.text();
2329 Paragraph const & par = text.getPar(sl.pit());
2331 // on boundary, so we are really at the character before
2332 pos_type pos = sl.pos();
2333 if (pos > 0 && boundary())
2336 // on space? Take the font before (only for RTL boundary stay)
2338 TextMetrics const & tm = bv().textMetrics(&text);
2339 if (pos == sl.lastpos()
2340 || (par.isSeparator(pos)
2341 && !tm.isRTLBoundary(sl.pit(), pos)))
2345 // get font at the position
2346 Font font = par.getFont(buffer()->params(), pos,
2347 text.outerFont(sl.pit()));
2353 void Cursor::sanitize()
2355 setBuffer(&bv_->buffer());
2356 CursorData::sanitize();
2360 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2362 // find inset in common
2364 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2365 if (&old[i].inset() != &cur[i].inset())
2369 // update words if we just moved to another paragraph
2370 if (i == old.depth() && i == cur.depth()
2371 && !cur.buffer()->isClean()
2372 && cur.inTexted() && old.inTexted()
2373 && cur.pit() != old.pit()) {
2374 old.paragraph().updateWords();
2377 // notify everything on top of the common part in old cursor,
2378 // but stop if the inset claims the cursor to be invalid now
2379 for (size_type j = i; j < old.depth(); ++j) {
2380 Cursor inset_pos = old;
2381 inset_pos.cutOff(j);
2382 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2386 // notify everything on top of the common part in new cursor,
2387 // but stop if the inset claims the cursor to be invalid now
2388 for (; i < cur.depth(); ++i) {
2389 if (cur[i].inset().notifyCursorEnters(cur))
2397 void Cursor::setCurrentFont()
2399 CursorSlice const & cs = innerTextSlice();
2400 Paragraph const & par = cs.paragraph();
2401 pos_type cpit = cs.pit();
2402 pos_type cpos = cs.pos();
2403 Text const & ctext = *cs.text();
2404 TextMetrics const & tm = bv().textMetrics(&ctext);
2406 // are we behind previous char in fact? -> go to that char
2407 if (cpos > 0 && boundary())
2410 // find position to take the font from
2412 // paragraph end? -> font of last char
2413 if (cpos == lastpos())
2415 // on space? -> look at the words in front of space
2416 else if (cpos > 0 && par.isSeparator(cpos)) {
2417 // abc| def -> font of c
2418 // abc |[WERBEH], i.e. boundary==true -> font of c
2419 // abc [WERBEH]| def, font of the space
2420 if (!tm.isRTLBoundary(cpit, cpos))
2426 BufferParams const & bufparams = buffer()->params();
2427 current_font = par.getFontSettings(bufparams, cpos);
2428 real_current_font = tm.displayFont(cpit, cpos);
2430 // special case for paragraph end
2431 if (cs.pos() == lastpos()
2432 && tm.isRTLBoundary(cpit, cs.pos())
2434 Language const * lang = par.getParLanguage(bufparams);
2435 current_font.setLanguage(lang);
2436 current_font.fontInfo().setNumber(FONT_OFF);
2437 real_current_font.setLanguage(lang);
2438 real_current_font.fontInfo().setNumber(FONT_OFF);
2443 void Cursor::checkBufferStructure()
2445 Buffer const * master = buffer()->masterBuffer();
2446 master->tocBackend().updateItem(*this);
2447 if (master != buffer() && !master->hasGuiDelegate())
2448 // In case the master has no gui associated with it,
2449 // the TocItem is not updated (part of bug 5699).
2450 buffer()->tocBackend().updateItem(*this);
2452 // If the last tracked change of the paragraph has just been
2453 // deleted, then we need to recompute the buffer flag
2454 // tracked_changes_present_.
2455 if (inTexted() && paragraph().isChangeUpdateRequired())
2456 disp_.forceChangesUpdate();
2460 void Cursor::moveToClosestEdge(int const x, bool const edit)
2462 if (Inset const * inset = nextInset()) {
2463 // stay in front of insets for which we want to open the dialog
2464 // (e.g. InsetMathSpace).
2465 if (edit && (inset->hasSettings() || !inset->contextMenuName().empty()))
2467 CoordCache::Insets const & insetCache = bv().coordCache().getInsets();
2468 if (!insetCache.has(inset))
2470 int const wid = insetCache.dim(inset).wid;
2471 Point p = insetCache.xy(inset);
2472 if (x > p.x_ + (wid + 1) / 2)