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 <boost/bind.hpp>
64 bool positionable(DocIterator const & cursor, DocIterator const & anchor)
66 // avoid deeper nested insets when selecting
67 if (cursor.depth() > anchor.depth())
70 // anchor might be deeper, should have same path then
71 for (size_t i = 0; i < cursor.depth(); ++i)
72 if (&cursor[i].inset() != &anchor[i].inset())
75 // position should be ok.
80 // Find position closest to (x, y) in cell given by iter.
81 // Used only in mathed
82 DocIterator bruteFind2(Cursor const & c, int x, int y)
84 double best_dist = numeric_limits<double>::max();
91 et.top().pos() = et.top().asInsetMath()->cell(et.top().idx()).size();
92 for (size_t i = 0;; ++i) {
95 Inset const * inset = &it.inset();
96 map<Inset const *, Geometry> const & data =
97 c.bv().coordCache().getInsets().getData();
98 map<Inset const *, Geometry>::const_iterator I = data.find(inset);
100 // FIXME: in the case where the inset is not in the cache, this
101 // means that no part of it is visible on screen. In this case
102 // we don't do elaborate search and we just return the forwarded
103 // DocIterator at its beginning.
104 if (I == data.end()) {
109 Point o = I->second.pos;
110 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
111 // Convert to absolute
114 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
115 // '<=' in order to take the last possible position
116 // this is important for clicking behind \sum in e.g. '\sum_i a'
117 LYXERR(Debug::DEBUG, "i: " << i << " d: " << d
118 << " best: " << best_dist);
119 if (d <= best_dist) {
132 /// moves position closest to (x, y) in given box
133 bool bruteFind(Cursor & cursor,
134 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
136 LASSERT(!cursor.empty(), return false);
137 Inset & inset = cursor[0].inset();
138 BufferView & bv = cursor.bv();
140 CoordCache::InnerParPosCache const & cache =
141 bv.coordCache().getParPos().find(cursor.bottom().text())->second;
142 // Get an iterator on the first paragraph in the cache
143 DocIterator it(inset);
144 it.push_back(CursorSlice(inset));
145 it.pit() = cache.begin()->first;
146 // Get an iterator after the last paragraph in the cache
147 DocIterator et(inset);
148 et.push_back(CursorSlice(inset));
149 et.pit() = boost::prior(cache.end())->first;
150 if (et.pit() >= et.lastpit())
151 et = doc_iterator_end(inset);
155 double best_dist = numeric_limits<double>::max();;
156 DocIterator best_cursor = et;
158 for ( ; it != et; it.forwardPos(true)) {
159 // avoid invalid nesting when selecting
160 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
161 Point p = bv.getPos(it, false);
164 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
165 double const dx = xo - x;
166 double const dy = yo - y;
167 double const d = dx * dx + dy * dy;
168 // '<=' in order to take the last possible position
169 // this is important for clicking behind \sum in e.g. '\sum_i a'
170 if (d <= best_dist) {
171 // lyxerr << "*" << endl;
179 if (best_cursor != et) {
180 cursor.setCursor(best_cursor);
189 /// moves position closest to (x, y) in given box
190 bool bruteFind3(Cursor & cur, int x, int y, bool up)
192 BufferView & bv = cur.bv();
193 int ylow = up ? 0 : y + 1;
194 int yhigh = up ? y - 1 : bv.workHeight();
196 int xhigh = bv.workWidth();
198 // FIXME: bit more work needed to get 'from' and 'to' right.
199 pit_type from = cur.bottom().pit();
200 //pit_type to = cur.bottom().pit();
201 //lyxerr << "Pit start: " << from << endl;
203 //lyxerr << "bruteFind3: x: " << x << " y: " << y
204 // << " xlow: " << xlow << " xhigh: " << xhigh
205 // << " ylow: " << ylow << " yhigh: " << yhigh
207 DocIterator it = doc_iterator_begin(cur.buffer());
209 DocIterator et = doc_iterator_end(cur.buffer());
211 double best_dist = numeric_limits<double>::max();
212 DocIterator best_cursor = et;
214 for ( ; it != et; it.forwardPos()) {
215 // avoid invalid nesting when selecting
216 if (bv.cursorStatus(it) == CUR_INSIDE
217 && (!cur.selection() || positionable(it, cur.anchor_))) {
218 Point p = bv.getPos(it, false);
221 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
222 double const dx = xo - x;
223 double const dy = yo - y;
224 double const d = dx * dx + dy * dy;
225 //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
226 // << " dx: " << dx << " dy: " << dy
227 // << " idx: " << it.idx() << " pos: " << it.pos()
230 // '<=' in order to take the last possible position
231 // this is important for clicking behind \sum in e.g. '\sum_i a'
232 if (d <= best_dist) {
233 //lyxerr << "*" << endl;
241 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
242 if (best_cursor == et)
244 cur.setCursor(best_cursor);
251 // be careful: this is called from the bv's constructor, too, so
252 // bv functions are not yet available!
253 Cursor::Cursor(BufferView & bv)
254 : DocIterator(&bv.buffer()), bv_(&bv), anchor_(),
255 x_target_(-1), textTargetOffset_(0),
256 selection_(false), mark_(false), word_selection_(false),
257 logicalpos_(false), current_font(inherit_font)
264 push_back(CursorSlice(buffer()->inset()));
265 anchor_ = doc_iterator_begin(buffer());
273 // this (intentionally) does neither touch anchor nor selection status
274 void Cursor::setCursor(DocIterator const & cur)
276 DocIterator::operator=(cur);
280 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
284 // Try to fix cursor in case it is broken.
287 // Is this a function that acts on inset at point?
288 Inset * inset = cur.nextInset();
289 if (lyxaction.funcHasFlag(cmd.action, LyXAction::AtPoint)
290 && inset && inset->getStatus(cur, cmd, status))
293 // This is, of course, a mess. Better create a new doc iterator and use
294 // this in Inset::getStatus. This might require an additional
295 // BufferView * arg, though (which should be avoided)
296 //Cursor safe = *this;
298 for ( ; cur.depth(); cur.pop()) {
299 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
300 LASSERT(cur.idx() <= cur.lastidx(), /**/);
301 LASSERT(cur.pit() <= cur.lastpit(), /**/);
302 LASSERT(cur.pos() <= cur.lastpos(), /**/);
304 // The inset's getStatus() will return 'true' if it made
305 // a definitive decision on whether it want to handle the
306 // request or not. The result of this decision is put into
307 // the 'status' parameter.
308 if (cur.inset().getStatus(cur, cmd, status)) {
317 void Cursor::saveBeforeDispatchPosXY()
319 getPos(beforeDispatchPosX_, beforeDispatchPosY_);
323 void Cursor::dispatch(FuncRequest const & cmd0)
325 LYXERR(Debug::DEBUG, "cmd: " << cmd0 << '\n' << *this);
330 FuncRequest cmd = cmd0;
333 buffer()->undo().beginUndoGroup();
335 // Is this a function that acts on inset at point?
336 if (lyxaction.funcHasFlag(cmd.action, LyXAction::AtPoint)
338 result().dispatched(true);
339 result().update(Update::FitCursor | Update::Force);
340 FuncRequest tmpcmd = cmd;
341 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
342 << cmd0 << endl << *this);
343 nextInset()->dispatch(*this, tmpcmd);
344 if (result().dispatched()) {
345 buffer()->undo().endUndoGroup();
350 // store some values to be used inside of the handlers
351 beforeDispatchCursor_ = *this;
352 for (; depth(); pop(), boundary(false)) {
353 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
354 << cmd0 << endl << *this);
355 LASSERT(pos() <= lastpos(), /**/);
356 LASSERT(idx() <= lastidx(), /**/);
357 LASSERT(pit() <= lastpit(), /**/);
359 // The common case is 'LFUN handled, need update', so make the
360 // LFUN handler's life easier by assuming this as default value.
361 // The handler can reset the update and val flags if necessary.
362 disp_.update(Update::FitCursor | Update::Force);
363 disp_.dispatched(true);
364 inset().dispatch(*this, cmd);
365 if (disp_.dispatched())
369 // it completely to get a 'bomb early' behaviour in case this
370 // object will be used again.
371 if (!disp_.dispatched()) {
372 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
373 // We might have invalidated the cursor when removing an empty
374 // paragraph while the cursor could not be moved out the inset
375 // while we initially thought we could. This might happen when
376 // a multiline inset becomes an inline inset when the second
377 // paragraph is removed.
378 if (safe.pit() > safe.lastpit()) {
379 safe.pit() = safe.lastpit();
380 safe.pos() = safe.lastpos();
383 disp_.update(Update::None);
384 disp_.dispatched(false);
386 // restore the previous one because nested Cursor::dispatch calls
387 // are possible which would change it
388 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
390 buffer()->undo().endUndoGroup();
394 DispatchResult Cursor::result() const
400 BufferView & Cursor::bv() const
409 LASSERT(depth() >= 1, /**/);
414 void Cursor::push(Inset & p)
416 push_back(CursorSlice(p));
417 p.setBuffer(*buffer());
421 void Cursor::pushBackward(Inset & p)
423 LASSERT(!empty(), return);
424 //lyxerr << "Entering inset " << t << " front" << endl;
430 bool Cursor::popBackward()
432 LASSERT(!empty(), return false);
440 bool Cursor::popForward()
442 LASSERT(!empty(), return false);
443 //lyxerr << "Leaving inset from in back" << endl;
444 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
448 pos() += lastpos() - lp + 1;
453 int Cursor::currentMode()
455 LASSERT(!empty(), /**/);
456 for (int i = depth() - 1; i >= 0; --i) {
457 int res = operator[](i).inset().currentMode();
458 bool locked_mode = operator[](i).inset().lockedMode();
459 // Also return UNDECIDED_MODE when the mode is locked,
460 // as in this case it is treated the same as TEXT_MODE
461 if (res != Inset::UNDECIDED_MODE || locked_mode)
464 return Inset::TEXT_MODE;
468 void Cursor::getPos(int & x, int & y) const
470 Point p = bv().getPos(*this, boundary());
476 Row const & Cursor::textRow() const
478 CursorSlice const & cs = innerTextSlice();
479 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
480 LASSERT(!pm.rows().empty(), /**/);
481 return pm.getRow(pos(), boundary());
485 void Cursor::resetAnchor()
491 void Cursor::setCursorToAnchor()
494 DocIterator normal = anchor_;
495 while (depth() < normal.depth())
497 if (depth() < anchor_.depth() && top() <= anchor_[depth() - 1])
504 bool Cursor::posBackward()
513 bool Cursor::posForward()
515 if (pos() == lastpos())
522 bool Cursor::posVisRight(bool skip_inset)
524 Cursor new_cur = *this; // where we will move to
525 pos_type left_pos; // position visually left of current cursor
526 pos_type right_pos; // position visually right of current cursor
527 bool new_pos_is_RTL; // is new position we're moving to RTL?
529 getSurroundingPos(left_pos, right_pos);
531 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
533 // Are we at an inset?
534 new_cur.pos() = right_pos;
535 new_cur.boundary(false);
537 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
538 // we actually move the cursor at the end of this function, for now
539 // we just keep track of the new position in new_cur...
540 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
543 // Are we already at rightmost pos in row?
544 else if (text()->empty() || right_pos == -1) {
547 if (!new_cur.posVisToNewRow(false)) {
548 LYXERR(Debug::RTL, "not moving!");
552 // we actually move the cursor at the end of this function, for now
553 // just keep track of the new position in new_cur...
554 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
555 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
558 // normal movement to the right
561 // Recall, if the cursor is at position 'x', that means *before*
562 // the character at position 'x'. In RTL, "before" means "to the
563 // right of", in LTR, "to the left of". So currently our situation
564 // is this: the position to our right is 'right_pos' (i.e., we're
565 // currently to the left of 'right_pos'). In order to move to the
566 // right, it depends whether or not the character at 'right_pos' is RTL.
567 new_pos_is_RTL = paragraph().getFontSettings(
568 buffer()->params(), right_pos).isVisibleRightToLeft();
569 // If the character at 'right_pos' *is* LTR, then in order to move to
570 // the right of it, we need to be *after* 'right_pos', i.e., move to
571 // position 'right_pos' + 1.
572 if (!new_pos_is_RTL) {
573 new_cur.pos() = right_pos + 1;
574 // set the boundary to true in two situations:
576 // 1. if new_pos is now lastpos, and we're in an RTL paragraph
577 // (this means that we're moving right to the end of an LTR chunk
578 // which is at the end of an RTL paragraph);
579 (new_cur.pos() == lastpos()
580 && paragraph().isRTL(buffer()->params()))
581 // 2. if the position *after* right_pos is RTL (we want to be
582 // *after* right_pos, not before right_pos + 1!)
583 || paragraph().getFontSettings(buffer()->params(),
584 new_cur.pos()).isVisibleRightToLeft()
586 new_cur.boundary(true);
587 else // set the boundary to false
588 new_cur.boundary(false);
590 // Otherwise (if the character at position 'right_pos' is RTL), then
591 // moving to the right of it is as easy as setting the new position
594 new_cur.pos() = right_pos;
595 new_cur.boundary(false);
600 bool moved = (new_cur.pos() != pos()
601 || new_cur.pit() != pit()
602 || new_cur.boundary() != boundary()
603 || &new_cur.inset() != &inset());
606 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
607 << (new_cur.boundary() ? " (boundary)" : ""));
615 bool Cursor::posVisLeft(bool skip_inset)
617 Cursor new_cur = *this; // where we will move to
618 pos_type left_pos; // position visually left of current cursor
619 pos_type right_pos; // position visually right of current cursor
620 bool new_pos_is_RTL; // is new position we're moving to RTL?
622 getSurroundingPos(left_pos, right_pos);
624 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
626 // Are we at an inset?
627 new_cur.pos() = left_pos;
628 new_cur.boundary(false);
630 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
631 // we actually move the cursor at the end of this function, for now
632 // we just keep track of the new position in new_cur...
633 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
636 // Are we already at leftmost pos in row?
637 else if (text()->empty() || left_pos == -1) {
640 if (!new_cur.posVisToNewRow(true)) {
641 LYXERR(Debug::RTL, "not moving!");
645 // we actually move the cursor at the end of this function, for now
646 // just keep track of the new position in new_cur...
647 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
648 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
651 // normal movement to the left
654 // Recall, if the cursor is at position 'x', that means *before*
655 // the character at position 'x'. In RTL, "before" means "to the
656 // right of", in LTR, "to the left of". So currently our situation
657 // is this: the position to our left is 'left_pos' (i.e., we're
658 // currently to the right of 'left_pos'). In order to move to the
659 // left, it depends whether or not the character at 'left_pos' is RTL.
660 new_pos_is_RTL = paragraph().getFontSettings(
661 buffer()->params(), left_pos).isVisibleRightToLeft();
662 // If the character at 'left_pos' *is* RTL, then in order to move to
663 // the left of it, we need to be *after* 'left_pos', i.e., move to
664 // position 'left_pos' + 1.
665 if (new_pos_is_RTL) {
666 new_cur.pos() = left_pos + 1;
667 // set the boundary to true in two situations:
669 // 1. if new_pos is now lastpos and we're in an LTR paragraph
670 // (this means that we're moving left to the end of an RTL chunk
671 // which is at the end of an LTR paragraph);
672 (new_cur.pos() == lastpos()
673 && !paragraph().isRTL(buffer()->params()))
674 // 2. if the position *after* left_pos is not RTL (we want to be
675 // *after* left_pos, not before left_pos + 1!)
676 || !paragraph().getFontSettings(buffer()->params(),
677 new_cur.pos()).isVisibleRightToLeft()
679 new_cur.boundary(true);
680 else // set the boundary to false
681 new_cur.boundary(false);
683 // Otherwise (if the character at position 'left_pos' is LTR), then
684 // moving to the left of it is as easy as setting the new position
687 new_cur.pos() = left_pos;
688 new_cur.boundary(false);
693 bool moved = (new_cur.pos() != pos()
694 || new_cur.pit() != pit()
695 || new_cur.boundary() != boundary());
698 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
699 << (new_cur.boundary() ? " (boundary)" : ""));
707 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos)
709 // preparing bidi tables
710 Paragraph const & par = paragraph();
711 Buffer const & buf = *buffer();
712 Row const & row = textRow();
714 bidi.computeTables(par, buf, row);
716 LYXERR(Debug::RTL, "bidi: " << row.pos() << "--" << row.endpos());
718 // The cursor is painted *before* the character at pos(), or, if 'boundary'
719 // is true, *after* the character at (pos() - 1). So we already have one
720 // known position around the cursor:
721 pos_type const known_pos = boundary() && pos() > 0 ? pos() - 1 : pos();
723 // edge case: if we're at the end of the paragraph, things are a little
724 // different (because lastpos is a position which does not really "exist"
725 // --- there's no character there yet).
726 if (known_pos == lastpos()) {
727 if (par.isRTL(buf.params())) {
729 right_pos = bidi.vis2log(row.pos());
733 left_pos = bidi.vis2log(row.endpos() - 1);
738 // Whether 'known_pos' is to the left or to the right of the cursor depends
739 // on whether it is an RTL or LTR character...
740 bool const cur_is_RTL =
741 par.getFontSettings(buf.params(), known_pos).isVisibleRightToLeft();
742 // ... in the following manner:
743 // For an RTL character, "before" means "to the right" and "after" means
744 // "to the left"; and for LTR, it's the reverse. So, 'known_pos' is to the
745 // right of the cursor if (RTL && boundary) or (!RTL && !boundary):
746 bool const known_pos_on_right = cur_is_RTL == boundary();
748 // So we now know one of the positions surrounding the cursor. Let's
749 // determine the other one:
750 if (known_pos_on_right) {
751 right_pos = known_pos;
752 // *visual* position of 'left_pos':
753 pos_type v_left_pos = bidi.log2vis(right_pos) - 1;
754 // If the position we just identified as 'left_pos' is a "skipped
755 // separator" (a separator which is at the logical end of a row,
756 // except for the last row in a paragraph; such separators are not
757 // painted, so they "are not really there"; note that in bidi text,
758 // such a separator could appear visually in the middle of a row),
759 // set 'left_pos' to the *next* position to the left.
760 if (bidi.inRange(v_left_pos)
761 && bidi.vis2log(v_left_pos) + 1 == row.endpos()
762 && row.endpos() < lastpos()
763 && par.isSeparator(bidi.vis2log(v_left_pos)))
766 // calculate the logical position of 'left_pos', if in row
767 if (!bidi.inRange(v_left_pos))
770 left_pos = bidi.vis2log(v_left_pos);
771 // If the position we identified as 'right_pos' is a "skipped
772 // separator", set 'right_pos' to the *next* position to the right.
773 if (right_pos + 1 == row.endpos() && row.endpos() < lastpos()
774 && par.isSeparator(right_pos)) {
775 pos_type const v_right_pos = bidi.log2vis(right_pos) + 1;
776 if (!bidi.inRange(v_right_pos))
779 right_pos = bidi.vis2log(v_right_pos);
782 // known_pos is on the left
783 left_pos = known_pos;
784 // *visual* position of 'right_pos'
785 pos_type v_right_pos = bidi.log2vis(left_pos) + 1;
786 // If the position we just identified as 'right_pos' is a "skipped
787 // separator", set 'right_pos' to the *next* position to the right.
788 if (bidi.inRange(v_right_pos)
789 && bidi.vis2log(v_right_pos) + 1 == row.endpos()
790 && row.endpos() < lastpos()
791 && par.isSeparator(bidi.vis2log(v_right_pos)))
794 // calculate the logical position of 'right_pos', if in row
795 if (!bidi.inRange(v_right_pos))
798 right_pos = bidi.vis2log(v_right_pos);
799 // If the position we identified as 'left_pos' is a "skipped
800 // separator", set 'left_pos' to the *next* position to the left.
801 if (left_pos + 1 == row.endpos() && row.endpos() < lastpos()
802 && par.isSeparator(left_pos)) {
803 pos_type const v_left_pos = bidi.log2vis(left_pos) - 1;
804 if (!bidi.inRange(v_left_pos))
807 left_pos = bidi.vis2log(v_left_pos);
814 bool Cursor::posVisToNewRow(bool movingLeft)
816 Paragraph const & par = paragraph();
817 Buffer const & buf = *buffer();
818 Row const & row = textRow();
819 bool par_is_LTR = !par.isRTL(buf.params());
821 // Inside a table, determining whether to move to the next or previous row
822 // should be done based on the table's direction.
824 if (s >= 1 && (*this)[s].inset().asInsetTabular()) {
825 par_is_LTR = !(*this)[s].inset().asInsetTabular()->isRightToLeft(*this);
826 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
829 // if moving left in an LTR paragraph or moving right in an RTL one,
830 // move to previous row
831 if (par_is_LTR == movingLeft) {
832 if (row.pos() == 0) { // we're at first row in paragraph
833 if (pit() == 0) // no previous paragraph! don't move
835 // move to last pos in previous par
839 } else { // move to previous row in this par
840 pos() = row.pos() - 1; // this is guaranteed to be in previous row
844 // if moving left in an RTL paragraph or moving right in an LTR one,
847 if (row.endpos() == lastpos()) { // we're at last row in paragraph
848 if (pit() == lastpit()) // last paragraph! don't move
850 // move to first row in next par
854 } else { // move to next row in this par
855 pos() = row.endpos();
860 // make sure we're at left-/right-most pos in new row
861 posVisToRowExtremity(!movingLeft);
867 void Cursor::posVisToRowExtremity(bool left)
869 // prepare bidi tables
870 Paragraph const & par = paragraph();
871 Buffer const & buf = *buffer();
872 Row const & row = textRow();
874 bidi.computeTables(par, buf, row);
876 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
877 << (boundary() ? 1 : 0));
879 if (left) { // move to leftmost position
880 // if this is an RTL paragraph, and we're at the last row in the
881 // paragraph, move to lastpos
882 if (par.isRTL(buf.params()) && row.endpos() == lastpos())
885 pos() = bidi.vis2log(row.pos());
887 // Moving to the leftmost position in the row, the cursor should
888 // normally be placed to the *left* of the leftmost position.
889 // A very common exception, though, is if the leftmost character
890 // also happens to be the separator at the (logical) end of the row
891 // --- in this case, the separator is positioned beyond the left
892 // margin, and we don't want to move the cursor there (moving to
893 // the left of the separator is equivalent to moving to the next
894 // line). So, in this case we actually want to place the cursor
895 // to the *right* of the leftmost position (the separator).
896 // Another exception is if we're moving to the logically last
897 // position in the row, which is *not* a separator: this means
898 // that the entire row has no separators (if there were any, the
899 // row would have been broken there); and therefore in this case
900 // we also move to the *right* of the last position (this indicates
901 // to the user that there is no space after this position, and is
902 // consistent with the behavior in the middle of a row --- moving
903 // right or left moves to the next/previous character; if we were
904 // to move to the *left* of this position, that would simulate
905 // a separator which is not really there!).
906 // Finally, there is an exception to the previous exception: if
907 // this non-separator-but-last-position-in-row is an inset, then
908 // we *do* want to stay to the left of it anyway: this is the
909 // "boundary" which we simulate at insets.
910 // Another exception is when row.endpos() is 0.
912 // do we want to be to the right of pos?
913 // as explained above, if at last pos in row, stay to the right
914 bool const right_of_pos = row.endpos() > 0
915 && pos() == row.endpos() - 1 && !par.isInset(pos());
917 // Now we know if we want to be to the left or to the right of pos,
918 // let's make sure we are where we want to be.
919 bool const new_pos_is_RTL =
920 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
922 if (new_pos_is_RTL != right_of_pos) {
928 // move to rightmost position
929 // if this is an LTR paragraph, and we're at the last row in the
930 // paragraph, move to lastpos
931 if (!par.isRTL(buf.params()) && row.endpos() == lastpos())
934 pos() = row.endpos() > 0 ? bidi.vis2log(row.endpos() - 1) : 0;
936 // Moving to the rightmost position in the row, the cursor should
937 // normally be placed to the *right* of the rightmost position.
938 // A very common exception, though, is if the rightmost character
939 // also happens to be the separator at the (logical) end of the row
940 // --- in this case, the separator is positioned beyond the right
941 // margin, and we don't want to move the cursor there (moving to
942 // the right of the separator is equivalent to moving to the next
943 // line). So, in this case we actually want to place the cursor
944 // to the *left* of the rightmost position (the separator).
945 // Another exception is if we're moving to the logically last
946 // position in the row, which is *not* a separator: this means
947 // that the entire row has no separators (if there were any, the
948 // row would have been broken there); and therefore in this case
949 // we also move to the *left* of the last position (this indicates
950 // to the user that there is no space after this position, and is
951 // consistent with the behavior in the middle of a row --- moving
952 // right or left moves to the next/previous character; if we were
953 // to move to the *right* of this position, that would simulate
954 // a separator which is not really there!).
955 // Finally, there is an exception to the previous exception: if
956 // this non-separator-but-last-position-in-row is an inset, then
957 // we *do* want to stay to the right of it anyway: this is the
958 // "boundary" which we simulate at insets.
959 // Another exception is when row.endpos() is 0.
961 // do we want to be to the left of pos?
962 // as explained above, if at last pos in row, stay to the left,
963 // unless the last position is the same as the first.
964 bool const left_of_pos = row.endpos() > 0
965 && pos() == row.endpos() - 1 && !par.isInset(pos());
967 // Now we know if we want to be to the left or to the right of pos,
968 // let's make sure we are where we want to be.
969 bool const new_pos_is_RTL =
970 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
972 if (new_pos_is_RTL == left_of_pos) {
978 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
979 << (boundary() ? 1 : 0));
983 CursorSlice Cursor::anchor() const
987 LASSERT(anchor_.depth() >= depth(), /**/);
988 CursorSlice normal = anchor_[depth() - 1];
989 if (depth() < anchor_.depth() && top() <= normal) {
990 // anchor is behind cursor -> move anchor behind the inset
997 CursorSlice Cursor::selBegin() const
1001 return anchor() < top() ? anchor() : top();
1005 CursorSlice Cursor::selEnd() const
1009 return anchor() > top() ? anchor() : top();
1013 DocIterator Cursor::selectionBegin() const
1019 // FIXME: This is a work-around for the problem that
1020 // CursorSlice doesn't keep track of the boundary.
1021 if (anchor() == top())
1022 di = anchor_.boundary() > boundary() ? anchor_ : *this;
1024 di = anchor() < top() ? anchor_ : *this;
1030 DocIterator Cursor::selectionEnd() const
1036 // FIXME: This is a work-around for the problem that
1037 // CursorSlice doesn't keep track of the boundary.
1038 if (anchor() == top())
1039 di = anchor_.boundary() < boundary() ? anchor_ : *this;
1041 di = anchor() > top() ? anchor_ : *this;
1043 if (di.depth() > depth()) {
1051 void Cursor::setSelection()
1054 // A selection with no contents is not a selection
1055 // FIXME: doesnt look ok
1056 if (idx() == anchor().idx() &&
1057 pit() == anchor().pit() &&
1058 pos() == anchor().pos())
1059 setSelection(false);
1063 void Cursor::setSelection(DocIterator const & where, int n)
1072 void Cursor::clearSelection()
1074 setSelection(false);
1075 setWordSelection(false);
1081 void Cursor::setTargetX(int x)
1084 textTargetOffset_ = 0;
1088 int Cursor::x_target() const
1094 void Cursor::clearTargetX()
1097 textTargetOffset_ = 0;
1101 void Cursor::updateTextTargetOffset()
1106 textTargetOffset_ = x - x_target_;
1110 void Cursor::info(odocstream & os) const
1112 for (int i = 1, n = depth(); i < n; ++i) {
1113 operator[](i).inset().infoize(os);
1117 Inset const * inset = prevInset();
1118 // prevInset() can return 0 in certain case.
1120 prevInset()->infoize2(os);
1122 // overwite old message
1127 bool Cursor::selHandle(bool sel)
1129 //lyxerr << "Cursor::selHandle" << endl;
1132 if (sel == selection())
1136 cap::saveSelection(*this);
1144 ostream & operator<<(ostream & os, Cursor const & cur)
1146 os << "\n cursor: | anchor:\n";
1147 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
1148 os << " " << cur[i] << " | ";
1149 if (i < cur.anchor_.depth())
1150 os << cur.anchor_[i];
1152 os << "-------------------------------";
1155 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
1156 os << "------------------------------- | " << cur.anchor_[i] << "\n";
1158 os << " selection: " << cur.selection_
1159 << " x_target: " << cur.x_target_ << endl;
1164 LyXErr & operator<<(LyXErr & os, Cursor const & cur)
1174 ///////////////////////////////////////////////////////////////////
1177 // The part below is the non-integrated rest of the original math
1178 // cursor. This should be either generalized for texted or moved
1179 // back to mathed (in most cases to InsetMathNest).
1181 ///////////////////////////////////////////////////////////////////
1183 #include "mathed/InsetMathChar.h"
1184 #include "mathed/InsetMathGrid.h"
1185 #include "mathed/InsetMathScript.h"
1186 #include "mathed/InsetMathUnknown.h"
1187 #include "mathed/MathFactory.h"
1188 #include "mathed/MathStream.h"
1189 #include "mathed/MathSupport.h"
1194 //#define FILEDEBUG 1
1197 bool Cursor::isInside(Inset const * p) const
1199 for (size_t i = 0; i != depth(); ++i)
1200 if (&operator[](i).inset() == p)
1206 void Cursor::leaveInset(Inset const & inset)
1208 for (size_t i = 0; i != depth(); ++i) {
1209 if (&operator[](i).inset() == &inset) {
1217 bool Cursor::openable(MathAtom const & t) const
1228 // we can't move into anything new during selection
1229 if (depth() >= anchor_.depth())
1231 if (t.nucleus() != &anchor_[depth()].inset())
1238 void Cursor::setScreenPos(int x, int /*y*/)
1241 //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
1246 void Cursor::plainErase()
1248 cell().erase(pos());
1252 void Cursor::markInsert()
1254 insert(char_type(0));
1258 void Cursor::markErase()
1260 cell().erase(pos());
1264 void Cursor::plainInsert(MathAtom const & t)
1266 cell().insert(pos(), t);
1268 inset().setBuffer(bv_->buffer());
1273 void Cursor::insert(docstring const & str)
1275 for_each(str.begin(), str.end(),
1276 boost::bind(static_cast<void(Cursor::*)(char_type)>
1277 (&Cursor::insert), this, _1));
1281 void Cursor::insert(char_type c)
1283 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1284 LASSERT(!empty(), /**/);
1286 cap::selClearOrDel(*this);
1287 insert(new InsetMathChar(c));
1289 text()->insertChar(*this, c);
1294 void Cursor::insert(MathAtom const & t)
1296 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1298 cap::selClearOrDel(*this);
1303 void Cursor::insert(Inset * inset0)
1305 LASSERT(inset0, /**/);
1307 insert(MathAtom(inset0));
1309 text()->insertInset(*this, inset0);
1310 inset0->setBuffer(bv_->buffer());
1316 void Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1318 MathData ar(buffer());
1320 if (ar.size() == 1 && (enter || selection()))
1327 void Cursor::niceInsert(MathAtom const & t)
1330 docstring const safe = cap::grabAndEraseSelection(*this);
1332 // If possible, enter the new inset and move the contents of the selection
1333 if (t->isActive()) {
1335 // be careful here: don't use 'pushBackward(t)' as this we need to
1336 // push the clone, not the original
1337 pushBackward(*nextInset());
1338 // We may not use niceInsert here (recursion)
1339 MathData ar(buffer());
1346 void Cursor::insert(MathData const & ar)
1350 cap::eraseSelection(*this);
1351 cell().insert(pos(), ar);
1353 // FIXME audit setBuffer/updateBuffer calls
1354 inset().setBuffer(bv_->buffer());
1358 bool Cursor::backspace()
1360 autocorrect() = false;
1363 cap::eraseSelection(*this);
1368 // If empty cell, and not part of a big cell
1369 if (lastpos() == 0 && inset().nargs() == 1) {
1371 // Directly delete empty cell: [|[]] => [|]
1377 // [|], can not delete from inside
1388 if (inMacroMode()) {
1389 InsetMathUnknown * p = activeMacro();
1390 if (p->name().size() > 1) {
1391 p->setName(p->name().substr(0, p->name().size() - 1));
1396 if (pos() != 0 && prevAtom()->nargs() > 0) {
1397 // let's require two backspaces for 'big stuff' and
1398 // highlight on the first
1410 bool Cursor::erase()
1412 autocorrect() = false;
1417 cap::eraseSelection(*this);
1421 // delete empty cells if possible
1422 if (pos() == lastpos() && inset().idxDelete(idx()))
1425 // special behaviour when in last position of cell
1426 if (pos() == lastpos()) {
1427 bool one_cell = inset().nargs() == 1;
1428 if (one_cell && lastpos() == 0) {
1430 // Directly delete empty cell: [|[]] => [|]
1436 // [|], can not delete from inside
1441 inset().idxGlue(idx());
1445 // 'clever' UI hack: only erase large items if previously slected
1446 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
1461 DocIterator save = *this;
1462 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1463 this->dispatch(cmd);
1464 if (disp_.dispatched())
1467 autocorrect() = false;
1475 DocIterator save = *this;
1476 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1477 this->dispatch(cmd);
1478 if (disp_.dispatched())
1481 autocorrect() = false;
1486 bool Cursor::macroModeClose()
1490 InsetMathUnknown * p = activeMacro();
1492 MathData selection(buffer());
1493 asArray(p->selection(), selection);
1494 docstring const s = p->name();
1496 cell().erase(pos());
1498 // do nothing if the macro name is empty
1502 // trigger updates of macros, at least, if no full
1503 // updates take place anyway
1504 updateFlags(Update::Force);
1506 docstring const name = s.substr(1);
1507 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1508 if (in && in->interpretString(*this, s))
1510 MathAtom atom = buffer()->getMacro(name, *this, false) ?
1511 MathAtom(new MathMacro(buffer(), name)) : createInsetMath(name, buffer());
1513 // try to put argument into macro, if we just inserted a macro
1514 bool macroArg = false;
1515 MathMacro * atomAsMacro = atom.nucleus()->asMacro();
1517 // macros here are still unfolded (in init mode in fact). So
1518 // we have to resolve the macro here manually and check its arity
1519 // to put the selection behind it if arity > 0.
1520 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1521 if (selection.size() > 0 && data && data->numargs() - data->optionals() > 0) {
1523 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1525 // non-greedy case. Do not touch the arguments behind
1526 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1529 // insert remembered selection into first argument of a non-macro
1530 else if (atom.nucleus()->nargs() > 0)
1531 atom.nucleus()->cell(0).append(selection);
1535 // finally put the macro argument behind, if needed
1537 if (selection.size() > 1 || selection[0]->asScriptInset())
1538 plainInsert(MathAtom(new InsetMathBrace(selection)));
1547 docstring Cursor::macroName()
1549 return inMacroMode() ? activeMacro()->name() : docstring();
1553 void Cursor::handleNest(MathAtom const & a, int c)
1555 //lyxerr << "Cursor::handleNest: " << c << endl;
1557 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1560 pushBackward(*nextInset());
1564 int Cursor::targetX() const
1566 if (x_target() != -1)
1575 int Cursor::textTargetOffset() const
1577 return textTargetOffset_;
1581 void Cursor::setTargetX()
1590 bool Cursor::inMacroMode() const
1596 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1597 return p && !p->final();
1601 InsetMathUnknown * Cursor::activeMacro()
1603 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1607 InsetMathUnknown const * Cursor::activeMacro() const
1609 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1613 void Cursor::pullArg()
1616 MathData ar = cell();
1617 if (popBackward() && inMathed()) {
1619 cell().insert(pos(), ar);
1622 //formula()->mutateToText();
1627 void Cursor::touch()
1631 DocIterator::const_iterator it = begin();
1632 DocIterator::const_iterator et = end();
1633 for ( ; it != et; ++it)
1639 void Cursor::normalize()
1641 if (idx() > lastidx()) {
1642 lyxerr << "this should not really happen - 1: "
1643 << idx() << ' ' << nargs()
1644 << " in: " << &inset() << endl;
1648 if (pos() > lastpos()) {
1649 lyxerr << "this should not really happen - 2: "
1650 << pos() << ' ' << lastpos() << " in idx: " << idx()
1652 odocstringstream os;
1653 WriteStream wi(os, false, true, WriteStream::wsDefault);
1654 inset().asInsetMath()->write(wi);
1655 lyxerr << to_utf8(os.str()) << endl;
1661 bool Cursor::upDownInMath(bool up)
1663 // Be warned: The 'logic' implemented in this function is highly
1664 // fragile. A distance of one pixel or a '<' vs '<=' _really
1665 // matters. So fiddle around with it only if you think you know
1666 // what you are doing!
1670 xo = beforeDispatchPosX_;
1672 // check if we had something else in mind, if not, this is the future
1674 if (x_target_ == -1)
1676 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1677 // In text mode inside the line (not left or right) possibly set a new target_x,
1678 // but only if we are somewhere else than the previous target-offset.
1680 // We want to keep the x-target on subsequent up/down movements
1681 // that cross beyond the end of short lines. Thus a special
1682 // handling when the cursor is at the end of line: Use the new
1683 // x-target only if the old one was before the end of line
1684 // or the old one was after the beginning of the line
1685 bool inRTL = isWithinRtlParagraph(*this);
1689 left = pos() == textRow().endpos();
1690 right = pos() == textRow().pos();
1692 left = pos() == textRow().pos();
1693 right = pos() == textRow().endpos();
1695 if ((!left && !right) ||
1696 (left && !right && xo < x_target_) ||
1697 (!left && right && x_target_ < xo))
1704 // try neigbouring script insets
1706 if (inMathed() && !selection()) {
1709 InsetMathScript const * p = prevAtom()->asScriptInset();
1710 if (p && p->has(up)) {
1712 push(*const_cast<InsetMathScript*>(p));
1713 idx() = p->idxOfScript(up);
1716 // we went in the right direction? Otherwise don't jump into the script
1720 int oy = beforeDispatchPosY_;
1721 if ((!up && y <= oy) ||
1730 if (pos() != lastpos()) {
1731 InsetMathScript const * p = nextAtom()->asScriptInset();
1732 if (p && p->has(up)) {
1733 push(*const_cast<InsetMathScript*>(p));
1734 idx() = p->idxOfScript(up);
1737 // we went in the right direction? Otherwise don't jump into the script
1741 int oy = beforeDispatchPosY_;
1742 if ((!up && y <= oy) ||
1751 // try to find an inset that knows better then we,
1752 if (inset().idxUpDown(*this, up)) {
1753 //lyxerr << "idxUpDown triggered" << endl;
1754 // try to find best position within this inset
1756 setCursor(bruteFind2(*this, xo, yo));
1760 // any improvement going just out of inset?
1761 if (popBackward() && inMathed()) {
1762 //lyxerr << "updown: popBackward succeeded" << endl;
1765 int yold = beforeDispatchPosY_;
1767 if (up ? ynew < yold : ynew > yold)
1771 // no success, we are probably at the document top or bottom
1777 bool Cursor::atFirstOrLastRow(bool up)
1779 TextMetrics const & tm = bv_->textMetrics(text());
1780 ParagraphMetrics const & pm = tm.parMetrics(pit());
1783 if (pos() && boundary())
1784 row = pm.pos2row(pos() - 1);
1786 row = pm.pos2row(pos());
1789 if (pit() == 0 && row == 0)
1792 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1793 row + 1 >= int(pm.rows().size()))
1799 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1801 LASSERT(text(), /**/);
1807 xo = beforeDispatchPosX_;
1809 // update the targetX - this is here before the "return false"
1810 // to set a new target which can be used by InsetTexts above
1811 // if we cannot move up/down inside this inset anymore
1812 if (x_target_ == -1)
1814 else if (xo - textTargetOffset() != x_target() &&
1815 depth() == beforeDispatchCursor_.depth()) {
1816 // In text mode inside the line (not left or right) possibly set a new target_x,
1817 // but only if we are somewhere else than the previous target-offset.
1819 // We want to keep the x-target on subsequent up/down movements
1820 // that cross beyond the end of short lines. Thus a special
1821 // handling when the cursor is at the end of line: Use the new
1822 // x-target only if the old one was before the end of line
1823 // or the old one was after the beginning of the line
1824 bool inRTL = isWithinRtlParagraph(*this);
1828 left = pos() == textRow().endpos();
1829 right = pos() == textRow().pos();
1831 left = pos() == textRow().pos();
1832 right = pos() == textRow().endpos();
1834 if ((!left && !right) ||
1835 (left && !right && xo < x_target_) ||
1836 (!left && right && x_target_ < xo))
1843 // first get the current line
1844 TextMetrics & tm = bv_->textMetrics(text());
1845 ParagraphMetrics const & pm = tm.parMetrics(pit());
1847 if (pos() && boundary())
1848 row = pm.pos2row(pos() - 1);
1850 row = pm.pos2row(pos());
1852 if (atFirstOrLastRow(up)) {
1853 // Is there a place for the cursor to go ? If yes, we
1854 // can execute the DEPM, otherwise we should keep the
1855 // paragraph to host the cursor.
1856 Cursor dummy = *this;
1857 bool valid_destination = false;
1858 for(; dummy.depth(); dummy.pop())
1859 if (!dummy.atFirstOrLastRow(up)) {
1860 valid_destination = true;
1864 // will a next dispatch follow and if there is a new
1865 // dispatch will it move the cursor out ?
1866 if (depth() > 1 && valid_destination) {
1867 // The cursor hasn't changed yet. This happens when
1868 // you e.g. move out of an inset. And to give the
1869 // DEPM the possibility of doing something we must
1870 // provide it with two different cursors. (Lgb, vfr)
1872 dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
1873 dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
1875 updateNeeded |= bv().checkDepm(dummy, *this);
1876 updateTextTargetOffset();
1881 // with and without selection are handled differently
1883 int yo = bv().getPos(*this, boundary()).y_;
1885 // To next/previous row
1887 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1889 tm.editXY(*this, xo, yo + textRow().descent() + 1);
1892 // This happens when you move out of an inset.
1893 // And to give the DEPM the possibility of doing
1894 // something we must provide it with two different
1896 Cursor dummy = *this;
1899 if (bv().checkDepm(dummy, old)) {
1900 updateNeeded = true;
1901 // Make sure that cur gets back whatever happened to dummy(Lgb)
1905 // if there is a selection, we stay out of any inset,
1906 // and just jump to the right position:
1912 } else if (pit() > 0) {
1914 TextMetrics & tm = bv_->textMetrics(text());
1915 if (!tm.contains(pit()))
1916 tm.newParMetricsUp();
1917 ParagraphMetrics const & pmcur = tm.parMetrics(pit());
1918 next_row = pmcur.rows().size() - 1;
1921 if (row + 1 < int(pm.rows().size())) {
1923 } else if (pit() + 1 < int(text()->paragraphs().size())) {
1925 TextMetrics & tm = bv_->textMetrics(text());
1926 if (!tm.contains(pit()))
1927 tm.newParMetricsDown();
1931 top().pos() = min(tm.x2pos(pit(), next_row, xo), top().lastpos());
1933 int const xpos = tm.x2pos(pit(), next_row, xo);
1934 bool const at_end_row = xpos == tm.x2pos(pit(), next_row, tm.width());
1935 bool const at_beg_row = xpos == tm.x2pos(pit(), next_row, 0);
1937 if (at_end_row && at_beg_row)
1938 // make sure the cursor ends up on this row
1941 boundary(at_end_row);
1943 updateNeeded |= bv().checkDepm(*this, old);
1946 updateTextTargetOffset();
1951 void Cursor::handleFont(string const & font)
1953 LYXERR(Debug::DEBUG, font);
1957 safe = cap::grabAndEraseSelection(*this);
1962 if (lastpos() != 0) {
1963 // something left in the cell
1965 // cursor in first position
1967 } else if (pos() == lastpos()) {
1968 // cursor in last position
1971 // cursor in between. split cell
1972 MathData::iterator bt = cell().begin();
1973 MathAtom at = createInsetMath(from_utf8(font), buffer());
1974 at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
1975 cell().erase(bt, bt + pos());
1980 // nothing left in the cell
1989 void Cursor::message(docstring const & msg) const
1991 disp_.setMessage(msg);
1995 void Cursor::errorMessage(docstring const & msg) const
1997 disp_.setMessage(msg);
1998 disp_.setError(true);
2002 static docstring parbreak(InsetCode code)
2004 odocstringstream os;
2006 // only add blank line if we're not in an ERT or Listings inset
2007 if (code != ERT_CODE && code != LISTINGS_CODE)
2013 docstring Cursor::selectionAsString(bool with_label) const
2019 return cap::grabSelection(*this);
2021 int const label = with_label
2022 ? AS_STR_LABEL | AS_STR_INSETS : AS_STR_INSETS;
2024 idx_type const startidx = selBegin().idx();
2025 idx_type const endidx = selEnd().idx();
2026 if (startidx != endidx) {
2027 // multicell selection
2028 InsetTabular * table = inset().asInsetTabular();
2029 LASSERT(table, return docstring());
2030 return table->asString(startidx, endidx);
2033 ParagraphList const & pars = text()->paragraphs();
2035 pit_type const startpit = selBegin().pit();
2036 pit_type const endpit = selEnd().pit();
2037 size_t const startpos = selBegin().pos();
2038 size_t const endpos = selEnd().pos();
2040 if (startpit == endpit)
2041 return pars[startpit].asString(startpos, endpos, label);
2043 // First paragraph in selection
2044 docstring result = pars[startpit].
2045 asString(startpos, pars[startpit].size(), label)
2046 + parbreak(inset().lyxCode());
2048 // The paragraphs in between (if any)
2049 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
2050 Paragraph const & par = pars[pit];
2051 result += par.asString(0, par.size(), label)
2052 + parbreak(inset().lyxCode());
2055 // Last paragraph in selection
2056 result += pars[endpit].asString(0, endpos, label);
2062 docstring Cursor::currentState() const
2065 odocstringstream os;
2071 return text()->currentState(*this);
2077 docstring Cursor::getPossibleLabel() const
2079 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
2083 Encoding const * Cursor::getEncoding() const
2087 CursorSlice const & sl = innerTextSlice();
2088 Text const & text = *sl.text();
2089 Font font = text.getPar(sl.pit()).getFont(
2090 bv().buffer().params(), sl.pos(), text.outerFont(sl.pit()));
2091 return font.language()->encoding();
2095 void Cursor::undispatched()
2097 disp_.dispatched(false);
2101 void Cursor::dispatched()
2103 disp_.dispatched(true);
2107 void Cursor::updateFlags(Update::flags f)
2113 void Cursor::noUpdate()
2115 disp_.update(Update::None);
2119 Font Cursor::getFont() const
2121 // The logic here should more or less match to the Cursor::setCurrentFont
2122 // logic, i.e. the cursor height should give a hint what will happen
2123 // if a character is entered.
2125 // HACK. far from being perfect...
2127 CursorSlice const & sl = innerTextSlice();
2128 Text const & text = *sl.text();
2129 Paragraph const & par = text.getPar(sl.pit());
2131 // on boundary, so we are really at the character before
2132 pos_type pos = sl.pos();
2133 if (pos > 0 && boundary())
2136 // on space? Take the font before (only for RTL boundary stay)
2138 TextMetrics const & tm = bv().textMetrics(&text);
2139 if (pos == sl.lastpos()
2140 || (par.isSeparator(pos)
2141 && !tm.isRTLBoundary(sl.pit(), pos)))
2145 // get font at the position
2146 Font font = par.getFont(buffer()->params(), pos,
2147 text.outerFont(sl.pit()));
2153 bool Cursor::fixIfBroken()
2155 bool const broken_cursor = DocIterator::fixIfBroken();
2156 bool const broken_anchor = anchor_.fixIfBroken();
2158 if (broken_cursor || broken_anchor) {
2166 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2168 // find inset in common
2170 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2171 if (&old[i].inset() != &cur[i].inset())
2175 // update words if we just moved to another paragraph
2176 if (i == old.depth() && i == cur.depth()
2177 && !cur.buffer()->isClean()
2178 && cur.inTexted() && old.inTexted()
2179 && cur.pit() != old.pit()) {
2180 old.paragraph().updateWords();
2183 // notify everything on top of the common part in old cursor,
2184 // but stop if the inset claims the cursor to be invalid now
2185 for (size_type j = i; j < old.depth(); ++j) {
2186 Cursor inset_pos = old;
2187 inset_pos.cutOff(j);
2188 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2192 // notify everything on top of the common part in new cursor,
2193 // but stop if the inset claims the cursor to be invalid now
2194 for (; i < cur.depth(); ++i) {
2195 if (cur[i].inset().notifyCursorEnters(cur))
2203 void Cursor::setCurrentFont()
2205 CursorSlice const & cs = innerTextSlice();
2206 Paragraph const & par = cs.paragraph();
2207 pos_type cpit = cs.pit();
2208 pos_type cpos = cs.pos();
2209 Text const & ctext = *cs.text();
2210 TextMetrics const & tm = bv().textMetrics(&ctext);
2212 // are we behind previous char in fact? -> go to that char
2213 if (cpos > 0 && boundary())
2216 // find position to take the font from
2218 // paragraph end? -> font of last char
2219 if (cpos == lastpos())
2221 // on space? -> look at the words in front of space
2222 else if (cpos > 0 && par.isSeparator(cpos)) {
2223 // abc| def -> font of c
2224 // abc |[WERBEH], i.e. boundary==true -> font of c
2225 // abc [WERBEH]| def, font of the space
2226 if (!tm.isRTLBoundary(cpit, cpos))
2232 BufferParams const & bufparams = buffer()->params();
2233 current_font = par.getFontSettings(bufparams, cpos);
2234 real_current_font = tm.displayFont(cpit, cpos);
2236 // special case for paragraph end
2237 if (cs.pos() == lastpos()
2238 && tm.isRTLBoundary(cpit, cs.pos())
2240 Language const * lang = par.getParLanguage(bufparams);
2241 current_font.setLanguage(lang);
2242 current_font.fontInfo().setNumber(FONT_OFF);
2243 real_current_font.setLanguage(lang);
2244 real_current_font.fontInfo().setNumber(FONT_OFF);
2249 bool Cursor::textUndo()
2251 DocIterator dit = *this;
2252 // Undo::textUndo() will modify dit.
2253 if (!buffer()->undo().textUndo(dit))
2263 bool Cursor::textRedo()
2265 DocIterator dit = *this;
2266 // Undo::textRedo() will modify dit.
2267 if (!buffer()->undo().textRedo(dit))
2277 void Cursor::finishUndo() const
2279 buffer()->undo().finishUndo();
2283 void Cursor::beginUndoGroup() const
2285 buffer()->undo().beginUndoGroup();
2289 void Cursor::endUndoGroup() const
2291 buffer()->undo().endUndoGroup();
2295 void Cursor::recordUndo(UndoKind kind, pit_type from, pit_type to) const
2297 buffer()->undo().recordUndo(*this, kind, from, to);
2301 void Cursor::recordUndo(UndoKind kind, pit_type from) const
2303 buffer()->undo().recordUndo(*this, kind, from);
2307 void Cursor::recordUndo(UndoKind kind) const
2309 buffer()->undo().recordUndo(*this, kind);
2313 void Cursor::recordUndoInset(UndoKind kind) const
2315 buffer()->undo().recordUndoInset(*this, kind);
2319 void Cursor::recordUndoFullDocument() const
2321 buffer()->undo().recordUndoFullDocument(*this);
2325 void Cursor::recordUndoSelection() const
2328 if (cap::multipleCellsSelected(*this))
2333 buffer()->undo().recordUndo(*this, ATOMIC_UNDO,
2334 selBegin().pit(), selEnd().pit());
2339 void Cursor::checkBufferStructure()
2341 Buffer const * master = buffer()->masterBuffer();
2342 master->tocBackend().updateItem(*this);
2343 if (master != buffer() && !master->hasGuiDelegate())
2344 // In case the master has no gui associated with it,
2345 // the TocItem is not updated (part of bug 5699).
2346 buffer()->tocBackend().updateItem(*this);