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"
29 #include "LyXAction.h"
31 #include "Paragraph.h"
32 #include "ParIterator.h"
35 #include "TextMetrics.h"
36 #include "TocBackend.h"
38 #include "support/lassert.h"
39 #include "support/debug.h"
40 #include "support/docstream.h"
42 #include "insets/InsetTabular.h"
43 #include "insets/InsetText.h"
45 #include "mathed/InsetMath.h"
46 #include "mathed/InsetMathBrace.h"
47 #include "mathed/InsetMathScript.h"
48 #include "mathed/MacroTable.h"
49 #include "mathed/MathData.h"
50 #include "mathed/MathMacro.h"
52 #include "support/bind.h"
65 bool positionable(DocIterator const & cursor, DocIterator const & anchor)
67 // avoid deeper nested insets when selecting
68 if (cursor.depth() > anchor.depth())
71 // anchor might be deeper, should have same path then
72 for (size_t i = 0; i < cursor.depth(); ++i)
73 if (&cursor[i].inset() != &anchor[i].inset())
76 // position should be ok.
81 // Find position closest to (x, y) in cell given by iter.
82 // Used only in mathed
83 DocIterator bruteFind2(Cursor const & c, int x, int y)
85 double best_dist = numeric_limits<double>::max();
92 et.top().pos() = et.top().asInsetMath()->cell(et.top().idx()).size();
93 for (size_t i = 0;; ++i) {
96 Inset const * inset = &it.inset();
97 map<Inset const *, Geometry> const & data =
98 c.bv().coordCache().getInsets().getData();
99 map<Inset const *, Geometry>::const_iterator I = data.find(inset);
101 // FIXME: in the case where the inset is not in the cache, this
102 // means that no part of it is visible on screen. In this case
103 // we don't do elaborate search and we just return the forwarded
104 // DocIterator at its beginning.
105 if (I == data.end()) {
110 Point o = I->second.pos;
111 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
112 // Convert to absolute
115 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
116 // '<=' in order to take the last possible position
117 // this is important for clicking behind \sum in e.g. '\sum_i a'
118 LYXERR(Debug::DEBUG, "i: " << i << " d: " << d
119 << " best: " << best_dist);
120 if (d <= best_dist) {
133 /// moves position closest to (x, y) in given box
134 bool bruteFind(Cursor & cursor,
135 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
137 LASSERT(!cursor.empty(), return false);
138 Inset & inset = cursor[0].inset();
139 BufferView & bv = cursor.bv();
141 CoordCache::InnerParPosCache const & cache =
142 bv.coordCache().getParPos().find(cursor.bottom().text())->second;
143 // Get an iterator on the first paragraph in the cache
144 DocIterator it(inset);
145 it.push_back(CursorSlice(inset));
146 it.pit() = cache.begin()->first;
147 // Get an iterator after the last paragraph in the cache
148 DocIterator et(inset);
149 et.push_back(CursorSlice(inset));
150 et.pit() = boost::prior(cache.end())->first;
151 if (et.pit() >= et.lastpit())
152 et = doc_iterator_end(inset);
156 double best_dist = numeric_limits<double>::max();;
157 DocIterator best_cursor = et;
159 for ( ; it != et; it.forwardPos(true)) {
160 // avoid invalid nesting when selecting
161 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
162 Point p = bv.getPos(it, false);
165 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
166 double const dx = xo - x;
167 double const dy = yo - y;
168 double const d = dx * dx + dy * dy;
169 // '<=' in order to take the last possible position
170 // this is important for clicking behind \sum in e.g. '\sum_i a'
171 if (d <= best_dist) {
172 // lyxerr << "*" << endl;
180 if (best_cursor != et) {
181 cursor.setCursor(best_cursor);
190 /// moves position closest to (x, y) in given box
191 bool bruteFind3(Cursor & cur, int x, int y, bool up)
193 BufferView & bv = cur.bv();
194 int ylow = up ? 0 : y + 1;
195 int yhigh = up ? y - 1 : bv.workHeight();
197 int xhigh = bv.workWidth();
199 // FIXME: bit more work needed to get 'from' and 'to' right.
200 pit_type from = cur.bottom().pit();
201 //pit_type to = cur.bottom().pit();
202 //lyxerr << "Pit start: " << from << endl;
204 //lyxerr << "bruteFind3: x: " << x << " y: " << y
205 // << " xlow: " << xlow << " xhigh: " << xhigh
206 // << " ylow: " << ylow << " yhigh: " << yhigh
208 DocIterator it = doc_iterator_begin(cur.buffer());
210 DocIterator et = doc_iterator_end(cur.buffer());
212 double best_dist = numeric_limits<double>::max();
213 DocIterator best_cursor = et;
215 for ( ; it != et; it.forwardPos()) {
216 // avoid invalid nesting when selecting
217 if (bv.cursorStatus(it) == CUR_INSIDE
218 && (!cur.selection() || positionable(it, cur.realAnchor()))) {
219 // If this function is ever used again, check whether this
220 // is the same as "bv.getPos(it, 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 // be careful: this is called from the bv's constructor, too, so
255 // bv functions are not yet available!
256 Cursor::Cursor(BufferView & bv)
257 : DocIterator(&bv.buffer()), bv_(&bv), anchor_(),
258 x_target_(-1), textTargetOffset_(0),
259 selection_(false), mark_(false), word_selection_(false),
260 logicalpos_(false), current_font(inherit_font)
267 push_back(CursorSlice(buffer()->inset()));
268 anchor_ = doc_iterator_begin(buffer());
276 // this (intentionally) does neither touch anchor nor selection status
277 void Cursor::setCursor(DocIterator const & cur)
279 DocIterator::operator=(cur);
283 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
287 // Try to fix cursor in case it is broken.
290 // Is this a function that acts on inset at point?
291 Inset * inset = cur.nextInset();
292 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
293 && inset && inset->getStatus(cur, cmd, status))
296 // This is, of course, a mess. Better create a new doc iterator and use
297 // this in Inset::getStatus. This might require an additional
298 // BufferView * arg, though (which should be avoided)
299 //Cursor safe = *this;
301 for ( ; cur.depth(); cur.pop()) {
302 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
303 LASSERT(cur.idx() <= cur.lastidx(), /**/);
304 LASSERT(cur.pit() <= cur.lastpit(), /**/);
305 LASSERT(cur.pos() <= cur.lastpos(), /**/);
307 // The inset's getStatus() will return 'true' if it made
308 // a definitive decision on whether it want to handle the
309 // request or not. The result of this decision is put into
310 // the 'status' parameter.
311 if (cur.inset().getStatus(cur, cmd, status)) {
320 void Cursor::saveBeforeDispatchPosXY()
322 getPos(beforeDispatchPosX_, beforeDispatchPosY_);
326 void Cursor::dispatch(FuncRequest const & cmd0)
328 LYXERR(Debug::DEBUG, "cmd: " << cmd0 << '\n' << *this);
333 FuncRequest cmd = cmd0;
336 buffer()->undo().beginUndoGroup();
338 // Is this a function that acts on inset at point?
339 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
341 disp_.dispatched(true);
342 disp_.update(Update::FitCursor | Update::Force);
343 FuncRequest tmpcmd = cmd;
344 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
345 << cmd0 << endl << *this);
346 nextInset()->dispatch(*this, tmpcmd);
347 if (disp_.dispatched()) {
348 buffer()->undo().endUndoGroup();
353 // store some values to be used inside of the handlers
354 beforeDispatchCursor_ = *this;
355 for (; depth(); pop(), boundary(false)) {
356 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
357 << cmd0 << endl << *this);
358 LASSERT(pos() <= lastpos(), /**/);
359 LASSERT(idx() <= lastidx(), /**/);
360 LASSERT(pit() <= lastpit(), /**/);
362 // The common case is 'LFUN handled, need update', so make the
363 // LFUN handler's life easier by assuming this as default value.
364 // The handler can reset the update and val flags if necessary.
365 disp_.update(Update::FitCursor | Update::Force);
366 disp_.dispatched(true);
367 inset().dispatch(*this, cmd);
368 if (disp_.dispatched())
372 // it completely to get a 'bomb early' behaviour in case this
373 // object will be used again.
374 if (!disp_.dispatched()) {
375 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
376 // We might have invalidated the cursor when removing an empty
377 // paragraph while the cursor could not be moved out the inset
378 // while we initially thought we could. This might happen when
379 // a multiline inset becomes an inline inset when the second
380 // paragraph is removed.
381 if (safe.pit() > safe.lastpit()) {
382 safe.pit() = safe.lastpit();
383 safe.pos() = safe.lastpos();
386 disp_.update(Update::None);
387 disp_.dispatched(false);
389 // restore the previous one because nested Cursor::dispatch calls
390 // are possible which would change it
391 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
393 buffer()->undo().endUndoGroup();
397 DispatchResult const & Cursor::result() const
403 BufferView & Cursor::bv() const
412 LASSERT(depth() >= 1, /**/);
417 void Cursor::push(Inset & p)
419 push_back(CursorSlice(p));
420 p.setBuffer(*buffer());
424 void Cursor::pushBackward(Inset & p)
426 LASSERT(!empty(), return);
427 //lyxerr << "Entering inset " << t << " front" << endl;
433 bool Cursor::popBackward()
435 LASSERT(!empty(), return false);
443 bool Cursor::popForward()
445 LASSERT(!empty(), return false);
446 //lyxerr << "Leaving inset from in back" << endl;
447 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
451 pos() += lastpos() - lp + 1;
456 int Cursor::currentMode()
458 LASSERT(!empty(), /**/);
459 for (int i = depth() - 1; i >= 0; --i) {
460 int res = operator[](i).inset().currentMode();
461 bool locked_mode = operator[](i).inset().lockedMode();
462 // Also return UNDECIDED_MODE when the mode is locked,
463 // as in this case it is treated the same as TEXT_MODE
464 if (res != Inset::UNDECIDED_MODE || locked_mode)
467 return Inset::TEXT_MODE;
471 void Cursor::getPos(int & x, int & y) const
473 Point p = bv().getPos(*this);
479 Row const & Cursor::textRow() const
481 CursorSlice const & cs = innerTextSlice();
482 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
483 LASSERT(!pm.rows().empty(), /**/);
484 return pm.getRow(pos(), boundary());
488 void Cursor::resetAnchor()
494 void Cursor::setCursorToAnchor()
497 DocIterator normal = anchor_;
498 while (depth() < normal.depth())
500 if (depth() < anchor_.depth() && top() <= anchor_[depth() - 1])
507 bool Cursor::posBackward()
516 bool Cursor::posForward()
518 if (pos() == lastpos())
525 bool Cursor::posVisRight(bool skip_inset)
527 Cursor new_cur = *this; // where we will move to
528 pos_type left_pos; // position visually left of current cursor
529 pos_type right_pos; // position visually right of current cursor
530 bool new_pos_is_RTL; // is new position we're moving to RTL?
532 getSurroundingPos(left_pos, right_pos);
534 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
536 // Are we at an inset?
537 new_cur.pos() = right_pos;
538 new_cur.boundary(false);
540 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
541 // we actually move the cursor at the end of this function, for now
542 // we just keep track of the new position in new_cur...
543 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
546 // Are we already at rightmost pos in row?
547 else if (text()->empty() || right_pos == -1) {
550 if (!new_cur.posVisToNewRow(false)) {
551 LYXERR(Debug::RTL, "not moving!");
555 // we actually move the cursor at the end of this function, for now
556 // just keep track of the new position in new_cur...
557 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
558 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
561 // normal movement to the right
564 // Recall, if the cursor is at position 'x', that means *before*
565 // the character at position 'x'. In RTL, "before" means "to the
566 // right of", in LTR, "to the left of". So currently our situation
567 // is this: the position to our right is 'right_pos' (i.e., we're
568 // currently to the left of 'right_pos'). In order to move to the
569 // right, it depends whether or not the character at 'right_pos' is RTL.
570 new_pos_is_RTL = paragraph().getFontSettings(
571 buffer()->params(), right_pos).isVisibleRightToLeft();
572 // If the character at 'right_pos' *is* LTR, then in order to move to
573 // the right of it, we need to be *after* 'right_pos', i.e., move to
574 // position 'right_pos' + 1.
575 if (!new_pos_is_RTL) {
576 new_cur.pos() = right_pos + 1;
577 // set the boundary to true in two situations:
579 // 1. if new_pos is now lastpos, and we're in an RTL paragraph
580 // (this means that we're moving right to the end of an LTR chunk
581 // which is at the end of an RTL paragraph);
582 (new_cur.pos() == lastpos()
583 && paragraph().isRTL(buffer()->params()))
584 // 2. if the position *after* right_pos is RTL (we want to be
585 // *after* right_pos, not before right_pos + 1!)
586 || paragraph().getFontSettings(buffer()->params(),
587 new_cur.pos()).isVisibleRightToLeft()
589 new_cur.boundary(true);
590 else // set the boundary to false
591 new_cur.boundary(false);
593 // Otherwise (if the character at position 'right_pos' is RTL), then
594 // moving to the right of it is as easy as setting the new position
597 new_cur.pos() = right_pos;
598 new_cur.boundary(false);
603 bool moved = (new_cur.pos() != pos()
604 || new_cur.pit() != pit()
605 || new_cur.boundary() != boundary()
606 || &new_cur.inset() != &inset());
609 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
610 << (new_cur.boundary() ? " (boundary)" : ""));
618 bool Cursor::posVisLeft(bool skip_inset)
620 Cursor new_cur = *this; // where we will move to
621 pos_type left_pos; // position visually left of current cursor
622 pos_type right_pos; // position visually right of current cursor
623 bool new_pos_is_RTL; // is new position we're moving to RTL?
625 getSurroundingPos(left_pos, right_pos);
627 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
629 // Are we at an inset?
630 new_cur.pos() = left_pos;
631 new_cur.boundary(false);
633 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
634 // we actually move the cursor at the end of this function, for now
635 // we just keep track of the new position in new_cur...
636 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
639 // Are we already at leftmost pos in row?
640 else if (text()->empty() || left_pos == -1) {
643 if (!new_cur.posVisToNewRow(true)) {
644 LYXERR(Debug::RTL, "not moving!");
648 // we actually move the cursor at the end of this function, for now
649 // just keep track of the new position in new_cur...
650 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
651 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
654 // normal movement to the left
657 // Recall, if the cursor is at position 'x', that means *before*
658 // the character at position 'x'. In RTL, "before" means "to the
659 // right of", in LTR, "to the left of". So currently our situation
660 // is this: the position to our left is 'left_pos' (i.e., we're
661 // currently to the right of 'left_pos'). In order to move to the
662 // left, it depends whether or not the character at 'left_pos' is RTL.
663 new_pos_is_RTL = paragraph().getFontSettings(
664 buffer()->params(), left_pos).isVisibleRightToLeft();
665 // If the character at 'left_pos' *is* RTL, then in order to move to
666 // the left of it, we need to be *after* 'left_pos', i.e., move to
667 // position 'left_pos' + 1.
668 if (new_pos_is_RTL) {
669 new_cur.pos() = left_pos + 1;
670 // set the boundary to true in two situations:
672 // 1. if new_pos is now lastpos and we're in an LTR paragraph
673 // (this means that we're moving left to the end of an RTL chunk
674 // which is at the end of an LTR paragraph);
675 (new_cur.pos() == lastpos()
676 && !paragraph().isRTL(buffer()->params()))
677 // 2. if the position *after* left_pos is not RTL (we want to be
678 // *after* left_pos, not before left_pos + 1!)
679 || !paragraph().getFontSettings(buffer()->params(),
680 new_cur.pos()).isVisibleRightToLeft()
682 new_cur.boundary(true);
683 else // set the boundary to false
684 new_cur.boundary(false);
686 // Otherwise (if the character at position 'left_pos' is LTR), then
687 // moving to the left of it is as easy as setting the new position
690 new_cur.pos() = left_pos;
691 new_cur.boundary(false);
696 bool moved = (new_cur.pos() != pos()
697 || new_cur.pit() != pit()
698 || new_cur.boundary() != boundary());
701 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
702 << (new_cur.boundary() ? " (boundary)" : ""));
710 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos)
712 // preparing bidi tables
713 Paragraph const & par = paragraph();
714 Buffer const & buf = *buffer();
715 Row const & row = textRow();
717 bidi.computeTables(par, buf, row);
719 LYXERR(Debug::RTL, "bidi: " << row.pos() << "--" << row.endpos());
721 // The cursor is painted *before* the character at pos(), or, if 'boundary'
722 // is true, *after* the character at (pos() - 1). So we already have one
723 // known position around the cursor:
724 pos_type const known_pos = boundary() && pos() > 0 ? pos() - 1 : pos();
726 // edge case: if we're at the end of the paragraph, things are a little
727 // different (because lastpos is a position which does not really "exist"
728 // --- there's no character there yet).
729 if (known_pos == lastpos()) {
730 if (par.isRTL(buf.params())) {
732 right_pos = bidi.vis2log(row.pos());
736 left_pos = bidi.vis2log(row.endpos() - 1);
741 // Whether 'known_pos' is to the left or to the right of the cursor depends
742 // on whether it is an RTL or LTR character...
743 bool const cur_is_RTL =
744 par.getFontSettings(buf.params(), known_pos).isVisibleRightToLeft();
745 // ... in the following manner:
746 // For an RTL character, "before" means "to the right" and "after" means
747 // "to the left"; and for LTR, it's the reverse. So, 'known_pos' is to the
748 // right of the cursor if (RTL && boundary) or (!RTL && !boundary):
749 bool const known_pos_on_right = cur_is_RTL == boundary();
751 // So we now know one of the positions surrounding the cursor. Let's
752 // determine the other one:
753 if (known_pos_on_right) {
754 right_pos = known_pos;
755 // *visual* position of 'left_pos':
756 pos_type v_left_pos = bidi.log2vis(right_pos) - 1;
757 // If the position we just identified as 'left_pos' is a "skipped
758 // separator" (a separator which is at the logical end of a row,
759 // except for the last row in a paragraph; such separators are not
760 // painted, so they "are not really there"; note that in bidi text,
761 // such a separator could appear visually in the middle of a row),
762 // set 'left_pos' to the *next* position to the left.
763 if (bidi.inRange(v_left_pos)
764 && bidi.vis2log(v_left_pos) + 1 == row.endpos()
765 && row.endpos() < lastpos()
766 && par.isSeparator(bidi.vis2log(v_left_pos)))
769 // calculate the logical position of 'left_pos', if in row
770 if (!bidi.inRange(v_left_pos))
773 left_pos = bidi.vis2log(v_left_pos);
774 // If the position we identified as 'right_pos' is a "skipped
775 // separator", set 'right_pos' to the *next* position to the right.
776 if (right_pos + 1 == row.endpos() && row.endpos() < lastpos()
777 && par.isSeparator(right_pos)) {
778 pos_type const v_right_pos = bidi.log2vis(right_pos) + 1;
779 if (!bidi.inRange(v_right_pos))
782 right_pos = bidi.vis2log(v_right_pos);
785 // known_pos is on the left
786 left_pos = known_pos;
787 // *visual* position of 'right_pos'
788 pos_type v_right_pos = bidi.log2vis(left_pos) + 1;
789 // If the position we just identified as 'right_pos' is a "skipped
790 // separator", set 'right_pos' to the *next* position to the right.
791 if (bidi.inRange(v_right_pos)
792 && bidi.vis2log(v_right_pos) + 1 == row.endpos()
793 && row.endpos() < lastpos()
794 && par.isSeparator(bidi.vis2log(v_right_pos)))
797 // calculate the logical position of 'right_pos', if in row
798 if (!bidi.inRange(v_right_pos))
801 right_pos = bidi.vis2log(v_right_pos);
802 // If the position we identified as 'left_pos' is a "skipped
803 // separator", set 'left_pos' to the *next* position to the left.
804 if (left_pos + 1 == row.endpos() && row.endpos() < lastpos()
805 && par.isSeparator(left_pos)) {
806 pos_type const v_left_pos = bidi.log2vis(left_pos) - 1;
807 if (!bidi.inRange(v_left_pos))
810 left_pos = bidi.vis2log(v_left_pos);
817 bool Cursor::posVisToNewRow(bool movingLeft)
819 Paragraph const & par = paragraph();
820 Buffer const & buf = *buffer();
821 Row const & row = textRow();
822 bool par_is_LTR = !par.isRTL(buf.params());
824 // Inside a table, determining whether to move to the next or previous row
825 // should be done based on the table's direction.
827 if (s >= 1 && (*this)[s].inset().asInsetTabular()) {
828 par_is_LTR = !(*this)[s].inset().asInsetTabular()->isRightToLeft(*this);
829 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
832 // if moving left in an LTR paragraph or moving right in an RTL one,
833 // move to previous row
834 if (par_is_LTR == movingLeft) {
835 if (row.pos() == 0) { // we're at first row in paragraph
836 if (pit() == 0) // no previous paragraph! don't move
838 // move to last pos in previous par
842 } else { // move to previous row in this par
843 pos() = row.pos() - 1; // this is guaranteed to be in previous row
847 // if moving left in an RTL paragraph or moving right in an LTR one,
850 if (row.endpos() == lastpos()) { // we're at last row in paragraph
851 if (pit() == lastpit()) // last paragraph! don't move
853 // move to first row in next par
857 } else { // move to next row in this par
858 pos() = row.endpos();
863 // make sure we're at left-/right-most pos in new row
864 posVisToRowExtremity(!movingLeft);
870 void Cursor::posVisToRowExtremity(bool left)
872 // prepare bidi tables
873 Paragraph const & par = paragraph();
874 Buffer const & buf = *buffer();
875 Row const & row = textRow();
877 bidi.computeTables(par, buf, row);
879 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
880 << (boundary() ? 1 : 0));
882 if (left) { // move to leftmost position
883 // if this is an RTL paragraph, and we're at the last row in the
884 // paragraph, move to lastpos
885 if (par.isRTL(buf.params()) && row.endpos() == lastpos())
888 pos() = bidi.vis2log(row.pos());
890 // Moving to the leftmost position in the row, the cursor should
891 // normally be placed to the *left* of the leftmost position.
892 // A very common exception, though, is if the leftmost character
893 // also happens to be the separator at the (logical) end of the row
894 // --- in this case, the separator is positioned beyond the left
895 // margin, and we don't want to move the cursor there (moving to
896 // the left of the separator is equivalent to moving to the next
897 // line). So, in this case we actually want to place the cursor
898 // to the *right* of the leftmost position (the separator).
899 // Another exception is if we're moving to the logically last
900 // position in the row, which is *not* a separator: this means
901 // that the entire row has no separators (if there were any, the
902 // row would have been broken there); and therefore in this case
903 // we also move to the *right* of the last position (this indicates
904 // to the user that there is no space after this position, and is
905 // consistent with the behavior in the middle of a row --- moving
906 // right or left moves to the next/previous character; if we were
907 // to move to the *left* of this position, that would simulate
908 // a separator which is not really there!).
909 // Finally, there is an exception to the previous exception: if
910 // this non-separator-but-last-position-in-row is an inset, then
911 // we *do* want to stay to the left of it anyway: this is the
912 // "boundary" which we simulate at insets.
913 // Another exception is when row.endpos() is 0.
915 // do we want to be to the right of pos?
916 // as explained above, if at last pos in row, stay to the right
917 bool const right_of_pos = row.endpos() > 0
918 && pos() == row.endpos() - 1 && !par.isInset(pos());
920 // Now we know if we want to be to the left or to the right of pos,
921 // let's make sure we are where we want to be.
922 bool const new_pos_is_RTL =
923 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
925 if (new_pos_is_RTL != right_of_pos) {
931 // move to rightmost position
932 // if this is an LTR paragraph, and we're at the last row in the
933 // paragraph, move to lastpos
934 if (!par.isRTL(buf.params()) && row.endpos() == lastpos())
937 pos() = row.endpos() > 0 ? bidi.vis2log(row.endpos() - 1) : 0;
939 // Moving to the rightmost position in the row, the cursor should
940 // normally be placed to the *right* of the rightmost position.
941 // A very common exception, though, is if the rightmost character
942 // also happens to be the separator at the (logical) end of the row
943 // --- in this case, the separator is positioned beyond the right
944 // margin, and we don't want to move the cursor there (moving to
945 // the right of the separator is equivalent to moving to the next
946 // line). So, in this case we actually want to place the cursor
947 // to the *left* of the rightmost position (the separator).
948 // Another exception is if we're moving to the logically last
949 // position in the row, which is *not* a separator: this means
950 // that the entire row has no separators (if there were any, the
951 // row would have been broken there); and therefore in this case
952 // we also move to the *left* of the last position (this indicates
953 // to the user that there is no space after this position, and is
954 // consistent with the behavior in the middle of a row --- moving
955 // right or left moves to the next/previous character; if we were
956 // to move to the *right* of this position, that would simulate
957 // a separator which is not really there!).
958 // Finally, there is an exception to the previous exception: if
959 // this non-separator-but-last-position-in-row is an inset, then
960 // we *do* want to stay to the right of it anyway: this is the
961 // "boundary" which we simulate at insets.
962 // Another exception is when row.endpos() is 0.
964 // do we want to be to the left of pos?
965 // as explained above, if at last pos in row, stay to the left,
966 // unless the last position is the same as the first.
967 bool const left_of_pos = row.endpos() > 0
968 && pos() == row.endpos() - 1 && !par.isInset(pos());
970 // Now we know if we want to be to the left or to the right of pos,
971 // let's make sure we are where we want to be.
972 bool const new_pos_is_RTL =
973 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
975 if (new_pos_is_RTL == left_of_pos) {
981 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
982 << (boundary() ? 1 : 0));
986 CursorSlice Cursor::normalAnchor() const
990 LASSERT(anchor_.depth() >= depth(), /**/);
991 CursorSlice normal = anchor_[depth() - 1];
992 if (depth() < anchor_.depth() && top() <= normal) {
993 // anchor is behind cursor -> move anchor behind the inset
1000 DocIterator & Cursor::realAnchor()
1006 CursorSlice Cursor::selBegin() const
1010 return normalAnchor() < top() ? normalAnchor() : top();
1014 CursorSlice Cursor::selEnd() const
1018 return normalAnchor() > top() ? normalAnchor() : top();
1022 DocIterator Cursor::selectionBegin() const
1028 // FIXME: This is a work-around for the problem that
1029 // CursorSlice doesn't keep track of the boundary.
1030 if (normalAnchor() == top())
1031 di = anchor_.boundary() > boundary() ? anchor_ : *this;
1033 di = normalAnchor() < top() ? anchor_ : *this;
1039 DocIterator Cursor::selectionEnd() const
1045 // FIXME: This is a work-around for the problem that
1046 // CursorSlice doesn't keep track of the boundary.
1047 if (normalAnchor() == top())
1048 di = anchor_.boundary() < boundary() ? anchor_ : *this;
1050 di = normalAnchor() > top() ? anchor_ : *this;
1052 if (di.depth() > depth()) {
1060 void Cursor::setSelection()
1063 // A selection with no contents is not a selection
1064 // FIXME: doesnt look ok
1065 if (idx() == normalAnchor().idx() &&
1066 pit() == normalAnchor().pit() &&
1067 pos() == normalAnchor().pos())
1068 setSelection(false);
1072 void Cursor::setSelection(DocIterator const & where, int n)
1081 void Cursor::clearSelection()
1083 setSelection(false);
1084 setWordSelection(false);
1090 void Cursor::setTargetX(int x)
1093 textTargetOffset_ = 0;
1097 int Cursor::x_target() const
1103 void Cursor::clearTargetX()
1106 textTargetOffset_ = 0;
1110 void Cursor::updateTextTargetOffset()
1115 textTargetOffset_ = x - x_target_;
1119 void Cursor::info(odocstream & os) const
1121 for (int i = 1, n = depth(); i < n; ++i) {
1122 operator[](i).inset().infoize(os);
1126 Inset const * inset = prevInset();
1127 // prevInset() can return 0 in certain case.
1129 prevInset()->infoize2(os);
1131 // overwite old message
1136 bool Cursor::selHandle(bool sel)
1138 //lyxerr << "Cursor::selHandle" << endl;
1141 if (sel == selection())
1145 cap::saveSelection(*this);
1153 ostream & operator<<(ostream & os, Cursor const & cur)
1155 os << "\n cursor: | anchor:\n";
1156 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
1157 os << " " << cur[i] << " | ";
1158 if (i < cur.anchor_.depth())
1159 os << cur.anchor_[i];
1161 os << "-------------------------------";
1164 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
1165 os << "------------------------------- | " << cur.anchor_[i] << "\n";
1167 os << " selection: " << cur.selection_
1168 << " x_target: " << cur.x_target_ << endl;
1173 LyXErr & operator<<(LyXErr & os, Cursor const & cur)
1183 ///////////////////////////////////////////////////////////////////
1186 // The part below is the non-integrated rest of the original math
1187 // cursor. This should be either generalized for texted or moved
1188 // back to mathed (in most cases to InsetMathNest).
1190 ///////////////////////////////////////////////////////////////////
1192 #include "mathed/InsetMathChar.h"
1193 #include "mathed/InsetMathGrid.h"
1194 #include "mathed/InsetMathScript.h"
1195 #include "mathed/InsetMathUnknown.h"
1196 #include "mathed/MathFactory.h"
1197 #include "mathed/MathStream.h"
1198 #include "mathed/MathSupport.h"
1203 //#define FILEDEBUG 1
1206 bool Cursor::isInside(Inset const * p) const
1208 for (size_t i = 0; i != depth(); ++i)
1209 if (&operator[](i).inset() == p)
1215 void Cursor::leaveInset(Inset const & inset)
1217 for (size_t i = 0; i != depth(); ++i) {
1218 if (&operator[](i).inset() == &inset) {
1226 bool Cursor::openable(MathAtom const & t) const
1237 // we can't move into anything new during selection
1238 if (depth() >= anchor_.depth())
1240 if (t.nucleus() != &anchor_[depth()].inset())
1247 void Cursor::setScreenPos(int x, int /*y*/)
1250 //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
1255 void Cursor::plainErase()
1257 cell().erase(pos());
1261 void Cursor::markInsert()
1263 insert(char_type(0));
1267 void Cursor::markErase()
1269 cell().erase(pos());
1273 void Cursor::plainInsert(MathAtom const & t)
1275 cell().insert(pos(), t);
1277 inset().setBuffer(bv_->buffer());
1282 void Cursor::insert(docstring const & str)
1284 for_each(str.begin(), str.end(),
1285 bind(static_cast<void(Cursor::*)(char_type)>
1286 (&Cursor::insert), this, _1));
1290 void Cursor::insert(char_type c)
1292 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1293 LASSERT(!empty(), /**/);
1295 cap::selClearOrDel(*this);
1296 insert(new InsetMathChar(c));
1298 text()->insertChar(*this, c);
1303 void Cursor::insert(MathAtom const & t)
1305 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1307 cap::selClearOrDel(*this);
1312 void Cursor::insert(Inset * inset0)
1314 LASSERT(inset0, /**/);
1316 insert(MathAtom(inset0));
1318 text()->insertInset(*this, inset0);
1319 inset0->setBuffer(bv_->buffer());
1325 void Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1327 MathData ar(buffer());
1329 if (ar.size() == 1 && (enter || selection()))
1336 void Cursor::niceInsert(MathAtom const & t)
1339 docstring const safe = cap::grabAndEraseSelection(*this);
1341 // If possible, enter the new inset and move the contents of the selection
1342 if (t->isActive()) {
1344 // be careful here: don't use 'pushBackward(t)' as this we need to
1345 // push the clone, not the original
1346 pushBackward(*nextInset());
1347 // We may not use niceInsert here (recursion)
1348 MathData ar(buffer());
1355 void Cursor::insert(MathData const & ar)
1359 cap::eraseSelection(*this);
1360 cell().insert(pos(), ar);
1362 // FIXME audit setBuffer/updateBuffer calls
1363 inset().setBuffer(bv_->buffer());
1367 bool Cursor::backspace()
1369 autocorrect() = false;
1372 cap::eraseSelection(*this);
1377 // If empty cell, and not part of a big cell
1378 if (lastpos() == 0 && inset().nargs() == 1) {
1380 // Directly delete empty cell: [|[]] => [|]
1386 // [|], can not delete from inside
1397 if (inMacroMode()) {
1398 InsetMathUnknown * p = activeMacro();
1399 if (p->name().size() > 1) {
1400 p->setName(p->name().substr(0, p->name().size() - 1));
1405 if (pos() != 0 && prevAtom()->nargs() > 0) {
1406 // let's require two backspaces for 'big stuff' and
1407 // highlight on the first
1419 bool Cursor::erase()
1421 autocorrect() = false;
1426 cap::eraseSelection(*this);
1430 // delete empty cells if possible
1431 if (pos() == lastpos() && inset().idxDelete(idx()))
1434 // special behaviour when in last position of cell
1435 if (pos() == lastpos()) {
1436 bool one_cell = inset().nargs() == 1;
1437 if (one_cell && lastpos() == 0) {
1439 // Directly delete empty cell: [|[]] => [|]
1445 // [|], can not delete from inside
1450 inset().idxGlue(idx());
1454 // 'clever' UI hack: only erase large items if previously slected
1455 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
1470 DocIterator save = *this;
1471 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1472 this->dispatch(cmd);
1473 if (disp_.dispatched())
1476 autocorrect() = false;
1484 DocIterator save = *this;
1485 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1486 this->dispatch(cmd);
1487 if (disp_.dispatched())
1490 autocorrect() = false;
1495 bool Cursor::macroModeClose()
1499 InsetMathUnknown * p = activeMacro();
1501 MathData selection(buffer());
1502 asArray(p->selection(), selection);
1503 docstring const s = p->name();
1505 cell().erase(pos());
1507 // do nothing if the macro name is empty
1511 // trigger updates of macros, at least, if no full
1512 // updates take place anyway
1513 updateFlags(Update::Force);
1515 docstring const name = s.substr(1);
1516 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1517 if (in && in->interpretString(*this, s))
1519 MathAtom atom = buffer()->getMacro(name, *this, false) ?
1520 MathAtom(new MathMacro(buffer(), name)) : createInsetMath(name, buffer());
1522 // try to put argument into macro, if we just inserted a macro
1523 bool macroArg = false;
1524 MathMacro * atomAsMacro = atom.nucleus()->asMacro();
1526 // macros here are still unfolded (in init mode in fact). So
1527 // we have to resolve the macro here manually and check its arity
1528 // to put the selection behind it if arity > 0.
1529 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1530 if (selection.size() > 0 && data && data->numargs() - data->optionals() > 0) {
1532 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1534 // non-greedy case. Do not touch the arguments behind
1535 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1538 // insert remembered selection into first argument of a non-macro
1539 else if (atom.nucleus()->nargs() > 0)
1540 atom.nucleus()->cell(0).append(selection);
1544 // finally put the macro argument behind, if needed
1546 if (selection.size() > 1 || selection[0]->asScriptInset())
1547 plainInsert(MathAtom(new InsetMathBrace(selection)));
1556 docstring Cursor::macroName()
1558 return inMacroMode() ? activeMacro()->name() : docstring();
1562 void Cursor::handleNest(MathAtom const & a, int c)
1564 //lyxerr << "Cursor::handleNest: " << c << endl;
1566 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1569 pushBackward(*nextInset());
1573 int Cursor::targetX() const
1575 if (x_target() != -1)
1584 int Cursor::textTargetOffset() const
1586 return textTargetOffset_;
1590 void Cursor::setTargetX()
1599 bool Cursor::inMacroMode() const
1605 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1606 return p && !p->final();
1610 InsetMathUnknown * Cursor::activeMacro()
1612 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1616 InsetMathUnknown const * Cursor::activeMacro() const
1618 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1622 void Cursor::pullArg()
1625 MathData ar = cell();
1626 if (popBackward() && inMathed()) {
1628 cell().insert(pos(), ar);
1631 //formula()->mutateToText();
1636 void Cursor::touch()
1640 DocIterator::const_iterator it = begin();
1641 DocIterator::const_iterator et = end();
1642 for ( ; it != et; ++it)
1648 void Cursor::normalize()
1650 if (idx() > lastidx()) {
1651 lyxerr << "this should not really happen - 1: "
1652 << idx() << ' ' << nargs()
1653 << " in: " << &inset() << endl;
1657 if (pos() > lastpos()) {
1658 lyxerr << "this should not really happen - 2: "
1659 << pos() << ' ' << lastpos() << " in idx: " << idx()
1661 odocstringstream os;
1662 WriteStream wi(os, false, true, WriteStream::wsDefault);
1663 inset().asInsetMath()->write(wi);
1664 lyxerr << to_utf8(os.str()) << endl;
1670 bool Cursor::upDownInMath(bool up)
1672 // Be warned: The 'logic' implemented in this function is highly
1673 // fragile. A distance of one pixel or a '<' vs '<=' _really
1674 // matters. So fiddle around with it only if you think you know
1675 // what you are doing!
1679 xo = beforeDispatchPosX_;
1681 // check if we had something else in mind, if not, this is the future
1683 if (x_target_ == -1)
1685 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1686 // In text mode inside the line (not left or right) possibly set a new target_x,
1687 // but only if we are somewhere else than the previous target-offset.
1689 // We want to keep the x-target on subsequent up/down movements
1690 // that cross beyond the end of short lines. Thus a special
1691 // handling when the cursor is at the end of line: Use the new
1692 // x-target only if the old one was before the end of line
1693 // or the old one was after the beginning of the line
1694 bool inRTL = isWithinRtlParagraph(*this);
1698 left = pos() == textRow().endpos();
1699 right = pos() == textRow().pos();
1701 left = pos() == textRow().pos();
1702 right = pos() == textRow().endpos();
1704 if ((!left && !right) ||
1705 (left && !right && xo < x_target_) ||
1706 (!left && right && x_target_ < xo))
1713 // try neigbouring script insets
1715 if (inMathed() && !selection()) {
1718 InsetMathScript const * p = prevAtom()->asScriptInset();
1719 if (p && p->has(up)) {
1721 push(*const_cast<InsetMathScript*>(p));
1722 idx() = p->idxOfScript(up);
1725 // we went in the right direction? Otherwise don't jump into the script
1729 int oy = beforeDispatchPosY_;
1730 if ((!up && y <= oy) ||
1739 if (pos() != lastpos()) {
1740 InsetMathScript const * p = nextAtom()->asScriptInset();
1741 if (p && p->has(up)) {
1742 push(*const_cast<InsetMathScript*>(p));
1743 idx() = p->idxOfScript(up);
1746 // we went in the right direction? Otherwise don't jump into the script
1750 int oy = beforeDispatchPosY_;
1751 if ((!up && y <= oy) ||
1760 // try to find an inset that knows better then we,
1761 if (inset().idxUpDown(*this, up)) {
1762 //lyxerr << "idxUpDown triggered" << endl;
1763 // try to find best position within this inset
1765 setCursor(bruteFind2(*this, xo, yo));
1769 // any improvement going just out of inset?
1770 if (popBackward() && inMathed()) {
1771 //lyxerr << "updown: popBackward succeeded" << endl;
1774 int yold = beforeDispatchPosY_;
1776 if (up ? ynew < yold : ynew > yold)
1780 // no success, we are probably at the document top or bottom
1786 bool Cursor::atFirstOrLastRow(bool up)
1788 TextMetrics const & tm = bv_->textMetrics(text());
1789 ParagraphMetrics const & pm = tm.parMetrics(pit());
1792 if (pos() && boundary())
1793 row = pm.pos2row(pos() - 1);
1795 row = pm.pos2row(pos());
1798 if (pit() == 0 && row == 0)
1801 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1802 row + 1 >= int(pm.rows().size()))
1808 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1810 LASSERT(text(), /**/);
1816 xo = beforeDispatchPosX_;
1818 // update the targetX - this is here before the "return false"
1819 // to set a new target which can be used by InsetTexts above
1820 // if we cannot move up/down inside this inset anymore
1821 if (x_target_ == -1)
1823 else if (xo - textTargetOffset() != x_target() &&
1824 depth() == beforeDispatchCursor_.depth()) {
1825 // In text mode inside the line (not left or right) possibly set a new target_x,
1826 // but only if we are somewhere else than the previous target-offset.
1828 // We want to keep the x-target on subsequent up/down movements
1829 // that cross beyond the end of short lines. Thus a special
1830 // handling when the cursor is at the end of line: Use the new
1831 // x-target only if the old one was before the end of line
1832 // or the old one was after the beginning of the line
1833 bool inRTL = isWithinRtlParagraph(*this);
1837 left = pos() == textRow().endpos();
1838 right = pos() == textRow().pos();
1840 left = pos() == textRow().pos();
1841 right = pos() == textRow().endpos();
1843 if ((!left && !right) ||
1844 (left && !right && xo < x_target_) ||
1845 (!left && right && x_target_ < xo))
1852 // first get the current line
1853 TextMetrics & tm = bv_->textMetrics(text());
1854 ParagraphMetrics const & pm = tm.parMetrics(pit());
1856 if (pos() && boundary())
1857 row = pm.pos2row(pos() - 1);
1859 row = pm.pos2row(pos());
1861 if (atFirstOrLastRow(up)) {
1862 // Is there a place for the cursor to go ? If yes, we
1863 // can execute the DEPM, otherwise we should keep the
1864 // paragraph to host the cursor.
1865 Cursor dummy = *this;
1866 bool valid_destination = false;
1867 for(; dummy.depth(); dummy.pop())
1868 if (!dummy.atFirstOrLastRow(up)) {
1869 valid_destination = true;
1873 // will a next dispatch follow and if there is a new
1874 // dispatch will it move the cursor out ?
1875 if (depth() > 1 && valid_destination) {
1876 // The cursor hasn't changed yet. This happens when
1877 // you e.g. move out of an inset. And to give the
1878 // DEPM the possibility of doing something we must
1879 // provide it with two different cursors. (Lgb, vfr)
1881 dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
1882 dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
1884 updateNeeded |= bv().checkDepm(dummy, *this);
1885 updateTextTargetOffset();
1890 // with and without selection are handled differently
1892 int yo = bv().getPos(*this).y_;
1894 // To next/previous row
1896 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1898 tm.editXY(*this, xo, yo + textRow().descent() + 1);
1901 // This happens when you move out of an inset.
1902 // And to give the DEPM the possibility of doing
1903 // something we must provide it with two different
1905 Cursor dummy = *this;
1908 if (bv().checkDepm(dummy, old)) {
1909 updateNeeded = true;
1910 // Make sure that cur gets back whatever happened to dummy(Lgb)
1914 // if there is a selection, we stay out of any inset,
1915 // and just jump to the right position:
1921 } else if (pit() > 0) {
1923 TextMetrics & tm = bv_->textMetrics(text());
1924 if (!tm.contains(pit()))
1925 tm.newParMetricsUp();
1926 ParagraphMetrics const & pmcur = tm.parMetrics(pit());
1927 next_row = pmcur.rows().size() - 1;
1930 if (row + 1 < int(pm.rows().size())) {
1932 } else if (pit() + 1 < int(text()->paragraphs().size())) {
1934 TextMetrics & tm = bv_->textMetrics(text());
1935 if (!tm.contains(pit()))
1936 tm.newParMetricsDown();
1940 top().pos() = min(tm.x2pos(pit(), next_row, xo), top().lastpos());
1942 int const xpos = tm.x2pos(pit(), next_row, xo);
1943 bool const at_end_row = xpos == tm.x2pos(pit(), next_row, tm.width());
1944 bool const at_beg_row = xpos == tm.x2pos(pit(), next_row, 0);
1946 if (at_end_row && at_beg_row)
1947 // make sure the cursor ends up on this row
1950 boundary(at_end_row);
1952 updateNeeded |= bv().checkDepm(*this, old);
1955 updateTextTargetOffset();
1960 void Cursor::handleFont(string const & font)
1962 LYXERR(Debug::DEBUG, font);
1966 safe = cap::grabAndEraseSelection(*this);
1971 if (lastpos() != 0) {
1972 // something left in the cell
1974 // cursor in first position
1976 } else if (pos() == lastpos()) {
1977 // cursor in last position
1980 // cursor in between. split cell
1981 MathData::iterator bt = cell().begin();
1982 MathAtom at = createInsetMath(from_utf8(font), buffer());
1983 at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
1984 cell().erase(bt, bt + pos());
1989 // nothing left in the cell
1998 void Cursor::message(docstring const & msg) const
2000 disp_.setMessage(msg);
2004 void Cursor::errorMessage(docstring const & msg) const
2006 disp_.setMessage(msg);
2007 disp_.setError(true);
2011 static docstring parbreak(InsetCode code)
2013 odocstringstream os;
2015 // only add blank line if we're not in an ERT or Listings inset
2016 if (code != ERT_CODE && code != LISTINGS_CODE)
2022 docstring Cursor::selectionAsString(bool with_label) const
2028 return cap::grabSelection(*this);
2030 int const label = with_label
2031 ? AS_STR_LABEL | AS_STR_INSETS : AS_STR_INSETS;
2033 idx_type const startidx = selBegin().idx();
2034 idx_type const endidx = selEnd().idx();
2035 if (startidx != endidx) {
2036 // multicell selection
2037 InsetTabular * table = inset().asInsetTabular();
2038 LASSERT(table, return docstring());
2039 return table->asString(startidx, endidx);
2042 ParagraphList const & pars = text()->paragraphs();
2044 pit_type const startpit = selBegin().pit();
2045 pit_type const endpit = selEnd().pit();
2046 size_t const startpos = selBegin().pos();
2047 size_t const endpos = selEnd().pos();
2049 if (startpit == endpit)
2050 return pars[startpit].asString(startpos, endpos, label);
2052 // First paragraph in selection
2053 docstring result = pars[startpit].
2054 asString(startpos, pars[startpit].size(), label)
2055 + parbreak(inset().lyxCode());
2057 // The paragraphs in between (if any)
2058 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
2059 Paragraph const & par = pars[pit];
2060 result += par.asString(0, par.size(), label)
2061 + parbreak(inset().lyxCode());
2064 // Last paragraph in selection
2065 result += pars[endpit].asString(0, endpos, label);
2071 docstring Cursor::currentState() const
2074 odocstringstream os;
2080 return text()->currentState(*this);
2086 docstring Cursor::getPossibleLabel() const
2088 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
2092 Encoding const * Cursor::getEncoding() const
2096 CursorSlice const & sl = innerTextSlice();
2097 Text const & text = *sl.text();
2098 Font font = text.getPar(sl.pit()).getFont(
2099 bv().buffer().params(), sl.pos(), text.outerFont(sl.pit()));
2100 return font.language()->encoding();
2104 void Cursor::undispatched()
2106 disp_.dispatched(false);
2110 void Cursor::dispatched()
2112 disp_.dispatched(true);
2116 void Cursor::updateFlags(Update::flags f)
2122 void Cursor::noUpdate()
2124 disp_.update(Update::None);
2128 Font Cursor::getFont() const
2130 // The logic here should more or less match to the Cursor::setCurrentFont
2131 // logic, i.e. the cursor height should give a hint what will happen
2132 // if a character is entered.
2134 // HACK. far from being perfect...
2136 CursorSlice const & sl = innerTextSlice();
2137 Text const & text = *sl.text();
2138 Paragraph const & par = text.getPar(sl.pit());
2140 // on boundary, so we are really at the character before
2141 pos_type pos = sl.pos();
2142 if (pos > 0 && boundary())
2145 // on space? Take the font before (only for RTL boundary stay)
2147 TextMetrics const & tm = bv().textMetrics(&text);
2148 if (pos == sl.lastpos()
2149 || (par.isSeparator(pos)
2150 && !tm.isRTLBoundary(sl.pit(), pos)))
2154 // get font at the position
2155 Font font = par.getFont(buffer()->params(), pos,
2156 text.outerFont(sl.pit()));
2162 bool Cursor::fixIfBroken()
2164 bool const broken_cursor = DocIterator::fixIfBroken();
2165 bool const broken_anchor = anchor_.fixIfBroken();
2167 if (broken_cursor || broken_anchor) {
2175 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2177 // find inset in common
2179 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2180 if (&old[i].inset() != &cur[i].inset())
2184 // update words if we just moved to another paragraph
2185 if (i == old.depth() && i == cur.depth()
2186 && !cur.buffer()->isClean()
2187 && cur.inTexted() && old.inTexted()
2188 && cur.pit() != old.pit()) {
2189 old.paragraph().updateWords();
2192 // notify everything on top of the common part in old cursor,
2193 // but stop if the inset claims the cursor to be invalid now
2194 for (size_type j = i; j < old.depth(); ++j) {
2195 Cursor inset_pos = old;
2196 inset_pos.cutOff(j);
2197 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2201 // notify everything on top of the common part in new cursor,
2202 // but stop if the inset claims the cursor to be invalid now
2203 for (; i < cur.depth(); ++i) {
2204 if (cur[i].inset().notifyCursorEnters(cur))
2212 void Cursor::setCurrentFont()
2214 CursorSlice const & cs = innerTextSlice();
2215 Paragraph const & par = cs.paragraph();
2216 pos_type cpit = cs.pit();
2217 pos_type cpos = cs.pos();
2218 Text const & ctext = *cs.text();
2219 TextMetrics const & tm = bv().textMetrics(&ctext);
2221 // are we behind previous char in fact? -> go to that char
2222 if (cpos > 0 && boundary())
2225 // find position to take the font from
2227 // paragraph end? -> font of last char
2228 if (cpos == lastpos())
2230 // on space? -> look at the words in front of space
2231 else if (cpos > 0 && par.isSeparator(cpos)) {
2232 // abc| def -> font of c
2233 // abc |[WERBEH], i.e. boundary==true -> font of c
2234 // abc [WERBEH]| def, font of the space
2235 if (!tm.isRTLBoundary(cpit, cpos))
2241 BufferParams const & bufparams = buffer()->params();
2242 current_font = par.getFontSettings(bufparams, cpos);
2243 real_current_font = tm.displayFont(cpit, cpos);
2245 // special case for paragraph end
2246 if (cs.pos() == lastpos()
2247 && tm.isRTLBoundary(cpit, cs.pos())
2249 Language const * lang = par.getParLanguage(bufparams);
2250 current_font.setLanguage(lang);
2251 current_font.fontInfo().setNumber(FONT_OFF);
2252 real_current_font.setLanguage(lang);
2253 real_current_font.fontInfo().setNumber(FONT_OFF);
2258 bool Cursor::textUndo()
2260 DocIterator dit = *this;
2261 // Undo::textUndo() will modify dit.
2262 if (!buffer()->undo().textUndo(dit))
2272 bool Cursor::textRedo()
2274 DocIterator dit = *this;
2275 // Undo::textRedo() will modify dit.
2276 if (!buffer()->undo().textRedo(dit))
2286 void Cursor::finishUndo() const
2288 buffer()->undo().finishUndo();
2292 void Cursor::beginUndoGroup() const
2294 buffer()->undo().beginUndoGroup();
2298 void Cursor::endUndoGroup() const
2300 buffer()->undo().endUndoGroup();
2304 void Cursor::recordUndo(UndoKind kind, pit_type from, pit_type to) const
2306 buffer()->undo().recordUndo(*this, kind, from, to);
2310 void Cursor::recordUndo(UndoKind kind, pit_type from) const
2312 buffer()->undo().recordUndo(*this, kind, from);
2316 void Cursor::recordUndo(UndoKind kind) const
2318 buffer()->undo().recordUndo(*this, kind);
2322 void Cursor::recordUndoInset(UndoKind kind) const
2324 buffer()->undo().recordUndoInset(*this, kind);
2328 void Cursor::recordUndoFullDocument() const
2330 buffer()->undo().recordUndoFullDocument(*this);
2334 void Cursor::recordUndoSelection() const
2337 if (cap::multipleCellsSelected(*this))
2342 buffer()->undo().recordUndo(*this, ATOMIC_UNDO,
2343 selBegin().pit(), selEnd().pit());
2348 void Cursor::checkBufferStructure()
2350 Buffer const * master = buffer()->masterBuffer();
2351 master->tocBackend().updateItem(*this);
2352 if (master != buffer() && !master->hasGuiDelegate())
2353 // In case the master has no gui associated with it,
2354 // the TocItem is not updated (part of bug 5699).
2355 buffer()->tocBackend().updateItem(*this);