3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alejandro Aguilar Sierra
7 * \author Alfredo Braunstein
8 * \author Dov Feldstern
10 * \author Stefan Schimanski
12 * Full author contact details are available in file CREDITS.
18 #include "BufferView.h"
19 #include "CoordCache.h"
21 #include "CutAndPaste.h"
22 #include "DispatchResult.h"
24 #include "FuncRequest.h"
26 #include "LyXAction.h"
28 #include "Paragraph.h"
29 #include "ParIterator.h"
31 #include "texstream.h"
33 #include "TextMetrics.h"
34 #include "TocBackend.h"
36 #include "support/debug.h"
37 #include "support/docstream.h"
38 #include "support/ExceptionMessage.h"
39 #include "support/gettext.h"
40 #include "support/lassert.h"
42 #include "insets/InsetTabular.h"
43 #include "insets/InsetText.h"
45 #include "mathed/InsetMath.h"
46 #include "mathed/InsetMathBrace.h"
47 #include "mathed/InsetMathEnsureMath.h"
48 #include "mathed/InsetMathScript.h"
49 #include "mathed/MacroTable.h"
50 #include "mathed/MathData.h"
51 #include "mathed/MathFactory.h"
52 #include "mathed/InsetMathMacro.h"
65 // Find position closest to (x, y) in cell given by iter.
66 // Used only in mathed
67 DocIterator bruteFind(Cursor const & c, int x, int y)
69 double best_dist = numeric_limits<double>::max();
76 et.pos() = et.lastpos();
77 for (size_t i = 0;; ++i) {
80 Inset const * inset = &it.inset();
81 CoordCache::Insets const & insetCache = c.bv().coordCache().getInsets();
83 // FIXME: in the case where the inset is not in the cache, this
84 // means that no part of it is visible on screen. In this case
85 // we don't do elaborate search and we just return the forwarded
86 // DocIterator at its beginning.
87 if (!insetCache.has(inset)) {
92 Point const o = insetCache.xy(inset);
93 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
94 // Convert to absolute
97 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
98 // '<=' in order to take the last possible position
99 // this is important for clicking behind \sum in e.g. '\sum_i a'
100 LYXERR(Debug::DEBUG, "i: " << i << " d: " << d
101 << " best: " << best_dist);
102 if (d <= best_dist) {
122 CursorData::CursorData()
123 : DocIterator(), anchor_(), selection_(false), mark_(false),
124 word_selection_(false), autocorrect_(false), current_font(inherit_font)
128 CursorData::CursorData(Buffer * buffer)
129 : DocIterator(buffer), anchor_(), selection_(false), mark_(false),
130 word_selection_(false), autocorrect_(false), current_font(inherit_font)
134 CursorData::CursorData(DocIterator const & dit)
135 : DocIterator(dit), anchor_(), selection_(false), mark_(false),
136 word_selection_(false), autocorrect_(false), current_font(inherit_font)
142 ostream & operator<<(ostream & os, CursorData const & cur)
144 os << "\n cursor: | anchor:\n";
145 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
146 os << " " << cur[i] << " | ";
147 if (i < cur.anchor_.depth())
148 os << cur.anchor_[i];
150 os << "-------------------------------";
153 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
154 os << "------------------------------- | " << cur.anchor_[i] << "\n";
156 os << " selection: " << cur.selection_
157 // << " x_target: " << cur.x_target_
158 << " boundary: " << cur.boundary() << endl;
163 LyXErr & operator<<(LyXErr & os, CursorData const & cur)
170 void CursorData::reset()
173 push_back(CursorSlice(buffer()->inset()));
174 anchor_ = doc_iterator_begin(buffer());
176 new_word_ = doc_iterator_begin(buffer());
183 void CursorData::setCursor(DocIterator const & cur)
185 DocIterator::operator=(cur);
189 void CursorData::setCursorSelectionTo(DocIterator dit)
193 while (i < dit.depth() && i < anchor_.depth() && dit[i] == anchor_[i])
195 if (i != dit.depth()) {
196 // otherwise the cursor is already normal
197 if (i == anchor_.depth())
198 // dit is a proper extension of the anchor_
200 else if (i + 1 < dit.depth()) {
201 // one has dit[i] != anchor_[i] but either dit[i-1] == anchor_[i-1]
202 // or i == 0. Remove excess.
204 if (dit[i] > anchor_[i])
205 // place dit after the inset it was in
214 void CursorData::setCursorToAnchor()
217 DocIterator normal = anchor_;
218 while (depth() < normal.depth())
220 if (depth() < anchor_.depth() && top() <= anchor_[depth() - 1])
227 CursorSlice CursorData::normalAnchor() const
231 // LASSERT: There have been several bugs around this code, that seem
232 // to involve failures to reset the anchor. We can at least not crash
233 // in release mode by resetting it ourselves.
234 if (anchor_.depth() < depth()) {
235 LYXERR0("Cursor is deeper than anchor. PLEASE REPORT.\nCursor is"
237 const_cast<DocIterator &>(anchor_) = *this;
240 CursorSlice normal = anchor_[depth() - 1];
241 if (depth() < anchor_.depth() && top() <= normal) {
242 // anchor is behind cursor -> move anchor behind the inset
249 void CursorData::setSelection()
252 if (idx() == normalAnchor().idx() &&
253 pit() == normalAnchor().pit() &&
254 pos() == normalAnchor().pos())
259 void CursorData::setSelection(DocIterator const & where, int n)
268 void CursorData::resetAnchor()
271 checkNewWordPosition();
275 CursorSlice CursorData::selBegin() const
279 return normalAnchor() < top() ? normalAnchor() : top();
283 CursorSlice CursorData::selEnd() const
287 return normalAnchor() > top() ? normalAnchor() : top();
291 DocIterator CursorData::selectionBegin() const
297 // FIXME: This is a work-around for the problem that
298 // CursorSlice doesn't keep track of the boundary.
299 if (normalAnchor() == top())
300 di = anchor_.boundary() > boundary() ? anchor_ : *this;
302 di = normalAnchor() < top() ? anchor_ : *this;
308 DocIterator CursorData::selectionEnd() const
314 // FIXME: This is a work-around for the problem that
315 // CursorSlice doesn't keep track of the boundary.
316 if (normalAnchor() == top())
317 di = anchor_.boundary() < boundary() ? anchor_ : *this;
319 di = normalAnchor() > top() ? anchor_ : *this;
321 if (di.depth() > depth()) {
331 docstring parbreak(CursorData const * cur)
335 // only add blank line if we're not in a ParbreakIsNewline situation
336 if (!cur->inset().getLayout().parbreakIsNewline()
337 && !cur->paragraph().layout().parbreak_is_newline)
345 docstring CursorData::selectionAsString(bool with_label) const
351 return cap::grabSelection(*this);
353 int const label = with_label
354 ? AS_STR_LABEL | AS_STR_INSETS : AS_STR_INSETS;
356 idx_type const startidx = selBegin().idx();
357 idx_type const endidx = selEnd().idx();
358 if (startidx != endidx) {
359 // multicell selection
360 InsetTabular * table = inset().asInsetTabular();
361 LASSERT(table, return docstring());
362 return table->asString(startidx, endidx);
365 ParagraphList const & pars = text()->paragraphs();
367 pit_type const startpit = selBegin().pit();
368 pit_type const endpit = selEnd().pit();
369 size_t const startpos = selBegin().pos();
370 size_t const endpos = selEnd().pos();
372 if (startpit == endpit)
373 return pars[startpit].asString(startpos, endpos, label);
375 // First paragraph in selection
376 docstring result = pars[startpit].
377 asString(startpos, pars[startpit].size(), label)
380 // The paragraphs in between (if any)
381 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
382 Paragraph const & par = pars[pit];
383 result += par.asString(0, par.size(), label)
387 // Last paragraph in selection
388 result += pars[endpit].asString(0, endpos, label);
394 void CursorData::info(odocstream & os, bool devel_mode) const
396 for (int i = 1, n = depth(); i < n; ++i) {
397 operator[](i).inset().infoize(os);
401 Inset const * inset = prevInset();
402 // prevInset() can return 0 in certain case.
404 prevInset()->infoize2(os);
407 InsetMath * math = inset().asInsetMath();
409 os << _(", Inset: ") << math->id();
410 os << _(", Cell: ") << idx();
411 os << _(", Position: ") << pos();
416 docstring CursorData::currentState(bool devel_mode) const
420 info(os, devel_mode);
425 return text()->currentState(*this, devel_mode);
431 void CursorData::markNewWordPosition()
433 if (lyxrc.spellcheck_continuously && inTexted() && new_word_.empty()) {
434 FontSpan nw = locateWord(WHOLE_WORD);
435 if (nw.size() == 1) {
436 LYXERR(Debug::DEBUG, "start new word: "
438 << " pos: " << nw.first);
445 void CursorData::clearNewWordPosition()
447 if (!new_word_.empty()) {
448 LYXERR(Debug::DEBUG, "clear new word: "
450 << " pos: " << pos());
456 void CursorData::checkNewWordPosition()
458 if (!lyxrc.spellcheck_continuously || new_word_.empty())
460 // forget the position of the current new word if
461 // 1) or the remembered position was "broken"
462 // 2) or the count of nested insets changed
463 // 3) the top-level inset is not the same anymore
464 // 4) the cell index changed
465 // 5) or the paragraph changed
466 // 6) or the cursor pos is out of paragraph bound
467 if (new_word_.fixIfBroken()
468 || depth() != new_word_.depth()
469 || &inset() != &new_word_.inset()
470 || pit() != new_word_.pit()
471 || idx() != new_word_.idx()
472 || new_word_.pos() > new_word_.lastpos())
473 clearNewWordPosition();
475 FontSpan nw = locateWord(WHOLE_WORD);
477 FontSpan ow = new_word_.locateWord(WHOLE_WORD);
478 if (nw.intersect(ow).empty())
479 clearNewWordPosition();
481 LYXERR(Debug::DEBUG, "new word: "
483 << " pos: " << nw.first << ".." << nw.last);
485 clearNewWordPosition();
490 void CursorData::clearSelection()
493 setWordSelection(false);
499 int CursorData::countInsetsInSelection(InsetCode const & inset_code)
504 DocIterator from, to;
505 from = selectionBegin();
510 if (!from.nextInset()) //move to closest inset
513 while (!from.empty() && from < to) {
514 Inset * inset = from.nextInset();
517 if (inset->lyxCode() == inset_code)
525 bool CursorData::insetInSelection(InsetCode const & inset_code)
530 DocIterator from, to;
531 from = selectionBegin();
534 if (!from.nextInset()) //move to closest inset
537 while (!from.empty() && from < to) {
538 Inset * inset = from.nextInset();
541 if (inset->lyxCode() == inset_code)
549 bool CursorData::fixIfBroken()
551 bool const broken_cursor = DocIterator::fixIfBroken();
552 bool const broken_anchor = anchor_.fixIfBroken();
554 if (broken_cursor || broken_anchor) {
555 clearNewWordPosition();
563 void CursorData::sanitize()
565 DocIterator::sanitize();
566 new_word_.sanitize();
574 bool CursorData::undoAction()
576 if (!buffer()->undo().undoAction(*this))
583 bool CursorData::redoAction()
585 if (!buffer()->undo().redoAction(*this))
592 void CursorData::finishUndo() const
594 buffer()->undo().finishUndo();
598 void CursorData::beginUndoGroup() const
600 buffer()->undo().beginUndoGroup(*this);
604 void CursorData::endUndoGroup() const
606 buffer()->undo().endUndoGroup(*this);
610 void CursorData::recordUndo(pit_type from, pit_type to) const
612 buffer()->undo().recordUndo(*this, from, to);
616 void CursorData::recordUndo(pit_type from) const
618 buffer()->undo().recordUndo(*this, from, pit());
622 void CursorData::recordUndo(UndoKind kind) const
624 buffer()->undo().recordUndo(*this, kind);
628 void CursorData::recordUndoInset(Inset const * in) const
630 buffer()->undo().recordUndoInset(*this, in);
634 void CursorData::recordUndoFullBuffer() const
636 buffer()->undo().recordUndoFullBuffer(*this);
640 void CursorData::recordUndoBufferParams() const
642 buffer()->undo().recordUndoBufferParams(*this);
646 void CursorData::recordUndoSelection() const
649 if (cap::multipleCellsSelected(*this))
654 buffer()->undo().recordUndo(*this,
655 selBegin().pit(), selEnd().pit());
660 int CursorData::currentMode()
662 LASSERT(!empty(), return Inset::UNDECIDED_MODE);
663 for (int i = depth() - 1; i >= 0; --i) {
664 int res = operator[](i).inset().currentMode();
665 bool locked_mode = operator[](i).inset().lockedMode();
666 // Also return UNDECIDED_MODE when the mode is locked,
667 // as in this case it is treated the same as TEXT_MODE
668 if (res != Inset::UNDECIDED_MODE || locked_mode)
671 return Inset::TEXT_MODE;
675 bool CursorData::confirmDeletion(bool const before) const
678 if (Inset const * inset = before ? prevInset() : nextInset())
679 return inset->confirmDeletion();
681 DocIterator dit = selectionBegin();
682 CursorSlice const end = selectionEnd().top();
683 for (; dit.top() < end; dit.top().forwardPos())
684 if (Inset const * inset = dit.nextInset())
685 if (inset->confirmDeletion())
698 // be careful: this is called from the bv's constructor, too, so
699 // bv functions are not yet available!
700 Cursor::Cursor(BufferView & bv)
701 : CursorData(&bv.buffer()), bv_(&bv),
702 x_target_(-1), textTargetOffset_(0),
703 beforeDispatchPosX_(0), beforeDispatchPosY_(0)
714 void Cursor::setCursorData(CursorData const & data)
716 CursorData::operator=(data);
720 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
724 // Try to fix cursor in case it is broken.
727 // Is this a function that acts on inset at point?
728 Inset * inset = cur.nextInset();
729 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
730 && inset && inset->getStatus(cur, cmd, status))
733 // This is, of course, a mess. Better create a new doc iterator and use
734 // this in Inset::getStatus. This might require an additional
735 // BufferView * arg, though (which should be avoided)
736 //Cursor safe = *this;
738 for ( ; cur.depth(); cur.pop()) {
739 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
740 // LASSERT: Is it safe to continue here, or should we return?
741 LASSERT(cur.idx() <= cur.lastidx(), /**/);
742 LASSERT(cur.pit() <= cur.lastpit(), /**/);
743 LASSERT(cur.pos() <= cur.lastpos(), /**/);
745 // The inset's getStatus() will return 'true' if it made
746 // a definitive decision on whether it want to handle the
747 // request or not. The result of this decision is put into
748 // the 'status' parameter.
749 if (cur.inset().getStatus(cur, cmd, status)) {
758 void Cursor::saveBeforeDispatchPosXY()
760 getPos(beforeDispatchPosX_, beforeDispatchPosY_);
764 void Cursor::dispatch(FuncRequest const & cmd0)
766 LYXERR(Debug::ACTION, "Cursor::dispatch: cmd: " << cmd0 << '\n' << *this);
771 FuncRequest cmd = cmd0;
774 disp_ = DispatchResult();
778 // Is this a function that acts on inset at point?
779 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
781 disp_.dispatched(true);
782 disp_.screenUpdate(Update::FitCursor | Update::Force);
783 FuncRequest tmpcmd = cmd;
784 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
785 << cmd0 << endl << *this);
786 nextInset()->dispatch(*this, tmpcmd);
787 if (disp_.dispatched()) {
793 // store some values to be used inside of the handlers
794 beforeDispatchCursor_ = *this;
795 for (; depth(); pop(), boundary(false)) {
796 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
797 << cmd0 << endl << *this);
799 // In any of these cases, the cursor is invalid, and we should
800 // try to save this document rather than crash.
801 LBUFERR(pos() <= lastpos());
802 LBUFERR(idx() <= lastidx());
803 LBUFERR(pit() <= lastpit());
805 // The common case is 'LFUN handled, need update', so make the
806 // LFUN handler's life easier by assuming this as default value.
807 // The handler can reset the update and val flags if necessary.
808 disp_.screenUpdate(Update::FitCursor | Update::Force);
809 disp_.dispatched(true);
810 inset().dispatch(*this, cmd);
811 if (disp_.dispatched())
815 // it completely to get a 'bomb early' behaviour in case this
816 // object will be used again.
817 if (!disp_.dispatched()) {
818 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
819 // We might have invalidated the cursor when removing an empty
820 // paragraph while the cursor could not be moved out the inset
821 // while we initially thought we could. This might happen when
822 // a multiline inset becomes an inline inset when the second
823 // paragraph is removed.
824 if (safe.pit() > safe.lastpit()) {
825 safe.pit() = safe.lastpit();
826 safe.pos() = safe.lastpos();
829 disp_.screenUpdate(Update::None);
830 disp_.dispatched(false);
832 // restore the previous one because nested Cursor::dispatch calls
833 // are possible which would change it
834 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
838 // NOTE: The code below has been copied to BufferView::dispatch.
839 // If you need to modify this, please update the other one too.
841 // notify insets we just left
843 old.beginUndoGroup();
845 bool badcursor = notifyCursorLeavesOrEnters(old, *this);
848 bv().resetInlineCompletionPos();
855 DispatchResult const & Cursor::result() const
861 void Cursor::message(docstring const & msg) const
863 disp_.setMessage(msg);
867 void Cursor::errorMessage(docstring const & msg) const
869 disp_.setMessage(msg);
870 disp_.setError(true);
874 BufferView & Cursor::bv() const
883 LBUFERR(depth() >= 1);
888 void Cursor::push(Inset & p)
890 push_back(CursorSlice(p));
891 p.setBuffer(*buffer());
895 void Cursor::pushBackward(Inset & p)
897 LASSERT(!empty(), return);
898 //lyxerr << "Entering inset " << t << " front" << endl;
904 void Cursor::editInsertedInset()
906 LASSERT(!empty(), return);
910 InsetMath &p = prevMath();
917 // this could be a while() loop, but only one cell is not empty in
918 // cases we are interested in. The cell is not empty because we
919 // have inserted the selection in there.
920 if (!cell().empty()) {
921 // if it is not empty, move to the next one.
922 if (!inset().idxNext(*this))
923 // If there is no next one, exit the inset.
929 bool Cursor::popBackward()
931 LASSERT(!empty(), return false);
939 bool Cursor::popForward()
941 LASSERT(!empty(), return false);
942 //lyxerr << "Leaving inset from in back" << endl;
943 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
947 pos() += lastpos() - lp + 1;
952 void Cursor::getPos(int & x, int & y) const
954 Point p = bv().getPos(*this);
960 Row const & Cursor::textRow() const
962 CursorSlice const & cs = innerTextSlice();
963 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
964 return pm.getRow(pos(), boundary());
968 bool Cursor::posVisRight(bool skip_inset)
970 Cursor new_cur = *this; // where we will move to
971 pos_type left_pos; // position visually left of current cursor
972 pos_type right_pos; // position visually right of current cursor
974 getSurroundingPos(left_pos, right_pos);
976 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
978 // Are we at an inset?
979 new_cur.pos() = right_pos;
980 new_cur.boundary(false);
982 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
983 // we actually move the cursor at the end of this
984 // function, for now we just keep track of the new
985 // position in new_cur...
986 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
989 // Are we already at rightmost pos in row?
990 else if (text()->empty() || right_pos == -1) {
993 if (!new_cur.posVisToNewRow(false)) {
994 LYXERR(Debug::RTL, "not moving!");
998 // we actually move the cursor at the end of this
999 // function, for now just keep track of the new
1000 // position in new_cur...
1001 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
1002 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
1005 // normal movement to the right
1008 // Recall, if the cursor is at position 'x', that
1009 // means *before* the character at position 'x'. In
1010 // RTL, "before" means "to the right of", in LTR, "to
1011 // the left of". So currently our situation is this:
1012 // the position to our right is 'right_pos' (i.e.,
1013 // we're currently to the left of 'right_pos'). In
1014 // order to move to the right, it depends whether or
1015 // not the character at 'right_pos' is RTL.
1016 bool const new_pos_is_RTL = paragraph().getFontSettings(
1017 buffer()->params(), right_pos).isVisibleRightToLeft();
1018 // If the character at 'right_pos' *is* LTR, then in
1019 // order to move to the right of it, we need to be
1020 // *after* 'right_pos', i.e., move to position
1022 if (!new_pos_is_RTL) {
1023 new_cur.pos() = right_pos + 1;
1024 // set the boundary to true in two situations:
1026 // 1. if new_pos is now lastpos, and we're in
1027 // an RTL paragraph (this means that we're
1028 // moving right to the end of an LTR chunk
1029 // which is at the end of an RTL paragraph);
1030 (new_cur.pos() == lastpos()
1031 && paragraph().isRTL(buffer()->params()))
1032 // 2. if the position *after* right_pos is RTL
1033 // (we want to be *after* right_pos, not
1034 // before right_pos + 1!)
1035 || paragraph().getFontSettings(buffer()->params(),
1036 new_cur.pos()).isVisibleRightToLeft()
1038 new_cur.boundary(true);
1039 else // set the boundary to false
1040 new_cur.boundary(false);
1042 // Otherwise (if the character at position 'right_pos'
1043 // is RTL), then moving to the right of it is as easy
1044 // as setting the new position to 'right_pos'.
1046 new_cur.pos() = right_pos;
1047 new_cur.boundary(false);
1052 bool const moved = new_cur != *this || new_cur.boundary() != boundary();
1055 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
1056 << (new_cur.boundary() ? " (boundary)" : ""));
1064 bool Cursor::posVisLeft(bool skip_inset)
1066 Cursor new_cur = *this; // where we will move to
1067 pos_type left_pos; // position visually left of current cursor
1068 pos_type right_pos; // position visually right of current cursor
1070 getSurroundingPos(left_pos, right_pos);
1072 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
1074 // Are we at an inset?
1075 new_cur.pos() = left_pos;
1076 new_cur.boundary(false);
1078 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
1079 // we actually move the cursor at the end of this
1080 // function, for now we just keep track of the new
1081 // position in new_cur...
1082 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
1085 // Are we already at leftmost pos in row?
1086 else if (text()->empty() || left_pos == -1) {
1089 if (!new_cur.posVisToNewRow(true)) {
1090 LYXERR(Debug::RTL, "not moving!");
1094 // we actually move the cursor at the end of this
1095 // function, for now just keep track of the new
1096 // position in new_cur...
1097 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
1098 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
1101 // normal movement to the left
1104 // Recall, if the cursor is at position 'x', that
1105 // means *before* the character at position 'x'. In
1106 // RTL, "before" means "to the right of", in LTR, "to
1107 // the left of". So currently our situation is this:
1108 // the position to our left is 'left_pos' (i.e., we're
1109 // currently to the right of 'left_pos'). In order to
1110 // move to the left, it depends whether or not the
1111 // character at 'left_pos' is RTL.
1112 bool const new_pos_is_RTL = paragraph().getFontSettings(
1113 buffer()->params(), left_pos).isVisibleRightToLeft();
1114 // If the character at 'left_pos' *is* RTL, then in
1115 // order to move to the left of it, we need to be
1116 // *after* 'left_pos', i.e., move to position
1118 if (new_pos_is_RTL) {
1119 new_cur.pos() = left_pos + 1;
1120 // set the boundary to true in two situations:
1122 // 1. if new_pos is now lastpos and we're in
1123 // an LTR paragraph (this means that we're
1124 // moving left to the end of an RTL chunk
1125 // which is at the end of an LTR paragraph);
1126 (new_cur.pos() == lastpos()
1127 && !paragraph().isRTL(buffer()->params()))
1128 // 2. if the position *after* left_pos is not
1129 // RTL (we want to be *after* left_pos, not
1130 // before left_pos + 1!)
1131 || !paragraph().getFontSettings(buffer()->params(),
1132 new_cur.pos()).isVisibleRightToLeft()
1134 new_cur.boundary(true);
1135 else // set the boundary to false
1136 new_cur.boundary(false);
1138 // Otherwise (if the character at position 'left_pos'
1139 // is LTR), then moving to the left of it is as easy
1140 // as setting the new position to 'left_pos'.
1142 new_cur.pos() = left_pos;
1143 new_cur.boundary(false);
1148 bool const moved = new_cur != *this || new_cur.boundary() != boundary();
1151 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
1152 << (new_cur.boundary() ? " (boundary)" : ""));
1162 // Return true on success
1163 bool findNonVirtual(Row const & row, Row::const_iterator & cit, bool onleft)
1166 while (cit != row.begin() && cit->isVirtual())
1169 while (cit != row.end() && cit->isVirtual())
1172 return cit != row.end() && !cit->isVirtual();
1177 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos) const
1179 // by default, we know nothing.
1183 Row const & row = textRow();
1185 Row::const_iterator cit = row.findElement(pos(), boundary(), dummy);
1186 // Handle the case of empty row
1187 if (cit == row.end()) {
1189 right_pos = row.pos();
1191 left_pos = row.pos() - 1;
1195 // skip virtual elements and exit if no non-virtual one exists
1196 if (!findNonVirtual(row, cit, !cit->isRTL()))
1199 // if the position is at the left side of the element, we have to
1200 // look at the previous element
1201 if (pos() == cit->left_pos()) {
1202 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1203 << "), AT LEFT of *cit=" << *cit);
1204 // this one is easy (see common case below)
1205 right_pos = pos() - (cit->isRTL() ? 1 : 0);
1206 // at the left of the row
1207 if (cit == row.begin())
1210 if (!findNonVirtual(row, cit, true))
1212 // [...[ is the row element, | is cursor position (! with boundary)
1213 // [ 1 2 [ is a ltr row element with pos=1 and endpos=3
1214 // ] 2 1] is an rtl row element with pos=1 and endpos=3
1215 // [ 1 2 [ [|3 4 [ => (2, 3)
1216 // or [ 1 2 [ ]!4 3 ] => (2, 4)
1217 // or ] 2 1 ] [|3 4 [ => (1, 3)
1218 // or ] 4 3 ] ]!2 1 ] => (3, 2)
1219 left_pos = cit->right_pos() - (cit->isRTL() ? 0 : 1);
1220 // happens with consecutive row of same direction
1221 if (left_pos == right_pos) {
1222 left_pos += cit->isRTL() ? 1 : -1;
1225 // same code but with the element at the right
1226 else if (pos() == cit->right_pos()) {
1227 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1228 << "), AT RIGHT of *cit=" << *cit);
1229 // this one is easy (see common case below)
1230 left_pos = pos() - (cit->isRTL() ? 0 : 1);
1231 // at the right of the row
1232 if (cit + 1 == row.end())
1235 if (!findNonVirtual(row, cit, false))
1237 // [ 1 2![ [ 3 4 [ => (2, 3)
1238 // or [ 1 2![ ] 4 3 ] => (2, 4)
1239 // or ] 2 1|] [ 3 4 [ => (1, 3)
1240 // or ] 4 3|] ] 2 1 ] => (3, 2)
1241 right_pos = cit->left_pos() - (cit->isRTL() ? 1 : 0);
1242 // happens with consecutive row of same direction
1243 if (right_pos == left_pos)
1244 right_pos += cit->isRTL() ? -1 : 1;
1246 // common case: both positions are inside the row element
1248 // [ 1 2|3 [ => (2, 3)
1249 // or ] 3|2 1 ] => (3, 2)
1250 left_pos = pos() - (cit->isRTL() ? 0 : 1);
1251 right_pos = pos() - (cit->isRTL() ? 1 : 0);
1254 // Note that debug message does not catch all early returns above
1255 LYXERR(Debug::RTL,"getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1256 << ") => (" << left_pos << ", " << right_pos <<")");
1260 bool Cursor::posVisToNewRow(bool movingLeft)
1262 Row const & row = textRow();
1263 bool par_is_LTR = !row.isRTL();
1265 // Inside a table, determining whether to move to the next or
1266 // previous row should be done based on the table's direction.
1267 if (inset().asInsetTabular()) {
1268 par_is_LTR = !inset().asInsetTabular()->isRightToLeft(*this);
1269 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
1272 // if moving left in an LTR paragraph or moving right in an
1273 // RTL one, move to previous row
1274 if (par_is_LTR == movingLeft) {
1275 if (row.pos() == 0) { // we're at first row in paragraph
1276 if (pit() == 0) // no previous paragraph! don't move
1278 // move to last pos in previous par
1282 } else { // move to previous row in this par
1283 pos() = row.pos() - 1; // this is guaranteed to be in previous row
1287 // if moving left in an RTL paragraph or moving right in an
1288 // LTR one, move to next row
1290 if (row.endpos() == lastpos()) { // we're at last row in paragraph
1291 if (pit() == lastpit()) // last paragraph! don't move
1293 // move to first row in next par
1297 } else { // move to next row in this par
1298 pos() = row.endpos();
1303 // make sure we're at left-/right-most pos in new row
1304 posVisToRowExtremity(!movingLeft);
1310 void Cursor::posVisToRowExtremity(bool left)
1312 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
1313 << (boundary() ? 1 : 0));
1315 TextMetrics const & tm = bv_->textMetrics(text());
1316 // Looking for extremities is like clicking on the left or the
1317 // right of the row.
1318 int x = tm.origin().x_ + (left ? 0 : textRow().width());
1320 pos() = tm.getPosNearX(textRow(), x, b);
1323 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
1324 << (boundary() ? 1 : 0));
1328 bool Cursor::reverseDirectionNeeded() const
1331 * We determine the directions based on the direction of the
1332 * bottom() --- i.e., outermost --- paragraph, because that is
1333 * the only way to achieve consistency of the arrow's movements
1334 * within a paragraph, and thus avoid situations in which the
1335 * cursor gets stuck.
1337 return bottom().paragraph().isRTL(bv().buffer().params());
1341 void Cursor::setTargetX(int x)
1344 textTargetOffset_ = 0;
1348 int Cursor::x_target() const
1354 void Cursor::clearTargetX()
1357 textTargetOffset_ = 0;
1361 void Cursor::updateTextTargetOffset()
1366 textTargetOffset_ = x - x_target_;
1370 bool Cursor::selHandle(bool sel)
1372 //lyxerr << "Cursor::selHandle" << endl;
1375 if (sel == selection())
1379 cap::saveSelection(*this);
1387 bool Cursor::atFirstOrLastRow(bool up)
1389 TextMetrics const & tm = bv_->textMetrics(text());
1390 ParagraphMetrics const & pm = tm.parMetrics(pit());
1393 if (pos() && boundary())
1394 row = pm.pos2row(pos() - 1);
1396 row = pm.pos2row(pos());
1399 if (pit() == 0 && row == 0)
1402 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1403 row + 1 >= int(pm.rows().size()))
1413 ///////////////////////////////////////////////////////////////////
1416 // The part below is the non-integrated rest of the original math
1417 // cursor. This should be either generalized for texted or moved
1418 // back to mathed (in most cases to InsetMathNest).
1420 ///////////////////////////////////////////////////////////////////
1422 #include "mathed/InsetMathChar.h"
1423 #include "mathed/InsetMathGrid.h"
1424 #include "mathed/InsetMathScript.h"
1425 #include "mathed/InsetMathUnknown.h"
1426 #include "mathed/MathFactory.h"
1427 #include "mathed/MathStream.h"
1428 #include "mathed/MathSupport.h"
1433 bool Cursor::openable(MathAtom const & t) const
1444 // we can't move into anything new during selection
1445 if (depth() >= realAnchor().depth())
1447 if (t.nucleus() != &realAnchor()[depth()].inset())
1454 void Cursor::plainErase()
1456 cell().erase(pos());
1460 void Cursor::plainInsert(MathAtom const & t)
1462 cell().insert(pos(), t);
1464 inset().setBuffer(bv_->buffer());
1466 checkBufferStructure();
1470 void Cursor::insert(char_type c)
1472 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1473 LASSERT(!empty(), return);
1475 cap::selClearOrDel(*this);
1476 insert(new InsetMathChar(c));
1478 text()->insertChar(*this, c);
1483 void Cursor::insert(docstring const & str)
1485 for (char_type c : str)
1490 void Cursor::insert(Inset * inset0)
1492 LASSERT(inset0, return);
1494 insert(MathAtom(inset0->asInsetMath()));
1496 text()->insertInset(*this, inset0);
1497 inset0->setBuffer(bv_->buffer());
1499 if (inset0->isLabeled())
1500 forceBufferUpdate();
1505 void Cursor::insert(MathAtom const & t)
1507 LATTEST(inMathed());
1508 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1510 cap::selClearOrDel(*this);
1515 void Cursor::insert(MathData const & ar)
1517 LATTEST(inMathed());
1520 cap::eraseSelection(*this);
1521 cell().insert(pos(), ar);
1523 // FIXME audit setBuffer calls
1524 inset().setBuffer(bv_->buffer());
1528 int Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1530 LATTEST(inMathed());
1531 MathData ar(buffer());
1533 if (ar.size() == 1 && (enter || selection()))
1541 void Cursor::niceInsert(MathAtom const & t)
1543 LATTEST(inMathed());
1545 docstring const safe = cap::grabAndEraseSelection(*this);
1547 // If possible, enter the new inset and move the contents of the selection
1548 if (t->isActive()) {
1549 idx_type const idx = prevMath().asNestInset()->firstIdx();
1550 MathData ar(buffer());
1552 prevMath().cell(idx).insert(0, ar);
1553 editInsertedInset();
1554 } else if (t->asMacro() && !safe.empty()) {
1555 MathData ar(buffer());
1557 docstring const name = t->asMacro()->name();
1558 MacroData const * data = buffer()->getMacro(name);
1559 if (data && data->numargs() - data->optionals() > 0) {
1560 plainInsert(MathAtom(new InsetMathBrace(ar)));
1567 bool Cursor::backspace(bool const force)
1570 cap::eraseSelection(*this);
1575 // If empty cell, and not part of a big cell
1576 if (lastpos() == 0 && inset().nargs() == 1) {
1578 // Directly delete empty cell: [|[]] => [|]
1584 // [|], can not delete from inside
1595 if (inMacroMode()) {
1596 InsetMathUnknown * p = activeMacro();
1597 if (p->name().size() > 1) {
1598 p->setName(p->name().substr(0, p->name().size() - 1));
1603 if (pos() != 0 && !force && prevAtom()->confirmDeletion()) {
1604 // let's require two backspaces for 'big stuff' and
1605 // highlight on the first
1617 bool Cursor::erase(bool const force)
1623 cap::eraseSelection(*this);
1627 // delete empty cells if possible
1628 if (pos() == lastpos() && inset().idxDelete(idx()))
1631 // special behaviour when in last position of cell
1632 if (pos() == lastpos()) {
1633 bool one_cell = inset().nargs() == 1;
1634 if (one_cell && lastpos() == 0) {
1636 // Directly delete empty cell: [|[]] => [|]
1642 // [|], can not delete from inside
1647 inset().idxGlue(idx());
1651 // 'clever' UI hack: only erase large items if previously slected
1652 if (pos() != lastpos() && !force && nextAtom()->confirmDeletion()) {
1667 DocIterator save = *this;
1668 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1669 this->dispatch(cmd);
1670 if (disp_.dispatched())
1680 DocIterator save = *this;
1681 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1682 this->dispatch(cmd);
1683 if (disp_.dispatched())
1690 void Cursor::handleNest(MathAtom const & a)
1692 idx_type const idx = a.nucleus()->asNestInset()->firstIdx();
1693 //lyxerr << "Cursor::handleNest: " << idx << endl;
1695 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(idx));
1697 editInsertedInset();
1701 int Cursor::targetX() const
1703 if (x_target() != -1)
1712 int Cursor::textTargetOffset() const
1714 return textTargetOffset_;
1718 void Cursor::setTargetX()
1727 bool Cursor::macroModeClose(bool cancel)
1731 InsetMathUnknown * p = activeMacro();
1733 MathData selection(buffer());
1734 asArray(p->selection(), selection);
1735 docstring const s = p->name();
1737 cell().erase(pos());
1739 // trigger updates of macros, at least, if no full
1740 // updates take place anyway
1741 screenUpdateFlags(Update::Force);
1743 // do nothing if the macro name is empty
1744 if (s == "\\" || cancel) {
1748 docstring const name = s.substr(1);
1749 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1750 if (in && in->interpretString(*this, s))
1752 bool const user_macro = buffer()->getMacro(name, *this, false);
1753 MathAtom atom = user_macro ? MathAtom(new InsetMathMacro(buffer(), name))
1754 : createInsetMath(name, buffer());
1756 // try to put argument into macro, if we just inserted a macro
1757 bool macroArg = false;
1758 InsetMathMacro * atomAsMacro = atom.nucleus()->asMacro();
1759 InsetMathNest * atomAsNest = atom.nucleus()->asNestInset();
1761 // macros here are still unfolded (in init mode in fact). So
1762 // we have to resolve the macro here manually and check its arity
1763 // to put the selection behind it if arity > 0.
1764 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1765 if (!selection.empty() && data && data->numargs()) {
1767 atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1769 // non-greedy case. Do not touch the arguments behind
1770 atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1773 // insert remembered selection into first argument of a non-macro
1774 else if (atomAsNest && atomAsNest->nargs() > 0)
1775 atomAsNest->cell(atomAsNest->firstIdx()).append(selection);
1777 MathWordList const & words = mathedWordList();
1778 MathWordList::const_iterator it = words.find(name);
1779 bool keep_mathmode = user_macro
1780 || (it != words.end() && (it->second.inset == "font"
1781 || it->second.inset == "oldfont"
1782 || it->second.inset == "mbox"));
1783 bool ert_macro = !user_macro && it == words.end() && atomAsMacro;
1785 if (in && in->currentMode() == Inset::TEXT_MODE
1786 && atom.nucleus()->currentMode() == Inset::MATH_MODE
1787 && name != from_ascii("ensuremath") && !ert_macro) {
1788 MathAtom at(new InsetMathEnsureMath(buffer()));
1789 at.nucleus()->cell(0).push_back(atom);
1792 } else if (in && in->currentMode() == Inset::MATH_MODE
1793 && atom.nucleus()->currentMode() == Inset::TEXT_MODE
1794 && !keep_mathmode) {
1795 MathAtom at = createInsetMath("text", buffer());
1796 at.nucleus()->cell(0).push_back(atom);
1802 // finally put the macro argument behind, if needed
1804 if (selection.size() > 1 || selection[0]->asScriptInset())
1805 plainInsert(MathAtom(new InsetMathBrace(selection)));
1814 bool Cursor::inMacroMode() const
1818 if (pos() == 0 || cell().empty())
1820 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1821 return p && !p->final();
1825 InsetMathUnknown * Cursor::activeMacro()
1827 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1831 InsetMathUnknown const * Cursor::activeMacro() const
1833 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1837 docstring Cursor::macroName()
1839 return inMacroMode() ? activeMacro()->name() : docstring();
1843 void Cursor::pullArg()
1846 MathData ar = cell();
1847 if (popBackward() && inMathed()) {
1849 cell().insert(pos(), ar);
1852 //formula()->mutateToText();
1857 void Cursor::normalize()
1859 if (idx() > lastidx()) {
1860 lyxerr << "this should not really happen - 1: "
1861 << idx() << ' ' << nargs()
1862 << " in: " << &inset() << endl;
1866 if (pos() > lastpos()) {
1867 lyxerr << "this should not really happen - 2: "
1868 << pos() << ' ' << lastpos() << " in idx: " << idx()
1870 odocstringstream os;
1871 otexrowstream ots(os);
1872 WriteStream wi(ots, false, true, WriteStream::wsDefault);
1873 inset().asInsetMath()->write(wi);
1874 lyxerr << to_utf8(os.str()) << endl;
1880 bool Cursor::upDownInMath(bool up)
1882 // Be warned: The 'logic' implemented in this function is highly
1883 // fragile. A distance of one pixel or a '<' vs '<=' _really
1884 // matters. So fiddle around with it only if you think you know
1885 // what you are doing!
1889 xo = beforeDispatchPosX_;
1891 // check if we had something else in mind, if not, this is the future
1893 if (x_target_ == -1)
1895 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1896 // In text mode inside the line (not left or right) possibly set a new target_x,
1897 // but only if we are somewhere else than the previous target-offset.
1899 // We want to keep the x-target on subsequent up/down movements
1900 // that cross beyond the end of short lines. Thus a special
1901 // handling when the cursor is at the end of line: Use the new
1902 // x-target only if the old one was before the end of line
1903 // or the old one was after the beginning of the line
1904 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
1908 left = pos() == textRow().endpos();
1909 right = pos() == textRow().pos();
1911 left = pos() == textRow().pos();
1912 right = pos() == textRow().endpos();
1914 if ((!left && !right) ||
1915 (left && !right && xo < x_target_) ||
1916 (!left && right && x_target_ < xo))
1923 // try neigbouring script insets
1925 if (inMathed() && !selection()) {
1928 InsetMathScript const * p = prevAtom()->asScriptInset();
1929 if (p && p->has(up)) {
1931 push(*const_cast<InsetMathScript*>(p));
1932 idx() = p->idxOfScript(up);
1935 // we went in the right direction? Otherwise don't jump into the script
1939 int oy = beforeDispatchPosY_;
1940 if ((!up && y <= oy) ||
1949 if (pos() != lastpos()) {
1950 InsetMathScript const * p = nextAtom()->asScriptInset();
1951 if (p && p->has(up)) {
1952 push(*const_cast<InsetMathScript*>(p));
1953 idx() = p->idxOfScript(up);
1956 // we went in the right direction? Otherwise don't jump into the script
1960 int oy = beforeDispatchPosY_;
1961 if ((!up && y <= oy) ||
1970 // try to find an inset that knows better then we,
1971 if (inset().idxUpDown(*this, up)) {
1972 //lyxerr << "idxUpDown triggered" << endl;
1973 // try to find best position within this inset
1975 setCursor(bruteFind(*this, xo, yo));
1979 // any improvement going just out of inset?
1980 if (popBackward() && inMathed()) {
1981 //lyxerr << "updown: popBackward succeeded" << endl;
1984 int yold = beforeDispatchPosY_;
1986 if (up ? ynew < yold : ynew > yold)
1990 // no success, we are probably at the document top or bottom
1996 bool Cursor::mathForward(bool word)
1998 LASSERT(inMathed(), return false);
1999 if (pos() < lastpos()) {
2001 // word: skip a group of insets of the form X*(B*|R*|P*) (greedy
2002 // match) where X is any math class, B is mathbin, R is mathrel, and
2003 // P is mathpunct. Make sure that the following remains true:
2004 // mathForward(true); mathBackward(true); mathForward(true)
2005 // is the same as mathForward(true) and
2006 // mathBackward(true); mathForward(true); mathBackward(true)
2007 // is the same as mathBackward(true).
2008 MathClass mc = nextMath().mathClass();
2011 while (pos() < lastpos() && mc == nextMath().mathClass());
2012 if (pos() < lastpos() &&
2013 ((mc = nextMath().mathClass()) == MC_BIN ||
2014 mc == MC_REL || mc == MC_PUNCT))
2017 while (pos() < lastpos() && mc == nextMath().mathClass());
2018 } else if (openable(nextAtom())) {
2019 // single step: try to enter the next inset
2020 pushBackward(nextMath());
2021 inset().idxFirst(*this);
2026 if (inset().idxForward(*this))
2028 // try to pop forwards --- but don't pop out of math! leave that to
2030 int s = depth() - 2;
2031 if (s >= 0 && operator[](s).inset().asInsetMath())
2032 return popForward();
2037 bool Cursor::mathBackward(bool word)
2039 LASSERT(inMathed(), return false);
2042 // word: skip a group of insets. See the comment in mathForward.
2043 MathClass mc = prevMath().mathClass();
2046 while (pos() > 0 && mc == prevMath().mathClass());
2047 if (pos() > 0 && (mc == MC_BIN || mc == MC_REL || mc == MC_PUNCT)) {
2048 mc = prevMath().mathClass();
2051 while (pos() > 0 && mc == prevMath().mathClass());
2053 } else if (openable(prevAtom())) {
2054 // single step: try to enter the preceding inset
2057 inset().idxLast(*this);
2062 if (inset().idxBackward(*this))
2064 // try to pop backwards --- but don't pop out of math! leave that to
2066 int s = depth() - 2;
2067 if (s >= 0 && operator[](s).inset().asInsetMath())
2068 return popBackward();
2073 bool Cursor::upDownInText(bool up, bool & updateNeeded)
2075 LASSERT(text(), return false);
2081 xo = beforeDispatchPosX_;
2083 // update the targetX - this is here before the "return false"
2084 // to set a new target which can be used by InsetTexts above
2085 // if we cannot move up/down inside this inset anymore
2086 if (x_target_ == -1)
2088 else if (xo - textTargetOffset() != x_target() &&
2089 depth() == beforeDispatchCursor_.depth()) {
2090 // In text mode inside the line (not left or right)
2091 // possibly set a new target_x, but only if we are
2092 // somewhere else than the previous target-offset.
2094 // We want to keep the x-target on subsequent up/down
2095 // movements that cross beyond the end of short lines.
2096 // Thus a special handling when the cursor is at the
2097 // end of line: Use the new x-target only if the old
2098 // one was before the end of line or the old one was
2099 // after the beginning of the line
2100 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
2104 left = pos() == textRow().endpos();
2105 right = pos() == textRow().pos();
2107 left = pos() == textRow().pos();
2108 right = pos() == textRow().endpos();
2110 if ((!left && !right) ||
2111 (left && !right && xo < x_target_) ||
2112 (!left && right && x_target_ < xo))
2119 // first get the current line
2120 TextMetrics & tm = bv_->textMetrics(text());
2121 ParagraphMetrics const & pm = tm.parMetrics(pit());
2123 if (pos() && boundary())
2124 row = pm.pos2row(pos() - 1);
2126 row = pm.pos2row(pos());
2128 if (atFirstOrLastRow(up)) {
2129 // Is there a place for the cursor to go ? If yes, we
2130 // can execute the DEPM, otherwise we should keep the
2131 // paragraph to host the cursor.
2132 Cursor dummy = *this;
2133 bool valid_destination = false;
2134 for(; dummy.depth(); dummy.pop())
2135 if (!dummy.atFirstOrLastRow(up)) {
2136 valid_destination = true;
2140 // will a next dispatch follow and if there is a new
2141 // dispatch will it move the cursor out ?
2142 if (depth() > 1 && valid_destination) {
2143 // The cursor hasn't changed yet. This happens when
2144 // you e.g. move out of an inset. And to give the
2145 // DEPM the possibility of doing something we must
2146 // provide it with two different cursors. (Lgb, vfr)
2148 dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
2149 dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
2151 updateNeeded |= bv().checkDepm(dummy, *this);
2152 updateTextTargetOffset();
2154 forceBufferUpdate();
2159 // with and without selection are handled differently
2161 int yo1 = bv().getPos(*this).y_;
2163 // To next/previous row
2164 // FIXME: the y position is often guessed wrongly across styles and
2165 // insets, which leads to weird behaviour.
2167 tm.editXY(*this, xo, yo1 - textRow().ascent() - 1);
2169 tm.editXY(*this, xo, yo1 + textRow().descent() + 1);
2170 x_target_ = old.x_target_;
2173 // This happens when you move out of an inset.
2174 // And to give the DEPM the possibility of doing
2175 // something we must provide it with two different
2177 Cursor dummy = *this;
2180 if (bv().checkDepm(dummy, old)) {
2181 updateNeeded = true;
2182 // Make sure that cur gets back whatever happened to dummy (Lgb)
2185 if (inTexted() && pos() && paragraph().isEnvSeparator(pos() - 1))
2188 // if there is a selection, we stay out of any inset,
2189 // and just jump to the right position:
2195 } else if (pit() > 0) {
2197 TextMetrics & tm2 = bv_->textMetrics(text());
2198 if (!tm2.contains(pit()))
2199 tm2.newParMetricsUp();
2200 ParagraphMetrics const & pmcur = tm2.parMetrics(pit());
2201 next_row = pmcur.rows().size() - 1;
2204 if (row + 1 < int(pm.rows().size())) {
2206 } else if (pit() + 1 < int(text()->paragraphs().size())) {
2208 TextMetrics & tm2 = bv_->textMetrics(text());
2209 if (!tm2.contains(pit()))
2210 tm2.newParMetricsDown();
2215 Row const & real_next_row = tm.parMetrics(pit()).rows()[next_row];
2217 top().pos() = tm.getPosNearX(real_next_row, xo, bound);
2219 // When selection==false, this is done by TextMetrics::editXY
2222 updateNeeded |= bv().checkDepm(*this, old);
2226 forceBufferUpdate();
2227 updateTextTargetOffset();
2232 void Cursor::handleFont(string const & font)
2234 LYXERR(Debug::DEBUG, font);
2238 safe = cap::grabAndEraseSelection(*this);
2243 if (lastpos() != 0) {
2244 // something left in the cell
2246 // cursor in first position
2248 } else if (pos() == lastpos()) {
2249 // cursor in last position
2252 // cursor in between. split cell
2253 MathData::iterator bt = cell().begin();
2254 MathAtom at = createInsetMath(from_utf8(font), buffer());
2255 at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
2256 cell().erase(bt, bt + pos());
2261 // nothing left in the cell
2270 void Cursor::undispatched() const
2272 disp_.dispatched(false);
2276 void Cursor::dispatched() const
2278 disp_.dispatched(true);
2282 void Cursor::screenUpdateFlags(Update::flags f) const
2284 disp_.screenUpdate(f);
2288 void Cursor::noScreenUpdate() const
2290 disp_.screenUpdate(Update::None);
2294 void Cursor::forceBufferUpdate() const
2296 disp_.forceBufferUpdate();
2300 void Cursor::clearBufferUpdate() const
2302 disp_.clearBufferUpdate();
2306 bool Cursor::needBufferUpdate() const
2308 return disp_.needBufferUpdate();
2312 Font Cursor::getFont() const
2314 // The logic here should more or less match to the
2315 // Cursor::setCurrentFont logic, i.e. the cursor height should
2316 // give a hint what will happen if a character is entered.
2317 // FIXME: this is not the case, what about removing this method ? (see #10478).
2319 // HACK. far from being perfect...
2321 CursorSlice const & sl = innerTextSlice();
2322 Text const & text = *sl.text();
2323 Paragraph const & par = text.getPar(sl.pit());
2325 // on boundary, so we are really at the character before
2326 pos_type pos = sl.pos();
2327 if (pos > 0 && boundary())
2330 // on space? Take the font before (only for RTL boundary stay)
2332 TextMetrics const & tm = bv().textMetrics(&text);
2333 if (pos == sl.lastpos()
2334 || (par.isSeparator(pos)
2335 && !tm.isRTLBoundary(sl.pit(), pos)))
2339 // get font at the position
2340 Font font = par.getFont(buffer()->params(), pos,
2341 text.outerFont(sl.pit()));
2347 void Cursor::sanitize()
2349 setBuffer(&bv_->buffer());
2350 CursorData::sanitize();
2354 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2356 // find inset in common
2358 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2359 if (&old[i].inset() != &cur[i].inset())
2363 // update words if we just moved to another paragraph
2364 if (i == old.depth() && i == cur.depth()
2365 && !cur.buffer()->isClean()
2366 && cur.inTexted() && old.inTexted()
2367 && cur.pit() != old.pit()) {
2368 old.paragraph().updateWords();
2371 // notify everything on top of the common part in old cursor,
2372 // but stop if the inset claims the cursor to be invalid now
2373 for (size_type j = i; j < old.depth(); ++j) {
2374 Cursor inset_pos = old;
2375 inset_pos.cutOff(j);
2376 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2380 // notify everything on top of the common part in new cursor,
2381 // but stop if the inset claims the cursor to be invalid now
2382 for (; i < cur.depth(); ++i) {
2383 if (cur[i].inset().notifyCursorEnters(cur))
2391 void Cursor::setCurrentFont()
2393 CursorSlice const & cs = innerTextSlice();
2394 Paragraph const & par = cs.paragraph();
2395 pos_type cpit = cs.pit();
2396 pos_type cpos = cs.pos();
2397 Text const & ctext = *cs.text();
2398 TextMetrics const & tm = bv().textMetrics(&ctext);
2400 // are we behind previous char in fact? -> go to that char
2401 if (cpos > 0 && boundary())
2404 // find position to take the font from
2406 // paragraph end? -> font of last char
2407 if (cpos == lastpos())
2409 // on space? -> look at the words in front of space
2410 else if (cpos > 0 && par.isSeparator(cpos)) {
2411 // abc| def -> font of c
2412 // abc |[WERBEH], i.e. boundary==true -> font of c
2413 // abc [WERBEH]| def, font of the space
2414 if (!tm.isRTLBoundary(cpit, cpos))
2420 BufferParams const & bufparams = buffer()->params();
2421 current_font = par.getFontSettings(bufparams, cpos);
2422 real_current_font = tm.displayFont(cpit, cpos);
2424 // special case for paragraph end
2425 if (cs.pos() == lastpos()
2426 && tm.isRTLBoundary(cpit, cs.pos())
2428 Language const * lang = par.getParLanguage(bufparams);
2429 current_font.setLanguage(lang);
2430 current_font.fontInfo().setNumber(FONT_OFF);
2431 real_current_font.setLanguage(lang);
2432 real_current_font.fontInfo().setNumber(FONT_OFF);
2437 void Cursor::checkBufferStructure()
2439 Buffer const * master = buffer()->masterBuffer();
2440 master->tocBackend().updateItem(*this);
2441 if (master != buffer() && !master->hasGuiDelegate())
2442 // In case the master has no gui associated with it,
2443 // the TocItem is not updated (part of bug 5699).
2444 buffer()->tocBackend().updateItem(*this);
2446 // If the last tracked change of the paragraph has just been
2447 // deleted, then we need to recompute the buffer flag
2448 // tracked_changes_present_.
2449 if (inTexted() && paragraph().isChangeUpdateRequired())
2450 disp_.forceChangesUpdate();
2454 void Cursor::moveToClosestEdge(int const x, bool const edit)
2456 if (Inset const * inset = nextInset()) {
2457 // stay in front of insets for which we want to open the dialog
2458 // (e.g. InsetMathSpace).
2459 if (edit && (inset->hasSettings() || !inset->contextMenuName().empty()))
2461 CoordCache::Insets const & insetCache = bv().coordCache().getInsets();
2462 if (!insetCache.has(inset))
2464 int const wid = insetCache.dim(inset).wid;
2465 Point p = insetCache.xy(inset);
2466 if (x > p.x_ + (wid + 1) / 2)