3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alejandro Aguilar Sierra
7 * \author Alfredo Braunstein
8 * \author Dov Feldstern
10 * \author Stefan Schimanski
12 * Full author contact details are available in file CREDITS.
19 #include "BufferView.h"
20 #include "CoordCache.h"
22 #include "CutAndPaste.h"
23 #include "DispatchResult.h"
27 #include "FuncRequest.h"
30 #include "LyXAction.h"
32 #include "Paragraph.h"
33 #include "ParIterator.h"
36 #include "TextMetrics.h"
37 #include "TocBackend.h"
39 #include "support/lassert.h"
40 #include "support/debug.h"
41 #include "support/docstream.h"
43 #include "insets/InsetTabular.h"
44 #include "insets/InsetText.h"
46 #include "mathed/InsetMath.h"
47 #include "mathed/InsetMathBrace.h"
48 #include "mathed/InsetMathScript.h"
49 #include "mathed/MacroTable.h"
50 #include "mathed/MathData.h"
51 #include "mathed/MathMacro.h"
53 #include "support/bind.h"
66 bool positionable(DocIterator const & cursor, DocIterator const & anchor)
68 // avoid deeper nested insets when selecting
69 if (cursor.depth() > anchor.depth())
72 // anchor might be deeper, should have same path then
73 for (size_t i = 0; i < cursor.depth(); ++i)
74 if (&cursor[i].inset() != &anchor[i].inset())
77 // position should be ok.
82 // Find position closest to (x, y) in cell given by iter.
83 // Used only in mathed
84 DocIterator bruteFind2(Cursor const & c, int x, int y)
86 double best_dist = numeric_limits<double>::max();
93 et.top().pos() = et.top().asInsetMath()->cell(et.top().idx()).size();
94 for (size_t i = 0;; ++i) {
97 Inset const * inset = &it.inset();
98 CoordCache const & cache = c.bv().coordCache();
100 // FIXME: in the case where the inset is not in the cache, this
101 // means that no part of it is visible on screen. In this case
102 // we don't do elaborate search and we just return the forwarded
103 // DocIterator at its beginning.
104 if (!cache.getInsets().has(inset)) {
109 Point const o = cache.getInsets().xy(inset);
110 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
111 // Convert to absolute
114 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
115 // '<=' in order to take the last possible position
116 // this is important for clicking behind \sum in e.g. '\sum_i a'
117 LYXERR(Debug::DEBUG, "i: " << i << " d: " << d
118 << " best: " << best_dist);
119 if (d <= best_dist) {
132 /// moves position closest to (x, y) in given box
133 bool bruteFind(Cursor & cursor,
134 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
136 LASSERT(!cursor.empty(), return false);
137 Inset & inset = cursor[0].inset();
138 BufferView & bv = cursor.bv();
140 CoordCache::InnerParPosCache const & cache =
141 bv.coordCache().getParPos().find(cursor.bottom().text())->second;
142 // Get an iterator on the first paragraph in the cache
143 DocIterator it(inset);
144 it.push_back(CursorSlice(inset));
145 it.pit() = cache.begin()->first;
146 // Get an iterator after the last paragraph in the cache
147 DocIterator et(inset);
148 et.push_back(CursorSlice(inset));
149 et.pit() = boost::prior(cache.end())->first;
150 if (et.pit() >= et.lastpit())
151 et = doc_iterator_end(inset);
155 double best_dist = numeric_limits<double>::max();
156 DocIterator best_cursor = et;
158 for ( ; it != et; it.forwardPos(true)) {
159 // avoid invalid nesting when selecting
160 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
161 Point p = bv.getPos(it, false);
164 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
165 double const dx = xo - x;
166 double const dy = yo - y;
167 double const d = dx * dx + dy * dy;
168 // '<=' in order to take the last possible position
169 // this is important for clicking behind \sum in e.g. '\sum_i a'
170 if (d <= best_dist) {
171 // lyxerr << "*" << endl;
179 if (best_cursor != et) {
180 cursor.setCursor(best_cursor);
189 /// moves position closest to (x, y) in given box
190 bool bruteFind3(Cursor & cur, int x, int y, bool up)
192 BufferView & bv = cur.bv();
193 int ylow = up ? 0 : y + 1;
194 int yhigh = up ? y - 1 : bv.workHeight();
196 int xhigh = bv.workWidth();
198 // FIXME: bit more work needed to get 'from' and 'to' right.
199 pit_type from = cur.bottom().pit();
200 //pit_type to = cur.bottom().pit();
201 //lyxerr << "Pit start: " << from << endl;
203 //lyxerr << "bruteFind3: x: " << x << " y: " << y
204 // << " xlow: " << xlow << " xhigh: " << xhigh
205 // << " ylow: " << ylow << " yhigh: " << yhigh
207 DocIterator it = doc_iterator_begin(cur.buffer());
209 DocIterator et = doc_iterator_end(cur.buffer());
211 double best_dist = numeric_limits<double>::max();
212 DocIterator best_cursor = et;
214 for ( ; it != et; it.forwardPos()) {
215 // avoid invalid nesting when selecting
216 if (bv.cursorStatus(it) == CUR_INSIDE
217 && (!cur.selection() || positionable(it, cur.realAnchor()))) {
218 // If this function is ever used again, check whether this
219 // is the same as "bv.getPos(it, false)" with boundary = false.
220 Point p = bv.getPos(it);
223 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
224 double const dx = xo - x;
225 double const dy = yo - y;
226 double const d = dx * dx + dy * dy;
227 //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
228 // << " dx: " << dx << " dy: " << dy
229 // << " idx: " << it.idx() << " pos: " << it.pos()
232 // '<=' in order to take the last possible position
233 // this is important for clicking behind \sum in e.g. '\sum_i a'
234 if (d <= best_dist) {
235 //lyxerr << "*" << endl;
243 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
244 if (best_cursor == et)
246 cur.setCursor(best_cursor);
253 CursorData::CursorData()
254 : DocIterator(), anchor_(),
255 selection_(false), mark_(false), word_selection_(false),
256 logicalpos_(false), current_font(inherit_font)
260 CursorData::CursorData(Buffer * buffer)
261 : DocIterator(buffer), anchor_(),
262 selection_(false), mark_(false), word_selection_(false),
263 logicalpos_(false), current_font(inherit_font)
267 CursorData::CursorData(DocIterator const & dit)
268 : DocIterator(dit), anchor_(),
269 selection_(false), mark_(false), word_selection_(false),
270 logicalpos_(false), current_font(inherit_font)
274 // be careful: this is called from the bv's constructor, too, so
275 // bv functions are not yet available!
276 Cursor::Cursor(BufferView & bv)
277 : CursorData(&bv.buffer()), bv_(&bv),
278 x_target_(-1), textTargetOffset_(0)
285 push_back(CursorSlice(buffer()->inset()));
286 anchor_ = doc_iterator_begin(buffer());
294 // this (intentionally) does neither touch anchor nor selection status
295 void Cursor::setCursor(DocIterator const & cur)
297 DocIterator::operator=(cur);
301 void Cursor::setCursorToAnchor()
304 DocIterator normal = anchor_;
305 while (depth() < normal.depth())
307 if (depth() < anchor_.depth() && top() <= anchor_[depth() - 1])
314 void Cursor::setCursorData(CursorData const & data)
316 CursorData::operator=(data);
320 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
324 // Try to fix cursor in case it is broken.
327 // Is this a function that acts on inset at point?
328 Inset * inset = cur.nextInset();
329 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
330 && inset && inset->getStatus(cur, cmd, status))
333 // This is, of course, a mess. Better create a new doc iterator and use
334 // this in Inset::getStatus. This might require an additional
335 // BufferView * arg, though (which should be avoided)
336 //Cursor safe = *this;
338 for ( ; cur.depth(); cur.pop()) {
339 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
340 LASSERT(cur.idx() <= cur.lastidx(), /**/);
341 LASSERT(cur.pit() <= cur.lastpit(), /**/);
342 LASSERT(cur.pos() <= cur.lastpos(), /**/);
344 // The inset's getStatus() will return 'true' if it made
345 // a definitive decision on whether it want to handle the
346 // request or not. The result of this decision is put into
347 // the 'status' parameter.
348 if (cur.inset().getStatus(cur, cmd, status)) {
357 void Cursor::saveBeforeDispatchPosXY()
359 getPos(beforeDispatchPosX_, beforeDispatchPosY_);
363 void Cursor::dispatch(FuncRequest const & cmd0)
365 LYXERR(Debug::DEBUG, "cmd: " << cmd0 << '\n' << *this);
370 FuncRequest cmd = cmd0;
373 disp_ = DispatchResult();
377 // Is this a function that acts on inset at point?
378 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
380 disp_.dispatched(true);
381 disp_.screenUpdate(Update::FitCursor | Update::Force);
382 FuncRequest tmpcmd = cmd;
383 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
384 << cmd0 << endl << *this);
385 nextInset()->dispatch(*this, tmpcmd);
386 if (disp_.dispatched()) {
392 // store some values to be used inside of the handlers
393 beforeDispatchCursor_ = *this;
394 for (; depth(); pop(), boundary(false)) {
395 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
396 << cmd0 << endl << *this);
397 LASSERT(pos() <= lastpos(), /**/);
398 LASSERT(idx() <= lastidx(), /**/);
399 LASSERT(pit() <= lastpit(), /**/);
401 // The common case is 'LFUN handled, need update', so make the
402 // LFUN handler's life easier by assuming this as default value.
403 // The handler can reset the update and val flags if necessary.
404 disp_.screenUpdate(Update::FitCursor | Update::Force);
405 disp_.dispatched(true);
406 inset().dispatch(*this, cmd);
407 if (disp_.dispatched())
411 // it completely to get a 'bomb early' behaviour in case this
412 // object will be used again.
413 if (!disp_.dispatched()) {
414 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
415 // We might have invalidated the cursor when removing an empty
416 // paragraph while the cursor could not be moved out the inset
417 // while we initially thought we could. This might happen when
418 // a multiline inset becomes an inline inset when the second
419 // paragraph is removed.
420 if (safe.pit() > safe.lastpit()) {
421 safe.pit() = safe.lastpit();
422 safe.pos() = safe.lastpos();
425 disp_.screenUpdate(Update::None);
426 disp_.dispatched(false);
428 // restore the previous one because nested Cursor::dispatch calls
429 // are possible which would change it
430 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
434 // notify insets we just left
436 old.beginUndoGroup();
438 bool badcursor = notifyCursorLeavesOrEnters(old, *this);
441 bv().resetInlineCompletionPos();
448 DispatchResult const & Cursor::result() const
454 BufferView & Cursor::bv() const
463 LASSERT(depth() >= 1, /**/);
468 void Cursor::push(Inset & p)
470 push_back(CursorSlice(p));
471 p.setBuffer(*buffer());
475 void Cursor::pushBackward(Inset & p)
477 LASSERT(!empty(), return);
478 //lyxerr << "Entering inset " << t << " front" << endl;
484 bool Cursor::popBackward()
486 LASSERT(!empty(), return false);
494 bool Cursor::popForward()
496 LASSERT(!empty(), return false);
497 //lyxerr << "Leaving inset from in back" << endl;
498 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
502 pos() += lastpos() - lp + 1;
507 int Cursor::currentMode()
509 LASSERT(!empty(), /**/);
510 for (int i = depth() - 1; i >= 0; --i) {
511 int res = operator[](i).inset().currentMode();
512 bool locked_mode = operator[](i).inset().lockedMode();
513 // Also return UNDECIDED_MODE when the mode is locked,
514 // as in this case it is treated the same as TEXT_MODE
515 if (res != Inset::UNDECIDED_MODE || locked_mode)
518 return Inset::TEXT_MODE;
522 void Cursor::getPos(int & x, int & y) const
524 Point p = bv().getPos(*this);
530 Row const & Cursor::textRow() const
532 CursorSlice const & cs = innerTextSlice();
533 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
534 LASSERT(!pm.rows().empty(), /**/);
535 return pm.getRow(pos(), boundary());
539 void Cursor::resetAnchor()
542 checkNewWordPosition();
546 void Cursor::markNewWordPosition()
548 if (lyxrc.spellcheck_continuously && inTexted() && new_word_.empty()) {
549 FontSpan nw = locateWord(WHOLE_WORD);
550 if (nw.size() == 1) {
551 LYXERR(Debug::DEBUG, "start new word: "
553 << " pos: " << nw.first);
560 void Cursor::clearNewWordPosition()
562 if (!new_word_.empty()) {
563 LYXERR(Debug::DEBUG, "clear new word: "
565 << " pos: " << pos());
571 void Cursor::checkNewWordPosition()
573 if (!lyxrc.spellcheck_continuously || new_word_.empty())
576 clearNewWordPosition();
578 // forget the position of the current new word if
579 // 1) the paragraph changes or
580 // 2) the count of nested insets changes or
581 // 3) the cursor pos is out of paragraph bound
582 if (pit() != new_word_.pit() ||
583 depth() != new_word_.depth() ||
584 new_word_.pos() > new_word_.lastpos()) {
585 clearNewWordPosition();
586 } else if (new_word_.fixIfBroken())
587 // 4) or the remembered position was "broken"
588 clearNewWordPosition();
590 FontSpan nw = locateWord(WHOLE_WORD);
592 FontSpan ow = new_word_.locateWord(WHOLE_WORD);
593 if (nw.intersect(ow).empty())
594 clearNewWordPosition();
596 LYXERR(Debug::DEBUG, "new word: "
598 << " pos: " << nw.first << ".." << nw.last);
600 clearNewWordPosition();
607 bool Cursor::posBackward()
616 bool Cursor::posForward()
618 if (pos() == lastpos())
625 bool Cursor::posVisRight(bool skip_inset)
627 Cursor new_cur = *this; // where we will move to
628 pos_type left_pos; // position visually left of current cursor
629 pos_type right_pos; // position visually right of current cursor
630 bool new_pos_is_RTL; // is new position we're moving to RTL?
632 getSurroundingPos(left_pos, right_pos);
634 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
636 // Are we at an inset?
637 new_cur.pos() = right_pos;
638 new_cur.boundary(false);
640 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
641 // we actually move the cursor at the end of this function, for now
642 // we just keep track of the new position in new_cur...
643 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
646 // Are we already at rightmost pos in row?
647 else if (text()->empty() || right_pos == -1) {
650 if (!new_cur.posVisToNewRow(false)) {
651 LYXERR(Debug::RTL, "not moving!");
655 // we actually move the cursor at the end of this function, for now
656 // just keep track of the new position in new_cur...
657 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
658 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
661 // normal movement to the right
664 // Recall, if the cursor is at position 'x', that means *before*
665 // the character at position 'x'. In RTL, "before" means "to the
666 // right of", in LTR, "to the left of". So currently our situation
667 // is this: the position to our right is 'right_pos' (i.e., we're
668 // currently to the left of 'right_pos'). In order to move to the
669 // right, it depends whether or not the character at 'right_pos' is RTL.
670 new_pos_is_RTL = paragraph().getFontSettings(
671 buffer()->params(), right_pos).isVisibleRightToLeft();
672 // If the character at 'right_pos' *is* LTR, then in order to move to
673 // the right of it, we need to be *after* 'right_pos', i.e., move to
674 // position 'right_pos' + 1.
675 if (!new_pos_is_RTL) {
676 new_cur.pos() = right_pos + 1;
677 // set the boundary to true in two situations:
679 // 1. if new_pos is now lastpos, and we're in an RTL paragraph
680 // (this means that we're moving right to the end of an LTR chunk
681 // which is at the end of an RTL paragraph);
682 (new_cur.pos() == lastpos()
683 && paragraph().isRTL(buffer()->params()))
684 // 2. if the position *after* right_pos is RTL (we want to be
685 // *after* right_pos, not before right_pos + 1!)
686 || paragraph().getFontSettings(buffer()->params(),
687 new_cur.pos()).isVisibleRightToLeft()
689 new_cur.boundary(true);
690 else // set the boundary to false
691 new_cur.boundary(false);
693 // Otherwise (if the character at position 'right_pos' is RTL), then
694 // moving to the right of it is as easy as setting the new position
697 new_cur.pos() = right_pos;
698 new_cur.boundary(false);
703 bool moved = (new_cur.pos() != pos()
704 || new_cur.pit() != pit()
705 || new_cur.boundary() != boundary()
706 || &new_cur.inset() != &inset());
709 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
710 << (new_cur.boundary() ? " (boundary)" : ""));
718 bool Cursor::posVisLeft(bool skip_inset)
720 Cursor new_cur = *this; // where we will move to
721 pos_type left_pos; // position visually left of current cursor
722 pos_type right_pos; // position visually right of current cursor
723 bool new_pos_is_RTL; // is new position we're moving to RTL?
725 getSurroundingPos(left_pos, right_pos);
727 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
729 // Are we at an inset?
730 new_cur.pos() = left_pos;
731 new_cur.boundary(false);
733 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
734 // we actually move the cursor at the end of this function, for now
735 // we just keep track of the new position in new_cur...
736 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
739 // Are we already at leftmost pos in row?
740 else if (text()->empty() || left_pos == -1) {
743 if (!new_cur.posVisToNewRow(true)) {
744 LYXERR(Debug::RTL, "not moving!");
748 // we actually move the cursor at the end of this function, for now
749 // just keep track of the new position in new_cur...
750 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
751 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
754 // normal movement to the left
757 // Recall, if the cursor is at position 'x', that means *before*
758 // the character at position 'x'. In RTL, "before" means "to the
759 // right of", in LTR, "to the left of". So currently our situation
760 // is this: the position to our left is 'left_pos' (i.e., we're
761 // currently to the right of 'left_pos'). In order to move to the
762 // left, it depends whether or not the character at 'left_pos' is RTL.
763 new_pos_is_RTL = paragraph().getFontSettings(
764 buffer()->params(), left_pos).isVisibleRightToLeft();
765 // If the character at 'left_pos' *is* RTL, then in order to move to
766 // the left of it, we need to be *after* 'left_pos', i.e., move to
767 // position 'left_pos' + 1.
768 if (new_pos_is_RTL) {
769 new_cur.pos() = left_pos + 1;
770 // set the boundary to true in two situations:
772 // 1. if new_pos is now lastpos and we're in an LTR paragraph
773 // (this means that we're moving left to the end of an RTL chunk
774 // which is at the end of an LTR paragraph);
775 (new_cur.pos() == lastpos()
776 && !paragraph().isRTL(buffer()->params()))
777 // 2. if the position *after* left_pos is not RTL (we want to be
778 // *after* left_pos, not before left_pos + 1!)
779 || !paragraph().getFontSettings(buffer()->params(),
780 new_cur.pos()).isVisibleRightToLeft()
782 new_cur.boundary(true);
783 else // set the boundary to false
784 new_cur.boundary(false);
786 // Otherwise (if the character at position 'left_pos' is LTR), then
787 // moving to the left of it is as easy as setting the new position
790 new_cur.pos() = left_pos;
791 new_cur.boundary(false);
796 bool moved = (new_cur.pos() != pos()
797 || new_cur.pit() != pit()
798 || new_cur.boundary() != boundary());
801 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
802 << (new_cur.boundary() ? " (boundary)" : ""));
810 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos)
812 // preparing bidi tables
813 Paragraph const & par = paragraph();
814 Buffer const & buf = *buffer();
815 Row const & row = textRow();
817 bidi.computeTables(par, buf, row);
819 LYXERR(Debug::RTL, "bidi: " << row.pos() << "--" << row.endpos());
821 // The cursor is painted *before* the character at pos(), or, if 'boundary'
822 // is true, *after* the character at (pos() - 1). So we already have one
823 // known position around the cursor:
824 pos_type const known_pos = boundary() && pos() > 0 ? pos() - 1 : pos();
826 // edge case: if we're at the end of the paragraph, things are a little
827 // different (because lastpos is a position which does not really "exist"
828 // --- there's no character there yet).
829 if (known_pos == lastpos()) {
830 if (par.isRTL(buf.params())) {
832 right_pos = bidi.vis2log(row.pos());
836 left_pos = bidi.vis2log(row.endpos() - 1);
841 // Whether 'known_pos' is to the left or to the right of the cursor depends
842 // on whether it is an RTL or LTR character...
843 bool const cur_is_RTL =
844 par.getFontSettings(buf.params(), known_pos).isVisibleRightToLeft();
845 // ... in the following manner:
846 // For an RTL character, "before" means "to the right" and "after" means
847 // "to the left"; and for LTR, it's the reverse. So, 'known_pos' is to the
848 // right of the cursor if (RTL && boundary) or (!RTL && !boundary):
849 bool const known_pos_on_right = cur_is_RTL == boundary();
851 // So we now know one of the positions surrounding the cursor. Let's
852 // determine the other one:
853 if (known_pos_on_right) {
854 right_pos = known_pos;
855 // *visual* position of 'left_pos':
856 pos_type v_left_pos = bidi.log2vis(right_pos) - 1;
857 // If the position we just identified as 'left_pos' is a "skipped
858 // separator" (a separator which is at the logical end of a row,
859 // except for the last row in a paragraph; such separators are not
860 // painted, so they "are not really there"; note that in bidi text,
861 // such a separator could appear visually in the middle of a row),
862 // set 'left_pos' to the *next* position to the left.
863 if (bidi.inRange(v_left_pos)
864 && bidi.vis2log(v_left_pos) + 1 == row.endpos()
865 && row.endpos() < lastpos()
866 && par.isSeparator(bidi.vis2log(v_left_pos)))
869 // calculate the logical position of 'left_pos', if in row
870 if (!bidi.inRange(v_left_pos))
873 left_pos = bidi.vis2log(v_left_pos);
874 // If the position we identified as 'right_pos' is a "skipped
875 // separator", set 'right_pos' to the *next* position to the right.
876 if (right_pos + 1 == row.endpos() && row.endpos() < lastpos()
877 && par.isSeparator(right_pos)) {
878 pos_type const v_right_pos = bidi.log2vis(right_pos) + 1;
879 if (!bidi.inRange(v_right_pos))
882 right_pos = bidi.vis2log(v_right_pos);
885 // known_pos is on the left
886 left_pos = known_pos;
887 // *visual* position of 'right_pos'
888 pos_type v_right_pos = bidi.log2vis(left_pos) + 1;
889 // If the position we just identified as 'right_pos' is a "skipped
890 // separator", set 'right_pos' to the *next* position to the right.
891 if (bidi.inRange(v_right_pos)
892 && bidi.vis2log(v_right_pos) + 1 == row.endpos()
893 && row.endpos() < lastpos()
894 && par.isSeparator(bidi.vis2log(v_right_pos)))
897 // calculate the logical position of 'right_pos', if in row
898 if (!bidi.inRange(v_right_pos))
901 right_pos = bidi.vis2log(v_right_pos);
902 // If the position we identified as 'left_pos' is a "skipped
903 // separator", set 'left_pos' to the *next* position to the left.
904 if (left_pos + 1 == row.endpos() && row.endpos() < lastpos()
905 && par.isSeparator(left_pos)) {
906 pos_type const v_left_pos = bidi.log2vis(left_pos) - 1;
907 if (!bidi.inRange(v_left_pos))
910 left_pos = bidi.vis2log(v_left_pos);
917 bool Cursor::posVisToNewRow(bool movingLeft)
919 Paragraph const & par = paragraph();
920 Buffer const & buf = *buffer();
921 Row const & row = textRow();
922 bool par_is_LTR = !par.isRTL(buf.params());
924 // Inside a table, determining whether to move to the next or previous row
925 // should be done based on the table's direction.
927 if (s >= 1 && (*this)[s].inset().asInsetTabular()) {
928 par_is_LTR = !(*this)[s].inset().asInsetTabular()->isRightToLeft(*this);
929 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
932 // if moving left in an LTR paragraph or moving right in an RTL one,
933 // move to previous row
934 if (par_is_LTR == movingLeft) {
935 if (row.pos() == 0) { // we're at first row in paragraph
936 if (pit() == 0) // no previous paragraph! don't move
938 // move to last pos in previous par
942 } else { // move to previous row in this par
943 pos() = row.pos() - 1; // this is guaranteed to be in previous row
947 // if moving left in an RTL paragraph or moving right in an LTR one,
950 if (row.endpos() == lastpos()) { // we're at last row in paragraph
951 if (pit() == lastpit()) // last paragraph! don't move
953 // move to first row in next par
957 } else { // move to next row in this par
958 pos() = row.endpos();
963 // make sure we're at left-/right-most pos in new row
964 posVisToRowExtremity(!movingLeft);
970 void Cursor::posVisToRowExtremity(bool left)
972 // prepare bidi tables
973 Paragraph const & par = paragraph();
974 Buffer const & buf = *buffer();
975 Row const & row = textRow();
977 bidi.computeTables(par, buf, row);
979 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
980 << (boundary() ? 1 : 0));
982 if (left) { // move to leftmost position
983 // if this is an RTL paragraph, and we're at the last row in the
984 // paragraph, move to lastpos
985 if (par.isRTL(buf.params()) && row.endpos() == lastpos())
988 pos() = bidi.vis2log(row.pos());
990 // Moving to the leftmost position in the row, the cursor should
991 // normally be placed to the *left* of the leftmost position.
992 // A very common exception, though, is if the leftmost character
993 // also happens to be the separator at the (logical) end of the row
994 // --- in this case, the separator is positioned beyond the left
995 // margin, and we don't want to move the cursor there (moving to
996 // the left of the separator is equivalent to moving to the next
997 // line). So, in this case we actually want to place the cursor
998 // to the *right* of the leftmost position (the separator).
999 // Another exception is if we're moving to the logically last
1000 // position in the row, which is *not* a separator: this means
1001 // that the entire row has no separators (if there were any, the
1002 // row would have been broken there); and therefore in this case
1003 // we also move to the *right* of the last position (this indicates
1004 // to the user that there is no space after this position, and is
1005 // consistent with the behavior in the middle of a row --- moving
1006 // right or left moves to the next/previous character; if we were
1007 // to move to the *left* of this position, that would simulate
1008 // a separator which is not really there!).
1009 // Finally, there is an exception to the previous exception: if
1010 // this non-separator-but-last-position-in-row is an inset, then
1011 // we *do* want to stay to the left of it anyway: this is the
1012 // "boundary" which we simulate at insets.
1013 // Another exception is when row.endpos() is 0.
1015 // do we want to be to the right of pos?
1016 // as explained above, if at last pos in row, stay to the right
1017 bool const right_of_pos = row.endpos() > 0
1018 && pos() == row.endpos() - 1 && !par.isInset(pos());
1020 // Now we know if we want to be to the left or to the right of pos,
1021 // let's make sure we are where we want to be.
1022 bool const new_pos_is_RTL =
1023 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
1025 if (new_pos_is_RTL != right_of_pos) {
1031 // move to rightmost position
1032 // if this is an LTR paragraph, and we're at the last row in the
1033 // paragraph, move to lastpos
1034 if (!par.isRTL(buf.params()) && row.endpos() == lastpos())
1037 pos() = row.endpos() > 0 ? bidi.vis2log(row.endpos() - 1) : 0;
1039 // Moving to the rightmost position in the row, the cursor should
1040 // normally be placed to the *right* of the rightmost position.
1041 // A very common exception, though, is if the rightmost character
1042 // also happens to be the separator at the (logical) end of the row
1043 // --- in this case, the separator is positioned beyond the right
1044 // margin, and we don't want to move the cursor there (moving to
1045 // the right of the separator is equivalent to moving to the next
1046 // line). So, in this case we actually want to place the cursor
1047 // to the *left* of the rightmost position (the separator).
1048 // Another exception is if we're moving to the logically last
1049 // position in the row, which is *not* a separator: this means
1050 // that the entire row has no separators (if there were any, the
1051 // row would have been broken there); and therefore in this case
1052 // we also move to the *left* of the last position (this indicates
1053 // to the user that there is no space after this position, and is
1054 // consistent with the behavior in the middle of a row --- moving
1055 // right or left moves to the next/previous character; if we were
1056 // to move to the *right* of this position, that would simulate
1057 // a separator which is not really there!).
1058 // Finally, there is an exception to the previous exception: if
1059 // this non-separator-but-last-position-in-row is an inset, then
1060 // we *do* want to stay to the right of it anyway: this is the
1061 // "boundary" which we simulate at insets.
1062 // Another exception is when row.endpos() is 0.
1064 // do we want to be to the left of pos?
1065 // as explained above, if at last pos in row, stay to the left,
1066 // unless the last position is the same as the first.
1067 bool const left_of_pos = row.endpos() > 0
1068 && pos() == row.endpos() - 1 && !par.isInset(pos());
1070 // Now we know if we want to be to the left or to the right of pos,
1071 // let's make sure we are where we want to be.
1072 bool const new_pos_is_RTL =
1073 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
1075 if (new_pos_is_RTL == left_of_pos) {
1081 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
1082 << (boundary() ? 1 : 0));
1086 CursorSlice Cursor::normalAnchor() const
1090 LASSERT(anchor_.depth() >= depth(), /**/);
1091 CursorSlice normal = anchor_[depth() - 1];
1092 if (depth() < anchor_.depth() && top() <= normal) {
1093 // anchor is behind cursor -> move anchor behind the inset
1100 DocIterator & Cursor::realAnchor()
1106 CursorSlice Cursor::selBegin() const
1110 return normalAnchor() < top() ? normalAnchor() : top();
1114 CursorSlice Cursor::selEnd() const
1118 return normalAnchor() > top() ? normalAnchor() : top();
1122 DocIterator Cursor::selectionBegin() const
1128 // FIXME: This is a work-around for the problem that
1129 // CursorSlice doesn't keep track of the boundary.
1130 if (normalAnchor() == top())
1131 di = anchor_.boundary() > boundary() ? anchor_ : *this;
1133 di = normalAnchor() < top() ? anchor_ : *this;
1139 DocIterator Cursor::selectionEnd() const
1145 // FIXME: This is a work-around for the problem that
1146 // CursorSlice doesn't keep track of the boundary.
1147 if (normalAnchor() == top())
1148 di = anchor_.boundary() < boundary() ? anchor_ : *this;
1150 di = normalAnchor() > top() ? anchor_ : *this;
1152 if (di.depth() > depth()) {
1160 void Cursor::setSelection()
1163 // A selection with no contents is not a selection
1164 // FIXME: doesnt look ok
1165 if (idx() == normalAnchor().idx() &&
1166 pit() == normalAnchor().pit() &&
1167 pos() == normalAnchor().pos())
1168 setSelection(false);
1172 void Cursor::setSelection(DocIterator const & where, int n)
1181 void Cursor::clearSelection()
1183 setSelection(false);
1184 setWordSelection(false);
1190 void Cursor::setTargetX(int x)
1193 textTargetOffset_ = 0;
1197 int Cursor::x_target() const
1203 void Cursor::clearTargetX()
1206 textTargetOffset_ = 0;
1210 void Cursor::updateTextTargetOffset()
1215 textTargetOffset_ = x - x_target_;
1219 void Cursor::info(odocstream & os) const
1221 for (int i = 1, n = depth(); i < n; ++i) {
1222 operator[](i).inset().infoize(os);
1226 Inset const * inset = prevInset();
1227 // prevInset() can return 0 in certain case.
1229 prevInset()->infoize2(os);
1231 // overwite old message
1236 bool Cursor::selHandle(bool sel)
1238 //lyxerr << "Cursor::selHandle" << endl;
1241 if (sel == selection())
1245 cap::saveSelection(*this);
1253 ostream & operator<<(ostream & os, Cursor const & cur)
1255 os << "\n cursor: | anchor:\n";
1256 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
1257 os << " " << cur[i] << " | ";
1258 if (i < cur.anchor_.depth())
1259 os << cur.anchor_[i];
1261 os << "-------------------------------";
1264 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
1265 os << "------------------------------- | " << cur.anchor_[i] << "\n";
1267 os << " selection: " << cur.selection_
1268 << " x_target: " << cur.x_target_ << endl;
1273 LyXErr & operator<<(LyXErr & os, Cursor const & cur)
1283 ///////////////////////////////////////////////////////////////////
1286 // The part below is the non-integrated rest of the original math
1287 // cursor. This should be either generalized for texted or moved
1288 // back to mathed (in most cases to InsetMathNest).
1290 ///////////////////////////////////////////////////////////////////
1292 #include "mathed/InsetMathChar.h"
1293 #include "mathed/InsetMathGrid.h"
1294 #include "mathed/InsetMathScript.h"
1295 #include "mathed/InsetMathUnknown.h"
1296 #include "mathed/MathFactory.h"
1297 #include "mathed/MathStream.h"
1298 #include "mathed/MathSupport.h"
1303 bool Cursor::isInside(Inset const * p) const
1305 for (size_t i = 0; i != depth(); ++i)
1306 if (&operator[](i).inset() == p)
1312 void Cursor::leaveInset(Inset const & inset)
1314 for (size_t i = 0; i != depth(); ++i) {
1315 if (&operator[](i).inset() == &inset) {
1323 bool Cursor::openable(MathAtom const & t) const
1334 // we can't move into anything new during selection
1335 if (depth() >= anchor_.depth())
1337 if (t.nucleus() != &anchor_[depth()].inset())
1344 void Cursor::setScreenPos(int x, int /*y*/)
1347 //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
1352 void Cursor::plainErase()
1354 cell().erase(pos());
1358 void Cursor::markInsert()
1360 insert(char_type(0));
1364 void Cursor::markErase()
1366 cell().erase(pos());
1370 void Cursor::plainInsert(MathAtom const & t)
1372 cell().insert(pos(), t);
1374 inset().setBuffer(bv_->buffer());
1376 forceBufferUpdate();
1380 void Cursor::insert(docstring const & str)
1382 for_each(str.begin(), str.end(),
1383 bind(static_cast<void(Cursor::*)(char_type)>
1384 (&Cursor::insert), this, _1));
1388 void Cursor::insert(char_type c)
1390 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1391 LASSERT(!empty(), /**/);
1393 cap::selClearOrDel(*this);
1394 insert(new InsetMathChar(c));
1396 text()->insertChar(*this, c);
1401 void Cursor::insert(MathAtom const & t)
1403 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1405 cap::selClearOrDel(*this);
1410 void Cursor::insert(Inset * inset0)
1412 LASSERT(inset0, /**/);
1414 insert(MathAtom(inset0->asInsetMath()));
1416 text()->insertInset(*this, inset0);
1417 inset0->setBuffer(bv_->buffer());
1419 if (inset0->isLabeled())
1420 forceBufferUpdate();
1425 int Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1427 MathData ar(buffer());
1429 if (ar.size() == 1 && (enter || selection()))
1437 void Cursor::niceInsert(MathAtom const & t)
1440 docstring const safe = cap::grabAndEraseSelection(*this);
1442 // If possible, enter the new inset and move the contents of the selection
1443 if (t->isActive()) {
1445 // be careful here: don't use 'pushBackward(t)' as this we need to
1446 // push the clone, not the original
1447 pushBackward(*nextInset());
1448 // We may not use niceInsert here (recursion)
1449 MathData ar(buffer());
1452 } else if (t->asMacro() && !safe.empty()) {
1453 MathData ar(buffer());
1455 docstring const name = t->asMacro()->name();
1456 MacroData const * data = buffer()->getMacro(name);
1457 if (data && data->numargs() - data->optionals() > 0) {
1458 plainInsert(MathAtom(new InsetMathBrace(ar)));
1465 void Cursor::insert(MathData const & ar)
1469 cap::eraseSelection(*this);
1470 cell().insert(pos(), ar);
1472 // FIXME audit setBuffer calls
1473 inset().setBuffer(bv_->buffer());
1477 bool Cursor::backspace()
1479 autocorrect() = false;
1482 cap::eraseSelection(*this);
1487 // If empty cell, and not part of a big cell
1488 if (lastpos() == 0 && inset().nargs() == 1) {
1490 // Directly delete empty cell: [|[]] => [|]
1496 // [|], can not delete from inside
1507 if (inMacroMode()) {
1508 InsetMathUnknown * p = activeMacro();
1509 if (p->name().size() > 1) {
1510 p->setName(p->name().substr(0, p->name().size() - 1));
1515 if (pos() != 0 && prevAtom()->nargs() > 0) {
1516 // let's require two backspaces for 'big stuff' and
1517 // highlight on the first
1529 bool Cursor::erase()
1531 autocorrect() = false;
1536 cap::eraseSelection(*this);
1540 // delete empty cells if possible
1541 if (pos() == lastpos() && inset().idxDelete(idx()))
1544 // special behaviour when in last position of cell
1545 if (pos() == lastpos()) {
1546 bool one_cell = inset().nargs() == 1;
1547 if (one_cell && lastpos() == 0) {
1549 // Directly delete empty cell: [|[]] => [|]
1555 // [|], can not delete from inside
1560 inset().idxGlue(idx());
1564 // 'clever' UI hack: only erase large items if previously slected
1565 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
1580 DocIterator save = *this;
1581 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1582 this->dispatch(cmd);
1583 if (disp_.dispatched())
1586 autocorrect() = false;
1594 DocIterator save = *this;
1595 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1596 this->dispatch(cmd);
1597 if (disp_.dispatched())
1600 autocorrect() = false;
1605 bool Cursor::macroModeClose()
1609 InsetMathUnknown * p = activeMacro();
1611 MathData selection(buffer());
1612 asArray(p->selection(), selection);
1613 docstring const s = p->name();
1615 cell().erase(pos());
1617 // do nothing if the macro name is empty
1621 // trigger updates of macros, at least, if no full
1622 // updates take place anyway
1623 screenUpdateFlags(Update::Force);
1625 docstring const name = s.substr(1);
1626 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1627 if (in && in->interpretString(*this, s))
1629 MathAtom atom = buffer()->getMacro(name, *this, false) ?
1630 MathAtom(new MathMacro(buffer(), name)) : createInsetMath(name, buffer());
1632 // try to put argument into macro, if we just inserted a macro
1633 bool macroArg = false;
1634 MathMacro * atomAsMacro = atom.nucleus()->asMacro();
1636 // macros here are still unfolded (in init mode in fact). So
1637 // we have to resolve the macro here manually and check its arity
1638 // to put the selection behind it if arity > 0.
1639 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1640 if (selection.size() > 0 && data && data->numargs() - data->optionals() > 0) {
1642 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1644 // non-greedy case. Do not touch the arguments behind
1645 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1648 // insert remembered selection into first argument of a non-macro
1649 else if (atom.nucleus()->nargs() > 0)
1650 atom.nucleus()->cell(0).append(selection);
1654 // finally put the macro argument behind, if needed
1656 if (selection.size() > 1 || selection[0]->asScriptInset())
1657 plainInsert(MathAtom(new InsetMathBrace(selection)));
1666 docstring Cursor::macroName()
1668 return inMacroMode() ? activeMacro()->name() : docstring();
1672 void Cursor::handleNest(MathAtom const & a, int c)
1674 //lyxerr << "Cursor::handleNest: " << c << endl;
1676 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1679 pushBackward(*nextInset());
1683 int Cursor::targetX() const
1685 if (x_target() != -1)
1694 int Cursor::textTargetOffset() const
1696 return textTargetOffset_;
1700 void Cursor::setTargetX()
1709 bool Cursor::inMacroMode() const
1713 if (pos() == 0 || cell().empty())
1715 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1716 return p && !p->final();
1720 InsetMathUnknown * Cursor::activeMacro()
1722 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1726 InsetMathUnknown const * Cursor::activeMacro() const
1728 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1732 void Cursor::pullArg()
1735 MathData ar = cell();
1736 if (popBackward() && inMathed()) {
1738 cell().insert(pos(), ar);
1741 //formula()->mutateToText();
1746 void Cursor::touch()
1750 DocIterator::const_iterator it = begin();
1751 DocIterator::const_iterator et = end();
1752 for ( ; it != et; ++it)
1758 void Cursor::normalize()
1760 if (idx() > lastidx()) {
1761 lyxerr << "this should not really happen - 1: "
1762 << idx() << ' ' << nargs()
1763 << " in: " << &inset() << endl;
1767 if (pos() > lastpos()) {
1768 lyxerr << "this should not really happen - 2: "
1769 << pos() << ' ' << lastpos() << " in idx: " << idx()
1771 odocstringstream os;
1772 WriteStream wi(os, false, true, WriteStream::wsDefault);
1773 inset().asInsetMath()->write(wi);
1774 lyxerr << to_utf8(os.str()) << endl;
1780 bool Cursor::upDownInMath(bool up)
1782 // Be warned: The 'logic' implemented in this function is highly
1783 // fragile. A distance of one pixel or a '<' vs '<=' _really
1784 // matters. So fiddle around with it only if you think you know
1785 // what you are doing!
1789 xo = beforeDispatchPosX_;
1791 // check if we had something else in mind, if not, this is the future
1793 if (x_target_ == -1)
1795 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1796 // In text mode inside the line (not left or right) possibly set a new target_x,
1797 // but only if we are somewhere else than the previous target-offset.
1799 // We want to keep the x-target on subsequent up/down movements
1800 // that cross beyond the end of short lines. Thus a special
1801 // handling when the cursor is at the end of line: Use the new
1802 // x-target only if the old one was before the end of line
1803 // or the old one was after the beginning of the line
1804 bool inRTL = isWithinRtlParagraph(*this);
1808 left = pos() == textRow().endpos();
1809 right = pos() == textRow().pos();
1811 left = pos() == textRow().pos();
1812 right = pos() == textRow().endpos();
1814 if ((!left && !right) ||
1815 (left && !right && xo < x_target_) ||
1816 (!left && right && x_target_ < xo))
1823 // try neigbouring script insets
1825 if (inMathed() && !selection()) {
1828 InsetMathScript const * p = prevAtom()->asScriptInset();
1829 if (p && p->has(up)) {
1831 push(*const_cast<InsetMathScript*>(p));
1832 idx() = p->idxOfScript(up);
1835 // we went in the right direction? Otherwise don't jump into the script
1839 int oy = beforeDispatchPosY_;
1840 if ((!up && y <= oy) ||
1849 if (pos() != lastpos()) {
1850 InsetMathScript const * p = nextAtom()->asScriptInset();
1851 if (p && p->has(up)) {
1852 push(*const_cast<InsetMathScript*>(p));
1853 idx() = p->idxOfScript(up);
1856 // we went in the right direction? Otherwise don't jump into the script
1860 int oy = beforeDispatchPosY_;
1861 if ((!up && y <= oy) ||
1870 // try to find an inset that knows better then we,
1871 if (inset().idxUpDown(*this, up)) {
1872 //lyxerr << "idxUpDown triggered" << endl;
1873 // try to find best position within this inset
1875 setCursor(bruteFind2(*this, xo, yo));
1879 // any improvement going just out of inset?
1880 if (popBackward() && inMathed()) {
1881 //lyxerr << "updown: popBackward succeeded" << endl;
1884 int yold = beforeDispatchPosY_;
1886 if (up ? ynew < yold : ynew > yold)
1890 // no success, we are probably at the document top or bottom
1896 bool Cursor::atFirstOrLastRow(bool up)
1898 TextMetrics const & tm = bv_->textMetrics(text());
1899 ParagraphMetrics const & pm = tm.parMetrics(pit());
1902 if (pos() && boundary())
1903 row = pm.pos2row(pos() - 1);
1905 row = pm.pos2row(pos());
1908 if (pit() == 0 && row == 0)
1911 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1912 row + 1 >= int(pm.rows().size()))
1918 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1920 LASSERT(text(), /**/);
1926 xo = beforeDispatchPosX_;
1928 // update the targetX - this is here before the "return false"
1929 // to set a new target which can be used by InsetTexts above
1930 // if we cannot move up/down inside this inset anymore
1931 if (x_target_ == -1)
1933 else if (xo - textTargetOffset() != x_target() &&
1934 depth() == beforeDispatchCursor_.depth()) {
1935 // In text mode inside the line (not left or right) possibly set a new target_x,
1936 // but only if we are somewhere else than the previous target-offset.
1938 // We want to keep the x-target on subsequent up/down movements
1939 // that cross beyond the end of short lines. Thus a special
1940 // handling when the cursor is at the end of line: Use the new
1941 // x-target only if the old one was before the end of line
1942 // or the old one was after the beginning of the line
1943 bool inRTL = isWithinRtlParagraph(*this);
1947 left = pos() == textRow().endpos();
1948 right = pos() == textRow().pos();
1950 left = pos() == textRow().pos();
1951 right = pos() == textRow().endpos();
1953 if ((!left && !right) ||
1954 (left && !right && xo < x_target_) ||
1955 (!left && right && x_target_ < xo))
1962 // first get the current line
1963 TextMetrics & tm = bv_->textMetrics(text());
1964 ParagraphMetrics const & pm = tm.parMetrics(pit());
1966 if (pos() && boundary())
1967 row = pm.pos2row(pos() - 1);
1969 row = pm.pos2row(pos());
1971 if (atFirstOrLastRow(up)) {
1972 // Is there a place for the cursor to go ? If yes, we
1973 // can execute the DEPM, otherwise we should keep the
1974 // paragraph to host the cursor.
1975 Cursor dummy = *this;
1976 bool valid_destination = false;
1977 for(; dummy.depth(); dummy.pop())
1978 if (!dummy.atFirstOrLastRow(up)) {
1979 valid_destination = true;
1983 // will a next dispatch follow and if there is a new
1984 // dispatch will it move the cursor out ?
1985 if (depth() > 1 && valid_destination) {
1986 // The cursor hasn't changed yet. This happens when
1987 // you e.g. move out of an inset. And to give the
1988 // DEPM the possibility of doing something we must
1989 // provide it with two different cursors. (Lgb, vfr)
1991 dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
1992 dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
1994 updateNeeded |= bv().checkDepm(dummy, *this);
1995 updateTextTargetOffset();
1997 forceBufferUpdate();
1998 // DEPM may have requested a screen update
1999 this->screenUpdateFlags(
2000 this->screenUpdate() | dummy.screenUpdate());
2006 // with and without selection are handled differently
2008 int yo = bv().getPos(*this).y_;
2010 // To next/previous row
2012 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
2014 tm.editXY(*this, xo, yo + textRow().descent() + 1);
2017 // This happens when you move out of an inset.
2018 // And to give the DEPM the possibility of doing
2019 // something we must provide it with two different
2021 Cursor dummy = *this;
2024 if (bv().checkDepm(dummy, old)) {
2025 updateNeeded = true;
2026 // Make sure that cur gets back whatever happened to dummy (Lgb)
2027 // This will include any screen update requested by DEPM
2031 // if there is a selection, we stay out of any inset,
2032 // and just jump to the right position:
2038 } else if (pit() > 0) {
2040 TextMetrics & tm = bv_->textMetrics(text());
2041 if (!tm.contains(pit()))
2042 tm.newParMetricsUp();
2043 ParagraphMetrics const & pmcur = tm.parMetrics(pit());
2044 next_row = pmcur.rows().size() - 1;
2047 if (row + 1 < int(pm.rows().size())) {
2049 } else if (pit() + 1 < int(text()->paragraphs().size())) {
2051 TextMetrics & tm = bv_->textMetrics(text());
2052 if (!tm.contains(pit()))
2053 tm.newParMetricsDown();
2057 top().pos() = min(tm.x2pos(pit(), next_row, xo), top().lastpos());
2059 int const xpos = tm.x2pos(pit(), next_row, xo);
2060 bool const at_end_row = xpos == tm.x2pos(pit(), next_row, tm.width());
2061 bool const at_beg_row = xpos == tm.x2pos(pit(), next_row, 0);
2063 if (at_end_row && at_beg_row)
2064 // make sure the cursor ends up on this row
2067 boundary(at_end_row);
2069 updateNeeded |= bv().checkDepm(*this, old);
2073 forceBufferUpdate();
2074 updateTextTargetOffset();
2079 void Cursor::handleFont(string const & font)
2081 LYXERR(Debug::DEBUG, font);
2085 safe = cap::grabAndEraseSelection(*this);
2090 if (lastpos() != 0) {
2091 // something left in the cell
2093 // cursor in first position
2095 } else if (pos() == lastpos()) {
2096 // cursor in last position
2099 // cursor in between. split cell
2100 MathData::iterator bt = cell().begin();
2101 MathAtom at = createInsetMath(from_utf8(font), buffer());
2102 at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
2103 cell().erase(bt, bt + pos());
2108 // nothing left in the cell
2117 void Cursor::message(docstring const & msg) const
2119 disp_.setMessage(msg);
2123 void Cursor::errorMessage(docstring const & msg) const
2125 disp_.setMessage(msg);
2126 disp_.setError(true);
2131 docstring parbreak(Cursor const * cur)
2133 odocstringstream os;
2135 // only add blank line if we're not in a ParbreakIsNewline situation
2136 if (!cur->inset().getLayout().parbreakIsNewline()
2137 && !cur->paragraph().layout().parbreak_is_newline)
2144 docstring Cursor::selectionAsString(bool with_label) const
2150 return cap::grabSelection(*this);
2152 int const label = with_label
2153 ? AS_STR_LABEL | AS_STR_INSETS : AS_STR_INSETS;
2155 idx_type const startidx = selBegin().idx();
2156 idx_type const endidx = selEnd().idx();
2157 if (startidx != endidx) {
2158 // multicell selection
2159 InsetTabular * table = inset().asInsetTabular();
2160 LASSERT(table, return docstring());
2161 return table->asString(startidx, endidx);
2164 ParagraphList const & pars = text()->paragraphs();
2166 pit_type const startpit = selBegin().pit();
2167 pit_type const endpit = selEnd().pit();
2168 size_t const startpos = selBegin().pos();
2169 size_t const endpos = selEnd().pos();
2171 if (startpit == endpit)
2172 return pars[startpit].asString(startpos, endpos, label);
2174 // First paragraph in selection
2175 docstring result = pars[startpit].
2176 asString(startpos, pars[startpit].size(), label)
2179 // The paragraphs in between (if any)
2180 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
2181 Paragraph const & par = pars[pit];
2182 result += par.asString(0, par.size(), label)
2186 // Last paragraph in selection
2187 result += pars[endpit].asString(0, endpos, label);
2193 docstring Cursor::currentState() const
2196 odocstringstream os;
2202 return text()->currentState(*this);
2208 docstring Cursor::getPossibleLabel() const
2210 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
2214 Encoding const * Cursor::getEncoding() const
2218 CursorSlice const & sl = innerTextSlice();
2219 Text const & text = *sl.text();
2220 Font font = text.getPar(sl.pit()).getFont(
2221 bv().buffer().params(), sl.pos(), text.outerFont(sl.pit()));
2222 return font.language()->encoding();
2226 void Cursor::undispatched() const
2228 disp_.dispatched(false);
2232 void Cursor::dispatched() const
2234 disp_.dispatched(true);
2238 void Cursor::screenUpdateFlags(Update::flags f) const
2240 disp_.screenUpdate(f);
2244 void Cursor::forceBufferUpdate() const
2246 disp_.forceBufferUpdate();
2250 void Cursor::clearBufferUpdate() const
2252 disp_.clearBufferUpdate();
2256 bool Cursor::needBufferUpdate() const
2258 return disp_.needBufferUpdate();
2262 void Cursor::noScreenUpdate() const
2264 disp_.screenUpdate(Update::None);
2268 Font Cursor::getFont() const
2270 // The logic here should more or less match to the Cursor::setCurrentFont
2271 // logic, i.e. the cursor height should give a hint what will happen
2272 // if a character is entered.
2274 // HACK. far from being perfect...
2276 CursorSlice const & sl = innerTextSlice();
2277 Text const & text = *sl.text();
2278 Paragraph const & par = text.getPar(sl.pit());
2280 // on boundary, so we are really at the character before
2281 pos_type pos = sl.pos();
2282 if (pos > 0 && boundary())
2285 // on space? Take the font before (only for RTL boundary stay)
2287 TextMetrics const & tm = bv().textMetrics(&text);
2288 if (pos == sl.lastpos()
2289 || (par.isSeparator(pos)
2290 && !tm.isRTLBoundary(sl.pit(), pos)))
2294 // get font at the position
2295 Font font = par.getFont(buffer()->params(), pos,
2296 text.outerFont(sl.pit()));
2302 bool Cursor::fixIfBroken()
2304 bool const broken_cursor = DocIterator::fixIfBroken();
2305 bool const broken_anchor = anchor_.fixIfBroken();
2307 if (broken_cursor || broken_anchor) {
2308 clearNewWordPosition();
2316 void Cursor::sanitize()
2318 setBuffer(&bv_->buffer());
2319 DocIterator::sanitize();
2324 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2326 // find inset in common
2328 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2329 if (&old[i].inset() != &cur[i].inset())
2333 // update words if we just moved to another paragraph
2334 if (i == old.depth() && i == cur.depth()
2335 && !cur.buffer()->isClean()
2336 && cur.inTexted() && old.inTexted()
2337 && cur.pit() != old.pit()) {
2338 old.paragraph().updateWords();
2341 // notify everything on top of the common part in old cursor,
2342 // but stop if the inset claims the cursor to be invalid now
2343 for (size_type j = i; j < old.depth(); ++j) {
2344 Cursor inset_pos = old;
2345 inset_pos.cutOff(j);
2346 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2350 // notify everything on top of the common part in new cursor,
2351 // but stop if the inset claims the cursor to be invalid now
2352 for (; i < cur.depth(); ++i) {
2353 if (cur[i].inset().notifyCursorEnters(cur))
2361 void Cursor::setCurrentFont()
2363 CursorSlice const & cs = innerTextSlice();
2364 Paragraph const & par = cs.paragraph();
2365 pos_type cpit = cs.pit();
2366 pos_type cpos = cs.pos();
2367 Text const & ctext = *cs.text();
2368 TextMetrics const & tm = bv().textMetrics(&ctext);
2370 // are we behind previous char in fact? -> go to that char
2371 if (cpos > 0 && boundary())
2374 // find position to take the font from
2376 // paragraph end? -> font of last char
2377 if (cpos == lastpos())
2379 // on space? -> look at the words in front of space
2380 else if (cpos > 0 && par.isSeparator(cpos)) {
2381 // abc| def -> font of c
2382 // abc |[WERBEH], i.e. boundary==true -> font of c
2383 // abc [WERBEH]| def, font of the space
2384 if (!tm.isRTLBoundary(cpit, cpos))
2390 BufferParams const & bufparams = buffer()->params();
2391 current_font = par.getFontSettings(bufparams, cpos);
2392 real_current_font = tm.displayFont(cpit, cpos);
2394 // special case for paragraph end
2395 if (cs.pos() == lastpos()
2396 && tm.isRTLBoundary(cpit, cs.pos())
2398 Language const * lang = par.getParLanguage(bufparams);
2399 current_font.setLanguage(lang);
2400 current_font.fontInfo().setNumber(FONT_OFF);
2401 real_current_font.setLanguage(lang);
2402 real_current_font.fontInfo().setNumber(FONT_OFF);
2407 bool Cursor::textUndo()
2409 if (!buffer()->undo().textUndo(*this))
2416 bool Cursor::textRedo()
2418 if (!buffer()->undo().textRedo(*this))
2425 void Cursor::finishUndo() const
2427 buffer()->undo().finishUndo();
2431 void Cursor::beginUndoGroup() const
2433 buffer()->undo().beginUndoGroup();
2437 void Cursor::endUndoGroup() const
2439 buffer()->undo().endUndoGroup(*this);
2443 void Cursor::recordUndo(UndoKind kind, pit_type from, pit_type to) const
2445 buffer()->undo().recordUndo(*this, kind, from, to);
2449 void Cursor::recordUndo(UndoKind kind, pit_type from) const
2451 buffer()->undo().recordUndo(*this, kind, from);
2455 void Cursor::recordUndo(UndoKind kind) const
2457 buffer()->undo().recordUndo(*this, kind);
2461 void Cursor::recordUndoInset(UndoKind kind, Inset const * inset) const
2463 buffer()->undo().recordUndoInset(*this, kind, inset);
2467 void Cursor::recordUndoFullDocument() const
2469 buffer()->undo().recordUndoFullDocument(*this);
2473 void Cursor::recordUndoSelection() const
2476 if (cap::multipleCellsSelected(*this))
2481 buffer()->undo().recordUndo(*this, ATOMIC_UNDO,
2482 selBegin().pit(), selEnd().pit());
2487 void Cursor::checkBufferStructure()
2489 Buffer const * master = buffer()->masterBuffer();
2490 master->tocBackend().updateItem(*this);
2491 if (master != buffer() && !master->hasGuiDelegate())
2492 // In case the master has no gui associated with it,
2493 // the TocItem is not updated (part of bug 5699).
2494 buffer()->tocBackend().updateItem(*this);