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());
295 // this (intentionally) does neither touch anchor nor selection status
296 void Cursor::setCursor(DocIterator const & cur)
298 DocIterator::operator=(cur);
302 void Cursor::setCursorToAnchor()
305 DocIterator normal = anchor_;
306 while (depth() < normal.depth())
308 if (depth() < anchor_.depth() && top() <= anchor_[depth() - 1])
315 void Cursor::setCursorData(CursorData const & data)
317 CursorData::operator=(data);
321 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
325 // Try to fix cursor in case it is broken.
328 // Is this a function that acts on inset at point?
329 Inset * inset = cur.nextInset();
330 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
331 && inset && inset->getStatus(cur, cmd, status))
334 // This is, of course, a mess. Better create a new doc iterator and use
335 // this in Inset::getStatus. This might require an additional
336 // BufferView * arg, though (which should be avoided)
337 //Cursor safe = *this;
339 for ( ; cur.depth(); cur.pop()) {
340 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
341 LASSERT(cur.idx() <= cur.lastidx(), /**/);
342 LASSERT(cur.pit() <= cur.lastpit(), /**/);
343 LASSERT(cur.pos() <= cur.lastpos(), /**/);
345 // The inset's getStatus() will return 'true' if it made
346 // a definitive decision on whether it want to handle the
347 // request or not. The result of this decision is put into
348 // the 'status' parameter.
349 if (cur.inset().getStatus(cur, cmd, status)) {
358 void Cursor::saveBeforeDispatchPosXY()
360 getPos(beforeDispatchPosX_, beforeDispatchPosY_);
364 void Cursor::dispatch(FuncRequest const & cmd0)
366 LYXERR(Debug::DEBUG, "cmd: " << cmd0 << '\n' << *this);
371 FuncRequest cmd = cmd0;
374 disp_ = DispatchResult();
378 // Is this a function that acts on inset at point?
379 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
381 disp_.dispatched(true);
382 disp_.screenUpdate(Update::FitCursor | Update::Force);
383 FuncRequest tmpcmd = cmd;
384 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
385 << cmd0 << endl << *this);
386 nextInset()->dispatch(*this, tmpcmd);
387 if (disp_.dispatched()) {
393 // store some values to be used inside of the handlers
394 beforeDispatchCursor_ = *this;
395 for (; depth(); pop(), boundary(false)) {
396 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
397 << cmd0 << endl << *this);
398 LASSERT(pos() <= lastpos(), /**/);
399 LASSERT(idx() <= lastidx(), /**/);
400 LASSERT(pit() <= lastpit(), /**/);
402 // The common case is 'LFUN handled, need update', so make the
403 // LFUN handler's life easier by assuming this as default value.
404 // The handler can reset the update and val flags if necessary.
405 disp_.screenUpdate(Update::FitCursor | Update::Force);
406 disp_.dispatched(true);
407 inset().dispatch(*this, cmd);
408 if (disp_.dispatched())
412 // it completely to get a 'bomb early' behaviour in case this
413 // object will be used again.
414 if (!disp_.dispatched()) {
415 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
416 // We might have invalidated the cursor when removing an empty
417 // paragraph while the cursor could not be moved out the inset
418 // while we initially thought we could. This might happen when
419 // a multiline inset becomes an inline inset when the second
420 // paragraph is removed.
421 if (safe.pit() > safe.lastpit()) {
422 safe.pit() = safe.lastpit();
423 safe.pos() = safe.lastpos();
426 disp_.screenUpdate(Update::None);
427 disp_.dispatched(false);
429 // restore the previous one because nested Cursor::dispatch calls
430 // are possible which would change it
431 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
435 // notify insets we just left
437 old.beginUndoGroup();
439 bool badcursor = notifyCursorLeavesOrEnters(old, *this);
442 bv().resetInlineCompletionPos();
449 DispatchResult const & Cursor::result() const
455 BufferView & Cursor::bv() const
464 LASSERT(depth() >= 1, /**/);
469 void Cursor::push(Inset & p)
471 push_back(CursorSlice(p));
472 p.setBuffer(*buffer());
476 void Cursor::pushBackward(Inset & p)
478 LASSERT(!empty(), return);
479 //lyxerr << "Entering inset " << t << " front" << endl;
485 bool Cursor::popBackward()
487 LASSERT(!empty(), return false);
495 bool Cursor::popForward()
497 LASSERT(!empty(), return false);
498 //lyxerr << "Leaving inset from in back" << endl;
499 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
503 pos() += lastpos() - lp + 1;
508 int Cursor::currentMode()
510 LASSERT(!empty(), /**/);
511 for (int i = depth() - 1; i >= 0; --i) {
512 int res = operator[](i).inset().currentMode();
513 bool locked_mode = operator[](i).inset().lockedMode();
514 // Also return UNDECIDED_MODE when the mode is locked,
515 // as in this case it is treated the same as TEXT_MODE
516 if (res != Inset::UNDECIDED_MODE || locked_mode)
519 return Inset::TEXT_MODE;
523 void Cursor::getPos(int & x, int & y) const
525 Point p = bv().getPos(*this);
531 Row const & Cursor::textRow() const
533 CursorSlice const & cs = innerTextSlice();
534 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
535 LASSERT(!pm.rows().empty(), /**/);
536 return pm.getRow(pos(), boundary());
540 void Cursor::resetAnchor()
543 checkNewWordPosition();
547 void Cursor::markNewWordPosition()
549 if (lyxrc.spellcheck_continuously && inTexted() && new_word_.empty()) {
550 FontSpan nw = locateWord(WHOLE_WORD);
551 if (nw.size() == 1) {
552 LYXERR(Debug::DEBUG, "start new word: "
554 << " pos: " << nw.first);
561 void Cursor::clearNewWordPosition()
563 if (!new_word_.empty()) {
564 LYXERR(Debug::DEBUG, "clear new word: "
566 << " pos: " << pos());
572 void Cursor::checkNewWordPosition()
574 if (!lyxrc.spellcheck_continuously || new_word_.empty())
577 clearNewWordPosition();
579 // forget the position of the current new word if
580 // 1) the paragraph changes or
581 // 2) the count of nested insets changes or
582 // 3) the cursor pos is out of paragraph bound
583 if (pit() != new_word_.pit() ||
584 depth() != new_word_.depth() ||
585 new_word_.pos() > new_word_.lastpos()) {
586 clearNewWordPosition();
587 } else if (new_word_.fixIfBroken())
588 // 4) or the remembered position was "broken"
589 clearNewWordPosition();
591 FontSpan nw = locateWord(WHOLE_WORD);
593 FontSpan ow = new_word_.locateWord(WHOLE_WORD);
594 if (nw.intersect(ow).empty())
595 clearNewWordPosition();
597 LYXERR(Debug::DEBUG, "new word: "
599 << " pos: " << nw.first << ".." << nw.last);
601 clearNewWordPosition();
608 bool Cursor::posBackward()
617 bool Cursor::posForward()
619 if (pos() == lastpos())
626 bool Cursor::posVisRight(bool skip_inset)
628 Cursor new_cur = *this; // where we will move to
629 pos_type left_pos; // position visually left of current cursor
630 pos_type right_pos; // position visually right of current cursor
631 bool new_pos_is_RTL; // is new position we're moving to RTL?
633 getSurroundingPos(left_pos, right_pos);
635 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
637 // Are we at an inset?
638 new_cur.pos() = right_pos;
639 new_cur.boundary(false);
641 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
642 // we actually move the cursor at the end of this
643 // function, for now we just keep track of the new
644 // position in new_cur...
645 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
648 // Are we already at rightmost pos in row?
649 else if (text()->empty() || right_pos == -1) {
652 if (!new_cur.posVisToNewRow(false)) {
653 LYXERR(Debug::RTL, "not moving!");
657 // we actually move the cursor at the end of this
658 // function, for now just keep track of the new
659 // position in new_cur...
660 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
661 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
664 // normal movement to the right
667 // Recall, if the cursor is at position 'x', that
668 // means *before* the character at position 'x'. In
669 // RTL, "before" means "to the right of", in LTR, "to
670 // the left of". So currently our situation is this:
671 // the position to our right is 'right_pos' (i.e.,
672 // we're currently to the left of 'right_pos'). In
673 // order to move to the right, it depends whether or
674 // not the character at 'right_pos' is RTL.
675 new_pos_is_RTL = paragraph().getFontSettings(
676 buffer()->params(), right_pos).isVisibleRightToLeft();
677 // If the character at 'right_pos' *is* LTR, then in
678 // order to move to the right of it, we need to be
679 // *after* 'right_pos', i.e., move to position
681 if (!new_pos_is_RTL) {
682 new_cur.pos() = right_pos + 1;
683 // set the boundary to true in two situations:
685 // 1. if new_pos is now lastpos, and we're in
686 // an RTL paragraph (this means that we're
687 // moving right to the end of an LTR chunk
688 // which is at the end of an RTL paragraph);
689 (new_cur.pos() == lastpos()
690 && paragraph().isRTL(buffer()->params()))
691 // 2. if the position *after* right_pos is RTL
692 // (we want to be *after* right_pos, not
693 // before right_pos + 1!)
694 || paragraph().getFontSettings(buffer()->params(),
695 new_cur.pos()).isVisibleRightToLeft()
697 new_cur.boundary(true);
698 else // set the boundary to false
699 new_cur.boundary(false);
701 // Otherwise (if the character at position 'right_pos'
702 // is RTL), then moving to the right of it is as easy
703 // as setting the new position to 'right_pos'.
705 new_cur.pos() = right_pos;
706 new_cur.boundary(false);
711 bool moved = (new_cur.pos() != pos()
712 || new_cur.pit() != pit()
713 || new_cur.boundary() != boundary()
714 || &new_cur.inset() != &inset());
717 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
718 << (new_cur.boundary() ? " (boundary)" : ""));
726 bool Cursor::posVisLeft(bool skip_inset)
728 Cursor new_cur = *this; // where we will move to
729 pos_type left_pos; // position visually left of current cursor
730 pos_type right_pos; // position visually right of current cursor
731 bool new_pos_is_RTL; // is new position we're moving to RTL?
733 getSurroundingPos(left_pos, right_pos);
735 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
737 // Are we at an inset?
738 new_cur.pos() = left_pos;
739 new_cur.boundary(false);
741 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
742 // we actually move the cursor at the end of this
743 // function, for now we just keep track of the new
744 // position in new_cur...
745 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
748 // Are we already at leftmost pos in row?
749 else if (text()->empty() || left_pos == -1) {
752 if (!new_cur.posVisToNewRow(true)) {
753 LYXERR(Debug::RTL, "not moving!");
757 // we actually move the cursor at the end of this
758 // function, for now just keep track of the new
759 // position in new_cur...
760 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
761 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
764 // normal movement to the left
767 // Recall, if the cursor is at position 'x', that
768 // means *before* the character at position 'x'. In
769 // RTL, "before" means "to the right of", in LTR, "to
770 // the left of". So currently our situation is this:
771 // the position to our left is 'left_pos' (i.e., we're
772 // currently to the right of 'left_pos'). In order to
773 // move to the left, it depends whether or not the
774 // character at 'left_pos' is RTL.
775 new_pos_is_RTL = paragraph().getFontSettings(
776 buffer()->params(), left_pos).isVisibleRightToLeft();
777 // If the character at 'left_pos' *is* RTL, then in
778 // order to move to the left of it, we need to be
779 // *after* 'left_pos', i.e., move to position
781 if (new_pos_is_RTL) {
782 new_cur.pos() = left_pos + 1;
783 // set the boundary to true in two situations:
785 // 1. if new_pos is now lastpos and we're in
786 // an LTR paragraph (this means that we're
787 // moving left to the end of an RTL chunk
788 // which is at the end of an LTR paragraph);
789 (new_cur.pos() == lastpos()
790 && !paragraph().isRTL(buffer()->params()))
791 // 2. if the position *after* left_pos is not
792 // RTL (we want to be *after* left_pos, not
793 // before left_pos + 1!)
794 || !paragraph().getFontSettings(buffer()->params(),
795 new_cur.pos()).isVisibleRightToLeft()
797 new_cur.boundary(true);
798 else // set the boundary to false
799 new_cur.boundary(false);
801 // Otherwise (if the character at position 'left_pos'
802 // is LTR), then moving to the left of it is as easy
803 // as setting the new position to 'left_pos'.
805 new_cur.pos() = left_pos;
806 new_cur.boundary(false);
811 bool moved = (new_cur.pos() != pos()
812 || new_cur.pit() != pit()
813 || new_cur.boundary() != boundary());
816 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
817 << (new_cur.boundary() ? " (boundary)" : ""));
825 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos)
827 // preparing bidi tables
828 Paragraph const & par = paragraph();
829 Buffer const & buf = *buffer();
830 Row const & row = textRow();
832 bidi.computeTables(par, buf, row);
834 LYXERR(Debug::RTL, "bidi: " << row.pos() << "--" << row.endpos());
836 // The cursor is painted *before* the character at pos(), or,
837 // if 'boundary' is true, *after* the character at (pos() -
838 // 1). So we already have one known position around the
840 pos_type const known_pos = boundary() && pos() > 0 ? pos() - 1 : pos();
842 // edge case: if we're at the end of the paragraph, things are
843 // a little different (because lastpos is a position which
844 // does not really "exist" --- there's no character there
846 if (known_pos == lastpos()) {
847 if (par.isRTL(buf.params())) {
849 right_pos = bidi.vis2log(row.pos());
853 left_pos = bidi.vis2log(row.endpos() - 1);
858 // Whether 'known_pos' is to the left or to the right of the
859 // cursor depends on whether it is an RTL or LTR character...
860 bool const cur_is_RTL =
861 par.getFontSettings(buf.params(), known_pos).isVisibleRightToLeft();
862 // ... in the following manner:
863 // For an RTL character, "before"
864 // means "to the right" and "after" means "to the left"; and
865 // for LTR, it's the reverse. So, 'known_pos' is to the right
866 // of the cursor if (RTL && boundary) or (!RTL && !boundary):
867 bool const known_pos_on_right = cur_is_RTL == boundary();
869 // So we now know one of the positions surrounding the cursor.
870 // Let's determine the other one:
871 if (known_pos_on_right) {
872 right_pos = known_pos;
873 // *visual* position of 'left_pos':
874 pos_type v_left_pos = bidi.log2vis(right_pos) - 1;
875 // If the position we just identified as 'left_pos' is
876 // a "skipped separator" (a separator which is at the
877 // logical end of a row, except for the last row in a
878 // paragraph; such separators are not painted, so they
879 // "are not really there"; note that in bidi text,
880 // such a separator could appear visually in the
881 // middle of a row), set 'left_pos' to the *next*
882 // position to the left.
883 if (bidi.inRange(v_left_pos)
884 && bidi.vis2log(v_left_pos) + 1 == row.endpos()
885 && row.endpos() < lastpos()
886 && par.isSeparator(bidi.vis2log(v_left_pos)))
889 // calculate the logical position of 'left_pos', if in row
890 if (!bidi.inRange(v_left_pos))
893 left_pos = bidi.vis2log(v_left_pos);
894 // If the position we identified as 'right_pos' is a
895 // "skipped separator", set 'right_pos' to the *next*
896 // position to the right.
897 if (right_pos + 1 == row.endpos() && row.endpos() < lastpos()
898 && par.isSeparator(right_pos)) {
899 pos_type const v_right_pos = bidi.log2vis(right_pos) + 1;
900 if (!bidi.inRange(v_right_pos))
903 right_pos = bidi.vis2log(v_right_pos);
906 // known_pos is on the left
907 left_pos = known_pos;
908 // *visual* position of 'right_pos'
909 pos_type v_right_pos = bidi.log2vis(left_pos) + 1;
910 // If the position we just identified as 'right_pos'
911 // is a "skipped separator", set 'right_pos' to the
912 // *next* position to the right.
913 if (bidi.inRange(v_right_pos)
914 && bidi.vis2log(v_right_pos) + 1 == row.endpos()
915 && row.endpos() < lastpos()
916 && par.isSeparator(bidi.vis2log(v_right_pos)))
919 // calculate the logical position of 'right_pos', if in row
920 if (!bidi.inRange(v_right_pos))
923 right_pos = bidi.vis2log(v_right_pos);
924 // If the position we identified as 'left_pos' is a
925 // "skipped separator", set 'left_pos' to the *next*
926 // position to the left.
927 if (left_pos + 1 == row.endpos() && row.endpos() < lastpos()
928 && par.isSeparator(left_pos)) {
929 pos_type const v_left_pos = bidi.log2vis(left_pos) - 1;
930 if (!bidi.inRange(v_left_pos))
933 left_pos = bidi.vis2log(v_left_pos);
940 bool Cursor::posVisToNewRow(bool movingLeft)
942 Paragraph const & par = paragraph();
943 Buffer const & buf = *buffer();
944 Row const & row = textRow();
945 bool par_is_LTR = !par.isRTL(buf.params());
947 // Inside a table, determining whether to move to the next or
948 // previous row should be done based on the table's direction.
950 if (s >= 1 && (*this)[s].inset().asInsetTabular()) {
951 par_is_LTR = !(*this)[s].inset().asInsetTabular()->isRightToLeft(*this);
952 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
955 // if moving left in an LTR paragraph or moving right in an
956 // RTL one, move to previous row
957 if (par_is_LTR == movingLeft) {
958 if (row.pos() == 0) { // we're at first row in paragraph
959 if (pit() == 0) // no previous paragraph! don't move
961 // move to last pos in previous par
965 } else { // move to previous row in this par
966 pos() = row.pos() - 1; // this is guaranteed to be in previous row
970 // if moving left in an RTL paragraph or moving right in an
971 // LTR one, move to next row
973 if (row.endpos() == lastpos()) { // we're at last row in paragraph
974 if (pit() == lastpit()) // last paragraph! don't move
976 // move to first row in next par
980 } else { // move to next row in this par
981 pos() = row.endpos();
986 // make sure we're at left-/right-most pos in new row
987 posVisToRowExtremity(!movingLeft);
993 void Cursor::posVisToRowExtremity(bool left)
995 // prepare bidi tables
996 Paragraph const & par = paragraph();
997 Buffer const & buf = *buffer();
998 Row const & row = textRow();
1000 bidi.computeTables(par, buf, row);
1002 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
1003 << (boundary() ? 1 : 0));
1005 if (left) { // move to leftmost position
1006 // if this is an RTL paragraph, and we're at the last row in the
1007 // paragraph, move to lastpos
1008 if (par.isRTL(buf.params()) && row.endpos() == lastpos())
1011 pos() = bidi.vis2log(row.pos());
1013 // Moving to the leftmost position in the row,
1014 // the cursor should normally be placed to the
1015 // *left* of the leftmost position. A very
1016 // common exception, though, is if the
1017 // leftmost character also happens to be the
1018 // separator at the (logical) end of the row
1019 // --- in this case, the separator is
1020 // positioned beyond the left margin, and we
1021 // don't want to move the cursor there (moving
1022 // to the left of the separator is equivalent
1023 // to moving to the next line). So, in this
1024 // case we actually want to place the cursor
1025 // to the *right* of the leftmost position
1026 // (the separator). Another exception is if
1027 // we're moving to the logically last position
1028 // in the row, which is *not* a separator:
1029 // this means that the entire row has no
1030 // separators (if there were any, the row
1031 // would have been broken there); and
1032 // therefore in this case we also move to the
1033 // *right* of the last position (this
1034 // indicates to the user that there is no
1035 // space after this position, and is
1036 // consistent with the behavior in the middle
1037 // of a row --- moving right or left moves to
1038 // the next/previous character; if we were to
1039 // move to the *left* of this position, that
1040 // would simulate a separator which is not
1041 // really there!). Finally, there is an
1042 // exception to the previous exception: if
1043 // this non-separator-but-last-position-in-row
1044 // is an inset, then we *do* want to stay to
1045 // the left of it anyway: this is the
1046 // "boundary" which we simulate at insets.
1048 // Another exception is when row.endpos() is
1051 // do we want to be to the right of pos?
1052 // as explained above, if at last pos in row, stay to the right
1053 bool const right_of_pos = row.endpos() > 0
1054 && pos() == row.endpos() - 1 && !par.isInset(pos());
1056 // Now we know if we want to be to the left or to the right of pos,
1057 // let's make sure we are where we want to be.
1058 bool const new_pos_is_RTL =
1059 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
1061 if (new_pos_is_RTL != right_of_pos) {
1067 // move to rightmost position
1068 // if this is an LTR paragraph, and we're at the last row in the
1069 // paragraph, move to lastpos
1070 if (!par.isRTL(buf.params()) && row.endpos() == lastpos())
1073 pos() = row.endpos() > 0 ? bidi.vis2log(row.endpos() - 1) : 0;
1075 // Moving to the rightmost position in the
1076 // row, the cursor should normally be placed
1077 // to the *right* of the rightmost position. A
1078 // very common exception, though, is if the
1079 // rightmost character also happens to be the
1080 // separator at the (logical) end of the row
1081 // --- in this case, the separator is
1082 // positioned beyond the right margin, and we
1083 // don't want to move the cursor there (moving
1084 // to the right of the separator is equivalent
1085 // to moving to the next line). So, in this
1086 // case we actually want to place the cursor
1087 // to the *left* of the rightmost position
1088 // (the separator). Another exception is if
1089 // we're moving to the logically last position
1090 // in the row, which is *not* a separator:
1091 // this means that the entire row has no
1092 // separators (if there were any, the row
1093 // would have been broken there); and
1094 // therefore in this case we also move to the
1095 // *left* of the last position (this indicates
1096 // to the user that there is no space after
1097 // this position, and is consistent with the
1098 // behavior in the middle of a row --- moving
1099 // right or left moves to the next/previous
1100 // character; if we were to move to the
1101 // *right* of this position, that would
1102 // simulate a separator which is not really
1103 // there!). Finally, there is an exception to
1104 // the previous exception: if this
1105 // non-separator-but-last-position-in-row is
1106 // an inset, then we *do* want to stay to the
1107 // right of it anyway: this is the "boundary"
1108 // which we simulate at insets. Another
1109 // exception is when row.endpos() is 0.
1111 // do we want to be to the left of pos?
1112 // as explained above, if at last pos in row, stay to the left,
1113 // unless the last position is the same as the first.
1114 bool const left_of_pos = row.endpos() > 0
1115 && pos() == row.endpos() - 1 && !par.isInset(pos());
1117 // Now we know if we want to be to the left or to the right of pos,
1118 // let's make sure we are where we want to be.
1119 bool const new_pos_is_RTL =
1120 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
1122 if (new_pos_is_RTL == left_of_pos) {
1128 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
1129 << (boundary() ? 1 : 0));
1133 CursorSlice Cursor::normalAnchor() const
1137 LASSERT(anchor_.depth() >= depth(), /**/);
1138 CursorSlice normal = anchor_[depth() - 1];
1139 if (depth() < anchor_.depth() && top() <= normal) {
1140 // anchor is behind cursor -> move anchor behind the inset
1147 DocIterator & Cursor::realAnchor()
1153 CursorSlice Cursor::selBegin() const
1157 return normalAnchor() < top() ? normalAnchor() : top();
1161 CursorSlice Cursor::selEnd() const
1165 return normalAnchor() > top() ? normalAnchor() : top();
1169 DocIterator Cursor::selectionBegin() const
1175 // FIXME: This is a work-around for the problem that
1176 // CursorSlice doesn't keep track of the boundary.
1177 if (normalAnchor() == top())
1178 di = anchor_.boundary() > boundary() ? anchor_ : *this;
1180 di = normalAnchor() < top() ? anchor_ : *this;
1186 DocIterator Cursor::selectionEnd() const
1192 // FIXME: This is a work-around for the problem that
1193 // CursorSlice doesn't keep track of the boundary.
1194 if (normalAnchor() == top())
1195 di = anchor_.boundary() < boundary() ? anchor_ : *this;
1197 di = normalAnchor() > top() ? anchor_ : *this;
1199 if (di.depth() > depth()) {
1207 void Cursor::setSelection()
1210 // A selection with no contents is not a selection
1211 // FIXME: doesnt look ok
1212 if (idx() == normalAnchor().idx() &&
1213 pit() == normalAnchor().pit() &&
1214 pos() == normalAnchor().pos())
1215 setSelection(false);
1219 void Cursor::setSelection(DocIterator const & where, int n)
1228 void Cursor::clearSelection()
1230 setSelection(false);
1231 setWordSelection(false);
1237 void Cursor::setTargetX(int x)
1240 textTargetOffset_ = 0;
1244 int Cursor::x_target() const
1250 void Cursor::clearTargetX()
1253 textTargetOffset_ = 0;
1257 void Cursor::updateTextTargetOffset()
1262 textTargetOffset_ = x - x_target_;
1266 void Cursor::info(odocstream & os) const
1268 for (int i = 1, n = depth(); i < n; ++i) {
1269 operator[](i).inset().infoize(os);
1273 Inset const * inset = prevInset();
1274 // prevInset() can return 0 in certain case.
1276 prevInset()->infoize2(os);
1278 // overwite old message
1283 bool Cursor::selHandle(bool sel)
1285 //lyxerr << "Cursor::selHandle" << endl;
1288 if (sel == selection())
1292 cap::saveSelection(*this);
1300 ostream & operator<<(ostream & os, Cursor const & cur)
1302 os << "\n cursor: | anchor:\n";
1303 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
1304 os << " " << cur[i] << " | ";
1305 if (i < cur.anchor_.depth())
1306 os << cur.anchor_[i];
1308 os << "-------------------------------";
1311 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
1312 os << "------------------------------- | " << cur.anchor_[i] << "\n";
1314 os << " selection: " << cur.selection_
1315 << " x_target: " << cur.x_target_ << endl;
1320 LyXErr & operator<<(LyXErr & os, Cursor const & cur)
1330 ///////////////////////////////////////////////////////////////////
1333 // The part below is the non-integrated rest of the original math
1334 // cursor. This should be either generalized for texted or moved
1335 // back to mathed (in most cases to InsetMathNest).
1337 ///////////////////////////////////////////////////////////////////
1339 #include "mathed/InsetMathChar.h"
1340 #include "mathed/InsetMathGrid.h"
1341 #include "mathed/InsetMathScript.h"
1342 #include "mathed/InsetMathUnknown.h"
1343 #include "mathed/MathFactory.h"
1344 #include "mathed/MathStream.h"
1345 #include "mathed/MathSupport.h"
1350 bool Cursor::isInside(Inset const * p) const
1352 for (size_t i = 0; i != depth(); ++i)
1353 if (&operator[](i).inset() == p)
1359 void Cursor::leaveInset(Inset const & inset)
1361 for (size_t i = 0; i != depth(); ++i) {
1362 if (&operator[](i).inset() == &inset) {
1370 bool Cursor::openable(MathAtom const & t) const
1381 // we can't move into anything new during selection
1382 if (depth() >= anchor_.depth())
1384 if (t.nucleus() != &anchor_[depth()].inset())
1391 void Cursor::setScreenPos(int x, int /*y*/)
1394 //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
1399 void Cursor::plainErase()
1401 cell().erase(pos());
1405 void Cursor::markInsert()
1407 insert(char_type(0));
1411 void Cursor::markErase()
1413 cell().erase(pos());
1417 void Cursor::plainInsert(MathAtom const & t)
1419 cell().insert(pos(), t);
1421 inset().setBuffer(bv_->buffer());
1423 forceBufferUpdate();
1427 void Cursor::insert(docstring const & str)
1429 for_each(str.begin(), str.end(),
1430 bind(static_cast<void(Cursor::*)(char_type)>
1431 (&Cursor::insert), this, _1));
1435 void Cursor::insert(char_type c)
1437 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1438 LASSERT(!empty(), /**/);
1440 cap::selClearOrDel(*this);
1441 insert(new InsetMathChar(c));
1443 text()->insertChar(*this, c);
1448 void Cursor::insert(MathAtom const & t)
1450 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1452 cap::selClearOrDel(*this);
1457 void Cursor::insert(Inset * inset0)
1459 LASSERT(inset0, /**/);
1461 insert(MathAtom(inset0->asInsetMath()));
1463 text()->insertInset(*this, inset0);
1464 inset0->setBuffer(bv_->buffer());
1466 if (inset0->isLabeled())
1467 forceBufferUpdate();
1472 int Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1474 MathData ar(buffer());
1476 if (ar.size() == 1 && (enter || selection()))
1484 void Cursor::niceInsert(MathAtom const & t)
1487 docstring const safe = cap::grabAndEraseSelection(*this);
1489 // If possible, enter the new inset and move the contents of the selection
1490 if (t->isActive()) {
1492 // be careful here: don't use 'pushBackward(t)' as this we need to
1493 // push the clone, not the original
1494 pushBackward(*nextInset());
1495 // We may not use niceInsert here (recursion)
1496 MathData ar(buffer());
1499 } else if (t->asMacro() && !safe.empty()) {
1500 MathData ar(buffer());
1502 docstring const name = t->asMacro()->name();
1503 MacroData const * data = buffer()->getMacro(name);
1504 if (data && data->numargs() - data->optionals() > 0) {
1505 plainInsert(MathAtom(new InsetMathBrace(ar)));
1512 void Cursor::insert(MathData const & ar)
1516 cap::eraseSelection(*this);
1517 cell().insert(pos(), ar);
1519 // FIXME audit setBuffer calls
1520 inset().setBuffer(bv_->buffer());
1524 bool Cursor::backspace()
1526 autocorrect() = false;
1529 cap::eraseSelection(*this);
1534 // If empty cell, and not part of a big cell
1535 if (lastpos() == 0 && inset().nargs() == 1) {
1537 // Directly delete empty cell: [|[]] => [|]
1543 // [|], can not delete from inside
1554 if (inMacroMode()) {
1555 InsetMathUnknown * p = activeMacro();
1556 if (p->name().size() > 1) {
1557 p->setName(p->name().substr(0, p->name().size() - 1));
1562 if (pos() != 0 && prevAtom()->nargs() > 0) {
1563 // let's require two backspaces for 'big stuff' and
1564 // highlight on the first
1576 bool Cursor::erase()
1578 autocorrect() = false;
1583 cap::eraseSelection(*this);
1587 // delete empty cells if possible
1588 if (pos() == lastpos() && inset().idxDelete(idx()))
1591 // special behaviour when in last position of cell
1592 if (pos() == lastpos()) {
1593 bool one_cell = inset().nargs() == 1;
1594 if (one_cell && lastpos() == 0) {
1596 // Directly delete empty cell: [|[]] => [|]
1602 // [|], can not delete from inside
1607 inset().idxGlue(idx());
1611 // 'clever' UI hack: only erase large items if previously slected
1612 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
1627 DocIterator save = *this;
1628 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1629 this->dispatch(cmd);
1630 if (disp_.dispatched())
1633 autocorrect() = false;
1641 DocIterator save = *this;
1642 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1643 this->dispatch(cmd);
1644 if (disp_.dispatched())
1647 autocorrect() = false;
1652 bool Cursor::macroModeClose()
1656 InsetMathUnknown * p = activeMacro();
1658 MathData selection(buffer());
1659 asArray(p->selection(), selection);
1660 docstring const s = p->name();
1662 cell().erase(pos());
1664 // do nothing if the macro name is empty
1668 // trigger updates of macros, at least, if no full
1669 // updates take place anyway
1670 screenUpdateFlags(Update::Force);
1672 docstring const name = s.substr(1);
1673 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1674 if (in && in->interpretString(*this, s))
1676 MathAtom atom = buffer()->getMacro(name, *this, false) ?
1677 MathAtom(new MathMacro(buffer(), name)) : createInsetMath(name, buffer());
1679 // try to put argument into macro, if we just inserted a macro
1680 bool macroArg = false;
1681 MathMacro * atomAsMacro = atom.nucleus()->asMacro();
1683 // macros here are still unfolded (in init mode in fact). So
1684 // we have to resolve the macro here manually and check its arity
1685 // to put the selection behind it if arity > 0.
1686 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1687 if (!selection.empty() && data && data->numargs() - data->optionals() > 0) {
1689 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1691 // non-greedy case. Do not touch the arguments behind
1692 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1695 // insert remembered selection into first argument of a non-macro
1696 else if (atom.nucleus()->nargs() > 0)
1697 atom.nucleus()->cell(0).append(selection);
1701 // finally put the macro argument behind, if needed
1703 if (selection.size() > 1 || selection[0]->asScriptInset())
1704 plainInsert(MathAtom(new InsetMathBrace(selection)));
1713 docstring Cursor::macroName()
1715 return inMacroMode() ? activeMacro()->name() : docstring();
1719 void Cursor::handleNest(MathAtom const & a, int c)
1721 //lyxerr << "Cursor::handleNest: " << c << endl;
1723 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1726 pushBackward(*nextInset());
1730 int Cursor::targetX() const
1732 if (x_target() != -1)
1741 int Cursor::textTargetOffset() const
1743 return textTargetOffset_;
1747 void Cursor::setTargetX()
1756 bool Cursor::inMacroMode() const
1760 if (pos() == 0 || cell().empty())
1762 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1763 return p && !p->final();
1767 InsetMathUnknown * Cursor::activeMacro()
1769 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1773 InsetMathUnknown const * Cursor::activeMacro() const
1775 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1779 void Cursor::pullArg()
1782 MathData ar = cell();
1783 if (popBackward() && inMathed()) {
1785 cell().insert(pos(), ar);
1788 //formula()->mutateToText();
1793 void Cursor::touch()
1797 DocIterator::const_iterator it = begin();
1798 DocIterator::const_iterator et = end();
1799 for ( ; it != et; ++it)
1805 void Cursor::normalize()
1807 if (idx() > lastidx()) {
1808 lyxerr << "this should not really happen - 1: "
1809 << idx() << ' ' << nargs()
1810 << " in: " << &inset() << endl;
1814 if (pos() > lastpos()) {
1815 lyxerr << "this should not really happen - 2: "
1816 << pos() << ' ' << lastpos() << " in idx: " << idx()
1818 odocstringstream os;
1819 WriteStream wi(os, false, true, WriteStream::wsDefault);
1820 inset().asInsetMath()->write(wi);
1821 lyxerr << to_utf8(os.str()) << endl;
1827 bool Cursor::upDownInMath(bool up)
1829 // Be warned: The 'logic' implemented in this function is highly
1830 // fragile. A distance of one pixel or a '<' vs '<=' _really
1831 // matters. So fiddle around with it only if you think you know
1832 // what you are doing!
1836 xo = beforeDispatchPosX_;
1838 // check if we had something else in mind, if not, this is the future
1840 if (x_target_ == -1)
1842 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1843 // In text mode inside the line (not left or right) possibly set a new target_x,
1844 // but only if we are somewhere else than the previous target-offset.
1846 // We want to keep the x-target on subsequent up/down movements
1847 // that cross beyond the end of short lines. Thus a special
1848 // handling when the cursor is at the end of line: Use the new
1849 // x-target only if the old one was before the end of line
1850 // or the old one was after the beginning of the line
1851 bool inRTL = isWithinRtlParagraph(*this);
1855 left = pos() == textRow().endpos();
1856 right = pos() == textRow().pos();
1858 left = pos() == textRow().pos();
1859 right = pos() == textRow().endpos();
1861 if ((!left && !right) ||
1862 (left && !right && xo < x_target_) ||
1863 (!left && right && x_target_ < xo))
1870 // try neigbouring script insets
1872 if (inMathed() && !selection()) {
1875 InsetMathScript const * p = prevAtom()->asScriptInset();
1876 if (p && p->has(up)) {
1878 push(*const_cast<InsetMathScript*>(p));
1879 idx() = p->idxOfScript(up);
1882 // we went in the right direction? Otherwise don't jump into the script
1886 int oy = beforeDispatchPosY_;
1887 if ((!up && y <= oy) ||
1896 if (pos() != lastpos()) {
1897 InsetMathScript const * p = nextAtom()->asScriptInset();
1898 if (p && p->has(up)) {
1899 push(*const_cast<InsetMathScript*>(p));
1900 idx() = p->idxOfScript(up);
1903 // we went in the right direction? Otherwise don't jump into the script
1907 int oy = beforeDispatchPosY_;
1908 if ((!up && y <= oy) ||
1917 // try to find an inset that knows better then we,
1918 if (inset().idxUpDown(*this, up)) {
1919 //lyxerr << "idxUpDown triggered" << endl;
1920 // try to find best position within this inset
1922 setCursor(bruteFind2(*this, xo, yo));
1926 // any improvement going just out of inset?
1927 if (popBackward() && inMathed()) {
1928 //lyxerr << "updown: popBackward succeeded" << endl;
1931 int yold = beforeDispatchPosY_;
1933 if (up ? ynew < yold : ynew > yold)
1937 // no success, we are probably at the document top or bottom
1943 bool Cursor::atFirstOrLastRow(bool up)
1945 TextMetrics const & tm = bv_->textMetrics(text());
1946 ParagraphMetrics const & pm = tm.parMetrics(pit());
1949 if (pos() && boundary())
1950 row = pm.pos2row(pos() - 1);
1952 row = pm.pos2row(pos());
1955 if (pit() == 0 && row == 0)
1958 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1959 row + 1 >= int(pm.rows().size()))
1966 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1968 LASSERT(text(), /**/);
1974 xo = beforeDispatchPosX_;
1976 // update the targetX - this is here before the "return false"
1977 // to set a new target which can be used by InsetTexts above
1978 // if we cannot move up/down inside this inset anymore
1979 if (x_target_ == -1)
1981 else if (xo - textTargetOffset() != x_target() &&
1982 depth() == beforeDispatchCursor_.depth()) {
1983 // In text mode inside the line (not left or right)
1984 // possibly set a new target_x, but only if we are
1985 // somewhere else than the previous target-offset.
1987 // We want to keep the x-target on subsequent up/down
1988 // movements that cross beyond the end of short lines.
1989 // Thus a special handling when the cursor is at the
1990 // end of line: Use the new x-target only if the old
1991 // one was before the end of line or the old one was
1992 // after the beginning of the line
1993 bool inRTL = isWithinRtlParagraph(*this);
1997 left = pos() == textRow().endpos();
1998 right = pos() == textRow().pos();
2000 left = pos() == textRow().pos();
2001 right = pos() == textRow().endpos();
2003 if ((!left && !right) ||
2004 (left && !right && xo < x_target_) ||
2005 (!left && right && x_target_ < xo))
2012 // first get the current line
2013 TextMetrics & tm = bv_->textMetrics(text());
2014 ParagraphMetrics const & pm = tm.parMetrics(pit());
2016 if (pos() && boundary())
2017 row = pm.pos2row(pos() - 1);
2019 row = pm.pos2row(pos());
2021 if (atFirstOrLastRow(up)) {
2022 // Is there a place for the cursor to go ? If yes, we
2023 // can execute the DEPM, otherwise we should keep the
2024 // paragraph to host the cursor.
2025 Cursor dummy = *this;
2026 bool valid_destination = false;
2027 for(; dummy.depth(); dummy.pop())
2028 if (!dummy.atFirstOrLastRow(up)) {
2029 valid_destination = true;
2033 // will a next dispatch follow and if there is a new
2034 // dispatch will it move the cursor out ?
2035 if (depth() > 1 && valid_destination) {
2036 // The cursor hasn't changed yet. This happens when
2037 // you e.g. move out of an inset. And to give the
2038 // DEPM the possibility of doing something we must
2039 // provide it with two different cursors. (Lgb, vfr)
2041 dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
2042 dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
2044 updateNeeded |= bv().checkDepm(dummy, *this);
2045 updateTextTargetOffset();
2047 forceBufferUpdate();
2048 // DEPM may have requested a screen update
2049 this->screenUpdateFlags(
2050 this->screenUpdate() | dummy.screenUpdate());
2056 // with and without selection are handled differently
2058 int yo = bv().getPos(*this).y_;
2060 // To next/previous row
2062 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
2064 tm.editXY(*this, xo, yo + textRow().descent() + 1);
2067 // This happens when you move out of an inset.
2068 // And to give the DEPM the possibility of doing
2069 // something we must provide it with two different
2071 Cursor dummy = *this;
2074 if (bv().checkDepm(dummy, old)) {
2075 updateNeeded = true;
2076 // Make sure that cur gets back whatever happened to dummy (Lgb)
2077 // This will include any screen update requested by DEPM
2081 // if there is a selection, we stay out of any inset,
2082 // and just jump to the right position:
2088 } else if (pit() > 0) {
2090 TextMetrics & tm = bv_->textMetrics(text());
2091 if (!tm.contains(pit()))
2092 tm.newParMetricsUp();
2093 ParagraphMetrics const & pmcur = tm.parMetrics(pit());
2094 next_row = pmcur.rows().size() - 1;
2097 if (row + 1 < int(pm.rows().size())) {
2099 } else if (pit() + 1 < int(text()->paragraphs().size())) {
2101 TextMetrics & tm = bv_->textMetrics(text());
2102 if (!tm.contains(pit()))
2103 tm.newParMetricsDown();
2107 top().pos() = min(tm.x2pos(pit(), next_row, xo), top().lastpos());
2109 int const xpos = tm.x2pos(pit(), next_row, xo);
2110 bool const at_end_row = xpos == tm.x2pos(pit(), next_row, tm.width());
2111 bool const at_beg_row = xpos == tm.x2pos(pit(), next_row, 0);
2113 if (at_end_row && at_beg_row)
2114 // make sure the cursor ends up on this row
2117 boundary(at_end_row);
2119 updateNeeded |= bv().checkDepm(*this, old);
2123 forceBufferUpdate();
2124 updateTextTargetOffset();
2129 void Cursor::handleFont(string const & font)
2131 LYXERR(Debug::DEBUG, font);
2135 safe = cap::grabAndEraseSelection(*this);
2140 if (lastpos() != 0) {
2141 // something left in the cell
2143 // cursor in first position
2145 } else if (pos() == lastpos()) {
2146 // cursor in last position
2149 // cursor in between. split cell
2150 MathData::iterator bt = cell().begin();
2151 MathAtom at = createInsetMath(from_utf8(font), buffer());
2152 at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
2153 cell().erase(bt, bt + pos());
2158 // nothing left in the cell
2167 void Cursor::message(docstring const & msg) const
2169 disp_.setMessage(msg);
2173 void Cursor::errorMessage(docstring const & msg) const
2175 disp_.setMessage(msg);
2176 disp_.setError(true);
2182 docstring parbreak(Cursor const * cur)
2184 odocstringstream os;
2186 // only add blank line if we're not in a ParbreakIsNewline situation
2187 if (!cur->inset().getLayout().parbreakIsNewline()
2188 && !cur->paragraph().layout().parbreak_is_newline)
2196 docstring Cursor::selectionAsString(bool with_label) const
2202 return cap::grabSelection(*this);
2204 int const label = with_label
2205 ? AS_STR_LABEL | AS_STR_INSETS : AS_STR_INSETS;
2207 idx_type const startidx = selBegin().idx();
2208 idx_type const endidx = selEnd().idx();
2209 if (startidx != endidx) {
2210 // multicell selection
2211 InsetTabular * table = inset().asInsetTabular();
2212 LASSERT(table, return docstring());
2213 return table->asString(startidx, endidx);
2216 ParagraphList const & pars = text()->paragraphs();
2218 pit_type const startpit = selBegin().pit();
2219 pit_type const endpit = selEnd().pit();
2220 size_t const startpos = selBegin().pos();
2221 size_t const endpos = selEnd().pos();
2223 if (startpit == endpit)
2224 return pars[startpit].asString(startpos, endpos, label);
2226 // First paragraph in selection
2227 docstring result = pars[startpit].
2228 asString(startpos, pars[startpit].size(), label)
2231 // The paragraphs in between (if any)
2232 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
2233 Paragraph const & par = pars[pit];
2234 result += par.asString(0, par.size(), label)
2238 // Last paragraph in selection
2239 result += pars[endpit].asString(0, endpos, label);
2245 docstring Cursor::currentState() const
2248 odocstringstream os;
2254 return text()->currentState(*this);
2260 docstring Cursor::getPossibleLabel() const
2262 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
2266 Encoding const * Cursor::getEncoding() const
2270 CursorSlice const & sl = innerTextSlice();
2271 Text const & text = *sl.text();
2272 Font font = text.getPar(sl.pit()).getFont(
2273 bv().buffer().params(), sl.pos(), text.outerFont(sl.pit()));
2274 return font.language()->encoding();
2278 void Cursor::undispatched() const
2280 disp_.dispatched(false);
2284 void Cursor::dispatched() const
2286 disp_.dispatched(true);
2290 void Cursor::screenUpdateFlags(Update::flags f) const
2292 disp_.screenUpdate(f);
2296 void Cursor::forceBufferUpdate() const
2298 disp_.forceBufferUpdate();
2302 void Cursor::clearBufferUpdate() const
2304 disp_.clearBufferUpdate();
2308 bool Cursor::needBufferUpdate() const
2310 return disp_.needBufferUpdate();
2314 void Cursor::noScreenUpdate() const
2316 disp_.screenUpdate(Update::None);
2320 Font Cursor::getFont() const
2322 // The logic here should more or less match to the
2323 // Cursor::setCurrentFont logic, i.e. the cursor height should
2324 // give a hint what will happen if a character is entered.
2326 // HACK. far from being perfect...
2328 CursorSlice const & sl = innerTextSlice();
2329 Text const & text = *sl.text();
2330 Paragraph const & par = text.getPar(sl.pit());
2332 // on boundary, so we are really at the character before
2333 pos_type pos = sl.pos();
2334 if (pos > 0 && boundary())
2337 // on space? Take the font before (only for RTL boundary stay)
2339 TextMetrics const & tm = bv().textMetrics(&text);
2340 if (pos == sl.lastpos()
2341 || (par.isSeparator(pos)
2342 && !tm.isRTLBoundary(sl.pit(), pos)))
2346 // get font at the position
2347 Font font = par.getFont(buffer()->params(), pos,
2348 text.outerFont(sl.pit()));
2354 bool Cursor::fixIfBroken()
2356 bool const broken_cursor = DocIterator::fixIfBroken();
2357 bool const broken_anchor = anchor_.fixIfBroken();
2359 if (broken_cursor || broken_anchor) {
2360 clearNewWordPosition();
2368 void Cursor::sanitize()
2370 setBuffer(&bv_->buffer());
2371 DocIterator::sanitize();
2376 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2378 // find inset in common
2380 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2381 if (&old[i].inset() != &cur[i].inset())
2385 // update words if we just moved to another paragraph
2386 if (i == old.depth() && i == cur.depth()
2387 && !cur.buffer()->isClean()
2388 && cur.inTexted() && old.inTexted()
2389 && cur.pit() != old.pit()) {
2390 old.paragraph().updateWords();
2393 // notify everything on top of the common part in old cursor,
2394 // but stop if the inset claims the cursor to be invalid now
2395 for (size_type j = i; j < old.depth(); ++j) {
2396 Cursor inset_pos = old;
2397 inset_pos.cutOff(j);
2398 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2402 // notify everything on top of the common part in new cursor,
2403 // but stop if the inset claims the cursor to be invalid now
2404 for (; i < cur.depth(); ++i) {
2405 if (cur[i].inset().notifyCursorEnters(cur))
2413 void Cursor::setCurrentFont()
2415 CursorSlice const & cs = innerTextSlice();
2416 Paragraph const & par = cs.paragraph();
2417 pos_type cpit = cs.pit();
2418 pos_type cpos = cs.pos();
2419 Text const & ctext = *cs.text();
2420 TextMetrics const & tm = bv().textMetrics(&ctext);
2422 // are we behind previous char in fact? -> go to that char
2423 if (cpos > 0 && boundary())
2426 // find position to take the font from
2428 // paragraph end? -> font of last char
2429 if (cpos == lastpos())
2431 // on space? -> look at the words in front of space
2432 else if (cpos > 0 && par.isSeparator(cpos)) {
2433 // abc| def -> font of c
2434 // abc |[WERBEH], i.e. boundary==true -> font of c
2435 // abc [WERBEH]| def, font of the space
2436 if (!tm.isRTLBoundary(cpit, cpos))
2442 BufferParams const & bufparams = buffer()->params();
2443 current_font = par.getFontSettings(bufparams, cpos);
2444 real_current_font = tm.displayFont(cpit, cpos);
2446 // special case for paragraph end
2447 if (cs.pos() == lastpos()
2448 && tm.isRTLBoundary(cpit, cs.pos())
2450 Language const * lang = par.getParLanguage(bufparams);
2451 current_font.setLanguage(lang);
2452 current_font.fontInfo().setNumber(FONT_OFF);
2453 real_current_font.setLanguage(lang);
2454 real_current_font.fontInfo().setNumber(FONT_OFF);
2459 bool Cursor::textUndo()
2461 if (!buffer()->undo().textUndo(*this))
2468 bool Cursor::textRedo()
2470 if (!buffer()->undo().textRedo(*this))
2477 void Cursor::finishUndo() const
2479 buffer()->undo().finishUndo();
2483 void Cursor::beginUndoGroup() const
2485 buffer()->undo().beginUndoGroup();
2489 void Cursor::endUndoGroup() const
2491 buffer()->undo().endUndoGroup(*this);
2495 void Cursor::recordUndo(UndoKind kind, pit_type from, pit_type to) const
2497 buffer()->undo().recordUndo(*this, kind, from, to);
2501 void Cursor::recordUndo(UndoKind kind, pit_type from) const
2503 buffer()->undo().recordUndo(*this, kind, from);
2507 void Cursor::recordUndo(UndoKind kind) const
2509 buffer()->undo().recordUndo(*this, kind);
2513 void Cursor::recordUndoInset(UndoKind kind, Inset const * inset) const
2515 buffer()->undo().recordUndoInset(*this, kind, inset);
2519 void Cursor::recordUndoFullDocument() const
2521 buffer()->undo().recordUndoFullDocument(*this);
2525 void Cursor::recordUndoSelection() const
2528 if (cap::multipleCellsSelected(*this))
2533 buffer()->undo().recordUndo(*this, ATOMIC_UNDO,
2534 selBegin().pit(), selEnd().pit());
2539 void Cursor::checkBufferStructure()
2541 Buffer const * master = buffer()->masterBuffer();
2542 master->tocBackend().updateItem(*this);
2543 if (master != buffer() && !master->hasGuiDelegate())
2544 // In case the master has no gui associated with it,
2545 // the TocItem is not updated (part of bug 5699).
2546 buffer()->tocBackend().updateItem(*this);