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"
27 #include "LyXAction.h"
29 #include "Paragraph.h"
30 #include "ParIterator.h"
32 #include "texstream.h"
34 #include "TextMetrics.h"
35 #include "TocBackend.h"
37 #include "support/debug.h"
38 #include "support/docstream.h"
39 #include "support/ExceptionMessage.h"
40 #include "support/gettext.h"
41 #include "support/lassert.h"
43 #include "insets/InsetTabular.h"
44 #include "insets/InsetText.h"
46 #include "mathed/InsetMath.h"
47 #include "mathed/InsetMathBrace.h"
48 #include "mathed/InsetMathEnsureMath.h"
49 #include "mathed/InsetMathScript.h"
50 #include "mathed/MacroTable.h"
51 #include "mathed/MathData.h"
52 #include "mathed/MathFactory.h"
53 #include "mathed/InsetMathMacro.h"
55 #include "frontends/Application.h"
68 // Find position closest to (x, y) in cell given by iter.
69 // Used only in mathed
70 DocIterator bruteFind(Cursor const & c, int x, int y)
72 double best_dist = numeric_limits<double>::max();
79 et.pos() = et.lastpos();
80 for (size_t i = 0;; ++i) {
83 Inset const * inset = &it.inset();
84 CoordCache::Insets const & insetCache = c.bv().coordCache().getInsets();
86 // FIXME: in the case where the inset is not in the cache, this
87 // means that no part of it is visible on screen. In this case
88 // we don't do elaborate search and we just return the forwarded
89 // DocIterator at its beginning.
90 if (!insetCache.has(inset)) {
95 Point const o = insetCache.xy(inset);
96 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
97 // Convert to absolute
100 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
101 // '<=' in order to take the last possible position
102 // this is important for clicking behind \sum in e.g. '\sum_i a'
103 LYXERR(Debug::DEBUG, "i: " << i << " d: " << d
104 << " best: " << best_dist);
105 if (d <= best_dist) {
125 CursorData::CursorData()
126 : DocIterator(), anchor_(), selection_(false), mark_(false),
127 word_selection_(false), current_font(inherit_font)
131 CursorData::CursorData(Buffer * buffer)
132 : DocIterator(buffer), anchor_(), selection_(false), mark_(false),
133 word_selection_(false), current_font(inherit_font)
137 CursorData::CursorData(DocIterator const & dit)
138 : DocIterator(dit), anchor_(), selection_(false), mark_(false),
139 word_selection_(false), current_font(inherit_font)
145 ostream & operator<<(ostream & os, CursorData const & cur)
147 os << "\n cursor: | anchor:\n";
148 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
149 os << " " << cur[i] << " | ";
150 if (i < cur.anchor_.depth())
151 os << cur.anchor_[i];
153 os << "-------------------------------";
156 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
157 os << "------------------------------- | " << cur.anchor_[i] << "\n";
159 os << " selection: " << cur.selection_
160 // << " x_target: " << cur.x_target_
161 << " boundary: " << cur.boundary() << endl;
166 LyXErr & operator<<(LyXErr & os, CursorData const & cur)
173 void CursorData::reset()
176 push_back(CursorSlice(buffer()->inset()));
177 anchor_ = doc_iterator_begin(buffer());
179 new_word_ = doc_iterator_begin(buffer());
186 void CursorData::setCursor(DocIterator const & cur)
188 DocIterator::operator=(cur);
192 void CursorData::setCursorSelectionTo(DocIterator dit)
196 while (i < dit.depth() && i < anchor_.depth() && dit[i] == anchor_[i])
198 if (i != dit.depth()) {
199 // otherwise the cursor is already normal
200 if (i == anchor_.depth())
201 // dit is a proper extension of the anchor_
203 else if (i + 1 < dit.depth()) {
204 // one has dit[i] != anchor_[i] but either dit[i-1] == anchor_[i-1]
205 // or i == 0. Remove excess.
207 if (dit[i] > anchor_[i])
208 // place dit after the inset it was in
217 void CursorData::setCursorToAnchor()
220 DocIterator normal = anchor_;
221 while (depth() < normal.depth())
223 if (depth() < anchor_.depth() && top() <= anchor_[depth() - 1])
230 CursorSlice CursorData::normalAnchor() const
234 // LASSERT: There have been several bugs around this code, that seem
235 // to involve failures to reset the anchor. We can at least not crash
236 // in release mode by resetting it ourselves.
237 if (anchor_.depth() < depth()) {
238 LYXERR0("Cursor is deeper than anchor. PLEASE REPORT.\nCursor is"
240 const_cast<DocIterator &>(anchor_) = *this;
243 CursorSlice normal = anchor_[depth() - 1];
244 if (depth() < anchor_.depth() && top() <= normal) {
245 // anchor is behind cursor -> move anchor behind the inset
252 void CursorData::setSelection()
255 if (idx() == normalAnchor().idx() &&
256 pit() == normalAnchor().pit() &&
257 pos() == normalAnchor().pos())
262 void CursorData::setSelection(DocIterator const & where, int n)
271 void CursorData::resetAnchor()
274 checkNewWordPosition();
278 CursorSlice CursorData::selBegin() const
282 return normalAnchor() < top() ? normalAnchor() : top();
286 CursorSlice CursorData::selEnd() const
290 return normalAnchor() > top() ? normalAnchor() : top();
294 DocIterator CursorData::selectionBegin() const
300 // FIXME: This is a work-around for the problem that
301 // CursorSlice doesn't keep track of the boundary.
302 if (normalAnchor() == top())
303 di = anchor_.boundary() > boundary() ? anchor_ : *this;
305 di = normalAnchor() < top() ? anchor_ : *this;
311 DocIterator CursorData::selectionEnd() const
317 // FIXME: This is a work-around for the problem that
318 // CursorSlice doesn't keep track of the boundary.
319 if (normalAnchor() == top())
320 di = anchor_.boundary() < boundary() ? anchor_ : *this;
322 di = normalAnchor() > top() ? anchor_ : *this;
324 if (di.depth() > depth()) {
334 docstring parbreak(CursorData const * cur)
336 if (cur->inset().getLayout().parbreakIgnored())
340 // only add blank line if we're not in a ParbreakIsNewline situation
341 if (!cur->inset().getLayout().parbreakIsNewline()
342 && !cur->paragraph().layout().parbreak_is_newline)
350 docstring CursorData::selectionAsString(bool with_label) const
356 return cap::grabSelection(*this);
358 int const label = with_label
359 ? AS_STR_LABEL | AS_STR_INSETS : AS_STR_INSETS;
361 idx_type const startidx = selBegin().idx();
362 idx_type const endidx = selEnd().idx();
363 if (startidx != endidx) {
364 // multicell selection
365 InsetTabular * table = inset().asInsetTabular();
366 LASSERT(table, return docstring());
367 return table->asString(startidx, endidx);
370 ParagraphList const & pars = text()->paragraphs();
372 pit_type const startpit = selBegin().pit();
373 pit_type const endpit = selEnd().pit();
374 size_t const startpos = selBegin().pos();
375 size_t const endpos = selEnd().pos();
377 if (startpit == endpit)
378 return pars[startpit].asString(startpos, endpos, label);
380 // First paragraph in selection
381 docstring result = pars[startpit].
382 asString(startpos, pars[startpit].size(), label)
385 // The paragraphs in between (if any)
386 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
387 Paragraph const & par = pars[pit];
388 result += par.asString(0, par.size(), label)
392 // Last paragraph in selection
393 result += pars[endpit].asString(0, endpos, label);
399 void CursorData::info(odocstream & os, bool devel_mode) const
401 for (int i = 1, n = depth(); i < n; ++i) {
402 operator[](i).inset().infoize(os);
406 Inset const * inset = prevInset();
407 // prevInset() can return 0 in certain case.
409 prevInset()->infoize2(os);
412 InsetMath * math = inset().asInsetMath();
414 os << _(", Inset: ") << math->id();
415 os << _(", Cell: ") << idx();
416 os << _(", Position: ") << pos();
421 docstring CursorData::currentState(bool devel_mode) const
425 info(os, devel_mode);
430 return text()->currentState(*this, devel_mode);
436 void CursorData::markNewWordPosition()
438 if (lyxrc.spellcheck_continuously && inTexted() && new_word_.empty()) {
439 FontSpan nw = locateWord(WHOLE_WORD);
440 if (nw.size() == 1) {
441 LYXERR(Debug::DEBUG, "start new word: "
443 << " pos: " << nw.first);
450 void CursorData::clearNewWordPosition()
452 if (!new_word_.empty()) {
453 LYXERR(Debug::DEBUG, "clear new word: "
455 << " pos: " << pos());
461 void CursorData::checkNewWordPosition()
463 if (!lyxrc.spellcheck_continuously || new_word_.empty())
465 // forget the position of the current new word if
466 // 1) or the remembered position was "broken"
467 // 2) or the count of nested insets changed
468 // 3) the top-level inset is not the same anymore
469 // 4) the cell index changed
470 // 5) or the paragraph changed
471 // 6) or the cursor pos is out of paragraph bound
472 if (new_word_.fixIfBroken()
473 || depth() != new_word_.depth()
474 || &inset() != &new_word_.inset()
475 || pit() != new_word_.pit()
476 || idx() != new_word_.idx()
477 || new_word_.pos() > new_word_.lastpos())
478 clearNewWordPosition();
480 FontSpan nw = locateWord(WHOLE_WORD);
482 FontSpan ow = new_word_.locateWord(WHOLE_WORD);
483 if (nw.intersect(ow).empty())
484 clearNewWordPosition();
486 LYXERR(Debug::DEBUG, "new word: "
488 << " pos: " << nw.first << ".." << nw.last);
490 clearNewWordPosition();
495 void CursorData::clearSelection()
498 setWordSelection(false);
504 int CursorData::countInsetsInSelection(InsetCode const & inset_code)
509 DocIterator from, to;
510 from = selectionBegin();
515 if (!from.nextInset()) //move to closest inset
518 while (!from.empty() && from < to) {
519 Inset * inset = from.nextInset();
522 if (inset->lyxCode() == inset_code)
530 bool CursorData::insetInSelection(InsetCode const & inset_code)
535 DocIterator from, to;
536 from = selectionBegin();
539 if (!from.nextInset()) //move to closest inset
542 while (!from.empty() && from < to) {
543 Inset * inset = from.nextInset();
546 if (inset->lyxCode() == inset_code)
554 bool CursorData::fixIfBroken()
556 bool const broken_cursor = DocIterator::fixIfBroken();
557 bool const broken_anchor = anchor_.fixIfBroken();
559 if (broken_cursor || broken_anchor) {
560 clearNewWordPosition();
568 void CursorData::sanitize()
570 DocIterator::sanitize();
571 new_word_.sanitize();
579 bool CursorData::undoAction()
581 if (!buffer()->undo().undoAction(*this))
588 bool CursorData::redoAction()
590 if (!buffer()->undo().redoAction(*this))
597 void CursorData::finishUndo() const
599 buffer()->undo().finishUndo();
603 void CursorData::beginUndoGroup() const
605 buffer()->undo().beginUndoGroup(*this);
609 void CursorData::endUndoGroup() const
611 buffer()->undo().endUndoGroup(*this);
615 void CursorData::splitUndoGroup() const
617 buffer()->undo().splitUndoGroup(*this);
621 void CursorData::recordUndo(pit_type from, pit_type to) const
623 buffer()->undo().recordUndo(*this, from, to);
627 void CursorData::recordUndo(pit_type from) const
629 buffer()->undo().recordUndo(*this, from, pit());
633 void CursorData::recordUndo(UndoKind kind) const
635 buffer()->undo().recordUndo(*this, kind);
639 void CursorData::recordUndoInset(Inset const * in) const
641 buffer()->undo().recordUndoInset(*this, in);
645 void CursorData::recordUndoFullBuffer() const
647 buffer()->undo().recordUndoFullBuffer(*this);
651 void CursorData::recordUndoBufferParams() const
653 buffer()->undo().recordUndoBufferParams(*this);
657 void CursorData::recordUndoSelection() const
660 if (cap::multipleCellsSelected(*this))
665 buffer()->undo().recordUndo(*this,
666 selBegin().pit(), selEnd().pit());
671 int CursorData::currentMode()
673 LASSERT(!empty(), return Inset::UNDECIDED_MODE);
674 for (int i = depth() - 1; i >= 0; --i) {
675 int res = operator[](i).inset().currentMode();
676 bool locked_mode = operator[](i).inset().lockedMode();
677 // Also return UNDECIDED_MODE when the mode is locked,
678 // as in this case it is treated the same as TEXT_MODE
679 if (res != Inset::UNDECIDED_MODE || locked_mode)
682 return Inset::TEXT_MODE;
686 bool CursorData::confirmDeletion(bool const before) const
689 if (Inset const * inset = before ? prevInset() : nextInset())
690 return inset->confirmDeletion();
692 DocIterator dit = selectionBegin();
693 CursorSlice const end = selectionEnd().top();
694 for (; dit.top() < end; dit.top().forwardPos())
695 if (Inset const * inset = dit.nextInset())
696 if (inset->confirmDeletion())
709 // be careful: this is called from the bv's constructor, too, so
710 // bv functions are not yet available!
711 Cursor::Cursor(BufferView & bv)
712 : CursorData(&bv.buffer()), bv_(&bv),
713 x_target_(-1), textTargetOffset_(0),
714 beforeDispatchPosX_(0), beforeDispatchPosY_(0)
725 void Cursor::setCursorData(CursorData const & data)
727 CursorData::operator=(data);
731 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
735 // Try to fix cursor in case it is broken.
738 // Is this a function that acts on inset at point?
739 Inset * inset = cur.nextInset();
740 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
741 && inset && inset->getStatus(cur, cmd, status))
744 // This is, of course, a mess. Better create a new doc iterator and use
745 // this in Inset::getStatus. This might require an additional
746 // BufferView * arg, though (which should be avoided)
747 //Cursor safe = *this;
749 for ( ; cur.depth(); cur.pop()) {
750 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
751 // LASSERT: Is it safe to continue here, or should we return?
752 LASSERT(cur.idx() <= cur.lastidx(), /**/);
753 LASSERT(cur.pit() <= cur.lastpit(), /**/);
754 LASSERT(cur.pos() <= cur.lastpos(), /**/);
756 // The inset's getStatus() will return 'true' if it made
757 // a definitive decision on whether it want to handle the
758 // request or not. The result of this decision is put into
759 // the 'status' parameter.
760 if (cur.inset().getStatus(cur, cmd, status)) {
769 void Cursor::saveBeforeDispatchPosXY()
771 getPos(beforeDispatchPosX_, beforeDispatchPosY_);
775 void Cursor::dispatch(FuncRequest const & cmd0)
777 LYXERR(Debug::ACTION, "Cursor::dispatch: cmd: " << cmd0 << '\n' << *this);
782 FuncRequest cmd = cmd0;
785 disp_ = DispatchResult();
789 // Is this a function that acts on inset at point?
790 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
792 disp_.dispatched(true);
793 disp_.screenUpdate(Update::FitCursor | Update::Force);
794 FuncRequest tmpcmd = cmd;
795 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
796 << cmd0 << endl << *this);
797 nextInset()->dispatch(*this, tmpcmd);
798 if (disp_.dispatched()) {
804 // store some values to be used inside of the handlers
805 beforeDispatchCursor_ = *this;
806 for (; depth(); pop(), boundary(false)) {
807 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
808 << cmd0 << endl << *this);
810 // In any of these cases, the cursor is invalid, and we should
811 // try to save this document rather than crash.
812 LBUFERR(pos() <= lastpos());
813 LBUFERR(idx() <= lastidx());
814 LBUFERR(pit() <= lastpit());
816 // The common case is 'LFUN handled, need update', so make the
817 // LFUN handler's life easier by assuming this as default value.
818 // The handler can reset the update and val flags if necessary.
819 disp_.screenUpdate(Update::FitCursor | Update::Force);
820 disp_.dispatched(true);
821 inset().dispatch(*this, cmd);
822 if (disp_.dispatched())
826 // it completely to get a 'bomb early' behaviour in case this
827 // object will be used again.
828 if (!disp_.dispatched()) {
829 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
830 // We might have invalidated the cursor when removing an empty
831 // paragraph while the cursor could not be moved out the inset
832 // while we initially thought we could. This might happen when
833 // a multiline inset becomes an inline inset when the second
834 // paragraph is removed.
835 if (safe.pit() > safe.lastpit()) {
836 safe.pit() = safe.lastpit();
837 safe.pos() = safe.lastpos();
840 disp_.screenUpdate(Update::None);
841 disp_.dispatched(false);
843 // restore the previous one because nested Cursor::dispatch calls
844 // are possible which would change it
845 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
849 // NOTE: The code below has been copied to BufferView::dispatch.
850 // If you need to modify this, please update the other one too.
852 // notify insets we just left
854 old.beginUndoGroup();
856 bool badcursor = notifyCursorLeavesOrEnters(old, *this);
859 bv().resetInlineCompletionPos();
866 DispatchResult const & Cursor::result() const
872 void Cursor::message(docstring const & msg) const
874 disp_.setMessage(msg);
878 void Cursor::errorMessage(docstring const & msg) const
880 disp_.setMessage(msg);
881 disp_.setError(true);
885 BufferView & Cursor::bv() const
894 LBUFERR(depth() >= 1);
899 void Cursor::push(Inset & p)
901 push_back(CursorSlice(p));
902 p.setBuffer(*buffer());
906 void Cursor::pushBackward(Inset & p)
908 LASSERT(!empty(), return);
909 //lyxerr << "Entering inset " << t << " front" << endl;
915 void Cursor::editInsertedInset()
917 LASSERT(!empty(), return);
921 InsetMath &p = prevMath();
928 // this could be a while() loop, but only one cell is not empty in
929 // cases we are interested in. The cell is not empty because we
930 // have inserted the selection in there.
931 if (!cell().empty()) {
932 // if it is not empty, move to the next one.
933 if (!inset().idxNext(*this))
934 // If there is no next one, exit the inset.
940 bool Cursor::popBackward()
942 LASSERT(!empty(), return false);
950 bool Cursor::popForward()
952 LASSERT(!empty(), return false);
953 //lyxerr << "Leaving inset from in back" << endl;
954 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
958 pos() += lastpos() - lp + 1;
963 void Cursor::getPos(int & x, int & y) const
965 Point p = bv().getPos(*this);
971 Row const & Cursor::textRow() const
973 CursorSlice const & cs = innerTextSlice();
974 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
975 return pm.getRow(pos(), boundary());
979 bool Cursor::posVisRight(bool skip_inset)
981 Cursor new_cur = *this; // where we will move to
982 pos_type left_pos; // position visually left of current cursor
983 pos_type right_pos; // position visually right of current cursor
985 getSurroundingPos(left_pos, right_pos);
987 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
989 // Are we at an inset?
990 new_cur.pos() = right_pos;
991 new_cur.boundary(false);
993 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
994 // we actually move the cursor at the end of this
995 // function, for now we just keep track of the new
996 // position in new_cur...
997 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
1000 // Are we already at rightmost pos in row?
1001 else if (text()->empty() || right_pos == -1) {
1004 if (!new_cur.posVisToNewRow(false)) {
1005 LYXERR(Debug::RTL, "not moving!");
1009 // we actually move the cursor at the end of this
1010 // function, for now just keep track of the new
1011 // position in new_cur...
1012 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
1013 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
1016 // normal movement to the right
1019 // Recall, if the cursor is at position 'x', that
1020 // means *before* the character at position 'x'. In
1021 // RTL, "before" means "to the right of", in LTR, "to
1022 // the left of". So currently our situation is this:
1023 // the position to our right is 'right_pos' (i.e.,
1024 // we're currently to the left of 'right_pos'). In
1025 // order to move to the right, it depends whether or
1026 // not the character at 'right_pos' is RTL.
1027 bool const new_pos_is_RTL = paragraph().getFontSettings(
1028 buffer()->params(), right_pos).isVisibleRightToLeft();
1029 // If the character at 'right_pos' *is* LTR, then in
1030 // order to move to the right of it, we need to be
1031 // *after* 'right_pos', i.e., move to position
1033 if (!new_pos_is_RTL) {
1034 new_cur.pos() = right_pos + 1;
1035 // set the boundary to true in two situations:
1037 // 1. if new_pos is now lastpos, and we're in
1038 // an RTL paragraph (this means that we're
1039 // moving right to the end of an LTR chunk
1040 // which is at the end of an RTL paragraph);
1041 (new_cur.pos() == lastpos()
1042 && paragraph().isRTL(buffer()->params()))
1043 // 2. if the position *after* right_pos is RTL
1044 // (we want to be *after* right_pos, not
1045 // before right_pos + 1!)
1046 || paragraph().getFontSettings(buffer()->params(),
1047 new_cur.pos()).isVisibleRightToLeft()
1049 new_cur.boundary(true);
1050 else // set the boundary to false
1051 new_cur.boundary(false);
1053 // Otherwise (if the character at position 'right_pos'
1054 // is RTL), then moving to the right of it is as easy
1055 // as setting the new position to 'right_pos'.
1057 new_cur.pos() = right_pos;
1058 new_cur.boundary(false);
1063 bool const moved = new_cur != *this || new_cur.boundary() != boundary();
1066 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
1067 << (new_cur.boundary() ? " (boundary)" : ""));
1075 bool Cursor::posVisLeft(bool skip_inset)
1077 Cursor new_cur = *this; // where we will move to
1078 pos_type left_pos; // position visually left of current cursor
1079 pos_type right_pos; // position visually right of current cursor
1081 getSurroundingPos(left_pos, right_pos);
1083 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
1085 // Are we at an inset?
1086 new_cur.pos() = left_pos;
1087 new_cur.boundary(false);
1089 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
1090 // we actually move the cursor at the end of this
1091 // function, for now we just keep track of the new
1092 // position in new_cur...
1093 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
1096 // Are we already at leftmost pos in row?
1097 else if (text()->empty() || left_pos == -1) {
1100 if (!new_cur.posVisToNewRow(true)) {
1101 LYXERR(Debug::RTL, "not moving!");
1105 // we actually move the cursor at the end of this
1106 // function, for now just keep track of the new
1107 // position in new_cur...
1108 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
1109 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
1112 // normal movement to the left
1115 // Recall, if the cursor is at position 'x', that
1116 // means *before* the character at position 'x'. In
1117 // RTL, "before" means "to the right of", in LTR, "to
1118 // the left of". So currently our situation is this:
1119 // the position to our left is 'left_pos' (i.e., we're
1120 // currently to the right of 'left_pos'). In order to
1121 // move to the left, it depends whether or not the
1122 // character at 'left_pos' is RTL.
1123 bool const new_pos_is_RTL = paragraph().getFontSettings(
1124 buffer()->params(), left_pos).isVisibleRightToLeft();
1125 // If the character at 'left_pos' *is* RTL, then in
1126 // order to move to the left of it, we need to be
1127 // *after* 'left_pos', i.e., move to position
1129 if (new_pos_is_RTL) {
1130 new_cur.pos() = left_pos + 1;
1131 // set the boundary to true in two situations:
1133 // 1. if new_pos is now lastpos and we're in
1134 // an LTR paragraph (this means that we're
1135 // moving left to the end of an RTL chunk
1136 // which is at the end of an LTR paragraph);
1137 (new_cur.pos() == lastpos()
1138 && !paragraph().isRTL(buffer()->params()))
1139 // 2. if the position *after* left_pos is not
1140 // RTL (we want to be *after* left_pos, not
1141 // before left_pos + 1!)
1142 || !paragraph().getFontSettings(buffer()->params(),
1143 new_cur.pos()).isVisibleRightToLeft()
1145 new_cur.boundary(true);
1146 else // set the boundary to false
1147 new_cur.boundary(false);
1149 // Otherwise (if the character at position 'left_pos'
1150 // is LTR), then moving to the left of it is as easy
1151 // as setting the new position to 'left_pos'.
1153 new_cur.pos() = left_pos;
1154 new_cur.boundary(false);
1159 bool const moved = new_cur != *this || new_cur.boundary() != boundary();
1162 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
1163 << (new_cur.boundary() ? " (boundary)" : ""));
1173 // Return true on success
1174 bool findNonVirtual(Row const & row, Row::const_iterator & cit, bool onleft)
1177 while (cit != row.begin() && cit->isVirtual())
1180 while (cit != row.end() && cit->isVirtual())
1183 return cit != row.end() && !cit->isVirtual();
1188 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos) const
1190 // by default, we know nothing.
1194 Row const & row = textRow();
1196 Row::const_iterator cit = row.findElement(pos(), boundary(), dummy);
1197 // Handle the case of empty row
1198 if (cit == row.end()) {
1200 right_pos = row.pos();
1202 left_pos = row.pos() - 1;
1206 // skip virtual elements and exit if no non-virtual one exists
1207 if (!findNonVirtual(row, cit, !cit->isRTL()))
1210 // if the position is at the left side of the element, we have to
1211 // look at the previous element
1212 if (pos() == cit->left_pos()) {
1213 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1214 << "), AT LEFT of *cit=" << *cit);
1215 // this one is easy (see common case below)
1216 right_pos = pos() - (cit->isRTL() ? 1 : 0);
1217 // at the left of the row
1218 if (cit == row.begin())
1221 if (!findNonVirtual(row, cit, true))
1223 // [...[ is the row element, | is cursor position (! with boundary)
1224 // [ 1 2 [ is a ltr row element with pos=1 and endpos=3
1225 // ] 2 1] is an rtl row element with pos=1 and endpos=3
1226 // [ 1 2 [ [|3 4 [ => (2, 3)
1227 // or [ 1 2 [ ]!4 3 ] => (2, 4)
1228 // or ] 2 1 ] [|3 4 [ => (1, 3)
1229 // or ] 4 3 ] ]!2 1 ] => (3, 2)
1230 left_pos = cit->right_pos() - (cit->isRTL() ? 0 : 1);
1231 // happens with consecutive row of same direction
1232 if (left_pos == right_pos) {
1233 left_pos += cit->isRTL() ? 1 : -1;
1236 // same code but with the element at the right
1237 else if (pos() == cit->right_pos()) {
1238 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1239 << "), AT RIGHT of *cit=" << *cit);
1240 // this one is easy (see common case below)
1241 left_pos = pos() - (cit->isRTL() ? 0 : 1);
1242 // at the right of the row
1243 if (cit + 1 == row.end())
1246 if (!findNonVirtual(row, cit, false))
1248 // [ 1 2![ [ 3 4 [ => (2, 3)
1249 // or [ 1 2![ ] 4 3 ] => (2, 4)
1250 // or ] 2 1|] [ 3 4 [ => (1, 3)
1251 // or ] 4 3|] ] 2 1 ] => (3, 2)
1252 right_pos = cit->left_pos() - (cit->isRTL() ? 1 : 0);
1253 // happens with consecutive row of same direction
1254 if (right_pos == left_pos)
1255 right_pos += cit->isRTL() ? -1 : 1;
1257 // common case: both positions are inside the row element
1259 // [ 1 2|3 [ => (2, 3)
1260 // or ] 3|2 1 ] => (3, 2)
1261 left_pos = pos() - (cit->isRTL() ? 0 : 1);
1262 right_pos = pos() - (cit->isRTL() ? 1 : 0);
1265 // Note that debug message does not catch all early returns above
1266 LYXERR(Debug::RTL,"getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1267 << ") => (" << left_pos << ", " << right_pos <<")");
1271 bool Cursor::posVisToNewRow(bool movingLeft)
1273 Row const & row = textRow();
1274 bool par_is_LTR = !row.isRTL();
1276 // Inside a table, determining whether to move to the next or
1277 // previous row should be done based on the table's direction.
1278 if (inset().asInsetTabular()) {
1279 par_is_LTR = !inset().asInsetTabular()->isRightToLeft(*this);
1280 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
1283 // if moving left in an LTR paragraph or moving right in an
1284 // RTL one, move to previous row
1285 if (par_is_LTR == movingLeft) {
1286 if (row.pos() == 0) { // we're at first row in paragraph
1287 if (pit() == 0) // no previous paragraph! don't move
1289 // move to last pos in previous par
1293 } else { // move to previous row in this par
1294 pos() = row.pos() - 1; // this is guaranteed to be in previous row
1298 // if moving left in an RTL paragraph or moving right in an
1299 // LTR one, move to next row
1301 if (row.endpos() == lastpos()) { // we're at last row in paragraph
1302 if (pit() == lastpit()) // last paragraph! don't move
1304 // move to first row in next par
1308 } else { // move to next row in this par
1309 pos() = row.endpos();
1314 // make sure we're at left-/right-most pos in new row
1315 posVisToRowExtremity(!movingLeft);
1321 void Cursor::posVisToRowExtremity(bool left)
1323 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
1324 << (boundary() ? 1 : 0));
1326 TextMetrics const & tm = bv_->textMetrics(text());
1327 // Looking for extremities is like clicking on the left or the
1328 // right of the row.
1329 int x = tm.origin().x_ + (left ? 0 : textRow().width());
1331 pos() = tm.getPosNearX(textRow(), x, b);
1334 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
1335 << (boundary() ? 1 : 0));
1339 bool Cursor::reverseDirectionNeeded() const
1342 * We determine the directions based on the direction of the
1343 * bottom() --- i.e., outermost --- paragraph, because that is
1344 * the only way to achieve consistency of the arrow's movements
1345 * within a paragraph, and thus avoid situations in which the
1346 * cursor gets stuck.
1348 return bottom().paragraph().isRTL(bv().buffer().params());
1352 void Cursor::setTargetX(int x)
1355 textTargetOffset_ = 0;
1359 int Cursor::x_target() const
1365 void Cursor::clearTargetX()
1368 textTargetOffset_ = 0;
1372 void Cursor::updateTextTargetOffset()
1377 textTargetOffset_ = x - x_target_;
1381 bool Cursor::selHandle(bool sel)
1383 //lyxerr << "Cursor::selHandle" << endl;
1386 if (sel == selection())
1390 cap::saveSelection(*this);
1398 bool Cursor::atFirstOrLastRow(bool up)
1400 TextMetrics const & tm = bv_->textMetrics(text());
1401 ParagraphMetrics const & pm = tm.parMetrics(pit());
1404 if (pos() && boundary())
1405 row = pm.pos2row(pos() - 1);
1407 row = pm.pos2row(pos());
1410 if (pit() == 0 && row == 0)
1413 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1414 row + 1 >= int(pm.rows().size()))
1424 ///////////////////////////////////////////////////////////////////
1427 // The part below is the non-integrated rest of the original math
1428 // cursor. This should be either generalized for texted or moved
1429 // back to mathed (in most cases to InsetMathNest).
1431 ///////////////////////////////////////////////////////////////////
1433 #include "mathed/InsetMathChar.h"
1434 #include "mathed/InsetMathGrid.h"
1435 #include "mathed/InsetMathScript.h"
1436 #include "mathed/InsetMathUnknown.h"
1437 #include "mathed/MathFactory.h"
1438 #include "mathed/MathStream.h"
1439 #include "mathed/MathSupport.h"
1444 bool Cursor::openable(MathAtom const & t) const
1455 // we can't move into anything new during selection
1456 if (depth() >= realAnchor().depth())
1458 if (t.nucleus() != &realAnchor()[depth()].inset())
1465 void Cursor::plainErase()
1467 cell().erase(pos());
1471 void Cursor::plainInsert(MathAtom const & t)
1473 cell().insert(pos(), t);
1475 inset().setBuffer(bv_->buffer());
1477 checkBufferStructure();
1481 void Cursor::insert(char_type c)
1483 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1484 LASSERT(!empty(), return);
1486 cap::selClearOrDel(*this);
1487 insert(new InsetMathChar(c));
1489 text()->insertChar(*this, c);
1494 void Cursor::insert(docstring const & str)
1496 for (char_type c : str)
1501 void Cursor::insert(Inset * inset0)
1503 LASSERT(inset0, return);
1505 insert(MathAtom(inset0->asInsetMath()));
1507 text()->insertInset(*this, inset0);
1508 inset0->setBuffer(bv_->buffer());
1510 if (inset0->isLabeled())
1511 forceBufferUpdate();
1516 void Cursor::insert(MathAtom const & t)
1518 LATTEST(inMathed());
1519 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1521 cap::selClearOrDel(*this);
1526 void Cursor::insert(MathData const & ar)
1528 LATTEST(inMathed());
1531 cap::eraseSelection(*this);
1532 cell().insert(pos(), ar);
1534 // FIXME audit setBuffer calls
1535 inset().setBuffer(bv_->buffer());
1539 int Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1541 LATTEST(inMathed());
1542 MathData ar(buffer());
1544 if (ar.size() == 1 && (enter || selection()))
1552 void Cursor::niceInsert(MathAtom const & t)
1554 LATTEST(inMathed());
1556 docstring const safe = cap::grabAndEraseSelection(*this);
1558 // If possible, enter the new inset and move the contents of the selection
1559 if (t->isActive()) {
1560 idx_type const idx = prevMath().asNestInset()->firstIdx();
1561 MathData ar(buffer());
1563 prevMath().cell(idx).insert(0, ar);
1564 editInsertedInset();
1565 } else if (t->asMacro() && !safe.empty()) {
1566 MathData ar(buffer());
1568 docstring const name = t->asMacro()->name();
1569 MacroData const * data = buffer()->getMacro(name);
1570 if (data && data->numargs() - data->optionals() > 0) {
1571 plainInsert(MathAtom(new InsetMathBrace(ar)));
1578 bool Cursor::backspace(bool const force)
1581 cap::eraseSelection(*this);
1586 // If empty cell, and not part of a big cell
1587 if (lastpos() == 0 && inset().nargs() == 1) {
1589 // Directly delete empty cell: [|[]] => [|]
1595 // [|], can not delete from inside
1606 if (inMacroMode()) {
1607 InsetMathUnknown * p = activeMacro();
1608 if (p->name().size() > 1) {
1609 p->setName(p->name().substr(0, p->name().size() - 1));
1614 if (pos() != 0 && !force && prevAtom()->confirmDeletion()) {
1615 // let's require two backspaces for 'big stuff' and
1616 // highlight on the first
1628 bool Cursor::erase(bool const force)
1634 cap::eraseSelection(*this);
1638 // delete empty cells if possible
1639 if (pos() == lastpos() && inset().idxDelete(idx()))
1642 // special behaviour when in last position of cell
1643 if (pos() == lastpos()) {
1644 bool one_cell = inset().nargs() == 1;
1645 if (one_cell && lastpos() == 0) {
1647 // Directly delete empty cell: [|[]] => [|]
1653 // [|], can not delete from inside
1658 inset().idxGlue(idx());
1662 // 'clever' UI hack: only erase large items if previously slected
1663 if (pos() != lastpos() && !force && nextAtom()->confirmDeletion()) {
1678 DocIterator save = *this;
1679 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1680 this->dispatch(cmd);
1681 if (disp_.dispatched())
1691 DocIterator save = *this;
1692 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1693 this->dispatch(cmd);
1694 if (disp_.dispatched())
1701 void Cursor::handleNest(MathAtom const & a)
1703 idx_type const idx = a.nucleus()->asNestInset()->firstIdx();
1704 //lyxerr << "Cursor::handleNest: " << idx << endl;
1706 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(idx));
1708 editInsertedInset();
1712 int Cursor::targetX() const
1714 if (x_target() != -1)
1723 int Cursor::textTargetOffset() const
1725 return textTargetOffset_;
1729 void Cursor::setTargetX()
1738 bool Cursor::macroModeClose(bool cancel)
1742 InsetMathUnknown * p = activeMacro();
1744 MathData selection(buffer());
1745 asArray(p->selection(), selection);
1746 docstring const s = p->name();
1748 cell().erase(pos());
1750 // trigger updates of macros, at least, if no full
1751 // updates take place anyway
1752 screenUpdateFlags(Update::Force);
1754 // do nothing if the macro name is empty
1755 if (s == "\\" || cancel) {
1759 docstring const name = s.substr(1);
1760 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1761 if (in && in->interpretString(*this, s))
1763 bool const user_macro = buffer()->getMacro(name, *this, false);
1764 MathAtom atom = user_macro ? MathAtom(new InsetMathMacro(buffer(), name))
1765 : createInsetMath(name, buffer());
1767 // try to put argument into macro, if we just inserted a macro
1768 bool macroArg = false;
1769 InsetMathMacro * atomAsMacro = atom.nucleus()->asMacro();
1770 InsetMathNest * atomAsNest = atom.nucleus()->asNestInset();
1772 // macros here are still unfolded (in init mode in fact). So
1773 // we have to resolve the macro here manually and check its arity
1774 // to put the selection behind it if arity > 0.
1775 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1776 if (!selection.empty() && data && data->numargs()) {
1778 atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1780 // non-greedy case. Do not touch the arguments behind
1781 atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1784 // insert remembered selection into first argument of a non-macro
1785 else if (atomAsNest && atomAsNest->nargs() > 0)
1786 atomAsNest->cell(atomAsNest->firstIdx()).append(selection);
1788 MathWordList const & words = mathedWordList();
1789 MathWordList::const_iterator it = words.find(name);
1790 bool keep_mathmode = user_macro
1791 || (it != words.end() && (it->second.inset == "font"
1792 || it->second.inset == "oldfont"
1793 || it->second.inset == "mbox"));
1794 bool ert_macro = !user_macro && it == words.end() && atomAsMacro;
1796 if (in && in->currentMode() == Inset::TEXT_MODE
1797 && atom.nucleus()->currentMode() == Inset::MATH_MODE
1798 && name != from_ascii("ensuremath") && !ert_macro) {
1799 MathAtom at(new InsetMathEnsureMath(buffer()));
1800 at.nucleus()->cell(0).push_back(atom);
1803 } else if (in && in->currentMode() == Inset::MATH_MODE
1804 && atom.nucleus()->currentMode() == Inset::TEXT_MODE
1805 && !keep_mathmode) {
1806 MathAtom at = createInsetMath("text", buffer());
1807 at.nucleus()->cell(0).push_back(atom);
1813 // finally put the macro argument behind, if needed
1815 if (selection.size() > 1 || selection[0]->asScriptInset())
1816 plainInsert(MathAtom(new InsetMathBrace(selection)));
1825 bool Cursor::inMacroMode() const
1829 if (pos() == 0 || cell().empty())
1831 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1832 return p && !p->final();
1836 InsetMathUnknown * Cursor::activeMacro()
1838 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1842 InsetMathUnknown const * Cursor::activeMacro() const
1844 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1848 docstring Cursor::macroName()
1850 return inMacroMode() ? activeMacro()->name() : docstring();
1854 void Cursor::pullArg()
1857 MathData ar = cell();
1858 if (popBackward() && inMathed()) {
1860 cell().insert(pos(), ar);
1863 //formula()->mutateToText();
1868 void Cursor::normalize()
1870 if (idx() > lastidx()) {
1871 lyxerr << "this should not really happen - 1: "
1872 << idx() << ' ' << nargs()
1873 << " in: " << &inset() << endl;
1877 if (pos() > lastpos()) {
1878 lyxerr << "this should not really happen - 2: "
1879 << pos() << ' ' << lastpos() << " in idx: " << idx()
1881 odocstringstream os;
1882 otexrowstream ots(os);
1883 WriteStream wi(ots, false, true, WriteStream::wsDefault);
1884 inset().asInsetMath()->write(wi);
1885 lyxerr << to_utf8(os.str()) << endl;
1891 bool Cursor::upDownInMath(bool up)
1893 // Be warned: The 'logic' implemented in this function is highly
1894 // fragile. A distance of one pixel or a '<' vs '<=' _really
1895 // matters. So fiddle around with it only if you think you know
1896 // what you are doing!
1900 xo = beforeDispatchPosX_;
1902 // check if we had something else in mind, if not, this is the future
1904 if (x_target_ == -1)
1906 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1907 // In text mode inside the line (not left or right) possibly set a new target_x,
1908 // but only if we are somewhere else than the previous target-offset.
1910 // We want to keep the x-target on subsequent up/down movements
1911 // that cross beyond the end of short lines. Thus a special
1912 // handling when the cursor is at the end of line: Use the new
1913 // x-target only if the old one was before the end of line
1914 // or the old one was after the beginning of the line
1915 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
1919 left = pos() == textRow().endpos();
1920 right = pos() == textRow().pos();
1922 left = pos() == textRow().pos();
1923 right = pos() == textRow().endpos();
1925 if ((!left && !right) ||
1926 (left && !right && xo < x_target_) ||
1927 (!left && right && x_target_ < xo))
1934 // try neigbouring script insets
1936 if (inMathed() && !selection()) {
1939 InsetMathScript const * p = prevAtom()->asScriptInset();
1940 if (p && p->has(up)) {
1942 push(*const_cast<InsetMathScript*>(p));
1943 idx() = p->idxOfScript(up);
1946 // we went in the right direction? Otherwise don't jump into the script
1950 int oy = beforeDispatchPosY_;
1951 if ((!up && y <= oy) ||
1960 if (pos() != lastpos()) {
1961 InsetMathScript const * p = nextAtom()->asScriptInset();
1962 if (p && p->has(up)) {
1963 push(*const_cast<InsetMathScript*>(p));
1964 idx() = p->idxOfScript(up);
1967 // we went in the right direction? Otherwise don't jump into the script
1971 int oy = beforeDispatchPosY_;
1972 if ((!up && y <= oy) ||
1981 // try to find an inset that knows better then we,
1982 if (inset().idxUpDown(*this, up)) {
1983 //lyxerr << "idxUpDown triggered" << endl;
1984 // try to find best position within this inset
1986 setCursor(bruteFind(*this, xo, yo));
1990 // any improvement going just out of inset?
1991 if (popBackward() && inMathed()) {
1992 //lyxerr << "updown: popBackward succeeded" << endl;
1995 int yold = beforeDispatchPosY_;
1997 if (up ? ynew < yold : ynew > yold)
2001 // no success, we are probably at the document top or bottom
2007 bool Cursor::mathForward(bool word)
2009 LASSERT(inMathed(), return false);
2010 if (pos() < lastpos()) {
2012 // word: skip a group of insets of the form X*(B*|R*|P*) (greedy
2013 // match) where X is any math class, B is mathbin, R is mathrel, and
2014 // P is mathpunct. Make sure that the following remains true:
2015 // mathForward(true); mathBackward(true); mathForward(true)
2016 // is the same as mathForward(true) and
2017 // mathBackward(true); mathForward(true); mathBackward(true)
2018 // is the same as mathBackward(true).
2019 MathClass mc = nextMath().mathClass();
2022 while (pos() < lastpos() && mc == nextMath().mathClass());
2023 if (pos() < lastpos() &&
2024 ((mc = nextMath().mathClass()) == MC_BIN ||
2025 mc == MC_REL || mc == MC_PUNCT))
2028 while (pos() < lastpos() && mc == nextMath().mathClass());
2029 } else if (openable(nextAtom())) {
2030 // single step: try to enter the next inset
2031 pushBackward(nextMath());
2032 inset().idxFirst(*this);
2037 if (inset().idxForward(*this))
2039 // try to pop forwards --- but don't pop out of math! leave that to
2041 int s = depth() - 2;
2042 if (s >= 0 && operator[](s).inset().asInsetMath())
2043 return popForward();
2048 bool Cursor::mathBackward(bool word)
2050 LASSERT(inMathed(), return false);
2053 // word: skip a group of insets. See the comment in mathForward.
2054 MathClass mc = prevMath().mathClass();
2057 while (pos() > 0 && mc == prevMath().mathClass());
2058 if (pos() > 0 && (mc == MC_BIN || mc == MC_REL || mc == MC_PUNCT)) {
2059 mc = prevMath().mathClass();
2062 while (pos() > 0 && mc == prevMath().mathClass());
2064 } else if (openable(prevAtom())) {
2065 // single step: try to enter the preceding inset
2068 inset().idxLast(*this);
2073 if (inset().idxBackward(*this))
2075 // try to pop backwards --- but don't pop out of math! leave that to
2077 int s = depth() - 2;
2078 if (s >= 0 && operator[](s).inset().asInsetMath())
2079 return popBackward();
2084 bool Cursor::upDownInText(bool up, bool & updateNeeded)
2086 LASSERT(text(), return false);
2092 xo = beforeDispatchPosX_;
2094 // update the targetX - this is here before the "return false"
2095 // to set a new target which can be used by InsetTexts above
2096 // if we cannot move up/down inside this inset anymore
2097 if (x_target_ == -1)
2099 else if (xo - textTargetOffset() != x_target() &&
2100 depth() == beforeDispatchCursor_.depth()) {
2101 // In text mode inside the line (not left or right)
2102 // possibly set a new target_x, but only if we are
2103 // somewhere else than the previous target-offset.
2105 // We want to keep the x-target on subsequent up/down
2106 // movements that cross beyond the end of short lines.
2107 // Thus a special handling when the cursor is at the
2108 // end of line: Use the new x-target only if the old
2109 // one was before the end of line or the old one was
2110 // after the beginning of the line
2111 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
2115 left = pos() == textRow().endpos();
2116 right = pos() == textRow().pos();
2118 left = pos() == textRow().pos();
2119 right = pos() == textRow().endpos();
2121 if ((!left && !right) ||
2122 (left && !right && xo < x_target_) ||
2123 (!left && right && x_target_ < xo))
2130 // first get the current line
2131 TextMetrics & tm = bv_->textMetrics(text());
2132 ParagraphMetrics const & pm = tm.parMetrics(pit());
2134 if (pos() && boundary())
2135 row = pm.pos2row(pos() - 1);
2137 row = pm.pos2row(pos());
2139 if (atFirstOrLastRow(up)) {
2140 // Is there a place for the cursor to go ? If yes, we
2141 // can execute the DEPM, otherwise we should keep the
2142 // paragraph to host the cursor.
2143 Cursor dummy = *this;
2144 bool valid_destination = false;
2145 for(; dummy.depth(); dummy.pop())
2146 if (!dummy.atFirstOrLastRow(up)) {
2147 valid_destination = true;
2151 // will a next dispatch follow and if there is a new
2152 // dispatch will it move the cursor out ?
2153 if (depth() > 1 && valid_destination) {
2154 // The cursor hasn't changed yet. This happens when
2155 // you e.g. move out of an inset. And to give the
2156 // DEPM the possibility of doing something we must
2157 // provide it with two different cursors. (Lgb, vfr)
2159 dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
2160 dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
2162 updateNeeded |= bv().checkDepm(dummy, *this);
2163 updateTextTargetOffset();
2165 forceBufferUpdate();
2170 // with and without selection are handled differently
2172 int yo1 = bv().getPos(*this).y_;
2174 // To next/previous row
2175 // FIXME: the y position is often guessed wrongly across styles and
2176 // insets, which leads to weird behaviour.
2178 tm.editXY(*this, xo, yo1 - textRow().ascent() - 1);
2180 tm.editXY(*this, xo, yo1 + textRow().descent() + 1);
2181 x_target_ = old.x_target_;
2184 // This happens when you move out of an inset.
2185 // And to give the DEPM the possibility of doing
2186 // something we must provide it with two different
2188 Cursor dummy = *this;
2191 if (bv().checkDepm(dummy, old)) {
2192 updateNeeded = true;
2193 // Make sure that cur gets back whatever happened to dummy (Lgb)
2196 if (inTexted() && pos() && paragraph().isEnvSeparator(pos() - 1))
2199 // if there is a selection, we stay out of any inset,
2200 // and just jump to the right position:
2206 } else if (pit() > 0) {
2208 TextMetrics & tm2 = bv_->textMetrics(text());
2209 if (!tm2.contains(pit()))
2210 tm2.newParMetricsUp();
2211 ParagraphMetrics const & pmcur = tm2.parMetrics(pit());
2212 next_row = pmcur.rows().size() - 1;
2215 if (row + 1 < int(pm.rows().size())) {
2217 } else if (pit() + 1 < int(text()->paragraphs().size())) {
2219 TextMetrics & tm2 = bv_->textMetrics(text());
2220 if (!tm2.contains(pit()))
2221 tm2.newParMetricsDown();
2226 Row const & real_next_row = tm.parMetrics(pit()).rows()[next_row];
2228 top().pos() = tm.getPosNearX(real_next_row, xo, bound);
2230 // When selection==false, this is done by TextMetrics::editXY
2233 updateNeeded |= bv().checkDepm(*this, old);
2237 forceBufferUpdate();
2238 updateTextTargetOffset();
2243 void Cursor::handleFont(string const & font)
2245 LYXERR(Debug::DEBUG, font);
2249 safe = cap::grabAndEraseSelection(*this);
2254 if (lastpos() != 0) {
2255 // something left in the cell
2257 // cursor in first position
2259 } else if (pos() == lastpos()) {
2260 // cursor in last position
2263 // cursor in between. split cell
2264 MathData::iterator bt = cell().begin();
2265 MathAtom at = createInsetMath(from_utf8(font), buffer());
2266 at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
2267 cell().erase(bt, bt + pos());
2272 // nothing left in the cell
2281 void Cursor::undispatched() const
2283 disp_.dispatched(false);
2287 void Cursor::dispatched() const
2289 disp_.dispatched(true);
2293 void Cursor::screenUpdateFlags(Update::flags f) const
2295 disp_.screenUpdate(f);
2299 void Cursor::noScreenUpdate() const
2301 disp_.screenUpdate(Update::None);
2305 void Cursor::forceBufferUpdate() const
2307 disp_.forceBufferUpdate();
2311 void Cursor::clearBufferUpdate() const
2313 disp_.clearBufferUpdate();
2317 bool Cursor::needBufferUpdate() const
2319 return disp_.needBufferUpdate();
2323 Font Cursor::getFont() const
2325 // The logic here should more or less match to the
2326 // Cursor::setCurrentFont logic, i.e. the cursor height should
2327 // give a hint what will happen if a character is entered.
2328 // FIXME: this is not the case, what about removing this method ? (see #10478).
2330 // HACK. far from being perfect...
2332 CursorSlice const & sl = innerTextSlice();
2333 Text const & text = *sl.text();
2334 Paragraph const & par = text.getPar(sl.pit());
2336 // on boundary, so we are really at the character before
2337 pos_type pos = sl.pos();
2338 if (pos > 0 && boundary())
2341 // on space? Take the font before (only for RTL boundary stay)
2343 TextMetrics const & tm = bv().textMetrics(&text);
2344 if (pos == sl.lastpos()
2345 || (par.isSeparator(pos)
2346 && !tm.isRTLBoundary(sl.pit(), pos)))
2350 // get font at the position
2351 Font font = par.getFont(buffer()->params(), pos,
2352 text.outerFont(sl.pit()));
2358 void Cursor::sanitize()
2360 setBuffer(&bv_->buffer());
2361 CursorData::sanitize();
2365 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2367 // find inset in common
2369 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2370 if (&old[i].inset() != &cur[i].inset())
2374 // update words if we just moved to another paragraph
2375 if (i == old.depth() && i == cur.depth()
2376 && !cur.buffer()->isClean()
2377 && cur.inTexted() && old.inTexted()
2378 && cur.pit() != old.pit()) {
2379 old.paragraph().updateWords();
2382 // notify everything on top of the common part in old cursor,
2383 // but stop if the inset claims the cursor to be invalid now
2384 for (size_type j = i; j < old.depth(); ++j) {
2385 Cursor inset_pos = old;
2386 inset_pos.cutOff(j);
2387 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2391 // notify everything on top of the common part in new cursor,
2392 // but stop if the inset claims the cursor to be invalid now
2393 for (; i < cur.depth(); ++i) {
2394 if (cur[i].inset().notifyCursorEnters(cur))
2402 void Cursor::setLanguageFromInput()
2404 if (!lyxrc.respect_os_kbd_language)
2406 string const & code = theApp()->inputLanguageCode();
2407 Language const * lang = languages.getFromCode(code, buffer()->getLanguages());
2409 current_font.setLanguage(lang);
2410 real_current_font.setLanguage(lang);
2412 LYXERR0("setLanguageFromCode: unknown language code " << code);
2416 void Cursor::setCurrentFont()
2418 CursorSlice const & cs = innerTextSlice();
2419 Paragraph const & par = cs.paragraph();
2420 pos_type cpit = cs.pit();
2421 pos_type cpos = cs.pos();
2422 Text const & ctext = *cs.text();
2423 TextMetrics const & tm = bv().textMetrics(&ctext);
2425 // are we behind previous char in fact? -> go to that char
2426 if (cpos > 0 && boundary())
2429 // find position to take the font from
2431 // paragraph end? -> font of last char
2432 if (cpos == lastpos())
2434 // on space? -> look at the words in front of space
2435 else if (cpos > 0 && par.isSeparator(cpos)) {
2436 // abc| def -> font of c
2437 // abc |[WERBEH], i.e. boundary==true -> font of c
2438 // abc [WERBEH]| def, font of the space
2439 if (!tm.isRTLBoundary(cpit, cpos))
2445 BufferParams const & bufparams = buffer()->params();
2446 current_font = par.getFontSettings(bufparams, cpos);
2447 real_current_font = tm.displayFont(cpit, cpos);
2449 // set language to input language
2450 setLanguageFromInput();
2452 // special case for paragraph end
2453 if (cs.pos() == lastpos()
2454 && tm.isRTLBoundary(cpit, cs.pos())
2456 Language const * lang = par.getParLanguage(bufparams);
2457 current_font.setLanguage(lang);
2458 current_font.fontInfo().setNumber(FONT_OFF);
2459 real_current_font.setLanguage(lang);
2460 real_current_font.fontInfo().setNumber(FONT_OFF);
2465 void Cursor::checkBufferStructure()
2467 Buffer const * master = buffer()->masterBuffer();
2468 master->tocBackend().updateItem(*this);
2469 if (master != buffer() && !master->hasGuiDelegate())
2470 // In case the master has no gui associated with it,
2471 // the TocItem is not updated (part of bug 5699).
2472 buffer()->tocBackend().updateItem(*this);
2474 // If the last tracked change of the paragraph has just been
2475 // deleted, then we need to recompute the buffer flag
2476 // tracked_changes_present_.
2477 if (inTexted() && paragraph().isChangeUpdateRequired())
2478 disp_.forceChangesUpdate();
2482 void Cursor::moveToClosestEdge(int const x, bool const edit)
2484 if (Inset const * inset = nextInset()) {
2485 // stay in front of insets for which we want to open the dialog
2486 // (e.g. InsetMathSpace).
2487 if (edit && (inset->hasSettings() || !inset->contextMenuName().empty()))
2489 CoordCache::Insets const & insetCache = bv().coordCache().getInsets();
2490 if (!insetCache.has(inset))
2492 int const wid = insetCache.dim(inset).wid;
2493 Point p = insetCache.xy(inset);
2494 if (x > p.x_ + (wid + 1) / 2)