3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alejandro Aguilar Sierra
7 * \author Alfredo Braunstein
8 * \author Dov Feldstern
10 * \author Stefan Schimanski
12 * Full author contact details are available in file CREDITS.
19 #include "BufferView.h"
20 #include "CoordCache.h"
22 #include "CutAndPaste.h"
23 #include "DispatchResult.h"
27 #include "FuncRequest.h"
30 #include "LyXAction.h"
32 #include "Paragraph.h"
33 #include "ParIterator.h"
36 #include "TextMetrics.h"
37 #include "TocBackend.h"
39 #include "support/debug.h"
40 #include "support/docstream.h"
41 #include "support/ExceptionMessage.h"
42 #include "support/gettext.h"
43 #include "support/lassert.h"
45 #include "insets/InsetTabular.h"
46 #include "insets/InsetText.h"
48 #include "mathed/InsetMath.h"
49 #include "mathed/InsetMathBrace.h"
50 #include "mathed/InsetMathScript.h"
51 #include "mathed/MacroTable.h"
52 #include "mathed/MathData.h"
53 #include "mathed/MathMacro.h"
55 #include "support/bind.h"
68 // Find position closest to (x, y) in cell given by iter.
69 // Used only in mathed
70 DocIterator bruteFind2(Cursor const & c, int x, int y)
72 double best_dist = numeric_limits<double>::max();
79 et.top().pos() = et.top().asInsetMath()->cell(et.top().idx()).size();
80 for (size_t i = 0;; ++i) {
83 Inset const * inset = &it.inset();
84 CoordCache const & cache = c.bv().coordCache();
86 // FIXME: in the case where the inset is not in the cache, this
87 // means that no part of it is visible on screen. In this case
88 // we don't do elaborate search and we just return the forwarded
89 // DocIterator at its beginning.
90 if (!cache.getInsets().has(inset)) {
95 Point const o = cache.getInsets().xy(inset);
96 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
97 // Convert to absolute
100 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
101 // '<=' in order to take the last possible position
102 // this is important for clicking behind \sum in e.g. '\sum_i a'
103 LYXERR(Debug::DEBUG, "i: " << i << " d: " << d
104 << " best: " << best_dist);
105 if (d <= best_dist) {
118 /// moves position closest to (x, y) in given box
119 bool bruteFind(Cursor & cursor,
120 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
122 LASSERT(!cursor.empty(), return false);
123 Inset & inset = cursor[0].inset();
124 BufferView & bv = cursor.bv();
126 CoordCache::InnerParPosCache const & cache =
127 bv.coordCache().getParPos().find(cursor.bottom().text())->second;
128 // Get an iterator on the first paragraph in the cache
129 DocIterator it(inset);
130 it.push_back(CursorSlice(inset));
131 it.pit() = cache.begin()->first;
132 // Get an iterator after the last paragraph in the cache
133 DocIterator et(inset);
134 et.push_back(CursorSlice(inset));
135 et.pit() = prev(cache.end(), 1)->first;
136 if (et.pit() >= et.lastpit())
137 et = doc_iterator_end(inset);
141 double best_dist = numeric_limits<double>::max();
142 DocIterator best_cursor = et;
144 for ( ; it != et; it.forwardPos(true)) {
145 // avoid invalid nesting when selecting
146 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
147 Point p = bv.getPos(it, false);
150 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
151 double const dx = xo - x;
152 double const dy = yo - y;
153 double const d = dx * dx + dy * dy;
154 // '<=' in order to take the last possible position
155 // this is important for clicking behind \sum in e.g. '\sum_i a'
156 if (d <= best_dist) {
157 // lyxerr << "*" << endl;
165 if (best_cursor != et) {
166 cursor.setCursor(best_cursor);
175 /// moves position closest to (x, y) in given box
176 bool bruteFind3(Cursor & cur, int x, int y, bool up)
178 BufferView & bv = cur.bv();
179 int ylow = up ? 0 : y + 1;
180 int yhigh = up ? y - 1 : bv.workHeight();
182 int xhigh = bv.workWidth();
184 // FIXME: bit more work needed to get 'from' and 'to' right.
185 pit_type from = cur.bottom().pit();
186 //pit_type to = cur.bottom().pit();
187 //lyxerr << "Pit start: " << from << endl;
189 //lyxerr << "bruteFind3: x: " << x << " y: " << y
190 // << " xlow: " << xlow << " xhigh: " << xhigh
191 // << " ylow: " << ylow << " yhigh: " << yhigh
193 DocIterator it = doc_iterator_begin(cur.buffer());
195 DocIterator et = doc_iterator_end(cur.buffer());
197 double best_dist = numeric_limits<double>::max();
198 DocIterator best_cursor = et;
200 for ( ; it != et; it.forwardPos()) {
201 // avoid invalid nesting when selecting
202 if (bv.cursorStatus(it) == CUR_INSIDE
203 && (!cur.selection() || positionable(it, cur.realAnchor()))) {
204 // If this function is ever used again, check
205 // whether this is the same as "bv.getPos(it,
206 // false)" with boundary = false.
207 Point p = bv.getPos(it);
210 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
211 double const dx = xo - x;
212 double const dy = yo - y;
213 double const d = dx * dx + dy * dy;
214 //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
215 // << " dx: " << dx << " dy: " << dy
216 // << " idx: " << it.idx() << " pos: " << it.pos()
219 // '<=' in order to take the last possible position
220 // this is important for clicking behind \sum in e.g. '\sum_i a'
221 if (d <= best_dist) {
222 //lyxerr << "*" << endl;
230 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
231 if (best_cursor == et)
233 cur.setCursor(best_cursor);
240 CursorData::CursorData()
241 : DocIterator(), anchor_(),
242 selection_(false), mark_(false), word_selection_(false),
243 logicalpos_(false), current_font(inherit_font),
244 autocorrect_(false), macromode_(false)
248 CursorData::CursorData(Buffer * buffer)
249 : DocIterator(buffer), anchor_(),
250 selection_(false), mark_(false), word_selection_(false),
251 logicalpos_(false), current_font(inherit_font),
252 autocorrect_(false), macromode_(false)
256 CursorData::CursorData(DocIterator const & dit)
257 : DocIterator(dit), anchor_(),
258 selection_(false), mark_(false), word_selection_(false),
259 logicalpos_(false), current_font(inherit_font),
260 autocorrect_(false), macromode_(false)
266 ostream & operator<<(ostream & os, CursorData const & cur)
268 os << "\n cursor: | anchor:\n";
269 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
270 os << " " << cur[i] << " | ";
271 if (i < cur.anchor_.depth())
272 os << cur.anchor_[i];
274 os << "-------------------------------";
277 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
278 os << "------------------------------- | " << cur.anchor_[i] << "\n";
280 os << " selection: " << cur.selection_
281 // << " x_target: " << cur.x_target_
282 << " boundary: " << cur.boundary() << endl;
287 LyXErr & operator<<(LyXErr & os, CursorData const & cur)
294 // be careful: this is called from the bv's constructor, too, so
295 // bv functions are not yet available!
296 Cursor::Cursor(BufferView & bv)
297 : CursorData(&bv.buffer()), bv_(&bv),
298 x_target_(-1), textTargetOffset_(0),
299 beforeDispatchPosX_(0), beforeDispatchPosY_(0)
306 push_back(CursorSlice(buffer()->inset()));
307 anchor_ = doc_iterator_begin(buffer());
309 new_word_ = doc_iterator_begin(buffer());
317 // this (intentionally) does neither touch anchor nor selection status
318 void Cursor::setCursor(DocIterator const & cur)
320 DocIterator::operator=(cur);
324 void Cursor::setCursorToAnchor()
327 DocIterator normal = anchor_;
328 while (depth() < normal.depth())
330 if (depth() < anchor_.depth() && top() <= anchor_[depth() - 1])
337 void Cursor::setCursorData(CursorData const & data)
339 CursorData::operator=(data);
343 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
347 // Try to fix cursor in case it is broken.
350 // Is this a function that acts on inset at point?
351 Inset * inset = cur.nextInset();
352 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
353 && inset && inset->getStatus(cur, cmd, status))
356 // This is, of course, a mess. Better create a new doc iterator and use
357 // this in Inset::getStatus. This might require an additional
358 // BufferView * arg, though (which should be avoided)
359 //Cursor safe = *this;
361 for ( ; cur.depth(); cur.pop()) {
362 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
363 // LASSERT: Is it safe to continue here, or should we return?
364 LASSERT(cur.idx() <= cur.lastidx(), /**/);
365 LASSERT(cur.pit() <= cur.lastpit(), /**/);
366 LASSERT(cur.pos() <= cur.lastpos(), /**/);
368 // The inset's getStatus() will return 'true' if it made
369 // a definitive decision on whether it want to handle the
370 // request or not. The result of this decision is put into
371 // the 'status' parameter.
372 if (cur.inset().getStatus(cur, cmd, status)) {
381 void Cursor::saveBeforeDispatchPosXY()
383 getPos(beforeDispatchPosX_, beforeDispatchPosY_);
387 void Cursor::dispatch(FuncRequest const & cmd0)
389 LYXERR(Debug::ACTION, "Cursor::dispatch: cmd: " << cmd0 << '\n' << *this);
394 FuncRequest cmd = cmd0;
397 disp_ = DispatchResult();
401 // Is this a function that acts on inset at point?
402 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
404 disp_.dispatched(true);
405 disp_.screenUpdate(Update::FitCursor | Update::Force);
406 FuncRequest tmpcmd = cmd;
407 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
408 << cmd0 << endl << *this);
409 nextInset()->dispatch(*this, tmpcmd);
410 if (disp_.dispatched()) {
416 // store some values to be used inside of the handlers
417 beforeDispatchCursor_ = *this;
418 for (; depth(); pop(), boundary(false)) {
419 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
420 << cmd0 << endl << *this);
422 // In any of these cases, the cursor is invalid, and we should
423 // try to save this document rather than crash.
424 LBUFERR(pos() <= lastpos());
425 LBUFERR(idx() <= lastidx());
426 LBUFERR(pit() <= lastpit());
428 // The common case is 'LFUN handled, need update', so make the
429 // LFUN handler's life easier by assuming this as default value.
430 // The handler can reset the update and val flags if necessary.
431 disp_.screenUpdate(Update::FitCursor | Update::Force);
432 disp_.dispatched(true);
433 inset().dispatch(*this, cmd);
434 if (disp_.dispatched())
438 // it completely to get a 'bomb early' behaviour in case this
439 // object will be used again.
440 if (!disp_.dispatched()) {
441 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
442 // We might have invalidated the cursor when removing an empty
443 // paragraph while the cursor could not be moved out the inset
444 // while we initially thought we could. This might happen when
445 // a multiline inset becomes an inline inset when the second
446 // paragraph is removed.
447 if (safe.pit() > safe.lastpit()) {
448 safe.pit() = safe.lastpit();
449 safe.pos() = safe.lastpos();
452 disp_.screenUpdate(Update::None);
453 disp_.dispatched(false);
455 // restore the previous one because nested Cursor::dispatch calls
456 // are possible which would change it
457 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
461 // NOTE: The code below has been copied to BufferView::dispatch.
462 // If you need to modify this, please update the other one too.
464 // notify insets we just left
466 old.beginUndoGroup();
468 bool badcursor = notifyCursorLeavesOrEnters(old, *this);
471 bv().resetInlineCompletionPos();
478 DispatchResult const & Cursor::result() const
484 BufferView & Cursor::bv() const
493 LBUFERR(depth() >= 1);
498 void Cursor::push(Inset & p)
500 push_back(CursorSlice(p));
501 p.setBuffer(*buffer());
505 void Cursor::pushBackward(Inset & p)
507 LASSERT(!empty(), return);
508 //lyxerr << "Entering inset " << t << " front" << endl;
514 bool Cursor::popBackward()
516 LASSERT(!empty(), return false);
524 bool Cursor::popForward()
526 LASSERT(!empty(), return false);
527 //lyxerr << "Leaving inset from in back" << endl;
528 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
532 pos() += lastpos() - lp + 1;
537 int Cursor::currentMode()
539 LASSERT(!empty(), return Inset::UNDECIDED_MODE);
540 for (int i = depth() - 1; i >= 0; --i) {
541 int res = operator[](i).inset().currentMode();
542 bool locked_mode = operator[](i).inset().lockedMode();
543 // Also return UNDECIDED_MODE when the mode is locked,
544 // as in this case it is treated the same as TEXT_MODE
545 if (res != Inset::UNDECIDED_MODE || locked_mode)
548 return Inset::TEXT_MODE;
552 void Cursor::getPos(int & x, int & y) const
554 Point p = bv().getPos(*this);
560 Row const & Cursor::textRow() const
562 CursorSlice const & cs = innerTextSlice();
563 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
564 return pm.getRow(pos(), boundary());
568 void Cursor::resetAnchor()
571 checkNewWordPosition();
575 void Cursor::markNewWordPosition()
577 if (lyxrc.spellcheck_continuously && inTexted() && new_word_.empty()) {
578 FontSpan nw = locateWord(WHOLE_WORD);
579 if (nw.size() == 1) {
580 LYXERR(Debug::DEBUG, "start new word: "
582 << " pos: " << nw.first);
589 void Cursor::clearNewWordPosition()
591 if (!new_word_.empty()) {
592 LYXERR(Debug::DEBUG, "clear new word: "
594 << " pos: " << pos());
600 void Cursor::checkNewWordPosition()
602 if (!lyxrc.spellcheck_continuously || new_word_.empty())
605 clearNewWordPosition();
607 // forget the position of the current new word if
608 // 1) the paragraph changes or
609 // 2) the count of nested insets changes or
610 // 3) the cursor pos is out of paragraph bound
611 if (pit() != new_word_.pit() ||
612 depth() != new_word_.depth() ||
613 new_word_.pos() > new_word_.lastpos()) {
614 clearNewWordPosition();
615 } else if (new_word_.fixIfBroken())
616 // 4) or the remembered position was "broken"
617 clearNewWordPosition();
619 FontSpan nw = locateWord(WHOLE_WORD);
621 FontSpan ow = new_word_.locateWord(WHOLE_WORD);
622 if (nw.intersect(ow).empty())
623 clearNewWordPosition();
625 LYXERR(Debug::DEBUG, "new word: "
627 << " pos: " << nw.first << ".." << nw.last);
629 clearNewWordPosition();
636 bool Cursor::posBackward()
645 bool Cursor::posForward()
647 if (pos() == lastpos())
654 bool Cursor::posVisRight(bool skip_inset)
656 Cursor new_cur = *this; // where we will move to
657 pos_type left_pos; // position visually left of current cursor
658 pos_type right_pos; // position visually right of current cursor
660 getSurroundingPos(left_pos, right_pos);
662 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
664 // Are we at an inset?
665 new_cur.pos() = right_pos;
666 new_cur.boundary(false);
668 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
669 // we actually move the cursor at the end of this
670 // function, for now we just keep track of the new
671 // position in new_cur...
672 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
675 // Are we already at rightmost pos in row?
676 else if (text()->empty() || right_pos == -1) {
679 if (!new_cur.posVisToNewRow(false)) {
680 LYXERR(Debug::RTL, "not moving!");
684 // we actually move the cursor at the end of this
685 // function, for now just keep track of the new
686 // position in new_cur...
687 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
688 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
691 // normal movement to the right
694 // Recall, if the cursor is at position 'x', that
695 // means *before* the character at position 'x'. In
696 // RTL, "before" means "to the right of", in LTR, "to
697 // the left of". So currently our situation is this:
698 // the position to our right is 'right_pos' (i.e.,
699 // we're currently to the left of 'right_pos'). In
700 // order to move to the right, it depends whether or
701 // not the character at 'right_pos' is RTL.
702 bool const new_pos_is_RTL = paragraph().getFontSettings(
703 buffer()->params(), right_pos).isVisibleRightToLeft();
704 // If the character at 'right_pos' *is* LTR, then in
705 // order to move to the right of it, we need to be
706 // *after* 'right_pos', i.e., move to position
708 if (!new_pos_is_RTL) {
709 new_cur.pos() = right_pos + 1;
710 // set the boundary to true in two situations:
712 // 1. if new_pos is now lastpos, and we're in
713 // an RTL paragraph (this means that we're
714 // moving right to the end of an LTR chunk
715 // which is at the end of an RTL paragraph);
716 (new_cur.pos() == lastpos()
717 && paragraph().isRTL(buffer()->params()))
718 // 2. if the position *after* right_pos is RTL
719 // (we want to be *after* right_pos, not
720 // before right_pos + 1!)
721 || paragraph().getFontSettings(buffer()->params(),
722 new_cur.pos()).isVisibleRightToLeft()
724 new_cur.boundary(true);
725 else // set the boundary to false
726 new_cur.boundary(false);
728 // Otherwise (if the character at position 'right_pos'
729 // is RTL), then moving to the right of it is as easy
730 // as setting the new position to 'right_pos'.
732 new_cur.pos() = right_pos;
733 new_cur.boundary(false);
738 bool moved = (new_cur.pos() != pos()
739 || new_cur.pit() != pit()
740 || new_cur.boundary() != boundary()
741 || &new_cur.inset() != &inset());
744 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
745 << (new_cur.boundary() ? " (boundary)" : ""));
753 bool Cursor::posVisLeft(bool skip_inset)
755 Cursor new_cur = *this; // where we will move to
756 pos_type left_pos; // position visually left of current cursor
757 pos_type right_pos; // position visually right of current cursor
759 getSurroundingPos(left_pos, right_pos);
761 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
763 // Are we at an inset?
764 new_cur.pos() = left_pos;
765 new_cur.boundary(false);
767 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
768 // we actually move the cursor at the end of this
769 // function, for now we just keep track of the new
770 // position in new_cur...
771 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
774 // Are we already at leftmost pos in row?
775 else if (text()->empty() || left_pos == -1) {
778 if (!new_cur.posVisToNewRow(true)) {
779 LYXERR(Debug::RTL, "not moving!");
783 // we actually move the cursor at the end of this
784 // function, for now just keep track of the new
785 // position in new_cur...
786 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
787 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
790 // normal movement to the left
793 // Recall, if the cursor is at position 'x', that
794 // means *before* the character at position 'x'. In
795 // RTL, "before" means "to the right of", in LTR, "to
796 // the left of". So currently our situation is this:
797 // the position to our left is 'left_pos' (i.e., we're
798 // currently to the right of 'left_pos'). In order to
799 // move to the left, it depends whether or not the
800 // character at 'left_pos' is RTL.
801 bool const new_pos_is_RTL = paragraph().getFontSettings(
802 buffer()->params(), left_pos).isVisibleRightToLeft();
803 // If the character at 'left_pos' *is* RTL, then in
804 // order to move to the left of it, we need to be
805 // *after* 'left_pos', i.e., move to position
807 if (new_pos_is_RTL) {
808 new_cur.pos() = left_pos + 1;
809 // set the boundary to true in two situations:
811 // 1. if new_pos is now lastpos and we're in
812 // an LTR paragraph (this means that we're
813 // moving left to the end of an RTL chunk
814 // which is at the end of an LTR paragraph);
815 (new_cur.pos() == lastpos()
816 && !paragraph().isRTL(buffer()->params()))
817 // 2. if the position *after* left_pos is not
818 // RTL (we want to be *after* left_pos, not
819 // before left_pos + 1!)
820 || !paragraph().getFontSettings(buffer()->params(),
821 new_cur.pos()).isVisibleRightToLeft()
823 new_cur.boundary(true);
824 else // set the boundary to false
825 new_cur.boundary(false);
827 // Otherwise (if the character at position 'left_pos'
828 // is LTR), then moving to the left of it is as easy
829 // as setting the new position to 'left_pos'.
831 new_cur.pos() = left_pos;
832 new_cur.boundary(false);
837 bool moved = (new_cur.pos() != pos()
838 || new_cur.pit() != pit()
839 || new_cur.boundary() != boundary());
842 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
843 << (new_cur.boundary() ? " (boundary)" : ""));
851 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos)
853 // preparing bidi tables
854 Paragraph const & par = paragraph();
855 Buffer const & buf = *buffer();
856 Row const & row = textRow();
858 bidi.computeTables(par, buf, row);
860 LYXERR(Debug::RTL, "bidi: " << row.pos() << "--" << row.endpos());
862 // The cursor is painted *before* the character at pos(), or,
863 // if 'boundary' is true, *after* the character at (pos() -
864 // 1). So we already have one known position around the
866 pos_type const known_pos = boundary() && pos() > 0 ? pos() - 1 : pos();
868 // edge case: if we're at the end of the paragraph, things are
869 // a little different (because lastpos is a position which
870 // does not really "exist" --- there's no character there
872 if (known_pos == lastpos()) {
873 if (par.isRTL(buf.params())) {
875 right_pos = bidi.vis2log(row.pos());
879 left_pos = bidi.vis2log(row.endpos() - 1);
884 // Whether 'known_pos' is to the left or to the right of the
885 // cursor depends on whether it is an RTL or LTR character...
886 bool const cur_is_RTL =
887 par.getFontSettings(buf.params(), known_pos).isVisibleRightToLeft();
888 // ... in the following manner:
889 // For an RTL character, "before"
890 // means "to the right" and "after" means "to the left"; and
891 // for LTR, it's the reverse. So, 'known_pos' is to the right
892 // of the cursor if (RTL && boundary) or (!RTL && !boundary):
893 bool const known_pos_on_right = cur_is_RTL == boundary();
895 // So we now know one of the positions surrounding the cursor.
896 // Let's determine the other one:
897 if (known_pos_on_right) {
898 right_pos = known_pos;
899 // *visual* position of 'left_pos':
900 pos_type v_left_pos = bidi.log2vis(right_pos) - 1;
901 // If the position we just identified as 'left_pos' is
902 // a "skipped separator" (a separator which is at the
903 // logical end of a row, except for the last row in a
904 // paragraph; such separators are not painted, so they
905 // "are not really there"; note that in bidi text,
906 // such a separator could appear visually in the
907 // middle of a row), set 'left_pos' to the *next*
908 // position to the left.
909 if (bidi.inRange(v_left_pos)
910 && bidi.vis2log(v_left_pos) + 1 == row.endpos()
911 && row.endpos() < lastpos()
912 && par.isSeparator(bidi.vis2log(v_left_pos)))
915 // calculate the logical position of 'left_pos', if in row
916 if (!bidi.inRange(v_left_pos))
919 left_pos = bidi.vis2log(v_left_pos);
920 // If the position we identified as 'right_pos' is a
921 // "skipped separator", set 'right_pos' to the *next*
922 // position to the right.
923 if (right_pos + 1 == row.endpos() && row.endpos() < lastpos()
924 && par.isSeparator(right_pos)) {
925 pos_type const v_right_pos = bidi.log2vis(right_pos) + 1;
926 if (!bidi.inRange(v_right_pos))
929 right_pos = bidi.vis2log(v_right_pos);
932 // known_pos is on the left
933 left_pos = known_pos;
934 // *visual* position of 'right_pos'
935 pos_type v_right_pos = bidi.log2vis(left_pos) + 1;
936 // If the position we just identified as 'right_pos'
937 // is a "skipped separator", set 'right_pos' to the
938 // *next* position to the right.
939 if (bidi.inRange(v_right_pos)
940 && bidi.vis2log(v_right_pos) + 1 == row.endpos()
941 && row.endpos() < lastpos()
942 && par.isSeparator(bidi.vis2log(v_right_pos)))
945 // calculate the logical position of 'right_pos', if in row
946 if (!bidi.inRange(v_right_pos))
949 right_pos = bidi.vis2log(v_right_pos);
950 // If the position we identified as 'left_pos' is a
951 // "skipped separator", set 'left_pos' to the *next*
952 // position to the left.
953 if (left_pos + 1 == row.endpos() && row.endpos() < lastpos()
954 && par.isSeparator(left_pos)) {
955 pos_type const v_left_pos = bidi.log2vis(left_pos) - 1;
956 if (!bidi.inRange(v_left_pos))
959 left_pos = bidi.vis2log(v_left_pos);
966 bool Cursor::posVisToNewRow(bool movingLeft)
968 Paragraph const & par = paragraph();
969 Buffer const & buf = *buffer();
970 Row const & row = textRow();
971 bool par_is_LTR = !par.isRTL(buf.params());
973 // Inside a table, determining whether to move to the next or
974 // previous row should be done based on the table's direction.
976 if (s >= 1 && (*this)[s].inset().asInsetTabular()) {
977 par_is_LTR = !(*this)[s].inset().asInsetTabular()->isRightToLeft(*this);
978 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
981 // if moving left in an LTR paragraph or moving right in an
982 // RTL one, move to previous row
983 if (par_is_LTR == movingLeft) {
984 if (row.pos() == 0) { // we're at first row in paragraph
985 if (pit() == 0) // no previous paragraph! don't move
987 // move to last pos in previous par
991 } else { // move to previous row in this par
992 pos() = row.pos() - 1; // this is guaranteed to be in previous row
996 // if moving left in an RTL paragraph or moving right in an
997 // LTR one, move to next row
999 if (row.endpos() == lastpos()) { // we're at last row in paragraph
1000 if (pit() == lastpit()) // last paragraph! don't move
1002 // move to first row in next par
1006 } else { // move to next row in this par
1007 pos() = row.endpos();
1012 // make sure we're at left-/right-most pos in new row
1013 posVisToRowExtremity(!movingLeft);
1019 void Cursor::posVisToRowExtremity(bool left)
1021 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
1022 << (boundary() ? 1 : 0));
1024 TextMetrics const & tm = bv_->textMetrics(text());
1025 // Looking for extremities is like clicking on the left or the
1026 // right of the row.
1027 int x = tm.origin().x_ + (left ? 0 : textRow().width());
1029 pos() = tm.getPosNearX(textRow(), x, b);
1032 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
1033 << (boundary() ? 1 : 0));
1037 bool Cursor::reverseDirectionNeeded() const
1040 * We determine the directions based on the direction of the
1041 * bottom() --- i.e., outermost --- paragraph, because that is
1042 * the only way to achieve consistency of the arrow's movements
1043 * within a paragraph, and thus avoid situations in which the
1044 * cursor gets stuck.
1046 return bottom().paragraph().isRTL(bv().buffer().params());
1050 CursorSlice Cursor::normalAnchor() const
1054 // LASSERT: There have been several bugs around this code, that seem
1055 // to involve failures to reset the anchor. We can at least not crash
1056 // in release mode by resetting it ourselves.
1057 LASSERT(anchor_.depth() >= depth(),
1058 const_cast<DocIterator &>(anchor_) = *this);
1060 CursorSlice normal = anchor_[depth() - 1];
1061 if (depth() < anchor_.depth() && top() <= normal) {
1062 // anchor is behind cursor -> move anchor behind the inset
1069 DocIterator & Cursor::realAnchor()
1075 CursorSlice Cursor::selBegin() const
1079 return normalAnchor() < top() ? normalAnchor() : top();
1083 CursorSlice Cursor::selEnd() const
1087 return normalAnchor() > top() ? normalAnchor() : top();
1091 DocIterator Cursor::selectionBegin() const
1097 // FIXME: This is a work-around for the problem that
1098 // CursorSlice doesn't keep track of the boundary.
1099 if (normalAnchor() == top())
1100 di = anchor_.boundary() > boundary() ? anchor_ : *this;
1102 di = normalAnchor() < top() ? anchor_ : *this;
1108 DocIterator Cursor::selectionEnd() const
1114 // FIXME: This is a work-around for the problem that
1115 // CursorSlice doesn't keep track of the boundary.
1116 if (normalAnchor() == top())
1117 di = anchor_.boundary() < boundary() ? anchor_ : *this;
1119 di = normalAnchor() > top() ? anchor_ : *this;
1121 if (di.depth() > depth()) {
1129 void Cursor::setSelection()
1132 if (idx() == normalAnchor().idx() &&
1133 pit() == normalAnchor().pit() &&
1134 pos() == normalAnchor().pos())
1135 setSelection(false);
1139 void Cursor::setSelection(DocIterator const & where, int n)
1148 void Cursor::clearSelection()
1150 setSelection(false);
1151 setWordSelection(false);
1157 void Cursor::setTargetX(int x)
1160 textTargetOffset_ = 0;
1164 int Cursor::x_target() const
1170 void Cursor::clearTargetX()
1173 textTargetOffset_ = 0;
1177 void Cursor::updateTextTargetOffset()
1182 textTargetOffset_ = x - x_target_;
1186 void Cursor::info(odocstream & os) const
1188 for (int i = 1, n = depth(); i < n; ++i) {
1189 operator[](i).inset().infoize(os);
1193 Inset const * inset = prevInset();
1194 // prevInset() can return 0 in certain case.
1196 prevInset()->infoize2(os);
1198 // overwite old message
1203 bool Cursor::selHandle(bool sel)
1205 //lyxerr << "Cursor::selHandle" << endl;
1208 if (sel == selection())
1212 cap::saveSelection(*this);
1221 ///////////////////////////////////////////////////////////////////
1224 // The part below is the non-integrated rest of the original math
1225 // cursor. This should be either generalized for texted or moved
1226 // back to mathed (in most cases to InsetMathNest).
1228 ///////////////////////////////////////////////////////////////////
1230 #include "mathed/InsetMathChar.h"
1231 #include "mathed/InsetMathGrid.h"
1232 #include "mathed/InsetMathScript.h"
1233 #include "mathed/InsetMathUnknown.h"
1234 #include "mathed/MathFactory.h"
1235 #include "mathed/MathStream.h"
1236 #include "mathed/MathSupport.h"
1241 bool Cursor::isInside(Inset const * p) const
1243 for (size_t i = 0; i != depth(); ++i)
1244 if (&operator[](i).inset() == p)
1250 void Cursor::leaveInset(Inset const & inset)
1252 for (size_t i = 0; i != depth(); ++i) {
1253 if (&operator[](i).inset() == &inset) {
1261 bool Cursor::openable(MathAtom const & t) const
1272 // we can't move into anything new during selection
1273 if (depth() >= anchor_.depth())
1275 if (t.nucleus() != &anchor_[depth()].inset())
1282 void Cursor::setScreenPos(int x, int /*y*/)
1285 //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
1290 void Cursor::plainErase()
1292 cell().erase(pos());
1296 void Cursor::markInsert()
1298 insert(char_type(0));
1302 void Cursor::markErase()
1304 cell().erase(pos());
1308 void Cursor::plainInsert(MathAtom const & t)
1310 cell().insert(pos(), t);
1312 inset().setBuffer(bv_->buffer());
1314 forceBufferUpdate();
1318 void Cursor::insert(docstring const & str)
1320 for_each(str.begin(), str.end(),
1321 bind(static_cast<void(Cursor::*)(char_type)>
1322 (&Cursor::insert), this, _1));
1326 void Cursor::insert(char_type c)
1328 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1329 LASSERT(!empty(), return);
1331 cap::selClearOrDel(*this);
1332 insert(new InsetMathChar(c));
1334 text()->insertChar(*this, c);
1339 void Cursor::insert(MathAtom const & t)
1341 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1343 cap::selClearOrDel(*this);
1348 void Cursor::insert(Inset * inset0)
1350 LASSERT(inset0, return);
1352 insert(MathAtom(inset0->asInsetMath()));
1354 text()->insertInset(*this, inset0);
1355 inset0->setBuffer(bv_->buffer());
1357 if (inset0->isLabeled())
1358 forceBufferUpdate();
1363 int Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1365 MathData ar(buffer());
1367 if (ar.size() == 1 && (enter || selection()))
1375 void Cursor::niceInsert(MathAtom const & t)
1378 docstring const safe = cap::grabAndEraseSelection(*this);
1380 // If possible, enter the new inset and move the contents of the selection
1381 if (t->isActive()) {
1383 // be careful here: don't use 'pushBackward(t)' as this we need to
1384 // push the clone, not the original
1385 pushBackward(*nextInset());
1386 // We may not use niceInsert here (recursion)
1387 MathData ar(buffer());
1390 } else if (t->asMacro() && !safe.empty()) {
1391 MathData ar(buffer());
1393 docstring const name = t->asMacro()->name();
1394 MacroData const * data = buffer()->getMacro(name);
1395 if (data && data->numargs() - data->optionals() > 0) {
1396 plainInsert(MathAtom(new InsetMathBrace(ar)));
1403 void Cursor::insert(MathData const & ar)
1407 cap::eraseSelection(*this);
1408 cell().insert(pos(), ar);
1410 // FIXME audit setBuffer calls
1411 inset().setBuffer(bv_->buffer());
1415 bool Cursor::backspace()
1418 cap::eraseSelection(*this);
1423 // If empty cell, and not part of a big cell
1424 if (lastpos() == 0 && inset().nargs() == 1) {
1426 // Directly delete empty cell: [|[]] => [|]
1432 // [|], can not delete from inside
1443 if (inMacroMode()) {
1444 InsetMathUnknown * p = activeMacro();
1445 if (p->name().size() > 1) {
1446 p->setName(p->name().substr(0, p->name().size() - 1));
1451 if (pos() != 0 && prevAtom()->nargs() > 0) {
1452 // let's require two backspaces for 'big stuff' and
1453 // highlight on the first
1465 bool Cursor::erase()
1471 cap::eraseSelection(*this);
1475 // delete empty cells if possible
1476 if (pos() == lastpos() && inset().idxDelete(idx()))
1479 // special behaviour when in last position of cell
1480 if (pos() == lastpos()) {
1481 bool one_cell = inset().nargs() == 1;
1482 if (one_cell && lastpos() == 0) {
1484 // Directly delete empty cell: [|[]] => [|]
1490 // [|], can not delete from inside
1495 inset().idxGlue(idx());
1499 // 'clever' UI hack: only erase large items if previously slected
1500 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
1515 DocIterator save = *this;
1516 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1517 this->dispatch(cmd);
1518 if (disp_.dispatched())
1528 DocIterator save = *this;
1529 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1530 this->dispatch(cmd);
1531 if (disp_.dispatched())
1538 bool Cursor::macroModeClose()
1542 InsetMathUnknown * p = activeMacro();
1544 MathData selection(buffer());
1545 asArray(p->selection(), selection);
1546 docstring const s = p->name();
1548 cell().erase(pos());
1550 // do nothing if the macro name is empty
1554 // trigger updates of macros, at least, if no full
1555 // updates take place anyway
1556 screenUpdateFlags(Update::Force);
1558 docstring const name = s.substr(1);
1559 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1560 if (in && in->interpretString(*this, s))
1562 MathAtom atom = buffer()->getMacro(name, *this, false) ?
1563 MathAtom(new MathMacro(buffer(), name)) : createInsetMath(name, buffer());
1565 // try to put argument into macro, if we just inserted a macro
1566 bool macroArg = false;
1567 MathMacro * atomAsMacro = atom.nucleus()->asMacro();
1569 // macros here are still unfolded (in init mode in fact). So
1570 // we have to resolve the macro here manually and check its arity
1571 // to put the selection behind it if arity > 0.
1572 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1573 if (!selection.empty() && data && data->numargs() - data->optionals() > 0) {
1575 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1577 // non-greedy case. Do not touch the arguments behind
1578 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1581 // insert remembered selection into first argument of a non-macro
1582 else if (atom.nucleus()->nargs() > 0)
1583 atom.nucleus()->cell(0).append(selection);
1587 // finally put the macro argument behind, if needed
1589 if (selection.size() > 1 || selection[0]->asScriptInset())
1590 plainInsert(MathAtom(new InsetMathBrace(selection)));
1599 docstring Cursor::macroName()
1601 return inMacroMode() ? activeMacro()->name() : docstring();
1605 void Cursor::handleNest(MathAtom const & a, int c)
1607 //lyxerr << "Cursor::handleNest: " << c << endl;
1609 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1612 pushBackward(*nextInset());
1616 int Cursor::targetX() const
1618 if (x_target() != -1)
1627 int Cursor::textTargetOffset() const
1629 return textTargetOffset_;
1633 void Cursor::setTargetX()
1642 bool Cursor::inMacroMode() const
1646 if (pos() == 0 || cell().empty())
1648 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1649 return p && !p->final();
1653 InsetMathUnknown * Cursor::activeMacro()
1655 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1659 InsetMathUnknown const * Cursor::activeMacro() const
1661 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1665 void Cursor::pullArg()
1668 MathData ar = cell();
1669 if (popBackward() && inMathed()) {
1671 cell().insert(pos(), ar);
1674 //formula()->mutateToText();
1679 void Cursor::touch()
1683 DocIterator::const_iterator it = begin();
1684 DocIterator::const_iterator et = end();
1685 for ( ; it != et; ++it)
1691 void Cursor::normalize()
1693 if (idx() > lastidx()) {
1694 lyxerr << "this should not really happen - 1: "
1695 << idx() << ' ' << nargs()
1696 << " in: " << &inset() << endl;
1700 if (pos() > lastpos()) {
1701 lyxerr << "this should not really happen - 2: "
1702 << pos() << ' ' << lastpos() << " in idx: " << idx()
1704 odocstringstream os;
1705 WriteStream wi(os, false, true, WriteStream::wsDefault);
1706 inset().asInsetMath()->write(wi);
1707 lyxerr << to_utf8(os.str()) << endl;
1713 bool Cursor::upDownInMath(bool up)
1715 // Be warned: The 'logic' implemented in this function is highly
1716 // fragile. A distance of one pixel or a '<' vs '<=' _really
1717 // matters. So fiddle around with it only if you think you know
1718 // what you are doing!
1722 xo = beforeDispatchPosX_;
1724 // check if we had something else in mind, if not, this is the future
1726 if (x_target_ == -1)
1728 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1729 // In text mode inside the line (not left or right) possibly set a new target_x,
1730 // but only if we are somewhere else than the previous target-offset.
1732 // We want to keep the x-target on subsequent up/down movements
1733 // that cross beyond the end of short lines. Thus a special
1734 // handling when the cursor is at the end of line: Use the new
1735 // x-target only if the old one was before the end of line
1736 // or the old one was after the beginning of the line
1737 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
1741 left = pos() == textRow().endpos();
1742 right = pos() == textRow().pos();
1744 left = pos() == textRow().pos();
1745 right = pos() == textRow().endpos();
1747 if ((!left && !right) ||
1748 (left && !right && xo < x_target_) ||
1749 (!left && right && x_target_ < xo))
1756 // try neigbouring script insets
1758 if (inMathed() && !selection()) {
1761 InsetMathScript const * p = prevAtom()->asScriptInset();
1762 if (p && p->has(up)) {
1764 push(*const_cast<InsetMathScript*>(p));
1765 idx() = p->idxOfScript(up);
1768 // we went in the right direction? Otherwise don't jump into the script
1772 int oy = beforeDispatchPosY_;
1773 if ((!up && y <= oy) ||
1782 if (pos() != lastpos()) {
1783 InsetMathScript const * p = nextAtom()->asScriptInset();
1784 if (p && p->has(up)) {
1785 push(*const_cast<InsetMathScript*>(p));
1786 idx() = p->idxOfScript(up);
1789 // we went in the right direction? Otherwise don't jump into the script
1793 int oy = beforeDispatchPosY_;
1794 if ((!up && y <= oy) ||
1803 // try to find an inset that knows better then we,
1804 if (inset().idxUpDown(*this, up)) {
1805 //lyxerr << "idxUpDown triggered" << endl;
1806 // try to find best position within this inset
1808 setCursor(bruteFind2(*this, xo, yo));
1812 // any improvement going just out of inset?
1813 if (popBackward() && inMathed()) {
1814 //lyxerr << "updown: popBackward succeeded" << endl;
1817 int yold = beforeDispatchPosY_;
1819 if (up ? ynew < yold : ynew > yold)
1823 // no success, we are probably at the document top or bottom
1829 bool Cursor::atFirstOrLastRow(bool up)
1831 TextMetrics const & tm = bv_->textMetrics(text());
1832 ParagraphMetrics const & pm = tm.parMetrics(pit());
1835 if (pos() && boundary())
1836 row = pm.pos2row(pos() - 1);
1838 row = pm.pos2row(pos());
1841 if (pit() == 0 && row == 0)
1844 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1845 row + 1 >= int(pm.rows().size()))
1852 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1854 LASSERT(text(), return false);
1860 xo = beforeDispatchPosX_;
1862 // update the targetX - this is here before the "return false"
1863 // to set a new target which can be used by InsetTexts above
1864 // if we cannot move up/down inside this inset anymore
1865 if (x_target_ == -1)
1867 else if (xo - textTargetOffset() != x_target() &&
1868 depth() == beforeDispatchCursor_.depth()) {
1869 // In text mode inside the line (not left or right)
1870 // possibly set a new target_x, but only if we are
1871 // somewhere else than the previous target-offset.
1873 // We want to keep the x-target on subsequent up/down
1874 // movements that cross beyond the end of short lines.
1875 // Thus a special handling when the cursor is at the
1876 // end of line: Use the new x-target only if the old
1877 // one was before the end of line or the old one was
1878 // after the beginning of the line
1879 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
1883 left = pos() == textRow().endpos();
1884 right = pos() == textRow().pos();
1886 left = pos() == textRow().pos();
1887 right = pos() == textRow().endpos();
1889 if ((!left && !right) ||
1890 (left && !right && xo < x_target_) ||
1891 (!left && right && x_target_ < xo))
1898 // first get the current line
1899 TextMetrics & tm = bv_->textMetrics(text());
1900 ParagraphMetrics const & pm = tm.parMetrics(pit());
1902 if (pos() && boundary())
1903 row = pm.pos2row(pos() - 1);
1905 row = pm.pos2row(pos());
1907 if (atFirstOrLastRow(up)) {
1908 // Is there a place for the cursor to go ? If yes, we
1909 // can execute the DEPM, otherwise we should keep the
1910 // paragraph to host the cursor.
1911 Cursor dummy = *this;
1912 bool valid_destination = false;
1913 for(; dummy.depth(); dummy.pop())
1914 if (!dummy.atFirstOrLastRow(up)) {
1915 valid_destination = true;
1919 // will a next dispatch follow and if there is a new
1920 // dispatch will it move the cursor out ?
1921 if (depth() > 1 && valid_destination) {
1922 // The cursor hasn't changed yet. This happens when
1923 // you e.g. move out of an inset. And to give the
1924 // DEPM the possibility of doing something we must
1925 // provide it with two different cursors. (Lgb, vfr)
1927 dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
1928 dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
1930 updateNeeded |= bv().checkDepm(dummy, *this);
1931 updateTextTargetOffset();
1933 forceBufferUpdate();
1938 // with and without selection are handled differently
1940 int yo = bv().getPos(*this).y_;
1942 // To next/previous row
1944 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1946 tm.editXY(*this, xo, yo + textRow().descent() + 1);
1949 // This happens when you move out of an inset.
1950 // And to give the DEPM the possibility of doing
1951 // something we must provide it with two different
1953 Cursor dummy = *this;
1956 if (bv().checkDepm(dummy, old)) {
1957 updateNeeded = true;
1958 // Make sure that cur gets back whatever happened to dummy (Lgb)
1962 // if there is a selection, we stay out of any inset,
1963 // and just jump to the right position:
1969 } else if (pit() > 0) {
1971 TextMetrics & tm = bv_->textMetrics(text());
1972 if (!tm.contains(pit()))
1973 tm.newParMetricsUp();
1974 ParagraphMetrics const & pmcur = tm.parMetrics(pit());
1975 next_row = pmcur.rows().size() - 1;
1978 if (row + 1 < int(pm.rows().size())) {
1980 } else if (pit() + 1 < int(text()->paragraphs().size())) {
1982 TextMetrics & tm = bv_->textMetrics(text());
1983 if (!tm.contains(pit()))
1984 tm.newParMetricsDown();
1989 Row const & real_next_row = tm.parMetrics(pit()).rows()[next_row];
1991 top().pos() = tm.getPosNearX(real_next_row, xo, bound);
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() const
2123 odocstringstream os;
2129 return text()->currentState(*this);
2135 docstring Cursor::getPossibleLabel() const
2137 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
2141 Encoding const * Cursor::getEncoding() const
2145 CursorSlice const & sl = innerTextSlice();
2146 Text const & text = *sl.text();
2147 Font font = text.getPar(sl.pit()).getFont(
2148 bv().buffer().params(), sl.pos(), text.outerFont(sl.pit()));
2149 return font.language()->encoding();
2153 void Cursor::undispatched() const
2155 disp_.dispatched(false);
2159 void Cursor::dispatched() const
2161 disp_.dispatched(true);
2165 void Cursor::screenUpdateFlags(Update::flags f) const
2167 disp_.screenUpdate(f);
2171 void Cursor::forceBufferUpdate() const
2173 disp_.forceBufferUpdate();
2177 void Cursor::clearBufferUpdate() const
2179 disp_.clearBufferUpdate();
2183 bool Cursor::needBufferUpdate() const
2185 return disp_.needBufferUpdate();
2189 void Cursor::noScreenUpdate() const
2191 disp_.screenUpdate(Update::None);
2195 Font Cursor::getFont() const
2197 // The logic here should more or less match to the
2198 // Cursor::setCurrentFont logic, i.e. the cursor height should
2199 // give a hint what will happen if a character is entered.
2201 // HACK. far from being perfect...
2203 CursorSlice const & sl = innerTextSlice();
2204 Text const & text = *sl.text();
2205 Paragraph const & par = text.getPar(sl.pit());
2207 // on boundary, so we are really at the character before
2208 pos_type pos = sl.pos();
2209 if (pos > 0 && boundary())
2212 // on space? Take the font before (only for RTL boundary stay)
2214 TextMetrics const & tm = bv().textMetrics(&text);
2215 if (pos == sl.lastpos()
2216 || (par.isSeparator(pos)
2217 && !tm.isRTLBoundary(sl.pit(), pos)))
2221 // get font at the position
2222 Font font = par.getFont(buffer()->params(), pos,
2223 text.outerFont(sl.pit()));
2229 bool Cursor::fixIfBroken()
2231 bool const broken_cursor = DocIterator::fixIfBroken();
2232 bool const broken_anchor = anchor_.fixIfBroken();
2234 if (broken_cursor || broken_anchor) {
2235 clearNewWordPosition();
2243 void Cursor::sanitize()
2245 setBuffer(&bv_->buffer());
2246 DocIterator::sanitize();
2254 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2256 // find inset in common
2258 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2259 if (&old[i].inset() != &cur[i].inset())
2263 // update words if we just moved to another paragraph
2264 if (i == old.depth() && i == cur.depth()
2265 && !cur.buffer()->isClean()
2266 && cur.inTexted() && old.inTexted()
2267 && cur.pit() != old.pit()) {
2268 old.paragraph().updateWords();
2271 // notify everything on top of the common part in old cursor,
2272 // but stop if the inset claims the cursor to be invalid now
2273 for (size_type j = i; j < old.depth(); ++j) {
2274 Cursor inset_pos = old;
2275 inset_pos.cutOff(j);
2276 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2280 // notify everything on top of the common part in new cursor,
2281 // but stop if the inset claims the cursor to be invalid now
2282 for (; i < cur.depth(); ++i) {
2283 if (cur[i].inset().notifyCursorEnters(cur))
2291 void Cursor::setCurrentFont()
2293 CursorSlice const & cs = innerTextSlice();
2294 Paragraph const & par = cs.paragraph();
2295 pos_type cpit = cs.pit();
2296 pos_type cpos = cs.pos();
2297 Text const & ctext = *cs.text();
2298 TextMetrics const & tm = bv().textMetrics(&ctext);
2300 // are we behind previous char in fact? -> go to that char
2301 if (cpos > 0 && boundary())
2304 // find position to take the font from
2306 // paragraph end? -> font of last char
2307 if (cpos == lastpos())
2309 // on space? -> look at the words in front of space
2310 else if (cpos > 0 && par.isSeparator(cpos)) {
2311 // abc| def -> font of c
2312 // abc |[WERBEH], i.e. boundary==true -> font of c
2313 // abc [WERBEH]| def, font of the space
2314 if (!tm.isRTLBoundary(cpit, cpos))
2320 BufferParams const & bufparams = buffer()->params();
2321 current_font = par.getFontSettings(bufparams, cpos);
2322 real_current_font = tm.displayFont(cpit, cpos);
2324 // special case for paragraph end
2325 if (cs.pos() == lastpos()
2326 && tm.isRTLBoundary(cpit, cs.pos())
2328 Language const * lang = par.getParLanguage(bufparams);
2329 current_font.setLanguage(lang);
2330 current_font.fontInfo().setNumber(FONT_OFF);
2331 real_current_font.setLanguage(lang);
2332 real_current_font.fontInfo().setNumber(FONT_OFF);
2337 bool Cursor::textUndo()
2339 if (!buffer()->undo().textUndo(*this))
2346 bool Cursor::textRedo()
2348 if (!buffer()->undo().textRedo(*this))
2355 void Cursor::finishUndo() const
2357 buffer()->undo().finishUndo();
2361 void Cursor::beginUndoGroup() const
2363 buffer()->undo().beginUndoGroup();
2367 void Cursor::endUndoGroup() const
2369 buffer()->undo().endUndoGroup(*this);
2373 void Cursor::recordUndo(pit_type from, pit_type to) const
2375 buffer()->undo().recordUndo(*this, from, to);
2379 void Cursor::recordUndo(pit_type from) const
2381 buffer()->undo().recordUndo(*this, from, pit());
2385 void Cursor::recordUndo(UndoKind kind) const
2387 buffer()->undo().recordUndo(*this, kind);
2391 void Cursor::recordUndoInset(Inset const * in) const
2393 buffer()->undo().recordUndoInset(*this, in);
2397 void Cursor::recordUndoFullBuffer() const
2399 buffer()->undo().recordUndoFullBuffer(*this);
2403 void Cursor::recordUndoBufferParams() const
2405 buffer()->undo().recordUndoBufferParams(*this);
2409 void Cursor::recordUndoSelection() const
2412 if (cap::multipleCellsSelected(*this))
2417 buffer()->undo().recordUndo(*this,
2418 selBegin().pit(), selEnd().pit());
2423 void Cursor::checkBufferStructure()
2425 Buffer const * master = buffer()->masterBuffer();
2426 master->tocBackend().updateItem(*this);
2427 if (master != buffer() && !master->hasGuiDelegate())
2428 // In case the master has no gui associated with it,
2429 // the TocItem is not updated (part of bug 5699).
2430 buffer()->tocBackend().updateItem(*this);