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 "BufferView.h"
19 #include "CoordCache.h"
21 #include "CutAndPaste.h"
22 #include "DispatchResult.h"
26 #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/debug.h"
39 #include "support/docstream.h"
40 #include "support/ExceptionMessage.h"
41 #include "support/gettext.h"
42 #include "support/lassert.h"
44 #include "insets/InsetTabular.h"
45 #include "insets/InsetText.h"
47 #include "mathed/InsetMath.h"
48 #include "mathed/InsetMathBrace.h"
49 #include "mathed/InsetMathScript.h"
50 #include "mathed/MacroTable.h"
51 #include "mathed/MathData.h"
52 #include "mathed/MathMacro.h"
54 #include "support/bind.h"
67 // Find position closest to (x, y) in cell given by iter.
68 // Used only in mathed
69 DocIterator bruteFind2(Cursor const & c, int x, int y)
71 double best_dist = numeric_limits<double>::max();
78 et.top().pos() = et.top().asInsetMath()->cell(et.top().idx()).size();
79 for (size_t i = 0;; ++i) {
82 Inset const * inset = &it.inset();
83 CoordCache const & cache = c.bv().coordCache();
85 // FIXME: in the case where the inset is not in the cache, this
86 // means that no part of it is visible on screen. In this case
87 // we don't do elaborate search and we just return the forwarded
88 // DocIterator at its beginning.
89 if (!cache.getInsets().has(inset)) {
94 Point const o = cache.getInsets().xy(inset);
95 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
96 // Convert to absolute
99 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
100 // '<=' in order to take the last possible position
101 // this is important for clicking behind \sum in e.g. '\sum_i a'
102 LYXERR(Debug::DEBUG, "i: " << i << " d: " << d
103 << " best: " << best_dist);
104 if (d <= best_dist) {
117 /// moves position closest to (x, y) in given box
118 bool bruteFind(Cursor & cursor,
119 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
121 LASSERT(!cursor.empty(), return false);
122 Inset & inset = cursor[0].inset();
123 BufferView & bv = cursor.bv();
125 CoordCache::InnerParPosCache const & cache =
126 bv.coordCache().getParPos().find(cursor.bottom().text())->second;
127 // Get an iterator on the first paragraph in the cache
128 DocIterator it(inset);
129 it.push_back(CursorSlice(inset));
130 it.pit() = cache.begin()->first;
131 // Get an iterator after the last paragraph in the cache
132 DocIterator et(inset);
133 et.push_back(CursorSlice(inset));
134 et.pit() = prev(cache.end(), 1)->first;
135 if (et.pit() >= et.lastpit())
136 et = doc_iterator_end(inset);
140 double best_dist = numeric_limits<double>::max();
141 DocIterator best_cursor = et;
143 for ( ; it != et; it.forwardPos(true)) {
144 // avoid invalid nesting when selecting
145 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
146 Point p = bv.getPos(it, false);
149 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
150 double const dx = xo - x;
151 double const dy = yo - y;
152 double const d = dx * dx + dy * dy;
153 // '<=' in order to take the last possible position
154 // this is important for clicking behind \sum in e.g. '\sum_i a'
155 if (d <= best_dist) {
156 // lyxerr << "*" << endl;
164 if (best_cursor != et) {
165 cursor.setCursor(best_cursor);
174 /// moves position closest to (x, y) in given box
175 bool bruteFind3(Cursor & cur, int x, int y, bool up)
177 BufferView & bv = cur.bv();
178 int ylow = up ? 0 : y + 1;
179 int yhigh = up ? y - 1 : bv.workHeight();
181 int xhigh = bv.workWidth();
183 // FIXME: bit more work needed to get 'from' and 'to' right.
184 pit_type from = cur.bottom().pit();
185 //pit_type to = cur.bottom().pit();
186 //lyxerr << "Pit start: " << from << endl;
188 //lyxerr << "bruteFind3: x: " << x << " y: " << y
189 // << " xlow: " << xlow << " xhigh: " << xhigh
190 // << " ylow: " << ylow << " yhigh: " << yhigh
192 DocIterator it = doc_iterator_begin(cur.buffer());
194 DocIterator et = doc_iterator_end(cur.buffer());
196 double best_dist = numeric_limits<double>::max();
197 DocIterator best_cursor = et;
199 for ( ; it != et; it.forwardPos()) {
200 // avoid invalid nesting when selecting
201 if (bv.cursorStatus(it) == CUR_INSIDE
202 && (!cur.selection() || positionable(it, cur.realAnchor()))) {
203 // If this function is ever used again, check
204 // whether this is the same as "bv.getPos(it,
205 // false)" with boundary = false.
206 Point p = bv.getPos(it);
209 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
210 double const dx = xo - x;
211 double const dy = yo - y;
212 double const d = dx * dx + dy * dy;
213 //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
214 // << " dx: " << dx << " dy: " << dy
215 // << " idx: " << it.idx() << " pos: " << it.pos()
218 // '<=' in order to take the last possible position
219 // this is important for clicking behind \sum in e.g. '\sum_i a'
220 if (d <= best_dist) {
221 //lyxerr << "*" << endl;
229 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
230 if (best_cursor == et)
232 cur.setCursor(best_cursor);
239 CursorData::CursorData()
240 : DocIterator(), anchor_(),
241 selection_(false), mark_(false), word_selection_(false),
242 logicalpos_(false), current_font(inherit_font),
243 autocorrect_(false), macromode_(false)
247 CursorData::CursorData(Buffer * buffer)
248 : DocIterator(buffer), anchor_(),
249 selection_(false), mark_(false), word_selection_(false),
250 logicalpos_(false), current_font(inherit_font),
251 autocorrect_(false), macromode_(false)
255 CursorData::CursorData(DocIterator const & dit)
256 : DocIterator(dit), anchor_(),
257 selection_(false), mark_(false), word_selection_(false),
258 logicalpos_(false), current_font(inherit_font),
259 autocorrect_(false), macromode_(false)
265 ostream & operator<<(ostream & os, CursorData const & cur)
267 os << "\n cursor: | anchor:\n";
268 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
269 os << " " << cur[i] << " | ";
270 if (i < cur.anchor_.depth())
271 os << cur.anchor_[i];
273 os << "-------------------------------";
276 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
277 os << "------------------------------- | " << cur.anchor_[i] << "\n";
279 os << " selection: " << cur.selection_
280 // << " x_target: " << cur.x_target_
281 << " boundary: " << cur.boundary() << endl;
286 LyXErr & operator<<(LyXErr & os, CursorData const & cur)
293 // be careful: this is called from the bv's constructor, too, so
294 // bv functions are not yet available!
295 Cursor::Cursor(BufferView & bv)
296 : CursorData(&bv.buffer()), bv_(&bv),
297 x_target_(-1), textTargetOffset_(0),
298 beforeDispatchPosX_(0), beforeDispatchPosY_(0)
305 push_back(CursorSlice(buffer()->inset()));
306 anchor_ = doc_iterator_begin(buffer());
308 new_word_ = doc_iterator_begin(buffer());
316 // this (intentionally) does neither touch anchor nor selection status
317 void Cursor::setCursor(DocIterator const & cur)
319 DocIterator::operator=(cur);
323 void Cursor::setCursorToAnchor()
326 DocIterator normal = anchor_;
327 while (depth() < normal.depth())
329 if (depth() < anchor_.depth() && top() <= anchor_[depth() - 1])
336 void Cursor::setCursorData(CursorData const & data)
338 CursorData::operator=(data);
342 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
346 // Try to fix cursor in case it is broken.
349 // Is this a function that acts on inset at point?
350 Inset * inset = cur.nextInset();
351 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
352 && inset && inset->getStatus(cur, cmd, status))
355 // This is, of course, a mess. Better create a new doc iterator and use
356 // this in Inset::getStatus. This might require an additional
357 // BufferView * arg, though (which should be avoided)
358 //Cursor safe = *this;
360 for ( ; cur.depth(); cur.pop()) {
361 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
362 // LASSERT: Is it safe to continue here, or should we return?
363 LASSERT(cur.idx() <= cur.lastidx(), /**/);
364 LASSERT(cur.pit() <= cur.lastpit(), /**/);
365 LASSERT(cur.pos() <= cur.lastpos(), /**/);
367 // The inset's getStatus() will return 'true' if it made
368 // a definitive decision on whether it want to handle the
369 // request or not. The result of this decision is put into
370 // the 'status' parameter.
371 if (cur.inset().getStatus(cur, cmd, status)) {
380 void Cursor::saveBeforeDispatchPosXY()
382 getPos(beforeDispatchPosX_, beforeDispatchPosY_);
386 void Cursor::dispatch(FuncRequest const & cmd0)
388 LYXERR(Debug::ACTION, "Cursor::dispatch: cmd: " << cmd0 << '\n' << *this);
393 FuncRequest cmd = cmd0;
396 disp_ = DispatchResult();
400 // Is this a function that acts on inset at point?
401 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
403 disp_.dispatched(true);
404 disp_.screenUpdate(Update::FitCursor | Update::Force);
405 FuncRequest tmpcmd = cmd;
406 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
407 << cmd0 << endl << *this);
408 nextInset()->dispatch(*this, tmpcmd);
409 if (disp_.dispatched()) {
415 // store some values to be used inside of the handlers
416 beforeDispatchCursor_ = *this;
417 for (; depth(); pop(), boundary(false)) {
418 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
419 << cmd0 << endl << *this);
421 // In any of these cases, the cursor is invalid, and we should
422 // try to save this document rather than crash.
423 LBUFERR(pos() <= lastpos());
424 LBUFERR(idx() <= lastidx());
425 LBUFERR(pit() <= lastpit());
427 // The common case is 'LFUN handled, need update', so make the
428 // LFUN handler's life easier by assuming this as default value.
429 // The handler can reset the update and val flags if necessary.
430 disp_.screenUpdate(Update::FitCursor | Update::Force);
431 disp_.dispatched(true);
432 inset().dispatch(*this, cmd);
433 if (disp_.dispatched())
437 // it completely to get a 'bomb early' behaviour in case this
438 // object will be used again.
439 if (!disp_.dispatched()) {
440 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
441 // We might have invalidated the cursor when removing an empty
442 // paragraph while the cursor could not be moved out the inset
443 // while we initially thought we could. This might happen when
444 // a multiline inset becomes an inline inset when the second
445 // paragraph is removed.
446 if (safe.pit() > safe.lastpit()) {
447 safe.pit() = safe.lastpit();
448 safe.pos() = safe.lastpos();
451 disp_.screenUpdate(Update::None);
452 disp_.dispatched(false);
454 // restore the previous one because nested Cursor::dispatch calls
455 // are possible which would change it
456 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
460 // NOTE: The code below has been copied to BufferView::dispatch.
461 // If you need to modify this, please update the other one too.
463 // notify insets we just left
465 old.beginUndoGroup();
467 bool badcursor = notifyCursorLeavesOrEnters(old, *this);
470 bv().resetInlineCompletionPos();
477 DispatchResult const & Cursor::result() const
483 BufferView & Cursor::bv() const
492 LBUFERR(depth() >= 1);
497 void Cursor::push(Inset & p)
499 push_back(CursorSlice(p));
500 p.setBuffer(*buffer());
504 void Cursor::pushBackward(Inset & p)
506 LASSERT(!empty(), return);
507 //lyxerr << "Entering inset " << t << " front" << endl;
513 bool Cursor::popBackward()
515 LASSERT(!empty(), return false);
523 bool Cursor::popForward()
525 LASSERT(!empty(), return false);
526 //lyxerr << "Leaving inset from in back" << endl;
527 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
531 pos() += lastpos() - lp + 1;
536 int Cursor::currentMode()
538 LASSERT(!empty(), return Inset::UNDECIDED_MODE);
539 for (int i = depth() - 1; i >= 0; --i) {
540 int res = operator[](i).inset().currentMode();
541 bool locked_mode = operator[](i).inset().lockedMode();
542 // Also return UNDECIDED_MODE when the mode is locked,
543 // as in this case it is treated the same as TEXT_MODE
544 if (res != Inset::UNDECIDED_MODE || locked_mode)
547 return Inset::TEXT_MODE;
551 bool Cursor::inCoordCache() const
553 CoordCache::Insets const & icache = bv_->coordCache().getInsets();
554 for (size_t i = 0 ; i < depth() ; ++i)
555 if (!icache.has(&(*this)[i].inset()))
561 void Cursor::getPos(int & x, int & y) const
563 Point p = bv().getPos(*this);
569 Row const & Cursor::textRow() const
571 CursorSlice const & cs = innerTextSlice();
572 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
573 return pm.getRow(pos(), boundary());
577 void Cursor::resetAnchor()
580 checkNewWordPosition();
584 void Cursor::markNewWordPosition()
586 if (lyxrc.spellcheck_continuously && inTexted() && new_word_.empty()) {
587 FontSpan nw = locateWord(WHOLE_WORD);
588 if (nw.size() == 1) {
589 LYXERR(Debug::DEBUG, "start new word: "
591 << " pos: " << nw.first);
598 void Cursor::clearNewWordPosition()
600 if (!new_word_.empty()) {
601 LYXERR(Debug::DEBUG, "clear new word: "
603 << " pos: " << pos());
609 void Cursor::checkNewWordPosition()
611 if (!lyxrc.spellcheck_continuously || new_word_.empty())
614 clearNewWordPosition();
616 // forget the position of the current new word if
617 // 1) the paragraph changes or
618 // 2) the count of nested insets changes or
619 // 3) the cursor pos is out of paragraph bound
620 if (pit() != new_word_.pit() ||
621 depth() != new_word_.depth() ||
622 new_word_.pos() > new_word_.lastpos()) {
623 clearNewWordPosition();
624 } else if (new_word_.fixIfBroken())
625 // 4) or the remembered position was "broken"
626 clearNewWordPosition();
628 FontSpan nw = locateWord(WHOLE_WORD);
630 FontSpan ow = new_word_.locateWord(WHOLE_WORD);
631 if (nw.intersect(ow).empty())
632 clearNewWordPosition();
634 LYXERR(Debug::DEBUG, "new word: "
636 << " pos: " << nw.first << ".." << nw.last);
638 clearNewWordPosition();
645 bool Cursor::posBackward()
654 bool Cursor::posForward()
656 if (pos() == lastpos())
663 bool Cursor::posVisRight(bool skip_inset)
665 Cursor new_cur = *this; // where we will move to
666 pos_type left_pos; // position visually left of current cursor
667 pos_type right_pos; // position visually right of current cursor
669 getSurroundingPos(left_pos, right_pos);
671 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
673 // Are we at an inset?
674 new_cur.pos() = right_pos;
675 new_cur.boundary(false);
677 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
678 // we actually move the cursor at the end of this
679 // function, for now we just keep track of the new
680 // position in new_cur...
681 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
684 // Are we already at rightmost pos in row?
685 else if (text()->empty() || right_pos == -1) {
688 if (!new_cur.posVisToNewRow(false)) {
689 LYXERR(Debug::RTL, "not moving!");
693 // we actually move the cursor at the end of this
694 // function, for now just keep track of the new
695 // position in new_cur...
696 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
697 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
700 // normal movement to the right
703 // Recall, if the cursor is at position 'x', that
704 // means *before* the character at position 'x'. In
705 // RTL, "before" means "to the right of", in LTR, "to
706 // the left of". So currently our situation is this:
707 // the position to our right is 'right_pos' (i.e.,
708 // we're currently to the left of 'right_pos'). In
709 // order to move to the right, it depends whether or
710 // not the character at 'right_pos' is RTL.
711 bool const new_pos_is_RTL = paragraph().getFontSettings(
712 buffer()->params(), right_pos).isVisibleRightToLeft();
713 // If the character at 'right_pos' *is* LTR, then in
714 // order to move to the right of it, we need to be
715 // *after* 'right_pos', i.e., move to position
717 if (!new_pos_is_RTL) {
718 new_cur.pos() = right_pos + 1;
719 // set the boundary to true in two situations:
721 // 1. if new_pos is now lastpos, and we're in
722 // an RTL paragraph (this means that we're
723 // moving right to the end of an LTR chunk
724 // which is at the end of an RTL paragraph);
725 (new_cur.pos() == lastpos()
726 && paragraph().isRTL(buffer()->params()))
727 // 2. if the position *after* right_pos is RTL
728 // (we want to be *after* right_pos, not
729 // before right_pos + 1!)
730 || paragraph().getFontSettings(buffer()->params(),
731 new_cur.pos()).isVisibleRightToLeft()
733 new_cur.boundary(true);
734 else // set the boundary to false
735 new_cur.boundary(false);
737 // Otherwise (if the character at position 'right_pos'
738 // is RTL), then moving to the right of it is as easy
739 // as setting the new position to 'right_pos'.
741 new_cur.pos() = right_pos;
742 new_cur.boundary(false);
747 bool const moved = new_cur != *this || new_cur.boundary() != boundary();
750 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
751 << (new_cur.boundary() ? " (boundary)" : ""));
759 bool Cursor::posVisLeft(bool skip_inset)
761 Cursor new_cur = *this; // where we will move to
762 pos_type left_pos; // position visually left of current cursor
763 pos_type right_pos; // position visually right of current cursor
765 getSurroundingPos(left_pos, right_pos);
767 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
769 // Are we at an inset?
770 new_cur.pos() = left_pos;
771 new_cur.boundary(false);
773 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
774 // we actually move the cursor at the end of this
775 // function, for now we just keep track of the new
776 // position in new_cur...
777 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
780 // Are we already at leftmost pos in row?
781 else if (text()->empty() || left_pos == -1) {
784 if (!new_cur.posVisToNewRow(true)) {
785 LYXERR(Debug::RTL, "not moving!");
789 // we actually move the cursor at the end of this
790 // function, for now just keep track of the new
791 // position in new_cur...
792 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
793 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
796 // normal movement to the left
799 // Recall, if the cursor is at position 'x', that
800 // means *before* the character at position 'x'. In
801 // RTL, "before" means "to the right of", in LTR, "to
802 // the left of". So currently our situation is this:
803 // the position to our left is 'left_pos' (i.e., we're
804 // currently to the right of 'left_pos'). In order to
805 // move to the left, it depends whether or not the
806 // character at 'left_pos' is RTL.
807 bool const new_pos_is_RTL = paragraph().getFontSettings(
808 buffer()->params(), left_pos).isVisibleRightToLeft();
809 // If the character at 'left_pos' *is* RTL, then in
810 // order to move to the left of it, we need to be
811 // *after* 'left_pos', i.e., move to position
813 if (new_pos_is_RTL) {
814 new_cur.pos() = left_pos + 1;
815 // set the boundary to true in two situations:
817 // 1. if new_pos is now lastpos and we're in
818 // an LTR paragraph (this means that we're
819 // moving left to the end of an RTL chunk
820 // which is at the end of an LTR paragraph);
821 (new_cur.pos() == lastpos()
822 && !paragraph().isRTL(buffer()->params()))
823 // 2. if the position *after* left_pos is not
824 // RTL (we want to be *after* left_pos, not
825 // before left_pos + 1!)
826 || !paragraph().getFontSettings(buffer()->params(),
827 new_cur.pos()).isVisibleRightToLeft()
829 new_cur.boundary(true);
830 else // set the boundary to false
831 new_cur.boundary(false);
833 // Otherwise (if the character at position 'left_pos'
834 // is LTR), then moving to the left of it is as easy
835 // as setting the new position to 'left_pos'.
837 new_cur.pos() = left_pos;
838 new_cur.boundary(false);
843 bool const moved = new_cur != *this || new_cur.boundary() != boundary();
846 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
847 << (new_cur.boundary() ? " (boundary)" : ""));
857 // Return true on success
858 bool findNonVirtual(Row const & row, Row::const_iterator & cit, bool onleft)
861 while (cit != row.begin() && cit->isVirtual())
864 while (cit != row.end() && cit->isVirtual())
867 return cit != row.end() && !cit->isVirtual();
872 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos) const
874 // by default, we know nothing.
878 Row const & row = textRow();
879 TextMetrics const & tm = bv_->textMetrics(text());
881 Row::const_iterator cit = tm.findRowElement(row, pos(), boundary(), dummy);
882 // Handle the case of empty row
883 if (cit == row.end()) {
884 if (paragraph().isRTL(buffer()->params()))
885 right_pos = row.pos();
887 left_pos = row.pos() - 1;
891 // skip virtual elements and exit if no non-virtual one exists
892 if (!findNonVirtual(row, cit, !cit->isRTL()))
895 // if the position is at the left side of the element, we have to
896 // look at the previous element
897 if (pos() == cit->left_pos()) {
898 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
899 << "), AT LEFT of *cit=" << *cit);
900 // this one is easy (see common case below)
901 right_pos = pos() - (cit->isRTL() ? 1 : 0);
902 // at the left of the row
903 if (cit == row.begin())
906 if (!findNonVirtual(row, cit, true))
908 // [...[ is the row element, | is cursor position (! with boundary)
909 // [ 1 2 [ is a ltr row element with pos=1 and endpos=3
910 // ] 2 1] is an rtl row element with pos=1 and endpos=3
911 // [ 1 2 [ [|3 4 [ => (2, 3)
912 // or [ 1 2 [ ]!4 3 ] => (2, 4)
913 // or ] 2 1 ] [|3 4 [ => (1, 3)
914 // or ] 4 3 ] ]!2 1 ] => (3, 2)
915 left_pos = cit->right_pos() - (cit->isRTL() ? 0 : 1);
916 // happens with consecutive row of same direction
917 if (left_pos == right_pos) {
918 left_pos += cit->isRTL() ? 1 : -1;
921 // same code but with the element at the right
922 else if (pos() == cit->right_pos()) {
923 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
924 << "), AT RIGHT of *cit=" << *cit);
925 // this one is easy (see common case below)
926 left_pos = pos() - (cit->isRTL() ? 0 : 1);
927 // at the right of the row
928 if (cit + 1 == row.end())
931 if (!findNonVirtual(row, cit, false))
933 // [ 1 2![ [ 3 4 [ => (2, 3)
934 // or [ 1 2![ ] 4 3 ] => (2, 4)
935 // or ] 2 1|] [ 3 4 [ => (1, 3)
936 // or ] 4 3|] ] 2 1 ] => (3, 2)
937 right_pos = cit->left_pos() - (cit->isRTL() ? 1 : 0);
938 // happens with consecutive row of same direction
939 if (right_pos == left_pos)
940 right_pos += cit->isRTL() ? -1 : 1;
942 // common case: both positions are inside the row element
944 // [ 1 2|3 [ => (2, 3)
945 // or ] 3|2 1 ] => (3, 2)
946 left_pos = pos() - (cit->isRTL() ? 0 : 1);
947 right_pos = pos() - (cit->isRTL() ? 1 : 0);
950 // Note that debug message does not catch all early returns above
951 LYXERR(Debug::RTL,"getSurroundingPos(" << pos() << (boundary() ? "b" : "")
952 << ") => (" << left_pos << ", " << right_pos <<")");
956 bool Cursor::posVisToNewRow(bool movingLeft)
958 Paragraph const & par = paragraph();
959 Buffer const & buf = *buffer();
960 Row const & row = textRow();
961 bool par_is_LTR = !par.isRTL(buf.params());
963 // Inside a table, determining whether to move to the next or
964 // previous row should be done based on the table's direction.
965 if (inset().asInsetTabular()) {
966 par_is_LTR = !inset().asInsetTabular()->isRightToLeft(*this);
967 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
970 // if moving left in an LTR paragraph or moving right in an
971 // RTL one, move to previous row
972 if (par_is_LTR == movingLeft) {
973 if (row.pos() == 0) { // we're at first row in paragraph
974 if (pit() == 0) // no previous paragraph! don't move
976 // move to last pos in previous par
980 } else { // move to previous row in this par
981 pos() = row.pos() - 1; // this is guaranteed to be in previous row
985 // if moving left in an RTL paragraph or moving right in an
986 // LTR one, move to next row
988 if (row.endpos() == lastpos()) { // we're at last row in paragraph
989 if (pit() == lastpit()) // last paragraph! don't move
991 // move to first row in next par
995 } else { // move to next row in this par
996 pos() = row.endpos();
1001 // make sure we're at left-/right-most pos in new row
1002 posVisToRowExtremity(!movingLeft);
1008 void Cursor::posVisToRowExtremity(bool left)
1010 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
1011 << (boundary() ? 1 : 0));
1013 TextMetrics const & tm = bv_->textMetrics(text());
1014 // Looking for extremities is like clicking on the left or the
1015 // right of the row.
1016 int x = tm.origin().x_ + (left ? 0 : textRow().width());
1018 pos() = tm.getPosNearX(textRow(), x, b);
1021 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
1022 << (boundary() ? 1 : 0));
1026 bool Cursor::reverseDirectionNeeded() const
1029 * We determine the directions based on the direction of the
1030 * bottom() --- i.e., outermost --- paragraph, because that is
1031 * the only way to achieve consistency of the arrow's movements
1032 * within a paragraph, and thus avoid situations in which the
1033 * cursor gets stuck.
1035 return bottom().paragraph().isRTL(bv().buffer().params());
1039 CursorSlice Cursor::normalAnchor() const
1043 // LASSERT: There have been several bugs around this code, that seem
1044 // to involve failures to reset the anchor. We can at least not crash
1045 // in release mode by resetting it ourselves.
1046 LASSERT(anchor_.depth() >= depth(),
1047 const_cast<DocIterator &>(anchor_) = *this);
1049 CursorSlice normal = anchor_[depth() - 1];
1050 if (depth() < anchor_.depth() && top() <= normal) {
1051 // anchor is behind cursor -> move anchor behind the inset
1058 DocIterator & Cursor::realAnchor()
1064 CursorSlice Cursor::selBegin() const
1068 return normalAnchor() < top() ? normalAnchor() : top();
1072 CursorSlice Cursor::selEnd() const
1076 return normalAnchor() > top() ? normalAnchor() : top();
1080 DocIterator Cursor::selectionBegin() const
1086 // FIXME: This is a work-around for the problem that
1087 // CursorSlice doesn't keep track of the boundary.
1088 if (normalAnchor() == top())
1089 di = anchor_.boundary() > boundary() ? anchor_ : *this;
1091 di = normalAnchor() < top() ? anchor_ : *this;
1097 DocIterator Cursor::selectionEnd() const
1103 // FIXME: This is a work-around for the problem that
1104 // CursorSlice doesn't keep track of the boundary.
1105 if (normalAnchor() == top())
1106 di = anchor_.boundary() < boundary() ? anchor_ : *this;
1108 di = normalAnchor() > top() ? anchor_ : *this;
1110 if (di.depth() > depth()) {
1118 void Cursor::setSelection()
1121 if (idx() == normalAnchor().idx() &&
1122 pit() == normalAnchor().pit() &&
1123 pos() == normalAnchor().pos())
1124 setSelection(false);
1128 void Cursor::setSelection(DocIterator const & where, int n)
1137 void Cursor::clearSelection()
1139 setSelection(false);
1140 setWordSelection(false);
1146 void Cursor::setTargetX(int x)
1149 textTargetOffset_ = 0;
1153 int Cursor::x_target() const
1159 void Cursor::clearTargetX()
1162 textTargetOffset_ = 0;
1166 void Cursor::updateTextTargetOffset()
1171 textTargetOffset_ = x - x_target_;
1175 void Cursor::info(odocstream & os) const
1177 for (int i = 1, n = depth(); i < n; ++i) {
1178 operator[](i).inset().infoize(os);
1182 Inset const * inset = prevInset();
1183 // prevInset() can return 0 in certain case.
1185 prevInset()->infoize2(os);
1190 bool Cursor::selHandle(bool sel)
1192 //lyxerr << "Cursor::selHandle" << endl;
1195 if (sel == selection())
1199 cap::saveSelection(*this);
1208 ///////////////////////////////////////////////////////////////////
1211 // The part below is the non-integrated rest of the original math
1212 // cursor. This should be either generalized for texted or moved
1213 // back to mathed (in most cases to InsetMathNest).
1215 ///////////////////////////////////////////////////////////////////
1217 #include "mathed/InsetMathChar.h"
1218 #include "mathed/InsetMathGrid.h"
1219 #include "mathed/InsetMathScript.h"
1220 #include "mathed/InsetMathUnknown.h"
1221 #include "mathed/MathFactory.h"
1222 #include "mathed/MathStream.h"
1223 #include "mathed/MathSupport.h"
1228 bool Cursor::isInside(Inset const * p) const
1230 for (size_t i = 0; i != depth(); ++i)
1231 if (&operator[](i).inset() == p)
1237 void Cursor::leaveInset(Inset const & inset)
1239 for (size_t i = 0; i != depth(); ++i) {
1240 if (&operator[](i).inset() == &inset) {
1248 bool Cursor::openable(MathAtom const & t) const
1259 // we can't move into anything new during selection
1260 if (depth() >= anchor_.depth())
1262 if (t.nucleus() != &anchor_[depth()].inset())
1269 void Cursor::setScreenPos(int x, int /*y*/)
1272 //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
1277 void Cursor::plainErase()
1279 cell().erase(pos());
1283 void Cursor::markInsert()
1285 insert(char_type(0));
1289 void Cursor::markErase()
1291 cell().erase(pos());
1295 void Cursor::plainInsert(MathAtom const & t)
1297 cell().insert(pos(), t);
1299 inset().setBuffer(bv_->buffer());
1301 checkBufferStructure();
1305 void Cursor::insert(docstring const & str)
1307 for_each(str.begin(), str.end(),
1308 bind(static_cast<void(Cursor::*)(char_type)>
1309 (&Cursor::insert), this, _1));
1313 void Cursor::insert(char_type c)
1315 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1316 LASSERT(!empty(), return);
1318 cap::selClearOrDel(*this);
1319 insert(new InsetMathChar(c));
1321 text()->insertChar(*this, c);
1326 void Cursor::insert(MathAtom const & t)
1328 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1330 cap::selClearOrDel(*this);
1335 void Cursor::insert(Inset * inset0)
1337 LASSERT(inset0, return);
1339 insert(MathAtom(inset0->asInsetMath()));
1341 text()->insertInset(*this, inset0);
1342 inset0->setBuffer(bv_->buffer());
1344 if (inset0->isLabeled())
1345 forceBufferUpdate();
1350 int Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1352 MathData ar(buffer());
1354 if (ar.size() == 1 && (enter || selection()))
1362 void Cursor::niceInsert(MathAtom const & t)
1365 docstring const safe = cap::grabAndEraseSelection(*this);
1367 // If possible, enter the new inset and move the contents of the selection
1368 if (t->isActive()) {
1370 // be careful here: don't use 'pushBackward(t)' as this we need to
1371 // push the clone, not the original
1372 pushBackward(*nextInset());
1373 // We may not use niceInsert here (recursion)
1374 MathData ar(buffer());
1377 } else if (t->asMacro() && !safe.empty()) {
1378 MathData ar(buffer());
1380 docstring const name = t->asMacro()->name();
1381 MacroData const * data = buffer()->getMacro(name);
1382 if (data && data->numargs() - data->optionals() > 0) {
1383 plainInsert(MathAtom(new InsetMathBrace(ar)));
1390 void Cursor::insert(MathData const & ar)
1394 cap::eraseSelection(*this);
1395 cell().insert(pos(), ar);
1397 // FIXME audit setBuffer calls
1398 inset().setBuffer(bv_->buffer());
1402 bool Cursor::backspace()
1405 cap::eraseSelection(*this);
1410 // If empty cell, and not part of a big cell
1411 if (lastpos() == 0 && inset().nargs() == 1) {
1413 // Directly delete empty cell: [|[]] => [|]
1419 // [|], can not delete from inside
1430 if (inMacroMode()) {
1431 InsetMathUnknown * p = activeMacro();
1432 if (p->name().size() > 1) {
1433 p->setName(p->name().substr(0, p->name().size() - 1));
1438 if (pos() != 0 && prevAtom()->nargs() > 0) {
1439 // let's require two backspaces for 'big stuff' and
1440 // highlight on the first
1452 bool Cursor::erase()
1458 cap::eraseSelection(*this);
1462 // delete empty cells if possible
1463 if (pos() == lastpos() && inset().idxDelete(idx()))
1466 // special behaviour when in last position of cell
1467 if (pos() == lastpos()) {
1468 bool one_cell = inset().nargs() == 1;
1469 if (one_cell && lastpos() == 0) {
1471 // Directly delete empty cell: [|[]] => [|]
1477 // [|], can not delete from inside
1482 inset().idxGlue(idx());
1486 // 'clever' UI hack: only erase large items if previously slected
1487 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
1502 DocIterator save = *this;
1503 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1504 this->dispatch(cmd);
1505 if (disp_.dispatched())
1515 DocIterator save = *this;
1516 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1517 this->dispatch(cmd);
1518 if (disp_.dispatched())
1525 bool Cursor::macroModeClose()
1529 InsetMathUnknown * p = activeMacro();
1531 MathData selection(buffer());
1532 asArray(p->selection(), selection);
1533 docstring const s = p->name();
1535 cell().erase(pos());
1537 // do nothing if the macro name is empty
1541 // trigger updates of macros, at least, if no full
1542 // updates take place anyway
1543 screenUpdateFlags(Update::Force);
1545 docstring const name = s.substr(1);
1546 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1547 if (in && in->interpretString(*this, s))
1549 MathAtom atom = buffer()->getMacro(name, *this, false) ?
1550 MathAtom(new MathMacro(buffer(), name)) : createInsetMath(name, buffer());
1552 // try to put argument into macro, if we just inserted a macro
1553 bool macroArg = false;
1554 MathMacro * atomAsMacro = atom.nucleus()->asMacro();
1556 // macros here are still unfolded (in init mode in fact). So
1557 // we have to resolve the macro here manually and check its arity
1558 // to put the selection behind it if arity > 0.
1559 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1560 if (!selection.empty() && data && data->numargs() - data->optionals() > 0) {
1562 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1564 // non-greedy case. Do not touch the arguments behind
1565 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1568 // insert remembered selection into first argument of a non-macro
1569 else if (atom.nucleus()->nargs() > 0)
1570 atom.nucleus()->cell(0).append(selection);
1574 // finally put the macro argument behind, if needed
1576 if (selection.size() > 1 || selection[0]->asScriptInset())
1577 plainInsert(MathAtom(new InsetMathBrace(selection)));
1586 docstring Cursor::macroName()
1588 return inMacroMode() ? activeMacro()->name() : docstring();
1592 void Cursor::handleNest(MathAtom const & a, int c)
1594 //lyxerr << "Cursor::handleNest: " << c << endl;
1596 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1599 pushBackward(*nextInset());
1603 int Cursor::targetX() const
1605 if (x_target() != -1)
1614 int Cursor::textTargetOffset() const
1616 return textTargetOffset_;
1620 void Cursor::setTargetX()
1629 bool Cursor::inMacroMode() const
1633 if (pos() == 0 || cell().empty())
1635 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1636 return p && !p->final();
1640 InsetMathUnknown * Cursor::activeMacro()
1642 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1646 InsetMathUnknown const * Cursor::activeMacro() const
1648 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1652 void Cursor::pullArg()
1655 MathData ar = cell();
1656 if (popBackward() && inMathed()) {
1658 cell().insert(pos(), ar);
1661 //formula()->mutateToText();
1666 void Cursor::touch()
1670 DocIterator::const_iterator it = begin();
1671 DocIterator::const_iterator et = end();
1672 for ( ; it != et; ++it)
1678 void Cursor::normalize()
1680 if (idx() > lastidx()) {
1681 lyxerr << "this should not really happen - 1: "
1682 << idx() << ' ' << nargs()
1683 << " in: " << &inset() << endl;
1687 if (pos() > lastpos()) {
1688 lyxerr << "this should not really happen - 2: "
1689 << pos() << ' ' << lastpos() << " in idx: " << idx()
1691 odocstringstream os;
1692 TexRow texrow(false);
1693 otexrowstream ots(os,texrow);
1694 WriteStream wi(ots, false, true, WriteStream::wsDefault);
1695 inset().asInsetMath()->write(wi);
1696 lyxerr << to_utf8(os.str()) << endl;
1702 bool Cursor::upDownInMath(bool up)
1704 // Be warned: The 'logic' implemented in this function is highly
1705 // fragile. A distance of one pixel or a '<' vs '<=' _really
1706 // matters. So fiddle around with it only if you think you know
1707 // what you are doing!
1711 xo = beforeDispatchPosX_;
1713 // check if we had something else in mind, if not, this is the future
1715 if (x_target_ == -1)
1717 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1718 // In text mode inside the line (not left or right) possibly set a new target_x,
1719 // but only if we are somewhere else than the previous target-offset.
1721 // We want to keep the x-target on subsequent up/down movements
1722 // that cross beyond the end of short lines. Thus a special
1723 // handling when the cursor is at the end of line: Use the new
1724 // x-target only if the old one was before the end of line
1725 // or the old one was after the beginning of the line
1726 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
1730 left = pos() == textRow().endpos();
1731 right = pos() == textRow().pos();
1733 left = pos() == textRow().pos();
1734 right = pos() == textRow().endpos();
1736 if ((!left && !right) ||
1737 (left && !right && xo < x_target_) ||
1738 (!left && right && x_target_ < xo))
1745 // try neigbouring script insets
1747 if (inMathed() && !selection()) {
1750 InsetMathScript const * p = prevAtom()->asScriptInset();
1751 if (p && p->has(up)) {
1753 push(*const_cast<InsetMathScript*>(p));
1754 idx() = p->idxOfScript(up);
1757 // we went in the right direction? Otherwise don't jump into the script
1761 int oy = beforeDispatchPosY_;
1762 if ((!up && y <= oy) ||
1771 if (pos() != lastpos()) {
1772 InsetMathScript const * p = nextAtom()->asScriptInset();
1773 if (p && p->has(up)) {
1774 push(*const_cast<InsetMathScript*>(p));
1775 idx() = p->idxOfScript(up);
1778 // we went in the right direction? Otherwise don't jump into the script
1782 int oy = beforeDispatchPosY_;
1783 if ((!up && y <= oy) ||
1792 // try to find an inset that knows better then we,
1793 if (inset().idxUpDown(*this, up)) {
1794 //lyxerr << "idxUpDown triggered" << endl;
1795 // try to find best position within this inset
1797 setCursor(bruteFind2(*this, xo, yo));
1801 // any improvement going just out of inset?
1802 if (popBackward() && inMathed()) {
1803 //lyxerr << "updown: popBackward succeeded" << endl;
1806 int yold = beforeDispatchPosY_;
1808 if (up ? ynew < yold : ynew > yold)
1812 // no success, we are probably at the document top or bottom
1818 bool Cursor::atFirstOrLastRow(bool up)
1820 TextMetrics const & tm = bv_->textMetrics(text());
1821 ParagraphMetrics const & pm = tm.parMetrics(pit());
1824 if (pos() && boundary())
1825 row = pm.pos2row(pos() - 1);
1827 row = pm.pos2row(pos());
1830 if (pit() == 0 && row == 0)
1833 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1834 row + 1 >= int(pm.rows().size()))
1841 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1843 LASSERT(text(), return false);
1849 xo = beforeDispatchPosX_;
1851 // update the targetX - this is here before the "return false"
1852 // to set a new target which can be used by InsetTexts above
1853 // if we cannot move up/down inside this inset anymore
1854 if (x_target_ == -1)
1856 else if (xo - textTargetOffset() != x_target() &&
1857 depth() == beforeDispatchCursor_.depth()) {
1858 // In text mode inside the line (not left or right)
1859 // possibly set a new target_x, but only if we are
1860 // somewhere else than the previous target-offset.
1862 // We want to keep the x-target on subsequent up/down
1863 // movements that cross beyond the end of short lines.
1864 // Thus a special handling when the cursor is at the
1865 // end of line: Use the new x-target only if the old
1866 // one was before the end of line or the old one was
1867 // after the beginning of the line
1868 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
1872 left = pos() == textRow().endpos();
1873 right = pos() == textRow().pos();
1875 left = pos() == textRow().pos();
1876 right = pos() == textRow().endpos();
1878 if ((!left && !right) ||
1879 (left && !right && xo < x_target_) ||
1880 (!left && right && x_target_ < xo))
1887 // first get the current line
1888 TextMetrics & tm = bv_->textMetrics(text());
1889 ParagraphMetrics const & pm = tm.parMetrics(pit());
1891 if (pos() && boundary())
1892 row = pm.pos2row(pos() - 1);
1894 row = pm.pos2row(pos());
1896 if (atFirstOrLastRow(up)) {
1897 // Is there a place for the cursor to go ? If yes, we
1898 // can execute the DEPM, otherwise we should keep the
1899 // paragraph to host the cursor.
1900 Cursor dummy = *this;
1901 bool valid_destination = false;
1902 for(; dummy.depth(); dummy.pop())
1903 if (!dummy.atFirstOrLastRow(up)) {
1904 valid_destination = true;
1908 // will a next dispatch follow and if there is a new
1909 // dispatch will it move the cursor out ?
1910 if (depth() > 1 && valid_destination) {
1911 // The cursor hasn't changed yet. This happens when
1912 // you e.g. move out of an inset. And to give the
1913 // DEPM the possibility of doing something we must
1914 // provide it with two different cursors. (Lgb, vfr)
1916 dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
1917 dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
1919 updateNeeded |= bv().checkDepm(dummy, *this);
1920 updateTextTargetOffset();
1922 forceBufferUpdate();
1927 // with and without selection are handled differently
1929 int yo = bv().getPos(*this).y_;
1931 // To next/previous row
1933 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1935 tm.editXY(*this, xo, yo + textRow().descent() + 1);
1938 // This happens when you move out of an inset.
1939 // And to give the DEPM the possibility of doing
1940 // something we must provide it with two different
1942 Cursor dummy = *this;
1945 if (bv().checkDepm(dummy, old)) {
1946 updateNeeded = true;
1947 // Make sure that cur gets back whatever happened to dummy (Lgb)
1950 if (pos() && paragraph().isEnvSeparator(pos() - 1))
1953 // if there is a selection, we stay out of any inset,
1954 // and just jump to the right position:
1960 } else if (pit() > 0) {
1962 TextMetrics & tm = bv_->textMetrics(text());
1963 if (!tm.contains(pit()))
1964 tm.newParMetricsUp();
1965 ParagraphMetrics const & pmcur = tm.parMetrics(pit());
1966 next_row = pmcur.rows().size() - 1;
1969 if (row + 1 < int(pm.rows().size())) {
1971 } else if (pit() + 1 < int(text()->paragraphs().size())) {
1973 TextMetrics & tm = bv_->textMetrics(text());
1974 if (!tm.contains(pit()))
1975 tm.newParMetricsDown();
1980 Row const & real_next_row = tm.parMetrics(pit()).rows()[next_row];
1982 top().pos() = tm.getPosNearX(real_next_row, xo, bound);
1985 updateNeeded |= bv().checkDepm(*this, old);
1989 forceBufferUpdate();
1990 updateTextTargetOffset();
1995 void Cursor::handleFont(string const & font)
1997 LYXERR(Debug::DEBUG, font);
2001 safe = cap::grabAndEraseSelection(*this);
2006 if (lastpos() != 0) {
2007 // something left in the cell
2009 // cursor in first position
2011 } else if (pos() == lastpos()) {
2012 // cursor in last position
2015 // cursor in between. split cell
2016 MathData::iterator bt = cell().begin();
2017 MathAtom at = createInsetMath(from_utf8(font), buffer());
2018 at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
2019 cell().erase(bt, bt + pos());
2024 // nothing left in the cell
2033 void Cursor::message(docstring const & msg) const
2035 disp_.setMessage(msg);
2039 void Cursor::errorMessage(docstring const & msg) const
2041 disp_.setMessage(msg);
2042 disp_.setError(true);
2048 docstring parbreak(Cursor const * cur)
2050 odocstringstream os;
2052 // only add blank line if we're not in a ParbreakIsNewline situation
2053 if (!cur->inset().getLayout().parbreakIsNewline()
2054 && !cur->paragraph().layout().parbreak_is_newline)
2062 docstring Cursor::selectionAsString(bool with_label) const
2068 return cap::grabSelection(*this);
2070 int const label = with_label
2071 ? AS_STR_LABEL | AS_STR_INSETS : AS_STR_INSETS;
2073 idx_type const startidx = selBegin().idx();
2074 idx_type const endidx = selEnd().idx();
2075 if (startidx != endidx) {
2076 // multicell selection
2077 InsetTabular * table = inset().asInsetTabular();
2078 LASSERT(table, return docstring());
2079 return table->asString(startidx, endidx);
2082 ParagraphList const & pars = text()->paragraphs();
2084 pit_type const startpit = selBegin().pit();
2085 pit_type const endpit = selEnd().pit();
2086 size_t const startpos = selBegin().pos();
2087 size_t const endpos = selEnd().pos();
2089 if (startpit == endpit)
2090 return pars[startpit].asString(startpos, endpos, label);
2092 // First paragraph in selection
2093 docstring result = pars[startpit].
2094 asString(startpos, pars[startpit].size(), label)
2097 // The paragraphs in between (if any)
2098 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
2099 Paragraph const & par = pars[pit];
2100 result += par.asString(0, par.size(), label)
2104 // Last paragraph in selection
2105 result += pars[endpit].asString(0, endpos, label);
2111 docstring Cursor::currentState() const
2114 odocstringstream os;
2116 #ifdef DEVEL_VERSION
2117 InsetMath * math = inset().asInsetMath();
2119 os << _(", Inset: ") << math->id();
2120 os << _(", Cell: ") << idx();
2121 os << _(", Position: ") << pos();
2127 return text()->currentState(*this);
2133 docstring Cursor::getPossibleLabel() const
2135 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
2139 Encoding const * Cursor::getEncoding() const
2143 CursorSlice const & sl = innerTextSlice();
2144 Text const & text = *sl.text();
2145 Font font = text.getPar(sl.pit()).getFont(
2146 bv().buffer().params(), sl.pos(), text.outerFont(sl.pit()));
2147 return font.language()->encoding();
2151 void Cursor::undispatched() const
2153 disp_.dispatched(false);
2157 void Cursor::dispatched() const
2159 disp_.dispatched(true);
2163 void Cursor::screenUpdateFlags(Update::flags f) const
2165 disp_.screenUpdate(f);
2169 void Cursor::forceBufferUpdate() const
2171 disp_.forceBufferUpdate();
2175 void Cursor::clearBufferUpdate() const
2177 disp_.clearBufferUpdate();
2181 bool Cursor::needBufferUpdate() const
2183 return disp_.needBufferUpdate();
2187 void Cursor::noScreenUpdate() const
2189 disp_.screenUpdate(Update::None);
2193 Font Cursor::getFont() const
2195 // The logic here should more or less match to the
2196 // Cursor::setCurrentFont logic, i.e. the cursor height should
2197 // give a hint what will happen if a character is entered.
2199 // HACK. far from being perfect...
2201 CursorSlice const & sl = innerTextSlice();
2202 Text const & text = *sl.text();
2203 Paragraph const & par = text.getPar(sl.pit());
2205 // on boundary, so we are really at the character before
2206 pos_type pos = sl.pos();
2207 if (pos > 0 && boundary())
2210 // on space? Take the font before (only for RTL boundary stay)
2212 TextMetrics const & tm = bv().textMetrics(&text);
2213 if (pos == sl.lastpos()
2214 || (par.isSeparator(pos)
2215 && !tm.isRTLBoundary(sl.pit(), pos)))
2219 // get font at the position
2220 Font font = par.getFont(buffer()->params(), pos,
2221 text.outerFont(sl.pit()));
2227 bool Cursor::fixIfBroken()
2229 bool const broken_cursor = DocIterator::fixIfBroken();
2230 bool const broken_anchor = anchor_.fixIfBroken();
2232 if (broken_cursor || broken_anchor) {
2233 clearNewWordPosition();
2241 void Cursor::sanitize()
2243 setBuffer(&bv_->buffer());
2244 DocIterator::sanitize();
2252 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2254 // find inset in common
2256 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2257 if (&old[i].inset() != &cur[i].inset())
2261 // update words if we just moved to another paragraph
2262 if (i == old.depth() && i == cur.depth()
2263 && !cur.buffer()->isClean()
2264 && cur.inTexted() && old.inTexted()
2265 && cur.pit() != old.pit()) {
2266 old.paragraph().updateWords();
2269 // notify everything on top of the common part in old cursor,
2270 // but stop if the inset claims the cursor to be invalid now
2271 for (size_type j = i; j < old.depth(); ++j) {
2272 Cursor inset_pos = old;
2273 inset_pos.cutOff(j);
2274 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2278 // notify everything on top of the common part in new cursor,
2279 // but stop if the inset claims the cursor to be invalid now
2280 for (; i < cur.depth(); ++i) {
2281 if (cur[i].inset().notifyCursorEnters(cur))
2289 void Cursor::setCurrentFont()
2291 CursorSlice const & cs = innerTextSlice();
2292 Paragraph const & par = cs.paragraph();
2293 pos_type cpit = cs.pit();
2294 pos_type cpos = cs.pos();
2295 Text const & ctext = *cs.text();
2296 TextMetrics const & tm = bv().textMetrics(&ctext);
2298 // are we behind previous char in fact? -> go to that char
2299 if (cpos > 0 && boundary())
2302 // find position to take the font from
2304 // paragraph end? -> font of last char
2305 if (cpos == lastpos())
2307 // on space? -> look at the words in front of space
2308 else if (cpos > 0 && par.isSeparator(cpos)) {
2309 // abc| def -> font of c
2310 // abc |[WERBEH], i.e. boundary==true -> font of c
2311 // abc [WERBEH]| def, font of the space
2312 if (!tm.isRTLBoundary(cpit, cpos))
2318 BufferParams const & bufparams = buffer()->params();
2319 current_font = par.getFontSettings(bufparams, cpos);
2320 real_current_font = tm.displayFont(cpit, cpos);
2322 // special case for paragraph end
2323 if (cs.pos() == lastpos()
2324 && tm.isRTLBoundary(cpit, cs.pos())
2326 Language const * lang = par.getParLanguage(bufparams);
2327 current_font.setLanguage(lang);
2328 current_font.fontInfo().setNumber(FONT_OFF);
2329 real_current_font.setLanguage(lang);
2330 real_current_font.fontInfo().setNumber(FONT_OFF);
2335 bool Cursor::textUndo()
2337 if (!buffer()->undo().textUndo(*this))
2344 bool Cursor::textRedo()
2346 if (!buffer()->undo().textRedo(*this))
2353 void Cursor::finishUndo() const
2355 buffer()->undo().finishUndo();
2359 void Cursor::beginUndoGroup() const
2361 buffer()->undo().beginUndoGroup(*this);
2365 void Cursor::endUndoGroup() const
2367 buffer()->undo().endUndoGroup(*this);
2371 void Cursor::recordUndo(pit_type from, pit_type to) const
2373 buffer()->undo().recordUndo(*this, from, to);
2377 void Cursor::recordUndo(pit_type from) const
2379 buffer()->undo().recordUndo(*this, from, pit());
2383 void Cursor::recordUndo(UndoKind kind) const
2385 buffer()->undo().recordUndo(*this, kind);
2389 void Cursor::recordUndoInset(Inset const * in) const
2391 buffer()->undo().recordUndoInset(*this, in);
2395 void Cursor::recordUndoFullBuffer() const
2397 buffer()->undo().recordUndoFullBuffer(*this);
2401 void Cursor::recordUndoBufferParams() const
2403 buffer()->undo().recordUndoBufferParams(*this);
2407 void Cursor::recordUndoSelection() const
2410 if (cap::multipleCellsSelected(*this))
2415 buffer()->undo().recordUndo(*this,
2416 selBegin().pit(), selEnd().pit());
2421 void Cursor::checkBufferStructure()
2423 Buffer const * master = buffer()->masterBuffer();
2424 master->tocBackend().updateItem(*this);
2425 if (master != buffer() && !master->hasGuiDelegate())
2426 // In case the master has no gui associated with it,
2427 // the TocItem is not updated (part of bug 5699).
2428 buffer()->tocBackend().updateItem(*this);