3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alejandro Aguilar Sierra
7 * \author Alfredo Braunstein
8 * \author Dov Feldstern
10 * \author Stefan Schimanski
12 * Full author contact details are available in file CREDITS.
19 #include "BufferView.h"
20 #include "CoordCache.h"
22 #include "CutAndPaste.h"
23 #include "DispatchResult.h"
27 #include "FuncRequest.h"
30 #include "LyXAction.h"
32 #include "Paragraph.h"
33 #include "ParIterator.h"
36 #include "TextMetrics.h"
37 #include "TocBackend.h"
39 #include "support/lassert.h"
40 #include "support/debug.h"
41 #include "support/docstream.h"
43 #include "insets/InsetTabular.h"
44 #include "insets/InsetText.h"
46 #include "mathed/InsetMath.h"
47 #include "mathed/InsetMathBrace.h"
48 #include "mathed/InsetMathScript.h"
49 #include "mathed/MacroTable.h"
50 #include "mathed/MathData.h"
51 #include "mathed/MathMacro.h"
53 #include "support/bind.h"
66 bool positionable(DocIterator const & cursor, DocIterator const & anchor)
68 // avoid deeper nested insets when selecting
69 if (cursor.depth() > anchor.depth())
72 // anchor might be deeper, should have same path then
73 for (size_t i = 0; i < cursor.depth(); ++i)
74 if (&cursor[i].inset() != &anchor[i].inset())
77 // position should be ok.
82 // Find position closest to (x, y) in cell given by iter.
83 // Used only in mathed
84 DocIterator bruteFind2(Cursor const & c, int x, int y)
86 double best_dist = numeric_limits<double>::max();
93 et.top().pos() = et.top().asInsetMath()->cell(et.top().idx()).size();
94 for (size_t i = 0;; ++i) {
97 Inset const * inset = &it.inset();
98 CoordCache const & cache = c.bv().coordCache();
100 // FIXME: in the case where the inset is not in the cache, this
101 // means that no part of it is visible on screen. In this case
102 // we don't do elaborate search and we just return the forwarded
103 // DocIterator at its beginning.
104 if (!cache.getInsets().has(inset)) {
109 Point const o = cache.getInsets().xy(inset);
110 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
111 // Convert to absolute
114 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
115 // '<=' in order to take the last possible position
116 // this is important for clicking behind \sum in e.g. '\sum_i a'
117 LYXERR(Debug::DEBUG, "i: " << i << " d: " << d
118 << " best: " << best_dist);
119 if (d <= best_dist) {
132 /// moves position closest to (x, y) in given box
133 bool bruteFind(Cursor & cursor,
134 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
136 LASSERT(!cursor.empty(), return false);
137 Inset & inset = cursor[0].inset();
138 BufferView & bv = cursor.bv();
140 CoordCache::InnerParPosCache const & cache =
141 bv.coordCache().getParPos().find(cursor.bottom().text())->second;
142 // Get an iterator on the first paragraph in the cache
143 DocIterator it(inset);
144 it.push_back(CursorSlice(inset));
145 it.pit() = cache.begin()->first;
146 // Get an iterator after the last paragraph in the cache
147 DocIterator et(inset);
148 et.push_back(CursorSlice(inset));
149 et.pit() = boost::prior(cache.end())->first;
150 if (et.pit() >= et.lastpit())
151 et = doc_iterator_end(inset);
155 double best_dist = numeric_limits<double>::max();
156 DocIterator best_cursor = et;
158 for ( ; it != et; it.forwardPos(true)) {
159 // avoid invalid nesting when selecting
160 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
161 Point p = bv.getPos(it, false);
164 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
165 double const dx = xo - x;
166 double const dy = yo - y;
167 double const d = dx * dx + dy * dy;
168 // '<=' in order to take the last possible position
169 // this is important for clicking behind \sum in e.g. '\sum_i a'
170 if (d <= best_dist) {
171 // lyxerr << "*" << endl;
179 if (best_cursor != et) {
180 cursor.setCursor(best_cursor);
189 /// moves position closest to (x, y) in given box
190 bool bruteFind3(Cursor & cur, int x, int y, bool up)
192 BufferView & bv = cur.bv();
193 int ylow = up ? 0 : y + 1;
194 int yhigh = up ? y - 1 : bv.workHeight();
196 int xhigh = bv.workWidth();
198 // FIXME: bit more work needed to get 'from' and 'to' right.
199 pit_type from = cur.bottom().pit();
200 //pit_type to = cur.bottom().pit();
201 //lyxerr << "Pit start: " << from << endl;
203 //lyxerr << "bruteFind3: x: " << x << " y: " << y
204 // << " xlow: " << xlow << " xhigh: " << xhigh
205 // << " ylow: " << ylow << " yhigh: " << yhigh
207 DocIterator it = doc_iterator_begin(cur.buffer());
209 DocIterator et = doc_iterator_end(cur.buffer());
211 double best_dist = numeric_limits<double>::max();
212 DocIterator best_cursor = et;
214 for ( ; it != et; it.forwardPos()) {
215 // avoid invalid nesting when selecting
216 if (bv.cursorStatus(it) == CUR_INSIDE
217 && (!cur.selection() || positionable(it, cur.realAnchor()))) {
218 // If this function is ever used again, check
219 // whether this is the same as "bv.getPos(it,
220 // false)" with boundary = false.
221 Point p = bv.getPos(it);
224 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
225 double const dx = xo - x;
226 double const dy = yo - y;
227 double const d = dx * dx + dy * dy;
228 //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
229 // << " dx: " << dx << " dy: " << dy
230 // << " idx: " << it.idx() << " pos: " << it.pos()
233 // '<=' in order to take the last possible position
234 // this is important for clicking behind \sum in e.g. '\sum_i a'
235 if (d <= best_dist) {
236 //lyxerr << "*" << endl;
244 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
245 if (best_cursor == et)
247 cur.setCursor(best_cursor);
254 CursorData::CursorData()
255 : DocIterator(), anchor_(),
256 selection_(false), mark_(false), word_selection_(false),
257 logicalpos_(false), current_font(inherit_font)
261 CursorData::CursorData(Buffer * buffer)
262 : DocIterator(buffer), anchor_(),
263 selection_(false), mark_(false), word_selection_(false),
264 logicalpos_(false), current_font(inherit_font)
268 CursorData::CursorData(DocIterator const & dit)
269 : DocIterator(dit), anchor_(),
270 selection_(false), mark_(false), word_selection_(false),
271 logicalpos_(false), current_font(inherit_font)
275 // be careful: this is called from the bv's constructor, too, so
276 // bv functions are not yet available!
277 Cursor::Cursor(BufferView & bv)
278 : CursorData(&bv.buffer()), bv_(&bv),
279 x_target_(-1), textTargetOffset_(0)
286 push_back(CursorSlice(buffer()->inset()));
287 anchor_ = doc_iterator_begin(buffer());
289 new_word_ = doc_iterator_begin(buffer());
297 // this (intentionally) does neither touch anchor nor selection status
298 void Cursor::setCursor(DocIterator const & cur)
300 DocIterator::operator=(cur);
304 void Cursor::setCursorToAnchor()
307 DocIterator normal = anchor_;
308 while (depth() < normal.depth())
310 if (depth() < anchor_.depth() && top() <= anchor_[depth() - 1])
317 void Cursor::setCursorData(CursorData const & data)
319 CursorData::operator=(data);
323 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
327 // Try to fix cursor in case it is broken.
330 // Is this a function that acts on inset at point?
331 Inset * inset = cur.nextInset();
332 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
333 && inset && inset->getStatus(cur, cmd, status))
336 // This is, of course, a mess. Better create a new doc iterator and use
337 // this in Inset::getStatus. This might require an additional
338 // BufferView * arg, though (which should be avoided)
339 //Cursor safe = *this;
341 for ( ; cur.depth(); cur.pop()) {
342 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
343 LASSERT(cur.idx() <= cur.lastidx(), /**/);
344 LASSERT(cur.pit() <= cur.lastpit(), /**/);
345 LASSERT(cur.pos() <= cur.lastpos(), /**/);
347 // The inset's getStatus() will return 'true' if it made
348 // a definitive decision on whether it want to handle the
349 // request or not. The result of this decision is put into
350 // the 'status' parameter.
351 if (cur.inset().getStatus(cur, cmd, status)) {
360 void Cursor::saveBeforeDispatchPosXY()
362 getPos(beforeDispatchPosX_, beforeDispatchPosY_);
366 void Cursor::dispatch(FuncRequest const & cmd0)
368 LYXERR(Debug::DEBUG, "cmd: " << cmd0 << '\n' << *this);
373 FuncRequest cmd = cmd0;
376 disp_ = DispatchResult();
380 // Is this a function that acts on inset at point?
381 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
383 disp_.dispatched(true);
384 disp_.screenUpdate(Update::FitCursor | Update::Force);
385 FuncRequest tmpcmd = cmd;
386 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
387 << cmd0 << endl << *this);
388 nextInset()->dispatch(*this, tmpcmd);
389 if (disp_.dispatched()) {
395 // store some values to be used inside of the handlers
396 beforeDispatchCursor_ = *this;
397 for (; depth(); pop(), boundary(false)) {
398 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
399 << cmd0 << endl << *this);
400 LASSERT(pos() <= lastpos(), /**/);
401 LASSERT(idx() <= lastidx(), /**/);
402 LASSERT(pit() <= lastpit(), /**/);
404 // The common case is 'LFUN handled, need update', so make the
405 // LFUN handler's life easier by assuming this as default value.
406 // The handler can reset the update and val flags if necessary.
407 disp_.screenUpdate(Update::FitCursor | Update::Force);
408 disp_.dispatched(true);
409 inset().dispatch(*this, cmd);
410 if (disp_.dispatched())
414 // it completely to get a 'bomb early' behaviour in case this
415 // object will be used again.
416 if (!disp_.dispatched()) {
417 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
418 // We might have invalidated the cursor when removing an empty
419 // paragraph while the cursor could not be moved out the inset
420 // while we initially thought we could. This might happen when
421 // a multiline inset becomes an inline inset when the second
422 // paragraph is removed.
423 if (safe.pit() > safe.lastpit()) {
424 safe.pit() = safe.lastpit();
425 safe.pos() = safe.lastpos();
428 disp_.screenUpdate(Update::None);
429 disp_.dispatched(false);
431 // restore the previous one because nested Cursor::dispatch calls
432 // are possible which would change it
433 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
437 // notify insets we just left
439 old.beginUndoGroup();
441 bool badcursor = notifyCursorLeavesOrEnters(old, *this);
444 bv().resetInlineCompletionPos();
451 DispatchResult const & Cursor::result() const
457 BufferView & Cursor::bv() const
466 LASSERT(depth() >= 1, /**/);
471 void Cursor::push(Inset & p)
473 push_back(CursorSlice(p));
474 p.setBuffer(*buffer());
478 void Cursor::pushBackward(Inset & p)
480 LASSERT(!empty(), return);
481 //lyxerr << "Entering inset " << t << " front" << endl;
487 bool Cursor::popBackward()
489 LASSERT(!empty(), return false);
497 bool Cursor::popForward()
499 LASSERT(!empty(), return false);
500 //lyxerr << "Leaving inset from in back" << endl;
501 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
505 pos() += lastpos() - lp + 1;
510 int Cursor::currentMode()
512 LASSERT(!empty(), /**/);
513 for (int i = depth() - 1; i >= 0; --i) {
514 int res = operator[](i).inset().currentMode();
515 bool locked_mode = operator[](i).inset().lockedMode();
516 // Also return UNDECIDED_MODE when the mode is locked,
517 // as in this case it is treated the same as TEXT_MODE
518 if (res != Inset::UNDECIDED_MODE || locked_mode)
521 return Inset::TEXT_MODE;
525 void Cursor::getPos(int & x, int & y) const
527 Point p = bv().getPos(*this);
533 Row const & Cursor::textRow() const
535 CursorSlice const & cs = innerTextSlice();
536 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
537 LASSERT(!pm.rows().empty(), /**/);
538 return pm.getRow(pos(), boundary());
542 void Cursor::resetAnchor()
545 checkNewWordPosition();
549 void Cursor::markNewWordPosition()
551 if (lyxrc.spellcheck_continuously && inTexted() && new_word_.empty()) {
552 FontSpan nw = locateWord(WHOLE_WORD);
553 if (nw.size() == 1) {
554 LYXERR(Debug::DEBUG, "start new word: "
556 << " pos: " << nw.first);
563 void Cursor::clearNewWordPosition()
565 if (!new_word_.empty()) {
566 LYXERR(Debug::DEBUG, "clear new word: "
568 << " pos: " << pos());
574 void Cursor::checkNewWordPosition()
576 if (!lyxrc.spellcheck_continuously || new_word_.empty())
579 clearNewWordPosition();
581 // forget the position of the current new word if
582 // 1) the paragraph changes or
583 // 2) the count of nested insets changes or
584 // 3) the cursor pos is out of paragraph bound
585 if (pit() != new_word_.pit() ||
586 depth() != new_word_.depth() ||
587 new_word_.pos() > new_word_.lastpos()) {
588 clearNewWordPosition();
589 } else if (new_word_.fixIfBroken())
590 // 4) or the remembered position was "broken"
591 clearNewWordPosition();
593 FontSpan nw = locateWord(WHOLE_WORD);
595 FontSpan ow = new_word_.locateWord(WHOLE_WORD);
596 if (nw.intersect(ow).empty())
597 clearNewWordPosition();
599 LYXERR(Debug::DEBUG, "new word: "
601 << " pos: " << nw.first << ".." << nw.last);
603 clearNewWordPosition();
610 bool Cursor::posBackward()
619 bool Cursor::posForward()
621 if (pos() == lastpos())
628 bool Cursor::posVisRight(bool skip_inset)
630 Cursor new_cur = *this; // where we will move to
631 pos_type left_pos; // position visually left of current cursor
632 pos_type right_pos; // position visually right of current cursor
633 bool new_pos_is_RTL; // is new position we're moving to RTL?
635 getSurroundingPos(left_pos, right_pos);
637 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
639 // Are we at an inset?
640 new_cur.pos() = right_pos;
641 new_cur.boundary(false);
643 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
644 // we actually move the cursor at the end of this
645 // function, for now we just keep track of the new
646 // position in new_cur...
647 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
650 // Are we already at rightmost pos in row?
651 else if (text()->empty() || right_pos == -1) {
654 if (!new_cur.posVisToNewRow(false)) {
655 LYXERR(Debug::RTL, "not moving!");
659 // we actually move the cursor at the end of this
660 // function, for now just keep track of the new
661 // position in new_cur...
662 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
663 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
666 // normal movement to the right
669 // Recall, if the cursor is at position 'x', that
670 // means *before* the character at position 'x'. In
671 // RTL, "before" means "to the right of", in LTR, "to
672 // the left of". So currently our situation is this:
673 // the position to our right is 'right_pos' (i.e.,
674 // we're currently to the left of 'right_pos'). In
675 // order to move to the right, it depends whether or
676 // not the character at 'right_pos' is RTL.
677 new_pos_is_RTL = paragraph().getFontSettings(
678 buffer()->params(), right_pos).isVisibleRightToLeft();
679 // If the character at 'right_pos' *is* LTR, then in
680 // order to move to the right of it, we need to be
681 // *after* 'right_pos', i.e., move to position
683 if (!new_pos_is_RTL) {
684 new_cur.pos() = right_pos + 1;
685 // set the boundary to true in two situations:
687 // 1. if new_pos is now lastpos, and we're in
688 // an RTL paragraph (this means that we're
689 // moving right to the end of an LTR chunk
690 // which is at the end of an RTL paragraph);
691 (new_cur.pos() == lastpos()
692 && paragraph().isRTL(buffer()->params()))
693 // 2. if the position *after* right_pos is RTL
694 // (we want to be *after* right_pos, not
695 // before right_pos + 1!)
696 || paragraph().getFontSettings(buffer()->params(),
697 new_cur.pos()).isVisibleRightToLeft()
699 new_cur.boundary(true);
700 else // set the boundary to false
701 new_cur.boundary(false);
703 // Otherwise (if the character at position 'right_pos'
704 // is RTL), then moving to the right of it is as easy
705 // as setting the new position to 'right_pos'.
707 new_cur.pos() = right_pos;
708 new_cur.boundary(false);
713 bool moved = (new_cur.pos() != pos()
714 || new_cur.pit() != pit()
715 || new_cur.boundary() != boundary()
716 || &new_cur.inset() != &inset());
719 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
720 << (new_cur.boundary() ? " (boundary)" : ""));
728 bool Cursor::posVisLeft(bool skip_inset)
730 Cursor new_cur = *this; // where we will move to
731 pos_type left_pos; // position visually left of current cursor
732 pos_type right_pos; // position visually right of current cursor
733 bool new_pos_is_RTL; // is new position we're moving to RTL?
735 getSurroundingPos(left_pos, right_pos);
737 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
739 // Are we at an inset?
740 new_cur.pos() = left_pos;
741 new_cur.boundary(false);
743 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
744 // we actually move the cursor at the end of this
745 // function, for now we just keep track of the new
746 // position in new_cur...
747 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
750 // Are we already at leftmost pos in row?
751 else if (text()->empty() || left_pos == -1) {
754 if (!new_cur.posVisToNewRow(true)) {
755 LYXERR(Debug::RTL, "not moving!");
759 // we actually move the cursor at the end of this
760 // function, for now just keep track of the new
761 // position in new_cur...
762 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
763 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
766 // normal movement to the left
769 // Recall, if the cursor is at position 'x', that
770 // means *before* the character at position 'x'. In
771 // RTL, "before" means "to the right of", in LTR, "to
772 // the left of". So currently our situation is this:
773 // the position to our left is 'left_pos' (i.e., we're
774 // currently to the right of 'left_pos'). In order to
775 // move to the left, it depends whether or not the
776 // character at 'left_pos' is RTL.
777 new_pos_is_RTL = paragraph().getFontSettings(
778 buffer()->params(), left_pos).isVisibleRightToLeft();
779 // If the character at 'left_pos' *is* RTL, then in
780 // order to move to the left of it, we need to be
781 // *after* 'left_pos', i.e., move to position
783 if (new_pos_is_RTL) {
784 new_cur.pos() = left_pos + 1;
785 // set the boundary to true in two situations:
787 // 1. if new_pos is now lastpos and we're in
788 // an LTR paragraph (this means that we're
789 // moving left to the end of an RTL chunk
790 // which is at the end of an LTR paragraph);
791 (new_cur.pos() == lastpos()
792 && !paragraph().isRTL(buffer()->params()))
793 // 2. if the position *after* left_pos is not
794 // RTL (we want to be *after* left_pos, not
795 // before left_pos + 1!)
796 || !paragraph().getFontSettings(buffer()->params(),
797 new_cur.pos()).isVisibleRightToLeft()
799 new_cur.boundary(true);
800 else // set the boundary to false
801 new_cur.boundary(false);
803 // Otherwise (if the character at position 'left_pos'
804 // is LTR), then moving to the left of it is as easy
805 // as setting the new position to 'left_pos'.
807 new_cur.pos() = left_pos;
808 new_cur.boundary(false);
813 bool moved = (new_cur.pos() != pos()
814 || new_cur.pit() != pit()
815 || new_cur.boundary() != boundary());
818 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
819 << (new_cur.boundary() ? " (boundary)" : ""));
827 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos)
829 // preparing bidi tables
830 Paragraph const & par = paragraph();
831 Buffer const & buf = *buffer();
832 Row const & row = textRow();
834 bidi.computeTables(par, buf, row);
836 LYXERR(Debug::RTL, "bidi: " << row.pos() << "--" << row.endpos());
838 // The cursor is painted *before* the character at pos(), or,
839 // if 'boundary' is true, *after* the character at (pos() -
840 // 1). So we already have one known position around the
842 pos_type const known_pos = boundary() && pos() > 0 ? pos() - 1 : pos();
844 // edge case: if we're at the end of the paragraph, things are
845 // a little different (because lastpos is a position which
846 // does not really "exist" --- there's no character there
848 if (known_pos == lastpos()) {
849 if (par.isRTL(buf.params())) {
851 right_pos = bidi.vis2log(row.pos());
855 left_pos = bidi.vis2log(row.endpos() - 1);
860 // Whether 'known_pos' is to the left or to the right of the
861 // cursor depends on whether it is an RTL or LTR character...
862 bool const cur_is_RTL =
863 par.getFontSettings(buf.params(), known_pos).isVisibleRightToLeft();
864 // ... in the following manner:
865 // For an RTL character, "before"
866 // means "to the right" and "after" means "to the left"; and
867 // for LTR, it's the reverse. So, 'known_pos' is to the right
868 // of the cursor if (RTL && boundary) or (!RTL && !boundary):
869 bool const known_pos_on_right = cur_is_RTL == boundary();
871 // So we now know one of the positions surrounding the cursor.
872 // Let's determine the other one:
873 if (known_pos_on_right) {
874 right_pos = known_pos;
875 // *visual* position of 'left_pos':
876 pos_type v_left_pos = bidi.log2vis(right_pos) - 1;
877 // If the position we just identified as 'left_pos' is
878 // a "skipped separator" (a separator which is at the
879 // logical end of a row, except for the last row in a
880 // paragraph; such separators are not painted, so they
881 // "are not really there"; note that in bidi text,
882 // such a separator could appear visually in the
883 // middle of a row), set 'left_pos' to the *next*
884 // position to the left.
885 if (bidi.inRange(v_left_pos)
886 && bidi.vis2log(v_left_pos) + 1 == row.endpos()
887 && row.endpos() < lastpos()
888 && par.isSeparator(bidi.vis2log(v_left_pos)))
891 // calculate the logical position of 'left_pos', if in row
892 if (!bidi.inRange(v_left_pos))
895 left_pos = bidi.vis2log(v_left_pos);
896 // If the position we identified as 'right_pos' is a
897 // "skipped separator", set 'right_pos' to the *next*
898 // position to the right.
899 if (right_pos + 1 == row.endpos() && row.endpos() < lastpos()
900 && par.isSeparator(right_pos)) {
901 pos_type const v_right_pos = bidi.log2vis(right_pos) + 1;
902 if (!bidi.inRange(v_right_pos))
905 right_pos = bidi.vis2log(v_right_pos);
908 // known_pos is on the left
909 left_pos = known_pos;
910 // *visual* position of 'right_pos'
911 pos_type v_right_pos = bidi.log2vis(left_pos) + 1;
912 // If the position we just identified as 'right_pos'
913 // is a "skipped separator", set 'right_pos' to the
914 // *next* position to the right.
915 if (bidi.inRange(v_right_pos)
916 && bidi.vis2log(v_right_pos) + 1 == row.endpos()
917 && row.endpos() < lastpos()
918 && par.isSeparator(bidi.vis2log(v_right_pos)))
921 // calculate the logical position of 'right_pos', if in row
922 if (!bidi.inRange(v_right_pos))
925 right_pos = bidi.vis2log(v_right_pos);
926 // If the position we identified as 'left_pos' is a
927 // "skipped separator", set 'left_pos' to the *next*
928 // position to the left.
929 if (left_pos + 1 == row.endpos() && row.endpos() < lastpos()
930 && par.isSeparator(left_pos)) {
931 pos_type const v_left_pos = bidi.log2vis(left_pos) - 1;
932 if (!bidi.inRange(v_left_pos))
935 left_pos = bidi.vis2log(v_left_pos);
942 bool Cursor::posVisToNewRow(bool movingLeft)
944 Paragraph const & par = paragraph();
945 Buffer const & buf = *buffer();
946 Row const & row = textRow();
947 bool par_is_LTR = !par.isRTL(buf.params());
949 // Inside a table, determining whether to move to the next or
950 // previous row should be done based on the table's direction.
952 if (s >= 1 && (*this)[s].inset().asInsetTabular()) {
953 par_is_LTR = !(*this)[s].inset().asInsetTabular()->isRightToLeft(*this);
954 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
957 // if moving left in an LTR paragraph or moving right in an
958 // RTL one, move to previous row
959 if (par_is_LTR == movingLeft) {
960 if (row.pos() == 0) { // we're at first row in paragraph
961 if (pit() == 0) // no previous paragraph! don't move
963 // move to last pos in previous par
967 } else { // move to previous row in this par
968 pos() = row.pos() - 1; // this is guaranteed to be in previous row
972 // if moving left in an RTL paragraph or moving right in an
973 // LTR one, move to next row
975 if (row.endpos() == lastpos()) { // we're at last row in paragraph
976 if (pit() == lastpit()) // last paragraph! don't move
978 // move to first row in next par
982 } else { // move to next row in this par
983 pos() = row.endpos();
988 // make sure we're at left-/right-most pos in new row
989 posVisToRowExtremity(!movingLeft);
995 void Cursor::posVisToRowExtremity(bool left)
997 // prepare bidi tables
998 Paragraph const & par = paragraph();
999 Buffer const & buf = *buffer();
1000 Row const & row = textRow();
1002 bidi.computeTables(par, buf, row);
1004 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
1005 << (boundary() ? 1 : 0));
1007 if (left) { // move to leftmost position
1008 // if this is an RTL paragraph, and we're at the last row in the
1009 // paragraph, move to lastpos
1010 if (par.isRTL(buf.params()) && row.endpos() == lastpos())
1013 pos() = bidi.vis2log(row.pos());
1015 // Moving to the leftmost position in the row,
1016 // the cursor should normally be placed to the
1017 // *left* of the leftmost position. A very
1018 // common exception, though, is if the
1019 // leftmost character also happens to be the
1020 // separator at the (logical) end of the row
1021 // --- in this case, the separator is
1022 // positioned beyond the left margin, and we
1023 // don't want to move the cursor there (moving
1024 // to the left of the separator is equivalent
1025 // to moving to the next line). So, in this
1026 // case we actually want to place the cursor
1027 // to the *right* of the leftmost position
1028 // (the separator). Another exception is if
1029 // we're moving to the logically last position
1030 // in the row, which is *not* a separator:
1031 // this means that the entire row has no
1032 // separators (if there were any, the row
1033 // would have been broken there); and
1034 // therefore in this case we also move to the
1035 // *right* of the last position (this
1036 // indicates to the user that there is no
1037 // space after this position, and is
1038 // consistent with the behavior in the middle
1039 // of a row --- moving right or left moves to
1040 // the next/previous character; if we were to
1041 // move to the *left* of this position, that
1042 // would simulate a separator which is not
1043 // really there!). Finally, there is an
1044 // exception to the previous exception: if
1045 // this non-separator-but-last-position-in-row
1046 // is an inset, then we *do* want to stay to
1047 // the left of it anyway: this is the
1048 // "boundary" which we simulate at insets.
1050 // Another exception is when row.endpos() is
1053 // do we want to be to the right of pos?
1054 // as explained above, if at last pos in row, stay to the right
1055 bool const right_of_pos = row.endpos() > 0
1056 && pos() == row.endpos() - 1 && !par.isInset(pos());
1058 // Now we know if we want to be to the left or to the right of pos,
1059 // let's make sure we are where we want to be.
1060 bool const new_pos_is_RTL =
1061 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
1063 if (new_pos_is_RTL != right_of_pos) {
1069 // move to rightmost position
1070 // if this is an LTR paragraph, and we're at the last row in the
1071 // paragraph, move to lastpos
1072 if (!par.isRTL(buf.params()) && row.endpos() == lastpos())
1075 pos() = row.endpos() > 0 ? bidi.vis2log(row.endpos() - 1) : 0;
1077 // Moving to the rightmost position in the
1078 // row, the cursor should normally be placed
1079 // to the *right* of the rightmost position. A
1080 // very common exception, though, is if the
1081 // rightmost character also happens to be the
1082 // separator at the (logical) end of the row
1083 // --- in this case, the separator is
1084 // positioned beyond the right margin, and we
1085 // don't want to move the cursor there (moving
1086 // to the right of the separator is equivalent
1087 // to moving to the next line). So, in this
1088 // case we actually want to place the cursor
1089 // to the *left* of the rightmost position
1090 // (the separator). Another exception is if
1091 // we're moving to the logically last position
1092 // in the row, which is *not* a separator:
1093 // this means that the entire row has no
1094 // separators (if there were any, the row
1095 // would have been broken there); and
1096 // therefore in this case we also move to the
1097 // *left* of the last position (this indicates
1098 // to the user that there is no space after
1099 // this position, and is consistent with the
1100 // behavior in the middle of a row --- moving
1101 // right or left moves to the next/previous
1102 // character; if we were to move to the
1103 // *right* of this position, that would
1104 // simulate a separator which is not really
1105 // there!). Finally, there is an exception to
1106 // the previous exception: if this
1107 // non-separator-but-last-position-in-row is
1108 // an inset, then we *do* want to stay to the
1109 // right of it anyway: this is the "boundary"
1110 // which we simulate at insets. Another
1111 // exception is when row.endpos() is 0.
1113 // do we want to be to the left of pos?
1114 // as explained above, if at last pos in row, stay to the left,
1115 // unless the last position is the same as the first.
1116 bool const left_of_pos = row.endpos() > 0
1117 && pos() == row.endpos() - 1 && !par.isInset(pos());
1119 // Now we know if we want to be to the left or to the right of pos,
1120 // let's make sure we are where we want to be.
1121 bool const new_pos_is_RTL =
1122 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
1124 if (new_pos_is_RTL == left_of_pos) {
1130 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
1131 << (boundary() ? 1 : 0));
1135 CursorSlice Cursor::normalAnchor() const
1139 LASSERT(anchor_.depth() >= depth(), /**/);
1140 CursorSlice normal = anchor_[depth() - 1];
1141 if (depth() < anchor_.depth() && top() <= normal) {
1142 // anchor is behind cursor -> move anchor behind the inset
1149 DocIterator & Cursor::realAnchor()
1155 CursorSlice Cursor::selBegin() const
1159 return normalAnchor() < top() ? normalAnchor() : top();
1163 CursorSlice Cursor::selEnd() const
1167 return normalAnchor() > top() ? normalAnchor() : top();
1171 DocIterator Cursor::selectionBegin() const
1177 // FIXME: This is a work-around for the problem that
1178 // CursorSlice doesn't keep track of the boundary.
1179 if (normalAnchor() == top())
1180 di = anchor_.boundary() > boundary() ? anchor_ : *this;
1182 di = normalAnchor() < top() ? anchor_ : *this;
1188 DocIterator Cursor::selectionEnd() const
1194 // FIXME: This is a work-around for the problem that
1195 // CursorSlice doesn't keep track of the boundary.
1196 if (normalAnchor() == top())
1197 di = anchor_.boundary() < boundary() ? anchor_ : *this;
1199 di = normalAnchor() > top() ? anchor_ : *this;
1201 if (di.depth() > depth()) {
1209 void Cursor::setSelection()
1212 // A selection with no contents is not a selection
1213 // FIXME: doesnt look ok
1214 if (idx() == normalAnchor().idx() &&
1215 pit() == normalAnchor().pit() &&
1216 pos() == normalAnchor().pos())
1217 setSelection(false);
1221 void Cursor::setSelection(DocIterator const & where, int n)
1230 void Cursor::clearSelection()
1232 setSelection(false);
1233 setWordSelection(false);
1239 void Cursor::setTargetX(int x)
1242 textTargetOffset_ = 0;
1246 int Cursor::x_target() const
1252 void Cursor::clearTargetX()
1255 textTargetOffset_ = 0;
1259 void Cursor::updateTextTargetOffset()
1264 textTargetOffset_ = x - x_target_;
1268 void Cursor::info(odocstream & os) const
1270 for (int i = 1, n = depth(); i < n; ++i) {
1271 operator[](i).inset().infoize(os);
1275 Inset const * inset = prevInset();
1276 // prevInset() can return 0 in certain case.
1278 prevInset()->infoize2(os);
1280 // overwite old message
1285 bool Cursor::selHandle(bool sel)
1287 //lyxerr << "Cursor::selHandle" << endl;
1290 if (sel == selection())
1294 cap::saveSelection(*this);
1302 ostream & operator<<(ostream & os, Cursor const & cur)
1304 os << "\n cursor: | anchor:\n";
1305 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
1306 os << " " << cur[i] << " | ";
1307 if (i < cur.anchor_.depth())
1308 os << cur.anchor_[i];
1310 os << "-------------------------------";
1313 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
1314 os << "------------------------------- | " << cur.anchor_[i] << "\n";
1316 os << " selection: " << cur.selection_
1317 << " x_target: " << cur.x_target_ << endl;
1322 LyXErr & operator<<(LyXErr & os, Cursor const & cur)
1332 ///////////////////////////////////////////////////////////////////
1335 // The part below is the non-integrated rest of the original math
1336 // cursor. This should be either generalized for texted or moved
1337 // back to mathed (in most cases to InsetMathNest).
1339 ///////////////////////////////////////////////////////////////////
1341 #include "mathed/InsetMathChar.h"
1342 #include "mathed/InsetMathGrid.h"
1343 #include "mathed/InsetMathScript.h"
1344 #include "mathed/InsetMathUnknown.h"
1345 #include "mathed/MathFactory.h"
1346 #include "mathed/MathStream.h"
1347 #include "mathed/MathSupport.h"
1352 bool Cursor::isInside(Inset const * p) const
1354 for (size_t i = 0; i != depth(); ++i)
1355 if (&operator[](i).inset() == p)
1361 void Cursor::leaveInset(Inset const & inset)
1363 for (size_t i = 0; i != depth(); ++i) {
1364 if (&operator[](i).inset() == &inset) {
1372 bool Cursor::openable(MathAtom const & t) const
1383 // we can't move into anything new during selection
1384 if (depth() >= anchor_.depth())
1386 if (t.nucleus() != &anchor_[depth()].inset())
1393 void Cursor::setScreenPos(int x, int /*y*/)
1396 //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
1401 void Cursor::plainErase()
1403 cell().erase(pos());
1407 void Cursor::markInsert()
1409 insert(char_type(0));
1413 void Cursor::markErase()
1415 cell().erase(pos());
1419 void Cursor::plainInsert(MathAtom const & t)
1421 cell().insert(pos(), t);
1423 inset().setBuffer(bv_->buffer());
1425 forceBufferUpdate();
1429 void Cursor::insert(docstring const & str)
1431 for_each(str.begin(), str.end(),
1432 bind(static_cast<void(Cursor::*)(char_type)>
1433 (&Cursor::insert), this, _1));
1437 void Cursor::insert(char_type c)
1439 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1440 LASSERT(!empty(), /**/);
1442 cap::selClearOrDel(*this);
1443 insert(new InsetMathChar(c));
1445 text()->insertChar(*this, c);
1450 void Cursor::insert(MathAtom const & t)
1452 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1454 cap::selClearOrDel(*this);
1459 void Cursor::insert(Inset * inset0)
1461 LASSERT(inset0, /**/);
1463 insert(MathAtom(inset0->asInsetMath()));
1465 text()->insertInset(*this, inset0);
1466 inset0->setBuffer(bv_->buffer());
1468 if (inset0->isLabeled())
1469 forceBufferUpdate();
1474 int Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1476 MathData ar(buffer());
1478 if (ar.size() == 1 && (enter || selection()))
1486 void Cursor::niceInsert(MathAtom const & t)
1489 docstring const safe = cap::grabAndEraseSelection(*this);
1491 // If possible, enter the new inset and move the contents of the selection
1492 if (t->isActive()) {
1494 // be careful here: don't use 'pushBackward(t)' as this we need to
1495 // push the clone, not the original
1496 pushBackward(*nextInset());
1497 // We may not use niceInsert here (recursion)
1498 MathData ar(buffer());
1501 } else if (t->asMacro() && !safe.empty()) {
1502 MathData ar(buffer());
1504 docstring const name = t->asMacro()->name();
1505 MacroData const * data = buffer()->getMacro(name);
1506 if (data && data->numargs() - data->optionals() > 0) {
1507 plainInsert(MathAtom(new InsetMathBrace(ar)));
1514 void Cursor::insert(MathData const & ar)
1518 cap::eraseSelection(*this);
1519 cell().insert(pos(), ar);
1521 // FIXME audit setBuffer calls
1522 inset().setBuffer(bv_->buffer());
1526 bool Cursor::backspace()
1528 autocorrect() = false;
1531 cap::eraseSelection(*this);
1536 // If empty cell, and not part of a big cell
1537 if (lastpos() == 0 && inset().nargs() == 1) {
1539 // Directly delete empty cell: [|[]] => [|]
1545 // [|], can not delete from inside
1556 if (inMacroMode()) {
1557 InsetMathUnknown * p = activeMacro();
1558 if (p->name().size() > 1) {
1559 p->setName(p->name().substr(0, p->name().size() - 1));
1564 if (pos() != 0 && prevAtom()->nargs() > 0) {
1565 // let's require two backspaces for 'big stuff' and
1566 // highlight on the first
1578 bool Cursor::erase()
1580 autocorrect() = false;
1585 cap::eraseSelection(*this);
1589 // delete empty cells if possible
1590 if (pos() == lastpos() && inset().idxDelete(idx()))
1593 // special behaviour when in last position of cell
1594 if (pos() == lastpos()) {
1595 bool one_cell = inset().nargs() == 1;
1596 if (one_cell && lastpos() == 0) {
1598 // Directly delete empty cell: [|[]] => [|]
1604 // [|], can not delete from inside
1609 inset().idxGlue(idx());
1613 // 'clever' UI hack: only erase large items if previously slected
1614 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
1629 DocIterator save = *this;
1630 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1631 this->dispatch(cmd);
1632 if (disp_.dispatched())
1635 autocorrect() = false;
1643 DocIterator save = *this;
1644 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1645 this->dispatch(cmd);
1646 if (disp_.dispatched())
1649 autocorrect() = false;
1654 bool Cursor::macroModeClose()
1658 InsetMathUnknown * p = activeMacro();
1660 MathData selection(buffer());
1661 asArray(p->selection(), selection);
1662 docstring const s = p->name();
1664 cell().erase(pos());
1666 // do nothing if the macro name is empty
1670 // trigger updates of macros, at least, if no full
1671 // updates take place anyway
1672 screenUpdateFlags(Update::Force);
1674 docstring const name = s.substr(1);
1675 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1676 if (in && in->interpretString(*this, s))
1678 MathAtom atom = buffer()->getMacro(name, *this, false) ?
1679 MathAtom(new MathMacro(buffer(), name)) : createInsetMath(name, buffer());
1681 // try to put argument into macro, if we just inserted a macro
1682 bool macroArg = false;
1683 MathMacro * atomAsMacro = atom.nucleus()->asMacro();
1685 // macros here are still unfolded (in init mode in fact). So
1686 // we have to resolve the macro here manually and check its arity
1687 // to put the selection behind it if arity > 0.
1688 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1689 if (!selection.empty() && data && data->numargs() - data->optionals() > 0) {
1691 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1693 // non-greedy case. Do not touch the arguments behind
1694 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1697 // insert remembered selection into first argument of a non-macro
1698 else if (atom.nucleus()->nargs() > 0)
1699 atom.nucleus()->cell(0).append(selection);
1703 // finally put the macro argument behind, if needed
1705 if (selection.size() > 1 || selection[0]->asScriptInset())
1706 plainInsert(MathAtom(new InsetMathBrace(selection)));
1715 docstring Cursor::macroName()
1717 return inMacroMode() ? activeMacro()->name() : docstring();
1721 void Cursor::handleNest(MathAtom const & a, int c)
1723 //lyxerr << "Cursor::handleNest: " << c << endl;
1725 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1728 pushBackward(*nextInset());
1732 int Cursor::targetX() const
1734 if (x_target() != -1)
1743 int Cursor::textTargetOffset() const
1745 return textTargetOffset_;
1749 void Cursor::setTargetX()
1758 bool Cursor::inMacroMode() const
1762 if (pos() == 0 || cell().empty())
1764 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1765 return p && !p->final();
1769 InsetMathUnknown * Cursor::activeMacro()
1771 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1775 InsetMathUnknown const * Cursor::activeMacro() const
1777 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1781 void Cursor::pullArg()
1784 MathData ar = cell();
1785 if (popBackward() && inMathed()) {
1787 cell().insert(pos(), ar);
1790 //formula()->mutateToText();
1795 void Cursor::touch()
1799 DocIterator::const_iterator it = begin();
1800 DocIterator::const_iterator et = end();
1801 for ( ; it != et; ++it)
1807 void Cursor::normalize()
1809 if (idx() > lastidx()) {
1810 lyxerr << "this should not really happen - 1: "
1811 << idx() << ' ' << nargs()
1812 << " in: " << &inset() << endl;
1816 if (pos() > lastpos()) {
1817 lyxerr << "this should not really happen - 2: "
1818 << pos() << ' ' << lastpos() << " in idx: " << idx()
1820 odocstringstream os;
1821 WriteStream wi(os, false, true, WriteStream::wsDefault);
1822 inset().asInsetMath()->write(wi);
1823 lyxerr << to_utf8(os.str()) << endl;
1829 bool Cursor::upDownInMath(bool up)
1831 // Be warned: The 'logic' implemented in this function is highly
1832 // fragile. A distance of one pixel or a '<' vs '<=' _really
1833 // matters. So fiddle around with it only if you think you know
1834 // what you are doing!
1838 xo = beforeDispatchPosX_;
1840 // check if we had something else in mind, if not, this is the future
1842 if (x_target_ == -1)
1844 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1845 // In text mode inside the line (not left or right) possibly set a new target_x,
1846 // but only if we are somewhere else than the previous target-offset.
1848 // We want to keep the x-target on subsequent up/down movements
1849 // that cross beyond the end of short lines. Thus a special
1850 // handling when the cursor is at the end of line: Use the new
1851 // x-target only if the old one was before the end of line
1852 // or the old one was after the beginning of the line
1853 bool inRTL = isWithinRtlParagraph(*this);
1857 left = pos() == textRow().endpos();
1858 right = pos() == textRow().pos();
1860 left = pos() == textRow().pos();
1861 right = pos() == textRow().endpos();
1863 if ((!left && !right) ||
1864 (left && !right && xo < x_target_) ||
1865 (!left && right && x_target_ < xo))
1872 // try neigbouring script insets
1874 if (inMathed() && !selection()) {
1877 InsetMathScript const * p = prevAtom()->asScriptInset();
1878 if (p && p->has(up)) {
1880 push(*const_cast<InsetMathScript*>(p));
1881 idx() = p->idxOfScript(up);
1884 // we went in the right direction? Otherwise don't jump into the script
1888 int oy = beforeDispatchPosY_;
1889 if ((!up && y <= oy) ||
1898 if (pos() != lastpos()) {
1899 InsetMathScript const * p = nextAtom()->asScriptInset();
1900 if (p && p->has(up)) {
1901 push(*const_cast<InsetMathScript*>(p));
1902 idx() = p->idxOfScript(up);
1905 // we went in the right direction? Otherwise don't jump into the script
1909 int oy = beforeDispatchPosY_;
1910 if ((!up && y <= oy) ||
1919 // try to find an inset that knows better then we,
1920 if (inset().idxUpDown(*this, up)) {
1921 //lyxerr << "idxUpDown triggered" << endl;
1922 // try to find best position within this inset
1924 setCursor(bruteFind2(*this, xo, yo));
1928 // any improvement going just out of inset?
1929 if (popBackward() && inMathed()) {
1930 //lyxerr << "updown: popBackward succeeded" << endl;
1933 int yold = beforeDispatchPosY_;
1935 if (up ? ynew < yold : ynew > yold)
1939 // no success, we are probably at the document top or bottom
1945 bool Cursor::atFirstOrLastRow(bool up)
1947 TextMetrics const & tm = bv_->textMetrics(text());
1948 ParagraphMetrics const & pm = tm.parMetrics(pit());
1951 if (pos() && boundary())
1952 row = pm.pos2row(pos() - 1);
1954 row = pm.pos2row(pos());
1957 if (pit() == 0 && row == 0)
1960 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1961 row + 1 >= int(pm.rows().size()))
1968 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1970 LASSERT(text(), /**/);
1976 xo = beforeDispatchPosX_;
1978 // update the targetX - this is here before the "return false"
1979 // to set a new target which can be used by InsetTexts above
1980 // if we cannot move up/down inside this inset anymore
1981 if (x_target_ == -1)
1983 else if (xo - textTargetOffset() != x_target() &&
1984 depth() == beforeDispatchCursor_.depth()) {
1985 // In text mode inside the line (not left or right)
1986 // possibly set a new target_x, but only if we are
1987 // somewhere else than the previous target-offset.
1989 // We want to keep the x-target on subsequent up/down
1990 // movements that cross beyond the end of short lines.
1991 // Thus a special handling when the cursor is at the
1992 // end of line: Use the new x-target only if the old
1993 // one was before the end of line or the old one was
1994 // after the beginning of the line
1995 bool inRTL = isWithinRtlParagraph(*this);
1999 left = pos() == textRow().endpos();
2000 right = pos() == textRow().pos();
2002 left = pos() == textRow().pos();
2003 right = pos() == textRow().endpos();
2005 if ((!left && !right) ||
2006 (left && !right && xo < x_target_) ||
2007 (!left && right && x_target_ < xo))
2014 // first get the current line
2015 TextMetrics & tm = bv_->textMetrics(text());
2016 ParagraphMetrics const & pm = tm.parMetrics(pit());
2018 if (pos() && boundary())
2019 row = pm.pos2row(pos() - 1);
2021 row = pm.pos2row(pos());
2023 if (atFirstOrLastRow(up)) {
2024 // Is there a place for the cursor to go ? If yes, we
2025 // can execute the DEPM, otherwise we should keep the
2026 // paragraph to host the cursor.
2027 Cursor dummy = *this;
2028 bool valid_destination = false;
2029 for(; dummy.depth(); dummy.pop())
2030 if (!dummy.atFirstOrLastRow(up)) {
2031 valid_destination = true;
2035 // will a next dispatch follow and if there is a new
2036 // dispatch will it move the cursor out ?
2037 if (depth() > 1 && valid_destination) {
2038 // The cursor hasn't changed yet. This happens when
2039 // you e.g. move out of an inset. And to give the
2040 // DEPM the possibility of doing something we must
2041 // provide it with two different cursors. (Lgb, vfr)
2043 dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
2044 dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
2046 updateNeeded |= bv().checkDepm(dummy, *this);
2047 updateTextTargetOffset();
2049 forceBufferUpdate();
2050 // DEPM may have requested a screen update
2051 this->screenUpdateFlags(
2052 this->screenUpdate() | dummy.screenUpdate());
2058 // with and without selection are handled differently
2060 int yo = bv().getPos(*this).y_;
2062 // To next/previous row
2064 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
2066 tm.editXY(*this, xo, yo + textRow().descent() + 1);
2069 // This happens when you move out of an inset.
2070 // And to give the DEPM the possibility of doing
2071 // something we must provide it with two different
2073 Cursor dummy = *this;
2076 if (bv().checkDepm(dummy, old)) {
2077 updateNeeded = true;
2078 // Make sure that cur gets back whatever happened to dummy (Lgb)
2079 // This will include any screen update requested by DEPM
2083 // if there is a selection, we stay out of any inset,
2084 // and just jump to the right position:
2090 } else if (pit() > 0) {
2092 TextMetrics & tm = bv_->textMetrics(text());
2093 if (!tm.contains(pit()))
2094 tm.newParMetricsUp();
2095 ParagraphMetrics const & pmcur = tm.parMetrics(pit());
2096 next_row = pmcur.rows().size() - 1;
2099 if (row + 1 < int(pm.rows().size())) {
2101 } else if (pit() + 1 < int(text()->paragraphs().size())) {
2103 TextMetrics & tm = bv_->textMetrics(text());
2104 if (!tm.contains(pit()))
2105 tm.newParMetricsDown();
2109 top().pos() = min(tm.x2pos(pit(), next_row, xo), top().lastpos());
2111 int const xpos = tm.x2pos(pit(), next_row, xo);
2112 bool const at_end_row = xpos == tm.x2pos(pit(), next_row, tm.width());
2113 bool const at_beg_row = xpos == tm.x2pos(pit(), next_row, 0);
2115 if (at_end_row && at_beg_row)
2116 // make sure the cursor ends up on this row
2119 boundary(at_end_row);
2121 updateNeeded |= bv().checkDepm(*this, old);
2125 forceBufferUpdate();
2126 updateTextTargetOffset();
2131 void Cursor::handleFont(string const & font)
2133 LYXERR(Debug::DEBUG, font);
2137 safe = cap::grabAndEraseSelection(*this);
2142 if (lastpos() != 0) {
2143 // something left in the cell
2145 // cursor in first position
2147 } else if (pos() == lastpos()) {
2148 // cursor in last position
2151 // cursor in between. split cell
2152 MathData::iterator bt = cell().begin();
2153 MathAtom at = createInsetMath(from_utf8(font), buffer());
2154 at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
2155 cell().erase(bt, bt + pos());
2160 // nothing left in the cell
2169 void Cursor::message(docstring const & msg) const
2171 disp_.setMessage(msg);
2175 void Cursor::errorMessage(docstring const & msg) const
2177 disp_.setMessage(msg);
2178 disp_.setError(true);
2184 docstring parbreak(Cursor const * cur)
2186 odocstringstream os;
2188 // only add blank line if we're not in a ParbreakIsNewline situation
2189 if (!cur->inset().getLayout().parbreakIsNewline()
2190 && !cur->paragraph().layout().parbreak_is_newline)
2198 docstring Cursor::selectionAsString(bool with_label) const
2204 return cap::grabSelection(*this);
2206 int const label = with_label
2207 ? AS_STR_LABEL | AS_STR_INSETS : AS_STR_INSETS;
2209 idx_type const startidx = selBegin().idx();
2210 idx_type const endidx = selEnd().idx();
2211 if (startidx != endidx) {
2212 // multicell selection
2213 InsetTabular * table = inset().asInsetTabular();
2214 LASSERT(table, return docstring());
2215 return table->asString(startidx, endidx);
2218 ParagraphList const & pars = text()->paragraphs();
2220 pit_type const startpit = selBegin().pit();
2221 pit_type const endpit = selEnd().pit();
2222 size_t const startpos = selBegin().pos();
2223 size_t const endpos = selEnd().pos();
2225 if (startpit == endpit)
2226 return pars[startpit].asString(startpos, endpos, label);
2228 // First paragraph in selection
2229 docstring result = pars[startpit].
2230 asString(startpos, pars[startpit].size(), label)
2233 // The paragraphs in between (if any)
2234 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
2235 Paragraph const & par = pars[pit];
2236 result += par.asString(0, par.size(), label)
2240 // Last paragraph in selection
2241 result += pars[endpit].asString(0, endpos, label);
2247 docstring Cursor::currentState() const
2250 odocstringstream os;
2256 return text()->currentState(*this);
2262 docstring Cursor::getPossibleLabel() const
2264 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
2268 Encoding const * Cursor::getEncoding() const
2272 CursorSlice const & sl = innerTextSlice();
2273 Text const & text = *sl.text();
2274 Font font = text.getPar(sl.pit()).getFont(
2275 bv().buffer().params(), sl.pos(), text.outerFont(sl.pit()));
2276 return font.language()->encoding();
2280 void Cursor::undispatched() const
2282 disp_.dispatched(false);
2286 void Cursor::dispatched() const
2288 disp_.dispatched(true);
2292 void Cursor::screenUpdateFlags(Update::flags f) const
2294 disp_.screenUpdate(f);
2298 void Cursor::forceBufferUpdate() const
2300 disp_.forceBufferUpdate();
2304 void Cursor::clearBufferUpdate() const
2306 disp_.clearBufferUpdate();
2310 bool Cursor::needBufferUpdate() const
2312 return disp_.needBufferUpdate();
2316 void Cursor::noScreenUpdate() const
2318 disp_.screenUpdate(Update::None);
2322 Font Cursor::getFont() const
2324 // The logic here should more or less match to the
2325 // Cursor::setCurrentFont logic, i.e. the cursor height should
2326 // give a hint what will happen if a character is entered.
2328 // HACK. far from being perfect...
2330 CursorSlice const & sl = innerTextSlice();
2331 Text const & text = *sl.text();
2332 Paragraph const & par = text.getPar(sl.pit());
2334 // on boundary, so we are really at the character before
2335 pos_type pos = sl.pos();
2336 if (pos > 0 && boundary())
2339 // on space? Take the font before (only for RTL boundary stay)
2341 TextMetrics const & tm = bv().textMetrics(&text);
2342 if (pos == sl.lastpos()
2343 || (par.isSeparator(pos)
2344 && !tm.isRTLBoundary(sl.pit(), pos)))
2348 // get font at the position
2349 Font font = par.getFont(buffer()->params(), pos,
2350 text.outerFont(sl.pit()));
2356 bool Cursor::fixIfBroken()
2358 bool const broken_cursor = DocIterator::fixIfBroken();
2359 bool const broken_anchor = anchor_.fixIfBroken();
2361 if (broken_cursor || broken_anchor) {
2362 clearNewWordPosition();
2370 void Cursor::sanitize()
2372 setBuffer(&bv_->buffer());
2373 DocIterator::sanitize();
2378 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2380 // find inset in common
2382 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2383 if (&old[i].inset() != &cur[i].inset())
2387 // update words if we just moved to another paragraph
2388 if (i == old.depth() && i == cur.depth()
2389 && !cur.buffer()->isClean()
2390 && cur.inTexted() && old.inTexted()
2391 && cur.pit() != old.pit()) {
2392 old.paragraph().updateWords();
2395 // notify everything on top of the common part in old cursor,
2396 // but stop if the inset claims the cursor to be invalid now
2397 for (size_type j = i; j < old.depth(); ++j) {
2398 Cursor inset_pos = old;
2399 inset_pos.cutOff(j);
2400 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2404 // notify everything on top of the common part in new cursor,
2405 // but stop if the inset claims the cursor to be invalid now
2406 for (; i < cur.depth(); ++i) {
2407 if (cur[i].inset().notifyCursorEnters(cur))
2415 void Cursor::setCurrentFont()
2417 CursorSlice const & cs = innerTextSlice();
2418 Paragraph const & par = cs.paragraph();
2419 pos_type cpit = cs.pit();
2420 pos_type cpos = cs.pos();
2421 Text const & ctext = *cs.text();
2422 TextMetrics const & tm = bv().textMetrics(&ctext);
2424 // are we behind previous char in fact? -> go to that char
2425 if (cpos > 0 && boundary())
2428 // find position to take the font from
2430 // paragraph end? -> font of last char
2431 if (cpos == lastpos())
2433 // on space? -> look at the words in front of space
2434 else if (cpos > 0 && par.isSeparator(cpos)) {
2435 // abc| def -> font of c
2436 // abc |[WERBEH], i.e. boundary==true -> font of c
2437 // abc [WERBEH]| def, font of the space
2438 if (!tm.isRTLBoundary(cpit, cpos))
2444 BufferParams const & bufparams = buffer()->params();
2445 current_font = par.getFontSettings(bufparams, cpos);
2446 real_current_font = tm.displayFont(cpit, cpos);
2448 // special case for paragraph end
2449 if (cs.pos() == lastpos()
2450 && tm.isRTLBoundary(cpit, cs.pos())
2452 Language const * lang = par.getParLanguage(bufparams);
2453 current_font.setLanguage(lang);
2454 current_font.fontInfo().setNumber(FONT_OFF);
2455 real_current_font.setLanguage(lang);
2456 real_current_font.fontInfo().setNumber(FONT_OFF);
2461 bool Cursor::textUndo()
2463 if (!buffer()->undo().textUndo(*this))
2470 bool Cursor::textRedo()
2472 if (!buffer()->undo().textRedo(*this))
2479 void Cursor::finishUndo() const
2481 buffer()->undo().finishUndo();
2485 void Cursor::beginUndoGroup() const
2487 buffer()->undo().beginUndoGroup();
2491 void Cursor::endUndoGroup() const
2493 buffer()->undo().endUndoGroup(*this);
2497 void Cursor::recordUndo(UndoKind kind, pit_type from, pit_type to) const
2499 buffer()->undo().recordUndo(*this, kind, from, to);
2503 void Cursor::recordUndo(UndoKind kind, pit_type from) const
2505 buffer()->undo().recordUndo(*this, kind, from);
2509 void Cursor::recordUndo(UndoKind kind) const
2511 buffer()->undo().recordUndo(*this, kind);
2515 void Cursor::recordUndoInset(UndoKind kind, Inset const * inset) const
2517 buffer()->undo().recordUndoInset(*this, kind, inset);
2521 void Cursor::recordUndoFullDocument() const
2523 buffer()->undo().recordUndoFullDocument(*this);
2527 void Cursor::recordUndoSelection() const
2530 if (cap::multipleCellsSelected(*this))
2535 buffer()->undo().recordUndo(*this, ATOMIC_UNDO,
2536 selBegin().pit(), selEnd().pit());
2541 void Cursor::checkBufferStructure()
2543 Buffer const * master = buffer()->masterBuffer();
2544 master->tocBackend().updateItem(*this);
2545 if (master != buffer() && !master->hasGuiDelegate())
2546 // In case the master has no gui associated with it,
2547 // the TocItem is not updated (part of bug 5699).
2548 buffer()->tocBackend().updateItem(*this);