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 map<Inset const *, Geometry> const & data =
99 c.bv().coordCache().getInsets().getData();
100 map<Inset const *, Geometry>::const_iterator I = data.find(inset);
102 // FIXME: in the case where the inset is not in the cache, this
103 // means that no part of it is visible on screen. In this case
104 // we don't do elaborate search and we just return the forwarded
105 // DocIterator at its beginning.
106 if (I == data.end()) {
111 Point o = I->second.pos;
112 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
113 // Convert to absolute
116 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
117 // '<=' in order to take the last possible position
118 // this is important for clicking behind \sum in e.g. '\sum_i a'
119 LYXERR(Debug::DEBUG, "i: " << i << " d: " << d
120 << " best: " << best_dist);
121 if (d <= best_dist) {
134 /// moves position closest to (x, y) in given box
135 bool bruteFind(Cursor & cursor,
136 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
138 LASSERT(!cursor.empty(), return false);
139 Inset & inset = cursor[0].inset();
140 BufferView & bv = cursor.bv();
142 CoordCache::InnerParPosCache const & cache =
143 bv.coordCache().getParPos().find(cursor.bottom().text())->second;
144 // Get an iterator on the first paragraph in the cache
145 DocIterator it(inset);
146 it.push_back(CursorSlice(inset));
147 it.pit() = cache.begin()->first;
148 // Get an iterator after the last paragraph in the cache
149 DocIterator et(inset);
150 et.push_back(CursorSlice(inset));
151 et.pit() = boost::prior(cache.end())->first;
152 if (et.pit() >= et.lastpit())
153 et = doc_iterator_end(inset);
157 double best_dist = numeric_limits<double>::max();;
158 DocIterator best_cursor = et;
160 for ( ; it != et; it.forwardPos(true)) {
161 // avoid invalid nesting when selecting
162 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
163 Point p = bv.getPos(it, false);
166 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
167 double const dx = xo - x;
168 double const dy = yo - y;
169 double const d = dx * dx + dy * dy;
170 // '<=' in order to take the last possible position
171 // this is important for clicking behind \sum in e.g. '\sum_i a'
172 if (d <= best_dist) {
173 // lyxerr << "*" << endl;
181 if (best_cursor != et) {
182 cursor.setCursor(best_cursor);
191 /// moves position closest to (x, y) in given box
192 bool bruteFind3(Cursor & cur, int x, int y, bool up)
194 BufferView & bv = cur.bv();
195 int ylow = up ? 0 : y + 1;
196 int yhigh = up ? y - 1 : bv.workHeight();
198 int xhigh = bv.workWidth();
200 // FIXME: bit more work needed to get 'from' and 'to' right.
201 pit_type from = cur.bottom().pit();
202 //pit_type to = cur.bottom().pit();
203 //lyxerr << "Pit start: " << from << endl;
205 //lyxerr << "bruteFind3: x: " << x << " y: " << y
206 // << " xlow: " << xlow << " xhigh: " << xhigh
207 // << " ylow: " << ylow << " yhigh: " << yhigh
209 DocIterator it = doc_iterator_begin(cur.buffer());
211 DocIterator et = doc_iterator_end(cur.buffer());
213 double best_dist = numeric_limits<double>::max();
214 DocIterator best_cursor = et;
216 for ( ; it != et; it.forwardPos()) {
217 // avoid invalid nesting when selecting
218 if (bv.cursorStatus(it) == CUR_INSIDE
219 && (!cur.selection() || positionable(it, cur.realAnchor()))) {
220 // If this function is ever used again, check whether this
221 // is the same as "bv.getPos(it, false)" with boundary = false.
222 Point p = bv.getPos(it);
225 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
226 double const dx = xo - x;
227 double const dy = yo - y;
228 double const d = dx * dx + dy * dy;
229 //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
230 // << " dx: " << dx << " dy: " << dy
231 // << " idx: " << it.idx() << " pos: " << it.pos()
234 // '<=' in order to take the last possible position
235 // this is important for clicking behind \sum in e.g. '\sum_i a'
236 if (d <= best_dist) {
237 //lyxerr << "*" << endl;
245 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
246 if (best_cursor == et)
248 cur.setCursor(best_cursor);
255 // be careful: this is called from the bv's constructor, too, so
256 // bv functions are not yet available!
257 Cursor::Cursor(BufferView & bv)
258 : DocIterator(&bv.buffer()), bv_(&bv), anchor_(),
259 x_target_(-1), textTargetOffset_(0),
260 selection_(false), mark_(false), word_selection_(false),
261 logicalpos_(false), current_font(inherit_font)
268 push_back(CursorSlice(buffer()->inset()));
269 anchor_ = doc_iterator_begin(buffer());
277 // this (intentionally) does neither touch anchor nor selection status
278 void Cursor::setCursor(DocIterator const & cur)
280 DocIterator::operator=(cur);
284 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
288 // Try to fix cursor in case it is broken.
291 // Is this a function that acts on inset at point?
292 Inset * inset = cur.nextInset();
293 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
294 && inset && inset->getStatus(cur, cmd, status))
297 // This is, of course, a mess. Better create a new doc iterator and use
298 // this in Inset::getStatus. This might require an additional
299 // BufferView * arg, though (which should be avoided)
300 //Cursor safe = *this;
302 for ( ; cur.depth(); cur.pop()) {
303 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
304 LASSERT(cur.idx() <= cur.lastidx(), /**/);
305 LASSERT(cur.pit() <= cur.lastpit(), /**/);
306 LASSERT(cur.pos() <= cur.lastpos(), /**/);
308 // The inset's getStatus() will return 'true' if it made
309 // a definitive decision on whether it want to handle the
310 // request or not. The result of this decision is put into
311 // the 'status' parameter.
312 if (cur.inset().getStatus(cur, cmd, status)) {
321 void Cursor::saveBeforeDispatchPosXY()
323 getPos(beforeDispatchPosX_, beforeDispatchPosY_);
327 void Cursor::dispatch(FuncRequest const & cmd0)
329 LYXERR(Debug::DEBUG, "cmd: " << cmd0 << '\n' << *this);
334 FuncRequest cmd = cmd0;
336 disp_ = DispatchResult();
338 buffer()->undo().beginUndoGroup();
340 // Is this a function that acts on inset at point?
341 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
343 disp_.dispatched(true);
344 disp_.screenUpdate(Update::FitCursor | Update::Force);
345 FuncRequest tmpcmd = cmd;
346 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
347 << cmd0 << endl << *this);
348 nextInset()->dispatch(*this, tmpcmd);
349 if (disp_.dispatched()) {
350 buffer()->undo().endUndoGroup();
355 // store some values to be used inside of the handlers
356 beforeDispatchCursor_ = *this;
357 for (; depth(); pop(), boundary(false)) {
358 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
359 << cmd0 << endl << *this);
360 LASSERT(pos() <= lastpos(), /**/);
361 LASSERT(idx() <= lastidx(), /**/);
362 LASSERT(pit() <= lastpit(), /**/);
364 // The common case is 'LFUN handled, need update', so make the
365 // LFUN handler's life easier by assuming this as default value.
366 // The handler can reset the update and val flags if necessary.
367 disp_.screenUpdate(Update::FitCursor | Update::Force);
368 disp_.dispatched(true);
369 inset().dispatch(*this, cmd);
370 if (disp_.dispatched())
374 // it completely to get a 'bomb early' behaviour in case this
375 // object will be used again.
376 if (!disp_.dispatched()) {
377 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
378 // We might have invalidated the cursor when removing an empty
379 // paragraph while the cursor could not be moved out the inset
380 // while we initially thought we could. This might happen when
381 // a multiline inset becomes an inline inset when the second
382 // paragraph is removed.
383 if (safe.pit() > safe.lastpit()) {
384 safe.pit() = safe.lastpit();
385 safe.pos() = safe.lastpos();
388 disp_.screenUpdate(Update::None);
389 disp_.dispatched(false);
391 // restore the previous one because nested Cursor::dispatch calls
392 // are possible which would change it
393 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
395 buffer()->undo().endUndoGroup();
399 DispatchResult const & Cursor::result() const
405 BufferView & Cursor::bv() const
414 LASSERT(depth() >= 1, /**/);
419 void Cursor::push(Inset & p)
421 push_back(CursorSlice(p));
422 p.setBuffer(*buffer());
426 void Cursor::pushBackward(Inset & p)
428 LASSERT(!empty(), return);
429 //lyxerr << "Entering inset " << t << " front" << endl;
435 bool Cursor::popBackward()
437 LASSERT(!empty(), return false);
445 bool Cursor::popForward()
447 LASSERT(!empty(), return false);
448 //lyxerr << "Leaving inset from in back" << endl;
449 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
453 pos() += lastpos() - lp + 1;
458 int Cursor::currentMode()
460 LASSERT(!empty(), /**/);
461 for (int i = depth() - 1; i >= 0; --i) {
462 int res = operator[](i).inset().currentMode();
463 bool locked_mode = operator[](i).inset().lockedMode();
464 // Also return UNDECIDED_MODE when the mode is locked,
465 // as in this case it is treated the same as TEXT_MODE
466 if (res != Inset::UNDECIDED_MODE || locked_mode)
469 return Inset::TEXT_MODE;
473 void Cursor::getPos(int & x, int & y) const
475 Point p = bv().getPos(*this);
481 Row const & Cursor::textRow() const
483 CursorSlice const & cs = innerTextSlice();
484 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
485 LASSERT(!pm.rows().empty(), /**/);
486 return pm.getRow(pos(), boundary());
490 void Cursor::resetAnchor()
496 void Cursor::setCursorToAnchor()
499 DocIterator normal = anchor_;
500 while (depth() < normal.depth())
502 if (depth() < anchor_.depth() && top() <= anchor_[depth() - 1])
509 bool Cursor::posBackward()
518 bool Cursor::posForward()
520 if (pos() == lastpos())
527 bool Cursor::posVisRight(bool skip_inset)
529 Cursor new_cur = *this; // where we will move to
530 pos_type left_pos; // position visually left of current cursor
531 pos_type right_pos; // position visually right of current cursor
532 bool new_pos_is_RTL; // is new position we're moving to RTL?
534 getSurroundingPos(left_pos, right_pos);
536 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
538 // Are we at an inset?
539 new_cur.pos() = right_pos;
540 new_cur.boundary(false);
542 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
543 // we actually move the cursor at the end of this function, for now
544 // we just keep track of the new position in new_cur...
545 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
548 // Are we already at rightmost pos in row?
549 else if (text()->empty() || right_pos == -1) {
552 if (!new_cur.posVisToNewRow(false)) {
553 LYXERR(Debug::RTL, "not moving!");
557 // we actually move the cursor at the end of this function, for now
558 // just keep track of the new position in new_cur...
559 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
560 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
563 // normal movement to the right
566 // Recall, if the cursor is at position 'x', that means *before*
567 // the character at position 'x'. In RTL, "before" means "to the
568 // right of", in LTR, "to the left of". So currently our situation
569 // is this: the position to our right is 'right_pos' (i.e., we're
570 // currently to the left of 'right_pos'). In order to move to the
571 // right, it depends whether or not the character at 'right_pos' is RTL.
572 new_pos_is_RTL = paragraph().getFontSettings(
573 buffer()->params(), right_pos).isVisibleRightToLeft();
574 // If the character at 'right_pos' *is* LTR, then in order to move to
575 // the right of it, we need to be *after* 'right_pos', i.e., move to
576 // position 'right_pos' + 1.
577 if (!new_pos_is_RTL) {
578 new_cur.pos() = right_pos + 1;
579 // set the boundary to true in two situations:
581 // 1. if new_pos is now lastpos, and we're in an RTL paragraph
582 // (this means that we're moving right to the end of an LTR chunk
583 // which is at the end of an RTL paragraph);
584 (new_cur.pos() == lastpos()
585 && paragraph().isRTL(buffer()->params()))
586 // 2. if the position *after* right_pos is RTL (we want to be
587 // *after* right_pos, not before right_pos + 1!)
588 || paragraph().getFontSettings(buffer()->params(),
589 new_cur.pos()).isVisibleRightToLeft()
591 new_cur.boundary(true);
592 else // set the boundary to false
593 new_cur.boundary(false);
595 // Otherwise (if the character at position 'right_pos' is RTL), then
596 // moving to the right of it is as easy as setting the new position
599 new_cur.pos() = right_pos;
600 new_cur.boundary(false);
605 bool moved = (new_cur.pos() != pos()
606 || new_cur.pit() != pit()
607 || new_cur.boundary() != boundary()
608 || &new_cur.inset() != &inset());
611 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
612 << (new_cur.boundary() ? " (boundary)" : ""));
620 bool Cursor::posVisLeft(bool skip_inset)
622 Cursor new_cur = *this; // where we will move to
623 pos_type left_pos; // position visually left of current cursor
624 pos_type right_pos; // position visually right of current cursor
625 bool new_pos_is_RTL; // is new position we're moving to RTL?
627 getSurroundingPos(left_pos, right_pos);
629 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
631 // Are we at an inset?
632 new_cur.pos() = left_pos;
633 new_cur.boundary(false);
635 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
636 // we actually move the cursor at the end of this function, for now
637 // we just keep track of the new position in new_cur...
638 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
641 // Are we already at leftmost pos in row?
642 else if (text()->empty() || left_pos == -1) {
645 if (!new_cur.posVisToNewRow(true)) {
646 LYXERR(Debug::RTL, "not moving!");
650 // we actually move the cursor at the end of this function, for now
651 // just keep track of the new position in new_cur...
652 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
653 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
656 // normal movement to the left
659 // Recall, if the cursor is at position 'x', that means *before*
660 // the character at position 'x'. In RTL, "before" means "to the
661 // right of", in LTR, "to the left of". So currently our situation
662 // is this: the position to our left is 'left_pos' (i.e., we're
663 // currently to the right of 'left_pos'). In order to move to the
664 // left, it depends whether or not the character at 'left_pos' is RTL.
665 new_pos_is_RTL = paragraph().getFontSettings(
666 buffer()->params(), left_pos).isVisibleRightToLeft();
667 // If the character at 'left_pos' *is* RTL, then in order to move to
668 // the left of it, we need to be *after* 'left_pos', i.e., move to
669 // position 'left_pos' + 1.
670 if (new_pos_is_RTL) {
671 new_cur.pos() = left_pos + 1;
672 // set the boundary to true in two situations:
674 // 1. if new_pos is now lastpos and we're in an LTR paragraph
675 // (this means that we're moving left to the end of an RTL chunk
676 // which is at the end of an LTR paragraph);
677 (new_cur.pos() == lastpos()
678 && !paragraph().isRTL(buffer()->params()))
679 // 2. if the position *after* left_pos is not RTL (we want to be
680 // *after* left_pos, not before left_pos + 1!)
681 || !paragraph().getFontSettings(buffer()->params(),
682 new_cur.pos()).isVisibleRightToLeft()
684 new_cur.boundary(true);
685 else // set the boundary to false
686 new_cur.boundary(false);
688 // Otherwise (if the character at position 'left_pos' is LTR), then
689 // moving to the left of it is as easy as setting the new position
692 new_cur.pos() = left_pos;
693 new_cur.boundary(false);
698 bool moved = (new_cur.pos() != pos()
699 || new_cur.pit() != pit()
700 || new_cur.boundary() != boundary());
703 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
704 << (new_cur.boundary() ? " (boundary)" : ""));
712 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos)
714 // preparing bidi tables
715 Paragraph const & par = paragraph();
716 Buffer const & buf = *buffer();
717 Row const & row = textRow();
719 bidi.computeTables(par, buf, row);
721 LYXERR(Debug::RTL, "bidi: " << row.pos() << "--" << row.endpos());
723 // The cursor is painted *before* the character at pos(), or, if 'boundary'
724 // is true, *after* the character at (pos() - 1). So we already have one
725 // known position around the cursor:
726 pos_type const known_pos = boundary() && pos() > 0 ? pos() - 1 : pos();
728 // edge case: if we're at the end of the paragraph, things are a little
729 // different (because lastpos is a position which does not really "exist"
730 // --- there's no character there yet).
731 if (known_pos == lastpos()) {
732 if (par.isRTL(buf.params())) {
734 right_pos = bidi.vis2log(row.pos());
738 left_pos = bidi.vis2log(row.endpos() - 1);
743 // Whether 'known_pos' is to the left or to the right of the cursor depends
744 // on whether it is an RTL or LTR character...
745 bool const cur_is_RTL =
746 par.getFontSettings(buf.params(), known_pos).isVisibleRightToLeft();
747 // ... in the following manner:
748 // For an RTL character, "before" means "to the right" and "after" means
749 // "to the left"; and for LTR, it's the reverse. So, 'known_pos' is to the
750 // right of the cursor if (RTL && boundary) or (!RTL && !boundary):
751 bool const known_pos_on_right = cur_is_RTL == boundary();
753 // So we now know one of the positions surrounding the cursor. Let's
754 // determine the other one:
755 if (known_pos_on_right) {
756 right_pos = known_pos;
757 // *visual* position of 'left_pos':
758 pos_type v_left_pos = bidi.log2vis(right_pos) - 1;
759 // If the position we just identified as 'left_pos' is a "skipped
760 // separator" (a separator which is at the logical end of a row,
761 // except for the last row in a paragraph; such separators are not
762 // painted, so they "are not really there"; note that in bidi text,
763 // such a separator could appear visually in the middle of a row),
764 // set 'left_pos' to the *next* position to the left.
765 if (bidi.inRange(v_left_pos)
766 && bidi.vis2log(v_left_pos) + 1 == row.endpos()
767 && row.endpos() < lastpos()
768 && par.isSeparator(bidi.vis2log(v_left_pos)))
771 // calculate the logical position of 'left_pos', if in row
772 if (!bidi.inRange(v_left_pos))
775 left_pos = bidi.vis2log(v_left_pos);
776 // If the position we identified as 'right_pos' is a "skipped
777 // separator", set 'right_pos' to the *next* position to the right.
778 if (right_pos + 1 == row.endpos() && row.endpos() < lastpos()
779 && par.isSeparator(right_pos)) {
780 pos_type const v_right_pos = bidi.log2vis(right_pos) + 1;
781 if (!bidi.inRange(v_right_pos))
784 right_pos = bidi.vis2log(v_right_pos);
787 // known_pos is on the left
788 left_pos = known_pos;
789 // *visual* position of 'right_pos'
790 pos_type v_right_pos = bidi.log2vis(left_pos) + 1;
791 // If the position we just identified as 'right_pos' is a "skipped
792 // separator", set 'right_pos' to the *next* position to the right.
793 if (bidi.inRange(v_right_pos)
794 && bidi.vis2log(v_right_pos) + 1 == row.endpos()
795 && row.endpos() < lastpos()
796 && par.isSeparator(bidi.vis2log(v_right_pos)))
799 // calculate the logical position of 'right_pos', if in row
800 if (!bidi.inRange(v_right_pos))
803 right_pos = bidi.vis2log(v_right_pos);
804 // If the position we identified as 'left_pos' is a "skipped
805 // separator", set 'left_pos' to the *next* position to the left.
806 if (left_pos + 1 == row.endpos() && row.endpos() < lastpos()
807 && par.isSeparator(left_pos)) {
808 pos_type const v_left_pos = bidi.log2vis(left_pos) - 1;
809 if (!bidi.inRange(v_left_pos))
812 left_pos = bidi.vis2log(v_left_pos);
819 bool Cursor::posVisToNewRow(bool movingLeft)
821 Paragraph const & par = paragraph();
822 Buffer const & buf = *buffer();
823 Row const & row = textRow();
824 bool par_is_LTR = !par.isRTL(buf.params());
826 // Inside a table, determining whether to move to the next or previous row
827 // should be done based on the table's direction.
829 if (s >= 1 && (*this)[s].inset().asInsetTabular()) {
830 par_is_LTR = !(*this)[s].inset().asInsetTabular()->isRightToLeft(*this);
831 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
834 // if moving left in an LTR paragraph or moving right in an RTL one,
835 // move to previous row
836 if (par_is_LTR == movingLeft) {
837 if (row.pos() == 0) { // we're at first row in paragraph
838 if (pit() == 0) // no previous paragraph! don't move
840 // move to last pos in previous par
844 } else { // move to previous row in this par
845 pos() = row.pos() - 1; // this is guaranteed to be in previous row
849 // if moving left in an RTL paragraph or moving right in an LTR one,
852 if (row.endpos() == lastpos()) { // we're at last row in paragraph
853 if (pit() == lastpit()) // last paragraph! don't move
855 // move to first row in next par
859 } else { // move to next row in this par
860 pos() = row.endpos();
865 // make sure we're at left-/right-most pos in new row
866 posVisToRowExtremity(!movingLeft);
872 void Cursor::posVisToRowExtremity(bool left)
874 // prepare bidi tables
875 Paragraph const & par = paragraph();
876 Buffer const & buf = *buffer();
877 Row const & row = textRow();
879 bidi.computeTables(par, buf, row);
881 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
882 << (boundary() ? 1 : 0));
884 if (left) { // move to leftmost position
885 // if this is an RTL paragraph, and we're at the last row in the
886 // paragraph, move to lastpos
887 if (par.isRTL(buf.params()) && row.endpos() == lastpos())
890 pos() = bidi.vis2log(row.pos());
892 // Moving to the leftmost position in the row, the cursor should
893 // normally be placed to the *left* of the leftmost position.
894 // A very common exception, though, is if the leftmost character
895 // also happens to be the separator at the (logical) end of the row
896 // --- in this case, the separator is positioned beyond the left
897 // margin, and we don't want to move the cursor there (moving to
898 // the left of the separator is equivalent to moving to the next
899 // line). So, in this case we actually want to place the cursor
900 // to the *right* of the leftmost position (the separator).
901 // Another exception is if we're moving to the logically last
902 // position in the row, which is *not* a separator: this means
903 // that the entire row has no separators (if there were any, the
904 // row would have been broken there); and therefore in this case
905 // we also move to the *right* of the last position (this indicates
906 // to the user that there is no space after this position, and is
907 // consistent with the behavior in the middle of a row --- moving
908 // right or left moves to the next/previous character; if we were
909 // to move to the *left* of this position, that would simulate
910 // a separator which is not really there!).
911 // Finally, there is an exception to the previous exception: if
912 // this non-separator-but-last-position-in-row is an inset, then
913 // we *do* want to stay to the left of it anyway: this is the
914 // "boundary" which we simulate at insets.
915 // Another exception is when row.endpos() is 0.
917 // do we want to be to the right of pos?
918 // as explained above, if at last pos in row, stay to the right
919 bool const right_of_pos = row.endpos() > 0
920 && pos() == row.endpos() - 1 && !par.isInset(pos());
922 // Now we know if we want to be to the left or to the right of pos,
923 // let's make sure we are where we want to be.
924 bool const new_pos_is_RTL =
925 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
927 if (new_pos_is_RTL != right_of_pos) {
933 // move to rightmost position
934 // if this is an LTR paragraph, and we're at the last row in the
935 // paragraph, move to lastpos
936 if (!par.isRTL(buf.params()) && row.endpos() == lastpos())
939 pos() = row.endpos() > 0 ? bidi.vis2log(row.endpos() - 1) : 0;
941 // Moving to the rightmost position in the row, the cursor should
942 // normally be placed to the *right* of the rightmost position.
943 // A very common exception, though, is if the rightmost character
944 // also happens to be the separator at the (logical) end of the row
945 // --- in this case, the separator is positioned beyond the right
946 // margin, and we don't want to move the cursor there (moving to
947 // the right of the separator is equivalent to moving to the next
948 // line). So, in this case we actually want to place the cursor
949 // to the *left* of the rightmost position (the separator).
950 // Another exception is if we're moving to the logically last
951 // position in the row, which is *not* a separator: this means
952 // that the entire row has no separators (if there were any, the
953 // row would have been broken there); and therefore in this case
954 // we also move to the *left* of the last position (this indicates
955 // to the user that there is no space after this position, and is
956 // consistent with the behavior in the middle of a row --- moving
957 // right or left moves to the next/previous character; if we were
958 // to move to the *right* of this position, that would simulate
959 // a separator which is not really there!).
960 // Finally, there is an exception to the previous exception: if
961 // this non-separator-but-last-position-in-row is an inset, then
962 // we *do* want to stay to the right of it anyway: this is the
963 // "boundary" which we simulate at insets.
964 // Another exception is when row.endpos() is 0.
966 // do we want to be to the left of pos?
967 // as explained above, if at last pos in row, stay to the left,
968 // unless the last position is the same as the first.
969 bool const left_of_pos = row.endpos() > 0
970 && pos() == row.endpos() - 1 && !par.isInset(pos());
972 // Now we know if we want to be to the left or to the right of pos,
973 // let's make sure we are where we want to be.
974 bool const new_pos_is_RTL =
975 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
977 if (new_pos_is_RTL == left_of_pos) {
983 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
984 << (boundary() ? 1 : 0));
988 CursorSlice Cursor::normalAnchor() const
992 LASSERT(anchor_.depth() >= depth(), /**/);
993 CursorSlice normal = anchor_[depth() - 1];
994 if (depth() < anchor_.depth() && top() <= normal) {
995 // anchor is behind cursor -> move anchor behind the inset
1002 DocIterator & Cursor::realAnchor()
1008 CursorSlice Cursor::selBegin() const
1012 return normalAnchor() < top() ? normalAnchor() : top();
1016 CursorSlice Cursor::selEnd() const
1020 return normalAnchor() > top() ? normalAnchor() : top();
1024 DocIterator Cursor::selectionBegin() const
1030 // FIXME: This is a work-around for the problem that
1031 // CursorSlice doesn't keep track of the boundary.
1032 if (normalAnchor() == top())
1033 di = anchor_.boundary() > boundary() ? anchor_ : *this;
1035 di = normalAnchor() < top() ? anchor_ : *this;
1041 DocIterator Cursor::selectionEnd() const
1047 // FIXME: This is a work-around for the problem that
1048 // CursorSlice doesn't keep track of the boundary.
1049 if (normalAnchor() == top())
1050 di = anchor_.boundary() < boundary() ? anchor_ : *this;
1052 di = normalAnchor() > top() ? anchor_ : *this;
1054 if (di.depth() > depth()) {
1062 void Cursor::setSelection()
1065 // A selection with no contents is not a selection
1066 // FIXME: doesnt look ok
1067 if (idx() == normalAnchor().idx() &&
1068 pit() == normalAnchor().pit() &&
1069 pos() == normalAnchor().pos())
1070 setSelection(false);
1074 void Cursor::setSelection(DocIterator const & where, int n)
1083 void Cursor::clearSelection()
1085 setSelection(false);
1086 setWordSelection(false);
1092 void Cursor::setTargetX(int x)
1095 textTargetOffset_ = 0;
1099 int Cursor::x_target() const
1105 void Cursor::clearTargetX()
1108 textTargetOffset_ = 0;
1112 void Cursor::updateTextTargetOffset()
1117 textTargetOffset_ = x - x_target_;
1121 void Cursor::info(odocstream & os) const
1123 for (int i = 1, n = depth(); i < n; ++i) {
1124 operator[](i).inset().infoize(os);
1128 Inset const * inset = prevInset();
1129 // prevInset() can return 0 in certain case.
1131 prevInset()->infoize2(os);
1133 // overwite old message
1138 bool Cursor::selHandle(bool sel)
1140 //lyxerr << "Cursor::selHandle" << endl;
1143 if (sel == selection())
1147 cap::saveSelection(*this);
1155 ostream & operator<<(ostream & os, Cursor const & cur)
1157 os << "\n cursor: | anchor:\n";
1158 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
1159 os << " " << cur[i] << " | ";
1160 if (i < cur.anchor_.depth())
1161 os << cur.anchor_[i];
1163 os << "-------------------------------";
1166 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
1167 os << "------------------------------- | " << cur.anchor_[i] << "\n";
1169 os << " selection: " << cur.selection_
1170 << " x_target: " << cur.x_target_ << endl;
1175 LyXErr & operator<<(LyXErr & os, Cursor const & cur)
1185 ///////////////////////////////////////////////////////////////////
1188 // The part below is the non-integrated rest of the original math
1189 // cursor. This should be either generalized for texted or moved
1190 // back to mathed (in most cases to InsetMathNest).
1192 ///////////////////////////////////////////////////////////////////
1194 #include "mathed/InsetMathChar.h"
1195 #include "mathed/InsetMathGrid.h"
1196 #include "mathed/InsetMathScript.h"
1197 #include "mathed/InsetMathUnknown.h"
1198 #include "mathed/MathFactory.h"
1199 #include "mathed/MathStream.h"
1200 #include "mathed/MathSupport.h"
1205 //#define FILEDEBUG 1
1208 bool Cursor::isInside(Inset const * p) const
1210 for (size_t i = 0; i != depth(); ++i)
1211 if (&operator[](i).inset() == p)
1217 void Cursor::leaveInset(Inset const & inset)
1219 for (size_t i = 0; i != depth(); ++i) {
1220 if (&operator[](i).inset() == &inset) {
1228 bool Cursor::openable(MathAtom const & t) const
1239 // we can't move into anything new during selection
1240 if (depth() >= anchor_.depth())
1242 if (t.nucleus() != &anchor_[depth()].inset())
1249 void Cursor::setScreenPos(int x, int /*y*/)
1252 //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
1257 void Cursor::plainErase()
1259 cell().erase(pos());
1263 void Cursor::markInsert()
1265 insert(char_type(0));
1269 void Cursor::markErase()
1271 cell().erase(pos());
1275 void Cursor::plainInsert(MathAtom const & t)
1277 cell().insert(pos(), t);
1279 inset().setBuffer(bv_->buffer());
1281 forceBufferUpdate();
1285 void Cursor::insert(docstring const & str)
1287 for_each(str.begin(), str.end(),
1288 bind(static_cast<void(Cursor::*)(char_type)>
1289 (&Cursor::insert), this, _1));
1293 void Cursor::insert(char_type c)
1295 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1296 LASSERT(!empty(), /**/);
1298 cap::selClearOrDel(*this);
1299 insert(new InsetMathChar(c));
1301 text()->insertChar(*this, c);
1306 void Cursor::insert(MathAtom const & t)
1308 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1310 cap::selClearOrDel(*this);
1315 void Cursor::insert(Inset * inset0)
1317 LASSERT(inset0, /**/);
1319 insert(MathAtom(inset0->asInsetMath()));
1321 text()->insertInset(*this, inset0);
1322 inset0->setBuffer(bv_->buffer());
1324 if (inset0->isLabeled())
1325 forceBufferUpdate();
1330 void Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1332 MathData ar(buffer());
1334 if (ar.size() == 1 && (enter || selection()))
1341 void Cursor::niceInsert(MathAtom const & t)
1344 docstring const safe = cap::grabAndEraseSelection(*this);
1346 // If possible, enter the new inset and move the contents of the selection
1347 if (t->isActive()) {
1349 // be careful here: don't use 'pushBackward(t)' as this we need to
1350 // push the clone, not the original
1351 pushBackward(*nextInset());
1352 // We may not use niceInsert here (recursion)
1353 MathData ar(buffer());
1360 void Cursor::insert(MathData const & ar)
1364 cap::eraseSelection(*this);
1365 cell().insert(pos(), ar);
1367 // FIXME audit setBuffer calls
1368 inset().setBuffer(bv_->buffer());
1372 bool Cursor::backspace()
1374 autocorrect() = false;
1377 cap::eraseSelection(*this);
1382 // If empty cell, and not part of a big cell
1383 if (lastpos() == 0 && inset().nargs() == 1) {
1385 // Directly delete empty cell: [|[]] => [|]
1391 // [|], can not delete from inside
1402 if (inMacroMode()) {
1403 InsetMathUnknown * p = activeMacro();
1404 if (p->name().size() > 1) {
1405 p->setName(p->name().substr(0, p->name().size() - 1));
1410 if (pos() != 0 && prevAtom()->nargs() > 0) {
1411 // let's require two backspaces for 'big stuff' and
1412 // highlight on the first
1424 bool Cursor::erase()
1426 autocorrect() = false;
1431 cap::eraseSelection(*this);
1435 // delete empty cells if possible
1436 if (pos() == lastpos() && inset().idxDelete(idx()))
1439 // special behaviour when in last position of cell
1440 if (pos() == lastpos()) {
1441 bool one_cell = inset().nargs() == 1;
1442 if (one_cell && lastpos() == 0) {
1444 // Directly delete empty cell: [|[]] => [|]
1450 // [|], can not delete from inside
1455 inset().idxGlue(idx());
1459 // 'clever' UI hack: only erase large items if previously slected
1460 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
1475 DocIterator save = *this;
1476 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1477 this->dispatch(cmd);
1478 if (disp_.dispatched())
1481 autocorrect() = false;
1489 DocIterator save = *this;
1490 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1491 this->dispatch(cmd);
1492 if (disp_.dispatched())
1495 autocorrect() = false;
1500 bool Cursor::macroModeClose()
1504 InsetMathUnknown * p = activeMacro();
1506 MathData selection(buffer());
1507 asArray(p->selection(), selection);
1508 docstring const s = p->name();
1510 cell().erase(pos());
1512 // do nothing if the macro name is empty
1516 // trigger updates of macros, at least, if no full
1517 // updates take place anyway
1518 screenUpdateFlags(Update::Force);
1520 docstring const name = s.substr(1);
1521 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1522 if (in && in->interpretString(*this, s))
1524 MathAtom atom = buffer()->getMacro(name, *this, false) ?
1525 MathAtom(new MathMacro(buffer(), name)) : createInsetMath(name, buffer());
1527 // try to put argument into macro, if we just inserted a macro
1528 bool macroArg = false;
1529 MathMacro * atomAsMacro = atom.nucleus()->asMacro();
1531 // macros here are still unfolded (in init mode in fact). So
1532 // we have to resolve the macro here manually and check its arity
1533 // to put the selection behind it if arity > 0.
1534 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1535 if (selection.size() > 0 && data && data->numargs() - data->optionals() > 0) {
1537 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1539 // non-greedy case. Do not touch the arguments behind
1540 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1543 // insert remembered selection into first argument of a non-macro
1544 else if (atom.nucleus()->nargs() > 0)
1545 atom.nucleus()->cell(0).append(selection);
1549 // finally put the macro argument behind, if needed
1551 if (selection.size() > 1 || selection[0]->asScriptInset())
1552 plainInsert(MathAtom(new InsetMathBrace(selection)));
1561 docstring Cursor::macroName()
1563 return inMacroMode() ? activeMacro()->name() : docstring();
1567 void Cursor::handleNest(MathAtom const & a, int c)
1569 //lyxerr << "Cursor::handleNest: " << c << endl;
1571 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1574 pushBackward(*nextInset());
1578 int Cursor::targetX() const
1580 if (x_target() != -1)
1589 int Cursor::textTargetOffset() const
1591 return textTargetOffset_;
1595 void Cursor::setTargetX()
1604 bool Cursor::inMacroMode() const
1610 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1611 return p && !p->final();
1615 InsetMathUnknown * Cursor::activeMacro()
1617 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1621 InsetMathUnknown const * Cursor::activeMacro() const
1623 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1627 void Cursor::pullArg()
1630 MathData ar = cell();
1631 if (popBackward() && inMathed()) {
1633 cell().insert(pos(), ar);
1636 //formula()->mutateToText();
1641 void Cursor::touch()
1645 DocIterator::const_iterator it = begin();
1646 DocIterator::const_iterator et = end();
1647 for ( ; it != et; ++it)
1653 void Cursor::normalize()
1655 if (idx() > lastidx()) {
1656 lyxerr << "this should not really happen - 1: "
1657 << idx() << ' ' << nargs()
1658 << " in: " << &inset() << endl;
1662 if (pos() > lastpos()) {
1663 lyxerr << "this should not really happen - 2: "
1664 << pos() << ' ' << lastpos() << " in idx: " << idx()
1666 odocstringstream os;
1667 WriteStream wi(os, false, true, WriteStream::wsDefault);
1668 inset().asInsetMath()->write(wi);
1669 lyxerr << to_utf8(os.str()) << endl;
1675 bool Cursor::upDownInMath(bool up)
1677 // Be warned: The 'logic' implemented in this function is highly
1678 // fragile. A distance of one pixel or a '<' vs '<=' _really
1679 // matters. So fiddle around with it only if you think you know
1680 // what you are doing!
1684 xo = beforeDispatchPosX_;
1686 // check if we had something else in mind, if not, this is the future
1688 if (x_target_ == -1)
1690 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1691 // In text mode inside the line (not left or right) possibly set a new target_x,
1692 // but only if we are somewhere else than the previous target-offset.
1694 // We want to keep the x-target on subsequent up/down movements
1695 // that cross beyond the end of short lines. Thus a special
1696 // handling when the cursor is at the end of line: Use the new
1697 // x-target only if the old one was before the end of line
1698 // or the old one was after the beginning of the line
1699 bool inRTL = isWithinRtlParagraph(*this);
1703 left = pos() == textRow().endpos();
1704 right = pos() == textRow().pos();
1706 left = pos() == textRow().pos();
1707 right = pos() == textRow().endpos();
1709 if ((!left && !right) ||
1710 (left && !right && xo < x_target_) ||
1711 (!left && right && x_target_ < xo))
1718 // try neigbouring script insets
1720 if (inMathed() && !selection()) {
1723 InsetMathScript const * p = prevAtom()->asScriptInset();
1724 if (p && p->has(up)) {
1726 push(*const_cast<InsetMathScript*>(p));
1727 idx() = p->idxOfScript(up);
1730 // we went in the right direction? Otherwise don't jump into the script
1734 int oy = beforeDispatchPosY_;
1735 if ((!up && y <= oy) ||
1744 if (pos() != lastpos()) {
1745 InsetMathScript const * p = nextAtom()->asScriptInset();
1746 if (p && p->has(up)) {
1747 push(*const_cast<InsetMathScript*>(p));
1748 idx() = p->idxOfScript(up);
1751 // we went in the right direction? Otherwise don't jump into the script
1755 int oy = beforeDispatchPosY_;
1756 if ((!up && y <= oy) ||
1765 // try to find an inset that knows better then we,
1766 if (inset().idxUpDown(*this, up)) {
1767 //lyxerr << "idxUpDown triggered" << endl;
1768 // try to find best position within this inset
1770 setCursor(bruteFind2(*this, xo, yo));
1774 // any improvement going just out of inset?
1775 if (popBackward() && inMathed()) {
1776 //lyxerr << "updown: popBackward succeeded" << endl;
1779 int yold = beforeDispatchPosY_;
1781 if (up ? ynew < yold : ynew > yold)
1785 // no success, we are probably at the document top or bottom
1791 bool Cursor::atFirstOrLastRow(bool up)
1793 TextMetrics const & tm = bv_->textMetrics(text());
1794 ParagraphMetrics const & pm = tm.parMetrics(pit());
1797 if (pos() && boundary())
1798 row = pm.pos2row(pos() - 1);
1800 row = pm.pos2row(pos());
1803 if (pit() == 0 && row == 0)
1806 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1807 row + 1 >= int(pm.rows().size()))
1813 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1815 LASSERT(text(), /**/);
1821 xo = beforeDispatchPosX_;
1823 // update the targetX - this is here before the "return false"
1824 // to set a new target which can be used by InsetTexts above
1825 // if we cannot move up/down inside this inset anymore
1826 if (x_target_ == -1)
1828 else if (xo - textTargetOffset() != x_target() &&
1829 depth() == beforeDispatchCursor_.depth()) {
1830 // In text mode inside the line (not left or right) possibly set a new target_x,
1831 // but only if we are somewhere else than the previous target-offset.
1833 // We want to keep the x-target on subsequent up/down movements
1834 // that cross beyond the end of short lines. Thus a special
1835 // handling when the cursor is at the end of line: Use the new
1836 // x-target only if the old one was before the end of line
1837 // or the old one was after the beginning of the line
1838 bool inRTL = isWithinRtlParagraph(*this);
1842 left = pos() == textRow().endpos();
1843 right = pos() == textRow().pos();
1845 left = pos() == textRow().pos();
1846 right = pos() == textRow().endpos();
1848 if ((!left && !right) ||
1849 (left && !right && xo < x_target_) ||
1850 (!left && right && x_target_ < xo))
1857 // first get the current line
1858 TextMetrics & tm = bv_->textMetrics(text());
1859 ParagraphMetrics const & pm = tm.parMetrics(pit());
1861 if (pos() && boundary())
1862 row = pm.pos2row(pos() - 1);
1864 row = pm.pos2row(pos());
1866 if (atFirstOrLastRow(up)) {
1867 // Is there a place for the cursor to go ? If yes, we
1868 // can execute the DEPM, otherwise we should keep the
1869 // paragraph to host the cursor.
1870 Cursor dummy = *this;
1871 bool valid_destination = false;
1872 for(; dummy.depth(); dummy.pop())
1873 if (!dummy.atFirstOrLastRow(up)) {
1874 valid_destination = true;
1878 // will a next dispatch follow and if there is a new
1879 // dispatch will it move the cursor out ?
1880 if (depth() > 1 && valid_destination) {
1881 // The cursor hasn't changed yet. This happens when
1882 // you e.g. move out of an inset. And to give the
1883 // DEPM the possibility of doing something we must
1884 // provide it with two different cursors. (Lgb, vfr)
1886 dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
1887 dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
1889 updateNeeded |= bv().checkDepm(dummy, *this);
1890 updateTextTargetOffset();
1892 forceBufferUpdate();
1897 // with and without selection are handled differently
1899 int yo = bv().getPos(*this).y_;
1901 // To next/previous row
1903 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1905 tm.editXY(*this, xo, yo + textRow().descent() + 1);
1908 // This happens when you move out of an inset.
1909 // And to give the DEPM the possibility of doing
1910 // something we must provide it with two different
1912 Cursor dummy = *this;
1915 if (bv().checkDepm(dummy, old)) {
1916 updateNeeded = true;
1917 // Make sure that cur gets back whatever happened to dummy (Lgb)
1921 // if there is a selection, we stay out of any inset,
1922 // and just jump to the right position:
1928 } else if (pit() > 0) {
1930 TextMetrics & tm = bv_->textMetrics(text());
1931 if (!tm.contains(pit()))
1932 tm.newParMetricsUp();
1933 ParagraphMetrics const & pmcur = tm.parMetrics(pit());
1934 next_row = pmcur.rows().size() - 1;
1937 if (row + 1 < int(pm.rows().size())) {
1939 } else if (pit() + 1 < int(text()->paragraphs().size())) {
1941 TextMetrics & tm = bv_->textMetrics(text());
1942 if (!tm.contains(pit()))
1943 tm.newParMetricsDown();
1947 top().pos() = min(tm.x2pos(pit(), next_row, xo), top().lastpos());
1949 int const xpos = tm.x2pos(pit(), next_row, xo);
1950 bool const at_end_row = xpos == tm.x2pos(pit(), next_row, tm.width());
1951 bool const at_beg_row = xpos == tm.x2pos(pit(), next_row, 0);
1953 if (at_end_row && at_beg_row)
1954 // make sure the cursor ends up on this row
1957 boundary(at_end_row);
1959 updateNeeded |= bv().checkDepm(*this, old);
1963 forceBufferUpdate();
1964 updateTextTargetOffset();
1969 void Cursor::handleFont(string const & font)
1971 LYXERR(Debug::DEBUG, font);
1975 safe = cap::grabAndEraseSelection(*this);
1980 if (lastpos() != 0) {
1981 // something left in the cell
1983 // cursor in first position
1985 } else if (pos() == lastpos()) {
1986 // cursor in last position
1989 // cursor in between. split cell
1990 MathData::iterator bt = cell().begin();
1991 MathAtom at = createInsetMath(from_utf8(font), buffer());
1992 at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
1993 cell().erase(bt, bt + pos());
1998 // nothing left in the cell
2007 void Cursor::message(docstring const & msg) const
2009 disp_.setMessage(msg);
2013 void Cursor::errorMessage(docstring const & msg) const
2015 disp_.setMessage(msg);
2016 disp_.setError(true);
2021 docstring parbreak(Cursor const * cur)
2023 odocstringstream os;
2025 // only add blank line if we're not in a ParbreakIsNewline situation
2026 if (!cur->inset().getLayout().parbreakIsNewline()
2027 && !cur->paragraph().layout().parbreak_is_newline)
2034 docstring Cursor::selectionAsString(bool with_label) const
2040 return cap::grabSelection(*this);
2042 int const label = with_label
2043 ? AS_STR_LABEL | AS_STR_INSETS : AS_STR_INSETS;
2045 idx_type const startidx = selBegin().idx();
2046 idx_type const endidx = selEnd().idx();
2047 if (startidx != endidx) {
2048 // multicell selection
2049 InsetTabular * table = inset().asInsetTabular();
2050 LASSERT(table, return docstring());
2051 return table->asString(startidx, endidx);
2054 ParagraphList const & pars = text()->paragraphs();
2056 pit_type const startpit = selBegin().pit();
2057 pit_type const endpit = selEnd().pit();
2058 size_t const startpos = selBegin().pos();
2059 size_t const endpos = selEnd().pos();
2061 if (startpit == endpit)
2062 return pars[startpit].asString(startpos, endpos, label);
2064 // First paragraph in selection
2065 docstring result = pars[startpit].
2066 asString(startpos, pars[startpit].size(), label)
2069 // The paragraphs in between (if any)
2070 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
2071 Paragraph const & par = pars[pit];
2072 result += par.asString(0, par.size(), label)
2076 // Last paragraph in selection
2077 result += pars[endpit].asString(0, endpos, label);
2083 docstring Cursor::currentState() const
2086 odocstringstream os;
2092 return text()->currentState(*this);
2098 docstring Cursor::getPossibleLabel() const
2100 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
2104 Encoding const * Cursor::getEncoding() const
2108 CursorSlice const & sl = innerTextSlice();
2109 Text const & text = *sl.text();
2110 Font font = text.getPar(sl.pit()).getFont(
2111 bv().buffer().params(), sl.pos(), text.outerFont(sl.pit()));
2112 return font.language()->encoding();
2116 void Cursor::undispatched()
2118 disp_.dispatched(false);
2122 void Cursor::dispatched()
2124 disp_.dispatched(true);
2128 void Cursor::screenUpdateFlags(Update::flags f)
2130 disp_.screenUpdate(f);
2134 void Cursor::forceBufferUpdate()
2136 disp_.forceBufferUpdate();
2140 void Cursor::clearBufferUpdate()
2142 disp_.clearBufferUpdate();
2146 bool Cursor::needBufferUpdate() const
2148 return disp_.needBufferUpdate();
2152 void Cursor::noScreenUpdate()
2154 disp_.screenUpdate(Update::None);
2158 Font Cursor::getFont() const
2160 // The logic here should more or less match to the Cursor::setCurrentFont
2161 // logic, i.e. the cursor height should give a hint what will happen
2162 // if a character is entered.
2164 // HACK. far from being perfect...
2166 CursorSlice const & sl = innerTextSlice();
2167 Text const & text = *sl.text();
2168 Paragraph const & par = text.getPar(sl.pit());
2170 // on boundary, so we are really at the character before
2171 pos_type pos = sl.pos();
2172 if (pos > 0 && boundary())
2175 // on space? Take the font before (only for RTL boundary stay)
2177 TextMetrics const & tm = bv().textMetrics(&text);
2178 if (pos == sl.lastpos()
2179 || (par.isSeparator(pos)
2180 && !tm.isRTLBoundary(sl.pit(), pos)))
2184 // get font at the position
2185 Font font = par.getFont(buffer()->params(), pos,
2186 text.outerFont(sl.pit()));
2192 bool Cursor::fixIfBroken()
2194 bool const broken_cursor = DocIterator::fixIfBroken();
2195 bool const broken_anchor = anchor_.fixIfBroken();
2197 if (broken_cursor || broken_anchor) {
2205 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2207 // find inset in common
2209 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2210 if (&old[i].inset() != &cur[i].inset())
2214 // update words if we just moved to another paragraph
2215 if (i == old.depth() && i == cur.depth()
2216 && !cur.buffer()->isClean()
2217 && cur.inTexted() && old.inTexted()
2218 && cur.pit() != old.pit()) {
2219 old.paragraph().updateWords();
2222 // notify everything on top of the common part in old cursor,
2223 // but stop if the inset claims the cursor to be invalid now
2224 for (size_type j = i; j < old.depth(); ++j) {
2225 Cursor inset_pos = old;
2226 inset_pos.cutOff(j);
2227 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2231 // notify everything on top of the common part in new cursor,
2232 // but stop if the inset claims the cursor to be invalid now
2233 for (; i < cur.depth(); ++i) {
2234 if (cur[i].inset().notifyCursorEnters(cur))
2242 void Cursor::setCurrentFont()
2244 CursorSlice const & cs = innerTextSlice();
2245 Paragraph const & par = cs.paragraph();
2246 pos_type cpit = cs.pit();
2247 pos_type cpos = cs.pos();
2248 Text const & ctext = *cs.text();
2249 TextMetrics const & tm = bv().textMetrics(&ctext);
2251 // are we behind previous char in fact? -> go to that char
2252 if (cpos > 0 && boundary())
2255 // find position to take the font from
2257 // paragraph end? -> font of last char
2258 if (cpos == lastpos())
2260 // on space? -> look at the words in front of space
2261 else if (cpos > 0 && par.isSeparator(cpos)) {
2262 // abc| def -> font of c
2263 // abc |[WERBEH], i.e. boundary==true -> font of c
2264 // abc [WERBEH]| def, font of the space
2265 if (!tm.isRTLBoundary(cpit, cpos))
2271 BufferParams const & bufparams = buffer()->params();
2272 current_font = par.getFontSettings(bufparams, cpos);
2273 real_current_font = tm.displayFont(cpit, cpos);
2275 // special case for paragraph end
2276 if (cs.pos() == lastpos()
2277 && tm.isRTLBoundary(cpit, cs.pos())
2279 Language const * lang = par.getParLanguage(bufparams);
2280 current_font.setLanguage(lang);
2281 current_font.fontInfo().setNumber(FONT_OFF);
2282 real_current_font.setLanguage(lang);
2283 real_current_font.fontInfo().setNumber(FONT_OFF);
2288 bool Cursor::textUndo()
2290 DocIterator dit = *this;
2291 // Undo::textUndo() will modify dit.
2292 if (!buffer()->undo().textUndo(dit))
2302 bool Cursor::textRedo()
2304 DocIterator dit = *this;
2305 // Undo::textRedo() will modify dit.
2306 if (!buffer()->undo().textRedo(dit))
2316 void Cursor::finishUndo() const
2318 buffer()->undo().finishUndo();
2322 void Cursor::beginUndoGroup() const
2324 buffer()->undo().beginUndoGroup();
2328 void Cursor::endUndoGroup() const
2330 buffer()->undo().endUndoGroup();
2334 void Cursor::recordUndo(UndoKind kind, pit_type from, pit_type to) const
2336 buffer()->undo().recordUndo(*this, kind, from, to);
2340 void Cursor::recordUndo(UndoKind kind, pit_type from) const
2342 buffer()->undo().recordUndo(*this, kind, from);
2346 void Cursor::recordUndo(UndoKind kind) const
2348 buffer()->undo().recordUndo(*this, kind);
2352 void Cursor::recordUndoInset(UndoKind kind) const
2354 buffer()->undo().recordUndoInset(*this, kind);
2358 void Cursor::recordUndoFullDocument() const
2360 buffer()->undo().recordUndoFullDocument(*this);
2364 void Cursor::recordUndoSelection() const
2367 if (cap::multipleCellsSelected(*this))
2372 buffer()->undo().recordUndo(*this, ATOMIC_UNDO,
2373 selBegin().pit(), selEnd().pit());
2378 void Cursor::checkBufferStructure()
2380 Buffer const * master = buffer()->masterBuffer();
2381 master->tocBackend().updateItem(*this);
2382 if (master != buffer() && !master->hasGuiDelegate())
2383 // In case the master has no gui associated with it,
2384 // the TocItem is not updated (part of bug 5699).
2385 buffer()->tocBackend().updateItem(*this);