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),
244 autocorrect_(false), macromode_(false)
248 CursorData::CursorData(Buffer * buffer)
249 : DocIterator(buffer), anchor_(),
250 selection_(false), mark_(false), word_selection_(false),
251 logicalpos_(false), current_font(inherit_font),
252 autocorrect_(false), macromode_(false)
256 CursorData::CursorData(DocIterator const & dit)
257 : DocIterator(dit), anchor_(),
258 selection_(false), mark_(false), word_selection_(false),
259 logicalpos_(false), current_font(inherit_font),
260 autocorrect_(false), macromode_(false)
264 // be careful: this is called from the bv's constructor, too, so
265 // bv functions are not yet available!
266 Cursor::Cursor(BufferView & bv)
267 : CursorData(&bv.buffer()), bv_(&bv),
268 x_target_(-1), textTargetOffset_(0),
269 beforeDispatchPosX_(0), beforeDispatchPosY_(0)
276 push_back(CursorSlice(buffer()->inset()));
277 anchor_ = doc_iterator_begin(buffer());
279 new_word_ = doc_iterator_begin(buffer());
287 // this (intentionally) does neither touch anchor nor selection status
288 void Cursor::setCursor(DocIterator const & cur)
290 DocIterator::operator=(cur);
294 void Cursor::setCursorToAnchor()
297 DocIterator normal = anchor_;
298 while (depth() < normal.depth())
300 if (depth() < anchor_.depth() && top() <= anchor_[depth() - 1])
307 void Cursor::setCursorData(CursorData const & data)
309 CursorData::operator=(data);
313 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
317 // Try to fix cursor in case it is broken.
320 // Is this a function that acts on inset at point?
321 Inset * inset = cur.nextInset();
322 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
323 && inset && inset->getStatus(cur, cmd, status))
326 // This is, of course, a mess. Better create a new doc iterator and use
327 // this in Inset::getStatus. This might require an additional
328 // BufferView * arg, though (which should be avoided)
329 //Cursor safe = *this;
331 for ( ; cur.depth(); cur.pop()) {
332 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
333 // LASSERT: Is it safe to continue here, or should we return?
334 LASSERT(cur.idx() <= cur.lastidx(), /**/);
335 LASSERT(cur.pit() <= cur.lastpit(), /**/);
336 LASSERT(cur.pos() <= cur.lastpos(), /**/);
338 // The inset's getStatus() will return 'true' if it made
339 // a definitive decision on whether it want to handle the
340 // request or not. The result of this decision is put into
341 // the 'status' parameter.
342 if (cur.inset().getStatus(cur, cmd, status)) {
351 void Cursor::saveBeforeDispatchPosXY()
353 getPos(beforeDispatchPosX_, beforeDispatchPosY_);
357 void Cursor::dispatch(FuncRequest const & cmd0)
359 LYXERR(Debug::DEBUG, "cmd: " << cmd0 << '\n' << *this);
364 FuncRequest cmd = cmd0;
367 disp_ = DispatchResult();
371 // Is this a function that acts on inset at point?
372 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
374 disp_.dispatched(true);
375 disp_.screenUpdate(Update::FitCursor | Update::Force);
376 FuncRequest tmpcmd = cmd;
377 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
378 << cmd0 << endl << *this);
379 nextInset()->dispatch(*this, tmpcmd);
380 if (disp_.dispatched()) {
386 // store some values to be used inside of the handlers
387 beforeDispatchCursor_ = *this;
388 for (; depth(); pop(), boundary(false)) {
389 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
390 << cmd0 << endl << *this);
392 // In any of these cases, the cursor is invalid, and we should
393 // try to save this document rather than crash.
394 LBUFERR(pos() <= lastpos());
395 LBUFERR(idx() <= lastidx());
396 LBUFERR(pit() <= lastpit());
398 // The common case is 'LFUN handled, need update', so make the
399 // LFUN handler's life easier by assuming this as default value.
400 // The handler can reset the update and val flags if necessary.
401 disp_.screenUpdate(Update::FitCursor | Update::Force);
402 disp_.dispatched(true);
403 inset().dispatch(*this, cmd);
404 if (disp_.dispatched())
408 // it completely to get a 'bomb early' behaviour in case this
409 // object will be used again.
410 if (!disp_.dispatched()) {
411 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
412 // We might have invalidated the cursor when removing an empty
413 // paragraph while the cursor could not be moved out the inset
414 // while we initially thought we could. This might happen when
415 // a multiline inset becomes an inline inset when the second
416 // paragraph is removed.
417 if (safe.pit() > safe.lastpit()) {
418 safe.pit() = safe.lastpit();
419 safe.pos() = safe.lastpos();
422 disp_.screenUpdate(Update::None);
423 disp_.dispatched(false);
425 // restore the previous one because nested Cursor::dispatch calls
426 // are possible which would change it
427 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
431 // notify insets we just left
433 old.beginUndoGroup();
435 bool badcursor = notifyCursorLeavesOrEnters(old, *this);
438 bv().resetInlineCompletionPos();
445 DispatchResult const & Cursor::result() const
451 BufferView & Cursor::bv() const
460 LBUFERR(depth() >= 1);
465 void Cursor::push(Inset & p)
467 push_back(CursorSlice(p));
468 p.setBuffer(*buffer());
472 void Cursor::pushBackward(Inset & p)
474 LASSERT(!empty(), return);
475 //lyxerr << "Entering inset " << t << " front" << endl;
481 bool Cursor::popBackward()
483 LASSERT(!empty(), return false);
491 bool Cursor::popForward()
493 LASSERT(!empty(), return false);
494 //lyxerr << "Leaving inset from in back" << endl;
495 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
499 pos() += lastpos() - lp + 1;
504 int Cursor::currentMode()
506 LASSERT(!empty(), return Inset::UNDECIDED_MODE);
507 for (int i = depth() - 1; i >= 0; --i) {
508 int res = operator[](i).inset().currentMode();
509 bool locked_mode = operator[](i).inset().lockedMode();
510 // Also return UNDECIDED_MODE when the mode is locked,
511 // as in this case it is treated the same as TEXT_MODE
512 if (res != Inset::UNDECIDED_MODE || locked_mode)
515 return Inset::TEXT_MODE;
519 void Cursor::getPos(int & x, int & y) const
521 Point p = bv().getPos(*this);
527 Row const & Cursor::textRow() const
529 CursorSlice const & cs = innerTextSlice();
530 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
531 return pm.getRow(pos(), boundary());
535 void Cursor::resetAnchor()
538 checkNewWordPosition();
542 void Cursor::markNewWordPosition()
544 if (lyxrc.spellcheck_continuously && inTexted() && new_word_.empty()) {
545 FontSpan nw = locateWord(WHOLE_WORD);
546 if (nw.size() == 1) {
547 LYXERR(Debug::DEBUG, "start new word: "
549 << " pos: " << nw.first);
556 void Cursor::clearNewWordPosition()
558 if (!new_word_.empty()) {
559 LYXERR(Debug::DEBUG, "clear new word: "
561 << " pos: " << pos());
567 void Cursor::checkNewWordPosition()
569 if (!lyxrc.spellcheck_continuously || new_word_.empty())
572 clearNewWordPosition();
574 // forget the position of the current new word if
575 // 1) the paragraph changes or
576 // 2) the count of nested insets changes or
577 // 3) the cursor pos is out of paragraph bound
578 if (pit() != new_word_.pit() ||
579 depth() != new_word_.depth() ||
580 new_word_.pos() > new_word_.lastpos()) {
581 clearNewWordPosition();
582 } else if (new_word_.fixIfBroken())
583 // 4) or the remembered position was "broken"
584 clearNewWordPosition();
586 FontSpan nw = locateWord(WHOLE_WORD);
588 FontSpan ow = new_word_.locateWord(WHOLE_WORD);
589 if (nw.intersect(ow).empty())
590 clearNewWordPosition();
592 LYXERR(Debug::DEBUG, "new word: "
594 << " pos: " << nw.first << ".." << nw.last);
596 clearNewWordPosition();
603 bool Cursor::posBackward()
612 bool Cursor::posForward()
614 if (pos() == lastpos())
621 bool Cursor::posVisRight(bool skip_inset)
623 Cursor new_cur = *this; // where we will move to
624 pos_type left_pos; // position visually left of current cursor
625 pos_type right_pos; // position visually right of current cursor
627 getSurroundingPos(left_pos, right_pos);
629 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
631 // Are we at an inset?
632 new_cur.pos() = right_pos;
633 new_cur.boundary(false);
635 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
636 // we actually move the cursor at the end of this
637 // function, for now we just keep track of the new
638 // position in new_cur...
639 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
642 // Are we already at rightmost pos in row?
643 else if (text()->empty() || right_pos == -1) {
646 if (!new_cur.posVisToNewRow(false)) {
647 LYXERR(Debug::RTL, "not moving!");
651 // we actually move the cursor at the end of this
652 // function, for now just keep track of the new
653 // position in new_cur...
654 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
655 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
658 // normal movement to the right
661 // Recall, if the cursor is at position 'x', that
662 // means *before* the character at position 'x'. In
663 // RTL, "before" means "to the right of", in LTR, "to
664 // the left of". So currently our situation is this:
665 // the position to our right is 'right_pos' (i.e.,
666 // we're currently to the left of 'right_pos'). In
667 // order to move to the right, it depends whether or
668 // not the character at 'right_pos' is RTL.
669 bool const new_pos_is_RTL = paragraph().getFontSettings(
670 buffer()->params(), right_pos).isVisibleRightToLeft();
671 // If the character at 'right_pos' *is* LTR, then in
672 // order to move to the right of it, we need to be
673 // *after* 'right_pos', i.e., move to position
675 if (!new_pos_is_RTL) {
676 new_cur.pos() = right_pos + 1;
677 // set the boundary to true in two situations:
679 // 1. if new_pos is now lastpos, and we're in
680 // an RTL paragraph (this means that we're
681 // moving right to the end of an LTR chunk
682 // which is at the end of an RTL paragraph);
683 (new_cur.pos() == lastpos()
684 && paragraph().isRTL(buffer()->params()))
685 // 2. if the position *after* right_pos is RTL
686 // (we want to be *after* right_pos, not
687 // before right_pos + 1!)
688 || paragraph().getFontSettings(buffer()->params(),
689 new_cur.pos()).isVisibleRightToLeft()
691 new_cur.boundary(true);
692 else // set the boundary to false
693 new_cur.boundary(false);
695 // Otherwise (if the character at position 'right_pos'
696 // is RTL), then moving to the right of it is as easy
697 // as setting the new position to 'right_pos'.
699 new_cur.pos() = right_pos;
700 new_cur.boundary(false);
705 bool moved = (new_cur.pos() != pos()
706 || new_cur.pit() != pit()
707 || new_cur.boundary() != boundary()
708 || &new_cur.inset() != &inset());
711 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
712 << (new_cur.boundary() ? " (boundary)" : ""));
720 bool Cursor::posVisLeft(bool skip_inset)
722 Cursor new_cur = *this; // where we will move to
723 pos_type left_pos; // position visually left of current cursor
724 pos_type right_pos; // position visually right of current cursor
726 getSurroundingPos(left_pos, right_pos);
728 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
730 // Are we at an inset?
731 new_cur.pos() = left_pos;
732 new_cur.boundary(false);
734 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
735 // we actually move the cursor at the end of this
736 // function, for now we just keep track of the new
737 // position in new_cur...
738 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
741 // Are we already at leftmost pos in row?
742 else if (text()->empty() || left_pos == -1) {
745 if (!new_cur.posVisToNewRow(true)) {
746 LYXERR(Debug::RTL, "not moving!");
750 // we actually move the cursor at the end of this
751 // function, for now just keep track of the new
752 // position in new_cur...
753 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
754 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
757 // normal movement to the left
760 // Recall, if the cursor is at position 'x', that
761 // means *before* the character at position 'x'. In
762 // RTL, "before" means "to the right of", in LTR, "to
763 // the left of". So currently our situation is this:
764 // the position to our left is 'left_pos' (i.e., we're
765 // currently to the right of 'left_pos'). In order to
766 // move to the left, it depends whether or not the
767 // character at 'left_pos' is RTL.
768 bool const new_pos_is_RTL = paragraph().getFontSettings(
769 buffer()->params(), left_pos).isVisibleRightToLeft();
770 // If the character at 'left_pos' *is* RTL, then in
771 // order to move to the left of it, we need to be
772 // *after* 'left_pos', i.e., move to position
774 if (new_pos_is_RTL) {
775 new_cur.pos() = left_pos + 1;
776 // set the boundary to true in two situations:
778 // 1. if new_pos is now lastpos and we're in
779 // an LTR paragraph (this means that we're
780 // moving left to the end of an RTL chunk
781 // which is at the end of an LTR paragraph);
782 (new_cur.pos() == lastpos()
783 && !paragraph().isRTL(buffer()->params()))
784 // 2. if the position *after* left_pos is not
785 // RTL (we want to be *after* left_pos, not
786 // before left_pos + 1!)
787 || !paragraph().getFontSettings(buffer()->params(),
788 new_cur.pos()).isVisibleRightToLeft()
790 new_cur.boundary(true);
791 else // set the boundary to false
792 new_cur.boundary(false);
794 // Otherwise (if the character at position 'left_pos'
795 // is LTR), then moving to the left of it is as easy
796 // as setting the new position to 'left_pos'.
798 new_cur.pos() = left_pos;
799 new_cur.boundary(false);
804 bool moved = (new_cur.pos() != pos()
805 || new_cur.pit() != pit()
806 || new_cur.boundary() != boundary());
809 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
810 << (new_cur.boundary() ? " (boundary)" : ""));
818 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos)
820 // preparing bidi tables
821 Paragraph const & par = paragraph();
822 Buffer const & buf = *buffer();
823 Row const & row = textRow();
825 bidi.computeTables(par, buf, row);
827 LYXERR(Debug::RTL, "bidi: " << row.pos() << "--" << row.endpos());
829 // The cursor is painted *before* the character at pos(), or,
830 // if 'boundary' is true, *after* the character at (pos() -
831 // 1). So we already have one known position around the
833 pos_type const known_pos = boundary() && pos() > 0 ? pos() - 1 : pos();
835 // edge case: if we're at the end of the paragraph, things are
836 // a little different (because lastpos is a position which
837 // does not really "exist" --- there's no character there
839 if (known_pos == lastpos()) {
840 if (par.isRTL(buf.params())) {
842 right_pos = bidi.vis2log(row.pos());
846 left_pos = bidi.vis2log(row.endpos() - 1);
851 // Whether 'known_pos' is to the left or to the right of the
852 // cursor depends on whether it is an RTL or LTR character...
853 bool const cur_is_RTL =
854 par.getFontSettings(buf.params(), known_pos).isVisibleRightToLeft();
855 // ... in the following manner:
856 // For an RTL character, "before"
857 // means "to the right" and "after" means "to the left"; and
858 // for LTR, it's the reverse. So, 'known_pos' is to the right
859 // of the cursor if (RTL && boundary) or (!RTL && !boundary):
860 bool const known_pos_on_right = cur_is_RTL == boundary();
862 // So we now know one of the positions surrounding the cursor.
863 // Let's determine the other one:
864 if (known_pos_on_right) {
865 right_pos = known_pos;
866 // *visual* position of 'left_pos':
867 pos_type v_left_pos = bidi.log2vis(right_pos) - 1;
868 // If the position we just identified as 'left_pos' is
869 // a "skipped separator" (a separator which is at the
870 // logical end of a row, except for the last row in a
871 // paragraph; such separators are not painted, so they
872 // "are not really there"; note that in bidi text,
873 // such a separator could appear visually in the
874 // middle of a row), set 'left_pos' to the *next*
875 // position to the left.
876 if (bidi.inRange(v_left_pos)
877 && bidi.vis2log(v_left_pos) + 1 == row.endpos()
878 && row.endpos() < lastpos()
879 && par.isSeparator(bidi.vis2log(v_left_pos)))
882 // calculate the logical position of 'left_pos', if in row
883 if (!bidi.inRange(v_left_pos))
886 left_pos = bidi.vis2log(v_left_pos);
887 // If the position we identified as 'right_pos' is a
888 // "skipped separator", set 'right_pos' to the *next*
889 // position to the right.
890 if (right_pos + 1 == row.endpos() && row.endpos() < lastpos()
891 && par.isSeparator(right_pos)) {
892 pos_type const v_right_pos = bidi.log2vis(right_pos) + 1;
893 if (!bidi.inRange(v_right_pos))
896 right_pos = bidi.vis2log(v_right_pos);
899 // known_pos is on the left
900 left_pos = known_pos;
901 // *visual* position of 'right_pos'
902 pos_type v_right_pos = bidi.log2vis(left_pos) + 1;
903 // If the position we just identified as 'right_pos'
904 // is a "skipped separator", set 'right_pos' to the
905 // *next* position to the right.
906 if (bidi.inRange(v_right_pos)
907 && bidi.vis2log(v_right_pos) + 1 == row.endpos()
908 && row.endpos() < lastpos()
909 && par.isSeparator(bidi.vis2log(v_right_pos)))
912 // calculate the logical position of 'right_pos', if in row
913 if (!bidi.inRange(v_right_pos))
916 right_pos = bidi.vis2log(v_right_pos);
917 // If the position we identified as 'left_pos' is a
918 // "skipped separator", set 'left_pos' to the *next*
919 // position to the left.
920 if (left_pos + 1 == row.endpos() && row.endpos() < lastpos()
921 && par.isSeparator(left_pos)) {
922 pos_type const v_left_pos = bidi.log2vis(left_pos) - 1;
923 if (!bidi.inRange(v_left_pos))
926 left_pos = bidi.vis2log(v_left_pos);
933 bool Cursor::posVisToNewRow(bool movingLeft)
935 Paragraph const & par = paragraph();
936 Buffer const & buf = *buffer();
937 Row const & row = textRow();
938 bool par_is_LTR = !par.isRTL(buf.params());
940 // Inside a table, determining whether to move to the next or
941 // previous row should be done based on the table's direction.
943 if (s >= 1 && (*this)[s].inset().asInsetTabular()) {
944 par_is_LTR = !(*this)[s].inset().asInsetTabular()->isRightToLeft(*this);
945 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
948 // if moving left in an LTR paragraph or moving right in an
949 // RTL one, move to previous row
950 if (par_is_LTR == movingLeft) {
951 if (row.pos() == 0) { // we're at first row in paragraph
952 if (pit() == 0) // no previous paragraph! don't move
954 // move to last pos in previous par
958 } else { // move to previous row in this par
959 pos() = row.pos() - 1; // this is guaranteed to be in previous row
963 // if moving left in an RTL paragraph or moving right in an
964 // LTR one, move to next row
966 if (row.endpos() == lastpos()) { // we're at last row in paragraph
967 if (pit() == lastpit()) // last paragraph! don't move
969 // move to first row in next par
973 } else { // move to next row in this par
974 pos() = row.endpos();
979 // make sure we're at left-/right-most pos in new row
980 posVisToRowExtremity(!movingLeft);
986 void Cursor::posVisToRowExtremity(bool left)
988 // prepare bidi tables
989 Paragraph const & par = paragraph();
990 Buffer const & buf = *buffer();
991 Row const & row = textRow();
993 bidi.computeTables(par, buf, row);
995 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
996 << (boundary() ? 1 : 0));
998 if (left) { // move to leftmost position
999 // if this is an RTL paragraph, and we're at the last row in the
1000 // paragraph, move to lastpos
1001 if (par.isRTL(buf.params()) && row.endpos() == lastpos())
1004 pos() = bidi.vis2log(row.pos());
1006 // Moving to the leftmost position in the row,
1007 // the cursor should normally be placed to the
1008 // *left* of the leftmost position. A very
1009 // common exception, though, is if the
1010 // leftmost character also happens to be the
1011 // separator at the (logical) end of the row
1012 // --- in this case, the separator is
1013 // positioned beyond the left margin, and we
1014 // don't want to move the cursor there (moving
1015 // to the left of the separator is equivalent
1016 // to moving to the next line). So, in this
1017 // case we actually want to place the cursor
1018 // to the *right* of the leftmost position
1019 // (the separator). Another exception is if
1020 // we're moving to the logically last position
1021 // in the row, which is *not* a separator:
1022 // this means that the entire row has no
1023 // separators (if there were any, the row
1024 // would have been broken there); and
1025 // therefore in this case we also move to the
1026 // *right* of the last position (this
1027 // indicates to the user that there is no
1028 // space after this position, and is
1029 // consistent with the behavior in the middle
1030 // of a row --- moving right or left moves to
1031 // the next/previous character; if we were to
1032 // move to the *left* of this position, that
1033 // would simulate a separator which is not
1034 // really there!). Finally, there is an
1035 // exception to the previous exception: if
1036 // this non-separator-but-last-position-in-row
1037 // is an inset, then we *do* want to stay to
1038 // the left of it anyway: this is the
1039 // "boundary" which we simulate at insets.
1041 // Another exception is when row.endpos() is
1044 // do we want to be to the right of pos?
1045 // as explained above, if at last pos in row, stay to the right
1046 bool const right_of_pos = row.endpos() > 0
1047 && pos() == row.endpos() - 1 && !par.isInset(pos());
1049 // Now we know if we want to be to the left or to the right of pos,
1050 // let's make sure we are where we want to be.
1051 bool const new_pos_is_RTL =
1052 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
1054 if (new_pos_is_RTL != right_of_pos) {
1060 // move to rightmost position
1061 // if this is an LTR paragraph, and we're at the last row in the
1062 // paragraph, move to lastpos
1063 if (!par.isRTL(buf.params()) && row.endpos() == lastpos())
1066 pos() = row.endpos() > 0 ? bidi.vis2log(row.endpos() - 1) : 0;
1068 // Moving to the rightmost position in the
1069 // row, the cursor should normally be placed
1070 // to the *right* of the rightmost position. A
1071 // very common exception, though, is if the
1072 // rightmost character also happens to be the
1073 // separator at the (logical) end of the row
1074 // --- in this case, the separator is
1075 // positioned beyond the right margin, and we
1076 // don't want to move the cursor there (moving
1077 // to the right of the separator is equivalent
1078 // to moving to the next line). So, in this
1079 // case we actually want to place the cursor
1080 // to the *left* of the rightmost position
1081 // (the separator). Another exception is if
1082 // we're moving to the logically last position
1083 // in the row, which is *not* a separator:
1084 // this means that the entire row has no
1085 // separators (if there were any, the row
1086 // would have been broken there); and
1087 // therefore in this case we also move to the
1088 // *left* of the last position (this indicates
1089 // to the user that there is no space after
1090 // this position, and is consistent with the
1091 // behavior in the middle of a row --- moving
1092 // right or left moves to the next/previous
1093 // character; if we were to move to the
1094 // *right* of this position, that would
1095 // simulate a separator which is not really
1096 // there!). Finally, there is an exception to
1097 // the previous exception: if this
1098 // non-separator-but-last-position-in-row is
1099 // an inset, then we *do* want to stay to the
1100 // right of it anyway: this is the "boundary"
1101 // which we simulate at insets. Another
1102 // exception is when row.endpos() is 0.
1104 // do we want to be to the left of pos?
1105 // as explained above, if at last pos in row, stay to the left,
1106 // unless the last position is the same as the first.
1107 bool const left_of_pos = row.endpos() > 0
1108 && pos() == row.endpos() - 1 && !par.isInset(pos());
1110 // Now we know if we want to be to the left or to the right of pos,
1111 // let's make sure we are where we want to be.
1112 bool const new_pos_is_RTL =
1113 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
1115 if (new_pos_is_RTL == left_of_pos) {
1121 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
1122 << (boundary() ? 1 : 0));
1126 CursorSlice Cursor::normalAnchor() const
1130 // LASSERT: There have been several bugs around this code, that seem
1131 // to involve failures to reset the anchor. We can at least not crash
1132 // in release mode by resetting it ourselves.
1133 LASSERT(anchor_.depth() >= depth(),
1134 const_cast<DocIterator &>(anchor_) = *this);
1136 CursorSlice normal = anchor_[depth() - 1];
1137 if (depth() < anchor_.depth() && top() <= normal) {
1138 // anchor is behind cursor -> move anchor behind the inset
1145 DocIterator & Cursor::realAnchor()
1151 CursorSlice Cursor::selBegin() const
1155 return normalAnchor() < top() ? normalAnchor() : top();
1159 CursorSlice Cursor::selEnd() const
1163 return normalAnchor() > top() ? normalAnchor() : top();
1167 DocIterator Cursor::selectionBegin() const
1173 // FIXME: This is a work-around for the problem that
1174 // CursorSlice doesn't keep track of the boundary.
1175 if (normalAnchor() == top())
1176 di = anchor_.boundary() > boundary() ? anchor_ : *this;
1178 di = normalAnchor() < top() ? anchor_ : *this;
1184 DocIterator Cursor::selectionEnd() const
1190 // FIXME: This is a work-around for the problem that
1191 // CursorSlice doesn't keep track of the boundary.
1192 if (normalAnchor() == top())
1193 di = anchor_.boundary() < boundary() ? anchor_ : *this;
1195 di = normalAnchor() > top() ? anchor_ : *this;
1197 if (di.depth() > depth()) {
1205 void Cursor::setSelection()
1208 if (idx() == normalAnchor().idx() &&
1209 pit() == normalAnchor().pit() &&
1210 pos() == normalAnchor().pos())
1211 setSelection(false);
1215 void Cursor::setSelection(DocIterator const & where, int n)
1224 void Cursor::clearSelection()
1226 setSelection(false);
1227 setWordSelection(false);
1233 void Cursor::setTargetX(int x)
1236 textTargetOffset_ = 0;
1240 int Cursor::x_target() const
1246 void Cursor::clearTargetX()
1249 textTargetOffset_ = 0;
1253 void Cursor::updateTextTargetOffset()
1258 textTargetOffset_ = x - x_target_;
1262 void Cursor::info(odocstream & os) const
1264 for (int i = 1, n = depth(); i < n; ++i) {
1265 operator[](i).inset().infoize(os);
1269 Inset const * inset = prevInset();
1270 // prevInset() can return 0 in certain case.
1272 prevInset()->infoize2(os);
1274 // overwite old message
1279 bool Cursor::selHandle(bool sel)
1281 //lyxerr << "Cursor::selHandle" << endl;
1284 if (sel == selection())
1288 cap::saveSelection(*this);
1296 ostream & operator<<(ostream & os, Cursor const & cur)
1298 os << "\n cursor: | anchor:\n";
1299 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
1300 os << " " << cur[i] << " | ";
1301 if (i < cur.anchor_.depth())
1302 os << cur.anchor_[i];
1304 os << "-------------------------------";
1307 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
1308 os << "------------------------------- | " << cur.anchor_[i] << "\n";
1310 os << " selection: " << cur.selection_
1311 << " x_target: " << cur.x_target_
1312 << " boundary: " << cur.boundary() << endl;
1317 LyXErr & operator<<(LyXErr & os, Cursor const & cur)
1327 ///////////////////////////////////////////////////////////////////
1330 // The part below is the non-integrated rest of the original math
1331 // cursor. This should be either generalized for texted or moved
1332 // back to mathed (in most cases to InsetMathNest).
1334 ///////////////////////////////////////////////////////////////////
1336 #include "mathed/InsetMathChar.h"
1337 #include "mathed/InsetMathGrid.h"
1338 #include "mathed/InsetMathScript.h"
1339 #include "mathed/InsetMathUnknown.h"
1340 #include "mathed/MathFactory.h"
1341 #include "mathed/MathStream.h"
1342 #include "mathed/MathSupport.h"
1347 bool Cursor::isInside(Inset const * p) const
1349 for (size_t i = 0; i != depth(); ++i)
1350 if (&operator[](i).inset() == p)
1356 void Cursor::leaveInset(Inset const & inset)
1358 for (size_t i = 0; i != depth(); ++i) {
1359 if (&operator[](i).inset() == &inset) {
1367 bool Cursor::openable(MathAtom const & t) const
1378 // we can't move into anything new during selection
1379 if (depth() >= anchor_.depth())
1381 if (t.nucleus() != &anchor_[depth()].inset())
1388 void Cursor::setScreenPos(int x, int /*y*/)
1391 //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
1396 void Cursor::plainErase()
1398 cell().erase(pos());
1402 void Cursor::markInsert()
1404 insert(char_type(0));
1408 void Cursor::markErase()
1410 cell().erase(pos());
1414 void Cursor::plainInsert(MathAtom const & t)
1416 cell().insert(pos(), t);
1418 inset().setBuffer(bv_->buffer());
1420 forceBufferUpdate();
1424 void Cursor::insert(docstring const & str)
1426 for_each(str.begin(), str.end(),
1427 bind(static_cast<void(Cursor::*)(char_type)>
1428 (&Cursor::insert), this, _1));
1432 void Cursor::insert(char_type c)
1434 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1435 LASSERT(!empty(), return);
1437 cap::selClearOrDel(*this);
1438 insert(new InsetMathChar(c));
1440 text()->insertChar(*this, c);
1445 void Cursor::insert(MathAtom const & t)
1447 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1449 cap::selClearOrDel(*this);
1454 void Cursor::insert(Inset * inset0)
1456 LASSERT(inset0, return);
1458 insert(MathAtom(inset0->asInsetMath()));
1460 text()->insertInset(*this, inset0);
1461 inset0->setBuffer(bv_->buffer());
1463 if (inset0->isLabeled())
1464 forceBufferUpdate();
1469 int Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1471 MathData ar(buffer());
1473 if (ar.size() == 1 && (enter || selection()))
1481 void Cursor::niceInsert(MathAtom const & t)
1484 docstring const safe = cap::grabAndEraseSelection(*this);
1486 // If possible, enter the new inset and move the contents of the selection
1487 if (t->isActive()) {
1489 // be careful here: don't use 'pushBackward(t)' as this we need to
1490 // push the clone, not the original
1491 pushBackward(*nextInset());
1492 // We may not use niceInsert here (recursion)
1493 MathData ar(buffer());
1496 } else if (t->asMacro() && !safe.empty()) {
1497 MathData ar(buffer());
1499 docstring const name = t->asMacro()->name();
1500 MacroData const * data = buffer()->getMacro(name);
1501 if (data && data->numargs() - data->optionals() > 0) {
1502 plainInsert(MathAtom(new InsetMathBrace(ar)));
1509 void Cursor::insert(MathData const & ar)
1513 cap::eraseSelection(*this);
1514 cell().insert(pos(), ar);
1516 // FIXME audit setBuffer calls
1517 inset().setBuffer(bv_->buffer());
1521 bool Cursor::backspace()
1524 cap::eraseSelection(*this);
1529 // If empty cell, and not part of a big cell
1530 if (lastpos() == 0 && inset().nargs() == 1) {
1532 // Directly delete empty cell: [|[]] => [|]
1538 // [|], can not delete from inside
1549 if (inMacroMode()) {
1550 InsetMathUnknown * p = activeMacro();
1551 if (p->name().size() > 1) {
1552 p->setName(p->name().substr(0, p->name().size() - 1));
1557 if (pos() != 0 && prevAtom()->nargs() > 0) {
1558 // let's require two backspaces for 'big stuff' and
1559 // highlight on the first
1571 bool Cursor::erase()
1577 cap::eraseSelection(*this);
1581 // delete empty cells if possible
1582 if (pos() == lastpos() && inset().idxDelete(idx()))
1585 // special behaviour when in last position of cell
1586 if (pos() == lastpos()) {
1587 bool one_cell = inset().nargs() == 1;
1588 if (one_cell && lastpos() == 0) {
1590 // Directly delete empty cell: [|[]] => [|]
1596 // [|], can not delete from inside
1601 inset().idxGlue(idx());
1605 // 'clever' UI hack: only erase large items if previously slected
1606 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
1621 DocIterator save = *this;
1622 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1623 this->dispatch(cmd);
1624 if (disp_.dispatched())
1634 DocIterator save = *this;
1635 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1636 this->dispatch(cmd);
1637 if (disp_.dispatched())
1644 bool Cursor::macroModeClose()
1648 InsetMathUnknown * p = activeMacro();
1650 MathData selection(buffer());
1651 asArray(p->selection(), selection);
1652 docstring const s = p->name();
1654 cell().erase(pos());
1656 // do nothing if the macro name is empty
1660 // trigger updates of macros, at least, if no full
1661 // updates take place anyway
1662 screenUpdateFlags(Update::Force);
1664 docstring const name = s.substr(1);
1665 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1666 if (in && in->interpretString(*this, s))
1668 MathAtom atom = buffer()->getMacro(name, *this, false) ?
1669 MathAtom(new MathMacro(buffer(), name)) : createInsetMath(name, buffer());
1671 // try to put argument into macro, if we just inserted a macro
1672 bool macroArg = false;
1673 MathMacro * atomAsMacro = atom.nucleus()->asMacro();
1675 // macros here are still unfolded (in init mode in fact). So
1676 // we have to resolve the macro here manually and check its arity
1677 // to put the selection behind it if arity > 0.
1678 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1679 if (!selection.empty() && data && data->numargs() - data->optionals() > 0) {
1681 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1683 // non-greedy case. Do not touch the arguments behind
1684 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1687 // insert remembered selection into first argument of a non-macro
1688 else if (atom.nucleus()->nargs() > 0)
1689 atom.nucleus()->cell(0).append(selection);
1693 // finally put the macro argument behind, if needed
1695 if (selection.size() > 1 || selection[0]->asScriptInset())
1696 plainInsert(MathAtom(new InsetMathBrace(selection)));
1705 docstring Cursor::macroName()
1707 return inMacroMode() ? activeMacro()->name() : docstring();
1711 void Cursor::handleNest(MathAtom const & a, int c)
1713 //lyxerr << "Cursor::handleNest: " << c << endl;
1715 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1718 pushBackward(*nextInset());
1722 int Cursor::targetX() const
1724 if (x_target() != -1)
1733 int Cursor::textTargetOffset() const
1735 return textTargetOffset_;
1739 void Cursor::setTargetX()
1748 bool Cursor::inMacroMode() const
1752 if (pos() == 0 || cell().empty())
1754 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1755 return p && !p->final();
1759 InsetMathUnknown * Cursor::activeMacro()
1761 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1765 InsetMathUnknown const * Cursor::activeMacro() const
1767 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1771 void Cursor::pullArg()
1774 MathData ar = cell();
1775 if (popBackward() && inMathed()) {
1777 cell().insert(pos(), ar);
1780 //formula()->mutateToText();
1785 void Cursor::touch()
1789 DocIterator::const_iterator it = begin();
1790 DocIterator::const_iterator et = end();
1791 for ( ; it != et; ++it)
1797 void Cursor::normalize()
1799 if (idx() > lastidx()) {
1800 lyxerr << "this should not really happen - 1: "
1801 << idx() << ' ' << nargs()
1802 << " in: " << &inset() << endl;
1806 if (pos() > lastpos()) {
1807 lyxerr << "this should not really happen - 2: "
1808 << pos() << ' ' << lastpos() << " in idx: " << idx()
1810 odocstringstream os;
1811 WriteStream wi(os, false, true, WriteStream::wsDefault);
1812 inset().asInsetMath()->write(wi);
1813 lyxerr << to_utf8(os.str()) << endl;
1819 bool Cursor::upDownInMath(bool up)
1821 // Be warned: The 'logic' implemented in this function is highly
1822 // fragile. A distance of one pixel or a '<' vs '<=' _really
1823 // matters. So fiddle around with it only if you think you know
1824 // what you are doing!
1828 xo = beforeDispatchPosX_;
1830 // check if we had something else in mind, if not, this is the future
1832 if (x_target_ == -1)
1834 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1835 // In text mode inside the line (not left or right) possibly set a new target_x,
1836 // but only if we are somewhere else than the previous target-offset.
1838 // We want to keep the x-target on subsequent up/down movements
1839 // that cross beyond the end of short lines. Thus a special
1840 // handling when the cursor is at the end of line: Use the new
1841 // x-target only if the old one was before the end of line
1842 // or the old one was after the beginning of the line
1843 bool inRTL = isWithinRtlParagraph(*this);
1847 left = pos() == textRow().endpos();
1848 right = pos() == textRow().pos();
1850 left = pos() == textRow().pos();
1851 right = pos() == textRow().endpos();
1853 if ((!left && !right) ||
1854 (left && !right && xo < x_target_) ||
1855 (!left && right && x_target_ < xo))
1862 // try neigbouring script insets
1864 if (inMathed() && !selection()) {
1867 InsetMathScript const * p = prevAtom()->asScriptInset();
1868 if (p && p->has(up)) {
1870 push(*const_cast<InsetMathScript*>(p));
1871 idx() = p->idxOfScript(up);
1874 // we went in the right direction? Otherwise don't jump into the script
1878 int oy = beforeDispatchPosY_;
1879 if ((!up && y <= oy) ||
1888 if (pos() != lastpos()) {
1889 InsetMathScript const * p = nextAtom()->asScriptInset();
1890 if (p && p->has(up)) {
1891 push(*const_cast<InsetMathScript*>(p));
1892 idx() = p->idxOfScript(up);
1895 // we went in the right direction? Otherwise don't jump into the script
1899 int oy = beforeDispatchPosY_;
1900 if ((!up && y <= oy) ||
1909 // try to find an inset that knows better then we,
1910 if (inset().idxUpDown(*this, up)) {
1911 //lyxerr << "idxUpDown triggered" << endl;
1912 // try to find best position within this inset
1914 setCursor(bruteFind2(*this, xo, yo));
1918 // any improvement going just out of inset?
1919 if (popBackward() && inMathed()) {
1920 //lyxerr << "updown: popBackward succeeded" << endl;
1923 int yold = beforeDispatchPosY_;
1925 if (up ? ynew < yold : ynew > yold)
1929 // no success, we are probably at the document top or bottom
1935 bool Cursor::atFirstOrLastRow(bool up)
1937 TextMetrics const & tm = bv_->textMetrics(text());
1938 ParagraphMetrics const & pm = tm.parMetrics(pit());
1941 if (pos() && boundary())
1942 row = pm.pos2row(pos() - 1);
1944 row = pm.pos2row(pos());
1947 if (pit() == 0 && row == 0)
1950 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1951 row + 1 >= int(pm.rows().size()))
1958 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1960 LASSERT(text(), return false);
1966 xo = beforeDispatchPosX_;
1968 // update the targetX - this is here before the "return false"
1969 // to set a new target which can be used by InsetTexts above
1970 // if we cannot move up/down inside this inset anymore
1971 if (x_target_ == -1)
1973 else if (xo - textTargetOffset() != x_target() &&
1974 depth() == beforeDispatchCursor_.depth()) {
1975 // In text mode inside the line (not left or right)
1976 // possibly set a new target_x, but only if we are
1977 // somewhere else than the previous target-offset.
1979 // We want to keep the x-target on subsequent up/down
1980 // movements that cross beyond the end of short lines.
1981 // Thus a special handling when the cursor is at the
1982 // end of line: Use the new x-target only if the old
1983 // one was before the end of line or the old one was
1984 // after the beginning of the line
1985 bool inRTL = isWithinRtlParagraph(*this);
1989 left = pos() == textRow().endpos();
1990 right = pos() == textRow().pos();
1992 left = pos() == textRow().pos();
1993 right = pos() == textRow().endpos();
1995 if ((!left && !right) ||
1996 (left && !right && xo < x_target_) ||
1997 (!left && right && x_target_ < xo))
2004 // first get the current line
2005 TextMetrics & tm = bv_->textMetrics(text());
2006 ParagraphMetrics const & pm = tm.parMetrics(pit());
2008 if (pos() && boundary())
2009 row = pm.pos2row(pos() - 1);
2011 row = pm.pos2row(pos());
2013 if (atFirstOrLastRow(up)) {
2014 // Is there a place for the cursor to go ? If yes, we
2015 // can execute the DEPM, otherwise we should keep the
2016 // paragraph to host the cursor.
2017 Cursor dummy = *this;
2018 bool valid_destination = false;
2019 for(; dummy.depth(); dummy.pop())
2020 if (!dummy.atFirstOrLastRow(up)) {
2021 valid_destination = true;
2025 // will a next dispatch follow and if there is a new
2026 // dispatch will it move the cursor out ?
2027 if (depth() > 1 && valid_destination) {
2028 // The cursor hasn't changed yet. This happens when
2029 // you e.g. move out of an inset. And to give the
2030 // DEPM the possibility of doing something we must
2031 // provide it with two different cursors. (Lgb, vfr)
2033 dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
2034 dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
2036 updateNeeded |= bv().checkDepm(dummy, *this);
2037 updateTextTargetOffset();
2039 forceBufferUpdate();
2044 // with and without selection are handled differently
2046 int yo = bv().getPos(*this).y_;
2048 // To next/previous row
2050 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
2052 tm.editXY(*this, xo, yo + textRow().descent() + 1);
2055 // This happens when you move out of an inset.
2056 // And to give the DEPM the possibility of doing
2057 // something we must provide it with two different
2059 Cursor dummy = *this;
2062 if (bv().checkDepm(dummy, old)) {
2063 updateNeeded = true;
2064 // Make sure that cur gets back whatever happened to dummy (Lgb)
2068 // if there is a selection, we stay out of any inset,
2069 // and just jump to the right position:
2075 } else if (pit() > 0) {
2077 TextMetrics & tm = bv_->textMetrics(text());
2078 if (!tm.contains(pit()))
2079 tm.newParMetricsUp();
2080 ParagraphMetrics const & pmcur = tm.parMetrics(pit());
2081 next_row = pmcur.rows().size() - 1;
2084 if (row + 1 < int(pm.rows().size())) {
2086 } else if (pit() + 1 < int(text()->paragraphs().size())) {
2088 TextMetrics & tm = bv_->textMetrics(text());
2089 if (!tm.contains(pit()))
2090 tm.newParMetricsDown();
2095 Row const & real_next_row = tm.parMetrics(pit()).rows()[next_row];
2097 top().pos() = tm.getPosNearX(real_next_row, xo, bound);
2100 updateNeeded |= bv().checkDepm(*this, old);
2104 forceBufferUpdate();
2105 updateTextTargetOffset();
2110 void Cursor::handleFont(string const & font)
2112 LYXERR(Debug::DEBUG, font);
2116 safe = cap::grabAndEraseSelection(*this);
2121 if (lastpos() != 0) {
2122 // something left in the cell
2124 // cursor in first position
2126 } else if (pos() == lastpos()) {
2127 // cursor in last position
2130 // cursor in between. split cell
2131 MathData::iterator bt = cell().begin();
2132 MathAtom at = createInsetMath(from_utf8(font), buffer());
2133 at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
2134 cell().erase(bt, bt + pos());
2139 // nothing left in the cell
2148 void Cursor::message(docstring const & msg) const
2150 disp_.setMessage(msg);
2154 void Cursor::errorMessage(docstring const & msg) const
2156 disp_.setMessage(msg);
2157 disp_.setError(true);
2163 docstring parbreak(Cursor const * cur)
2165 odocstringstream os;
2167 // only add blank line if we're not in a ParbreakIsNewline situation
2168 if (!cur->inset().getLayout().parbreakIsNewline()
2169 && !cur->paragraph().layout().parbreak_is_newline)
2177 docstring Cursor::selectionAsString(bool with_label) const
2183 return cap::grabSelection(*this);
2185 int const label = with_label
2186 ? AS_STR_LABEL | AS_STR_INSETS : AS_STR_INSETS;
2188 idx_type const startidx = selBegin().idx();
2189 idx_type const endidx = selEnd().idx();
2190 if (startidx != endidx) {
2191 // multicell selection
2192 InsetTabular * table = inset().asInsetTabular();
2193 LASSERT(table, return docstring());
2194 return table->asString(startidx, endidx);
2197 ParagraphList const & pars = text()->paragraphs();
2199 pit_type const startpit = selBegin().pit();
2200 pit_type const endpit = selEnd().pit();
2201 size_t const startpos = selBegin().pos();
2202 size_t const endpos = selEnd().pos();
2204 if (startpit == endpit)
2205 return pars[startpit].asString(startpos, endpos, label);
2207 // First paragraph in selection
2208 docstring result = pars[startpit].
2209 asString(startpos, pars[startpit].size(), label)
2212 // The paragraphs in between (if any)
2213 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
2214 Paragraph const & par = pars[pit];
2215 result += par.asString(0, par.size(), label)
2219 // Last paragraph in selection
2220 result += pars[endpit].asString(0, endpos, label);
2226 docstring Cursor::currentState() const
2229 odocstringstream os;
2235 return text()->currentState(*this);
2241 docstring Cursor::getPossibleLabel() const
2243 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
2247 Encoding const * Cursor::getEncoding() const
2251 CursorSlice const & sl = innerTextSlice();
2252 Text const & text = *sl.text();
2253 Font font = text.getPar(sl.pit()).getFont(
2254 bv().buffer().params(), sl.pos(), text.outerFont(sl.pit()));
2255 return font.language()->encoding();
2259 void Cursor::undispatched() const
2261 disp_.dispatched(false);
2265 void Cursor::dispatched() const
2267 disp_.dispatched(true);
2271 void Cursor::screenUpdateFlags(Update::flags f) const
2273 disp_.screenUpdate(f);
2277 void Cursor::forceBufferUpdate() const
2279 disp_.forceBufferUpdate();
2283 void Cursor::clearBufferUpdate() const
2285 disp_.clearBufferUpdate();
2289 bool Cursor::needBufferUpdate() const
2291 return disp_.needBufferUpdate();
2295 void Cursor::noScreenUpdate() const
2297 disp_.screenUpdate(Update::None);
2301 Font Cursor::getFont() const
2303 // The logic here should more or less match to the
2304 // Cursor::setCurrentFont logic, i.e. the cursor height should
2305 // give a hint what will happen if a character is entered.
2307 // HACK. far from being perfect...
2309 CursorSlice const & sl = innerTextSlice();
2310 Text const & text = *sl.text();
2311 Paragraph const & par = text.getPar(sl.pit());
2313 // on boundary, so we are really at the character before
2314 pos_type pos = sl.pos();
2315 if (pos > 0 && boundary())
2318 // on space? Take the font before (only for RTL boundary stay)
2320 TextMetrics const & tm = bv().textMetrics(&text);
2321 if (pos == sl.lastpos()
2322 || (par.isSeparator(pos)
2323 && !tm.isRTLBoundary(sl.pit(), pos)))
2327 // get font at the position
2328 Font font = par.getFont(buffer()->params(), pos,
2329 text.outerFont(sl.pit()));
2335 bool Cursor::fixIfBroken()
2337 bool const broken_cursor = DocIterator::fixIfBroken();
2338 bool const broken_anchor = anchor_.fixIfBroken();
2340 if (broken_cursor || broken_anchor) {
2341 clearNewWordPosition();
2349 void Cursor::sanitize()
2351 setBuffer(&bv_->buffer());
2352 DocIterator::sanitize();
2357 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2359 // find inset in common
2361 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2362 if (&old[i].inset() != &cur[i].inset())
2366 // update words if we just moved to another paragraph
2367 if (i == old.depth() && i == cur.depth()
2368 && !cur.buffer()->isClean()
2369 && cur.inTexted() && old.inTexted()
2370 && cur.pit() != old.pit()) {
2371 old.paragraph().updateWords();
2374 // notify everything on top of the common part in old cursor,
2375 // but stop if the inset claims the cursor to be invalid now
2376 for (size_type j = i; j < old.depth(); ++j) {
2377 Cursor inset_pos = old;
2378 inset_pos.cutOff(j);
2379 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2383 // notify everything on top of the common part in new cursor,
2384 // but stop if the inset claims the cursor to be invalid now
2385 for (; i < cur.depth(); ++i) {
2386 if (cur[i].inset().notifyCursorEnters(cur))
2394 void Cursor::setCurrentFont()
2396 CursorSlice const & cs = innerTextSlice();
2397 Paragraph const & par = cs.paragraph();
2398 pos_type cpit = cs.pit();
2399 pos_type cpos = cs.pos();
2400 Text const & ctext = *cs.text();
2401 TextMetrics const & tm = bv().textMetrics(&ctext);
2403 // are we behind previous char in fact? -> go to that char
2404 if (cpos > 0 && boundary())
2407 // find position to take the font from
2409 // paragraph end? -> font of last char
2410 if (cpos == lastpos())
2412 // on space? -> look at the words in front of space
2413 else if (cpos > 0 && par.isSeparator(cpos)) {
2414 // abc| def -> font of c
2415 // abc |[WERBEH], i.e. boundary==true -> font of c
2416 // abc [WERBEH]| def, font of the space
2417 if (!tm.isRTLBoundary(cpit, cpos))
2423 BufferParams const & bufparams = buffer()->params();
2424 current_font = par.getFontSettings(bufparams, cpos);
2425 real_current_font = tm.displayFont(cpit, cpos);
2427 // special case for paragraph end
2428 if (cs.pos() == lastpos()
2429 && tm.isRTLBoundary(cpit, cs.pos())
2431 Language const * lang = par.getParLanguage(bufparams);
2432 current_font.setLanguage(lang);
2433 current_font.fontInfo().setNumber(FONT_OFF);
2434 real_current_font.setLanguage(lang);
2435 real_current_font.fontInfo().setNumber(FONT_OFF);
2440 bool Cursor::textUndo()
2442 if (!buffer()->undo().textUndo(*this))
2449 bool Cursor::textRedo()
2451 if (!buffer()->undo().textRedo(*this))
2458 void Cursor::finishUndo() const
2460 buffer()->undo().finishUndo();
2464 void Cursor::beginUndoGroup() const
2466 buffer()->undo().beginUndoGroup();
2470 void Cursor::endUndoGroup() const
2472 buffer()->undo().endUndoGroup(*this);
2476 void Cursor::recordUndo(UndoKind kind, pit_type from, pit_type to) const
2478 buffer()->undo().recordUndo(*this, kind, from, to);
2482 void Cursor::recordUndo(UndoKind kind, pit_type from) const
2484 buffer()->undo().recordUndo(*this, kind, from);
2488 void Cursor::recordUndo(UndoKind kind) const
2490 buffer()->undo().recordUndo(*this, kind);
2494 void Cursor::recordUndoInset(UndoKind kind, Inset const * inset) const
2496 buffer()->undo().recordUndoInset(*this, kind, inset);
2500 void Cursor::recordUndoFullBuffer() const
2502 buffer()->undo().recordUndoFullBuffer(*this);
2506 void Cursor::recordUndoBufferParams() const
2508 buffer()->undo().recordUndoBufferParams(*this);
2512 void Cursor::recordUndoSelection() const
2515 if (cap::multipleCellsSelected(*this))
2520 buffer()->undo().recordUndo(*this, ATOMIC_UNDO,
2521 selBegin().pit(), selEnd().pit());
2526 void Cursor::checkBufferStructure()
2528 Buffer const * master = buffer()->masterBuffer();
2529 master->tocBackend().updateItem(*this);
2530 if (master != buffer() && !master->hasGuiDelegate())
2531 // In case the master has no gui associated with it,
2532 // the TocItem is not updated (part of bug 5699).
2533 buffer()->tocBackend().updateItem(*this);