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;
335 disp_ = DispatchResult();
337 buffer()->undo().beginUndoGroup();
339 // Is this a function that acts on inset at point?
340 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
342 disp_.dispatched(true);
343 disp_.screenUpdate(Update::FitCursor | Update::Force);
344 FuncRequest tmpcmd = cmd;
345 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
346 << cmd0 << endl << *this);
347 nextInset()->dispatch(*this, tmpcmd);
348 if (disp_.dispatched()) {
349 buffer()->undo().endUndoGroup();
354 // store some values to be used inside of the handlers
355 beforeDispatchCursor_ = *this;
356 for (; depth(); pop(), boundary(false)) {
357 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
358 << cmd0 << endl << *this);
359 LASSERT(pos() <= lastpos(), /**/);
360 LASSERT(idx() <= lastidx(), /**/);
361 LASSERT(pit() <= lastpit(), /**/);
363 // The common case is 'LFUN handled, need update', so make the
364 // LFUN handler's life easier by assuming this as default value.
365 // The handler can reset the update and val flags if necessary.
366 disp_.screenUpdate(Update::FitCursor | Update::Force);
367 disp_.dispatched(true);
368 inset().dispatch(*this, cmd);
369 if (disp_.dispatched())
373 // it completely to get a 'bomb early' behaviour in case this
374 // object will be used again.
375 if (!disp_.dispatched()) {
376 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
377 // We might have invalidated the cursor when removing an empty
378 // paragraph while the cursor could not be moved out the inset
379 // while we initially thought we could. This might happen when
380 // a multiline inset becomes an inline inset when the second
381 // paragraph is removed.
382 if (safe.pit() > safe.lastpit()) {
383 safe.pit() = safe.lastpit();
384 safe.pos() = safe.lastpos();
387 disp_.screenUpdate(Update::None);
388 disp_.dispatched(false);
390 // restore the previous one because nested Cursor::dispatch calls
391 // are possible which would change it
392 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
394 buffer()->undo().endUndoGroup();
398 DispatchResult const & Cursor::result() const
404 BufferView & Cursor::bv() const
413 LASSERT(depth() >= 1, /**/);
418 void Cursor::push(Inset & p)
420 push_back(CursorSlice(p));
421 p.setBuffer(*buffer());
425 void Cursor::pushBackward(Inset & p)
427 LASSERT(!empty(), return);
428 //lyxerr << "Entering inset " << t << " front" << endl;
434 bool Cursor::popBackward()
436 LASSERT(!empty(), return false);
444 bool Cursor::popForward()
446 LASSERT(!empty(), return false);
447 //lyxerr << "Leaving inset from in back" << endl;
448 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
452 pos() += lastpos() - lp + 1;
457 int Cursor::currentMode()
459 LASSERT(!empty(), /**/);
460 for (int i = depth() - 1; i >= 0; --i) {
461 int res = operator[](i).inset().currentMode();
462 bool locked_mode = operator[](i).inset().lockedMode();
463 // Also return UNDECIDED_MODE when the mode is locked,
464 // as in this case it is treated the same as TEXT_MODE
465 if (res != Inset::UNDECIDED_MODE || locked_mode)
468 return Inset::TEXT_MODE;
472 void Cursor::getPos(int & x, int & y) const
474 Point p = bv().getPos(*this);
480 Row const & Cursor::textRow() const
482 CursorSlice const & cs = innerTextSlice();
483 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
484 LASSERT(!pm.rows().empty(), /**/);
485 return pm.getRow(pos(), boundary());
489 void Cursor::resetAnchor()
495 void Cursor::setCursorToAnchor()
498 DocIterator normal = anchor_;
499 while (depth() < normal.depth())
501 if (depth() < anchor_.depth() && top() <= anchor_[depth() - 1])
508 bool Cursor::posBackward()
517 bool Cursor::posForward()
519 if (pos() == lastpos())
526 bool Cursor::posVisRight(bool skip_inset)
528 Cursor new_cur = *this; // where we will move to
529 pos_type left_pos; // position visually left of current cursor
530 pos_type right_pos; // position visually right of current cursor
531 bool new_pos_is_RTL; // is new position we're moving to RTL?
533 getSurroundingPos(left_pos, right_pos);
535 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
537 // Are we at an inset?
538 new_cur.pos() = right_pos;
539 new_cur.boundary(false);
541 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
542 // we actually move the cursor at the end of this function, for now
543 // we just keep track of the new position in new_cur...
544 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
547 // Are we already at rightmost pos in row?
548 else if (text()->empty() || right_pos == -1) {
551 if (!new_cur.posVisToNewRow(false)) {
552 LYXERR(Debug::RTL, "not moving!");
556 // we actually move the cursor at the end of this function, for now
557 // just keep track of the new position in new_cur...
558 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
559 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
562 // normal movement to the right
565 // Recall, if the cursor is at position 'x', that means *before*
566 // the character at position 'x'. In RTL, "before" means "to the
567 // right of", in LTR, "to the left of". So currently our situation
568 // is this: the position to our right is 'right_pos' (i.e., we're
569 // currently to the left of 'right_pos'). In order to move to the
570 // right, it depends whether or not the character at 'right_pos' is RTL.
571 new_pos_is_RTL = paragraph().getFontSettings(
572 buffer()->params(), right_pos).isVisibleRightToLeft();
573 // If the character at 'right_pos' *is* LTR, then in order to move to
574 // the right of it, we need to be *after* 'right_pos', i.e., move to
575 // position 'right_pos' + 1.
576 if (!new_pos_is_RTL) {
577 new_cur.pos() = right_pos + 1;
578 // set the boundary to true in two situations:
580 // 1. if new_pos is now lastpos, and we're in an RTL paragraph
581 // (this means that we're moving right to the end of an LTR chunk
582 // which is at the end of an RTL paragraph);
583 (new_cur.pos() == lastpos()
584 && paragraph().isRTL(buffer()->params()))
585 // 2. if the position *after* right_pos is RTL (we want to be
586 // *after* right_pos, not before right_pos + 1!)
587 || paragraph().getFontSettings(buffer()->params(),
588 new_cur.pos()).isVisibleRightToLeft()
590 new_cur.boundary(true);
591 else // set the boundary to false
592 new_cur.boundary(false);
594 // Otherwise (if the character at position 'right_pos' is RTL), then
595 // moving to the right of it is as easy as setting the new position
598 new_cur.pos() = right_pos;
599 new_cur.boundary(false);
604 bool moved = (new_cur.pos() != pos()
605 || new_cur.pit() != pit()
606 || new_cur.boundary() != boundary()
607 || &new_cur.inset() != &inset());
610 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
611 << (new_cur.boundary() ? " (boundary)" : ""));
619 bool Cursor::posVisLeft(bool skip_inset)
621 Cursor new_cur = *this; // where we will move to
622 pos_type left_pos; // position visually left of current cursor
623 pos_type right_pos; // position visually right of current cursor
624 bool new_pos_is_RTL; // is new position we're moving to RTL?
626 getSurroundingPos(left_pos, right_pos);
628 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
630 // Are we at an inset?
631 new_cur.pos() = left_pos;
632 new_cur.boundary(false);
634 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
635 // we actually move the cursor at the end of this function, for now
636 // we just keep track of the new position in new_cur...
637 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
640 // Are we already at leftmost pos in row?
641 else if (text()->empty() || left_pos == -1) {
644 if (!new_cur.posVisToNewRow(true)) {
645 LYXERR(Debug::RTL, "not moving!");
649 // we actually move the cursor at the end of this function, for now
650 // just keep track of the new position in new_cur...
651 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
652 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
655 // normal movement to the left
658 // Recall, if the cursor is at position 'x', that means *before*
659 // the character at position 'x'. In RTL, "before" means "to the
660 // right of", in LTR, "to the left of". So currently our situation
661 // is this: the position to our left is 'left_pos' (i.e., we're
662 // currently to the right of 'left_pos'). In order to move to the
663 // left, it depends whether or not the character at 'left_pos' is RTL.
664 new_pos_is_RTL = paragraph().getFontSettings(
665 buffer()->params(), left_pos).isVisibleRightToLeft();
666 // If the character at 'left_pos' *is* RTL, then in order to move to
667 // the left of it, we need to be *after* 'left_pos', i.e., move to
668 // position 'left_pos' + 1.
669 if (new_pos_is_RTL) {
670 new_cur.pos() = left_pos + 1;
671 // set the boundary to true in two situations:
673 // 1. if new_pos is now lastpos and we're in an LTR paragraph
674 // (this means that we're moving left to the end of an RTL chunk
675 // which is at the end of an LTR paragraph);
676 (new_cur.pos() == lastpos()
677 && !paragraph().isRTL(buffer()->params()))
678 // 2. if the position *after* left_pos is not RTL (we want to be
679 // *after* left_pos, not before left_pos + 1!)
680 || !paragraph().getFontSettings(buffer()->params(),
681 new_cur.pos()).isVisibleRightToLeft()
683 new_cur.boundary(true);
684 else // set the boundary to false
685 new_cur.boundary(false);
687 // Otherwise (if the character at position 'left_pos' is LTR), then
688 // moving to the left of it is as easy as setting the new position
691 new_cur.pos() = left_pos;
692 new_cur.boundary(false);
697 bool moved = (new_cur.pos() != pos()
698 || new_cur.pit() != pit()
699 || new_cur.boundary() != boundary());
702 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
703 << (new_cur.boundary() ? " (boundary)" : ""));
711 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos)
713 // preparing bidi tables
714 Paragraph const & par = paragraph();
715 Buffer const & buf = *buffer();
716 Row const & row = textRow();
718 bidi.computeTables(par, buf, row);
720 LYXERR(Debug::RTL, "bidi: " << row.pos() << "--" << row.endpos());
722 // The cursor is painted *before* the character at pos(), or, if 'boundary'
723 // is true, *after* the character at (pos() - 1). So we already have one
724 // known position around the cursor:
725 pos_type const known_pos = boundary() && pos() > 0 ? pos() - 1 : pos();
727 // edge case: if we're at the end of the paragraph, things are a little
728 // different (because lastpos is a position which does not really "exist"
729 // --- there's no character there yet).
730 if (known_pos == lastpos()) {
731 if (par.isRTL(buf.params())) {
733 right_pos = bidi.vis2log(row.pos());
737 left_pos = bidi.vis2log(row.endpos() - 1);
742 // Whether 'known_pos' is to the left or to the right of the cursor depends
743 // on whether it is an RTL or LTR character...
744 bool const cur_is_RTL =
745 par.getFontSettings(buf.params(), known_pos).isVisibleRightToLeft();
746 // ... in the following manner:
747 // For an RTL character, "before" means "to the right" and "after" means
748 // "to the left"; and for LTR, it's the reverse. So, 'known_pos' is to the
749 // right of the cursor if (RTL && boundary) or (!RTL && !boundary):
750 bool const known_pos_on_right = cur_is_RTL == boundary();
752 // So we now know one of the positions surrounding the cursor. Let's
753 // determine the other one:
754 if (known_pos_on_right) {
755 right_pos = known_pos;
756 // *visual* position of 'left_pos':
757 pos_type v_left_pos = bidi.log2vis(right_pos) - 1;
758 // If the position we just identified as 'left_pos' is a "skipped
759 // separator" (a separator which is at the logical end of a row,
760 // except for the last row in a paragraph; such separators are not
761 // painted, so they "are not really there"; note that in bidi text,
762 // such a separator could appear visually in the middle of a row),
763 // set 'left_pos' to the *next* position to the left.
764 if (bidi.inRange(v_left_pos)
765 && bidi.vis2log(v_left_pos) + 1 == row.endpos()
766 && row.endpos() < lastpos()
767 && par.isSeparator(bidi.vis2log(v_left_pos)))
770 // calculate the logical position of 'left_pos', if in row
771 if (!bidi.inRange(v_left_pos))
774 left_pos = bidi.vis2log(v_left_pos);
775 // If the position we identified as 'right_pos' is a "skipped
776 // separator", set 'right_pos' to the *next* position to the right.
777 if (right_pos + 1 == row.endpos() && row.endpos() < lastpos()
778 && par.isSeparator(right_pos)) {
779 pos_type const v_right_pos = bidi.log2vis(right_pos) + 1;
780 if (!bidi.inRange(v_right_pos))
783 right_pos = bidi.vis2log(v_right_pos);
786 // known_pos is on the left
787 left_pos = known_pos;
788 // *visual* position of 'right_pos'
789 pos_type v_right_pos = bidi.log2vis(left_pos) + 1;
790 // If the position we just identified as 'right_pos' is a "skipped
791 // separator", set 'right_pos' to the *next* position to the right.
792 if (bidi.inRange(v_right_pos)
793 && bidi.vis2log(v_right_pos) + 1 == row.endpos()
794 && row.endpos() < lastpos()
795 && par.isSeparator(bidi.vis2log(v_right_pos)))
798 // calculate the logical position of 'right_pos', if in row
799 if (!bidi.inRange(v_right_pos))
802 right_pos = bidi.vis2log(v_right_pos);
803 // If the position we identified as 'left_pos' is a "skipped
804 // separator", set 'left_pos' to the *next* position to the left.
805 if (left_pos + 1 == row.endpos() && row.endpos() < lastpos()
806 && par.isSeparator(left_pos)) {
807 pos_type const v_left_pos = bidi.log2vis(left_pos) - 1;
808 if (!bidi.inRange(v_left_pos))
811 left_pos = bidi.vis2log(v_left_pos);
818 bool Cursor::posVisToNewRow(bool movingLeft)
820 Paragraph const & par = paragraph();
821 Buffer const & buf = *buffer();
822 Row const & row = textRow();
823 bool par_is_LTR = !par.isRTL(buf.params());
825 // Inside a table, determining whether to move to the next or previous row
826 // should be done based on the table's direction.
828 if (s >= 1 && (*this)[s].inset().asInsetTabular()) {
829 par_is_LTR = !(*this)[s].inset().asInsetTabular()->isRightToLeft(*this);
830 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
833 // if moving left in an LTR paragraph or moving right in an RTL one,
834 // move to previous row
835 if (par_is_LTR == movingLeft) {
836 if (row.pos() == 0) { // we're at first row in paragraph
837 if (pit() == 0) // no previous paragraph! don't move
839 // move to last pos in previous par
843 } else { // move to previous row in this par
844 pos() = row.pos() - 1; // this is guaranteed to be in previous row
848 // if moving left in an RTL paragraph or moving right in an LTR one,
851 if (row.endpos() == lastpos()) { // we're at last row in paragraph
852 if (pit() == lastpit()) // last paragraph! don't move
854 // move to first row in next par
858 } else { // move to next row in this par
859 pos() = row.endpos();
864 // make sure we're at left-/right-most pos in new row
865 posVisToRowExtremity(!movingLeft);
871 void Cursor::posVisToRowExtremity(bool left)
873 // prepare bidi tables
874 Paragraph const & par = paragraph();
875 Buffer const & buf = *buffer();
876 Row const & row = textRow();
878 bidi.computeTables(par, buf, row);
880 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
881 << (boundary() ? 1 : 0));
883 if (left) { // move to leftmost position
884 // if this is an RTL paragraph, and we're at the last row in the
885 // paragraph, move to lastpos
886 if (par.isRTL(buf.params()) && row.endpos() == lastpos())
889 pos() = bidi.vis2log(row.pos());
891 // Moving to the leftmost position in the row, the cursor should
892 // normally be placed to the *left* of the leftmost position.
893 // A very common exception, though, is if the leftmost character
894 // also happens to be the separator at the (logical) end of the row
895 // --- in this case, the separator is positioned beyond the left
896 // margin, and we don't want to move the cursor there (moving to
897 // the left of the separator is equivalent to moving to the next
898 // line). So, in this case we actually want to place the cursor
899 // to the *right* of the leftmost position (the separator).
900 // Another exception is if we're moving to the logically last
901 // position in the row, which is *not* a separator: this means
902 // that the entire row has no separators (if there were any, the
903 // row would have been broken there); and therefore in this case
904 // we also move to the *right* of the last position (this indicates
905 // to the user that there is no space after this position, and is
906 // consistent with the behavior in the middle of a row --- moving
907 // right or left moves to the next/previous character; if we were
908 // to move to the *left* of this position, that would simulate
909 // a separator which is not really there!).
910 // Finally, there is an exception to the previous exception: if
911 // this non-separator-but-last-position-in-row is an inset, then
912 // we *do* want to stay to the left of it anyway: this is the
913 // "boundary" which we simulate at insets.
914 // Another exception is when row.endpos() is 0.
916 // do we want to be to the right of pos?
917 // as explained above, if at last pos in row, stay to the right
918 bool const right_of_pos = row.endpos() > 0
919 && pos() == row.endpos() - 1 && !par.isInset(pos());
921 // Now we know if we want to be to the left or to the right of pos,
922 // let's make sure we are where we want to be.
923 bool const new_pos_is_RTL =
924 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
926 if (new_pos_is_RTL != right_of_pos) {
932 // move to rightmost position
933 // if this is an LTR paragraph, and we're at the last row in the
934 // paragraph, move to lastpos
935 if (!par.isRTL(buf.params()) && row.endpos() == lastpos())
938 pos() = row.endpos() > 0 ? bidi.vis2log(row.endpos() - 1) : 0;
940 // Moving to the rightmost position in the row, the cursor should
941 // normally be placed to the *right* of the rightmost position.
942 // A very common exception, though, is if the rightmost character
943 // also happens to be the separator at the (logical) end of the row
944 // --- in this case, the separator is positioned beyond the right
945 // margin, and we don't want to move the cursor there (moving to
946 // the right of the separator is equivalent to moving to the next
947 // line). So, in this case we actually want to place the cursor
948 // to the *left* of the rightmost position (the separator).
949 // Another exception is if we're moving to the logically last
950 // position in the row, which is *not* a separator: this means
951 // that the entire row has no separators (if there were any, the
952 // row would have been broken there); and therefore in this case
953 // we also move to the *left* of the last position (this indicates
954 // to the user that there is no space after this position, and is
955 // consistent with the behavior in the middle of a row --- moving
956 // right or left moves to the next/previous character; if we were
957 // to move to the *right* of this position, that would simulate
958 // a separator which is not really there!).
959 // Finally, there is an exception to the previous exception: if
960 // this non-separator-but-last-position-in-row is an inset, then
961 // we *do* want to stay to the right of it anyway: this is the
962 // "boundary" which we simulate at insets.
963 // Another exception is when row.endpos() is 0.
965 // do we want to be to the left of pos?
966 // as explained above, if at last pos in row, stay to the left,
967 // unless the last position is the same as the first.
968 bool const left_of_pos = row.endpos() > 0
969 && pos() == row.endpos() - 1 && !par.isInset(pos());
971 // Now we know if we want to be to the left or to the right of pos,
972 // let's make sure we are where we want to be.
973 bool const new_pos_is_RTL =
974 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
976 if (new_pos_is_RTL == left_of_pos) {
982 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
983 << (boundary() ? 1 : 0));
987 CursorSlice Cursor::normalAnchor() const
991 LASSERT(anchor_.depth() >= depth(), /**/);
992 CursorSlice normal = anchor_[depth() - 1];
993 if (depth() < anchor_.depth() && top() <= normal) {
994 // anchor is behind cursor -> move anchor behind the inset
1001 DocIterator & Cursor::realAnchor()
1007 CursorSlice Cursor::selBegin() const
1011 return normalAnchor() < top() ? normalAnchor() : top();
1015 CursorSlice Cursor::selEnd() const
1019 return normalAnchor() > top() ? normalAnchor() : top();
1023 DocIterator Cursor::selectionBegin() const
1029 // FIXME: This is a work-around for the problem that
1030 // CursorSlice doesn't keep track of the boundary.
1031 if (normalAnchor() == top())
1032 di = anchor_.boundary() > boundary() ? anchor_ : *this;
1034 di = normalAnchor() < top() ? anchor_ : *this;
1040 DocIterator Cursor::selectionEnd() const
1046 // FIXME: This is a work-around for the problem that
1047 // CursorSlice doesn't keep track of the boundary.
1048 if (normalAnchor() == top())
1049 di = anchor_.boundary() < boundary() ? anchor_ : *this;
1051 di = normalAnchor() > top() ? anchor_ : *this;
1053 if (di.depth() > depth()) {
1061 void Cursor::setSelection()
1064 // A selection with no contents is not a selection
1065 // FIXME: doesnt look ok
1066 if (idx() == normalAnchor().idx() &&
1067 pit() == normalAnchor().pit() &&
1068 pos() == normalAnchor().pos())
1069 setSelection(false);
1073 void Cursor::setSelection(DocIterator const & where, int n)
1082 void Cursor::clearSelection()
1084 setSelection(false);
1085 setWordSelection(false);
1091 void Cursor::setTargetX(int x)
1094 textTargetOffset_ = 0;
1098 int Cursor::x_target() const
1104 void Cursor::clearTargetX()
1107 textTargetOffset_ = 0;
1111 void Cursor::updateTextTargetOffset()
1116 textTargetOffset_ = x - x_target_;
1120 void Cursor::info(odocstream & os) const
1122 for (int i = 1, n = depth(); i < n; ++i) {
1123 operator[](i).inset().infoize(os);
1127 Inset const * inset = prevInset();
1128 // prevInset() can return 0 in certain case.
1130 prevInset()->infoize2(os);
1132 // overwite old message
1137 bool Cursor::selHandle(bool sel)
1139 //lyxerr << "Cursor::selHandle" << endl;
1142 if (sel == selection())
1146 cap::saveSelection(*this);
1154 ostream & operator<<(ostream & os, Cursor const & cur)
1156 os << "\n cursor: | anchor:\n";
1157 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
1158 os << " " << cur[i] << " | ";
1159 if (i < cur.anchor_.depth())
1160 os << cur.anchor_[i];
1162 os << "-------------------------------";
1165 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
1166 os << "------------------------------- | " << cur.anchor_[i] << "\n";
1168 os << " selection: " << cur.selection_
1169 << " x_target: " << cur.x_target_ << endl;
1174 LyXErr & operator<<(LyXErr & os, Cursor const & cur)
1184 ///////////////////////////////////////////////////////////////////
1187 // The part below is the non-integrated rest of the original math
1188 // cursor. This should be either generalized for texted or moved
1189 // back to mathed (in most cases to InsetMathNest).
1191 ///////////////////////////////////////////////////////////////////
1193 #include "mathed/InsetMathChar.h"
1194 #include "mathed/InsetMathGrid.h"
1195 #include "mathed/InsetMathScript.h"
1196 #include "mathed/InsetMathUnknown.h"
1197 #include "mathed/MathFactory.h"
1198 #include "mathed/MathStream.h"
1199 #include "mathed/MathSupport.h"
1204 //#define FILEDEBUG 1
1207 bool Cursor::isInside(Inset const * p) const
1209 for (size_t i = 0; i != depth(); ++i)
1210 if (&operator[](i).inset() == p)
1216 void Cursor::leaveInset(Inset const & inset)
1218 for (size_t i = 0; i != depth(); ++i) {
1219 if (&operator[](i).inset() == &inset) {
1227 bool Cursor::openable(MathAtom const & t) const
1238 // we can't move into anything new during selection
1239 if (depth() >= anchor_.depth())
1241 if (t.nucleus() != &anchor_[depth()].inset())
1248 void Cursor::setScreenPos(int x, int /*y*/)
1251 //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
1256 void Cursor::plainErase()
1258 cell().erase(pos());
1262 void Cursor::markInsert()
1264 insert(char_type(0));
1268 void Cursor::markErase()
1270 cell().erase(pos());
1274 void Cursor::plainInsert(MathAtom const & t)
1276 cell().insert(pos(), t);
1278 inset().setBuffer(bv_->buffer());
1280 forceBufferUpdate();
1284 void Cursor::insert(docstring const & str)
1286 for_each(str.begin(), str.end(),
1287 bind(static_cast<void(Cursor::*)(char_type)>
1288 (&Cursor::insert), this, _1));
1292 void Cursor::insert(char_type c)
1294 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1295 LASSERT(!empty(), /**/);
1297 cap::selClearOrDel(*this);
1298 insert(new InsetMathChar(c));
1300 text()->insertChar(*this, c);
1305 void Cursor::insert(MathAtom const & t)
1307 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1309 cap::selClearOrDel(*this);
1314 void Cursor::insert(Inset * inset0)
1316 LASSERT(inset0, /**/);
1318 insert(MathAtom(inset0->asInsetMath()));
1320 text()->insertInset(*this, inset0);
1321 inset0->setBuffer(bv_->buffer());
1323 if (inset0->isLabeled())
1324 forceBufferUpdate();
1329 void Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1331 MathData ar(buffer());
1333 if (ar.size() == 1 && (enter || selection()))
1340 void Cursor::niceInsert(MathAtom const & t)
1343 docstring const safe = cap::grabAndEraseSelection(*this);
1345 // If possible, enter the new inset and move the contents of the selection
1346 if (t->isActive()) {
1348 // be careful here: don't use 'pushBackward(t)' as this we need to
1349 // push the clone, not the original
1350 pushBackward(*nextInset());
1351 // We may not use niceInsert here (recursion)
1352 MathData ar(buffer());
1359 void Cursor::insert(MathData const & ar)
1363 cap::eraseSelection(*this);
1364 cell().insert(pos(), ar);
1366 // FIXME audit setBuffer calls
1367 inset().setBuffer(bv_->buffer());
1371 bool Cursor::backspace()
1373 autocorrect() = false;
1376 cap::eraseSelection(*this);
1381 // If empty cell, and not part of a big cell
1382 if (lastpos() == 0 && inset().nargs() == 1) {
1384 // Directly delete empty cell: [|[]] => [|]
1390 // [|], can not delete from inside
1401 if (inMacroMode()) {
1402 InsetMathUnknown * p = activeMacro();
1403 if (p->name().size() > 1) {
1404 p->setName(p->name().substr(0, p->name().size() - 1));
1409 if (pos() != 0 && prevAtom()->nargs() > 0) {
1410 // let's require two backspaces for 'big stuff' and
1411 // highlight on the first
1423 bool Cursor::erase()
1425 autocorrect() = false;
1430 cap::eraseSelection(*this);
1434 // delete empty cells if possible
1435 if (pos() == lastpos() && inset().idxDelete(idx()))
1438 // special behaviour when in last position of cell
1439 if (pos() == lastpos()) {
1440 bool one_cell = inset().nargs() == 1;
1441 if (one_cell && lastpos() == 0) {
1443 // Directly delete empty cell: [|[]] => [|]
1449 // [|], can not delete from inside
1454 inset().idxGlue(idx());
1458 // 'clever' UI hack: only erase large items if previously slected
1459 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
1474 DocIterator save = *this;
1475 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1476 this->dispatch(cmd);
1477 if (disp_.dispatched())
1480 autocorrect() = false;
1488 DocIterator save = *this;
1489 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1490 this->dispatch(cmd);
1491 if (disp_.dispatched())
1494 autocorrect() = false;
1499 bool Cursor::macroModeClose()
1503 InsetMathUnknown * p = activeMacro();
1505 MathData selection(buffer());
1506 asArray(p->selection(), selection);
1507 docstring const s = p->name();
1509 cell().erase(pos());
1511 // do nothing if the macro name is empty
1515 // trigger updates of macros, at least, if no full
1516 // updates take place anyway
1517 screenUpdateFlags(Update::Force);
1519 docstring const name = s.substr(1);
1520 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1521 if (in && in->interpretString(*this, s))
1523 MathAtom atom = buffer()->getMacro(name, *this, false) ?
1524 MathAtom(new MathMacro(buffer(), name)) : createInsetMath(name, buffer());
1526 // try to put argument into macro, if we just inserted a macro
1527 bool macroArg = false;
1528 MathMacro * atomAsMacro = atom.nucleus()->asMacro();
1530 // macros here are still unfolded (in init mode in fact). So
1531 // we have to resolve the macro here manually and check its arity
1532 // to put the selection behind it if arity > 0.
1533 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1534 if (selection.size() > 0 && data && data->numargs() - data->optionals() > 0) {
1536 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1538 // non-greedy case. Do not touch the arguments behind
1539 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1542 // insert remembered selection into first argument of a non-macro
1543 else if (atom.nucleus()->nargs() > 0)
1544 atom.nucleus()->cell(0).append(selection);
1548 // finally put the macro argument behind, if needed
1550 if (selection.size() > 1 || selection[0]->asScriptInset())
1551 plainInsert(MathAtom(new InsetMathBrace(selection)));
1560 docstring Cursor::macroName()
1562 return inMacroMode() ? activeMacro()->name() : docstring();
1566 void Cursor::handleNest(MathAtom const & a, int c)
1568 //lyxerr << "Cursor::handleNest: " << c << endl;
1570 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1573 pushBackward(*nextInset());
1577 int Cursor::targetX() const
1579 if (x_target() != -1)
1588 int Cursor::textTargetOffset() const
1590 return textTargetOffset_;
1594 void Cursor::setTargetX()
1603 bool Cursor::inMacroMode() const
1609 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1610 return p && !p->final();
1614 InsetMathUnknown * Cursor::activeMacro()
1616 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1620 InsetMathUnknown const * Cursor::activeMacro() const
1622 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1626 void Cursor::pullArg()
1629 MathData ar = cell();
1630 if (popBackward() && inMathed()) {
1632 cell().insert(pos(), ar);
1635 //formula()->mutateToText();
1640 void Cursor::touch()
1644 DocIterator::const_iterator it = begin();
1645 DocIterator::const_iterator et = end();
1646 for ( ; it != et; ++it)
1652 void Cursor::normalize()
1654 if (idx() > lastidx()) {
1655 lyxerr << "this should not really happen - 1: "
1656 << idx() << ' ' << nargs()
1657 << " in: " << &inset() << endl;
1661 if (pos() > lastpos()) {
1662 lyxerr << "this should not really happen - 2: "
1663 << pos() << ' ' << lastpos() << " in idx: " << idx()
1665 odocstringstream os;
1666 WriteStream wi(os, false, true, WriteStream::wsDefault);
1667 inset().asInsetMath()->write(wi);
1668 lyxerr << to_utf8(os.str()) << endl;
1674 bool Cursor::upDownInMath(bool up)
1676 // Be warned: The 'logic' implemented in this function is highly
1677 // fragile. A distance of one pixel or a '<' vs '<=' _really
1678 // matters. So fiddle around with it only if you think you know
1679 // what you are doing!
1683 xo = beforeDispatchPosX_;
1685 // check if we had something else in mind, if not, this is the future
1687 if (x_target_ == -1)
1689 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1690 // In text mode inside the line (not left or right) possibly set a new target_x,
1691 // but only if we are somewhere else than the previous target-offset.
1693 // We want to keep the x-target on subsequent up/down movements
1694 // that cross beyond the end of short lines. Thus a special
1695 // handling when the cursor is at the end of line: Use the new
1696 // x-target only if the old one was before the end of line
1697 // or the old one was after the beginning of the line
1698 bool inRTL = isWithinRtlParagraph(*this);
1702 left = pos() == textRow().endpos();
1703 right = pos() == textRow().pos();
1705 left = pos() == textRow().pos();
1706 right = pos() == textRow().endpos();
1708 if ((!left && !right) ||
1709 (left && !right && xo < x_target_) ||
1710 (!left && right && x_target_ < xo))
1717 // try neigbouring script insets
1719 if (inMathed() && !selection()) {
1722 InsetMathScript const * p = prevAtom()->asScriptInset();
1723 if (p && p->has(up)) {
1725 push(*const_cast<InsetMathScript*>(p));
1726 idx() = p->idxOfScript(up);
1729 // we went in the right direction? Otherwise don't jump into the script
1733 int oy = beforeDispatchPosY_;
1734 if ((!up && y <= oy) ||
1743 if (pos() != lastpos()) {
1744 InsetMathScript const * p = nextAtom()->asScriptInset();
1745 if (p && p->has(up)) {
1746 push(*const_cast<InsetMathScript*>(p));
1747 idx() = p->idxOfScript(up);
1750 // we went in the right direction? Otherwise don't jump into the script
1754 int oy = beforeDispatchPosY_;
1755 if ((!up && y <= oy) ||
1764 // try to find an inset that knows better then we,
1765 if (inset().idxUpDown(*this, up)) {
1766 //lyxerr << "idxUpDown triggered" << endl;
1767 // try to find best position within this inset
1769 setCursor(bruteFind2(*this, xo, yo));
1773 // any improvement going just out of inset?
1774 if (popBackward() && inMathed()) {
1775 //lyxerr << "updown: popBackward succeeded" << endl;
1778 int yold = beforeDispatchPosY_;
1780 if (up ? ynew < yold : ynew > yold)
1784 // no success, we are probably at the document top or bottom
1790 bool Cursor::atFirstOrLastRow(bool up)
1792 TextMetrics const & tm = bv_->textMetrics(text());
1793 ParagraphMetrics const & pm = tm.parMetrics(pit());
1796 if (pos() && boundary())
1797 row = pm.pos2row(pos() - 1);
1799 row = pm.pos2row(pos());
1802 if (pit() == 0 && row == 0)
1805 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1806 row + 1 >= int(pm.rows().size()))
1812 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1814 LASSERT(text(), /**/);
1820 xo = beforeDispatchPosX_;
1822 // update the targetX - this is here before the "return false"
1823 // to set a new target which can be used by InsetTexts above
1824 // if we cannot move up/down inside this inset anymore
1825 if (x_target_ == -1)
1827 else if (xo - textTargetOffset() != x_target() &&
1828 depth() == beforeDispatchCursor_.depth()) {
1829 // In text mode inside the line (not left or right) possibly set a new target_x,
1830 // but only if we are somewhere else than the previous target-offset.
1832 // We want to keep the x-target on subsequent up/down movements
1833 // that cross beyond the end of short lines. Thus a special
1834 // handling when the cursor is at the end of line: Use the new
1835 // x-target only if the old one was before the end of line
1836 // or the old one was after the beginning of the line
1837 bool inRTL = isWithinRtlParagraph(*this);
1841 left = pos() == textRow().endpos();
1842 right = pos() == textRow().pos();
1844 left = pos() == textRow().pos();
1845 right = pos() == textRow().endpos();
1847 if ((!left && !right) ||
1848 (left && !right && xo < x_target_) ||
1849 (!left && right && x_target_ < xo))
1856 // first get the current line
1857 TextMetrics & tm = bv_->textMetrics(text());
1858 ParagraphMetrics const & pm = tm.parMetrics(pit());
1860 if (pos() && boundary())
1861 row = pm.pos2row(pos() - 1);
1863 row = pm.pos2row(pos());
1865 if (atFirstOrLastRow(up)) {
1866 // Is there a place for the cursor to go ? If yes, we
1867 // can execute the DEPM, otherwise we should keep the
1868 // paragraph to host the cursor.
1869 Cursor dummy = *this;
1870 bool valid_destination = false;
1871 for(; dummy.depth(); dummy.pop())
1872 if (!dummy.atFirstOrLastRow(up)) {
1873 valid_destination = true;
1877 // will a next dispatch follow and if there is a new
1878 // dispatch will it move the cursor out ?
1879 if (depth() > 1 && valid_destination) {
1880 // The cursor hasn't changed yet. This happens when
1881 // you e.g. move out of an inset. And to give the
1882 // DEPM the possibility of doing something we must
1883 // provide it with two different cursors. (Lgb, vfr)
1885 dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
1886 dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
1888 updateNeeded |= bv().checkDepm(dummy, *this);
1889 updateTextTargetOffset();
1891 forceBufferUpdate();
1896 // with and without selection are handled differently
1898 int yo = bv().getPos(*this).y_;
1900 // To next/previous row
1902 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1904 tm.editXY(*this, xo, yo + textRow().descent() + 1);
1907 // This happens when you move out of an inset.
1908 // And to give the DEPM the possibility of doing
1909 // something we must provide it with two different
1911 Cursor dummy = *this;
1914 if (bv().checkDepm(dummy, old)) {
1915 updateNeeded = true;
1916 // Make sure that cur gets back whatever happened to dummy (Lgb)
1920 // if there is a selection, we stay out of any inset,
1921 // and just jump to the right position:
1927 } else if (pit() > 0) {
1929 TextMetrics & tm = bv_->textMetrics(text());
1930 if (!tm.contains(pit()))
1931 tm.newParMetricsUp();
1932 ParagraphMetrics const & pmcur = tm.parMetrics(pit());
1933 next_row = pmcur.rows().size() - 1;
1936 if (row + 1 < int(pm.rows().size())) {
1938 } else if (pit() + 1 < int(text()->paragraphs().size())) {
1940 TextMetrics & tm = bv_->textMetrics(text());
1941 if (!tm.contains(pit()))
1942 tm.newParMetricsDown();
1946 top().pos() = min(tm.x2pos(pit(), next_row, xo), top().lastpos());
1948 int const xpos = tm.x2pos(pit(), next_row, xo);
1949 bool const at_end_row = xpos == tm.x2pos(pit(), next_row, tm.width());
1950 bool const at_beg_row = xpos == tm.x2pos(pit(), next_row, 0);
1952 if (at_end_row && at_beg_row)
1953 // make sure the cursor ends up on this row
1956 boundary(at_end_row);
1958 updateNeeded |= bv().checkDepm(*this, old);
1962 forceBufferUpdate();
1963 updateTextTargetOffset();
1968 void Cursor::handleFont(string const & font)
1970 LYXERR(Debug::DEBUG, font);
1974 safe = cap::grabAndEraseSelection(*this);
1979 if (lastpos() != 0) {
1980 // something left in the cell
1982 // cursor in first position
1984 } else if (pos() == lastpos()) {
1985 // cursor in last position
1988 // cursor in between. split cell
1989 MathData::iterator bt = cell().begin();
1990 MathAtom at = createInsetMath(from_utf8(font), buffer());
1991 at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
1992 cell().erase(bt, bt + pos());
1997 // nothing left in the cell
2006 void Cursor::message(docstring const & msg) const
2008 disp_.setMessage(msg);
2012 void Cursor::errorMessage(docstring const & msg) const
2014 disp_.setMessage(msg);
2015 disp_.setError(true);
2019 static docstring parbreak(InsetCode code)
2021 odocstringstream os;
2023 // only add blank line if we're not in an ERT or Listings inset
2024 if (code != ERT_CODE && code != LISTINGS_CODE)
2030 docstring Cursor::selectionAsString(bool with_label) const
2036 return cap::grabSelection(*this);
2038 int const label = with_label
2039 ? AS_STR_LABEL | AS_STR_INSETS : AS_STR_INSETS;
2041 idx_type const startidx = selBegin().idx();
2042 idx_type const endidx = selEnd().idx();
2043 if (startidx != endidx) {
2044 // multicell selection
2045 InsetTabular * table = inset().asInsetTabular();
2046 LASSERT(table, return docstring());
2047 return table->asString(startidx, endidx);
2050 ParagraphList const & pars = text()->paragraphs();
2052 pit_type const startpit = selBegin().pit();
2053 pit_type const endpit = selEnd().pit();
2054 size_t const startpos = selBegin().pos();
2055 size_t const endpos = selEnd().pos();
2057 if (startpit == endpit)
2058 return pars[startpit].asString(startpos, endpos, label);
2060 // First paragraph in selection
2061 docstring result = pars[startpit].
2062 asString(startpos, pars[startpit].size(), label)
2063 + parbreak(inset().lyxCode());
2065 // The paragraphs in between (if any)
2066 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
2067 Paragraph const & par = pars[pit];
2068 result += par.asString(0, par.size(), label)
2069 + parbreak(inset().lyxCode());
2072 // Last paragraph in selection
2073 result += pars[endpit].asString(0, endpos, label);
2079 docstring Cursor::currentState() const
2082 odocstringstream os;
2088 return text()->currentState(*this);
2094 docstring Cursor::getPossibleLabel() const
2096 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
2100 Encoding const * Cursor::getEncoding() const
2104 CursorSlice const & sl = innerTextSlice();
2105 Text const & text = *sl.text();
2106 Font font = text.getPar(sl.pit()).getFont(
2107 bv().buffer().params(), sl.pos(), text.outerFont(sl.pit()));
2108 return font.language()->encoding();
2112 void Cursor::undispatched()
2114 disp_.dispatched(false);
2118 void Cursor::dispatched()
2120 disp_.dispatched(true);
2124 void Cursor::screenUpdateFlags(Update::flags f)
2126 disp_.screenUpdate(f);
2130 void Cursor::forceBufferUpdate()
2132 disp_.forceBufferUpdate();
2136 void Cursor::clearBufferUpdate()
2138 disp_.clearBufferUpdate();
2142 bool Cursor::needBufferUpdate() const
2144 return disp_.needBufferUpdate();
2148 void Cursor::noScreenUpdate()
2150 disp_.screenUpdate(Update::None);
2154 Font Cursor::getFont() const
2156 // The logic here should more or less match to the Cursor::setCurrentFont
2157 // logic, i.e. the cursor height should give a hint what will happen
2158 // if a character is entered.
2160 // HACK. far from being perfect...
2162 CursorSlice const & sl = innerTextSlice();
2163 Text const & text = *sl.text();
2164 Paragraph const & par = text.getPar(sl.pit());
2166 // on boundary, so we are really at the character before
2167 pos_type pos = sl.pos();
2168 if (pos > 0 && boundary())
2171 // on space? Take the font before (only for RTL boundary stay)
2173 TextMetrics const & tm = bv().textMetrics(&text);
2174 if (pos == sl.lastpos()
2175 || (par.isSeparator(pos)
2176 && !tm.isRTLBoundary(sl.pit(), pos)))
2180 // get font at the position
2181 Font font = par.getFont(buffer()->params(), pos,
2182 text.outerFont(sl.pit()));
2188 bool Cursor::fixIfBroken()
2190 bool const broken_cursor = DocIterator::fixIfBroken();
2191 bool const broken_anchor = anchor_.fixIfBroken();
2193 if (broken_cursor || broken_anchor) {
2201 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2203 // find inset in common
2205 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2206 if (&old[i].inset() != &cur[i].inset())
2210 // update words if we just moved to another paragraph
2211 if (i == old.depth() && i == cur.depth()
2212 && !cur.buffer()->isClean()
2213 && cur.inTexted() && old.inTexted()
2214 && cur.pit() != old.pit()) {
2215 old.paragraph().updateWords();
2218 // notify everything on top of the common part in old cursor,
2219 // but stop if the inset claims the cursor to be invalid now
2220 for (size_type j = i; j < old.depth(); ++j) {
2221 Cursor inset_pos = old;
2222 inset_pos.cutOff(j);
2223 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2227 // notify everything on top of the common part in new cursor,
2228 // but stop if the inset claims the cursor to be invalid now
2229 for (; i < cur.depth(); ++i) {
2230 if (cur[i].inset().notifyCursorEnters(cur))
2238 void Cursor::setCurrentFont()
2240 CursorSlice const & cs = innerTextSlice();
2241 Paragraph const & par = cs.paragraph();
2242 pos_type cpit = cs.pit();
2243 pos_type cpos = cs.pos();
2244 Text const & ctext = *cs.text();
2245 TextMetrics const & tm = bv().textMetrics(&ctext);
2247 // are we behind previous char in fact? -> go to that char
2248 if (cpos > 0 && boundary())
2251 // find position to take the font from
2253 // paragraph end? -> font of last char
2254 if (cpos == lastpos())
2256 // on space? -> look at the words in front of space
2257 else if (cpos > 0 && par.isSeparator(cpos)) {
2258 // abc| def -> font of c
2259 // abc |[WERBEH], i.e. boundary==true -> font of c
2260 // abc [WERBEH]| def, font of the space
2261 if (!tm.isRTLBoundary(cpit, cpos))
2267 BufferParams const & bufparams = buffer()->params();
2268 current_font = par.getFontSettings(bufparams, cpos);
2269 real_current_font = tm.displayFont(cpit, cpos);
2271 // special case for paragraph end
2272 if (cs.pos() == lastpos()
2273 && tm.isRTLBoundary(cpit, cs.pos())
2275 Language const * lang = par.getParLanguage(bufparams);
2276 current_font.setLanguage(lang);
2277 current_font.fontInfo().setNumber(FONT_OFF);
2278 real_current_font.setLanguage(lang);
2279 real_current_font.fontInfo().setNumber(FONT_OFF);
2284 bool Cursor::textUndo()
2286 DocIterator dit = *this;
2287 // Undo::textUndo() will modify dit.
2288 if (!buffer()->undo().textUndo(dit))
2298 bool Cursor::textRedo()
2300 DocIterator dit = *this;
2301 // Undo::textRedo() will modify dit.
2302 if (!buffer()->undo().textRedo(dit))
2312 void Cursor::finishUndo() const
2314 buffer()->undo().finishUndo();
2318 void Cursor::beginUndoGroup() const
2320 buffer()->undo().beginUndoGroup();
2324 void Cursor::endUndoGroup() const
2326 buffer()->undo().endUndoGroup();
2330 void Cursor::recordUndo(UndoKind kind, pit_type from, pit_type to) const
2332 buffer()->undo().recordUndo(*this, kind, from, to);
2336 void Cursor::recordUndo(UndoKind kind, pit_type from) const
2338 buffer()->undo().recordUndo(*this, kind, from);
2342 void Cursor::recordUndo(UndoKind kind) const
2344 buffer()->undo().recordUndo(*this, kind);
2348 void Cursor::recordUndoInset(UndoKind kind) const
2350 buffer()->undo().recordUndoInset(*this, kind);
2354 void Cursor::recordUndoFullDocument() const
2356 buffer()->undo().recordUndoFullDocument(*this);
2360 void Cursor::recordUndoSelection() const
2363 if (cap::multipleCellsSelected(*this))
2368 buffer()->undo().recordUndo(*this, ATOMIC_UNDO,
2369 selBegin().pit(), selEnd().pit());
2374 void Cursor::checkBufferStructure()
2376 Buffer const * master = buffer()->masterBuffer();
2377 master->tocBackend().updateItem(*this);
2378 if (master != buffer() && !master->hasGuiDelegate())
2379 // In case the master has no gui associated with it,
2380 // the TocItem is not updated (part of bug 5699).
2381 buffer()->tocBackend().updateItem(*this);