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.
19 #include "BufferView.h"
20 #include "CoordCache.h"
22 #include "CutAndPaste.h"
23 #include "DispatchResult.h"
27 #include "FuncRequest.h"
30 #include "LyXAction.h"
32 #include "Paragraph.h"
33 #include "ParIterator.h"
36 #include "TextMetrics.h"
37 #include "TocBackend.h"
39 #include "support/debug.h"
40 #include "support/docstream.h"
41 #include "support/ExceptionMessage.h"
42 #include "support/gettext.h"
43 #include "support/lassert.h"
45 #include "insets/InsetTabular.h"
46 #include "insets/InsetText.h"
48 #include "mathed/InsetMath.h"
49 #include "mathed/InsetMathBrace.h"
50 #include "mathed/InsetMathScript.h"
51 #include "mathed/MacroTable.h"
52 #include "mathed/MathData.h"
53 #include "mathed/MathMacro.h"
55 #include "support/bind.h"
68 // Find position closest to (x, y) in cell given by iter.
69 // Used only in mathed
70 DocIterator bruteFind2(Cursor const & c, int x, int y)
72 double best_dist = numeric_limits<double>::max();
79 et.top().pos() = et.top().asInsetMath()->cell(et.top().idx()).size();
80 for (size_t i = 0;; ++i) {
83 Inset const * inset = &it.inset();
84 CoordCache const & cache = c.bv().coordCache();
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 (!cache.getInsets().has(inset)) {
95 Point const o = cache.getInsets().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) {
118 /// moves position closest to (x, y) in given box
119 bool bruteFind(Cursor & cursor,
120 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
122 LASSERT(!cursor.empty(), return false);
123 Inset & inset = cursor[0].inset();
124 BufferView & bv = cursor.bv();
126 CoordCache::InnerParPosCache const & cache =
127 bv.coordCache().getParPos().find(cursor.bottom().text())->second;
128 // Get an iterator on the first paragraph in the cache
129 DocIterator it(inset);
130 it.push_back(CursorSlice(inset));
131 it.pit() = cache.begin()->first;
132 // Get an iterator after the last paragraph in the cache
133 DocIterator et(inset);
134 et.push_back(CursorSlice(inset));
135 et.pit() = boost::prior(cache.end())->first;
136 if (et.pit() >= et.lastpit())
137 et = doc_iterator_end(inset);
141 double best_dist = numeric_limits<double>::max();
142 DocIterator best_cursor = et;
144 for ( ; it != et; it.forwardPos(true)) {
145 // avoid invalid nesting when selecting
146 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
147 Point p = bv.getPos(it, false);
150 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
151 double const dx = xo - x;
152 double const dy = yo - y;
153 double const d = dx * dx + dy * dy;
154 // '<=' in order to take the last possible position
155 // this is important for clicking behind \sum in e.g. '\sum_i a'
156 if (d <= best_dist) {
157 // lyxerr << "*" << endl;
165 if (best_cursor != et) {
166 cursor.setCursor(best_cursor);
175 /// moves position closest to (x, y) in given box
176 bool bruteFind3(Cursor & cur, int x, int y, bool up)
178 BufferView & bv = cur.bv();
179 int ylow = up ? 0 : y + 1;
180 int yhigh = up ? y - 1 : bv.workHeight();
182 int xhigh = bv.workWidth();
184 // FIXME: bit more work needed to get 'from' and 'to' right.
185 pit_type from = cur.bottom().pit();
186 //pit_type to = cur.bottom().pit();
187 //lyxerr << "Pit start: " << from << endl;
189 //lyxerr << "bruteFind3: x: " << x << " y: " << y
190 // << " xlow: " << xlow << " xhigh: " << xhigh
191 // << " ylow: " << ylow << " yhigh: " << yhigh
193 DocIterator it = doc_iterator_begin(cur.buffer());
195 DocIterator et = doc_iterator_end(cur.buffer());
197 double best_dist = numeric_limits<double>::max();
198 DocIterator best_cursor = et;
200 for ( ; it != et; it.forwardPos()) {
201 // avoid invalid nesting when selecting
202 if (bv.cursorStatus(it) == CUR_INSIDE
203 && (!cur.selection() || positionable(it, cur.realAnchor()))) {
204 // If this function is ever used again, check
205 // whether this is the same as "bv.getPos(it,
206 // false)" with boundary = false.
207 Point p = bv.getPos(it);
210 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
211 double const dx = xo - x;
212 double const dy = yo - y;
213 double const d = dx * dx + dy * dy;
214 //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
215 // << " dx: " << dx << " dy: " << dy
216 // << " idx: " << it.idx() << " pos: " << it.pos()
219 // '<=' in order to take the last possible position
220 // this is important for clicking behind \sum in e.g. '\sum_i a'
221 if (d <= best_dist) {
222 //lyxerr << "*" << endl;
230 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
231 if (best_cursor == et)
233 cur.setCursor(best_cursor);
240 CursorData::CursorData()
241 : DocIterator(), anchor_(),
242 selection_(false), mark_(false), word_selection_(false),
243 logicalpos_(false), current_font(inherit_font)
247 CursorData::CursorData(Buffer * buffer)
248 : DocIterator(buffer), anchor_(),
249 selection_(false), mark_(false), word_selection_(false),
250 logicalpos_(false), current_font(inherit_font)
254 CursorData::CursorData(DocIterator const & dit)
255 : DocIterator(dit), anchor_(),
256 selection_(false), mark_(false), word_selection_(false),
257 logicalpos_(false), current_font(inherit_font)
261 // be careful: this is called from the bv's constructor, too, so
262 // bv functions are not yet available!
263 Cursor::Cursor(BufferView & bv)
264 : CursorData(&bv.buffer()), bv_(&bv),
265 x_target_(-1), textTargetOffset_(0)
272 push_back(CursorSlice(buffer()->inset()));
273 anchor_ = doc_iterator_begin(buffer());
275 new_word_ = doc_iterator_begin(buffer());
283 // this (intentionally) does neither touch anchor nor selection status
284 void Cursor::setCursor(DocIterator const & cur)
286 DocIterator::operator=(cur);
290 void Cursor::setCursorToAnchor()
293 DocIterator normal = anchor_;
294 while (depth() < normal.depth())
296 if (depth() < anchor_.depth() && top() <= anchor_[depth() - 1])
303 void Cursor::setCursorData(CursorData const & data)
305 CursorData::operator=(data);
309 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
313 // Try to fix cursor in case it is broken.
316 // Is this a function that acts on inset at point?
317 Inset * inset = cur.nextInset();
318 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
319 && inset && inset->getStatus(cur, cmd, status))
322 // This is, of course, a mess. Better create a new doc iterator and use
323 // this in Inset::getStatus. This might require an additional
324 // BufferView * arg, though (which should be avoided)
325 //Cursor safe = *this;
327 for ( ; cur.depth(); cur.pop()) {
328 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
329 // LASSERT: Is it safe to continue here, or should we return?
330 LASSERT(cur.idx() <= cur.lastidx(), /**/);
331 LASSERT(cur.pit() <= cur.lastpit(), /**/);
332 LASSERT(cur.pos() <= cur.lastpos(), /**/);
334 // The inset's getStatus() will return 'true' if it made
335 // a definitive decision on whether it want to handle the
336 // request or not. The result of this decision is put into
337 // the 'status' parameter.
338 if (cur.inset().getStatus(cur, cmd, status)) {
347 void Cursor::saveBeforeDispatchPosXY()
349 getPos(beforeDispatchPosX_, beforeDispatchPosY_);
353 void Cursor::dispatch(FuncRequest const & cmd0)
355 LYXERR(Debug::DEBUG, "cmd: " << cmd0 << '\n' << *this);
360 FuncRequest cmd = cmd0;
363 disp_ = DispatchResult();
367 // Is this a function that acts on inset at point?
368 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
370 disp_.dispatched(true);
371 disp_.screenUpdate(Update::FitCursor | Update::Force);
372 FuncRequest tmpcmd = cmd;
373 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
374 << cmd0 << endl << *this);
375 nextInset()->dispatch(*this, tmpcmd);
376 if (disp_.dispatched()) {
382 // store some values to be used inside of the handlers
383 beforeDispatchCursor_ = *this;
384 for (; depth(); pop(), boundary(false)) {
385 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
386 << cmd0 << endl << *this);
388 // In any of these cases, the cursor is invalid, and we should
389 // try to save this document rather than crash.
390 LBUFERR(pos() <= lastpos());
391 LBUFERR(idx() <= lastidx());
392 LBUFERR(pit() <= lastpit());
394 // The common case is 'LFUN handled, need update', so make the
395 // LFUN handler's life easier by assuming this as default value.
396 // The handler can reset the update and val flags if necessary.
397 disp_.screenUpdate(Update::FitCursor | Update::Force);
398 disp_.dispatched(true);
399 inset().dispatch(*this, cmd);
400 if (disp_.dispatched())
404 // it completely to get a 'bomb early' behaviour in case this
405 // object will be used again.
406 if (!disp_.dispatched()) {
407 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
408 // We might have invalidated the cursor when removing an empty
409 // paragraph while the cursor could not be moved out the inset
410 // while we initially thought we could. This might happen when
411 // a multiline inset becomes an inline inset when the second
412 // paragraph is removed.
413 if (safe.pit() > safe.lastpit()) {
414 safe.pit() = safe.lastpit();
415 safe.pos() = safe.lastpos();
418 disp_.screenUpdate(Update::None);
419 disp_.dispatched(false);
421 // restore the previous one because nested Cursor::dispatch calls
422 // are possible which would change it
423 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
427 // notify insets we just left
429 old.beginUndoGroup();
431 bool badcursor = notifyCursorLeavesOrEnters(old, *this);
434 bv().resetInlineCompletionPos();
441 DispatchResult const & Cursor::result() const
447 BufferView & Cursor::bv() const
456 LBUFERR(depth() >= 1);
461 void Cursor::push(Inset & p)
463 push_back(CursorSlice(p));
464 p.setBuffer(*buffer());
468 void Cursor::pushBackward(Inset & p)
470 LASSERT(!empty(), return);
471 //lyxerr << "Entering inset " << t << " front" << endl;
477 bool Cursor::popBackward()
479 LASSERT(!empty(), return false);
487 bool Cursor::popForward()
489 LASSERT(!empty(), return false);
490 //lyxerr << "Leaving inset from in back" << endl;
491 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
495 pos() += lastpos() - lp + 1;
500 int Cursor::currentMode()
502 LASSERT(!empty(), return Inset::UNDECIDED_MODE);
503 for (int i = depth() - 1; i >= 0; --i) {
504 int res = operator[](i).inset().currentMode();
505 bool locked_mode = operator[](i).inset().lockedMode();
506 // Also return UNDECIDED_MODE when the mode is locked,
507 // as in this case it is treated the same as TEXT_MODE
508 if (res != Inset::UNDECIDED_MODE || locked_mode)
511 return Inset::TEXT_MODE;
515 void Cursor::getPos(int & x, int & y) const
517 Point p = bv().getPos(*this);
523 Row const & Cursor::textRow() const
525 CursorSlice const & cs = innerTextSlice();
526 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
527 return pm.getRow(pos(), boundary());
531 void Cursor::resetAnchor()
534 checkNewWordPosition();
538 void Cursor::markNewWordPosition()
540 if (lyxrc.spellcheck_continuously && inTexted() && new_word_.empty()) {
541 FontSpan nw = locateWord(WHOLE_WORD);
542 if (nw.size() == 1) {
543 LYXERR(Debug::DEBUG, "start new word: "
545 << " pos: " << nw.first);
552 void Cursor::clearNewWordPosition()
554 if (!new_word_.empty()) {
555 LYXERR(Debug::DEBUG, "clear new word: "
557 << " pos: " << pos());
563 void Cursor::checkNewWordPosition()
565 if (!lyxrc.spellcheck_continuously || new_word_.empty())
568 clearNewWordPosition();
570 // forget the position of the current new word if
571 // 1) the paragraph changes or
572 // 2) the count of nested insets changes or
573 // 3) the cursor pos is out of paragraph bound
574 if (pit() != new_word_.pit() ||
575 depth() != new_word_.depth() ||
576 new_word_.pos() > new_word_.lastpos()) {
577 clearNewWordPosition();
578 } else if (new_word_.fixIfBroken())
579 // 4) or the remembered position was "broken"
580 clearNewWordPosition();
582 FontSpan nw = locateWord(WHOLE_WORD);
584 FontSpan ow = new_word_.locateWord(WHOLE_WORD);
585 if (nw.intersect(ow).empty())
586 clearNewWordPosition();
588 LYXERR(Debug::DEBUG, "new word: "
590 << " pos: " << nw.first << ".." << nw.last);
592 clearNewWordPosition();
599 bool Cursor::posBackward()
608 bool Cursor::posForward()
610 if (pos() == lastpos())
617 bool Cursor::posVisRight(bool skip_inset)
619 Cursor new_cur = *this; // where we will move to
620 pos_type left_pos; // position visually left of current cursor
621 pos_type right_pos; // position visually right of current cursor
623 getSurroundingPos(left_pos, right_pos);
625 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
627 // Are we at an inset?
628 new_cur.pos() = right_pos;
629 new_cur.boundary(false);
631 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
632 // we actually move the cursor at the end of this
633 // function, for now we just keep track of the new
634 // position in new_cur...
635 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
638 // Are we already at rightmost pos in row?
639 else if (text()->empty() || right_pos == -1) {
642 if (!new_cur.posVisToNewRow(false)) {
643 LYXERR(Debug::RTL, "not moving!");
647 // we actually move the cursor at the end of this
648 // function, for now just keep track of the new
649 // position in new_cur...
650 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
651 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
654 // normal movement to the right
657 // Recall, if the cursor is at position 'x', that
658 // means *before* the character at position 'x'. In
659 // RTL, "before" means "to the right of", in LTR, "to
660 // the left of". So currently our situation is this:
661 // the position to our right is 'right_pos' (i.e.,
662 // we're currently to the left of 'right_pos'). In
663 // order to move to the right, it depends whether or
664 // not the character at 'right_pos' is RTL.
665 bool const new_pos_is_RTL = paragraph().getFontSettings(
666 buffer()->params(), right_pos).isVisibleRightToLeft();
667 // If the character at 'right_pos' *is* LTR, then in
668 // order to move to the right of it, we need to be
669 // *after* 'right_pos', i.e., move to position
671 if (!new_pos_is_RTL) {
672 new_cur.pos() = right_pos + 1;
673 // set the boundary to true in two situations:
675 // 1. if new_pos is now lastpos, and we're in
676 // an RTL paragraph (this means that we're
677 // moving right to the end of an LTR chunk
678 // which is at the end of an RTL paragraph);
679 (new_cur.pos() == lastpos()
680 && paragraph().isRTL(buffer()->params()))
681 // 2. if the position *after* right_pos is RTL
682 // (we want to be *after* right_pos, not
683 // before right_pos + 1!)
684 || paragraph().getFontSettings(buffer()->params(),
685 new_cur.pos()).isVisibleRightToLeft()
687 new_cur.boundary(true);
688 else // set the boundary to false
689 new_cur.boundary(false);
691 // Otherwise (if the character at position 'right_pos'
692 // is RTL), then moving to the right of it is as easy
693 // as setting the new position to 'right_pos'.
695 new_cur.pos() = right_pos;
696 new_cur.boundary(false);
701 bool moved = (new_cur.pos() != pos()
702 || new_cur.pit() != pit()
703 || new_cur.boundary() != boundary()
704 || &new_cur.inset() != &inset());
707 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
708 << (new_cur.boundary() ? " (boundary)" : ""));
716 bool Cursor::posVisLeft(bool skip_inset)
718 Cursor new_cur = *this; // where we will move to
719 pos_type left_pos; // position visually left of current cursor
720 pos_type right_pos; // position visually right of current cursor
722 getSurroundingPos(left_pos, right_pos);
724 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
726 // Are we at an inset?
727 new_cur.pos() = left_pos;
728 new_cur.boundary(false);
730 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
731 // we actually move the cursor at the end of this
732 // function, for now we just keep track of the new
733 // position in new_cur...
734 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
737 // Are we already at leftmost pos in row?
738 else if (text()->empty() || left_pos == -1) {
741 if (!new_cur.posVisToNewRow(true)) {
742 LYXERR(Debug::RTL, "not moving!");
746 // we actually move the cursor at the end of this
747 // function, for now just keep track of the new
748 // position in new_cur...
749 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
750 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
753 // normal movement to the left
756 // Recall, if the cursor is at position 'x', that
757 // means *before* the character at position 'x'. In
758 // RTL, "before" means "to the right of", in LTR, "to
759 // the left of". So currently our situation is this:
760 // the position to our left is 'left_pos' (i.e., we're
761 // currently to the right of 'left_pos'). In order to
762 // move to the left, it depends whether or not the
763 // character at 'left_pos' is RTL.
764 bool const new_pos_is_RTL = paragraph().getFontSettings(
765 buffer()->params(), left_pos).isVisibleRightToLeft();
766 // If the character at 'left_pos' *is* RTL, then in
767 // order to move to the left of it, we need to be
768 // *after* 'left_pos', i.e., move to position
770 if (new_pos_is_RTL) {
771 new_cur.pos() = left_pos + 1;
772 // set the boundary to true in two situations:
774 // 1. if new_pos is now lastpos and we're in
775 // an LTR paragraph (this means that we're
776 // moving left to the end of an RTL chunk
777 // which is at the end of an LTR paragraph);
778 (new_cur.pos() == lastpos()
779 && !paragraph().isRTL(buffer()->params()))
780 // 2. if the position *after* left_pos is not
781 // RTL (we want to be *after* left_pos, not
782 // before left_pos + 1!)
783 || !paragraph().getFontSettings(buffer()->params(),
784 new_cur.pos()).isVisibleRightToLeft()
786 new_cur.boundary(true);
787 else // set the boundary to false
788 new_cur.boundary(false);
790 // Otherwise (if the character at position 'left_pos'
791 // is LTR), then moving to the left of it is as easy
792 // as setting the new position to 'left_pos'.
794 new_cur.pos() = left_pos;
795 new_cur.boundary(false);
800 bool moved = (new_cur.pos() != pos()
801 || new_cur.pit() != pit()
802 || new_cur.boundary() != boundary());
805 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
806 << (new_cur.boundary() ? " (boundary)" : ""));
814 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos)
816 // preparing bidi tables
817 Paragraph const & par = paragraph();
818 Buffer const & buf = *buffer();
819 Row const & row = textRow();
821 bidi.computeTables(par, buf, row);
823 LYXERR(Debug::RTL, "bidi: " << row.pos() << "--" << row.endpos());
825 // The cursor is painted *before* the character at pos(), or,
826 // if 'boundary' is true, *after* the character at (pos() -
827 // 1). So we already have one known position around the
829 pos_type const known_pos = boundary() && pos() > 0 ? pos() - 1 : pos();
831 // edge case: if we're at the end of the paragraph, things are
832 // a little different (because lastpos is a position which
833 // does not really "exist" --- there's no character there
835 if (known_pos == lastpos()) {
836 if (par.isRTL(buf.params())) {
838 right_pos = bidi.vis2log(row.pos());
842 left_pos = bidi.vis2log(row.endpos() - 1);
847 // Whether 'known_pos' is to the left or to the right of the
848 // cursor depends on whether it is an RTL or LTR character...
849 bool const cur_is_RTL =
850 par.getFontSettings(buf.params(), known_pos).isVisibleRightToLeft();
851 // ... in the following manner:
852 // For an RTL character, "before"
853 // means "to the right" and "after" means "to the left"; and
854 // for LTR, it's the reverse. So, 'known_pos' is to the right
855 // of the cursor if (RTL && boundary) or (!RTL && !boundary):
856 bool const known_pos_on_right = cur_is_RTL == boundary();
858 // So we now know one of the positions surrounding the cursor.
859 // Let's determine the other one:
860 if (known_pos_on_right) {
861 right_pos = known_pos;
862 // *visual* position of 'left_pos':
863 pos_type v_left_pos = bidi.log2vis(right_pos) - 1;
864 // If the position we just identified as 'left_pos' is
865 // a "skipped separator" (a separator which is at the
866 // logical end of a row, except for the last row in a
867 // paragraph; such separators are not painted, so they
868 // "are not really there"; note that in bidi text,
869 // such a separator could appear visually in the
870 // middle of a row), set 'left_pos' to the *next*
871 // position to the left.
872 if (bidi.inRange(v_left_pos)
873 && bidi.vis2log(v_left_pos) + 1 == row.endpos()
874 && row.endpos() < lastpos()
875 && par.isSeparator(bidi.vis2log(v_left_pos)))
878 // calculate the logical position of 'left_pos', if in row
879 if (!bidi.inRange(v_left_pos))
882 left_pos = bidi.vis2log(v_left_pos);
883 // If the position we identified as 'right_pos' is a
884 // "skipped separator", set 'right_pos' to the *next*
885 // position to the right.
886 if (right_pos + 1 == row.endpos() && row.endpos() < lastpos()
887 && par.isSeparator(right_pos)) {
888 pos_type const v_right_pos = bidi.log2vis(right_pos) + 1;
889 if (!bidi.inRange(v_right_pos))
892 right_pos = bidi.vis2log(v_right_pos);
895 // known_pos is on the left
896 left_pos = known_pos;
897 // *visual* position of 'right_pos'
898 pos_type v_right_pos = bidi.log2vis(left_pos) + 1;
899 // If the position we just identified as 'right_pos'
900 // is a "skipped separator", set 'right_pos' to the
901 // *next* position to the right.
902 if (bidi.inRange(v_right_pos)
903 && bidi.vis2log(v_right_pos) + 1 == row.endpos()
904 && row.endpos() < lastpos()
905 && par.isSeparator(bidi.vis2log(v_right_pos)))
908 // calculate the logical position of 'right_pos', if in row
909 if (!bidi.inRange(v_right_pos))
912 right_pos = bidi.vis2log(v_right_pos);
913 // If the position we identified as 'left_pos' is a
914 // "skipped separator", set 'left_pos' to the *next*
915 // position to the left.
916 if (left_pos + 1 == row.endpos() && row.endpos() < lastpos()
917 && par.isSeparator(left_pos)) {
918 pos_type const v_left_pos = bidi.log2vis(left_pos) - 1;
919 if (!bidi.inRange(v_left_pos))
922 left_pos = bidi.vis2log(v_left_pos);
929 bool Cursor::posVisToNewRow(bool movingLeft)
931 Paragraph const & par = paragraph();
932 Buffer const & buf = *buffer();
933 Row const & row = textRow();
934 bool par_is_LTR = !par.isRTL(buf.params());
936 // Inside a table, determining whether to move to the next or
937 // previous row should be done based on the table's direction.
939 if (s >= 1 && (*this)[s].inset().asInsetTabular()) {
940 par_is_LTR = !(*this)[s].inset().asInsetTabular()->isRightToLeft(*this);
941 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
944 // if moving left in an LTR paragraph or moving right in an
945 // RTL one, move to previous row
946 if (par_is_LTR == movingLeft) {
947 if (row.pos() == 0) { // we're at first row in paragraph
948 if (pit() == 0) // no previous paragraph! don't move
950 // move to last pos in previous par
954 } else { // move to previous row in this par
955 pos() = row.pos() - 1; // this is guaranteed to be in previous row
959 // if moving left in an RTL paragraph or moving right in an
960 // LTR one, move to next row
962 if (row.endpos() == lastpos()) { // we're at last row in paragraph
963 if (pit() == lastpit()) // last paragraph! don't move
965 // move to first row in next par
969 } else { // move to next row in this par
970 pos() = row.endpos();
975 // make sure we're at left-/right-most pos in new row
976 posVisToRowExtremity(!movingLeft);
982 void Cursor::posVisToRowExtremity(bool left)
984 // prepare bidi tables
985 Paragraph const & par = paragraph();
986 Buffer const & buf = *buffer();
987 Row const & row = textRow();
989 bidi.computeTables(par, buf, row);
991 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
992 << (boundary() ? 1 : 0));
994 if (left) { // move to leftmost position
995 // if this is an RTL paragraph, and we're at the last row in the
996 // paragraph, move to lastpos
997 if (par.isRTL(buf.params()) && row.endpos() == lastpos())
1000 pos() = bidi.vis2log(row.pos());
1002 // Moving to the leftmost position in the row,
1003 // the cursor should normally be placed to the
1004 // *left* of the leftmost position. A very
1005 // common exception, though, is if the
1006 // leftmost character also happens to be the
1007 // separator at the (logical) end of the row
1008 // --- in this case, the separator is
1009 // positioned beyond the left margin, and we
1010 // don't want to move the cursor there (moving
1011 // to the left of the separator is equivalent
1012 // to moving to the next line). So, in this
1013 // case we actually want to place the cursor
1014 // to the *right* of the leftmost position
1015 // (the separator). Another exception is if
1016 // we're moving to the logically last position
1017 // in the row, which is *not* a separator:
1018 // this means that the entire row has no
1019 // separators (if there were any, the row
1020 // would have been broken there); and
1021 // therefore in this case we also move to the
1022 // *right* of the last position (this
1023 // indicates to the user that there is no
1024 // space after this position, and is
1025 // consistent with the behavior in the middle
1026 // of a row --- moving right or left moves to
1027 // the next/previous character; if we were to
1028 // move to the *left* of this position, that
1029 // would simulate a separator which is not
1030 // really there!). Finally, there is an
1031 // exception to the previous exception: if
1032 // this non-separator-but-last-position-in-row
1033 // is an inset, then we *do* want to stay to
1034 // the left of it anyway: this is the
1035 // "boundary" which we simulate at insets.
1037 // Another exception is when row.endpos() is
1040 // do we want to be to the right of pos?
1041 // as explained above, if at last pos in row, stay to the right
1042 bool const right_of_pos = row.endpos() > 0
1043 && pos() == row.endpos() - 1 && !par.isInset(pos());
1045 // Now we know if we want to be to the left or to the right of pos,
1046 // let's make sure we are where we want to be.
1047 bool const new_pos_is_RTL =
1048 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
1050 if (new_pos_is_RTL != right_of_pos) {
1056 // move to rightmost position
1057 // if this is an LTR paragraph, and we're at the last row in the
1058 // paragraph, move to lastpos
1059 if (!par.isRTL(buf.params()) && row.endpos() == lastpos())
1062 pos() = row.endpos() > 0 ? bidi.vis2log(row.endpos() - 1) : 0;
1064 // Moving to the rightmost position in the
1065 // row, the cursor should normally be placed
1066 // to the *right* of the rightmost position. A
1067 // very common exception, though, is if the
1068 // rightmost character also happens to be the
1069 // separator at the (logical) end of the row
1070 // --- in this case, the separator is
1071 // positioned beyond the right margin, and we
1072 // don't want to move the cursor there (moving
1073 // to the right of the separator is equivalent
1074 // to moving to the next line). So, in this
1075 // case we actually want to place the cursor
1076 // to the *left* of the rightmost position
1077 // (the separator). Another exception is if
1078 // we're moving to the logically last position
1079 // in the row, which is *not* a separator:
1080 // this means that the entire row has no
1081 // separators (if there were any, the row
1082 // would have been broken there); and
1083 // therefore in this case we also move to the
1084 // *left* of the last position (this indicates
1085 // to the user that there is no space after
1086 // this position, and is consistent with the
1087 // behavior in the middle of a row --- moving
1088 // right or left moves to the next/previous
1089 // character; if we were to move to the
1090 // *right* of this position, that would
1091 // simulate a separator which is not really
1092 // there!). Finally, there is an exception to
1093 // the previous exception: if this
1094 // non-separator-but-last-position-in-row is
1095 // an inset, then we *do* want to stay to the
1096 // right of it anyway: this is the "boundary"
1097 // which we simulate at insets. Another
1098 // exception is when row.endpos() is 0.
1100 // do we want to be to the left of pos?
1101 // as explained above, if at last pos in row, stay to the left,
1102 // unless the last position is the same as the first.
1103 bool const left_of_pos = row.endpos() > 0
1104 && pos() == row.endpos() - 1 && !par.isInset(pos());
1106 // Now we know if we want to be to the left or to the right of pos,
1107 // let's make sure we are where we want to be.
1108 bool const new_pos_is_RTL =
1109 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
1111 if (new_pos_is_RTL == left_of_pos) {
1117 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
1118 << (boundary() ? 1 : 0));
1122 CursorSlice Cursor::normalAnchor() const
1126 // LASSERT: There have been several bugs around this code, that seem
1127 // to involve failures to reset the anchor. We can at least not crash
1128 // in release mode by resetting it ourselves.
1129 LASSERT(anchor_.depth() >= depth(),
1130 const_cast<DocIterator &>(anchor_) = *this);
1132 CursorSlice normal = anchor_[depth() - 1];
1133 if (depth() < anchor_.depth() && top() <= normal) {
1134 // anchor is behind cursor -> move anchor behind the inset
1141 DocIterator & Cursor::realAnchor()
1147 CursorSlice Cursor::selBegin() const
1151 return normalAnchor() < top() ? normalAnchor() : top();
1155 CursorSlice Cursor::selEnd() const
1159 return normalAnchor() > top() ? normalAnchor() : top();
1163 DocIterator Cursor::selectionBegin() const
1169 // FIXME: This is a work-around for the problem that
1170 // CursorSlice doesn't keep track of the boundary.
1171 if (normalAnchor() == top())
1172 di = anchor_.boundary() > boundary() ? anchor_ : *this;
1174 di = normalAnchor() < top() ? anchor_ : *this;
1180 DocIterator Cursor::selectionEnd() const
1186 // FIXME: This is a work-around for the problem that
1187 // CursorSlice doesn't keep track of the boundary.
1188 if (normalAnchor() == top())
1189 di = anchor_.boundary() < boundary() ? anchor_ : *this;
1191 di = normalAnchor() > top() ? anchor_ : *this;
1193 if (di.depth() > depth()) {
1201 void Cursor::setSelection()
1204 if (idx() == normalAnchor().idx() &&
1205 pit() == normalAnchor().pit() &&
1206 pos() == normalAnchor().pos())
1207 setSelection(false);
1211 void Cursor::setSelection(DocIterator const & where, int n)
1220 void Cursor::clearSelection()
1222 setSelection(false);
1223 setWordSelection(false);
1229 void Cursor::setTargetX(int x)
1232 textTargetOffset_ = 0;
1236 int Cursor::x_target() const
1242 void Cursor::clearTargetX()
1245 textTargetOffset_ = 0;
1249 void Cursor::updateTextTargetOffset()
1254 textTargetOffset_ = x - x_target_;
1258 void Cursor::info(odocstream & os) const
1260 for (int i = 1, n = depth(); i < n; ++i) {
1261 operator[](i).inset().infoize(os);
1265 Inset const * inset = prevInset();
1266 // prevInset() can return 0 in certain case.
1268 prevInset()->infoize2(os);
1270 // overwite old message
1275 bool Cursor::selHandle(bool sel)
1277 //lyxerr << "Cursor::selHandle" << endl;
1280 if (sel == selection())
1284 cap::saveSelection(*this);
1292 ostream & operator<<(ostream & os, Cursor const & cur)
1294 os << "\n cursor: | anchor:\n";
1295 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
1296 os << " " << cur[i] << " | ";
1297 if (i < cur.anchor_.depth())
1298 os << cur.anchor_[i];
1300 os << "-------------------------------";
1303 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
1304 os << "------------------------------- | " << cur.anchor_[i] << "\n";
1306 os << " selection: " << cur.selection_
1307 << " x_target: " << cur.x_target_
1308 << " boundary: " << cur.boundary() << endl;
1313 LyXErr & operator<<(LyXErr & os, Cursor const & cur)
1323 ///////////////////////////////////////////////////////////////////
1326 // The part below is the non-integrated rest of the original math
1327 // cursor. This should be either generalized for texted or moved
1328 // back to mathed (in most cases to InsetMathNest).
1330 ///////////////////////////////////////////////////////////////////
1332 #include "mathed/InsetMathChar.h"
1333 #include "mathed/InsetMathGrid.h"
1334 #include "mathed/InsetMathScript.h"
1335 #include "mathed/InsetMathUnknown.h"
1336 #include "mathed/MathFactory.h"
1337 #include "mathed/MathStream.h"
1338 #include "mathed/MathSupport.h"
1343 bool Cursor::isInside(Inset const * p) const
1345 for (size_t i = 0; i != depth(); ++i)
1346 if (&operator[](i).inset() == p)
1352 void Cursor::leaveInset(Inset const & inset)
1354 for (size_t i = 0; i != depth(); ++i) {
1355 if (&operator[](i).inset() == &inset) {
1363 bool Cursor::openable(MathAtom const & t) const
1374 // we can't move into anything new during selection
1375 if (depth() >= anchor_.depth())
1377 if (t.nucleus() != &anchor_[depth()].inset())
1384 void Cursor::setScreenPos(int x, int /*y*/)
1387 //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
1392 void Cursor::plainErase()
1394 cell().erase(pos());
1398 void Cursor::markInsert()
1400 insert(char_type(0));
1404 void Cursor::markErase()
1406 cell().erase(pos());
1410 void Cursor::plainInsert(MathAtom const & t)
1412 cell().insert(pos(), t);
1414 inset().setBuffer(bv_->buffer());
1416 forceBufferUpdate();
1420 void Cursor::insert(docstring const & str)
1422 for_each(str.begin(), str.end(),
1423 bind(static_cast<void(Cursor::*)(char_type)>
1424 (&Cursor::insert), this, _1));
1428 void Cursor::insert(char_type c)
1430 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1431 LASSERT(!empty(), return);
1433 cap::selClearOrDel(*this);
1434 insert(new InsetMathChar(c));
1436 text()->insertChar(*this, c);
1441 void Cursor::insert(MathAtom const & t)
1443 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1445 cap::selClearOrDel(*this);
1450 void Cursor::insert(Inset * inset0)
1452 LASSERT(inset0, return);
1454 insert(MathAtom(inset0->asInsetMath()));
1456 text()->insertInset(*this, inset0);
1457 inset0->setBuffer(bv_->buffer());
1459 if (inset0->isLabeled())
1460 forceBufferUpdate();
1465 int Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1467 MathData ar(buffer());
1469 if (ar.size() == 1 && (enter || selection()))
1477 void Cursor::niceInsert(MathAtom const & t)
1480 docstring const safe = cap::grabAndEraseSelection(*this);
1482 // If possible, enter the new inset and move the contents of the selection
1483 if (t->isActive()) {
1485 // be careful here: don't use 'pushBackward(t)' as this we need to
1486 // push the clone, not the original
1487 pushBackward(*nextInset());
1488 // We may not use niceInsert here (recursion)
1489 MathData ar(buffer());
1492 } else if (t->asMacro() && !safe.empty()) {
1493 MathData ar(buffer());
1495 docstring const name = t->asMacro()->name();
1496 MacroData const * data = buffer()->getMacro(name);
1497 if (data && data->numargs() - data->optionals() > 0) {
1498 plainInsert(MathAtom(new InsetMathBrace(ar)));
1505 void Cursor::insert(MathData const & ar)
1509 cap::eraseSelection(*this);
1510 cell().insert(pos(), ar);
1512 // FIXME audit setBuffer calls
1513 inset().setBuffer(bv_->buffer());
1517 bool Cursor::backspace()
1520 cap::eraseSelection(*this);
1525 // If empty cell, and not part of a big cell
1526 if (lastpos() == 0 && inset().nargs() == 1) {
1528 // Directly delete empty cell: [|[]] => [|]
1534 // [|], can not delete from inside
1545 if (inMacroMode()) {
1546 InsetMathUnknown * p = activeMacro();
1547 if (p->name().size() > 1) {
1548 p->setName(p->name().substr(0, p->name().size() - 1));
1553 if (pos() != 0 && prevAtom()->nargs() > 0) {
1554 // let's require two backspaces for 'big stuff' and
1555 // highlight on the first
1567 bool Cursor::erase()
1573 cap::eraseSelection(*this);
1577 // delete empty cells if possible
1578 if (pos() == lastpos() && inset().idxDelete(idx()))
1581 // special behaviour when in last position of cell
1582 if (pos() == lastpos()) {
1583 bool one_cell = inset().nargs() == 1;
1584 if (one_cell && lastpos() == 0) {
1586 // Directly delete empty cell: [|[]] => [|]
1592 // [|], can not delete from inside
1597 inset().idxGlue(idx());
1601 // 'clever' UI hack: only erase large items if previously slected
1602 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
1617 DocIterator save = *this;
1618 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1619 this->dispatch(cmd);
1620 if (disp_.dispatched())
1630 DocIterator save = *this;
1631 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1632 this->dispatch(cmd);
1633 if (disp_.dispatched())
1640 bool Cursor::macroModeClose()
1644 InsetMathUnknown * p = activeMacro();
1646 MathData selection(buffer());
1647 asArray(p->selection(), selection);
1648 docstring const s = p->name();
1650 cell().erase(pos());
1652 // do nothing if the macro name is empty
1656 // trigger updates of macros, at least, if no full
1657 // updates take place anyway
1658 screenUpdateFlags(Update::Force);
1660 docstring const name = s.substr(1);
1661 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1662 if (in && in->interpretString(*this, s))
1664 MathAtom atom = buffer()->getMacro(name, *this, false) ?
1665 MathAtom(new MathMacro(buffer(), name)) : createInsetMath(name, buffer());
1667 // try to put argument into macro, if we just inserted a macro
1668 bool macroArg = false;
1669 MathMacro * atomAsMacro = atom.nucleus()->asMacro();
1671 // macros here are still unfolded (in init mode in fact). So
1672 // we have to resolve the macro here manually and check its arity
1673 // to put the selection behind it if arity > 0.
1674 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1675 if (!selection.empty() && data && data->numargs() - data->optionals() > 0) {
1677 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1679 // non-greedy case. Do not touch the arguments behind
1680 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1683 // insert remembered selection into first argument of a non-macro
1684 else if (atom.nucleus()->nargs() > 0)
1685 atom.nucleus()->cell(0).append(selection);
1689 // finally put the macro argument behind, if needed
1691 if (selection.size() > 1 || selection[0]->asScriptInset())
1692 plainInsert(MathAtom(new InsetMathBrace(selection)));
1701 docstring Cursor::macroName()
1703 return inMacroMode() ? activeMacro()->name() : docstring();
1707 void Cursor::handleNest(MathAtom const & a, int c)
1709 //lyxerr << "Cursor::handleNest: " << c << endl;
1711 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1714 pushBackward(*nextInset());
1718 int Cursor::targetX() const
1720 if (x_target() != -1)
1729 int Cursor::textTargetOffset() const
1731 return textTargetOffset_;
1735 void Cursor::setTargetX()
1744 bool Cursor::inMacroMode() const
1748 if (pos() == 0 || cell().empty())
1750 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1751 return p && !p->final();
1755 InsetMathUnknown * Cursor::activeMacro()
1757 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1761 InsetMathUnknown const * Cursor::activeMacro() const
1763 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1767 void Cursor::pullArg()
1770 MathData ar = cell();
1771 if (popBackward() && inMathed()) {
1773 cell().insert(pos(), ar);
1776 //formula()->mutateToText();
1781 void Cursor::touch()
1785 DocIterator::const_iterator it = begin();
1786 DocIterator::const_iterator et = end();
1787 for ( ; it != et; ++it)
1793 void Cursor::normalize()
1795 if (idx() > lastidx()) {
1796 lyxerr << "this should not really happen - 1: "
1797 << idx() << ' ' << nargs()
1798 << " in: " << &inset() << endl;
1802 if (pos() > lastpos()) {
1803 lyxerr << "this should not really happen - 2: "
1804 << pos() << ' ' << lastpos() << " in idx: " << idx()
1806 odocstringstream os;
1807 WriteStream wi(os, false, true, WriteStream::wsDefault);
1808 inset().asInsetMath()->write(wi);
1809 lyxerr << to_utf8(os.str()) << endl;
1815 bool Cursor::upDownInMath(bool up)
1817 // Be warned: The 'logic' implemented in this function is highly
1818 // fragile. A distance of one pixel or a '<' vs '<=' _really
1819 // matters. So fiddle around with it only if you think you know
1820 // what you are doing!
1824 xo = beforeDispatchPosX_;
1826 // check if we had something else in mind, if not, this is the future
1828 if (x_target_ == -1)
1830 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1831 // In text mode inside the line (not left or right) possibly set a new target_x,
1832 // but only if we are somewhere else than the previous target-offset.
1834 // We want to keep the x-target on subsequent up/down movements
1835 // that cross beyond the end of short lines. Thus a special
1836 // handling when the cursor is at the end of line: Use the new
1837 // x-target only if the old one was before the end of line
1838 // or the old one was after the beginning of the line
1839 bool inRTL = isWithinRtlParagraph(*this);
1843 left = pos() == textRow().endpos();
1844 right = pos() == textRow().pos();
1846 left = pos() == textRow().pos();
1847 right = pos() == textRow().endpos();
1849 if ((!left && !right) ||
1850 (left && !right && xo < x_target_) ||
1851 (!left && right && x_target_ < xo))
1858 // try neigbouring script insets
1860 if (inMathed() && !selection()) {
1863 InsetMathScript const * p = prevAtom()->asScriptInset();
1864 if (p && p->has(up)) {
1866 push(*const_cast<InsetMathScript*>(p));
1867 idx() = p->idxOfScript(up);
1870 // we went in the right direction? Otherwise don't jump into the script
1874 int oy = beforeDispatchPosY_;
1875 if ((!up && y <= oy) ||
1884 if (pos() != lastpos()) {
1885 InsetMathScript const * p = nextAtom()->asScriptInset();
1886 if (p && p->has(up)) {
1887 push(*const_cast<InsetMathScript*>(p));
1888 idx() = p->idxOfScript(up);
1891 // we went in the right direction? Otherwise don't jump into the script
1895 int oy = beforeDispatchPosY_;
1896 if ((!up && y <= oy) ||
1905 // try to find an inset that knows better then we,
1906 if (inset().idxUpDown(*this, up)) {
1907 //lyxerr << "idxUpDown triggered" << endl;
1908 // try to find best position within this inset
1910 setCursor(bruteFind2(*this, xo, yo));
1914 // any improvement going just out of inset?
1915 if (popBackward() && inMathed()) {
1916 //lyxerr << "updown: popBackward succeeded" << endl;
1919 int yold = beforeDispatchPosY_;
1921 if (up ? ynew < yold : ynew > yold)
1925 // no success, we are probably at the document top or bottom
1931 bool Cursor::atFirstOrLastRow(bool up)
1933 TextMetrics const & tm = bv_->textMetrics(text());
1934 ParagraphMetrics const & pm = tm.parMetrics(pit());
1937 if (pos() && boundary())
1938 row = pm.pos2row(pos() - 1);
1940 row = pm.pos2row(pos());
1943 if (pit() == 0 && row == 0)
1946 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1947 row + 1 >= int(pm.rows().size()))
1954 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1956 LASSERT(text(), return false);
1962 xo = beforeDispatchPosX_;
1964 // update the targetX - this is here before the "return false"
1965 // to set a new target which can be used by InsetTexts above
1966 // if we cannot move up/down inside this inset anymore
1967 if (x_target_ == -1)
1969 else if (xo - textTargetOffset() != x_target() &&
1970 depth() == beforeDispatchCursor_.depth()) {
1971 // In text mode inside the line (not left or right)
1972 // possibly set a new target_x, but only if we are
1973 // somewhere else than the previous target-offset.
1975 // We want to keep the x-target on subsequent up/down
1976 // movements that cross beyond the end of short lines.
1977 // Thus a special handling when the cursor is at the
1978 // end of line: Use the new x-target only if the old
1979 // one was before the end of line or the old one was
1980 // after the beginning of the line
1981 bool inRTL = isWithinRtlParagraph(*this);
1985 left = pos() == textRow().endpos();
1986 right = pos() == textRow().pos();
1988 left = pos() == textRow().pos();
1989 right = pos() == textRow().endpos();
1991 if ((!left && !right) ||
1992 (left && !right && xo < x_target_) ||
1993 (!left && right && x_target_ < xo))
2000 // first get the current line
2001 TextMetrics & tm = bv_->textMetrics(text());
2002 ParagraphMetrics const & pm = tm.parMetrics(pit());
2004 if (pos() && boundary())
2005 row = pm.pos2row(pos() - 1);
2007 row = pm.pos2row(pos());
2009 if (atFirstOrLastRow(up)) {
2010 // Is there a place for the cursor to go ? If yes, we
2011 // can execute the DEPM, otherwise we should keep the
2012 // paragraph to host the cursor.
2013 Cursor dummy = *this;
2014 bool valid_destination = false;
2015 for(; dummy.depth(); dummy.pop())
2016 if (!dummy.atFirstOrLastRow(up)) {
2017 valid_destination = true;
2021 // will a next dispatch follow and if there is a new
2022 // dispatch will it move the cursor out ?
2023 if (depth() > 1 && valid_destination) {
2024 // The cursor hasn't changed yet. This happens when
2025 // you e.g. move out of an inset. And to give the
2026 // DEPM the possibility of doing something we must
2027 // provide it with two different cursors. (Lgb, vfr)
2029 dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
2030 dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
2032 updateNeeded |= bv().checkDepm(dummy, *this);
2033 updateTextTargetOffset();
2035 forceBufferUpdate();
2040 // with and without selection are handled differently
2042 int yo = bv().getPos(*this).y_;
2044 // To next/previous row
2046 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
2048 tm.editXY(*this, xo, yo + textRow().descent() + 1);
2051 // This happens when you move out of an inset.
2052 // And to give the DEPM the possibility of doing
2053 // something we must provide it with two different
2055 Cursor dummy = *this;
2058 if (bv().checkDepm(dummy, old)) {
2059 updateNeeded = true;
2060 // Make sure that cur gets back whatever happened to dummy (Lgb)
2064 // if there is a selection, we stay out of any inset,
2065 // and just jump to the right position:
2071 } else if (pit() > 0) {
2073 TextMetrics & tm = bv_->textMetrics(text());
2074 if (!tm.contains(pit()))
2075 tm.newParMetricsUp();
2076 ParagraphMetrics const & pmcur = tm.parMetrics(pit());
2077 next_row = pmcur.rows().size() - 1;
2080 if (row + 1 < int(pm.rows().size())) {
2082 } else if (pit() + 1 < int(text()->paragraphs().size())) {
2084 TextMetrics & tm = bv_->textMetrics(text());
2085 if (!tm.contains(pit()))
2086 tm.newParMetricsDown();
2091 Row const & real_next_row = tm.parMetrics(pit()).rows()[next_row];
2093 top().pos() = tm.getPosNearX(real_next_row, xo, bound);
2096 updateNeeded |= bv().checkDepm(*this, old);
2100 forceBufferUpdate();
2101 updateTextTargetOffset();
2106 void Cursor::handleFont(string const & font)
2108 LYXERR(Debug::DEBUG, font);
2112 safe = cap::grabAndEraseSelection(*this);
2117 if (lastpos() != 0) {
2118 // something left in the cell
2120 // cursor in first position
2122 } else if (pos() == lastpos()) {
2123 // cursor in last position
2126 // cursor in between. split cell
2127 MathData::iterator bt = cell().begin();
2128 MathAtom at = createInsetMath(from_utf8(font), buffer());
2129 at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
2130 cell().erase(bt, bt + pos());
2135 // nothing left in the cell
2144 void Cursor::message(docstring const & msg) const
2146 disp_.setMessage(msg);
2150 void Cursor::errorMessage(docstring const & msg) const
2152 disp_.setMessage(msg);
2153 disp_.setError(true);
2159 docstring parbreak(Cursor const * cur)
2161 odocstringstream os;
2163 // only add blank line if we're not in a ParbreakIsNewline situation
2164 if (!cur->inset().getLayout().parbreakIsNewline()
2165 && !cur->paragraph().layout().parbreak_is_newline)
2173 docstring Cursor::selectionAsString(bool with_label) const
2179 return cap::grabSelection(*this);
2181 int const label = with_label
2182 ? AS_STR_LABEL | AS_STR_INSETS : AS_STR_INSETS;
2184 idx_type const startidx = selBegin().idx();
2185 idx_type const endidx = selEnd().idx();
2186 if (startidx != endidx) {
2187 // multicell selection
2188 InsetTabular * table = inset().asInsetTabular();
2189 LASSERT(table, return docstring());
2190 return table->asString(startidx, endidx);
2193 ParagraphList const & pars = text()->paragraphs();
2195 pit_type const startpit = selBegin().pit();
2196 pit_type const endpit = selEnd().pit();
2197 size_t const startpos = selBegin().pos();
2198 size_t const endpos = selEnd().pos();
2200 if (startpit == endpit)
2201 return pars[startpit].asString(startpos, endpos, label);
2203 // First paragraph in selection
2204 docstring result = pars[startpit].
2205 asString(startpos, pars[startpit].size(), label)
2208 // The paragraphs in between (if any)
2209 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
2210 Paragraph const & par = pars[pit];
2211 result += par.asString(0, par.size(), label)
2215 // Last paragraph in selection
2216 result += pars[endpit].asString(0, endpos, label);
2222 docstring Cursor::currentState() const
2225 odocstringstream os;
2231 return text()->currentState(*this);
2237 docstring Cursor::getPossibleLabel() const
2239 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
2243 Encoding const * Cursor::getEncoding() const
2247 CursorSlice const & sl = innerTextSlice();
2248 Text const & text = *sl.text();
2249 Font font = text.getPar(sl.pit()).getFont(
2250 bv().buffer().params(), sl.pos(), text.outerFont(sl.pit()));
2251 return font.language()->encoding();
2255 void Cursor::undispatched() const
2257 disp_.dispatched(false);
2261 void Cursor::dispatched() const
2263 disp_.dispatched(true);
2267 void Cursor::screenUpdateFlags(Update::flags f) const
2269 disp_.screenUpdate(f);
2273 void Cursor::forceBufferUpdate() const
2275 disp_.forceBufferUpdate();
2279 void Cursor::clearBufferUpdate() const
2281 disp_.clearBufferUpdate();
2285 bool Cursor::needBufferUpdate() const
2287 return disp_.needBufferUpdate();
2291 void Cursor::noScreenUpdate() const
2293 disp_.screenUpdate(Update::None);
2297 Font Cursor::getFont() const
2299 // The logic here should more or less match to the
2300 // Cursor::setCurrentFont logic, i.e. the cursor height should
2301 // give a hint what will happen if a character is entered.
2303 // HACK. far from being perfect...
2305 CursorSlice const & sl = innerTextSlice();
2306 Text const & text = *sl.text();
2307 Paragraph const & par = text.getPar(sl.pit());
2309 // on boundary, so we are really at the character before
2310 pos_type pos = sl.pos();
2311 if (pos > 0 && boundary())
2314 // on space? Take the font before (only for RTL boundary stay)
2316 TextMetrics const & tm = bv().textMetrics(&text);
2317 if (pos == sl.lastpos()
2318 || (par.isSeparator(pos)
2319 && !tm.isRTLBoundary(sl.pit(), pos)))
2323 // get font at the position
2324 Font font = par.getFont(buffer()->params(), pos,
2325 text.outerFont(sl.pit()));
2331 bool Cursor::fixIfBroken()
2333 bool const broken_cursor = DocIterator::fixIfBroken();
2334 bool const broken_anchor = anchor_.fixIfBroken();
2336 if (broken_cursor || broken_anchor) {
2337 clearNewWordPosition();
2345 void Cursor::sanitize()
2347 setBuffer(&bv_->buffer());
2348 DocIterator::sanitize();
2353 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2355 // find inset in common
2357 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2358 if (&old[i].inset() != &cur[i].inset())
2362 // update words if we just moved to another paragraph
2363 if (i == old.depth() && i == cur.depth()
2364 && !cur.buffer()->isClean()
2365 && cur.inTexted() && old.inTexted()
2366 && cur.pit() != old.pit()) {
2367 old.paragraph().updateWords();
2370 // notify everything on top of the common part in old cursor,
2371 // but stop if the inset claims the cursor to be invalid now
2372 for (size_type j = i; j < old.depth(); ++j) {
2373 Cursor inset_pos = old;
2374 inset_pos.cutOff(j);
2375 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2379 // notify everything on top of the common part in new cursor,
2380 // but stop if the inset claims the cursor to be invalid now
2381 for (; i < cur.depth(); ++i) {
2382 if (cur[i].inset().notifyCursorEnters(cur))
2390 void Cursor::setCurrentFont()
2392 CursorSlice const & cs = innerTextSlice();
2393 Paragraph const & par = cs.paragraph();
2394 pos_type cpit = cs.pit();
2395 pos_type cpos = cs.pos();
2396 Text const & ctext = *cs.text();
2397 TextMetrics const & tm = bv().textMetrics(&ctext);
2399 // are we behind previous char in fact? -> go to that char
2400 if (cpos > 0 && boundary())
2403 // find position to take the font from
2405 // paragraph end? -> font of last char
2406 if (cpos == lastpos())
2408 // on space? -> look at the words in front of space
2409 else if (cpos > 0 && par.isSeparator(cpos)) {
2410 // abc| def -> font of c
2411 // abc |[WERBEH], i.e. boundary==true -> font of c
2412 // abc [WERBEH]| def, font of the space
2413 if (!tm.isRTLBoundary(cpit, cpos))
2419 BufferParams const & bufparams = buffer()->params();
2420 current_font = par.getFontSettings(bufparams, cpos);
2421 real_current_font = tm.displayFont(cpit, cpos);
2423 // special case for paragraph end
2424 if (cs.pos() == lastpos()
2425 && tm.isRTLBoundary(cpit, cs.pos())
2427 Language const * lang = par.getParLanguage(bufparams);
2428 current_font.setLanguage(lang);
2429 current_font.fontInfo().setNumber(FONT_OFF);
2430 real_current_font.setLanguage(lang);
2431 real_current_font.fontInfo().setNumber(FONT_OFF);
2436 bool Cursor::textUndo()
2438 if (!buffer()->undo().textUndo(*this))
2445 bool Cursor::textRedo()
2447 if (!buffer()->undo().textRedo(*this))
2454 void Cursor::finishUndo() const
2456 buffer()->undo().finishUndo();
2460 void Cursor::beginUndoGroup() const
2462 buffer()->undo().beginUndoGroup();
2466 void Cursor::endUndoGroup() const
2468 buffer()->undo().endUndoGroup(*this);
2472 void Cursor::recordUndo(UndoKind kind, pit_type from, pit_type to) const
2474 buffer()->undo().recordUndo(*this, kind, from, to);
2478 void Cursor::recordUndo(UndoKind kind, pit_type from) const
2480 buffer()->undo().recordUndo(*this, kind, from);
2484 void Cursor::recordUndo(UndoKind kind) const
2486 buffer()->undo().recordUndo(*this, kind);
2490 void Cursor::recordUndoInset(UndoKind kind, Inset const * inset) const
2492 buffer()->undo().recordUndoInset(*this, kind, inset);
2496 void Cursor::recordUndoFullDocument() const
2498 buffer()->undo().recordUndoFullDocument(*this);
2502 void Cursor::recordUndoSelection() const
2505 if (cap::multipleCellsSelected(*this))
2510 buffer()->undo().recordUndo(*this, ATOMIC_UNDO,
2511 selBegin().pit(), selEnd().pit());
2516 void Cursor::checkBufferStructure()
2518 Buffer const * master = buffer()->masterBuffer();
2519 master->tocBackend().updateItem(*this);
2520 if (master != buffer() && !master->hasGuiDelegate())
2521 // In case the master has no gui associated with it,
2522 // the TocItem is not updated (part of bug 5699).
2523 buffer()->tocBackend().updateItem(*this);