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() = prev(cache.end(), 1)->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)
266 ostream & operator<<(ostream & os, CursorData const & cur)
268 os << "\n cursor: | anchor:\n";
269 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
270 os << " " << cur[i] << " | ";
271 if (i < cur.anchor_.depth())
272 os << cur.anchor_[i];
274 os << "-------------------------------";
277 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
278 os << "------------------------------- | " << cur.anchor_[i] << "\n";
280 os << " selection: " << cur.selection_
281 // << " x_target: " << cur.x_target_
282 << " boundary: " << cur.boundary() << endl;
287 LyXErr & operator<<(LyXErr & os, CursorData const & cur)
294 // be careful: this is called from the bv's constructor, too, so
295 // bv functions are not yet available!
296 Cursor::Cursor(BufferView & bv)
297 : CursorData(&bv.buffer()), bv_(&bv),
298 x_target_(-1), textTargetOffset_(0),
299 beforeDispatchPosX_(0), beforeDispatchPosY_(0)
306 push_back(CursorSlice(buffer()->inset()));
307 anchor_ = doc_iterator_begin(buffer());
309 new_word_ = doc_iterator_begin(buffer());
317 // this (intentionally) does neither touch anchor nor selection status
318 void Cursor::setCursor(DocIterator const & cur)
320 DocIterator::operator=(cur);
324 void Cursor::setCursorToAnchor()
327 DocIterator normal = anchor_;
328 while (depth() < normal.depth())
330 if (depth() < anchor_.depth() && top() <= anchor_[depth() - 1])
337 void Cursor::setCursorData(CursorData const & data)
339 CursorData::operator=(data);
343 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
347 // Try to fix cursor in case it is broken.
350 // Is this a function that acts on inset at point?
351 Inset * inset = cur.nextInset();
352 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
353 && inset && inset->getStatus(cur, cmd, status))
356 // This is, of course, a mess. Better create a new doc iterator and use
357 // this in Inset::getStatus. This might require an additional
358 // BufferView * arg, though (which should be avoided)
359 //Cursor safe = *this;
361 for ( ; cur.depth(); cur.pop()) {
362 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
363 // LASSERT: Is it safe to continue here, or should we return?
364 LASSERT(cur.idx() <= cur.lastidx(), /**/);
365 LASSERT(cur.pit() <= cur.lastpit(), /**/);
366 LASSERT(cur.pos() <= cur.lastpos(), /**/);
368 // The inset's getStatus() will return 'true' if it made
369 // a definitive decision on whether it want to handle the
370 // request or not. The result of this decision is put into
371 // the 'status' parameter.
372 if (cur.inset().getStatus(cur, cmd, status)) {
381 void Cursor::saveBeforeDispatchPosXY()
383 getPos(beforeDispatchPosX_, beforeDispatchPosY_);
387 void Cursor::dispatch(FuncRequest const & cmd0)
389 LYXERR(Debug::DEBUG, "cmd: " << cmd0 << '\n' << *this);
394 FuncRequest cmd = cmd0;
397 disp_ = DispatchResult();
401 // Is this a function that acts on inset at point?
402 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
404 disp_.dispatched(true);
405 disp_.screenUpdate(Update::FitCursor | Update::Force);
406 FuncRequest tmpcmd = cmd;
407 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
408 << cmd0 << endl << *this);
409 nextInset()->dispatch(*this, tmpcmd);
410 if (disp_.dispatched()) {
416 // store some values to be used inside of the handlers
417 beforeDispatchCursor_ = *this;
418 for (; depth(); pop(), boundary(false)) {
419 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
420 << cmd0 << endl << *this);
422 // In any of these cases, the cursor is invalid, and we should
423 // try to save this document rather than crash.
424 LBUFERR(pos() <= lastpos());
425 LBUFERR(idx() <= lastidx());
426 LBUFERR(pit() <= lastpit());
428 // The common case is 'LFUN handled, need update', so make the
429 // LFUN handler's life easier by assuming this as default value.
430 // The handler can reset the update and val flags if necessary.
431 disp_.screenUpdate(Update::FitCursor | Update::Force);
432 disp_.dispatched(true);
433 inset().dispatch(*this, cmd);
434 if (disp_.dispatched())
438 // it completely to get a 'bomb early' behaviour in case this
439 // object will be used again.
440 if (!disp_.dispatched()) {
441 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
442 // We might have invalidated the cursor when removing an empty
443 // paragraph while the cursor could not be moved out the inset
444 // while we initially thought we could. This might happen when
445 // a multiline inset becomes an inline inset when the second
446 // paragraph is removed.
447 if (safe.pit() > safe.lastpit()) {
448 safe.pit() = safe.lastpit();
449 safe.pos() = safe.lastpos();
452 disp_.screenUpdate(Update::None);
453 disp_.dispatched(false);
455 // restore the previous one because nested Cursor::dispatch calls
456 // are possible which would change it
457 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
461 // notify insets we just left
463 old.beginUndoGroup();
465 bool badcursor = notifyCursorLeavesOrEnters(old, *this);
468 bv().resetInlineCompletionPos();
475 DispatchResult const & Cursor::result() const
481 BufferView & Cursor::bv() const
490 LBUFERR(depth() >= 1);
495 void Cursor::push(Inset & p)
497 push_back(CursorSlice(p));
498 p.setBuffer(*buffer());
502 void Cursor::pushBackward(Inset & p)
504 LASSERT(!empty(), return);
505 //lyxerr << "Entering inset " << t << " front" << endl;
511 bool Cursor::popBackward()
513 LASSERT(!empty(), return false);
521 bool Cursor::popForward()
523 LASSERT(!empty(), return false);
524 //lyxerr << "Leaving inset from in back" << endl;
525 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
529 pos() += lastpos() - lp + 1;
534 int Cursor::currentMode()
536 LASSERT(!empty(), return Inset::UNDECIDED_MODE);
537 for (int i = depth() - 1; i >= 0; --i) {
538 int res = operator[](i).inset().currentMode();
539 bool locked_mode = operator[](i).inset().lockedMode();
540 // Also return UNDECIDED_MODE when the mode is locked,
541 // as in this case it is treated the same as TEXT_MODE
542 if (res != Inset::UNDECIDED_MODE || locked_mode)
545 return Inset::TEXT_MODE;
549 void Cursor::getPos(int & x, int & y) const
551 Point p = bv().getPos(*this);
557 Row const & Cursor::textRow() const
559 CursorSlice const & cs = innerTextSlice();
560 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
561 return pm.getRow(pos(), boundary());
565 void Cursor::resetAnchor()
568 checkNewWordPosition();
572 void Cursor::markNewWordPosition()
574 if (lyxrc.spellcheck_continuously && inTexted() && new_word_.empty()) {
575 FontSpan nw = locateWord(WHOLE_WORD);
576 if (nw.size() == 1) {
577 LYXERR(Debug::DEBUG, "start new word: "
579 << " pos: " << nw.first);
586 void Cursor::clearNewWordPosition()
588 if (!new_word_.empty()) {
589 LYXERR(Debug::DEBUG, "clear new word: "
591 << " pos: " << pos());
597 void Cursor::checkNewWordPosition()
599 if (!lyxrc.spellcheck_continuously || new_word_.empty())
602 clearNewWordPosition();
604 // forget the position of the current new word if
605 // 1) the paragraph changes or
606 // 2) the count of nested insets changes or
607 // 3) the cursor pos is out of paragraph bound
608 if (pit() != new_word_.pit() ||
609 depth() != new_word_.depth() ||
610 new_word_.pos() > new_word_.lastpos()) {
611 clearNewWordPosition();
612 } else if (new_word_.fixIfBroken())
613 // 4) or the remembered position was "broken"
614 clearNewWordPosition();
616 FontSpan nw = locateWord(WHOLE_WORD);
618 FontSpan ow = new_word_.locateWord(WHOLE_WORD);
619 if (nw.intersect(ow).empty())
620 clearNewWordPosition();
622 LYXERR(Debug::DEBUG, "new word: "
624 << " pos: " << nw.first << ".." << nw.last);
626 clearNewWordPosition();
633 bool Cursor::posBackward()
642 bool Cursor::posForward()
644 if (pos() == lastpos())
651 bool Cursor::posVisRight(bool skip_inset)
653 Cursor new_cur = *this; // where we will move to
654 pos_type left_pos; // position visually left of current cursor
655 pos_type right_pos; // position visually right of current cursor
657 getSurroundingPos(left_pos, right_pos);
659 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
661 // Are we at an inset?
662 new_cur.pos() = right_pos;
663 new_cur.boundary(false);
665 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
666 // we actually move the cursor at the end of this
667 // function, for now we just keep track of the new
668 // position in new_cur...
669 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
672 // Are we already at rightmost pos in row?
673 else if (text()->empty() || right_pos == -1) {
676 if (!new_cur.posVisToNewRow(false)) {
677 LYXERR(Debug::RTL, "not moving!");
681 // we actually move the cursor at the end of this
682 // function, for now just keep track of the new
683 // position in new_cur...
684 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
685 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
688 // normal movement to the right
691 // Recall, if the cursor is at position 'x', that
692 // means *before* the character at position 'x'. In
693 // RTL, "before" means "to the right of", in LTR, "to
694 // the left of". So currently our situation is this:
695 // the position to our right is 'right_pos' (i.e.,
696 // we're currently to the left of 'right_pos'). In
697 // order to move to the right, it depends whether or
698 // not the character at 'right_pos' is RTL.
699 bool const new_pos_is_RTL = paragraph().getFontSettings(
700 buffer()->params(), right_pos).isVisibleRightToLeft();
701 // If the character at 'right_pos' *is* LTR, then in
702 // order to move to the right of it, we need to be
703 // *after* 'right_pos', i.e., move to position
705 if (!new_pos_is_RTL) {
706 new_cur.pos() = right_pos + 1;
707 // set the boundary to true in two situations:
709 // 1. if new_pos is now lastpos, and we're in
710 // an RTL paragraph (this means that we're
711 // moving right to the end of an LTR chunk
712 // which is at the end of an RTL paragraph);
713 (new_cur.pos() == lastpos()
714 && paragraph().isRTL(buffer()->params()))
715 // 2. if the position *after* right_pos is RTL
716 // (we want to be *after* right_pos, not
717 // before right_pos + 1!)
718 || paragraph().getFontSettings(buffer()->params(),
719 new_cur.pos()).isVisibleRightToLeft()
721 new_cur.boundary(true);
722 else // set the boundary to false
723 new_cur.boundary(false);
725 // Otherwise (if the character at position 'right_pos'
726 // is RTL), then moving to the right of it is as easy
727 // as setting the new position to 'right_pos'.
729 new_cur.pos() = right_pos;
730 new_cur.boundary(false);
735 bool moved = (new_cur.pos() != pos()
736 || new_cur.pit() != pit()
737 || new_cur.boundary() != boundary()
738 || &new_cur.inset() != &inset());
741 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
742 << (new_cur.boundary() ? " (boundary)" : ""));
750 bool Cursor::posVisLeft(bool skip_inset)
752 Cursor new_cur = *this; // where we will move to
753 pos_type left_pos; // position visually left of current cursor
754 pos_type right_pos; // position visually right of current cursor
756 getSurroundingPos(left_pos, right_pos);
758 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
760 // Are we at an inset?
761 new_cur.pos() = left_pos;
762 new_cur.boundary(false);
764 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
765 // we actually move the cursor at the end of this
766 // function, for now we just keep track of the new
767 // position in new_cur...
768 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
771 // Are we already at leftmost pos in row?
772 else if (text()->empty() || left_pos == -1) {
775 if (!new_cur.posVisToNewRow(true)) {
776 LYXERR(Debug::RTL, "not moving!");
780 // we actually move the cursor at the end of this
781 // function, for now just keep track of the new
782 // position in new_cur...
783 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
784 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
787 // normal movement to the left
790 // Recall, if the cursor is at position 'x', that
791 // means *before* the character at position 'x'. In
792 // RTL, "before" means "to the right of", in LTR, "to
793 // the left of". So currently our situation is this:
794 // the position to our left is 'left_pos' (i.e., we're
795 // currently to the right of 'left_pos'). In order to
796 // move to the left, it depends whether or not the
797 // character at 'left_pos' is RTL.
798 bool const new_pos_is_RTL = paragraph().getFontSettings(
799 buffer()->params(), left_pos).isVisibleRightToLeft();
800 // If the character at 'left_pos' *is* RTL, then in
801 // order to move to the left of it, we need to be
802 // *after* 'left_pos', i.e., move to position
804 if (new_pos_is_RTL) {
805 new_cur.pos() = left_pos + 1;
806 // set the boundary to true in two situations:
808 // 1. if new_pos is now lastpos and we're in
809 // an LTR paragraph (this means that we're
810 // moving left to the end of an RTL chunk
811 // which is at the end of an LTR paragraph);
812 (new_cur.pos() == lastpos()
813 && !paragraph().isRTL(buffer()->params()))
814 // 2. if the position *after* left_pos is not
815 // RTL (we want to be *after* left_pos, not
816 // before left_pos + 1!)
817 || !paragraph().getFontSettings(buffer()->params(),
818 new_cur.pos()).isVisibleRightToLeft()
820 new_cur.boundary(true);
821 else // set the boundary to false
822 new_cur.boundary(false);
824 // Otherwise (if the character at position 'left_pos'
825 // is LTR), then moving to the left of it is as easy
826 // as setting the new position to 'left_pos'.
828 new_cur.pos() = left_pos;
829 new_cur.boundary(false);
834 bool moved = (new_cur.pos() != pos()
835 || new_cur.pit() != pit()
836 || new_cur.boundary() != boundary());
839 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
840 << (new_cur.boundary() ? " (boundary)" : ""));
848 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos)
850 // preparing bidi tables
851 Paragraph const & par = paragraph();
852 Buffer const & buf = *buffer();
853 Row const & row = textRow();
855 bidi.computeTables(par, buf, row);
857 LYXERR(Debug::RTL, "bidi: " << row.pos() << "--" << row.endpos());
859 // The cursor is painted *before* the character at pos(), or,
860 // if 'boundary' is true, *after* the character at (pos() -
861 // 1). So we already have one known position around the
863 pos_type const known_pos = boundary() && pos() > 0 ? pos() - 1 : pos();
865 // edge case: if we're at the end of the paragraph, things are
866 // a little different (because lastpos is a position which
867 // does not really "exist" --- there's no character there
869 if (known_pos == lastpos()) {
870 if (par.isRTL(buf.params())) {
872 right_pos = bidi.vis2log(row.pos());
876 left_pos = bidi.vis2log(row.endpos() - 1);
881 // Whether 'known_pos' is to the left or to the right of the
882 // cursor depends on whether it is an RTL or LTR character...
883 bool const cur_is_RTL =
884 par.getFontSettings(buf.params(), known_pos).isVisibleRightToLeft();
885 // ... in the following manner:
886 // For an RTL character, "before"
887 // means "to the right" and "after" means "to the left"; and
888 // for LTR, it's the reverse. So, 'known_pos' is to the right
889 // of the cursor if (RTL && boundary) or (!RTL && !boundary):
890 bool const known_pos_on_right = cur_is_RTL == boundary();
892 // So we now know one of the positions surrounding the cursor.
893 // Let's determine the other one:
894 if (known_pos_on_right) {
895 right_pos = known_pos;
896 // *visual* position of 'left_pos':
897 pos_type v_left_pos = bidi.log2vis(right_pos) - 1;
898 // If the position we just identified as 'left_pos' is
899 // a "skipped separator" (a separator which is at the
900 // logical end of a row, except for the last row in a
901 // paragraph; such separators are not painted, so they
902 // "are not really there"; note that in bidi text,
903 // such a separator could appear visually in the
904 // middle of a row), set 'left_pos' to the *next*
905 // position to the left.
906 if (bidi.inRange(v_left_pos)
907 && bidi.vis2log(v_left_pos) + 1 == row.endpos()
908 && row.endpos() < lastpos()
909 && par.isSeparator(bidi.vis2log(v_left_pos)))
912 // calculate the logical position of 'left_pos', if in row
913 if (!bidi.inRange(v_left_pos))
916 left_pos = bidi.vis2log(v_left_pos);
917 // If the position we identified as 'right_pos' is a
918 // "skipped separator", set 'right_pos' to the *next*
919 // position to the right.
920 if (right_pos + 1 == row.endpos() && row.endpos() < lastpos()
921 && par.isSeparator(right_pos)) {
922 pos_type const v_right_pos = bidi.log2vis(right_pos) + 1;
923 if (!bidi.inRange(v_right_pos))
926 right_pos = bidi.vis2log(v_right_pos);
929 // known_pos is on the left
930 left_pos = known_pos;
931 // *visual* position of 'right_pos'
932 pos_type v_right_pos = bidi.log2vis(left_pos) + 1;
933 // If the position we just identified as 'right_pos'
934 // is a "skipped separator", set 'right_pos' to the
935 // *next* position to the right.
936 if (bidi.inRange(v_right_pos)
937 && bidi.vis2log(v_right_pos) + 1 == row.endpos()
938 && row.endpos() < lastpos()
939 && par.isSeparator(bidi.vis2log(v_right_pos)))
942 // calculate the logical position of 'right_pos', if in row
943 if (!bidi.inRange(v_right_pos))
946 right_pos = bidi.vis2log(v_right_pos);
947 // If the position we identified as 'left_pos' is a
948 // "skipped separator", set 'left_pos' to the *next*
949 // position to the left.
950 if (left_pos + 1 == row.endpos() && row.endpos() < lastpos()
951 && par.isSeparator(left_pos)) {
952 pos_type const v_left_pos = bidi.log2vis(left_pos) - 1;
953 if (!bidi.inRange(v_left_pos))
956 left_pos = bidi.vis2log(v_left_pos);
963 bool Cursor::posVisToNewRow(bool movingLeft)
965 Paragraph const & par = paragraph();
966 Buffer const & buf = *buffer();
967 Row const & row = textRow();
968 bool par_is_LTR = !par.isRTL(buf.params());
970 // Inside a table, determining whether to move to the next or
971 // previous row should be done based on the table's direction.
973 if (s >= 1 && (*this)[s].inset().asInsetTabular()) {
974 par_is_LTR = !(*this)[s].inset().asInsetTabular()->isRightToLeft(*this);
975 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
978 // if moving left in an LTR paragraph or moving right in an
979 // RTL one, move to previous row
980 if (par_is_LTR == movingLeft) {
981 if (row.pos() == 0) { // we're at first row in paragraph
982 if (pit() == 0) // no previous paragraph! don't move
984 // move to last pos in previous par
988 } else { // move to previous row in this par
989 pos() = row.pos() - 1; // this is guaranteed to be in previous row
993 // if moving left in an RTL paragraph or moving right in an
994 // LTR one, move to next row
996 if (row.endpos() == lastpos()) { // we're at last row in paragraph
997 if (pit() == lastpit()) // last paragraph! don't move
999 // move to first row in next par
1003 } else { // move to next row in this par
1004 pos() = row.endpos();
1009 // make sure we're at left-/right-most pos in new row
1010 posVisToRowExtremity(!movingLeft);
1016 void Cursor::posVisToRowExtremity(bool left)
1018 // prepare bidi tables
1019 Paragraph const & par = paragraph();
1020 Buffer const & buf = *buffer();
1021 Row const & row = textRow();
1023 bidi.computeTables(par, buf, row);
1025 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
1026 << (boundary() ? 1 : 0));
1028 if (left) { // move to leftmost position
1029 // if this is an RTL paragraph, and we're at the last row in the
1030 // paragraph, move to lastpos
1031 if (par.isRTL(buf.params()) && row.endpos() == lastpos())
1034 pos() = bidi.vis2log(row.pos());
1036 // Moving to the leftmost position in the row,
1037 // the cursor should normally be placed to the
1038 // *left* of the leftmost position. A very
1039 // common exception, though, is if the
1040 // leftmost character also happens to be the
1041 // separator at the (logical) end of the row
1042 // --- in this case, the separator is
1043 // positioned beyond the left margin, and we
1044 // don't want to move the cursor there (moving
1045 // to the left of the separator is equivalent
1046 // to moving to the next line). So, in this
1047 // case we actually want to place the cursor
1048 // to the *right* of the leftmost position
1049 // (the separator). Another exception is if
1050 // we're moving to the logically last position
1051 // in the row, which is *not* a separator:
1052 // this means that the entire row has no
1053 // separators (if there were any, the row
1054 // would have been broken there); and
1055 // therefore in this case we also move to the
1056 // *right* of the last position (this
1057 // indicates to the user that there is no
1058 // space after this position, and is
1059 // consistent with the behavior in the middle
1060 // of a row --- moving right or left moves to
1061 // the next/previous character; if we were to
1062 // move to the *left* of this position, that
1063 // would simulate a separator which is not
1064 // really there!). Finally, there is an
1065 // exception to the previous exception: if
1066 // this non-separator-but-last-position-in-row
1067 // is an inset, then we *do* want to stay to
1068 // the left of it anyway: this is the
1069 // "boundary" which we simulate at insets.
1071 // Another exception is when row.endpos() is
1074 // do we want to be to the right of pos?
1075 // as explained above, if at last pos in row, stay to the right
1076 bool const right_of_pos = row.endpos() > 0
1077 && pos() == row.endpos() - 1 && !par.isInset(pos());
1079 // Now we know if we want to be to the left or to the right of pos,
1080 // let's make sure we are where we want to be.
1081 bool const new_pos_is_RTL =
1082 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
1084 if (new_pos_is_RTL != right_of_pos) {
1090 // move to rightmost position
1091 // if this is an LTR paragraph, and we're at the last row in the
1092 // paragraph, move to lastpos
1093 if (!par.isRTL(buf.params()) && row.endpos() == lastpos())
1096 pos() = row.endpos() > 0 ? bidi.vis2log(row.endpos() - 1) : 0;
1098 // Moving to the rightmost position in the
1099 // row, the cursor should normally be placed
1100 // to the *right* of the rightmost position. A
1101 // very common exception, though, is if the
1102 // rightmost character also happens to be the
1103 // separator at the (logical) end of the row
1104 // --- in this case, the separator is
1105 // positioned beyond the right margin, and we
1106 // don't want to move the cursor there (moving
1107 // to the right of the separator is equivalent
1108 // to moving to the next line). So, in this
1109 // case we actually want to place the cursor
1110 // to the *left* of the rightmost position
1111 // (the separator). Another exception is if
1112 // we're moving to the logically last position
1113 // in the row, which is *not* a separator:
1114 // this means that the entire row has no
1115 // separators (if there were any, the row
1116 // would have been broken there); and
1117 // therefore in this case we also move to the
1118 // *left* of the last position (this indicates
1119 // to the user that there is no space after
1120 // this position, and is consistent with the
1121 // behavior in the middle of a row --- moving
1122 // right or left moves to the next/previous
1123 // character; if we were to move to the
1124 // *right* of this position, that would
1125 // simulate a separator which is not really
1126 // there!). Finally, there is an exception to
1127 // the previous exception: if this
1128 // non-separator-but-last-position-in-row is
1129 // an inset, then we *do* want to stay to the
1130 // right of it anyway: this is the "boundary"
1131 // which we simulate at insets. Another
1132 // exception is when row.endpos() is 0.
1134 // do we want to be to the left of pos?
1135 // as explained above, if at last pos in row, stay to the left,
1136 // unless the last position is the same as the first.
1137 bool const left_of_pos = row.endpos() > 0
1138 && pos() == row.endpos() - 1 && !par.isInset(pos());
1140 // Now we know if we want to be to the left or to the right of pos,
1141 // let's make sure we are where we want to be.
1142 bool const new_pos_is_RTL =
1143 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
1145 if (new_pos_is_RTL == left_of_pos) {
1151 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
1152 << (boundary() ? 1 : 0));
1156 CursorSlice Cursor::normalAnchor() const
1160 // LASSERT: There have been several bugs around this code, that seem
1161 // to involve failures to reset the anchor. We can at least not crash
1162 // in release mode by resetting it ourselves.
1163 LASSERT(anchor_.depth() >= depth(),
1164 const_cast<DocIterator &>(anchor_) = *this);
1166 CursorSlice normal = anchor_[depth() - 1];
1167 if (depth() < anchor_.depth() && top() <= normal) {
1168 // anchor is behind cursor -> move anchor behind the inset
1175 DocIterator & Cursor::realAnchor()
1181 CursorSlice Cursor::selBegin() const
1185 return normalAnchor() < top() ? normalAnchor() : top();
1189 CursorSlice Cursor::selEnd() const
1193 return normalAnchor() > top() ? normalAnchor() : top();
1197 DocIterator Cursor::selectionBegin() const
1203 // FIXME: This is a work-around for the problem that
1204 // CursorSlice doesn't keep track of the boundary.
1205 if (normalAnchor() == top())
1206 di = anchor_.boundary() > boundary() ? anchor_ : *this;
1208 di = normalAnchor() < top() ? anchor_ : *this;
1214 DocIterator Cursor::selectionEnd() const
1220 // FIXME: This is a work-around for the problem that
1221 // CursorSlice doesn't keep track of the boundary.
1222 if (normalAnchor() == top())
1223 di = anchor_.boundary() < boundary() ? anchor_ : *this;
1225 di = normalAnchor() > top() ? anchor_ : *this;
1227 if (di.depth() > depth()) {
1235 void Cursor::setSelection()
1238 if (idx() == normalAnchor().idx() &&
1239 pit() == normalAnchor().pit() &&
1240 pos() == normalAnchor().pos())
1241 setSelection(false);
1245 void Cursor::setSelection(DocIterator const & where, int n)
1254 void Cursor::clearSelection()
1256 setSelection(false);
1257 setWordSelection(false);
1263 void Cursor::setTargetX(int x)
1266 textTargetOffset_ = 0;
1270 int Cursor::x_target() const
1276 void Cursor::clearTargetX()
1279 textTargetOffset_ = 0;
1283 void Cursor::updateTextTargetOffset()
1288 textTargetOffset_ = x - x_target_;
1292 void Cursor::info(odocstream & os) const
1294 for (int i = 1, n = depth(); i < n; ++i) {
1295 operator[](i).inset().infoize(os);
1299 Inset const * inset = prevInset();
1300 // prevInset() can return 0 in certain case.
1302 prevInset()->infoize2(os);
1304 // overwite old message
1309 bool Cursor::selHandle(bool sel)
1311 //lyxerr << "Cursor::selHandle" << endl;
1314 if (sel == selection())
1318 cap::saveSelection(*this);
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();
2360 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2362 // find inset in common
2364 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2365 if (&old[i].inset() != &cur[i].inset())
2369 // update words if we just moved to another paragraph
2370 if (i == old.depth() && i == cur.depth()
2371 && !cur.buffer()->isClean()
2372 && cur.inTexted() && old.inTexted()
2373 && cur.pit() != old.pit()) {
2374 old.paragraph().updateWords();
2377 // notify everything on top of the common part in old cursor,
2378 // but stop if the inset claims the cursor to be invalid now
2379 for (size_type j = i; j < old.depth(); ++j) {
2380 Cursor inset_pos = old;
2381 inset_pos.cutOff(j);
2382 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2386 // notify everything on top of the common part in new cursor,
2387 // but stop if the inset claims the cursor to be invalid now
2388 for (; i < cur.depth(); ++i) {
2389 if (cur[i].inset().notifyCursorEnters(cur))
2397 void Cursor::setCurrentFont()
2399 CursorSlice const & cs = innerTextSlice();
2400 Paragraph const & par = cs.paragraph();
2401 pos_type cpit = cs.pit();
2402 pos_type cpos = cs.pos();
2403 Text const & ctext = *cs.text();
2404 TextMetrics const & tm = bv().textMetrics(&ctext);
2406 // are we behind previous char in fact? -> go to that char
2407 if (cpos > 0 && boundary())
2410 // find position to take the font from
2412 // paragraph end? -> font of last char
2413 if (cpos == lastpos())
2415 // on space? -> look at the words in front of space
2416 else if (cpos > 0 && par.isSeparator(cpos)) {
2417 // abc| def -> font of c
2418 // abc |[WERBEH], i.e. boundary==true -> font of c
2419 // abc [WERBEH]| def, font of the space
2420 if (!tm.isRTLBoundary(cpit, cpos))
2426 BufferParams const & bufparams = buffer()->params();
2427 current_font = par.getFontSettings(bufparams, cpos);
2428 real_current_font = tm.displayFont(cpit, cpos);
2430 // special case for paragraph end
2431 if (cs.pos() == lastpos()
2432 && tm.isRTLBoundary(cpit, cs.pos())
2434 Language const * lang = par.getParLanguage(bufparams);
2435 current_font.setLanguage(lang);
2436 current_font.fontInfo().setNumber(FONT_OFF);
2437 real_current_font.setLanguage(lang);
2438 real_current_font.fontInfo().setNumber(FONT_OFF);
2443 bool Cursor::textUndo()
2445 if (!buffer()->undo().textUndo(*this))
2452 bool Cursor::textRedo()
2454 if (!buffer()->undo().textRedo(*this))
2461 void Cursor::finishUndo() const
2463 buffer()->undo().finishUndo();
2467 void Cursor::beginUndoGroup() const
2469 buffer()->undo().beginUndoGroup();
2473 void Cursor::endUndoGroup() const
2475 buffer()->undo().endUndoGroup(*this);
2479 void Cursor::recordUndo(pit_type from, pit_type to) const
2481 buffer()->undo().recordUndo(*this, from, to);
2485 void Cursor::recordUndo(pit_type from) const
2487 buffer()->undo().recordUndo(*this, from, pit());
2491 void Cursor::recordUndo(UndoKind kind) const
2493 buffer()->undo().recordUndo(*this, kind);
2497 void Cursor::recordUndoInset(Inset const * in) const
2499 buffer()->undo().recordUndoInset(*this, in);
2503 void Cursor::recordUndoFullBuffer() const
2505 buffer()->undo().recordUndoFullBuffer(*this);
2509 void Cursor::recordUndoBufferParams() const
2511 buffer()->undo().recordUndoBufferParams(*this);
2515 void Cursor::recordUndoSelection() const
2518 if (cap::multipleCellsSelected(*this))
2523 buffer()->undo().recordUndo(*this,
2524 selBegin().pit(), selEnd().pit());
2529 void Cursor::checkBufferStructure()
2531 Buffer const * master = buffer()->masterBuffer();
2532 master->tocBackend().updateItem(*this);
2533 if (master != buffer() && !master->hasGuiDelegate())
2534 // In case the master has no gui associated with it,
2535 // the TocItem is not updated (part of bug 5699).
2536 buffer()->tocBackend().updateItem(*this);