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 const with_label, bool const skipdelete) const
356 return cap::grabSelection(*this);
358 int label = with_label
359 ? AS_STR_LABEL | AS_STR_INSETS : AS_STR_INSETS;
362 ? AS_STR_LABEL | AS_STR_INSETS | AS_STR_SKIPDELETE
363 : AS_STR_INSETS | AS_STR_SKIPDELETE;
365 idx_type const startidx = selBegin().idx();
366 idx_type const endidx = selEnd().idx();
367 if (startidx != endidx) {
368 // multicell selection
369 InsetTabular * table = inset().asInsetTabular();
370 LASSERT(table, return docstring());
371 return table->asString(startidx, endidx);
374 ParagraphList const & pars = text()->paragraphs();
376 pit_type const startpit = selBegin().pit();
377 pit_type const endpit = selEnd().pit();
378 size_t const startpos = selBegin().pos();
379 size_t const endpos = selEnd().pos();
381 if (startpit == endpit)
382 return pars[startpit].asString(startpos, endpos, label);
384 // First paragraph in selection
385 docstring result = pars[startpit].
386 asString(startpos, pars[startpit].size(), label)
389 // The paragraphs in between (if any)
390 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
391 Paragraph const & par = pars[pit];
392 result += par.asString(0, par.size(), label)
396 // Last paragraph in selection
397 result += pars[endpit].asString(0, endpos, label);
403 void CursorData::info(odocstream & os, bool devel_mode) const
405 for (int i = 1, n = depth(); i < n; ++i) {
406 operator[](i).inset().infoize(os);
410 Inset const * inset = prevInset();
411 // prevInset() can return 0 in certain case.
413 prevInset()->infoize2(os);
416 InsetMath * math = inset().asInsetMath();
418 os << _(", Inset: ") << math->id();
419 os << _(", Cell: ") << idx();
420 os << _(", Position: ") << pos();
425 docstring CursorData::currentState(bool devel_mode) const
429 info(os, devel_mode);
434 return text()->currentState(*this, devel_mode);
440 void CursorData::markNewWordPosition()
442 if (lyxrc.spellcheck_continuously && inTexted() && new_word_.empty()) {
443 FontSpan nw = locateWord(WHOLE_WORD);
444 if (nw.size() == 1) {
445 LYXERR(Debug::DEBUG, "start new word: "
447 << " pos: " << nw.first);
454 void CursorData::clearNewWordPosition()
456 if (!new_word_.empty()) {
457 LYXERR(Debug::DEBUG, "clear new word: "
459 << " pos: " << pos());
465 void CursorData::checkNewWordPosition()
467 if (!lyxrc.spellcheck_continuously || new_word_.empty())
469 // forget the position of the current new word if
470 // 1) or the remembered position was "broken"
471 // 2) or the count of nested insets changed
472 // 3) the top-level inset is not the same anymore
473 // 4) the cell index changed
474 // 5) or the paragraph changed
475 // 6) or the cursor pos is out of paragraph bound
476 if (new_word_.fixIfBroken()
477 || depth() != new_word_.depth()
478 || &inset() != &new_word_.inset()
479 || pit() != new_word_.pit()
480 || idx() != new_word_.idx()
481 || new_word_.pos() > new_word_.lastpos())
482 clearNewWordPosition();
484 FontSpan nw = locateWord(WHOLE_WORD);
486 FontSpan ow = new_word_.locateWord(WHOLE_WORD);
487 if (nw.intersect(ow).empty())
488 clearNewWordPosition();
490 LYXERR(Debug::DEBUG, "new word: "
492 << " pos: " << nw.first << ".." << nw.last);
494 clearNewWordPosition();
499 void CursorData::clearSelection()
502 setWordSelection(false);
508 int CursorData::countInsetsInSelection(InsetCode const & inset_code)
513 DocIterator from, to;
514 from = selectionBegin();
519 if (!from.nextInset()) //move to closest inset
522 while (!from.empty() && from < to) {
523 Inset * inset = from.nextInset();
526 if (inset->lyxCode() == inset_code)
534 bool CursorData::insetInSelection(InsetCode const & inset_code)
539 DocIterator from, to;
540 from = selectionBegin();
543 if (!from.nextInset()) //move to closest inset
546 while (!from.empty() && from < to) {
547 Inset * inset = from.nextInset();
550 if (inset->lyxCode() == inset_code)
558 bool CursorData::fixIfBroken()
560 bool const broken_cursor = DocIterator::fixIfBroken();
561 bool const broken_anchor = anchor_.fixIfBroken();
563 if (broken_cursor || broken_anchor) {
564 clearNewWordPosition();
572 void CursorData::sanitize()
574 DocIterator::sanitize();
575 new_word_.sanitize();
583 bool CursorData::undoAction()
585 if (!buffer()->undo().undoAction(*this))
592 bool CursorData::redoAction()
594 if (!buffer()->undo().redoAction(*this))
601 void CursorData::finishUndo() const
603 buffer()->undo().finishUndo();
607 void CursorData::beginUndoGroup() const
609 buffer()->undo().beginUndoGroup(*this);
613 void CursorData::endUndoGroup() const
615 buffer()->undo().endUndoGroup(*this);
619 void CursorData::splitUndoGroup() const
621 buffer()->undo().splitUndoGroup(*this);
625 void CursorData::recordUndo(pit_type from, pit_type to) const
627 buffer()->undo().recordUndo(*this, from, to);
631 void CursorData::recordUndo(pit_type from) const
633 buffer()->undo().recordUndo(*this, from, pit());
637 void CursorData::recordUndo(UndoKind kind) const
639 buffer()->undo().recordUndo(*this, kind);
643 void CursorData::recordUndoInset(Inset const * in) const
645 buffer()->undo().recordUndoInset(*this, in);
649 void CursorData::recordUndoFullBuffer() const
651 buffer()->undo().recordUndoFullBuffer(*this);
655 void CursorData::recordUndoBufferParams() const
657 buffer()->undo().recordUndoBufferParams(*this);
661 void CursorData::recordUndoSelection() const
664 if (cap::multipleCellsSelected(*this))
669 buffer()->undo().recordUndo(*this,
670 selBegin().pit(), selEnd().pit());
675 int CursorData::currentMode()
677 LASSERT(!empty(), return Inset::UNDECIDED_MODE);
678 for (int i = depth() - 1; i >= 0; --i) {
679 int res = operator[](i).inset().currentMode();
680 bool locked_mode = operator[](i).inset().lockedMode();
681 // Also return UNDECIDED_MODE when the mode is locked,
682 // as in this case it is treated the same as TEXT_MODE
683 if (res != Inset::UNDECIDED_MODE || locked_mode)
686 return Inset::TEXT_MODE;
690 bool CursorData::confirmDeletion(bool const before) const
693 if (Inset const * inset = before ? prevInset() : nextInset())
694 return inset->confirmDeletion();
696 DocIterator dit = selectionBegin();
697 CursorSlice const end = selectionEnd().top();
698 for (; dit.top() < end; dit.top().forwardPos())
699 if (Inset const * inset = dit.nextInset())
700 if (inset->confirmDeletion())
713 // be careful: this is called from the bv's constructor, too, so
714 // bv functions are not yet available!
715 Cursor::Cursor(BufferView & bv)
716 : CursorData(&bv.buffer()), bv_(&bv),
717 x_target_(-1), textTargetOffset_(0),
718 beforeDispatchPosX_(0), beforeDispatchPosY_(0)
729 void Cursor::setCursorData(CursorData const & data)
731 CursorData::operator=(data);
735 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
739 // Try to fix cursor in case it is broken.
742 // Is this a function that acts on inset at point?
743 Inset * inset = cur.nextInset();
744 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
745 && inset && inset->getStatus(cur, cmd, status))
748 // This is, of course, a mess. Better create a new doc iterator and use
749 // this in Inset::getStatus. This might require an additional
750 // BufferView * arg, though (which should be avoided)
751 //Cursor safe = *this;
753 for ( ; cur.depth(); cur.pop()) {
754 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
755 // LASSERT: Is it safe to continue here, or should we return?
756 LASSERT(cur.idx() <= cur.lastidx(), /**/);
757 LASSERT(cur.pit() <= cur.lastpit(), /**/);
758 LASSERT(cur.pos() <= cur.lastpos(), /**/);
760 // The inset's getStatus() will return 'true' if it made
761 // a definitive decision on whether it want to handle the
762 // request or not. The result of this decision is put into
763 // the 'status' parameter.
764 if (cur.inset().getStatus(cur, cmd, status)) {
773 void Cursor::saveBeforeDispatchPosXY()
775 getPos(beforeDispatchPosX_, beforeDispatchPosY_);
779 void Cursor::dispatch(FuncRequest const & cmd0)
781 LYXERR(Debug::ACTION, "Cursor::dispatch: cmd: " << cmd0 << '\n' << *this);
786 FuncRequest cmd = cmd0;
789 disp_ = DispatchResult();
793 // Is this a function that acts on inset at point?
794 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
796 disp_.dispatched(true);
797 disp_.screenUpdate(Update::FitCursor | Update::Force);
798 FuncRequest tmpcmd = cmd;
799 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
800 << cmd0 << endl << *this);
801 nextInset()->dispatch(*this, tmpcmd);
802 if (disp_.dispatched()) {
808 // store some values to be used inside of the handlers
809 beforeDispatchCursor_ = *this;
810 for (; depth(); pop(), boundary(false)) {
811 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
812 << cmd0 << endl << *this);
814 // In any of these cases, the cursor is invalid, and we should
815 // try to save this document rather than crash.
816 LBUFERR(pos() <= lastpos());
817 LBUFERR(idx() <= lastidx());
818 LBUFERR(pit() <= lastpit());
820 // The common case is 'LFUN handled, need update', so make the
821 // LFUN handler's life easier by assuming this as default value.
822 // The handler can reset the update and val flags if necessary.
823 disp_.screenUpdate(Update::FitCursor | Update::Force);
824 disp_.dispatched(true);
825 inset().dispatch(*this, cmd);
826 if (disp_.dispatched())
830 // it completely to get a 'bomb early' behaviour in case this
831 // object will be used again.
832 if (!disp_.dispatched()) {
833 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
834 // We might have invalidated the cursor when removing an empty
835 // paragraph while the cursor could not be moved out the inset
836 // while we initially thought we could. This might happen when
837 // a multiline inset becomes an inline inset when the second
838 // paragraph is removed.
839 if (safe.pit() > safe.lastpit()) {
840 safe.pit() = safe.lastpit();
841 safe.pos() = safe.lastpos();
844 disp_.screenUpdate(Update::None);
845 disp_.dispatched(false);
847 // restore the previous one because nested Cursor::dispatch calls
848 // are possible which would change it
849 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
853 // NOTE: The code below has been copied to BufferView::dispatch.
854 // If you need to modify this, please update the other one too.
856 // notify insets we just left
858 old.beginUndoGroup();
860 bool badcursor = notifyCursorLeavesOrEnters(old, *this);
863 bv().resetInlineCompletionPos();
870 DispatchResult const & Cursor::result() const
876 void Cursor::message(docstring const & msg) const
878 disp_.setMessage(msg);
882 void Cursor::errorMessage(docstring const & msg) const
884 disp_.setMessage(msg);
885 disp_.setError(true);
889 BufferView & Cursor::bv() const
898 LBUFERR(depth() >= 1);
903 void Cursor::push(Inset & p)
905 push_back(CursorSlice(p));
906 p.setBuffer(*buffer());
910 void Cursor::pushBackward(Inset & p)
912 LASSERT(!empty(), return);
913 //lyxerr << "Entering inset " << t << " front" << endl;
919 void Cursor::editInsertedInset()
921 LASSERT(!empty(), return);
925 InsetMath &p = prevMath();
932 // this could be a while() loop, but only one cell is not empty in
933 // cases we are interested in. The cell is not empty because we
934 // have inserted the selection in there.
935 if (!cell().empty()) {
936 // if it is not empty, move to the next one.
937 if (!inset().idxNext(*this))
938 // If there is no next one, exit the inset.
944 bool Cursor::popBackward()
946 LASSERT(!empty(), return false);
954 bool Cursor::popForward()
956 LASSERT(!empty(), return false);
957 //lyxerr << "Leaving inset from in back" << endl;
958 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
962 pos() += lastpos() - lp + 1;
967 void Cursor::getPos(int & x, int & y) const
969 Point p = bv().getPos(*this);
975 Row const & Cursor::textRow() const
977 CursorSlice const & cs = innerTextSlice();
978 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
979 return pm.getRow(pos(), boundary());
983 bool Cursor::posVisRight(bool skip_inset)
985 Cursor new_cur = *this; // where we will move to
986 pos_type left_pos; // position visually left of current cursor
987 pos_type right_pos; // position visually right of current cursor
989 getSurroundingPos(left_pos, right_pos);
991 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
993 // Are we at an inset?
994 new_cur.pos() = right_pos;
995 new_cur.boundary(false);
997 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
998 // we actually move the cursor at the end of this
999 // function, for now we just keep track of the new
1000 // position in new_cur...
1001 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
1004 // Are we already at rightmost pos in row?
1005 else if (text()->empty() || right_pos == -1) {
1008 if (!new_cur.posVisToNewRow(false)) {
1009 LYXERR(Debug::RTL, "not moving!");
1013 // we actually move the cursor at the end of this
1014 // function, for now just keep track of the new
1015 // position in new_cur...
1016 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
1017 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
1020 // normal movement to the right
1023 // Recall, if the cursor is at position 'x', that
1024 // means *before* the character at position 'x'. In
1025 // RTL, "before" means "to the right of", in LTR, "to
1026 // the left of". So currently our situation is this:
1027 // the position to our right is 'right_pos' (i.e.,
1028 // we're currently to the left of 'right_pos'). In
1029 // order to move to the right, it depends whether or
1030 // not the character at 'right_pos' is RTL.
1031 bool const new_pos_is_RTL = paragraph().getFontSettings(
1032 buffer()->params(), right_pos).isVisibleRightToLeft();
1033 // If the character at 'right_pos' *is* LTR, then in
1034 // order to move to the right of it, we need to be
1035 // *after* 'right_pos', i.e., move to position
1037 if (!new_pos_is_RTL) {
1038 new_cur.pos() = right_pos + 1;
1039 // set the boundary to true in two situations:
1041 // 1. if new_pos is now lastpos, and we're in
1042 // an RTL paragraph (this means that we're
1043 // moving right to the end of an LTR chunk
1044 // which is at the end of an RTL paragraph);
1045 (new_cur.pos() == lastpos()
1046 && paragraph().isRTL(buffer()->params()))
1047 // 2. if the position *after* right_pos is RTL
1048 // (we want to be *after* right_pos, not
1049 // before right_pos + 1!)
1050 || paragraph().getFontSettings(buffer()->params(),
1051 new_cur.pos()).isVisibleRightToLeft()
1053 new_cur.boundary(true);
1054 else // set the boundary to false
1055 new_cur.boundary(false);
1057 // Otherwise (if the character at position 'right_pos'
1058 // is RTL), then moving to the right of it is as easy
1059 // as setting the new position to 'right_pos'.
1061 new_cur.pos() = right_pos;
1062 new_cur.boundary(false);
1067 bool const moved = new_cur != *this || new_cur.boundary() != boundary();
1070 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
1071 << (new_cur.boundary() ? " (boundary)" : ""));
1079 bool Cursor::posVisLeft(bool skip_inset)
1081 Cursor new_cur = *this; // where we will move to
1082 pos_type left_pos; // position visually left of current cursor
1083 pos_type right_pos; // position visually right of current cursor
1085 getSurroundingPos(left_pos, right_pos);
1087 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
1089 // Are we at an inset?
1090 new_cur.pos() = left_pos;
1091 new_cur.boundary(false);
1093 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
1094 // we actually move the cursor at the end of this
1095 // function, for now we just keep track of the new
1096 // position in new_cur...
1097 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
1100 // Are we already at leftmost pos in row?
1101 else if (text()->empty() || left_pos == -1) {
1104 if (!new_cur.posVisToNewRow(true)) {
1105 LYXERR(Debug::RTL, "not moving!");
1109 // we actually move the cursor at the end of this
1110 // function, for now just keep track of the new
1111 // position in new_cur...
1112 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
1113 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
1116 // normal movement to the left
1119 // Recall, if the cursor is at position 'x', that
1120 // means *before* the character at position 'x'. In
1121 // RTL, "before" means "to the right of", in LTR, "to
1122 // the left of". So currently our situation is this:
1123 // the position to our left is 'left_pos' (i.e., we're
1124 // currently to the right of 'left_pos'). In order to
1125 // move to the left, it depends whether or not the
1126 // character at 'left_pos' is RTL.
1127 bool const new_pos_is_RTL = paragraph().getFontSettings(
1128 buffer()->params(), left_pos).isVisibleRightToLeft();
1129 // If the character at 'left_pos' *is* RTL, then in
1130 // order to move to the left of it, we need to be
1131 // *after* 'left_pos', i.e., move to position
1133 if (new_pos_is_RTL) {
1134 new_cur.pos() = left_pos + 1;
1135 // set the boundary to true in two situations:
1137 // 1. if new_pos is now lastpos and we're in
1138 // an LTR paragraph (this means that we're
1139 // moving left to the end of an RTL chunk
1140 // which is at the end of an LTR paragraph);
1141 (new_cur.pos() == lastpos()
1142 && !paragraph().isRTL(buffer()->params()))
1143 // 2. if the position *after* left_pos is not
1144 // RTL (we want to be *after* left_pos, not
1145 // before left_pos + 1!)
1146 || !paragraph().getFontSettings(buffer()->params(),
1147 new_cur.pos()).isVisibleRightToLeft()
1149 new_cur.boundary(true);
1150 else // set the boundary to false
1151 new_cur.boundary(false);
1153 // Otherwise (if the character at position 'left_pos'
1154 // is LTR), then moving to the left of it is as easy
1155 // as setting the new position to 'left_pos'.
1157 new_cur.pos() = left_pos;
1158 new_cur.boundary(false);
1163 bool const moved = new_cur != *this || new_cur.boundary() != boundary();
1166 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
1167 << (new_cur.boundary() ? " (boundary)" : ""));
1177 // Return true on success
1178 bool findNonVirtual(Row const & row, Row::const_iterator & cit, bool onleft)
1181 while (cit != row.begin() && cit->isVirtual())
1184 while (cit != row.end() && cit->isVirtual())
1187 return cit != row.end() && !cit->isVirtual();
1192 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos) const
1194 // by default, we know nothing.
1198 Row const & row = textRow();
1200 Row::const_iterator cit = row.findElement(pos(), boundary(), dummy);
1201 // Handle the case of empty row
1202 if (cit == row.end()) {
1204 right_pos = row.pos();
1206 left_pos = row.pos() - 1;
1210 // skip virtual elements and exit if no non-virtual one exists
1211 if (!findNonVirtual(row, cit, !cit->isRTL()))
1214 // if the position is at the left side of the element, we have to
1215 // look at the previous element
1216 if (pos() == cit->left_pos()) {
1217 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1218 << "), AT LEFT of *cit=" << *cit);
1219 // this one is easy (see common case below)
1220 right_pos = pos() - (cit->isRTL() ? 1 : 0);
1221 // at the left of the row
1222 if (cit == row.begin())
1225 if (!findNonVirtual(row, cit, true))
1227 // [...[ is the row element, | is cursor position (! with boundary)
1228 // [ 1 2 [ is a ltr row element with pos=1 and endpos=3
1229 // ] 2 1] is an rtl row element with pos=1 and endpos=3
1230 // [ 1 2 [ [|3 4 [ => (2, 3)
1231 // or [ 1 2 [ ]!4 3 ] => (2, 4)
1232 // or ] 2 1 ] [|3 4 [ => (1, 3)
1233 // or ] 4 3 ] ]!2 1 ] => (3, 2)
1234 left_pos = cit->right_pos() - (cit->isRTL() ? 0 : 1);
1235 // happens with consecutive row of same direction
1236 if (left_pos == right_pos) {
1237 left_pos += cit->isRTL() ? 1 : -1;
1240 // same code but with the element at the right
1241 else if (pos() == cit->right_pos()) {
1242 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1243 << "), AT RIGHT of *cit=" << *cit);
1244 // this one is easy (see common case below)
1245 left_pos = pos() - (cit->isRTL() ? 0 : 1);
1246 // at the right of the row
1247 if (cit + 1 == row.end())
1250 if (!findNonVirtual(row, cit, false))
1252 // [ 1 2![ [ 3 4 [ => (2, 3)
1253 // or [ 1 2![ ] 4 3 ] => (2, 4)
1254 // or ] 2 1|] [ 3 4 [ => (1, 3)
1255 // or ] 4 3|] ] 2 1 ] => (3, 2)
1256 right_pos = cit->left_pos() - (cit->isRTL() ? 1 : 0);
1257 // happens with consecutive row of same direction
1258 if (right_pos == left_pos)
1259 right_pos += cit->isRTL() ? -1 : 1;
1261 // common case: both positions are inside the row element
1263 // [ 1 2|3 [ => (2, 3)
1264 // or ] 3|2 1 ] => (3, 2)
1265 left_pos = pos() - (cit->isRTL() ? 0 : 1);
1266 right_pos = pos() - (cit->isRTL() ? 1 : 0);
1269 // Note that debug message does not catch all early returns above
1270 LYXERR(Debug::RTL,"getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1271 << ") => (" << left_pos << ", " << right_pos <<")");
1275 bool Cursor::posVisToNewRow(bool movingLeft)
1277 Row const & row = textRow();
1278 bool par_is_LTR = !row.isRTL();
1280 // Inside a table, determining whether to move to the next or
1281 // previous row should be done based on the table's direction.
1282 if (inset().asInsetTabular()) {
1283 par_is_LTR = !inset().asInsetTabular()->isRightToLeft(*this);
1284 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
1287 // if moving left in an LTR paragraph or moving right in an
1288 // RTL one, move to previous row
1289 if (par_is_LTR == movingLeft) {
1290 if (row.pos() == 0) { // we're at first row in paragraph
1291 if (pit() == 0) // no previous paragraph! don't move
1293 // move to last pos in previous par
1297 } else { // move to previous row in this par
1298 pos() = row.pos() - 1; // this is guaranteed to be in previous row
1302 // if moving left in an RTL paragraph or moving right in an
1303 // LTR one, move to next row
1305 if (row.endpos() == lastpos()) { // we're at last row in paragraph
1306 if (pit() == lastpit()) // last paragraph! don't move
1308 // move to first row in next par
1312 } else { // move to next row in this par
1313 pos() = row.endpos();
1318 // make sure we're at left-/right-most pos in new row
1319 posVisToRowExtremity(!movingLeft);
1325 void Cursor::posVisToRowExtremity(bool left)
1327 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
1328 << (boundary() ? 1 : 0));
1330 TextMetrics const & tm = bv_->textMetrics(text());
1331 // Looking for extremities is like clicking on the left or the
1332 // right of the row.
1333 int x = tm.origin().x_ + (left ? 0 : textRow().width());
1335 pos() = tm.getPosNearX(textRow(), x, b);
1338 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
1339 << (boundary() ? 1 : 0));
1343 bool Cursor::reverseDirectionNeeded() const
1346 * We determine the directions based on the direction of the
1347 * bottom() --- i.e., outermost --- paragraph, because that is
1348 * the only way to achieve consistency of the arrow's movements
1349 * within a paragraph, and thus avoid situations in which the
1350 * cursor gets stuck.
1352 return bottom().paragraph().isRTL(bv().buffer().params());
1356 void Cursor::setTargetX(int x)
1359 textTargetOffset_ = 0;
1363 int Cursor::x_target() const
1369 void Cursor::clearTargetX()
1372 textTargetOffset_ = 0;
1376 void Cursor::updateTextTargetOffset()
1381 textTargetOffset_ = x - x_target_;
1385 bool Cursor::selHandle(bool sel)
1387 //lyxerr << "Cursor::selHandle" << endl;
1390 if (sel == selection())
1394 cap::saveSelection(*this);
1402 bool Cursor::atFirstOrLastRow(bool up)
1404 TextMetrics const & tm = bv_->textMetrics(text());
1405 ParagraphMetrics const & pm = tm.parMetrics(pit());
1408 if (pos() && boundary())
1409 row = pm.pos2row(pos() - 1);
1411 row = pm.pos2row(pos());
1414 if (pit() == 0 && row == 0)
1417 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1418 row + 1 >= int(pm.rows().size()))
1428 ///////////////////////////////////////////////////////////////////
1431 // The part below is the non-integrated rest of the original math
1432 // cursor. This should be either generalized for texted or moved
1433 // back to mathed (in most cases to InsetMathNest).
1435 ///////////////////////////////////////////////////////////////////
1437 #include "mathed/InsetMathChar.h"
1438 #include "mathed/InsetMathGrid.h"
1439 #include "mathed/InsetMathScript.h"
1440 #include "mathed/InsetMathUnknown.h"
1441 #include "mathed/MathFactory.h"
1442 #include "mathed/MathStream.h"
1443 #include "mathed/MathSupport.h"
1448 bool Cursor::openable(MathAtom const & t) const
1459 // we can't move into anything new during selection
1460 if (depth() >= realAnchor().depth())
1462 if (t.nucleus() != &realAnchor()[depth()].inset())
1469 void Cursor::plainErase()
1471 cell().erase(pos());
1475 void Cursor::plainInsert(MathAtom const & t)
1477 cell().insert(pos(), t);
1479 inset().setBuffer(bv_->buffer());
1481 checkBufferStructure();
1485 void Cursor::insert(char_type c)
1487 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1488 LASSERT(!empty(), return);
1490 cap::selClearOrDel(*this);
1491 insert(new InsetMathChar(c));
1493 text()->insertChar(*this, c);
1498 void Cursor::insert(docstring const & str)
1500 for (char_type c : str)
1505 void Cursor::insert(Inset * inset0)
1507 LASSERT(inset0, return);
1509 insert(MathAtom(inset0->asInsetMath()));
1511 text()->insertInset(*this, inset0);
1512 inset0->setBuffer(bv_->buffer());
1514 if (inset0->isLabeled())
1515 forceBufferUpdate();
1520 void Cursor::insert(MathAtom const & t)
1522 LATTEST(inMathed());
1523 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1525 cap::selClearOrDel(*this);
1530 void Cursor::insert(MathData const & ar)
1532 LATTEST(inMathed());
1535 cap::eraseSelection(*this);
1536 cell().insert(pos(), ar);
1538 // FIXME audit setBuffer calls
1539 inset().setBuffer(bv_->buffer());
1543 int Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1545 LATTEST(inMathed());
1546 MathData ar(buffer());
1548 if (ar.size() == 1 && (enter || selection()))
1556 void Cursor::niceInsert(MathAtom const & t)
1558 LATTEST(inMathed());
1560 docstring const safe = cap::grabAndEraseSelection(*this);
1562 // If possible, enter the new inset and move the contents of the selection
1563 if (t->isActive()) {
1564 idx_type const idx = prevMath().asNestInset()->firstIdx();
1565 MathData ar(buffer());
1567 prevMath().cell(idx).insert(0, ar);
1568 editInsertedInset();
1569 } else if (t->asMacro() && !safe.empty()) {
1570 MathData ar(buffer());
1572 docstring const name = t->asMacro()->name();
1573 MacroData const * data = buffer()->getMacro(name);
1574 if (data && data->numargs() - data->optionals() > 0) {
1575 plainInsert(MathAtom(new InsetMathBrace(ar)));
1582 bool Cursor::backspace(bool const force)
1585 cap::eraseSelection(*this);
1590 // If empty cell, and not part of a big cell
1591 if (lastpos() == 0 && inset().nargs() == 1) {
1593 // Directly delete empty cell: [|[]] => [|]
1599 // [|], can not delete from inside
1610 if (inMacroMode()) {
1611 InsetMathUnknown * p = activeMacro();
1612 if (p->name().size() > 1) {
1613 p->setName(p->name().substr(0, p->name().size() - 1));
1618 if (pos() != 0 && !force && prevAtom()->confirmDeletion()) {
1619 // let's require two backspaces for 'big stuff' and
1620 // highlight on the first
1632 bool Cursor::erase(bool const force)
1638 cap::eraseSelection(*this);
1642 // delete empty cells if possible
1643 if (pos() == lastpos() && inset().idxDelete(idx()))
1646 // special behaviour when in last position of cell
1647 if (pos() == lastpos()) {
1648 bool one_cell = inset().nargs() == 1;
1649 if (one_cell && lastpos() == 0) {
1651 // Directly delete empty cell: [|[]] => [|]
1657 // [|], can not delete from inside
1662 inset().idxGlue(idx());
1666 // 'clever' UI hack: only erase large items if previously slected
1667 if (pos() != lastpos() && !force && nextAtom()->confirmDeletion()) {
1682 DocIterator save = *this;
1683 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1684 this->dispatch(cmd);
1685 if (disp_.dispatched())
1695 DocIterator save = *this;
1696 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1697 this->dispatch(cmd);
1698 if (disp_.dispatched())
1705 void Cursor::handleNest(MathAtom const & a)
1707 idx_type const idx = a.nucleus()->asNestInset()->firstIdx();
1708 //lyxerr << "Cursor::handleNest: " << idx << endl;
1710 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(idx));
1712 editInsertedInset();
1716 int Cursor::targetX() const
1718 if (x_target() != -1)
1727 int Cursor::textTargetOffset() const
1729 return textTargetOffset_;
1733 void Cursor::setTargetX()
1742 bool Cursor::macroModeClose(bool cancel)
1746 InsetMathUnknown * p = activeMacro();
1748 MathData selection(buffer());
1749 asArray(p->selection(), selection);
1750 docstring const s = p->name();
1752 cell().erase(pos());
1754 // trigger updates of macros, at least, if no full
1755 // updates take place anyway
1756 screenUpdateFlags(Update::Force);
1758 // do nothing if the macro name is empty
1759 if (s == "\\" || cancel) {
1763 docstring const name = s.substr(1);
1764 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1765 if (in && in->interpretString(*this, s))
1767 bool const user_macro = buffer()->getMacro(name, *this, false);
1768 MathAtom atom = user_macro ? MathAtom(new InsetMathMacro(buffer(), name))
1769 : createInsetMath(name, buffer());
1771 // try to put argument into macro, if we just inserted a macro
1772 bool macroArg = false;
1773 InsetMathMacro * atomAsMacro = atom.nucleus()->asMacro();
1774 InsetMathNest * atomAsNest = atom.nucleus()->asNestInset();
1776 // macros here are still unfolded (in init mode in fact). So
1777 // we have to resolve the macro here manually and check its arity
1778 // to put the selection behind it if arity > 0.
1779 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1780 if (!selection.empty() && data && data->numargs()) {
1782 atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1784 // non-greedy case. Do not touch the arguments behind
1785 atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1788 // insert remembered selection into first argument of a non-macro
1789 else if (atomAsNest && atomAsNest->nargs() > 0)
1790 atomAsNest->cell(atomAsNest->firstIdx()).append(selection);
1792 MathWordList const & words = mathedWordList();
1793 MathWordList::const_iterator it = words.find(name);
1794 bool keep_mathmode = user_macro
1795 || (it != words.end() && (it->second.inset == "font"
1796 || it->second.inset == "oldfont"
1797 || it->second.inset == "mbox"));
1798 bool ert_macro = !user_macro && it == words.end() && atomAsMacro;
1800 if (in && in->currentMode() == Inset::TEXT_MODE
1801 && atom.nucleus()->currentMode() == Inset::MATH_MODE
1802 && name != from_ascii("ensuremath") && !ert_macro) {
1803 MathAtom at(new InsetMathEnsureMath(buffer()));
1804 at.nucleus()->cell(0).push_back(atom);
1807 } else if (in && in->currentMode() == Inset::MATH_MODE
1808 && atom.nucleus()->currentMode() == Inset::TEXT_MODE
1809 && !keep_mathmode) {
1810 MathAtom at = createInsetMath("text", buffer());
1811 at.nucleus()->cell(0).push_back(atom);
1817 // finally put the macro argument behind, if needed
1819 if (selection.size() > 1 || selection[0]->asScriptInset())
1820 plainInsert(MathAtom(new InsetMathBrace(selection)));
1829 bool Cursor::inMacroMode() const
1833 if (pos() == 0 || cell().empty())
1835 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1836 return p && !p->final();
1840 InsetMathUnknown * Cursor::activeMacro()
1842 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : nullptr;
1846 InsetMathUnknown const * Cursor::activeMacro() const
1848 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : nullptr;
1852 docstring Cursor::macroName()
1854 return inMacroMode() ? activeMacro()->name() : docstring();
1858 void Cursor::pullArg()
1861 MathData ar = cell();
1862 if (popBackward() && inMathed()) {
1864 cell().insert(pos(), ar);
1867 //formula()->mutateToText();
1872 void Cursor::normalize()
1874 if (idx() > lastidx()) {
1875 lyxerr << "this should not really happen - 1: "
1876 << idx() << ' ' << nargs()
1877 << " in: " << &inset() << endl;
1881 if (pos() > lastpos()) {
1882 lyxerr << "this should not really happen - 2: "
1883 << pos() << ' ' << lastpos() << " in idx: " << idx()
1885 odocstringstream os;
1886 otexrowstream ots(os);
1887 WriteStream wi(ots, false, true, WriteStream::wsDefault);
1888 inset().asInsetMath()->write(wi);
1889 lyxerr << to_utf8(os.str()) << endl;
1895 bool Cursor::upDownInMath(bool up)
1897 // Be warned: The 'logic' implemented in this function is highly
1898 // fragile. A distance of one pixel or a '<' vs '<=' _really
1899 // matters. So fiddle around with it only if you think you know
1900 // what you are doing!
1904 xo = beforeDispatchPosX_;
1906 // check if we had something else in mind, if not, this is the future
1908 if (x_target_ == -1)
1910 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1911 // In text mode inside the line (not left or right) possibly set a new target_x,
1912 // but only if we are somewhere else than the previous target-offset.
1914 // We want to keep the x-target on subsequent up/down movements
1915 // that cross beyond the end of short lines. Thus a special
1916 // handling when the cursor is at the end of line: Use the new
1917 // x-target only if the old one was before the end of line
1918 // or the old one was after the beginning of the line
1919 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
1923 left = pos() == textRow().endpos();
1924 right = pos() == textRow().pos();
1926 left = pos() == textRow().pos();
1927 right = pos() == textRow().endpos();
1929 if ((!left && !right) ||
1930 (left && !right && xo < x_target_) ||
1931 (!left && right && x_target_ < xo))
1938 // try neigbouring script insets
1940 if (inMathed() && !selection()) {
1943 InsetMathScript const * p = prevAtom()->asScriptInset();
1944 if (p && p->has(up)) {
1946 push(*const_cast<InsetMathScript*>(p));
1947 idx() = p->idxOfScript(up);
1950 // we went in the right direction? Otherwise don't jump into the script
1954 int oy = beforeDispatchPosY_;
1955 if ((!up && y <= oy) ||
1964 if (pos() != lastpos()) {
1965 InsetMathScript const * p = nextAtom()->asScriptInset();
1966 if (p && p->has(up)) {
1967 push(*const_cast<InsetMathScript*>(p));
1968 idx() = p->idxOfScript(up);
1971 // we went in the right direction? Otherwise don't jump into the script
1975 int oy = beforeDispatchPosY_;
1976 if ((!up && y <= oy) ||
1985 // try to find an inset that knows better then we,
1986 if (inset().idxUpDown(*this, up)) {
1987 //lyxerr << "idxUpDown triggered" << endl;
1988 // try to find best position within this inset
1990 setCursor(bruteFind(*this, xo, yo));
1994 // any improvement going just out of inset?
1995 if (popBackward() && inMathed()) {
1996 //lyxerr << "updown: popBackward succeeded" << endl;
1999 int yold = beforeDispatchPosY_;
2001 if (up ? ynew < yold : ynew > yold)
2005 // no success, we are probably at the document top or bottom
2011 bool Cursor::mathForward(bool word)
2013 LASSERT(inMathed(), return false);
2014 if (pos() < lastpos()) {
2016 // word: skip a group of insets of the form X*(B*|R*|P*) (greedy
2017 // match) where X is any math class, B is mathbin, R is mathrel, and
2018 // P is mathpunct. Make sure that the following remains true:
2019 // mathForward(true); mathBackward(true); mathForward(true)
2020 // is the same as mathForward(true) and
2021 // mathBackward(true); mathForward(true); mathBackward(true)
2022 // is the same as mathBackward(true).
2023 MathClass mc = nextMath().mathClass();
2026 while (pos() < lastpos() && mc == nextMath().mathClass());
2027 if (pos() < lastpos() &&
2028 ((mc = nextMath().mathClass()) == MC_BIN ||
2029 mc == MC_REL || mc == MC_PUNCT))
2032 while (pos() < lastpos() && mc == nextMath().mathClass());
2033 } else if (openable(nextAtom())) {
2034 // single step: try to enter the next inset
2035 pushBackward(nextMath());
2036 inset().idxFirst(*this);
2041 if (inset().idxForward(*this))
2043 // try to pop forwards --- but don't pop out of math! leave that to
2045 int s = depth() - 2;
2046 if (s >= 0 && operator[](s).inset().asInsetMath())
2047 return popForward();
2052 bool Cursor::mathBackward(bool word)
2054 LASSERT(inMathed(), return false);
2057 // word: skip a group of insets. See the comment in mathForward.
2058 MathClass mc = prevMath().mathClass();
2061 while (pos() > 0 && mc == prevMath().mathClass());
2062 if (pos() > 0 && (mc == MC_BIN || mc == MC_REL || mc == MC_PUNCT)) {
2063 mc = prevMath().mathClass();
2066 while (pos() > 0 && mc == prevMath().mathClass());
2068 } else if (openable(prevAtom())) {
2069 // single step: try to enter the preceding inset
2072 inset().idxLast(*this);
2077 if (inset().idxBackward(*this))
2079 // try to pop backwards --- but don't pop out of math! leave that to
2081 int s = depth() - 2;
2082 if (s >= 0 && operator[](s).inset().asInsetMath())
2083 return popBackward();
2088 bool Cursor::upDownInText(bool up, bool & updateNeeded)
2090 LASSERT(text(), return false);
2096 xo = beforeDispatchPosX_;
2098 // update the targetX - this is here before the "return false"
2099 // to set a new target which can be used by InsetTexts above
2100 // if we cannot move up/down inside this inset anymore
2101 if (x_target_ == -1)
2103 else if (xo - textTargetOffset() != x_target() &&
2104 depth() == beforeDispatchCursor_.depth()) {
2105 // In text mode inside the line (not left or right)
2106 // possibly set a new target_x, but only if we are
2107 // somewhere else than the previous target-offset.
2109 // We want to keep the x-target on subsequent up/down
2110 // movements that cross beyond the end of short lines.
2111 // Thus a special handling when the cursor is at the
2112 // end of line: Use the new x-target only if the old
2113 // one was before the end of line or the old one was
2114 // after the beginning of the line
2115 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
2119 left = pos() == textRow().endpos();
2120 right = pos() == textRow().pos();
2122 left = pos() == textRow().pos();
2123 right = pos() == textRow().endpos();
2125 if ((!left && !right) ||
2126 (left && !right && xo < x_target_) ||
2127 (!left && right && x_target_ < xo))
2134 // first get the current line
2135 TextMetrics & tm = bv_->textMetrics(text());
2136 ParagraphMetrics const & pm = tm.parMetrics(pit());
2138 if (pos() && boundary())
2139 row = pm.pos2row(pos() - 1);
2141 row = pm.pos2row(pos());
2143 if (atFirstOrLastRow(up)) {
2144 // Is there a place for the cursor to go ? If yes, we
2145 // can execute the DEPM, otherwise we should keep the
2146 // paragraph to host the cursor.
2147 Cursor dummy = *this;
2148 bool valid_destination = false;
2149 for(; dummy.depth(); dummy.pop())
2150 if (!dummy.atFirstOrLastRow(up)) {
2151 valid_destination = true;
2155 // will a next dispatch follow and if there is a new
2156 // dispatch will it move the cursor out ?
2157 if (depth() > 1 && valid_destination) {
2158 // The cursor hasn't changed yet. This happens when
2159 // you e.g. move out of an inset. And to give the
2160 // DEPM the possibility of doing something we must
2161 // provide it with two different cursors. (Lgb, vfr)
2163 dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
2164 dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
2166 updateNeeded |= bv().checkDepm(dummy, *this);
2167 updateTextTargetOffset();
2169 forceBufferUpdate();
2174 // with and without selection are handled differently
2176 int yo1 = bv().getPos(*this).y_;
2178 // To next/previous row
2179 // FIXME: the y position is often guessed wrongly across styles and
2180 // insets, which leads to weird behaviour.
2182 tm.editXY(*this, xo, yo1 - textRow().ascent() - 1);
2184 tm.editXY(*this, xo, yo1 + textRow().descent() + 1);
2185 x_target_ = old.x_target_;
2188 // This happens when you move out of an inset.
2189 // And to give the DEPM the possibility of doing
2190 // something we must provide it with two different
2192 Cursor dummy = *this;
2195 if (bv().checkDepm(dummy, old)) {
2196 updateNeeded = true;
2197 // Make sure that cur gets back whatever happened to dummy (Lgb)
2200 if (inTexted() && pos() && paragraph().isEnvSeparator(pos() - 1))
2203 // if there is a selection, we stay out of any inset,
2204 // and just jump to the right position:
2210 } else if (pit() > 0) {
2212 TextMetrics & tm2 = bv_->textMetrics(text());
2213 if (!tm2.contains(pit()))
2214 tm2.newParMetricsUp();
2215 ParagraphMetrics const & pmcur = tm2.parMetrics(pit());
2216 next_row = pmcur.rows().size() - 1;
2219 if (row + 1 < int(pm.rows().size())) {
2221 } else if (pit() + 1 < int(text()->paragraphs().size())) {
2223 TextMetrics & tm2 = bv_->textMetrics(text());
2224 if (!tm2.contains(pit()))
2225 tm2.newParMetricsDown();
2230 Row const & real_next_row = tm.parMetrics(pit()).rows()[next_row];
2232 top().pos() = tm.getPosNearX(real_next_row, xo, bound);
2234 // When selection==false, this is done by TextMetrics::editXY
2237 updateNeeded |= bv().checkDepm(*this, old);
2241 forceBufferUpdate();
2242 updateTextTargetOffset();
2247 void Cursor::handleFont(string const & font)
2249 LYXERR(Debug::DEBUG, font);
2253 safe = cap::grabAndEraseSelection(*this);
2258 if (lastpos() != 0) {
2259 // something left in the cell
2261 // cursor in first position
2263 } else if (pos() == lastpos()) {
2264 // cursor in last position
2267 // cursor in between. split cell
2268 MathData::iterator bt = cell().begin();
2269 MathAtom at = createInsetMath(from_utf8(font), buffer());
2270 at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
2271 cell().erase(bt, bt + pos());
2276 // nothing left in the cell
2285 void Cursor::undispatched() const
2287 disp_.dispatched(false);
2291 void Cursor::dispatched() const
2293 disp_.dispatched(true);
2297 void Cursor::screenUpdateFlags(Update::flags f) const
2299 disp_.screenUpdate(f);
2303 void Cursor::noScreenUpdate() const
2305 disp_.screenUpdate(Update::None);
2309 void Cursor::forceBufferUpdate() const
2311 disp_.forceBufferUpdate();
2315 void Cursor::clearBufferUpdate() const
2317 disp_.clearBufferUpdate();
2321 bool Cursor::needBufferUpdate() const
2323 return disp_.needBufferUpdate();
2327 Font Cursor::getFont() const
2329 // The logic here should more or less match to the
2330 // Cursor::setCurrentFont logic, i.e. the cursor height should
2331 // give a hint what will happen if a character is entered.
2332 // FIXME: this is not the case, what about removing this method ? (see #10478).
2334 // HACK. far from being perfect...
2336 CursorSlice const & sl = innerTextSlice();
2337 Text const & text = *sl.text();
2338 Paragraph const & par = text.getPar(sl.pit());
2340 // on boundary, so we are really at the character before
2341 pos_type pos = sl.pos();
2342 if (pos > 0 && boundary())
2345 // on space? Take the font before (only for RTL boundary stay)
2347 TextMetrics const & tm = bv().textMetrics(&text);
2348 if (pos == sl.lastpos()
2349 || (par.isSeparator(pos)
2350 && !tm.isRTLBoundary(sl.pit(), pos)))
2354 // get font at the position
2355 Font font = par.getFont(buffer()->params(), pos,
2356 text.outerFont(sl.pit()));
2362 void Cursor::sanitize()
2364 setBuffer(&bv_->buffer());
2365 CursorData::sanitize();
2369 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2371 // find inset in common
2373 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2374 if (&old[i].inset() != &cur[i].inset())
2378 // update words if we just moved to another paragraph
2379 if (i == old.depth() && i == cur.depth()
2380 && !cur.buffer()->isClean()
2381 && cur.inTexted() && old.inTexted()
2382 && cur.pit() != old.pit()) {
2383 old.paragraph().updateWords();
2386 // notify everything on top of the common part in old cursor,
2387 // but stop if the inset claims the cursor to be invalid now
2388 for (size_type j = i; j < old.depth(); ++j) {
2389 Cursor inset_pos = old;
2390 inset_pos.cutOff(j);
2391 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2395 // notify everything on top of the common part in new cursor,
2396 // but stop if the inset claims the cursor to be invalid now
2397 for (; i < cur.depth(); ++i) {
2398 if (cur[i].inset().notifyCursorEnters(cur))
2406 void Cursor::setLanguageFromInput()
2408 if (!lyxrc.respect_os_kbd_language)
2410 string const & code = theApp()->inputLanguageCode();
2411 Language const * lang = languages.getFromCode(code, buffer()->getLanguages());
2413 current_font.setLanguage(lang);
2414 real_current_font.setLanguage(lang);
2416 LYXERR0("setLanguageFromCode: unknown language code " << code);
2420 void Cursor::setCurrentFont()
2422 CursorSlice const & cs = innerTextSlice();
2423 Paragraph const & par = cs.paragraph();
2424 pos_type cpit = cs.pit();
2425 pos_type cpos = cs.pos();
2426 Text const & ctext = *cs.text();
2427 TextMetrics const & tm = bv().textMetrics(&ctext);
2429 // are we behind previous char in fact? -> go to that char
2430 if (cpos > 0 && boundary())
2433 // find position to take the font from
2435 // paragraph end? -> font of last char
2436 if (cpos == lastpos())
2438 // on space? -> look at the words in front of space
2439 else if (cpos > 0 && par.isSeparator(cpos)) {
2440 // abc| def -> font of c
2441 // abc |[WERBEH], i.e. boundary==true -> font of c
2442 // abc [WERBEH]| def, font of the space
2443 if (!tm.isRTLBoundary(cpit, cpos))
2449 BufferParams const & bufparams = buffer()->params();
2450 current_font = par.getFontSettings(bufparams, cpos);
2451 real_current_font = tm.displayFont(cpit, cpos);
2453 // set language to input language
2454 setLanguageFromInput();
2456 // special case for paragraph end
2457 if (cs.pos() == lastpos()
2458 && tm.isRTLBoundary(cpit, cs.pos())
2460 Language const * lang = par.getParLanguage(bufparams);
2461 current_font.setLanguage(lang);
2462 current_font.fontInfo().setNumber(FONT_OFF);
2463 real_current_font.setLanguage(lang);
2464 real_current_font.fontInfo().setNumber(FONT_OFF);
2469 void Cursor::checkBufferStructure()
2471 Buffer const * master = buffer()->masterBuffer();
2472 master->tocBackend().updateItem(*this);
2473 if (master != buffer() && !master->hasGuiDelegate())
2474 // In case the master has no gui associated with it,
2475 // the TocItem is not updated (part of bug 5699).
2476 buffer()->tocBackend().updateItem(*this);
2480 void Cursor::moveToClosestEdge(int const x, bool const edit)
2482 if (Inset const * inset = nextInset()) {
2483 // stay in front of insets for which we want to open the dialog
2484 // (e.g. InsetMathSpace).
2485 if (edit && (inset->hasSettings() || !inset->contextMenuName().empty()))
2487 CoordCache::Insets const & insetCache = bv().coordCache().getInsets();
2488 if (!insetCache.has(inset))
2490 int const wid = insetCache.dim(inset).wid;
2491 Point p = insetCache.xy(inset);
2492 if (x > p.x_ + (wid + 1) / 2)