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.
18 #include "BufferParams.h"
19 #include "BufferView.h"
20 #include "CoordCache.h"
22 #include "CutAndPaste.h"
23 #include "DispatchResult.h"
27 #include "FuncRequest.h"
30 #include "LyXAction.h"
32 #include "Paragraph.h"
33 #include "ParIterator.h"
35 #include "texstream.h"
37 #include "TextMetrics.h"
38 #include "TocBackend.h"
40 #include "support/debug.h"
41 #include "support/docstream.h"
42 #include "support/ExceptionMessage.h"
43 #include "support/gettext.h"
44 #include "support/lassert.h"
46 #include "insets/InsetTabular.h"
47 #include "insets/InsetText.h"
49 #include "mathed/InsetMath.h"
50 #include "mathed/InsetMathBrace.h"
51 #include "mathed/InsetMathEnsureMath.h"
52 #include "mathed/InsetMathScript.h"
53 #include "mathed/MacroTable.h"
54 #include "mathed/MathData.h"
55 #include "mathed/MathFactory.h"
56 #include "mathed/InsetMathMacro.h"
69 // Find position closest to (x, y) in cell given by iter.
70 // Used only in mathed
71 DocIterator bruteFind(Cursor const & c, int x, int y)
73 double best_dist = numeric_limits<double>::max();
80 et.pos() = et.lastpos();
81 for (size_t i = 0;; ++i) {
84 Inset const * inset = &it.inset();
85 CoordCache::Insets const & insetCache = c.bv().coordCache().getInsets();
87 // FIXME: in the case where the inset is not in the cache, this
88 // means that no part of it is visible on screen. In this case
89 // we don't do elaborate search and we just return the forwarded
90 // DocIterator at its beginning.
91 if (!insetCache.has(inset)) {
96 Point const o = insetCache.xy(inset);
97 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
98 // Convert to absolute
101 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
102 // '<=' in order to take the last possible position
103 // this is important for clicking behind \sum in e.g. '\sum_i a'
104 LYXERR(Debug::DEBUG, "i: " << i << " d: " << d
105 << " best: " << best_dist);
106 if (d <= best_dist) {
121 CursorData::CursorData()
122 : DocIterator(), anchor_(),
123 selection_(false), mark_(false), word_selection_(false),
124 current_font(inherit_font),
125 autocorrect_(false), macromode_(false)
129 CursorData::CursorData(Buffer * buffer)
130 : DocIterator(buffer), anchor_(),
131 selection_(false), mark_(false), word_selection_(false),
132 current_font(inherit_font),
133 autocorrect_(false), macromode_(false)
137 CursorData::CursorData(DocIterator const & dit)
138 : DocIterator(dit), anchor_(),
139 selection_(false), mark_(false), word_selection_(false),
140 current_font(inherit_font),
141 autocorrect_(false), macromode_(false)
147 ostream & operator<<(ostream & os, CursorData const & cur)
149 os << "\n cursor: | anchor:\n";
150 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
151 os << " " << cur[i] << " | ";
152 if (i < cur.anchor_.depth())
153 os << cur.anchor_[i];
155 os << "-------------------------------";
158 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
159 os << "------------------------------- | " << cur.anchor_[i] << "\n";
161 os << " selection: " << cur.selection_
162 // << " x_target: " << cur.x_target_
163 << " boundary: " << cur.boundary() << endl;
168 LyXErr & operator<<(LyXErr & os, CursorData const & cur)
175 // be careful: this is called from the bv's constructor, too, so
176 // bv functions are not yet available!
177 Cursor::Cursor(BufferView & bv)
178 : CursorData(&bv.buffer()), bv_(&bv),
179 x_target_(-1), textTargetOffset_(0),
180 beforeDispatchPosX_(0), beforeDispatchPosY_(0)
187 push_back(CursorSlice(buffer()->inset()));
188 anchor_ = doc_iterator_begin(buffer());
190 new_word_ = doc_iterator_begin(buffer());
198 void Cursor::setCursor(DocIterator const & cur)
200 DocIterator::operator=(cur);
204 void Cursor::setCursorSelectionTo(DocIterator dit)
208 while (i < dit.depth() && i < anchor_.depth() && dit[i] == anchor_[i])
210 if (i != dit.depth()) {
211 // otherwise the cursor is already normal
212 if (i == anchor_.depth())
213 // dit is a proper extension of the anchor_
215 else if (i + 1 < dit.depth()) {
216 // one has dit[i] != anchor_[i] but either dit[i-1] == anchor_[i-1]
217 // or i == 0. Remove excess.
219 if (dit[i] > anchor_[i])
220 // place dit after the inset it was in
229 void Cursor::setCursorToAnchor()
232 DocIterator normal = anchor_;
233 while (depth() < normal.depth())
235 if (depth() < anchor_.depth() && top() <= anchor_[depth() - 1])
242 void Cursor::setCursorData(CursorData const & data)
244 CursorData::operator=(data);
248 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
252 // Try to fix cursor in case it is broken.
255 // Is this a function that acts on inset at point?
256 Inset * inset = cur.nextInset();
257 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
258 && inset && inset->getStatus(cur, cmd, status))
261 // This is, of course, a mess. Better create a new doc iterator and use
262 // this in Inset::getStatus. This might require an additional
263 // BufferView * arg, though (which should be avoided)
264 //Cursor safe = *this;
266 for ( ; cur.depth(); cur.pop()) {
267 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
268 // LASSERT: Is it safe to continue here, or should we return?
269 LASSERT(cur.idx() <= cur.lastidx(), /**/);
270 LASSERT(cur.pit() <= cur.lastpit(), /**/);
271 LASSERT(cur.pos() <= cur.lastpos(), /**/);
273 // The inset's getStatus() will return 'true' if it made
274 // a definitive decision on whether it want to handle the
275 // request or not. The result of this decision is put into
276 // the 'status' parameter.
277 if (cur.inset().getStatus(cur, cmd, status)) {
286 void Cursor::saveBeforeDispatchPosXY()
288 getPos(beforeDispatchPosX_, beforeDispatchPosY_);
292 void Cursor::dispatch(FuncRequest const & cmd0)
294 LYXERR(Debug::ACTION, "Cursor::dispatch: cmd: " << cmd0 << '\n' << *this);
299 FuncRequest cmd = cmd0;
302 disp_ = DispatchResult();
306 // Is this a function that acts on inset at point?
307 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
309 disp_.dispatched(true);
310 disp_.screenUpdate(Update::FitCursor | Update::Force);
311 FuncRequest tmpcmd = cmd;
312 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
313 << cmd0 << endl << *this);
314 nextInset()->dispatch(*this, tmpcmd);
315 if (disp_.dispatched()) {
321 // store some values to be used inside of the handlers
322 beforeDispatchCursor_ = *this;
323 for (; depth(); pop(), boundary(false)) {
324 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
325 << cmd0 << endl << *this);
327 // In any of these cases, the cursor is invalid, and we should
328 // try to save this document rather than crash.
329 LBUFERR(pos() <= lastpos());
330 LBUFERR(idx() <= lastidx());
331 LBUFERR(pit() <= lastpit());
333 // The common case is 'LFUN handled, need update', so make the
334 // LFUN handler's life easier by assuming this as default value.
335 // The handler can reset the update and val flags if necessary.
336 disp_.screenUpdate(Update::FitCursor | Update::Force);
337 disp_.dispatched(true);
338 inset().dispatch(*this, cmd);
339 if (disp_.dispatched())
343 // it completely to get a 'bomb early' behaviour in case this
344 // object will be used again.
345 if (!disp_.dispatched()) {
346 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
347 // We might have invalidated the cursor when removing an empty
348 // paragraph while the cursor could not be moved out the inset
349 // while we initially thought we could. This might happen when
350 // a multiline inset becomes an inline inset when the second
351 // paragraph is removed.
352 if (safe.pit() > safe.lastpit()) {
353 safe.pit() = safe.lastpit();
354 safe.pos() = safe.lastpos();
357 disp_.screenUpdate(Update::None);
358 disp_.dispatched(false);
360 // restore the previous one because nested Cursor::dispatch calls
361 // are possible which would change it
362 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
366 // NOTE: The code below has been copied to BufferView::dispatch.
367 // If you need to modify this, please update the other one too.
369 // notify insets we just left
371 old.beginUndoGroup();
373 bool badcursor = notifyCursorLeavesOrEnters(old, *this);
376 bv().resetInlineCompletionPos();
383 DispatchResult const & Cursor::result() const
389 BufferView & Cursor::bv() const
398 LBUFERR(depth() >= 1);
403 void Cursor::push(Inset & p)
405 push_back(CursorSlice(p));
406 p.setBuffer(*buffer());
410 void Cursor::pushBackward(Inset & p)
412 LASSERT(!empty(), return);
413 //lyxerr << "Entering inset " << t << " front" << endl;
419 bool Cursor::popBackward()
421 LASSERT(!empty(), return false);
429 bool Cursor::popForward()
431 LASSERT(!empty(), return false);
432 //lyxerr << "Leaving inset from in back" << endl;
433 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
437 pos() += lastpos() - lp + 1;
442 int Cursor::currentMode()
444 LASSERT(!empty(), return Inset::UNDECIDED_MODE);
445 for (int i = depth() - 1; i >= 0; --i) {
446 int res = operator[](i).inset().currentMode();
447 bool locked_mode = operator[](i).inset().lockedMode();
448 // Also return UNDECIDED_MODE when the mode is locked,
449 // as in this case it is treated the same as TEXT_MODE
450 if (res != Inset::UNDECIDED_MODE || locked_mode)
453 return Inset::TEXT_MODE;
457 bool Cursor::inCoordCache() const
459 // the root inset is not in cache, but we do not need it.
462 CoordCache::Insets const & icache = bv_->coordCache().getInsets();
463 for (size_t i = 1 ; i < depth() ; ++i)
464 if (!icache.has(&(*this)[i].inset()))
470 void Cursor::getPos(int & x, int & y) const
472 Point p = bv().getPos(*this);
478 Row const & Cursor::textRow() const
480 CursorSlice const & cs = innerTextSlice();
481 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
482 return pm.getRow(pos(), boundary());
486 void Cursor::resetAnchor()
489 checkNewWordPosition();
493 void Cursor::markNewWordPosition()
495 if (lyxrc.spellcheck_continuously && inTexted() && new_word_.empty()) {
496 FontSpan nw = locateWord(WHOLE_WORD);
497 if (nw.size() == 1) {
498 LYXERR(Debug::DEBUG, "start new word: "
500 << " pos: " << nw.first);
507 void Cursor::clearNewWordPosition()
509 if (!new_word_.empty()) {
510 LYXERR(Debug::DEBUG, "clear new word: "
512 << " pos: " << pos());
518 void Cursor::checkNewWordPosition()
520 if (!lyxrc.spellcheck_continuously || new_word_.empty())
523 clearNewWordPosition();
525 // forget the position of the current new word if
526 // 1) the paragraph changes or
527 // 2) the count of nested insets changes or
528 // 3) the cursor pos is out of paragraph bound
529 if (pit() != new_word_.pit() ||
530 depth() != new_word_.depth() ||
531 new_word_.pos() > new_word_.lastpos()) {
532 clearNewWordPosition();
533 } else if (new_word_.fixIfBroken())
534 // 4) or the remembered position was "broken"
535 clearNewWordPosition();
537 FontSpan nw = locateWord(WHOLE_WORD);
539 FontSpan ow = new_word_.locateWord(WHOLE_WORD);
540 if (nw.intersect(ow).empty())
541 clearNewWordPosition();
543 LYXERR(Debug::DEBUG, "new word: "
545 << " pos: " << nw.first << ".." << nw.last);
547 clearNewWordPosition();
554 bool Cursor::posVisRight(bool skip_inset)
556 Cursor new_cur = *this; // where we will move to
557 pos_type left_pos; // position visually left of current cursor
558 pos_type right_pos; // position visually right of current cursor
560 getSurroundingPos(left_pos, right_pos);
562 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
564 // Are we at an inset?
565 new_cur.pos() = right_pos;
566 new_cur.boundary(false);
568 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
569 // we actually move the cursor at the end of this
570 // function, for now we just keep track of the new
571 // position in new_cur...
572 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
575 // Are we already at rightmost pos in row?
576 else if (text()->empty() || right_pos == -1) {
579 if (!new_cur.posVisToNewRow(false)) {
580 LYXERR(Debug::RTL, "not moving!");
584 // we actually move the cursor at the end of this
585 // function, for now just keep track of the new
586 // position in new_cur...
587 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
588 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
591 // normal movement to the right
594 // Recall, if the cursor is at position 'x', that
595 // means *before* the character at position 'x'. In
596 // RTL, "before" means "to the right of", in LTR, "to
597 // the left of". So currently our situation is this:
598 // the position to our right is 'right_pos' (i.e.,
599 // we're currently to the left of 'right_pos'). In
600 // order to move to the right, it depends whether or
601 // not the character at 'right_pos' is RTL.
602 bool const new_pos_is_RTL = paragraph().getFontSettings(
603 buffer()->params(), right_pos).isVisibleRightToLeft();
604 // If the character at 'right_pos' *is* LTR, then in
605 // order to move to the right of it, we need to be
606 // *after* 'right_pos', i.e., move to position
608 if (!new_pos_is_RTL) {
609 new_cur.pos() = right_pos + 1;
610 // set the boundary to true in two situations:
612 // 1. if new_pos is now lastpos, and we're in
613 // an RTL paragraph (this means that we're
614 // moving right to the end of an LTR chunk
615 // which is at the end of an RTL paragraph);
616 (new_cur.pos() == lastpos()
617 && paragraph().isRTL(buffer()->params()))
618 // 2. if the position *after* right_pos is RTL
619 // (we want to be *after* right_pos, not
620 // before right_pos + 1!)
621 || paragraph().getFontSettings(buffer()->params(),
622 new_cur.pos()).isVisibleRightToLeft()
624 new_cur.boundary(true);
625 else // set the boundary to false
626 new_cur.boundary(false);
628 // Otherwise (if the character at position 'right_pos'
629 // is RTL), then moving to the right of it is as easy
630 // as setting the new position to 'right_pos'.
632 new_cur.pos() = right_pos;
633 new_cur.boundary(false);
638 bool const moved = new_cur != *this || new_cur.boundary() != boundary();
641 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
642 << (new_cur.boundary() ? " (boundary)" : ""));
650 bool Cursor::posVisLeft(bool skip_inset)
652 Cursor new_cur = *this; // where we will move to
653 pos_type left_pos; // position visually left of current cursor
654 pos_type right_pos; // position visually right of current cursor
656 getSurroundingPos(left_pos, right_pos);
658 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
660 // Are we at an inset?
661 new_cur.pos() = left_pos;
662 new_cur.boundary(false);
664 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
665 // we actually move the cursor at the end of this
666 // function, for now we just keep track of the new
667 // position in new_cur...
668 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
671 // Are we already at leftmost pos in row?
672 else if (text()->empty() || left_pos == -1) {
675 if (!new_cur.posVisToNewRow(true)) {
676 LYXERR(Debug::RTL, "not moving!");
680 // we actually move the cursor at the end of this
681 // function, for now just keep track of the new
682 // position in new_cur...
683 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
684 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
687 // normal movement to the left
690 // Recall, if the cursor is at position 'x', that
691 // means *before* the character at position 'x'. In
692 // RTL, "before" means "to the right of", in LTR, "to
693 // the left of". So currently our situation is this:
694 // the position to our left is 'left_pos' (i.e., we're
695 // currently to the right of 'left_pos'). In order to
696 // move to the left, it depends whether or not the
697 // character at 'left_pos' is RTL.
698 bool const new_pos_is_RTL = paragraph().getFontSettings(
699 buffer()->params(), left_pos).isVisibleRightToLeft();
700 // If the character at 'left_pos' *is* RTL, then in
701 // order to move to the left of it, we need to be
702 // *after* 'left_pos', i.e., move to position
704 if (new_pos_is_RTL) {
705 new_cur.pos() = left_pos + 1;
706 // set the boundary to true in two situations:
708 // 1. if new_pos is now lastpos and we're in
709 // an LTR paragraph (this means that we're
710 // moving left to the end of an RTL chunk
711 // which is at the end of an LTR paragraph);
712 (new_cur.pos() == lastpos()
713 && !paragraph().isRTL(buffer()->params()))
714 // 2. if the position *after* left_pos is not
715 // RTL (we want to be *after* left_pos, not
716 // before left_pos + 1!)
717 || !paragraph().getFontSettings(buffer()->params(),
718 new_cur.pos()).isVisibleRightToLeft()
720 new_cur.boundary(true);
721 else // set the boundary to false
722 new_cur.boundary(false);
724 // Otherwise (if the character at position 'left_pos'
725 // is LTR), then moving to the left of it is as easy
726 // as setting the new position to 'left_pos'.
728 new_cur.pos() = left_pos;
729 new_cur.boundary(false);
734 bool const moved = new_cur != *this || new_cur.boundary() != boundary();
737 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
738 << (new_cur.boundary() ? " (boundary)" : ""));
748 // Return true on success
749 bool findNonVirtual(Row const & row, Row::const_iterator & cit, bool onleft)
752 while (cit != row.begin() && cit->isVirtual())
755 while (cit != row.end() && cit->isVirtual())
758 return cit != row.end() && !cit->isVirtual();
763 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos) const
765 // by default, we know nothing.
769 Row const & row = textRow();
771 Row::const_iterator cit = row.findElement(pos(), boundary(), dummy);
772 // Handle the case of empty row
773 if (cit == row.end()) {
775 right_pos = row.pos();
777 left_pos = row.pos() - 1;
781 // skip virtual elements and exit if no non-virtual one exists
782 if (!findNonVirtual(row, cit, !cit->isRTL()))
785 // if the position is at the left side of the element, we have to
786 // look at the previous element
787 if (pos() == cit->left_pos()) {
788 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
789 << "), AT LEFT of *cit=" << *cit);
790 // this one is easy (see common case below)
791 right_pos = pos() - (cit->isRTL() ? 1 : 0);
792 // at the left of the row
793 if (cit == row.begin())
796 if (!findNonVirtual(row, cit, true))
798 // [...[ is the row element, | is cursor position (! with boundary)
799 // [ 1 2 [ is a ltr row element with pos=1 and endpos=3
800 // ] 2 1] is an rtl row element with pos=1 and endpos=3
801 // [ 1 2 [ [|3 4 [ => (2, 3)
802 // or [ 1 2 [ ]!4 3 ] => (2, 4)
803 // or ] 2 1 ] [|3 4 [ => (1, 3)
804 // or ] 4 3 ] ]!2 1 ] => (3, 2)
805 left_pos = cit->right_pos() - (cit->isRTL() ? 0 : 1);
806 // happens with consecutive row of same direction
807 if (left_pos == right_pos) {
808 left_pos += cit->isRTL() ? 1 : -1;
811 // same code but with the element at the right
812 else if (pos() == cit->right_pos()) {
813 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
814 << "), AT RIGHT of *cit=" << *cit);
815 // this one is easy (see common case below)
816 left_pos = pos() - (cit->isRTL() ? 0 : 1);
817 // at the right of the row
818 if (cit + 1 == row.end())
821 if (!findNonVirtual(row, cit, false))
823 // [ 1 2![ [ 3 4 [ => (2, 3)
824 // or [ 1 2![ ] 4 3 ] => (2, 4)
825 // or ] 2 1|] [ 3 4 [ => (1, 3)
826 // or ] 4 3|] ] 2 1 ] => (3, 2)
827 right_pos = cit->left_pos() - (cit->isRTL() ? 1 : 0);
828 // happens with consecutive row of same direction
829 if (right_pos == left_pos)
830 right_pos += cit->isRTL() ? -1 : 1;
832 // common case: both positions are inside the row element
834 // [ 1 2|3 [ => (2, 3)
835 // or ] 3|2 1 ] => (3, 2)
836 left_pos = pos() - (cit->isRTL() ? 0 : 1);
837 right_pos = pos() - (cit->isRTL() ? 1 : 0);
840 // Note that debug message does not catch all early returns above
841 LYXERR(Debug::RTL,"getSurroundingPos(" << pos() << (boundary() ? "b" : "")
842 << ") => (" << left_pos << ", " << right_pos <<")");
846 bool Cursor::posVisToNewRow(bool movingLeft)
848 Row const & row = textRow();
849 bool par_is_LTR = !row.isRTL();
851 // Inside a table, determining whether to move to the next or
852 // previous row should be done based on the table's direction.
853 if (inset().asInsetTabular()) {
854 par_is_LTR = !inset().asInsetTabular()->isRightToLeft(*this);
855 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
858 // if moving left in an LTR paragraph or moving right in an
859 // RTL one, move to previous row
860 if (par_is_LTR == movingLeft) {
861 if (row.pos() == 0) { // we're at first row in paragraph
862 if (pit() == 0) // no previous paragraph! don't move
864 // move to last pos in previous par
868 } else { // move to previous row in this par
869 pos() = row.pos() - 1; // this is guaranteed to be in previous row
873 // if moving left in an RTL paragraph or moving right in an
874 // LTR one, move to next row
876 if (row.endpos() == lastpos()) { // we're at last row in paragraph
877 if (pit() == lastpit()) // last paragraph! don't move
879 // move to first row in next par
883 } else { // move to next row in this par
884 pos() = row.endpos();
889 // make sure we're at left-/right-most pos in new row
890 posVisToRowExtremity(!movingLeft);
896 void Cursor::posVisToRowExtremity(bool left)
898 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
899 << (boundary() ? 1 : 0));
901 TextMetrics const & tm = bv_->textMetrics(text());
902 // Looking for extremities is like clicking on the left or the
904 int x = tm.origin().x_ + (left ? 0 : textRow().width());
906 pos() = tm.getPosNearX(textRow(), x, b);
909 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
910 << (boundary() ? 1 : 0));
914 bool Cursor::reverseDirectionNeeded() const
917 * We determine the directions based on the direction of the
918 * bottom() --- i.e., outermost --- paragraph, because that is
919 * the only way to achieve consistency of the arrow's movements
920 * within a paragraph, and thus avoid situations in which the
923 return bottom().paragraph().isRTL(bv().buffer().params());
927 CursorSlice Cursor::normalAnchor() const
931 // LASSERT: There have been several bugs around this code, that seem
932 // to involve failures to reset the anchor. We can at least not crash
933 // in release mode by resetting it ourselves.
934 if (anchor_.depth() < depth()) {
935 LYXERR0("Cursor is deeper than anchor. PLEASE REPORT.\nCursor is"
937 const_cast<DocIterator &>(anchor_) = *this;
940 CursorSlice normal = anchor_[depth() - 1];
941 if (depth() < anchor_.depth() && top() <= normal) {
942 // anchor is behind cursor -> move anchor behind the inset
949 CursorSlice Cursor::selBegin() const
953 return normalAnchor() < top() ? normalAnchor() : top();
957 CursorSlice Cursor::selEnd() const
961 return normalAnchor() > top() ? normalAnchor() : top();
965 DocIterator Cursor::selectionBegin() const
971 // FIXME: This is a work-around for the problem that
972 // CursorSlice doesn't keep track of the boundary.
973 if (normalAnchor() == top())
974 di = anchor_.boundary() > boundary() ? anchor_ : *this;
976 di = normalAnchor() < top() ? anchor_ : *this;
982 DocIterator Cursor::selectionEnd() const
988 // FIXME: This is a work-around for the problem that
989 // CursorSlice doesn't keep track of the boundary.
990 if (normalAnchor() == top())
991 di = anchor_.boundary() < boundary() ? anchor_ : *this;
993 di = normalAnchor() > top() ? anchor_ : *this;
995 if (di.depth() > depth()) {
1003 void Cursor::setSelection()
1006 if (idx() == normalAnchor().idx() &&
1007 pit() == normalAnchor().pit() &&
1008 pos() == normalAnchor().pos())
1013 void Cursor::setSelection(DocIterator const & where, int n)
1022 void Cursor::clearSelection()
1025 setWordSelection(false);
1031 void Cursor::setTargetX(int x)
1034 textTargetOffset_ = 0;
1038 int Cursor::x_target() const
1044 void Cursor::clearTargetX()
1047 textTargetOffset_ = 0;
1051 void Cursor::updateTextTargetOffset()
1056 textTargetOffset_ = x - x_target_;
1060 void Cursor::info(odocstream & os, bool devel_mode) const
1062 for (int i = 1, n = depth(); i < n; ++i) {
1063 operator[](i).inset().infoize(os);
1067 Inset const * inset = prevInset();
1068 // prevInset() can return 0 in certain case.
1070 prevInset()->infoize2(os);
1073 InsetMath * math = inset().asInsetMath();
1075 os << _(", Inset: ") << math->id();
1076 os << _(", Cell: ") << idx();
1077 os << _(", Position: ") << pos();
1083 bool Cursor::selHandle(bool sel)
1085 //lyxerr << "Cursor::selHandle" << endl;
1088 if (sel == selection())
1092 cap::saveSelection(*this);
1101 ///////////////////////////////////////////////////////////////////
1104 // The part below is the non-integrated rest of the original math
1105 // cursor. This should be either generalized for texted or moved
1106 // back to mathed (in most cases to InsetMathNest).
1108 ///////////////////////////////////////////////////////////////////
1110 #include "mathed/InsetMathChar.h"
1111 #include "mathed/InsetMathGrid.h"
1112 #include "mathed/InsetMathScript.h"
1113 #include "mathed/InsetMathUnknown.h"
1114 #include "mathed/MathFactory.h"
1115 #include "mathed/MathStream.h"
1116 #include "mathed/MathSupport.h"
1121 bool Cursor::isInside(Inset const * p) const
1123 for (size_t i = 0; i != depth(); ++i)
1124 if (&operator[](i).inset() == p)
1130 void Cursor::leaveInset(Inset const & inset)
1132 for (size_t i = 0; i != depth(); ++i) {
1133 if (&operator[](i).inset() == &inset) {
1141 bool Cursor::openable(MathAtom const & t) const
1152 // we can't move into anything new during selection
1153 if (depth() >= anchor_.depth())
1155 if (t.nucleus() != &anchor_[depth()].inset())
1162 void Cursor::setScreenPos(int x, int /*y*/)
1165 //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
1170 void Cursor::plainErase()
1172 cell().erase(pos());
1176 void Cursor::markInsert()
1178 insert(char_type(0));
1182 void Cursor::markErase()
1184 cell().erase(pos());
1188 void Cursor::plainInsert(MathAtom const & t)
1190 cell().insert(pos(), t);
1192 inset().setBuffer(bv_->buffer());
1194 checkBufferStructure();
1198 void Cursor::insert(docstring const & str)
1200 for (char_type c : str)
1205 void Cursor::insert(char_type c)
1207 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1208 LASSERT(!empty(), return);
1210 cap::selClearOrDel(*this);
1211 insert(new InsetMathChar(c));
1213 text()->insertChar(*this, c);
1218 void Cursor::insert(MathAtom const & t)
1220 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1222 cap::selClearOrDel(*this);
1227 void Cursor::insert(Inset * inset0)
1229 LASSERT(inset0, return);
1231 insert(MathAtom(inset0->asInsetMath()));
1233 text()->insertInset(*this, inset0);
1234 inset0->setBuffer(bv_->buffer());
1236 if (inset0->isLabeled())
1237 forceBufferUpdate();
1242 int Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1244 MathData ar(buffer());
1246 if (ar.size() == 1 && (enter || selection()))
1254 void Cursor::niceInsert(MathAtom const & t)
1257 docstring const safe = cap::grabAndEraseSelection(*this);
1259 // If possible, enter the new inset and move the contents of the selection
1260 if (t->isActive()) {
1262 // be careful here: don't use 'pushBackward(t)' as this we need to
1263 // push the clone, not the original
1264 pushBackward(*nextInset());
1265 // We may not use niceInsert here (recursion)
1266 MathData ar(buffer());
1269 } else if (t->asMacro() && !safe.empty()) {
1270 MathData ar(buffer());
1272 docstring const name = t->asMacro()->name();
1273 MacroData const * data = buffer()->getMacro(name);
1274 if (data && data->numargs() - data->optionals() > 0) {
1275 plainInsert(MathAtom(new InsetMathBrace(ar)));
1282 void Cursor::insert(MathData const & ar)
1286 cap::eraseSelection(*this);
1287 cell().insert(pos(), ar);
1289 // FIXME audit setBuffer calls
1290 inset().setBuffer(bv_->buffer());
1294 bool Cursor::backspace(bool const force)
1297 cap::eraseSelection(*this);
1302 // If empty cell, and not part of a big cell
1303 if (lastpos() == 0 && inset().nargs() == 1) {
1305 // Directly delete empty cell: [|[]] => [|]
1311 // [|], can not delete from inside
1322 if (inMacroMode()) {
1323 InsetMathUnknown * p = activeMacro();
1324 if (p->name().size() > 1) {
1325 p->setName(p->name().substr(0, p->name().size() - 1));
1330 if (pos() != 0 && !force && prevAtom()->confirmDeletion()) {
1331 // let's require two backspaces for 'big stuff' and
1332 // highlight on the first
1344 bool Cursor::erase(bool const force)
1350 cap::eraseSelection(*this);
1354 // delete empty cells if possible
1355 if (pos() == lastpos() && inset().idxDelete(idx()))
1358 // special behaviour when in last position of cell
1359 if (pos() == lastpos()) {
1360 bool one_cell = inset().nargs() == 1;
1361 if (one_cell && lastpos() == 0) {
1363 // Directly delete empty cell: [|[]] => [|]
1369 // [|], can not delete from inside
1374 inset().idxGlue(idx());
1378 // 'clever' UI hack: only erase large items if previously slected
1379 if (pos() != lastpos() && !force && nextAtom()->confirmDeletion()) {
1394 DocIterator save = *this;
1395 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1396 this->dispatch(cmd);
1397 if (disp_.dispatched())
1407 DocIterator save = *this;
1408 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1409 this->dispatch(cmd);
1410 if (disp_.dispatched())
1417 bool Cursor::macroModeClose()
1421 InsetMathUnknown * p = activeMacro();
1423 MathData selection(buffer());
1424 asArray(p->selection(), selection);
1425 docstring const s = p->name();
1427 cell().erase(pos());
1429 // do nothing if the macro name is empty
1433 // trigger updates of macros, at least, if no full
1434 // updates take place anyway
1435 screenUpdateFlags(Update::Force);
1437 docstring const name = s.substr(1);
1438 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1439 if (in && in->interpretString(*this, s))
1441 bool const user_macro = buffer()->getMacro(name, *this, false);
1442 MathAtom atom = user_macro ? MathAtom(new InsetMathMacro(buffer(), name))
1443 : createInsetMath(name, buffer());
1445 // try to put argument into macro, if we just inserted a macro
1446 bool macroArg = false;
1447 InsetMathMacro * atomAsMacro = atom.nucleus()->asMacro();
1449 // macros here are still unfolded (in init mode in fact). So
1450 // we have to resolve the macro here manually and check its arity
1451 // to put the selection behind it if arity > 0.
1452 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1453 if (!selection.empty() && data && data->numargs() - data->optionals() > 0) {
1455 atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1457 // non-greedy case. Do not touch the arguments behind
1458 atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1461 // insert remembered selection into first argument of a non-macro
1462 else if (atom.nucleus()->nargs() > 0)
1463 atom.nucleus()->cell(0).append(selection);
1465 MathWordList const & words = mathedWordList();
1466 MathWordList::const_iterator it = words.find(name);
1467 bool keep_mathmode = user_macro
1468 || (it != words.end() && (it->second.inset == "font"
1469 || it->second.inset == "oldfont"
1470 || it->second.inset == "mbox"));
1471 bool ert_macro = !user_macro && it == words.end() && atomAsMacro;
1473 if (in && in->currentMode() == Inset::TEXT_MODE
1474 && atom.nucleus()->currentMode() == Inset::MATH_MODE
1475 && name != from_ascii("ensuremath") && !ert_macro) {
1476 MathAtom at(new InsetMathEnsureMath(buffer()));
1477 at.nucleus()->cell(0).push_back(atom);
1480 } else if (in && in->currentMode() == Inset::MATH_MODE
1481 && atom.nucleus()->currentMode() == Inset::TEXT_MODE
1482 && !keep_mathmode) {
1483 MathAtom at = createInsetMath("text", buffer());
1484 at.nucleus()->cell(0).push_back(atom);
1490 // finally put the macro argument behind, if needed
1492 if (selection.size() > 1 || selection[0]->asScriptInset())
1493 plainInsert(MathAtom(new InsetMathBrace(selection)));
1502 docstring Cursor::macroName()
1504 return inMacroMode() ? activeMacro()->name() : docstring();
1508 void Cursor::handleNest(MathAtom const & a, int c)
1510 //lyxerr << "Cursor::handleNest: " << c << endl;
1512 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1515 pushBackward(*nextInset());
1519 int Cursor::targetX() const
1521 if (x_target() != -1)
1530 int Cursor::textTargetOffset() const
1532 return textTargetOffset_;
1536 void Cursor::setTargetX()
1545 bool Cursor::inMacroMode() const
1549 if (pos() == 0 || cell().empty())
1551 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1552 return p && !p->final();
1556 InsetMathUnknown * Cursor::activeMacro()
1558 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1562 InsetMathUnknown const * Cursor::activeMacro() const
1564 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1568 void Cursor::pullArg()
1571 MathData ar = cell();
1572 if (popBackward() && inMathed()) {
1574 cell().insert(pos(), ar);
1577 //formula()->mutateToText();
1582 void Cursor::touch()
1586 DocIterator::const_iterator it = begin();
1587 DocIterator::const_iterator et = end();
1588 for ( ; it != et; ++it)
1594 void Cursor::normalize()
1596 if (idx() > lastidx()) {
1597 lyxerr << "this should not really happen - 1: "
1598 << idx() << ' ' << nargs()
1599 << " in: " << &inset() << endl;
1603 if (pos() > lastpos()) {
1604 lyxerr << "this should not really happen - 2: "
1605 << pos() << ' ' << lastpos() << " in idx: " << idx()
1607 odocstringstream os;
1608 otexrowstream ots(os);
1609 WriteStream wi(ots, false, true, WriteStream::wsDefault);
1610 inset().asInsetMath()->write(wi);
1611 lyxerr << to_utf8(os.str()) << endl;
1617 bool Cursor::upDownInMath(bool up)
1619 // Be warned: The 'logic' implemented in this function is highly
1620 // fragile. A distance of one pixel or a '<' vs '<=' _really
1621 // matters. So fiddle around with it only if you think you know
1622 // what you are doing!
1626 xo = beforeDispatchPosX_;
1628 // check if we had something else in mind, if not, this is the future
1630 if (x_target_ == -1)
1632 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1633 // In text mode inside the line (not left or right) possibly set a new target_x,
1634 // but only if we are somewhere else than the previous target-offset.
1636 // We want to keep the x-target on subsequent up/down movements
1637 // that cross beyond the end of short lines. Thus a special
1638 // handling when the cursor is at the end of line: Use the new
1639 // x-target only if the old one was before the end of line
1640 // or the old one was after the beginning of the line
1641 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
1645 left = pos() == textRow().endpos();
1646 right = pos() == textRow().pos();
1648 left = pos() == textRow().pos();
1649 right = pos() == textRow().endpos();
1651 if ((!left && !right) ||
1652 (left && !right && xo < x_target_) ||
1653 (!left && right && x_target_ < xo))
1660 // try neigbouring script insets
1662 if (inMathed() && !selection()) {
1665 InsetMathScript const * p = prevAtom()->asScriptInset();
1666 if (p && p->has(up)) {
1668 push(*const_cast<InsetMathScript*>(p));
1669 idx() = p->idxOfScript(up);
1672 // we went in the right direction? Otherwise don't jump into the script
1676 int oy = beforeDispatchPosY_;
1677 if ((!up && y <= oy) ||
1686 if (pos() != lastpos()) {
1687 InsetMathScript const * p = nextAtom()->asScriptInset();
1688 if (p && p->has(up)) {
1689 push(*const_cast<InsetMathScript*>(p));
1690 idx() = p->idxOfScript(up);
1693 // we went in the right direction? Otherwise don't jump into the script
1697 int oy = beforeDispatchPosY_;
1698 if ((!up && y <= oy) ||
1707 // try to find an inset that knows better then we,
1708 if (inset().idxUpDown(*this, up)) {
1709 //lyxerr << "idxUpDown triggered" << endl;
1710 // try to find best position within this inset
1712 setCursor(bruteFind(*this, xo, yo));
1716 // any improvement going just out of inset?
1717 if (popBackward() && inMathed()) {
1718 //lyxerr << "updown: popBackward succeeded" << endl;
1721 int yold = beforeDispatchPosY_;
1723 if (up ? ynew < yold : ynew > yold)
1727 // no success, we are probably at the document top or bottom
1733 InsetMath & Cursor::nextMath()
1735 return *nextAtom().nucleus();
1739 InsetMath & Cursor::prevMath()
1741 return *prevAtom().nucleus();
1745 bool Cursor::mathForward(bool word)
1747 LASSERT(inMathed(), return false);
1748 if (pos() < lastpos()) {
1750 // word: skip a group of insets of the form X*(B*|R*|P*) (greedy
1751 // match) where X is any math class, B is mathbin, R is mathrel, and
1752 // P is mathpunct. Make sure that the following remains true:
1753 // mathForward(true); mathBackward(true); mathForward(true)
1754 // is the same as mathForward(true) and
1755 // mathBackward(true); mathForward(true); mathBackward(true)
1756 // is the same as mathBackward(true).
1757 MathClass mc = nextMath().mathClass();
1760 while (pos() < lastpos() && mc == nextMath().mathClass());
1761 if (pos() < lastpos() &&
1762 ((mc = nextMath().mathClass()) == MC_BIN ||
1763 mc == MC_REL || mc == MC_PUNCT))
1766 while (pos() < lastpos() && mc == nextMath().mathClass());
1767 } else if (openable(nextAtom())) {
1768 // single step: try to enter the next inset
1769 pushBackward(nextMath());
1770 inset().idxFirst(*this);
1775 if (inset().idxForward(*this))
1777 // try to pop forwards --- but don't pop out of math! leave that to
1779 int s = depth() - 2;
1780 if (s >= 0 && operator[](s).inset().asInsetMath())
1781 return popForward();
1786 bool Cursor::mathBackward(bool word)
1788 LASSERT(inMathed(), return false);
1791 // word: skip a group of insets. See the comment in mathForward.
1792 MathClass mc = prevMath().mathClass();
1795 while (pos() > 0 && mc == prevMath().mathClass());
1796 if (pos() > 0 && (mc == MC_BIN || mc == MC_REL || mc == MC_PUNCT)) {
1797 mc = prevMath().mathClass();
1800 while (pos() > 0 && mc == prevMath().mathClass());
1802 } else if (openable(prevAtom())) {
1803 // single step: try to enter the preceding inset
1806 inset().idxLast(*this);
1811 if (inset().idxBackward(*this))
1813 // try to pop backwards --- but don't pop out of math! leave that to
1815 int s = depth() - 2;
1816 if (s >= 0 && operator[](s).inset().asInsetMath())
1817 return popBackward();
1822 bool Cursor::atFirstOrLastRow(bool up)
1824 TextMetrics const & tm = bv_->textMetrics(text());
1825 ParagraphMetrics const & pm = tm.parMetrics(pit());
1828 if (pos() && boundary())
1829 row = pm.pos2row(pos() - 1);
1831 row = pm.pos2row(pos());
1834 if (pit() == 0 && row == 0)
1837 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1838 row + 1 >= int(pm.rows().size()))
1845 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1847 LASSERT(text(), return false);
1853 xo = beforeDispatchPosX_;
1855 // update the targetX - this is here before the "return false"
1856 // to set a new target which can be used by InsetTexts above
1857 // if we cannot move up/down inside this inset anymore
1858 if (x_target_ == -1)
1860 else if (xo - textTargetOffset() != x_target() &&
1861 depth() == beforeDispatchCursor_.depth()) {
1862 // In text mode inside the line (not left or right)
1863 // possibly set a new target_x, but only if we are
1864 // somewhere else than the previous target-offset.
1866 // We want to keep the x-target on subsequent up/down
1867 // movements that cross beyond the end of short lines.
1868 // Thus a special handling when the cursor is at the
1869 // end of line: Use the new x-target only if the old
1870 // one was before the end of line or the old one was
1871 // after the beginning of the line
1872 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
1876 left = pos() == textRow().endpos();
1877 right = pos() == textRow().pos();
1879 left = pos() == textRow().pos();
1880 right = pos() == textRow().endpos();
1882 if ((!left && !right) ||
1883 (left && !right && xo < x_target_) ||
1884 (!left && right && x_target_ < xo))
1891 // first get the current line
1892 TextMetrics & tm = bv_->textMetrics(text());
1893 ParagraphMetrics const & pm = tm.parMetrics(pit());
1895 if (pos() && boundary())
1896 row = pm.pos2row(pos() - 1);
1898 row = pm.pos2row(pos());
1900 if (atFirstOrLastRow(up)) {
1901 // Is there a place for the cursor to go ? If yes, we
1902 // can execute the DEPM, otherwise we should keep the
1903 // paragraph to host the cursor.
1904 Cursor dummy = *this;
1905 bool valid_destination = false;
1906 for(; dummy.depth(); dummy.pop())
1907 if (!dummy.atFirstOrLastRow(up)) {
1908 valid_destination = true;
1912 // will a next dispatch follow and if there is a new
1913 // dispatch will it move the cursor out ?
1914 if (depth() > 1 && valid_destination) {
1915 // The cursor hasn't changed yet. This happens when
1916 // you e.g. move out of an inset. And to give the
1917 // DEPM the possibility of doing something we must
1918 // provide it with two different cursors. (Lgb, vfr)
1920 dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
1921 dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
1923 updateNeeded |= bv().checkDepm(dummy, *this);
1924 updateTextTargetOffset();
1926 forceBufferUpdate();
1931 // with and without selection are handled differently
1933 int yo = bv().getPos(*this).y_;
1935 // To next/previous row
1936 // FIXME: the y position is often guessed wrongly across styles and
1937 // insets, which leads to weird behaviour.
1939 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1941 tm.editXY(*this, xo, yo + textRow().descent() + 1);
1942 x_target_ = old.x_target_;
1945 // This happens when you move out of an inset.
1946 // And to give the DEPM the possibility of doing
1947 // something we must provide it with two different
1949 Cursor dummy = *this;
1952 if (bv().checkDepm(dummy, old)) {
1953 updateNeeded = true;
1954 // Make sure that cur gets back whatever happened to dummy (Lgb)
1957 if (inTexted() && pos() && paragraph().isEnvSeparator(pos() - 1))
1960 // if there is a selection, we stay out of any inset,
1961 // and just jump to the right position:
1967 } else if (pit() > 0) {
1969 TextMetrics & tm = bv_->textMetrics(text());
1970 if (!tm.contains(pit()))
1971 tm.newParMetricsUp();
1972 ParagraphMetrics const & pmcur = tm.parMetrics(pit());
1973 next_row = pmcur.rows().size() - 1;
1976 if (row + 1 < int(pm.rows().size())) {
1978 } else if (pit() + 1 < int(text()->paragraphs().size())) {
1980 TextMetrics & tm = bv_->textMetrics(text());
1981 if (!tm.contains(pit()))
1982 tm.newParMetricsDown();
1987 Row const & real_next_row = tm.parMetrics(pit()).rows()[next_row];
1989 top().pos() = tm.getPosNearX(real_next_row, xo, bound);
1991 // When selection==false, this is done by TextMetrics::editXY
1994 updateNeeded |= bv().checkDepm(*this, old);
1998 forceBufferUpdate();
1999 updateTextTargetOffset();
2004 void Cursor::handleFont(string const & font)
2006 LYXERR(Debug::DEBUG, font);
2010 safe = cap::grabAndEraseSelection(*this);
2015 if (lastpos() != 0) {
2016 // something left in the cell
2018 // cursor in first position
2020 } else if (pos() == lastpos()) {
2021 // cursor in last position
2024 // cursor in between. split cell
2025 MathData::iterator bt = cell().begin();
2026 MathAtom at = createInsetMath(from_utf8(font), buffer());
2027 at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
2028 cell().erase(bt, bt + pos());
2033 // nothing left in the cell
2042 void Cursor::message(docstring const & msg) const
2044 disp_.setMessage(msg);
2048 void Cursor::errorMessage(docstring const & msg) const
2050 disp_.setMessage(msg);
2051 disp_.setError(true);
2057 docstring parbreak(Cursor const * cur)
2059 odocstringstream os;
2061 // only add blank line if we're not in a ParbreakIsNewline situation
2062 if (!cur->inset().getLayout().parbreakIsNewline()
2063 && !cur->paragraph().layout().parbreak_is_newline)
2071 docstring Cursor::selectionAsString(bool with_label) const
2077 return cap::grabSelection(*this);
2079 int const label = with_label
2080 ? AS_STR_LABEL | AS_STR_INSETS : AS_STR_INSETS;
2082 idx_type const startidx = selBegin().idx();
2083 idx_type const endidx = selEnd().idx();
2084 if (startidx != endidx) {
2085 // multicell selection
2086 InsetTabular * table = inset().asInsetTabular();
2087 LASSERT(table, return docstring());
2088 return table->asString(startidx, endidx);
2091 ParagraphList const & pars = text()->paragraphs();
2093 pit_type const startpit = selBegin().pit();
2094 pit_type const endpit = selEnd().pit();
2095 size_t const startpos = selBegin().pos();
2096 size_t const endpos = selEnd().pos();
2098 if (startpit == endpit)
2099 return pars[startpit].asString(startpos, endpos, label);
2101 // First paragraph in selection
2102 docstring result = pars[startpit].
2103 asString(startpos, pars[startpit].size(), label)
2106 // The paragraphs in between (if any)
2107 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
2108 Paragraph const & par = pars[pit];
2109 result += par.asString(0, par.size(), label)
2113 // Last paragraph in selection
2114 result += pars[endpit].asString(0, endpos, label);
2120 docstring Cursor::currentState(bool devel_mode) const
2123 odocstringstream os;
2124 info(os, devel_mode);
2129 return text()->currentState(*this, devel_mode);
2135 docstring Cursor::getPossibleLabel() const
2137 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
2141 Encoding const * Cursor::getEncoding() const
2145 BufferParams const & bp = bv().buffer().params();
2146 if (bp.useNonTeXFonts)
2147 return encodings.fromLyXName("utf8-plain");
2149 CursorSlice const & sl = innerTextSlice();
2150 Text const & text = *sl.text();
2151 Font font = text.getPar(sl.pit()).getFont(bp, sl.pos(),
2152 text.outerFont(sl.pit()));
2153 return font.language()->encoding();
2157 void Cursor::undispatched() const
2159 disp_.dispatched(false);
2163 void Cursor::dispatched() const
2165 disp_.dispatched(true);
2169 void Cursor::screenUpdateFlags(Update::flags f) const
2171 disp_.screenUpdate(f);
2175 void Cursor::forceBufferUpdate() const
2177 disp_.forceBufferUpdate();
2181 void Cursor::clearBufferUpdate() const
2183 disp_.clearBufferUpdate();
2187 bool Cursor::needBufferUpdate() const
2189 return disp_.needBufferUpdate();
2193 void Cursor::noScreenUpdate() const
2195 disp_.screenUpdate(Update::None);
2199 Font Cursor::getFont() const
2201 // The logic here should more or less match to the
2202 // Cursor::setCurrentFont logic, i.e. the cursor height should
2203 // give a hint what will happen if a character is entered.
2204 // FIXME: this is not the case, what about removing this method ? (see #10478).
2206 // HACK. far from being perfect...
2208 CursorSlice const & sl = innerTextSlice();
2209 Text const & text = *sl.text();
2210 Paragraph const & par = text.getPar(sl.pit());
2212 // on boundary, so we are really at the character before
2213 pos_type pos = sl.pos();
2214 if (pos > 0 && boundary())
2217 // on space? Take the font before (only for RTL boundary stay)
2219 TextMetrics const & tm = bv().textMetrics(&text);
2220 if (pos == sl.lastpos()
2221 || (par.isSeparator(pos)
2222 && !tm.isRTLBoundary(sl.pit(), pos)))
2226 // get font at the position
2227 Font font = par.getFont(buffer()->params(), pos,
2228 text.outerFont(sl.pit()));
2234 bool Cursor::fixIfBroken()
2236 bool const broken_cursor = DocIterator::fixIfBroken();
2237 bool const broken_anchor = anchor_.fixIfBroken();
2239 if (broken_cursor || broken_anchor) {
2240 clearNewWordPosition();
2248 void Cursor::sanitize()
2250 setBuffer(&bv_->buffer());
2251 DocIterator::sanitize();
2252 new_word_.sanitize();
2260 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2262 // find inset in common
2264 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2265 if (&old[i].inset() != &cur[i].inset())
2269 // update words if we just moved to another paragraph
2270 if (i == old.depth() && i == cur.depth()
2271 && !cur.buffer()->isClean()
2272 && cur.inTexted() && old.inTexted()
2273 && cur.pit() != old.pit()) {
2274 old.paragraph().updateWords();
2277 // notify everything on top of the common part in old cursor,
2278 // but stop if the inset claims the cursor to be invalid now
2279 for (size_type j = i; j < old.depth(); ++j) {
2280 Cursor inset_pos = old;
2281 inset_pos.cutOff(j);
2282 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2286 // notify everything on top of the common part in new cursor,
2287 // but stop if the inset claims the cursor to be invalid now
2288 for (; i < cur.depth(); ++i) {
2289 if (cur[i].inset().notifyCursorEnters(cur))
2297 void Cursor::setCurrentFont()
2299 CursorSlice const & cs = innerTextSlice();
2300 Paragraph const & par = cs.paragraph();
2301 pos_type cpit = cs.pit();
2302 pos_type cpos = cs.pos();
2303 Text const & ctext = *cs.text();
2304 TextMetrics const & tm = bv().textMetrics(&ctext);
2306 // are we behind previous char in fact? -> go to that char
2307 if (cpos > 0 && boundary())
2310 // find position to take the font from
2312 // paragraph end? -> font of last char
2313 if (cpos == lastpos())
2315 // on space? -> look at the words in front of space
2316 else if (cpos > 0 && par.isSeparator(cpos)) {
2317 // abc| def -> font of c
2318 // abc |[WERBEH], i.e. boundary==true -> font of c
2319 // abc [WERBEH]| def, font of the space
2320 if (!tm.isRTLBoundary(cpit, cpos))
2326 BufferParams const & bufparams = buffer()->params();
2327 current_font = par.getFontSettings(bufparams, cpos);
2328 real_current_font = tm.displayFont(cpit, cpos);
2330 // special case for paragraph end
2331 if (cs.pos() == lastpos()
2332 && tm.isRTLBoundary(cpit, cs.pos())
2334 Language const * lang = par.getParLanguage(bufparams);
2335 current_font.setLanguage(lang);
2336 current_font.fontInfo().setNumber(FONT_OFF);
2337 real_current_font.setLanguage(lang);
2338 real_current_font.fontInfo().setNumber(FONT_OFF);
2343 bool Cursor::textUndo()
2345 if (!buffer()->undo().textUndo(*this))
2352 bool Cursor::textRedo()
2354 if (!buffer()->undo().textRedo(*this))
2361 void Cursor::finishUndo() const
2363 buffer()->undo().finishUndo();
2367 void Cursor::beginUndoGroup() const
2369 buffer()->undo().beginUndoGroup(*this);
2373 void Cursor::endUndoGroup() const
2375 buffer()->undo().endUndoGroup(*this);
2379 void Cursor::recordUndo(pit_type from, pit_type to) const
2381 buffer()->undo().recordUndo(*this, from, to);
2385 void Cursor::recordUndo(pit_type from) const
2387 buffer()->undo().recordUndo(*this, from, pit());
2391 void Cursor::recordUndo(UndoKind kind) const
2393 buffer()->undo().recordUndo(*this, kind);
2397 void Cursor::recordUndoInset(Inset const * in) const
2399 buffer()->undo().recordUndoInset(*this, in);
2403 void Cursor::recordUndoFullBuffer() const
2405 buffer()->undo().recordUndoFullBuffer(*this);
2409 void Cursor::recordUndoBufferParams() const
2411 buffer()->undo().recordUndoBufferParams(*this);
2415 void Cursor::recordUndoSelection() const
2418 if (cap::multipleCellsSelected(*this))
2423 buffer()->undo().recordUndo(*this,
2424 selBegin().pit(), selEnd().pit());
2429 void Cursor::checkBufferStructure()
2431 Buffer const * master = buffer()->masterBuffer();
2432 master->tocBackend().updateItem(*this);
2433 if (master != buffer() && !master->hasGuiDelegate())
2434 // In case the master has no gui associated with it,
2435 // the TocItem is not updated (part of bug 5699).
2436 buffer()->tocBackend().updateItem(*this);
2438 // If the last tracked change of the paragraph has just been
2439 // deleted, then we need to recompute the buffer flag
2440 // tracked_changes_present_.
2441 if (inTexted() && paragraph().isChangeUpdateRequired())
2442 disp_.forceChangesUpdate();
2446 bool Cursor::confirmDeletion(bool const before) const
2449 if (Inset const * inset = before ? prevInset() : nextInset())
2450 return inset->confirmDeletion();
2452 DocIterator dit = selectionBegin();
2453 CursorSlice const end = selectionEnd().top();
2454 for (; dit.top() < end; dit.top().forwardPos())
2455 if (Inset const * inset = dit.nextInset())
2456 if (inset->confirmDeletion())
2463 void Cursor::moveToClosestEdge(int const x, bool const edit)
2465 if (Inset const * inset = nextInset()) {
2466 // stay in front of insets for which we want to open the dialog
2467 // (e.g. InsetMathSpace).
2468 if (edit && (inset->hasSettings() || !inset->contextMenuName().empty()))
2470 CoordCache::Insets const & insetCache = bv().coordCache().getInsets();
2471 if (!insetCache.has(inset))
2473 int const wid = insetCache.dim(inset).wid;
2474 Point p = insetCache.xy(inset);
2475 if (x > p.x_ + (wid + 1) / 2)