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/lassert.h"
40 #include "support/debug.h"
41 #include "support/docstream.h"
43 #include "insets/InsetTabular.h"
44 #include "insets/InsetText.h"
46 #include "mathed/InsetMath.h"
47 #include "mathed/InsetMathBrace.h"
48 #include "mathed/InsetMathScript.h"
49 #include "mathed/MacroTable.h"
50 #include "mathed/MathData.h"
51 #include "mathed/MathMacro.h"
53 #include "support/bind.h"
66 bool positionable(DocIterator const & cursor, DocIterator const & anchor)
68 // avoid deeper nested insets when selecting
69 if (cursor.depth() > anchor.depth())
72 // anchor might be deeper, should have same path then
73 for (size_t i = 0; i < cursor.depth(); ++i)
74 if (&cursor[i].inset() != &anchor[i].inset())
77 // position should be ok.
82 // Find position closest to (x, y) in cell given by iter.
83 // Used only in mathed
84 DocIterator bruteFind2(Cursor const & c, int x, int y)
86 double best_dist = numeric_limits<double>::max();
93 et.top().pos() = et.top().asInsetMath()->cell(et.top().idx()).size();
94 for (size_t i = 0;; ++i) {
97 Inset const * inset = &it.inset();
98 CoordCache const & cache = c.bv().coordCache();
100 // FIXME: in the case where the inset is not in the cache, this
101 // means that no part of it is visible on screen. In this case
102 // we don't do elaborate search and we just return the forwarded
103 // DocIterator at its beginning.
104 if (!cache.getInsets().has(inset)) {
109 Point const o = cache.getInsets().xy(inset);
110 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
111 // Convert to absolute
114 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
115 // '<=' in order to take the last possible position
116 // this is important for clicking behind \sum in e.g. '\sum_i a'
117 LYXERR(Debug::DEBUG, "i: " << i << " d: " << d
118 << " best: " << best_dist);
119 if (d <= best_dist) {
132 /// moves position closest to (x, y) in given box
133 bool bruteFind(Cursor & cursor,
134 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
136 LASSERT(!cursor.empty(), return false);
137 Inset & inset = cursor[0].inset();
138 BufferView & bv = cursor.bv();
140 CoordCache::InnerParPosCache const & cache =
141 bv.coordCache().getParPos().find(cursor.bottom().text())->second;
142 // Get an iterator on the first paragraph in the cache
143 DocIterator it(inset);
144 it.push_back(CursorSlice(inset));
145 it.pit() = cache.begin()->first;
146 // Get an iterator after the last paragraph in the cache
147 DocIterator et(inset);
148 et.push_back(CursorSlice(inset));
149 et.pit() = boost::prior(cache.end())->first;
150 if (et.pit() >= et.lastpit())
151 et = doc_iterator_end(inset);
155 double best_dist = numeric_limits<double>::max();
156 DocIterator best_cursor = et;
158 for ( ; it != et; it.forwardPos(true)) {
159 // avoid invalid nesting when selecting
160 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
161 Point p = bv.getPos(it, false);
164 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
165 double const dx = xo - x;
166 double const dy = yo - y;
167 double const d = dx * dx + dy * dy;
168 // '<=' in order to take the last possible position
169 // this is important for clicking behind \sum in e.g. '\sum_i a'
170 if (d <= best_dist) {
171 // lyxerr << "*" << endl;
179 if (best_cursor != et) {
180 cursor.setCursor(best_cursor);
189 /// moves position closest to (x, y) in given box
190 bool bruteFind3(Cursor & cur, int x, int y, bool up)
192 BufferView & bv = cur.bv();
193 int ylow = up ? 0 : y + 1;
194 int yhigh = up ? y - 1 : bv.workHeight();
196 int xhigh = bv.workWidth();
198 // FIXME: bit more work needed to get 'from' and 'to' right.
199 pit_type from = cur.bottom().pit();
200 //pit_type to = cur.bottom().pit();
201 //lyxerr << "Pit start: " << from << endl;
203 //lyxerr << "bruteFind3: x: " << x << " y: " << y
204 // << " xlow: " << xlow << " xhigh: " << xhigh
205 // << " ylow: " << ylow << " yhigh: " << yhigh
207 DocIterator it = doc_iterator_begin(cur.buffer());
209 DocIterator et = doc_iterator_end(cur.buffer());
211 double best_dist = numeric_limits<double>::max();
212 DocIterator best_cursor = et;
214 for ( ; it != et; it.forwardPos()) {
215 // avoid invalid nesting when selecting
216 if (bv.cursorStatus(it) == CUR_INSIDE
217 && (!cur.selection() || positionable(it, cur.realAnchor()))) {
218 // If this function is ever used again, check whether this
219 // is the same as "bv.getPos(it, false)" with boundary = false.
220 Point p = bv.getPos(it);
223 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
224 double const dx = xo - x;
225 double const dy = yo - y;
226 double const d = dx * dx + dy * dy;
227 //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
228 // << " dx: " << dx << " dy: " << dy
229 // << " idx: " << it.idx() << " pos: " << it.pos()
232 // '<=' in order to take the last possible position
233 // this is important for clicking behind \sum in e.g. '\sum_i a'
234 if (d <= best_dist) {
235 //lyxerr << "*" << endl;
243 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
244 if (best_cursor == et)
246 cur.setCursor(best_cursor);
253 // be careful: this is called from the bv's constructor, too, so
254 // bv functions are not yet available!
255 Cursor::Cursor(BufferView & bv)
256 : DocIterator(&bv.buffer()), bv_(&bv), anchor_(),
257 x_target_(-1), textTargetOffset_(0),
258 selection_(false), mark_(false), word_selection_(false),
259 logicalpos_(false), current_font(inherit_font)
266 push_back(CursorSlice(buffer()->inset()));
267 anchor_ = doc_iterator_begin(buffer());
275 // this (intentionally) does neither touch anchor nor selection status
276 void Cursor::setCursor(DocIterator const & cur)
278 DocIterator::operator=(cur);
282 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
286 // Try to fix cursor in case it is broken.
289 // Is this a function that acts on inset at point?
290 Inset * inset = cur.nextInset();
291 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
292 && inset && inset->getStatus(cur, cmd, status))
295 // This is, of course, a mess. Better create a new doc iterator and use
296 // this in Inset::getStatus. This might require an additional
297 // BufferView * arg, though (which should be avoided)
298 //Cursor safe = *this;
300 for ( ; cur.depth(); cur.pop()) {
301 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
302 LASSERT(cur.idx() <= cur.lastidx(), /**/);
303 LASSERT(cur.pit() <= cur.lastpit(), /**/);
304 LASSERT(cur.pos() <= cur.lastpos(), /**/);
306 // The inset's getStatus() will return 'true' if it made
307 // a definitive decision on whether it want to handle the
308 // request or not. The result of this decision is put into
309 // the 'status' parameter.
310 if (cur.inset().getStatus(cur, cmd, status)) {
319 void Cursor::saveBeforeDispatchPosXY()
321 getPos(beforeDispatchPosX_, beforeDispatchPosY_);
325 void Cursor::dispatch(FuncRequest const & cmd0)
327 LYXERR(Debug::DEBUG, "cmd: " << cmd0 << '\n' << *this);
332 FuncRequest cmd = cmd0;
335 disp_ = DispatchResult();
337 buffer()->undo().beginUndoGroup();
339 // Is this a function that acts on inset at point?
340 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
342 disp_.dispatched(true);
343 disp_.screenUpdate(Update::FitCursor | Update::Force);
344 FuncRequest tmpcmd = cmd;
345 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
346 << cmd0 << endl << *this);
347 nextInset()->dispatch(*this, tmpcmd);
348 if (disp_.dispatched()) {
349 buffer()->undo().endUndoGroup();
354 // store some values to be used inside of the handlers
355 beforeDispatchCursor_ = *this;
356 for (; depth(); pop(), boundary(false)) {
357 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
358 << cmd0 << endl << *this);
359 LASSERT(pos() <= lastpos(), /**/);
360 LASSERT(idx() <= lastidx(), /**/);
361 LASSERT(pit() <= lastpit(), /**/);
363 // The common case is 'LFUN handled, need update', so make the
364 // LFUN handler's life easier by assuming this as default value.
365 // The handler can reset the update and val flags if necessary.
366 disp_.screenUpdate(Update::FitCursor | Update::Force);
367 disp_.dispatched(true);
368 inset().dispatch(*this, cmd);
369 if (disp_.dispatched())
373 // it completely to get a 'bomb early' behaviour in case this
374 // object will be used again.
375 if (!disp_.dispatched()) {
376 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
377 // We might have invalidated the cursor when removing an empty
378 // paragraph while the cursor could not be moved out the inset
379 // while we initially thought we could. This might happen when
380 // a multiline inset becomes an inline inset when the second
381 // paragraph is removed.
382 if (safe.pit() > safe.lastpit()) {
383 safe.pit() = safe.lastpit();
384 safe.pos() = safe.lastpos();
387 disp_.screenUpdate(Update::None);
388 disp_.dispatched(false);
390 // restore the previous one because nested Cursor::dispatch calls
391 // are possible which would change it
392 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
394 buffer()->undo().endUndoGroup();
396 // notify insets we just left
398 old.beginUndoGroup();
400 bool badcursor = notifyCursorLeavesOrEnters(old, *this);
403 bv().resetInlineCompletionPos();
410 DispatchResult const & Cursor::result() const
416 BufferView & Cursor::bv() const
425 LASSERT(depth() >= 1, /**/);
430 void Cursor::push(Inset & p)
432 push_back(CursorSlice(p));
433 p.setBuffer(*buffer());
437 void Cursor::pushBackward(Inset & p)
439 LASSERT(!empty(), return);
440 //lyxerr << "Entering inset " << t << " front" << endl;
446 bool Cursor::popBackward()
448 LASSERT(!empty(), return false);
456 bool Cursor::popForward()
458 LASSERT(!empty(), return false);
459 //lyxerr << "Leaving inset from in back" << endl;
460 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
464 pos() += lastpos() - lp + 1;
469 int Cursor::currentMode()
471 LASSERT(!empty(), /**/);
472 for (int i = depth() - 1; i >= 0; --i) {
473 int res = operator[](i).inset().currentMode();
474 bool locked_mode = operator[](i).inset().lockedMode();
475 // Also return UNDECIDED_MODE when the mode is locked,
476 // as in this case it is treated the same as TEXT_MODE
477 if (res != Inset::UNDECIDED_MODE || locked_mode)
480 return Inset::TEXT_MODE;
484 void Cursor::getPos(int & x, int & y) const
486 Point p = bv().getPos(*this);
492 Row const & Cursor::textRow() const
494 CursorSlice const & cs = innerTextSlice();
495 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
496 LASSERT(!pm.rows().empty(), /**/);
497 return pm.getRow(pos(), boundary());
501 void Cursor::resetAnchor()
504 checkNewWordPosition();
508 void Cursor::setCursorToAnchor()
511 DocIterator normal = anchor_;
512 while (depth() < normal.depth())
514 if (depth() < anchor_.depth() && top() <= anchor_[depth() - 1])
521 void Cursor::markEditPosition()
523 if (lyxrc.spellcheck_continuously && inTexted() && new_word_.empty()) {
524 FontSpan ow = locateWord(WHOLE_WORD);
525 if (ow.size() == 1) {
526 LYXERR(Debug::DEBUG, "start new word: "
528 << " pos: " << ow.first);
535 void Cursor::clearNewWordPosition()
537 if (!new_word_.empty()) {
538 LYXERR(Debug::DEBUG, "clear new word: "
540 << " pos: " << pos());
546 void Cursor::checkNewWordPosition()
548 if (!lyxrc.spellcheck_continuously || new_word_.empty())
551 clearNewWordPosition();
553 // forget the position of the current new word if
554 // 1) the paragraph changes or
555 // 2) the count of nested insets changes or
556 // 3) the cursor pos is out of paragraph bound
557 if (pit() != new_word_.pit() ||
558 depth() != new_word_.depth() ||
559 new_word_.pos() > new_word_.lastpos()) {
560 clearNewWordPosition();
561 } else if (new_word_.fixIfBroken())
562 // 4) or the remembered position was "broken"
563 clearNewWordPosition();
565 FontSpan nw = locateWord(WHOLE_WORD);
567 FontSpan ow = new_word_.locateWord(WHOLE_WORD);
568 if (nw.intersect(ow).empty())
569 clearNewWordPosition();
571 LYXERR(Debug::DEBUG, "new word: "
573 << " pos: " << nw.first << ".." << nw.last);
575 clearNewWordPosition();
582 bool Cursor::posBackward()
591 bool Cursor::posForward()
593 if (pos() == lastpos())
600 bool Cursor::posVisRight(bool skip_inset)
602 Cursor new_cur = *this; // where we will move to
603 pos_type left_pos; // position visually left of current cursor
604 pos_type right_pos; // position visually right of current cursor
605 bool new_pos_is_RTL; // is new position we're moving to RTL?
607 getSurroundingPos(left_pos, right_pos);
609 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
611 // Are we at an inset?
612 new_cur.pos() = right_pos;
613 new_cur.boundary(false);
615 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
616 // we actually move the cursor at the end of this function, for now
617 // we just keep track of the new position in new_cur...
618 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
621 // Are we already at rightmost pos in row?
622 else if (text()->empty() || right_pos == -1) {
625 if (!new_cur.posVisToNewRow(false)) {
626 LYXERR(Debug::RTL, "not moving!");
630 // we actually move the cursor at the end of this function, for now
631 // just keep track of the new position in new_cur...
632 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
633 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
636 // normal movement to the right
639 // Recall, if the cursor is at position 'x', that means *before*
640 // the character at position 'x'. In RTL, "before" means "to the
641 // right of", in LTR, "to the left of". So currently our situation
642 // is this: the position to our right is 'right_pos' (i.e., we're
643 // currently to the left of 'right_pos'). In order to move to the
644 // right, it depends whether or not the character at 'right_pos' is RTL.
645 new_pos_is_RTL = paragraph().getFontSettings(
646 buffer()->params(), right_pos).isVisibleRightToLeft();
647 // If the character at 'right_pos' *is* LTR, then in order to move to
648 // the right of it, we need to be *after* 'right_pos', i.e., move to
649 // position 'right_pos' + 1.
650 if (!new_pos_is_RTL) {
651 new_cur.pos() = right_pos + 1;
652 // set the boundary to true in two situations:
654 // 1. if new_pos is now lastpos, and we're in an RTL paragraph
655 // (this means that we're moving right to the end of an LTR chunk
656 // which is at the end of an RTL paragraph);
657 (new_cur.pos() == lastpos()
658 && paragraph().isRTL(buffer()->params()))
659 // 2. if the position *after* right_pos is RTL (we want to be
660 // *after* right_pos, not before right_pos + 1!)
661 || paragraph().getFontSettings(buffer()->params(),
662 new_cur.pos()).isVisibleRightToLeft()
664 new_cur.boundary(true);
665 else // set the boundary to false
666 new_cur.boundary(false);
668 // Otherwise (if the character at position 'right_pos' is RTL), then
669 // moving to the right of it is as easy as setting the new position
672 new_cur.pos() = right_pos;
673 new_cur.boundary(false);
678 bool moved = (new_cur.pos() != pos()
679 || new_cur.pit() != pit()
680 || new_cur.boundary() != boundary()
681 || &new_cur.inset() != &inset());
684 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
685 << (new_cur.boundary() ? " (boundary)" : ""));
693 bool Cursor::posVisLeft(bool skip_inset)
695 Cursor new_cur = *this; // where we will move to
696 pos_type left_pos; // position visually left of current cursor
697 pos_type right_pos; // position visually right of current cursor
698 bool new_pos_is_RTL; // is new position we're moving to RTL?
700 getSurroundingPos(left_pos, right_pos);
702 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
704 // Are we at an inset?
705 new_cur.pos() = left_pos;
706 new_cur.boundary(false);
708 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
709 // we actually move the cursor at the end of this function, for now
710 // we just keep track of the new position in new_cur...
711 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
714 // Are we already at leftmost pos in row?
715 else if (text()->empty() || left_pos == -1) {
718 if (!new_cur.posVisToNewRow(true)) {
719 LYXERR(Debug::RTL, "not moving!");
723 // we actually move the cursor at the end of this function, for now
724 // just keep track of the new position in new_cur...
725 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
726 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
729 // normal movement to the left
732 // Recall, if the cursor is at position 'x', that means *before*
733 // the character at position 'x'. In RTL, "before" means "to the
734 // right of", in LTR, "to the left of". So currently our situation
735 // is this: the position to our left is 'left_pos' (i.e., we're
736 // currently to the right of 'left_pos'). In order to move to the
737 // left, it depends whether or not the character at 'left_pos' is RTL.
738 new_pos_is_RTL = paragraph().getFontSettings(
739 buffer()->params(), left_pos).isVisibleRightToLeft();
740 // If the character at 'left_pos' *is* RTL, then in order to move to
741 // the left of it, we need to be *after* 'left_pos', i.e., move to
742 // position 'left_pos' + 1.
743 if (new_pos_is_RTL) {
744 new_cur.pos() = left_pos + 1;
745 // set the boundary to true in two situations:
747 // 1. if new_pos is now lastpos and we're in an LTR paragraph
748 // (this means that we're moving left to the end of an RTL chunk
749 // which is at the end of an LTR paragraph);
750 (new_cur.pos() == lastpos()
751 && !paragraph().isRTL(buffer()->params()))
752 // 2. if the position *after* left_pos is not RTL (we want to be
753 // *after* left_pos, not before left_pos + 1!)
754 || !paragraph().getFontSettings(buffer()->params(),
755 new_cur.pos()).isVisibleRightToLeft()
757 new_cur.boundary(true);
758 else // set the boundary to false
759 new_cur.boundary(false);
761 // Otherwise (if the character at position 'left_pos' is LTR), then
762 // moving to the left of it is as easy as setting the new position
765 new_cur.pos() = left_pos;
766 new_cur.boundary(false);
771 bool moved = (new_cur.pos() != pos()
772 || new_cur.pit() != pit()
773 || new_cur.boundary() != boundary());
776 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
777 << (new_cur.boundary() ? " (boundary)" : ""));
785 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos)
787 // preparing bidi tables
788 Paragraph const & par = paragraph();
789 Buffer const & buf = *buffer();
790 Row const & row = textRow();
792 bidi.computeTables(par, buf, row);
794 LYXERR(Debug::RTL, "bidi: " << row.pos() << "--" << row.endpos());
796 // The cursor is painted *before* the character at pos(), or, if 'boundary'
797 // is true, *after* the character at (pos() - 1). So we already have one
798 // known position around the cursor:
799 pos_type const known_pos = boundary() && pos() > 0 ? pos() - 1 : pos();
801 // edge case: if we're at the end of the paragraph, things are a little
802 // different (because lastpos is a position which does not really "exist"
803 // --- there's no character there yet).
804 if (known_pos == lastpos()) {
805 if (par.isRTL(buf.params())) {
807 right_pos = bidi.vis2log(row.pos());
811 left_pos = bidi.vis2log(row.endpos() - 1);
816 // Whether 'known_pos' is to the left or to the right of the cursor depends
817 // on whether it is an RTL or LTR character...
818 bool const cur_is_RTL =
819 par.getFontSettings(buf.params(), known_pos).isVisibleRightToLeft();
820 // ... in the following manner:
821 // For an RTL character, "before" means "to the right" and "after" means
822 // "to the left"; and for LTR, it's the reverse. So, 'known_pos' is to the
823 // right of the cursor if (RTL && boundary) or (!RTL && !boundary):
824 bool const known_pos_on_right = cur_is_RTL == boundary();
826 // So we now know one of the positions surrounding the cursor. Let's
827 // determine the other one:
828 if (known_pos_on_right) {
829 right_pos = known_pos;
830 // *visual* position of 'left_pos':
831 pos_type v_left_pos = bidi.log2vis(right_pos) - 1;
832 // If the position we just identified as 'left_pos' is a "skipped
833 // separator" (a separator which is at the logical end of a row,
834 // except for the last row in a paragraph; such separators are not
835 // painted, so they "are not really there"; note that in bidi text,
836 // such a separator could appear visually in the middle of a row),
837 // set 'left_pos' to the *next* position to the left.
838 if (bidi.inRange(v_left_pos)
839 && bidi.vis2log(v_left_pos) + 1 == row.endpos()
840 && row.endpos() < lastpos()
841 && par.isSeparator(bidi.vis2log(v_left_pos)))
844 // calculate the logical position of 'left_pos', if in row
845 if (!bidi.inRange(v_left_pos))
848 left_pos = bidi.vis2log(v_left_pos);
849 // If the position we identified as 'right_pos' is a "skipped
850 // separator", set 'right_pos' to the *next* position to the right.
851 if (right_pos + 1 == row.endpos() && row.endpos() < lastpos()
852 && par.isSeparator(right_pos)) {
853 pos_type const v_right_pos = bidi.log2vis(right_pos) + 1;
854 if (!bidi.inRange(v_right_pos))
857 right_pos = bidi.vis2log(v_right_pos);
860 // known_pos is on the left
861 left_pos = known_pos;
862 // *visual* position of 'right_pos'
863 pos_type v_right_pos = bidi.log2vis(left_pos) + 1;
864 // If the position we just identified as 'right_pos' is a "skipped
865 // separator", set 'right_pos' to the *next* position to the right.
866 if (bidi.inRange(v_right_pos)
867 && bidi.vis2log(v_right_pos) + 1 == row.endpos()
868 && row.endpos() < lastpos()
869 && par.isSeparator(bidi.vis2log(v_right_pos)))
872 // calculate the logical position of 'right_pos', if in row
873 if (!bidi.inRange(v_right_pos))
876 right_pos = bidi.vis2log(v_right_pos);
877 // If the position we identified as 'left_pos' is a "skipped
878 // separator", set 'left_pos' to the *next* position to the left.
879 if (left_pos + 1 == row.endpos() && row.endpos() < lastpos()
880 && par.isSeparator(left_pos)) {
881 pos_type const v_left_pos = bidi.log2vis(left_pos) - 1;
882 if (!bidi.inRange(v_left_pos))
885 left_pos = bidi.vis2log(v_left_pos);
892 bool Cursor::posVisToNewRow(bool movingLeft)
894 Paragraph const & par = paragraph();
895 Buffer const & buf = *buffer();
896 Row const & row = textRow();
897 bool par_is_LTR = !par.isRTL(buf.params());
899 // Inside a table, determining whether to move to the next or previous row
900 // should be done based on the table's direction.
902 if (s >= 1 && (*this)[s].inset().asInsetTabular()) {
903 par_is_LTR = !(*this)[s].inset().asInsetTabular()->isRightToLeft(*this);
904 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
907 // if moving left in an LTR paragraph or moving right in an RTL one,
908 // move to previous row
909 if (par_is_LTR == movingLeft) {
910 if (row.pos() == 0) { // we're at first row in paragraph
911 if (pit() == 0) // no previous paragraph! don't move
913 // move to last pos in previous par
917 } else { // move to previous row in this par
918 pos() = row.pos() - 1; // this is guaranteed to be in previous row
922 // if moving left in an RTL paragraph or moving right in an LTR one,
925 if (row.endpos() == lastpos()) { // we're at last row in paragraph
926 if (pit() == lastpit()) // last paragraph! don't move
928 // move to first row in next par
932 } else { // move to next row in this par
933 pos() = row.endpos();
938 // make sure we're at left-/right-most pos in new row
939 posVisToRowExtremity(!movingLeft);
945 void Cursor::posVisToRowExtremity(bool left)
947 // prepare bidi tables
948 Paragraph const & par = paragraph();
949 Buffer const & buf = *buffer();
950 Row const & row = textRow();
952 bidi.computeTables(par, buf, row);
954 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
955 << (boundary() ? 1 : 0));
957 if (left) { // move to leftmost position
958 // if this is an RTL paragraph, and we're at the last row in the
959 // paragraph, move to lastpos
960 if (par.isRTL(buf.params()) && row.endpos() == lastpos())
963 pos() = bidi.vis2log(row.pos());
965 // Moving to the leftmost position in the row, the cursor should
966 // normally be placed to the *left* of the leftmost position.
967 // A very common exception, though, is if the leftmost character
968 // also happens to be the separator at the (logical) end of the row
969 // --- in this case, the separator is positioned beyond the left
970 // margin, and we don't want to move the cursor there (moving to
971 // the left of the separator is equivalent to moving to the next
972 // line). So, in this case we actually want to place the cursor
973 // to the *right* of the leftmost position (the separator).
974 // Another exception is if we're moving to the logically last
975 // position in the row, which is *not* a separator: this means
976 // that the entire row has no separators (if there were any, the
977 // row would have been broken there); and therefore in this case
978 // we also move to the *right* of the last position (this indicates
979 // to the user that there is no space after this position, and is
980 // consistent with the behavior in the middle of a row --- moving
981 // right or left moves to the next/previous character; if we were
982 // to move to the *left* of this position, that would simulate
983 // a separator which is not really there!).
984 // Finally, there is an exception to the previous exception: if
985 // this non-separator-but-last-position-in-row is an inset, then
986 // we *do* want to stay to the left of it anyway: this is the
987 // "boundary" which we simulate at insets.
988 // Another exception is when row.endpos() is 0.
990 // do we want to be to the right of pos?
991 // as explained above, if at last pos in row, stay to the right
992 bool const right_of_pos = row.endpos() > 0
993 && pos() == row.endpos() - 1 && !par.isInset(pos());
995 // Now we know if we want to be to the left or to the right of pos,
996 // let's make sure we are where we want to be.
997 bool const new_pos_is_RTL =
998 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
1000 if (new_pos_is_RTL != right_of_pos) {
1006 // move to rightmost position
1007 // if this is an LTR paragraph, and we're at the last row in the
1008 // paragraph, move to lastpos
1009 if (!par.isRTL(buf.params()) && row.endpos() == lastpos())
1012 pos() = row.endpos() > 0 ? bidi.vis2log(row.endpos() - 1) : 0;
1014 // Moving to the rightmost position in the row, the cursor should
1015 // normally be placed to the *right* of the rightmost position.
1016 // A very common exception, though, is if the rightmost character
1017 // also happens to be the separator at the (logical) end of the row
1018 // --- in this case, the separator is positioned beyond the right
1019 // margin, and we don't want to move the cursor there (moving to
1020 // the right of the separator is equivalent to moving to the next
1021 // line). So, in this case we actually want to place the cursor
1022 // to the *left* of the rightmost position (the separator).
1023 // Another exception is if we're moving to the logically last
1024 // position in the row, which is *not* a separator: this means
1025 // that the entire row has no separators (if there were any, the
1026 // row would have been broken there); and therefore in this case
1027 // we also move to the *left* of the last position (this indicates
1028 // to the user that there is no space after this position, and is
1029 // consistent with the behavior in the middle of a row --- moving
1030 // right or left moves to the next/previous character; if we were
1031 // to move to the *right* of this position, that would simulate
1032 // a separator which is not really there!).
1033 // Finally, there is an exception to the previous exception: if
1034 // this non-separator-but-last-position-in-row is an inset, then
1035 // we *do* want to stay to the right of it anyway: this is the
1036 // "boundary" which we simulate at insets.
1037 // Another exception is when row.endpos() is 0.
1039 // do we want to be to the left of pos?
1040 // as explained above, if at last pos in row, stay to the left,
1041 // unless the last position is the same as the first.
1042 bool const left_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 == left_of_pos) {
1056 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
1057 << (boundary() ? 1 : 0));
1061 CursorSlice Cursor::normalAnchor() const
1065 LASSERT(anchor_.depth() >= depth(), /**/);
1066 CursorSlice normal = anchor_[depth() - 1];
1067 if (depth() < anchor_.depth() && top() <= normal) {
1068 // anchor is behind cursor -> move anchor behind the inset
1075 DocIterator & Cursor::realAnchor()
1081 CursorSlice Cursor::selBegin() const
1085 return normalAnchor() < top() ? normalAnchor() : top();
1089 CursorSlice Cursor::selEnd() const
1093 return normalAnchor() > top() ? normalAnchor() : top();
1097 DocIterator Cursor::selectionBegin() const
1103 // FIXME: This is a work-around for the problem that
1104 // CursorSlice doesn't keep track of the boundary.
1105 if (normalAnchor() == top())
1106 di = anchor_.boundary() > boundary() ? anchor_ : *this;
1108 di = normalAnchor() < top() ? anchor_ : *this;
1114 DocIterator Cursor::selectionEnd() const
1120 // FIXME: This is a work-around for the problem that
1121 // CursorSlice doesn't keep track of the boundary.
1122 if (normalAnchor() == top())
1123 di = anchor_.boundary() < boundary() ? anchor_ : *this;
1125 di = normalAnchor() > top() ? anchor_ : *this;
1127 if (di.depth() > depth()) {
1135 void Cursor::setSelection()
1138 // A selection with no contents is not a selection
1139 // FIXME: doesnt look ok
1140 if (idx() == normalAnchor().idx() &&
1141 pit() == normalAnchor().pit() &&
1142 pos() == normalAnchor().pos())
1143 setSelection(false);
1147 void Cursor::setSelection(DocIterator const & where, int n)
1156 void Cursor::clearSelection()
1158 setSelection(false);
1159 setWordSelection(false);
1165 void Cursor::setTargetX(int x)
1168 textTargetOffset_ = 0;
1172 int Cursor::x_target() const
1178 void Cursor::clearTargetX()
1181 textTargetOffset_ = 0;
1185 void Cursor::updateTextTargetOffset()
1190 textTargetOffset_ = x - x_target_;
1194 void Cursor::info(odocstream & os) const
1196 for (int i = 1, n = depth(); i < n; ++i) {
1197 operator[](i).inset().infoize(os);
1201 Inset const * inset = prevInset();
1202 // prevInset() can return 0 in certain case.
1204 prevInset()->infoize2(os);
1206 // overwite old message
1211 bool Cursor::selHandle(bool sel)
1213 //lyxerr << "Cursor::selHandle" << endl;
1216 if (sel == selection())
1220 cap::saveSelection(*this);
1228 ostream & operator<<(ostream & os, Cursor const & cur)
1230 os << "\n cursor: | anchor:\n";
1231 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
1232 os << " " << cur[i] << " | ";
1233 if (i < cur.anchor_.depth())
1234 os << cur.anchor_[i];
1236 os << "-------------------------------";
1239 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
1240 os << "------------------------------- | " << cur.anchor_[i] << "\n";
1242 os << " selection: " << cur.selection_
1243 << " x_target: " << cur.x_target_ << endl;
1248 LyXErr & operator<<(LyXErr & os, Cursor const & cur)
1258 ///////////////////////////////////////////////////////////////////
1261 // The part below is the non-integrated rest of the original math
1262 // cursor. This should be either generalized for texted or moved
1263 // back to mathed (in most cases to InsetMathNest).
1265 ///////////////////////////////////////////////////////////////////
1267 #include "mathed/InsetMathChar.h"
1268 #include "mathed/InsetMathGrid.h"
1269 #include "mathed/InsetMathScript.h"
1270 #include "mathed/InsetMathUnknown.h"
1271 #include "mathed/MathFactory.h"
1272 #include "mathed/MathStream.h"
1273 #include "mathed/MathSupport.h"
1278 bool Cursor::isInside(Inset const * p) const
1280 for (size_t i = 0; i != depth(); ++i)
1281 if (&operator[](i).inset() == p)
1287 void Cursor::leaveInset(Inset const & inset)
1289 for (size_t i = 0; i != depth(); ++i) {
1290 if (&operator[](i).inset() == &inset) {
1298 bool Cursor::openable(MathAtom const & t) const
1309 // we can't move into anything new during selection
1310 if (depth() >= anchor_.depth())
1312 if (t.nucleus() != &anchor_[depth()].inset())
1319 void Cursor::setScreenPos(int x, int /*y*/)
1322 //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
1327 void Cursor::plainErase()
1329 cell().erase(pos());
1333 void Cursor::markInsert()
1335 insert(char_type(0));
1339 void Cursor::markErase()
1341 cell().erase(pos());
1345 void Cursor::plainInsert(MathAtom const & t)
1347 cell().insert(pos(), t);
1349 inset().setBuffer(bv_->buffer());
1351 forceBufferUpdate();
1355 void Cursor::insert(docstring const & str)
1357 for_each(str.begin(), str.end(),
1358 bind(static_cast<void(Cursor::*)(char_type)>
1359 (&Cursor::insert), this, _1));
1363 void Cursor::insert(char_type c)
1365 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1366 LASSERT(!empty(), /**/);
1368 cap::selClearOrDel(*this);
1369 insert(new InsetMathChar(c));
1371 text()->insertChar(*this, c);
1376 void Cursor::insert(MathAtom const & t)
1378 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1380 cap::selClearOrDel(*this);
1385 void Cursor::insert(Inset * inset0)
1387 LASSERT(inset0, /**/);
1389 insert(MathAtom(inset0->asInsetMath()));
1391 text()->insertInset(*this, inset0);
1392 inset0->setBuffer(bv_->buffer());
1394 if (inset0->isLabeled())
1395 forceBufferUpdate();
1400 int Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1402 MathData ar(buffer());
1404 if (ar.size() == 1 && (enter || selection()))
1412 void Cursor::niceInsert(MathAtom const & t)
1415 docstring const safe = cap::grabAndEraseSelection(*this);
1417 // If possible, enter the new inset and move the contents of the selection
1418 if (t->isActive()) {
1420 // be careful here: don't use 'pushBackward(t)' as this we need to
1421 // push the clone, not the original
1422 pushBackward(*nextInset());
1423 // We may not use niceInsert here (recursion)
1424 MathData ar(buffer());
1427 } else if (t->asMacro() && !safe.empty()) {
1428 MathData ar(buffer());
1430 docstring const name = t->asMacro()->name();
1431 MacroData const * data = buffer()->getMacro(name);
1432 if (data && data->numargs() - data->optionals() > 0) {
1433 plainInsert(MathAtom(new InsetMathBrace(ar)));
1440 void Cursor::insert(MathData const & ar)
1444 cap::eraseSelection(*this);
1445 cell().insert(pos(), ar);
1447 // FIXME audit setBuffer calls
1448 inset().setBuffer(bv_->buffer());
1452 bool Cursor::backspace()
1454 autocorrect() = false;
1457 cap::eraseSelection(*this);
1462 // If empty cell, and not part of a big cell
1463 if (lastpos() == 0 && inset().nargs() == 1) {
1465 // Directly delete empty cell: [|[]] => [|]
1471 // [|], can not delete from inside
1482 if (inMacroMode()) {
1483 InsetMathUnknown * p = activeMacro();
1484 if (p->name().size() > 1) {
1485 p->setName(p->name().substr(0, p->name().size() - 1));
1490 if (pos() != 0 && prevAtom()->nargs() > 0) {
1491 // let's require two backspaces for 'big stuff' and
1492 // highlight on the first
1504 bool Cursor::erase()
1506 autocorrect() = false;
1511 cap::eraseSelection(*this);
1515 // delete empty cells if possible
1516 if (pos() == lastpos() && inset().idxDelete(idx()))
1519 // special behaviour when in last position of cell
1520 if (pos() == lastpos()) {
1521 bool one_cell = inset().nargs() == 1;
1522 if (one_cell && lastpos() == 0) {
1524 // Directly delete empty cell: [|[]] => [|]
1530 // [|], can not delete from inside
1535 inset().idxGlue(idx());
1539 // 'clever' UI hack: only erase large items if previously slected
1540 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
1555 DocIterator save = *this;
1556 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1557 this->dispatch(cmd);
1558 if (disp_.dispatched())
1561 autocorrect() = false;
1569 DocIterator save = *this;
1570 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1571 this->dispatch(cmd);
1572 if (disp_.dispatched())
1575 autocorrect() = false;
1580 bool Cursor::macroModeClose()
1584 InsetMathUnknown * p = activeMacro();
1586 MathData selection(buffer());
1587 asArray(p->selection(), selection);
1588 docstring const s = p->name();
1590 cell().erase(pos());
1592 // do nothing if the macro name is empty
1596 // trigger updates of macros, at least, if no full
1597 // updates take place anyway
1598 screenUpdateFlags(Update::Force);
1600 docstring const name = s.substr(1);
1601 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1602 if (in && in->interpretString(*this, s))
1604 MathAtom atom = buffer()->getMacro(name, *this, false) ?
1605 MathAtom(new MathMacro(buffer(), name)) : createInsetMath(name, buffer());
1607 // try to put argument into macro, if we just inserted a macro
1608 bool macroArg = false;
1609 MathMacro * atomAsMacro = atom.nucleus()->asMacro();
1611 // macros here are still unfolded (in init mode in fact). So
1612 // we have to resolve the macro here manually and check its arity
1613 // to put the selection behind it if arity > 0.
1614 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1615 if (selection.size() > 0 && data && data->numargs() - data->optionals() > 0) {
1617 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1619 // non-greedy case. Do not touch the arguments behind
1620 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1623 // insert remembered selection into first argument of a non-macro
1624 else if (atom.nucleus()->nargs() > 0)
1625 atom.nucleus()->cell(0).append(selection);
1629 // finally put the macro argument behind, if needed
1631 if (selection.size() > 1 || selection[0]->asScriptInset())
1632 plainInsert(MathAtom(new InsetMathBrace(selection)));
1641 docstring Cursor::macroName()
1643 return inMacroMode() ? activeMacro()->name() : docstring();
1647 void Cursor::handleNest(MathAtom const & a, int c)
1649 //lyxerr << "Cursor::handleNest: " << c << endl;
1651 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1654 pushBackward(*nextInset());
1658 int Cursor::targetX() const
1660 if (x_target() != -1)
1669 int Cursor::textTargetOffset() const
1671 return textTargetOffset_;
1675 void Cursor::setTargetX()
1684 bool Cursor::inMacroMode() const
1688 if (pos() == 0 || cell().empty())
1690 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1691 return p && !p->final();
1695 InsetMathUnknown * Cursor::activeMacro()
1697 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1701 InsetMathUnknown const * Cursor::activeMacro() const
1703 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1707 void Cursor::pullArg()
1710 MathData ar = cell();
1711 if (popBackward() && inMathed()) {
1713 cell().insert(pos(), ar);
1716 //formula()->mutateToText();
1721 void Cursor::touch()
1725 DocIterator::const_iterator it = begin();
1726 DocIterator::const_iterator et = end();
1727 for ( ; it != et; ++it)
1733 void Cursor::normalize()
1735 if (idx() > lastidx()) {
1736 lyxerr << "this should not really happen - 1: "
1737 << idx() << ' ' << nargs()
1738 << " in: " << &inset() << endl;
1742 if (pos() > lastpos()) {
1743 lyxerr << "this should not really happen - 2: "
1744 << pos() << ' ' << lastpos() << " in idx: " << idx()
1746 odocstringstream os;
1747 WriteStream wi(os, false, true, WriteStream::wsDefault);
1748 inset().asInsetMath()->write(wi);
1749 lyxerr << to_utf8(os.str()) << endl;
1755 bool Cursor::upDownInMath(bool up)
1757 // Be warned: The 'logic' implemented in this function is highly
1758 // fragile. A distance of one pixel or a '<' vs '<=' _really
1759 // matters. So fiddle around with it only if you think you know
1760 // what you are doing!
1764 xo = beforeDispatchPosX_;
1766 // check if we had something else in mind, if not, this is the future
1768 if (x_target_ == -1)
1770 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1771 // In text mode inside the line (not left or right) possibly set a new target_x,
1772 // but only if we are somewhere else than the previous target-offset.
1774 // We want to keep the x-target on subsequent up/down movements
1775 // that cross beyond the end of short lines. Thus a special
1776 // handling when the cursor is at the end of line: Use the new
1777 // x-target only if the old one was before the end of line
1778 // or the old one was after the beginning of the line
1779 bool inRTL = isWithinRtlParagraph(*this);
1783 left = pos() == textRow().endpos();
1784 right = pos() == textRow().pos();
1786 left = pos() == textRow().pos();
1787 right = pos() == textRow().endpos();
1789 if ((!left && !right) ||
1790 (left && !right && xo < x_target_) ||
1791 (!left && right && x_target_ < xo))
1798 // try neigbouring script insets
1800 if (inMathed() && !selection()) {
1803 InsetMathScript const * p = prevAtom()->asScriptInset();
1804 if (p && p->has(up)) {
1806 push(*const_cast<InsetMathScript*>(p));
1807 idx() = p->idxOfScript(up);
1810 // we went in the right direction? Otherwise don't jump into the script
1814 int oy = beforeDispatchPosY_;
1815 if ((!up && y <= oy) ||
1824 if (pos() != lastpos()) {
1825 InsetMathScript const * p = nextAtom()->asScriptInset();
1826 if (p && p->has(up)) {
1827 push(*const_cast<InsetMathScript*>(p));
1828 idx() = p->idxOfScript(up);
1831 // we went in the right direction? Otherwise don't jump into the script
1835 int oy = beforeDispatchPosY_;
1836 if ((!up && y <= oy) ||
1845 // try to find an inset that knows better then we,
1846 if (inset().idxUpDown(*this, up)) {
1847 //lyxerr << "idxUpDown triggered" << endl;
1848 // try to find best position within this inset
1850 setCursor(bruteFind2(*this, xo, yo));
1854 // any improvement going just out of inset?
1855 if (popBackward() && inMathed()) {
1856 //lyxerr << "updown: popBackward succeeded" << endl;
1859 int yold = beforeDispatchPosY_;
1861 if (up ? ynew < yold : ynew > yold)
1865 // no success, we are probably at the document top or bottom
1871 bool Cursor::atFirstOrLastRow(bool up)
1873 TextMetrics const & tm = bv_->textMetrics(text());
1874 ParagraphMetrics const & pm = tm.parMetrics(pit());
1877 if (pos() && boundary())
1878 row = pm.pos2row(pos() - 1);
1880 row = pm.pos2row(pos());
1883 if (pit() == 0 && row == 0)
1886 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1887 row + 1 >= int(pm.rows().size()))
1893 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1895 LASSERT(text(), /**/);
1901 xo = beforeDispatchPosX_;
1903 // update the targetX - this is here before the "return false"
1904 // to set a new target which can be used by InsetTexts above
1905 // if we cannot move up/down inside this inset anymore
1906 if (x_target_ == -1)
1908 else if (xo - textTargetOffset() != x_target() &&
1909 depth() == beforeDispatchCursor_.depth()) {
1910 // In text mode inside the line (not left or right) possibly set a new target_x,
1911 // but only if we are somewhere else than the previous target-offset.
1913 // We want to keep the x-target on subsequent up/down movements
1914 // that cross beyond the end of short lines. Thus a special
1915 // handling when the cursor is at the end of line: Use the new
1916 // x-target only if the old one was before the end of line
1917 // or the old one was after the beginning of the line
1918 bool inRTL = isWithinRtlParagraph(*this);
1922 left = pos() == textRow().endpos();
1923 right = pos() == textRow().pos();
1925 left = pos() == textRow().pos();
1926 right = pos() == textRow().endpos();
1928 if ((!left && !right) ||
1929 (left && !right && xo < x_target_) ||
1930 (!left && right && x_target_ < xo))
1937 // first get the current line
1938 TextMetrics & tm = bv_->textMetrics(text());
1939 ParagraphMetrics const & pm = tm.parMetrics(pit());
1941 if (pos() && boundary())
1942 row = pm.pos2row(pos() - 1);
1944 row = pm.pos2row(pos());
1946 if (atFirstOrLastRow(up)) {
1947 // Is there a place for the cursor to go ? If yes, we
1948 // can execute the DEPM, otherwise we should keep the
1949 // paragraph to host the cursor.
1950 Cursor dummy = *this;
1951 bool valid_destination = false;
1952 for(; dummy.depth(); dummy.pop())
1953 if (!dummy.atFirstOrLastRow(up)) {
1954 valid_destination = true;
1958 // will a next dispatch follow and if there is a new
1959 // dispatch will it move the cursor out ?
1960 if (depth() > 1 && valid_destination) {
1961 // The cursor hasn't changed yet. This happens when
1962 // you e.g. move out of an inset. And to give the
1963 // DEPM the possibility of doing something we must
1964 // provide it with two different cursors. (Lgb, vfr)
1966 dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
1967 dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
1969 updateNeeded |= bv().checkDepm(dummy, *this);
1970 updateTextTargetOffset();
1972 forceBufferUpdate();
1977 // with and without selection are handled differently
1979 int yo = bv().getPos(*this).y_;
1981 // To next/previous row
1983 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1985 tm.editXY(*this, xo, yo + textRow().descent() + 1);
1988 // This happens when you move out of an inset.
1989 // And to give the DEPM the possibility of doing
1990 // something we must provide it with two different
1992 Cursor dummy = *this;
1995 if (bv().checkDepm(dummy, old)) {
1996 updateNeeded = true;
1997 // Make sure that cur gets back whatever happened to dummy (Lgb)
2001 // if there is a selection, we stay out of any inset,
2002 // and just jump to the right position:
2008 } else if (pit() > 0) {
2010 TextMetrics & tm = bv_->textMetrics(text());
2011 if (!tm.contains(pit()))
2012 tm.newParMetricsUp();
2013 ParagraphMetrics const & pmcur = tm.parMetrics(pit());
2014 next_row = pmcur.rows().size() - 1;
2017 if (row + 1 < int(pm.rows().size())) {
2019 } else if (pit() + 1 < int(text()->paragraphs().size())) {
2021 TextMetrics & tm = bv_->textMetrics(text());
2022 if (!tm.contains(pit()))
2023 tm.newParMetricsDown();
2027 top().pos() = min(tm.x2pos(pit(), next_row, xo), top().lastpos());
2029 int const xpos = tm.x2pos(pit(), next_row, xo);
2030 bool const at_end_row = xpos == tm.x2pos(pit(), next_row, tm.width());
2031 bool const at_beg_row = xpos == tm.x2pos(pit(), next_row, 0);
2033 if (at_end_row && at_beg_row)
2034 // make sure the cursor ends up on this row
2037 boundary(at_end_row);
2039 updateNeeded |= bv().checkDepm(*this, old);
2043 forceBufferUpdate();
2044 updateTextTargetOffset();
2049 void Cursor::handleFont(string const & font)
2051 LYXERR(Debug::DEBUG, font);
2055 safe = cap::grabAndEraseSelection(*this);
2060 if (lastpos() != 0) {
2061 // something left in the cell
2063 // cursor in first position
2065 } else if (pos() == lastpos()) {
2066 // cursor in last position
2069 // cursor in between. split cell
2070 MathData::iterator bt = cell().begin();
2071 MathAtom at = createInsetMath(from_utf8(font), buffer());
2072 at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
2073 cell().erase(bt, bt + pos());
2078 // nothing left in the cell
2087 void Cursor::message(docstring const & msg) const
2089 disp_.setMessage(msg);
2093 void Cursor::errorMessage(docstring const & msg) const
2095 disp_.setMessage(msg);
2096 disp_.setError(true);
2101 docstring parbreak(Cursor const * cur)
2103 odocstringstream os;
2105 // only add blank line if we're not in a ParbreakIsNewline situation
2106 if (!cur->inset().getLayout().parbreakIsNewline()
2107 && !cur->paragraph().layout().parbreak_is_newline)
2114 docstring Cursor::selectionAsString(bool with_label) const
2120 return cap::grabSelection(*this);
2122 int const label = with_label
2123 ? AS_STR_LABEL | AS_STR_INSETS : AS_STR_INSETS;
2125 idx_type const startidx = selBegin().idx();
2126 idx_type const endidx = selEnd().idx();
2127 if (startidx != endidx) {
2128 // multicell selection
2129 InsetTabular * table = inset().asInsetTabular();
2130 LASSERT(table, return docstring());
2131 return table->asString(startidx, endidx);
2134 ParagraphList const & pars = text()->paragraphs();
2136 pit_type const startpit = selBegin().pit();
2137 pit_type const endpit = selEnd().pit();
2138 size_t const startpos = selBegin().pos();
2139 size_t const endpos = selEnd().pos();
2141 if (startpit == endpit)
2142 return pars[startpit].asString(startpos, endpos, label);
2144 // First paragraph in selection
2145 docstring result = pars[startpit].
2146 asString(startpos, pars[startpit].size(), label)
2149 // The paragraphs in between (if any)
2150 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
2151 Paragraph const & par = pars[pit];
2152 result += par.asString(0, par.size(), label)
2156 // Last paragraph in selection
2157 result += pars[endpit].asString(0, endpos, label);
2163 docstring Cursor::currentState() const
2166 odocstringstream os;
2172 return text()->currentState(*this);
2178 docstring Cursor::getPossibleLabel() const
2180 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
2184 Encoding const * Cursor::getEncoding() const
2188 CursorSlice const & sl = innerTextSlice();
2189 Text const & text = *sl.text();
2190 Font font = text.getPar(sl.pit()).getFont(
2191 bv().buffer().params(), sl.pos(), text.outerFont(sl.pit()));
2192 return font.language()->encoding();
2196 void Cursor::undispatched() const
2198 disp_.dispatched(false);
2202 void Cursor::dispatched() const
2204 disp_.dispatched(true);
2208 void Cursor::screenUpdateFlags(Update::flags f) const
2210 disp_.screenUpdate(f);
2214 void Cursor::forceBufferUpdate() const
2216 disp_.forceBufferUpdate();
2220 void Cursor::clearBufferUpdate() const
2222 disp_.clearBufferUpdate();
2226 bool Cursor::needBufferUpdate() const
2228 return disp_.needBufferUpdate();
2232 void Cursor::noScreenUpdate() const
2234 disp_.screenUpdate(Update::None);
2238 Font Cursor::getFont() const
2240 // The logic here should more or less match to the Cursor::setCurrentFont
2241 // logic, i.e. the cursor height should give a hint what will happen
2242 // if a character is entered.
2244 // HACK. far from being perfect...
2246 CursorSlice const & sl = innerTextSlice();
2247 Text const & text = *sl.text();
2248 Paragraph const & par = text.getPar(sl.pit());
2250 // on boundary, so we are really at the character before
2251 pos_type pos = sl.pos();
2252 if (pos > 0 && boundary())
2255 // on space? Take the font before (only for RTL boundary stay)
2257 TextMetrics const & tm = bv().textMetrics(&text);
2258 if (pos == sl.lastpos()
2259 || (par.isSeparator(pos)
2260 && !tm.isRTLBoundary(sl.pit(), pos)))
2264 // get font at the position
2265 Font font = par.getFont(buffer()->params(), pos,
2266 text.outerFont(sl.pit()));
2272 bool Cursor::fixIfBroken()
2274 bool const broken_cursor = DocIterator::fixIfBroken();
2275 bool const broken_anchor = anchor_.fixIfBroken();
2277 if (broken_cursor || broken_anchor) {
2278 clearNewWordPosition();
2286 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2288 // find inset in common
2290 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2291 if (&old[i].inset() != &cur[i].inset())
2295 // update words if we just moved to another paragraph
2296 if (i == old.depth() && i == cur.depth()
2297 && !cur.buffer()->isClean()
2298 && cur.inTexted() && old.inTexted()
2299 && cur.pit() != old.pit()) {
2300 old.paragraph().updateWords();
2303 // notify everything on top of the common part in old cursor,
2304 // but stop if the inset claims the cursor to be invalid now
2305 for (size_type j = i; j < old.depth(); ++j) {
2306 Cursor inset_pos = old;
2307 inset_pos.cutOff(j);
2308 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2312 // notify everything on top of the common part in new cursor,
2313 // but stop if the inset claims the cursor to be invalid now
2314 for (; i < cur.depth(); ++i) {
2315 if (cur[i].inset().notifyCursorEnters(cur))
2323 void Cursor::setCurrentFont()
2325 CursorSlice const & cs = innerTextSlice();
2326 Paragraph const & par = cs.paragraph();
2327 pos_type cpit = cs.pit();
2328 pos_type cpos = cs.pos();
2329 Text const & ctext = *cs.text();
2330 TextMetrics const & tm = bv().textMetrics(&ctext);
2332 // are we behind previous char in fact? -> go to that char
2333 if (cpos > 0 && boundary())
2336 // find position to take the font from
2338 // paragraph end? -> font of last char
2339 if (cpos == lastpos())
2341 // on space? -> look at the words in front of space
2342 else if (cpos > 0 && par.isSeparator(cpos)) {
2343 // abc| def -> font of c
2344 // abc |[WERBEH], i.e. boundary==true -> font of c
2345 // abc [WERBEH]| def, font of the space
2346 if (!tm.isRTLBoundary(cpit, cpos))
2352 BufferParams const & bufparams = buffer()->params();
2353 current_font = par.getFontSettings(bufparams, cpos);
2354 real_current_font = tm.displayFont(cpit, cpos);
2356 // special case for paragraph end
2357 if (cs.pos() == lastpos()
2358 && tm.isRTLBoundary(cpit, cs.pos())
2360 Language const * lang = par.getParLanguage(bufparams);
2361 current_font.setLanguage(lang);
2362 current_font.fontInfo().setNumber(FONT_OFF);
2363 real_current_font.setLanguage(lang);
2364 real_current_font.fontInfo().setNumber(FONT_OFF);
2369 bool Cursor::textUndo()
2371 DocIterator dit = *this;
2372 // Undo::textUndo() will modify dit.
2373 if (!buffer()->undo().textUndo(dit))
2383 bool Cursor::textRedo()
2385 DocIterator dit = *this;
2386 // Undo::textRedo() will modify dit.
2387 if (!buffer()->undo().textRedo(dit))
2397 void Cursor::finishUndo() const
2399 buffer()->undo().finishUndo();
2403 void Cursor::beginUndoGroup() const
2405 buffer()->undo().beginUndoGroup();
2409 void Cursor::endUndoGroup() const
2411 buffer()->undo().endUndoGroup();
2415 void Cursor::recordUndo(UndoKind kind, pit_type from, pit_type to) const
2417 buffer()->undo().recordUndo(*this, kind, from, to);
2421 void Cursor::recordUndo(UndoKind kind, pit_type from) const
2423 buffer()->undo().recordUndo(*this, kind, from);
2427 void Cursor::recordUndo(UndoKind kind) const
2429 buffer()->undo().recordUndo(*this, kind);
2433 void Cursor::recordUndoInset(UndoKind kind, Inset const * inset) const
2435 buffer()->undo().recordUndoInset(*this, kind, inset);
2439 void Cursor::recordUndoFullDocument() const
2441 buffer()->undo().recordUndoFullDocument(*this);
2445 void Cursor::recordUndoSelection() const
2448 if (cap::multipleCellsSelected(*this))
2453 buffer()->undo().recordUndo(*this, ATOMIC_UNDO,
2454 selBegin().pit(), selEnd().pit());
2459 void Cursor::checkBufferStructure()
2461 Buffer const * master = buffer()->masterBuffer();
2462 master->tocBackend().updateItem(*this);
2463 if (master != buffer() && !master->hasGuiDelegate())
2464 // In case the master has no gui associated with it,
2465 // the TocItem is not updated (part of bug 5699).
2466 buffer()->tocBackend().updateItem(*this);