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 bool positionable(DocIterator const & cursor, DocIterator const & anchor)
70 // avoid deeper nested insets when selecting
71 if (cursor.depth() > anchor.depth())
74 // anchor might be deeper, should have same path then
75 for (size_t i = 0; i < cursor.depth(); ++i)
76 if (&cursor[i].inset() != &anchor[i].inset())
79 // position should be ok.
84 // Find position closest to (x, y) in cell given by iter.
85 // Used only in mathed
86 DocIterator bruteFind2(Cursor const & c, int x, int y)
88 double best_dist = numeric_limits<double>::max();
95 et.top().pos() = et.top().asInsetMath()->cell(et.top().idx()).size();
96 for (size_t i = 0;; ++i) {
99 Inset const * inset = &it.inset();
100 CoordCache const & cache = c.bv().coordCache();
102 // FIXME: in the case where the inset is not in the cache, this
103 // means that no part of it is visible on screen. In this case
104 // we don't do elaborate search and we just return the forwarded
105 // DocIterator at its beginning.
106 if (!cache.getInsets().has(inset)) {
111 Point const o = cache.getInsets().xy(inset);
112 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
113 // Convert to absolute
116 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
117 // '<=' in order to take the last possible position
118 // this is important for clicking behind \sum in e.g. '\sum_i a'
119 LYXERR(Debug::DEBUG, "i: " << i << " d: " << d
120 << " best: " << best_dist);
121 if (d <= best_dist) {
134 /// moves position closest to (x, y) in given box
135 bool bruteFind(Cursor & cursor,
136 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
138 LASSERT(!cursor.empty(), return false);
139 Inset & inset = cursor[0].inset();
140 BufferView & bv = cursor.bv();
142 CoordCache::InnerParPosCache const & cache =
143 bv.coordCache().getParPos().find(cursor.bottom().text())->second;
144 // Get an iterator on the first paragraph in the cache
145 DocIterator it(inset);
146 it.push_back(CursorSlice(inset));
147 it.pit() = cache.begin()->first;
148 // Get an iterator after the last paragraph in the cache
149 DocIterator et(inset);
150 et.push_back(CursorSlice(inset));
151 et.pit() = boost::prior(cache.end())->first;
152 if (et.pit() >= et.lastpit())
153 et = doc_iterator_end(inset);
157 double best_dist = numeric_limits<double>::max();
158 DocIterator best_cursor = et;
160 for ( ; it != et; it.forwardPos(true)) {
161 // avoid invalid nesting when selecting
162 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
163 Point p = bv.getPos(it, false);
166 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
167 double const dx = xo - x;
168 double const dy = yo - y;
169 double const d = dx * dx + dy * dy;
170 // '<=' in order to take the last possible position
171 // this is important for clicking behind \sum in e.g. '\sum_i a'
172 if (d <= best_dist) {
173 // lyxerr << "*" << endl;
181 if (best_cursor != et) {
182 cursor.setCursor(best_cursor);
191 /// moves position closest to (x, y) in given box
192 bool bruteFind3(Cursor & cur, int x, int y, bool up)
194 BufferView & bv = cur.bv();
195 int ylow = up ? 0 : y + 1;
196 int yhigh = up ? y - 1 : bv.workHeight();
198 int xhigh = bv.workWidth();
200 // FIXME: bit more work needed to get 'from' and 'to' right.
201 pit_type from = cur.bottom().pit();
202 //pit_type to = cur.bottom().pit();
203 //lyxerr << "Pit start: " << from << endl;
205 //lyxerr << "bruteFind3: x: " << x << " y: " << y
206 // << " xlow: " << xlow << " xhigh: " << xhigh
207 // << " ylow: " << ylow << " yhigh: " << yhigh
209 DocIterator it = doc_iterator_begin(cur.buffer());
211 DocIterator et = doc_iterator_end(cur.buffer());
213 double best_dist = numeric_limits<double>::max();
214 DocIterator best_cursor = et;
216 for ( ; it != et; it.forwardPos()) {
217 // avoid invalid nesting when selecting
218 if (bv.cursorStatus(it) == CUR_INSIDE
219 && (!cur.selection() || positionable(it, cur.realAnchor()))) {
220 // If this function is ever used again, check
221 // whether this is the same as "bv.getPos(it,
222 // false)" with boundary = false.
223 Point p = bv.getPos(it);
226 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
227 double const dx = xo - x;
228 double const dy = yo - y;
229 double const d = dx * dx + dy * dy;
230 //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
231 // << " dx: " << dx << " dy: " << dy
232 // << " idx: " << it.idx() << " pos: " << it.pos()
235 // '<=' in order to take the last possible position
236 // this is important for clicking behind \sum in e.g. '\sum_i a'
237 if (d <= best_dist) {
238 //lyxerr << "*" << endl;
246 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
247 if (best_cursor == et)
249 cur.setCursor(best_cursor);
256 CursorData::CursorData()
257 : DocIterator(), anchor_(),
258 selection_(false), mark_(false), word_selection_(false),
259 logicalpos_(false), current_font(inherit_font)
263 CursorData::CursorData(Buffer * buffer)
264 : DocIterator(buffer), anchor_(),
265 selection_(false), mark_(false), word_selection_(false),
266 logicalpos_(false), current_font(inherit_font)
270 CursorData::CursorData(DocIterator const & dit)
271 : DocIterator(dit), anchor_(),
272 selection_(false), mark_(false), word_selection_(false),
273 logicalpos_(false), current_font(inherit_font)
277 // be careful: this is called from the bv's constructor, too, so
278 // bv functions are not yet available!
279 Cursor::Cursor(BufferView & bv)
280 : CursorData(&bv.buffer()), bv_(&bv),
281 x_target_(-1), textTargetOffset_(0)
288 push_back(CursorSlice(buffer()->inset()));
289 anchor_ = doc_iterator_begin(buffer());
291 new_word_ = doc_iterator_begin(buffer());
299 // this (intentionally) does neither touch anchor nor selection status
300 void Cursor::setCursor(DocIterator const & cur)
302 DocIterator::operator=(cur);
306 void Cursor::setCursorToAnchor()
309 DocIterator normal = anchor_;
310 while (depth() < normal.depth())
312 if (depth() < anchor_.depth() && top() <= anchor_[depth() - 1])
319 void Cursor::setCursorData(CursorData const & data)
321 CursorData::operator=(data);
325 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
329 // Try to fix cursor in case it is broken.
332 // Is this a function that acts on inset at point?
333 Inset * inset = cur.nextInset();
334 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
335 && inset && inset->getStatus(cur, cmd, status))
338 // This is, of course, a mess. Better create a new doc iterator and use
339 // this in Inset::getStatus. This might require an additional
340 // BufferView * arg, though (which should be avoided)
341 //Cursor safe = *this;
343 for ( ; cur.depth(); cur.pop()) {
344 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
345 // LASSERT: Is it safe to continue here, or should we return?
346 LASSERT(cur.idx() <= cur.lastidx(), /**/);
347 LASSERT(cur.pit() <= cur.lastpit(), /**/);
348 LASSERT(cur.pos() <= cur.lastpos(), /**/);
350 // The inset's getStatus() will return 'true' if it made
351 // a definitive decision on whether it want to handle the
352 // request or not. The result of this decision is put into
353 // the 'status' parameter.
354 if (cur.inset().getStatus(cur, cmd, status)) {
363 void Cursor::saveBeforeDispatchPosXY()
365 getPos(beforeDispatchPosX_, beforeDispatchPosY_);
369 void Cursor::dispatch(FuncRequest const & cmd0)
371 LYXERR(Debug::DEBUG, "cmd: " << cmd0 << '\n' << *this);
376 FuncRequest cmd = cmd0;
379 disp_ = DispatchResult();
383 // Is this a function that acts on inset at point?
384 if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
386 disp_.dispatched(true);
387 disp_.screenUpdate(Update::FitCursor | Update::Force);
388 FuncRequest tmpcmd = cmd;
389 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
390 << cmd0 << endl << *this);
391 nextInset()->dispatch(*this, tmpcmd);
392 if (disp_.dispatched()) {
398 // store some values to be used inside of the handlers
399 beforeDispatchCursor_ = *this;
400 for (; depth(); pop(), boundary(false)) {
401 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
402 << cmd0 << endl << *this);
404 // In any of these cases, the cursor is invalid, and we should
405 // try to save this document rather than crash.
406 LBUFERR(pos() <= lastpos());
407 LBUFERR(idx() <= lastidx());
408 LBUFERR(pit() <= lastpit());
410 // The common case is 'LFUN handled, need update', so make the
411 // LFUN handler's life easier by assuming this as default value.
412 // The handler can reset the update and val flags if necessary.
413 disp_.screenUpdate(Update::FitCursor | Update::Force);
414 disp_.dispatched(true);
415 inset().dispatch(*this, cmd);
416 if (disp_.dispatched())
420 // it completely to get a 'bomb early' behaviour in case this
421 // object will be used again.
422 if (!disp_.dispatched()) {
423 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
424 // We might have invalidated the cursor when removing an empty
425 // paragraph while the cursor could not be moved out the inset
426 // while we initially thought we could. This might happen when
427 // a multiline inset becomes an inline inset when the second
428 // paragraph is removed.
429 if (safe.pit() > safe.lastpit()) {
430 safe.pit() = safe.lastpit();
431 safe.pos() = safe.lastpos();
434 disp_.screenUpdate(Update::None);
435 disp_.dispatched(false);
437 // restore the previous one because nested Cursor::dispatch calls
438 // are possible which would change it
439 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
443 // notify insets we just left
445 old.beginUndoGroup();
447 bool badcursor = notifyCursorLeavesOrEnters(old, *this);
450 bv().resetInlineCompletionPos();
457 DispatchResult const & Cursor::result() const
463 BufferView & Cursor::bv() const
472 LBUFERR(depth() >= 1);
477 void Cursor::push(Inset & p)
479 push_back(CursorSlice(p));
480 p.setBuffer(*buffer());
484 void Cursor::pushBackward(Inset & p)
486 LASSERT(!empty(), return);
487 //lyxerr << "Entering inset " << t << " front" << endl;
493 bool Cursor::popBackward()
495 LASSERT(!empty(), return false);
503 bool Cursor::popForward()
505 LASSERT(!empty(), return false);
506 //lyxerr << "Leaving inset from in back" << endl;
507 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
511 pos() += lastpos() - lp + 1;
516 int Cursor::currentMode()
518 LASSERT(!empty(), return Inset::UNDECIDED_MODE);
519 for (int i = depth() - 1; i >= 0; --i) {
520 int res = operator[](i).inset().currentMode();
521 bool locked_mode = operator[](i).inset().lockedMode();
522 // Also return UNDECIDED_MODE when the mode is locked,
523 // as in this case it is treated the same as TEXT_MODE
524 if (res != Inset::UNDECIDED_MODE || locked_mode)
527 return Inset::TEXT_MODE;
531 void Cursor::getPos(int & x, int & y) const
533 Point p = bv().getPos(*this);
539 Row const & Cursor::textRow() const
541 CursorSlice const & cs = innerTextSlice();
542 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
543 return pm.getRow(pos(), boundary());
547 void Cursor::resetAnchor()
550 checkNewWordPosition();
554 void Cursor::markNewWordPosition()
556 if (lyxrc.spellcheck_continuously && inTexted() && new_word_.empty()) {
557 FontSpan nw = locateWord(WHOLE_WORD);
558 if (nw.size() == 1) {
559 LYXERR(Debug::DEBUG, "start new word: "
561 << " pos: " << nw.first);
568 void Cursor::clearNewWordPosition()
570 if (!new_word_.empty()) {
571 LYXERR(Debug::DEBUG, "clear new word: "
573 << " pos: " << pos());
579 void Cursor::checkNewWordPosition()
581 if (!lyxrc.spellcheck_continuously || new_word_.empty())
584 clearNewWordPosition();
586 // forget the position of the current new word if
587 // 1) the paragraph changes or
588 // 2) the count of nested insets changes or
589 // 3) the cursor pos is out of paragraph bound
590 if (pit() != new_word_.pit() ||
591 depth() != new_word_.depth() ||
592 new_word_.pos() > new_word_.lastpos()) {
593 clearNewWordPosition();
594 } else if (new_word_.fixIfBroken())
595 // 4) or the remembered position was "broken"
596 clearNewWordPosition();
598 FontSpan nw = locateWord(WHOLE_WORD);
600 FontSpan ow = new_word_.locateWord(WHOLE_WORD);
601 if (nw.intersect(ow).empty())
602 clearNewWordPosition();
604 LYXERR(Debug::DEBUG, "new word: "
606 << " pos: " << nw.first << ".." << nw.last);
608 clearNewWordPosition();
615 bool Cursor::posBackward()
624 bool Cursor::posForward()
626 if (pos() == lastpos())
633 bool Cursor::posVisRight(bool skip_inset)
635 Cursor new_cur = *this; // where we will move to
636 pos_type left_pos; // position visually left of current cursor
637 pos_type right_pos; // position visually right of current cursor
639 getSurroundingPos(left_pos, right_pos);
641 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
643 // Are we at an inset?
644 new_cur.pos() = right_pos;
645 new_cur.boundary(false);
647 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
648 // we actually move the cursor at the end of this
649 // function, for now we just keep track of the new
650 // position in new_cur...
651 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
654 // Are we already at rightmost pos in row?
655 else if (text()->empty() || right_pos == -1) {
658 if (!new_cur.posVisToNewRow(false)) {
659 LYXERR(Debug::RTL, "not moving!");
663 // we actually move the cursor at the end of this
664 // function, for now just keep track of the new
665 // position in new_cur...
666 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
667 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
670 // normal movement to the right
673 // Recall, if the cursor is at position 'x', that
674 // means *before* the character at position 'x'. In
675 // RTL, "before" means "to the right of", in LTR, "to
676 // the left of". So currently our situation is this:
677 // the position to our right is 'right_pos' (i.e.,
678 // we're currently to the left of 'right_pos'). In
679 // order to move to the right, it depends whether or
680 // not the character at 'right_pos' is RTL.
681 bool const new_pos_is_RTL = paragraph().getFontSettings(
682 buffer()->params(), right_pos).isVisibleRightToLeft();
683 // If the character at 'right_pos' *is* LTR, then in
684 // order to move to the right of it, we need to be
685 // *after* 'right_pos', i.e., move to position
687 if (!new_pos_is_RTL) {
688 new_cur.pos() = right_pos + 1;
689 // set the boundary to true in two situations:
691 // 1. if new_pos is now lastpos, and we're in
692 // an RTL paragraph (this means that we're
693 // moving right to the end of an LTR chunk
694 // which is at the end of an RTL paragraph);
695 (new_cur.pos() == lastpos()
696 && paragraph().isRTL(buffer()->params()))
697 // 2. if the position *after* right_pos is RTL
698 // (we want to be *after* right_pos, not
699 // before right_pos + 1!)
700 || paragraph().getFontSettings(buffer()->params(),
701 new_cur.pos()).isVisibleRightToLeft()
703 new_cur.boundary(true);
704 else // set the boundary to false
705 new_cur.boundary(false);
707 // Otherwise (if the character at position 'right_pos'
708 // is RTL), then moving to the right of it is as easy
709 // as setting the new position to 'right_pos'.
711 new_cur.pos() = right_pos;
712 new_cur.boundary(false);
717 bool moved = (new_cur.pos() != pos()
718 || new_cur.pit() != pit()
719 || new_cur.boundary() != boundary()
720 || &new_cur.inset() != &inset());
723 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
724 << (new_cur.boundary() ? " (boundary)" : ""));
732 bool Cursor::posVisLeft(bool skip_inset)
734 Cursor new_cur = *this; // where we will move to
735 pos_type left_pos; // position visually left of current cursor
736 pos_type right_pos; // position visually right of current cursor
738 getSurroundingPos(left_pos, right_pos);
740 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
742 // Are we at an inset?
743 new_cur.pos() = left_pos;
744 new_cur.boundary(false);
746 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
747 // we actually move the cursor at the end of this
748 // function, for now we just keep track of the new
749 // position in new_cur...
750 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
753 // Are we already at leftmost pos in row?
754 else if (text()->empty() || left_pos == -1) {
757 if (!new_cur.posVisToNewRow(true)) {
758 LYXERR(Debug::RTL, "not moving!");
762 // we actually move the cursor at the end of this
763 // function, for now just keep track of the new
764 // position in new_cur...
765 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
766 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
769 // normal movement to the left
772 // Recall, if the cursor is at position 'x', that
773 // means *before* the character at position 'x'. In
774 // RTL, "before" means "to the right of", in LTR, "to
775 // the left of". So currently our situation is this:
776 // the position to our left is 'left_pos' (i.e., we're
777 // currently to the right of 'left_pos'). In order to
778 // move to the left, it depends whether or not the
779 // character at 'left_pos' is RTL.
780 bool const new_pos_is_RTL = paragraph().getFontSettings(
781 buffer()->params(), left_pos).isVisibleRightToLeft();
782 // If the character at 'left_pos' *is* RTL, then in
783 // order to move to the left of it, we need to be
784 // *after* 'left_pos', i.e., move to position
786 if (new_pos_is_RTL) {
787 new_cur.pos() = left_pos + 1;
788 // set the boundary to true in two situations:
790 // 1. if new_pos is now lastpos and we're in
791 // an LTR paragraph (this means that we're
792 // moving left to the end of an RTL chunk
793 // which is at the end of an LTR paragraph);
794 (new_cur.pos() == lastpos()
795 && !paragraph().isRTL(buffer()->params()))
796 // 2. if the position *after* left_pos is not
797 // RTL (we want to be *after* left_pos, not
798 // before left_pos + 1!)
799 || !paragraph().getFontSettings(buffer()->params(),
800 new_cur.pos()).isVisibleRightToLeft()
802 new_cur.boundary(true);
803 else // set the boundary to false
804 new_cur.boundary(false);
806 // Otherwise (if the character at position 'left_pos'
807 // is LTR), then moving to the left of it is as easy
808 // as setting the new position to 'left_pos'.
810 new_cur.pos() = left_pos;
811 new_cur.boundary(false);
816 bool moved = (new_cur.pos() != pos()
817 || new_cur.pit() != pit()
818 || new_cur.boundary() != boundary());
821 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
822 << (new_cur.boundary() ? " (boundary)" : ""));
830 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos)
832 // preparing bidi tables
833 Paragraph const & par = paragraph();
834 Buffer const & buf = *buffer();
835 Row const & row = textRow();
837 bidi.computeTables(par, buf, row);
839 LYXERR(Debug::RTL, "bidi: " << row.pos() << "--" << row.endpos());
841 // The cursor is painted *before* the character at pos(), or,
842 // if 'boundary' is true, *after* the character at (pos() -
843 // 1). So we already have one known position around the
845 pos_type const known_pos = boundary() && pos() > 0 ? pos() - 1 : pos();
847 // edge case: if we're at the end of the paragraph, things are
848 // a little different (because lastpos is a position which
849 // does not really "exist" --- there's no character there
851 if (known_pos == lastpos()) {
852 if (par.isRTL(buf.params())) {
854 right_pos = bidi.vis2log(row.pos());
858 left_pos = bidi.vis2log(row.endpos() - 1);
863 // Whether 'known_pos' is to the left or to the right of the
864 // cursor depends on whether it is an RTL or LTR character...
865 bool const cur_is_RTL =
866 par.getFontSettings(buf.params(), known_pos).isVisibleRightToLeft();
867 // ... in the following manner:
868 // For an RTL character, "before"
869 // means "to the right" and "after" means "to the left"; and
870 // for LTR, it's the reverse. So, 'known_pos' is to the right
871 // of the cursor if (RTL && boundary) or (!RTL && !boundary):
872 bool const known_pos_on_right = cur_is_RTL == boundary();
874 // So we now know one of the positions surrounding the cursor.
875 // Let's determine the other one:
876 if (known_pos_on_right) {
877 right_pos = known_pos;
878 // *visual* position of 'left_pos':
879 pos_type v_left_pos = bidi.log2vis(right_pos) - 1;
880 // If the position we just identified as 'left_pos' is
881 // a "skipped separator" (a separator which is at the
882 // logical end of a row, except for the last row in a
883 // paragraph; such separators are not painted, so they
884 // "are not really there"; note that in bidi text,
885 // such a separator could appear visually in the
886 // middle of a row), set 'left_pos' to the *next*
887 // position to the left.
888 if (bidi.inRange(v_left_pos)
889 && bidi.vis2log(v_left_pos) + 1 == row.endpos()
890 && row.endpos() < lastpos()
891 && par.isSeparator(bidi.vis2log(v_left_pos)))
894 // calculate the logical position of 'left_pos', if in row
895 if (!bidi.inRange(v_left_pos))
898 left_pos = bidi.vis2log(v_left_pos);
899 // If the position we identified as 'right_pos' is a
900 // "skipped separator", set 'right_pos' to the *next*
901 // position to the right.
902 if (right_pos + 1 == row.endpos() && row.endpos() < lastpos()
903 && par.isSeparator(right_pos)) {
904 pos_type const v_right_pos = bidi.log2vis(right_pos) + 1;
905 if (!bidi.inRange(v_right_pos))
908 right_pos = bidi.vis2log(v_right_pos);
911 // known_pos is on the left
912 left_pos = known_pos;
913 // *visual* position of 'right_pos'
914 pos_type v_right_pos = bidi.log2vis(left_pos) + 1;
915 // If the position we just identified as 'right_pos'
916 // is a "skipped separator", set 'right_pos' to the
917 // *next* position to the right.
918 if (bidi.inRange(v_right_pos)
919 && bidi.vis2log(v_right_pos) + 1 == row.endpos()
920 && row.endpos() < lastpos()
921 && par.isSeparator(bidi.vis2log(v_right_pos)))
924 // calculate the logical position of 'right_pos', if in row
925 if (!bidi.inRange(v_right_pos))
928 right_pos = bidi.vis2log(v_right_pos);
929 // If the position we identified as 'left_pos' is a
930 // "skipped separator", set 'left_pos' to the *next*
931 // position to the left.
932 if (left_pos + 1 == row.endpos() && row.endpos() < lastpos()
933 && par.isSeparator(left_pos)) {
934 pos_type const v_left_pos = bidi.log2vis(left_pos) - 1;
935 if (!bidi.inRange(v_left_pos))
938 left_pos = bidi.vis2log(v_left_pos);
945 bool Cursor::posVisToNewRow(bool movingLeft)
947 Paragraph const & par = paragraph();
948 Buffer const & buf = *buffer();
949 Row const & row = textRow();
950 bool par_is_LTR = !par.isRTL(buf.params());
952 // Inside a table, determining whether to move to the next or
953 // previous row should be done based on the table's direction.
955 if (s >= 1 && (*this)[s].inset().asInsetTabular()) {
956 par_is_LTR = !(*this)[s].inset().asInsetTabular()->isRightToLeft(*this);
957 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
960 // if moving left in an LTR paragraph or moving right in an
961 // RTL one, move to previous row
962 if (par_is_LTR == movingLeft) {
963 if (row.pos() == 0) { // we're at first row in paragraph
964 if (pit() == 0) // no previous paragraph! don't move
966 // move to last pos in previous par
970 } else { // move to previous row in this par
971 pos() = row.pos() - 1; // this is guaranteed to be in previous row
975 // if moving left in an RTL paragraph or moving right in an
976 // LTR one, move to next row
978 if (row.endpos() == lastpos()) { // we're at last row in paragraph
979 if (pit() == lastpit()) // last paragraph! don't move
981 // move to first row in next par
985 } else { // move to next row in this par
986 pos() = row.endpos();
991 // make sure we're at left-/right-most pos in new row
992 posVisToRowExtremity(!movingLeft);
998 void Cursor::posVisToRowExtremity(bool left)
1000 // prepare bidi tables
1001 Paragraph const & par = paragraph();
1002 Buffer const & buf = *buffer();
1003 Row const & row = textRow();
1005 bidi.computeTables(par, buf, row);
1007 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
1008 << (boundary() ? 1 : 0));
1010 if (left) { // move to leftmost position
1011 // if this is an RTL paragraph, and we're at the last row in the
1012 // paragraph, move to lastpos
1013 if (par.isRTL(buf.params()) && row.endpos() == lastpos())
1016 pos() = bidi.vis2log(row.pos());
1018 // Moving to the leftmost position in the row,
1019 // the cursor should normally be placed to the
1020 // *left* of the leftmost position. A very
1021 // common exception, though, is if the
1022 // leftmost character also happens to be the
1023 // separator at the (logical) end of the row
1024 // --- in this case, the separator is
1025 // positioned beyond the left margin, and we
1026 // don't want to move the cursor there (moving
1027 // to the left of the separator is equivalent
1028 // to moving to the next line). So, in this
1029 // case we actually want to place the cursor
1030 // to the *right* of the leftmost position
1031 // (the separator). Another exception is if
1032 // we're moving to the logically last position
1033 // in the row, which is *not* a separator:
1034 // this means that the entire row has no
1035 // separators (if there were any, the row
1036 // would have been broken there); and
1037 // therefore in this case we also move to the
1038 // *right* of the last position (this
1039 // indicates to the user that there is no
1040 // space after this position, and is
1041 // consistent with the behavior in the middle
1042 // of a row --- moving right or left moves to
1043 // the next/previous character; if we were to
1044 // move to the *left* of this position, that
1045 // would simulate a separator which is not
1046 // really there!). Finally, there is an
1047 // exception to the previous exception: if
1048 // this non-separator-but-last-position-in-row
1049 // is an inset, then we *do* want to stay to
1050 // the left of it anyway: this is the
1051 // "boundary" which we simulate at insets.
1053 // Another exception is when row.endpos() is
1056 // do we want to be to the right of pos?
1057 // as explained above, if at last pos in row, stay to the right
1058 bool const right_of_pos = row.endpos() > 0
1059 && pos() == row.endpos() - 1 && !par.isInset(pos());
1061 // Now we know if we want to be to the left or to the right of pos,
1062 // let's make sure we are where we want to be.
1063 bool const new_pos_is_RTL =
1064 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
1066 if (new_pos_is_RTL != right_of_pos) {
1072 // move to rightmost position
1073 // if this is an LTR paragraph, and we're at the last row in the
1074 // paragraph, move to lastpos
1075 if (!par.isRTL(buf.params()) && row.endpos() == lastpos())
1078 pos() = row.endpos() > 0 ? bidi.vis2log(row.endpos() - 1) : 0;
1080 // Moving to the rightmost position in the
1081 // row, the cursor should normally be placed
1082 // to the *right* of the rightmost position. A
1083 // very common exception, though, is if the
1084 // rightmost character also happens to be the
1085 // separator at the (logical) end of the row
1086 // --- in this case, the separator is
1087 // positioned beyond the right margin, and we
1088 // don't want to move the cursor there (moving
1089 // to the right of the separator is equivalent
1090 // to moving to the next line). So, in this
1091 // case we actually want to place the cursor
1092 // to the *left* of the rightmost position
1093 // (the separator). Another exception is if
1094 // we're moving to the logically last position
1095 // in the row, which is *not* a separator:
1096 // this means that the entire row has no
1097 // separators (if there were any, the row
1098 // would have been broken there); and
1099 // therefore in this case we also move to the
1100 // *left* of the last position (this indicates
1101 // to the user that there is no space after
1102 // this position, and is consistent with the
1103 // behavior in the middle of a row --- moving
1104 // right or left moves to the next/previous
1105 // character; if we were to move to the
1106 // *right* of this position, that would
1107 // simulate a separator which is not really
1108 // there!). Finally, there is an exception to
1109 // the previous exception: if this
1110 // non-separator-but-last-position-in-row is
1111 // an inset, then we *do* want to stay to the
1112 // right of it anyway: this is the "boundary"
1113 // which we simulate at insets. Another
1114 // exception is when row.endpos() is 0.
1116 // do we want to be to the left of pos?
1117 // as explained above, if at last pos in row, stay to the left,
1118 // unless the last position is the same as the first.
1119 bool const left_of_pos = row.endpos() > 0
1120 && pos() == row.endpos() - 1 && !par.isInset(pos());
1122 // Now we know if we want to be to the left or to the right of pos,
1123 // let's make sure we are where we want to be.
1124 bool const new_pos_is_RTL =
1125 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
1127 if (new_pos_is_RTL == left_of_pos) {
1133 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
1134 << (boundary() ? 1 : 0));
1138 CursorSlice Cursor::normalAnchor() const
1142 // LASSERT: There have been several bugs around this code, that seem
1143 // to involve failures to reset the anchor. We can at least not crash
1144 // in release mode by resetting it ourselves.
1145 LASSERT(anchor_.depth() >= depth(),
1146 const_cast<DocIterator &>(anchor_) = *this);
1148 CursorSlice normal = anchor_[depth() - 1];
1149 if (depth() < anchor_.depth() && top() <= normal) {
1150 // anchor is behind cursor -> move anchor behind the inset
1157 DocIterator & Cursor::realAnchor()
1163 CursorSlice Cursor::selBegin() const
1167 return normalAnchor() < top() ? normalAnchor() : top();
1171 CursorSlice Cursor::selEnd() const
1175 return normalAnchor() > top() ? normalAnchor() : top();
1179 DocIterator Cursor::selectionBegin() const
1185 // FIXME: This is a work-around for the problem that
1186 // CursorSlice doesn't keep track of the boundary.
1187 if (normalAnchor() == top())
1188 di = anchor_.boundary() > boundary() ? anchor_ : *this;
1190 di = normalAnchor() < top() ? anchor_ : *this;
1196 DocIterator Cursor::selectionEnd() const
1202 // FIXME: This is a work-around for the problem that
1203 // CursorSlice doesn't keep track of the boundary.
1204 if (normalAnchor() == top())
1205 di = anchor_.boundary() < boundary() ? anchor_ : *this;
1207 di = normalAnchor() > top() ? anchor_ : *this;
1209 if (di.depth() > depth()) {
1217 void Cursor::setSelection()
1220 // A selection with no contents is not a selection
1221 // FIXME: doesnt look ok
1222 if (idx() == normalAnchor().idx() &&
1223 pit() == normalAnchor().pit() &&
1224 pos() == normalAnchor().pos())
1225 setSelection(false);
1229 void Cursor::setSelection(DocIterator const & where, int n)
1238 void Cursor::clearSelection()
1240 setSelection(false);
1241 setWordSelection(false);
1247 void Cursor::setTargetX(int x)
1250 textTargetOffset_ = 0;
1254 int Cursor::x_target() const
1260 void Cursor::clearTargetX()
1263 textTargetOffset_ = 0;
1267 void Cursor::updateTextTargetOffset()
1272 textTargetOffset_ = x - x_target_;
1276 void Cursor::info(odocstream & os) const
1278 for (int i = 1, n = depth(); i < n; ++i) {
1279 operator[](i).inset().infoize(os);
1283 Inset const * inset = prevInset();
1284 // prevInset() can return 0 in certain case.
1286 prevInset()->infoize2(os);
1288 // overwite old message
1293 bool Cursor::selHandle(bool sel)
1295 //lyxerr << "Cursor::selHandle" << endl;
1298 if (sel == selection())
1302 cap::saveSelection(*this);
1310 ostream & operator<<(ostream & os, Cursor const & cur)
1312 os << "\n cursor: | anchor:\n";
1313 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
1314 os << " " << cur[i] << " | ";
1315 if (i < cur.anchor_.depth())
1316 os << cur.anchor_[i];
1318 os << "-------------------------------";
1321 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
1322 os << "------------------------------- | " << cur.anchor_[i] << "\n";
1324 os << " selection: " << cur.selection_
1325 << " x_target: " << cur.x_target_
1326 << " boundary: " << cur.boundary() << endl;
1331 LyXErr & operator<<(LyXErr & os, Cursor const & cur)
1341 ///////////////////////////////////////////////////////////////////
1344 // The part below is the non-integrated rest of the original math
1345 // cursor. This should be either generalized for texted or moved
1346 // back to mathed (in most cases to InsetMathNest).
1348 ///////////////////////////////////////////////////////////////////
1350 #include "mathed/InsetMathChar.h"
1351 #include "mathed/InsetMathGrid.h"
1352 #include "mathed/InsetMathScript.h"
1353 #include "mathed/InsetMathUnknown.h"
1354 #include "mathed/MathFactory.h"
1355 #include "mathed/MathStream.h"
1356 #include "mathed/MathSupport.h"
1361 bool Cursor::isInside(Inset const * p) const
1363 for (size_t i = 0; i != depth(); ++i)
1364 if (&operator[](i).inset() == p)
1370 void Cursor::leaveInset(Inset const & inset)
1372 for (size_t i = 0; i != depth(); ++i) {
1373 if (&operator[](i).inset() == &inset) {
1381 bool Cursor::openable(MathAtom const & t) const
1392 // we can't move into anything new during selection
1393 if (depth() >= anchor_.depth())
1395 if (t.nucleus() != &anchor_[depth()].inset())
1402 void Cursor::setScreenPos(int x, int /*y*/)
1405 //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
1410 void Cursor::plainErase()
1412 cell().erase(pos());
1416 void Cursor::markInsert()
1418 insert(char_type(0));
1422 void Cursor::markErase()
1424 cell().erase(pos());
1428 void Cursor::plainInsert(MathAtom const & t)
1430 cell().insert(pos(), t);
1432 inset().setBuffer(bv_->buffer());
1434 forceBufferUpdate();
1438 void Cursor::insert(docstring const & str)
1440 for_each(str.begin(), str.end(),
1441 bind(static_cast<void(Cursor::*)(char_type)>
1442 (&Cursor::insert), this, _1));
1446 void Cursor::insert(char_type c)
1448 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1449 LASSERT(!empty(), return);
1451 cap::selClearOrDel(*this);
1452 insert(new InsetMathChar(c));
1454 text()->insertChar(*this, c);
1459 void Cursor::insert(MathAtom const & t)
1461 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1463 cap::selClearOrDel(*this);
1468 void Cursor::insert(Inset * inset0)
1470 LASSERT(inset0, return);
1472 insert(MathAtom(inset0->asInsetMath()));
1474 text()->insertInset(*this, inset0);
1475 inset0->setBuffer(bv_->buffer());
1477 if (inset0->isLabeled())
1478 forceBufferUpdate();
1483 int Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1485 MathData ar(buffer());
1487 if (ar.size() == 1 && (enter || selection()))
1495 void Cursor::niceInsert(MathAtom const & t)
1498 docstring const safe = cap::grabAndEraseSelection(*this);
1500 // If possible, enter the new inset and move the contents of the selection
1501 if (t->isActive()) {
1503 // be careful here: don't use 'pushBackward(t)' as this we need to
1504 // push the clone, not the original
1505 pushBackward(*nextInset());
1506 // We may not use niceInsert here (recursion)
1507 MathData ar(buffer());
1510 } else if (t->asMacro() && !safe.empty()) {
1511 MathData ar(buffer());
1513 docstring const name = t->asMacro()->name();
1514 MacroData const * data = buffer()->getMacro(name);
1515 if (data && data->numargs() - data->optionals() > 0) {
1516 plainInsert(MathAtom(new InsetMathBrace(ar)));
1523 void Cursor::insert(MathData const & ar)
1527 cap::eraseSelection(*this);
1528 cell().insert(pos(), ar);
1530 // FIXME audit setBuffer calls
1531 inset().setBuffer(bv_->buffer());
1535 bool Cursor::backspace()
1538 cap::eraseSelection(*this);
1543 // If empty cell, and not part of a big cell
1544 if (lastpos() == 0 && inset().nargs() == 1) {
1546 // Directly delete empty cell: [|[]] => [|]
1552 // [|], can not delete from inside
1563 if (inMacroMode()) {
1564 InsetMathUnknown * p = activeMacro();
1565 if (p->name().size() > 1) {
1566 p->setName(p->name().substr(0, p->name().size() - 1));
1571 if (pos() != 0 && prevAtom()->nargs() > 0) {
1572 // let's require two backspaces for 'big stuff' and
1573 // highlight on the first
1585 bool Cursor::erase()
1591 cap::eraseSelection(*this);
1595 // delete empty cells if possible
1596 if (pos() == lastpos() && inset().idxDelete(idx()))
1599 // special behaviour when in last position of cell
1600 if (pos() == lastpos()) {
1601 bool one_cell = inset().nargs() == 1;
1602 if (one_cell && lastpos() == 0) {
1604 // Directly delete empty cell: [|[]] => [|]
1610 // [|], can not delete from inside
1615 inset().idxGlue(idx());
1619 // 'clever' UI hack: only erase large items if previously slected
1620 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
1635 DocIterator save = *this;
1636 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1637 this->dispatch(cmd);
1638 if (disp_.dispatched())
1648 DocIterator save = *this;
1649 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1650 this->dispatch(cmd);
1651 if (disp_.dispatched())
1658 bool Cursor::macroModeClose()
1662 InsetMathUnknown * p = activeMacro();
1664 MathData selection(buffer());
1665 asArray(p->selection(), selection);
1666 docstring const s = p->name();
1668 cell().erase(pos());
1670 // do nothing if the macro name is empty
1674 // trigger updates of macros, at least, if no full
1675 // updates take place anyway
1676 screenUpdateFlags(Update::Force);
1678 docstring const name = s.substr(1);
1679 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1680 if (in && in->interpretString(*this, s))
1682 MathAtom atom = buffer()->getMacro(name, *this, false) ?
1683 MathAtom(new MathMacro(buffer(), name)) : createInsetMath(name, buffer());
1685 // try to put argument into macro, if we just inserted a macro
1686 bool macroArg = false;
1687 MathMacro * atomAsMacro = atom.nucleus()->asMacro();
1689 // macros here are still unfolded (in init mode in fact). So
1690 // we have to resolve the macro here manually and check its arity
1691 // to put the selection behind it if arity > 0.
1692 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1693 if (!selection.empty() && data && data->numargs() - data->optionals() > 0) {
1695 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1697 // non-greedy case. Do not touch the arguments behind
1698 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1701 // insert remembered selection into first argument of a non-macro
1702 else if (atom.nucleus()->nargs() > 0)
1703 atom.nucleus()->cell(0).append(selection);
1707 // finally put the macro argument behind, if needed
1709 if (selection.size() > 1 || selection[0]->asScriptInset())
1710 plainInsert(MathAtom(new InsetMathBrace(selection)));
1719 docstring Cursor::macroName()
1721 return inMacroMode() ? activeMacro()->name() : docstring();
1725 void Cursor::handleNest(MathAtom const & a, int c)
1727 //lyxerr << "Cursor::handleNest: " << c << endl;
1729 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1732 pushBackward(*nextInset());
1736 int Cursor::targetX() const
1738 if (x_target() != -1)
1747 int Cursor::textTargetOffset() const
1749 return textTargetOffset_;
1753 void Cursor::setTargetX()
1762 bool Cursor::inMacroMode() const
1766 if (pos() == 0 || cell().empty())
1768 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1769 return p && !p->final();
1773 InsetMathUnknown * Cursor::activeMacro()
1775 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1779 InsetMathUnknown const * Cursor::activeMacro() const
1781 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1785 void Cursor::pullArg()
1788 MathData ar = cell();
1789 if (popBackward() && inMathed()) {
1791 cell().insert(pos(), ar);
1794 //formula()->mutateToText();
1799 void Cursor::touch()
1803 DocIterator::const_iterator it = begin();
1804 DocIterator::const_iterator et = end();
1805 for ( ; it != et; ++it)
1811 void Cursor::normalize()
1813 if (idx() > lastidx()) {
1814 lyxerr << "this should not really happen - 1: "
1815 << idx() << ' ' << nargs()
1816 << " in: " << &inset() << endl;
1820 if (pos() > lastpos()) {
1821 lyxerr << "this should not really happen - 2: "
1822 << pos() << ' ' << lastpos() << " in idx: " << idx()
1824 odocstringstream os;
1825 WriteStream wi(os, false, true, WriteStream::wsDefault);
1826 inset().asInsetMath()->write(wi);
1827 lyxerr << to_utf8(os.str()) << endl;
1833 bool Cursor::upDownInMath(bool up)
1835 // Be warned: The 'logic' implemented in this function is highly
1836 // fragile. A distance of one pixel or a '<' vs '<=' _really
1837 // matters. So fiddle around with it only if you think you know
1838 // what you are doing!
1842 xo = beforeDispatchPosX_;
1844 // check if we had something else in mind, if not, this is the future
1846 if (x_target_ == -1)
1848 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1849 // In text mode inside the line (not left or right) possibly set a new target_x,
1850 // but only if we are somewhere else than the previous target-offset.
1852 // We want to keep the x-target on subsequent up/down movements
1853 // that cross beyond the end of short lines. Thus a special
1854 // handling when the cursor is at the end of line: Use the new
1855 // x-target only if the old one was before the end of line
1856 // or the old one was after the beginning of the line
1857 bool inRTL = isWithinRtlParagraph(*this);
1861 left = pos() == textRow().endpos();
1862 right = pos() == textRow().pos();
1864 left = pos() == textRow().pos();
1865 right = pos() == textRow().endpos();
1867 if ((!left && !right) ||
1868 (left && !right && xo < x_target_) ||
1869 (!left && right && x_target_ < xo))
1876 // try neigbouring script insets
1878 if (inMathed() && !selection()) {
1881 InsetMathScript const * p = prevAtom()->asScriptInset();
1882 if (p && p->has(up)) {
1884 push(*const_cast<InsetMathScript*>(p));
1885 idx() = p->idxOfScript(up);
1888 // we went in the right direction? Otherwise don't jump into the script
1892 int oy = beforeDispatchPosY_;
1893 if ((!up && y <= oy) ||
1902 if (pos() != lastpos()) {
1903 InsetMathScript const * p = nextAtom()->asScriptInset();
1904 if (p && p->has(up)) {
1905 push(*const_cast<InsetMathScript*>(p));
1906 idx() = p->idxOfScript(up);
1909 // we went in the right direction? Otherwise don't jump into the script
1913 int oy = beforeDispatchPosY_;
1914 if ((!up && y <= oy) ||
1923 // try to find an inset that knows better then we,
1924 if (inset().idxUpDown(*this, up)) {
1925 //lyxerr << "idxUpDown triggered" << endl;
1926 // try to find best position within this inset
1928 setCursor(bruteFind2(*this, xo, yo));
1932 // any improvement going just out of inset?
1933 if (popBackward() && inMathed()) {
1934 //lyxerr << "updown: popBackward succeeded" << endl;
1937 int yold = beforeDispatchPosY_;
1939 if (up ? ynew < yold : ynew > yold)
1943 // no success, we are probably at the document top or bottom
1949 bool Cursor::atFirstOrLastRow(bool up)
1951 TextMetrics const & tm = bv_->textMetrics(text());
1952 ParagraphMetrics const & pm = tm.parMetrics(pit());
1955 if (pos() && boundary())
1956 row = pm.pos2row(pos() - 1);
1958 row = pm.pos2row(pos());
1961 if (pit() == 0 && row == 0)
1964 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1965 row + 1 >= int(pm.rows().size()))
1972 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1974 LASSERT(text(), return false);
1980 xo = beforeDispatchPosX_;
1982 // update the targetX - this is here before the "return false"
1983 // to set a new target which can be used by InsetTexts above
1984 // if we cannot move up/down inside this inset anymore
1985 if (x_target_ == -1)
1987 else if (xo - textTargetOffset() != x_target() &&
1988 depth() == beforeDispatchCursor_.depth()) {
1989 // In text mode inside the line (not left or right)
1990 // possibly set a new target_x, but only if we are
1991 // somewhere else than the previous target-offset.
1993 // We want to keep the x-target on subsequent up/down
1994 // movements that cross beyond the end of short lines.
1995 // Thus a special handling when the cursor is at the
1996 // end of line: Use the new x-target only if the old
1997 // one was before the end of line or the old one was
1998 // after the beginning of the line
1999 bool inRTL = isWithinRtlParagraph(*this);
2003 left = pos() == textRow().endpos();
2004 right = pos() == textRow().pos();
2006 left = pos() == textRow().pos();
2007 right = pos() == textRow().endpos();
2009 if ((!left && !right) ||
2010 (left && !right && xo < x_target_) ||
2011 (!left && right && x_target_ < xo))
2018 // first get the current line
2019 TextMetrics & tm = bv_->textMetrics(text());
2020 ParagraphMetrics const & pm = tm.parMetrics(pit());
2022 if (pos() && boundary())
2023 row = pm.pos2row(pos() - 1);
2025 row = pm.pos2row(pos());
2027 if (atFirstOrLastRow(up)) {
2028 // Is there a place for the cursor to go ? If yes, we
2029 // can execute the DEPM, otherwise we should keep the
2030 // paragraph to host the cursor.
2031 Cursor dummy = *this;
2032 bool valid_destination = false;
2033 for(; dummy.depth(); dummy.pop())
2034 if (!dummy.atFirstOrLastRow(up)) {
2035 valid_destination = true;
2039 // will a next dispatch follow and if there is a new
2040 // dispatch will it move the cursor out ?
2041 if (depth() > 1 && valid_destination) {
2042 // The cursor hasn't changed yet. This happens when
2043 // you e.g. move out of an inset. And to give the
2044 // DEPM the possibility of doing something we must
2045 // provide it with two different cursors. (Lgb, vfr)
2047 dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
2048 dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
2050 updateNeeded |= bv().checkDepm(dummy, *this);
2051 updateTextTargetOffset();
2053 forceBufferUpdate();
2058 // with and without selection are handled differently
2060 int yo = bv().getPos(*this).y_;
2062 // To next/previous row
2064 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
2066 tm.editXY(*this, xo, yo + textRow().descent() + 1);
2069 // This happens when you move out of an inset.
2070 // And to give the DEPM the possibility of doing
2071 // something we must provide it with two different
2073 Cursor dummy = *this;
2076 if (bv().checkDepm(dummy, old)) {
2077 updateNeeded = true;
2078 // Make sure that cur gets back whatever happened to dummy (Lgb)
2082 // if there is a selection, we stay out of any inset,
2083 // and just jump to the right position:
2089 } else if (pit() > 0) {
2091 TextMetrics & tm = bv_->textMetrics(text());
2092 if (!tm.contains(pit()))
2093 tm.newParMetricsUp();
2094 ParagraphMetrics const & pmcur = tm.parMetrics(pit());
2095 next_row = pmcur.rows().size() - 1;
2098 if (row + 1 < int(pm.rows().size())) {
2100 } else if (pit() + 1 < int(text()->paragraphs().size())) {
2102 TextMetrics & tm = bv_->textMetrics(text());
2103 if (!tm.contains(pit()))
2104 tm.newParMetricsDown();
2109 Row const & real_next_row = tm.parMetrics(pit()).rows()[next_row];
2111 pos_type const col = tm.getColumnNearX(pit(), real_next_row,
2113 top().pos() = real_next_row.pos() + col;
2116 updateNeeded |= bv().checkDepm(*this, old);
2120 forceBufferUpdate();
2121 updateTextTargetOffset();
2126 void Cursor::handleFont(string const & font)
2128 LYXERR(Debug::DEBUG, font);
2132 safe = cap::grabAndEraseSelection(*this);
2137 if (lastpos() != 0) {
2138 // something left in the cell
2140 // cursor in first position
2142 } else if (pos() == lastpos()) {
2143 // cursor in last position
2146 // cursor in between. split cell
2147 MathData::iterator bt = cell().begin();
2148 MathAtom at = createInsetMath(from_utf8(font), buffer());
2149 at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
2150 cell().erase(bt, bt + pos());
2155 // nothing left in the cell
2164 void Cursor::message(docstring const & msg) const
2166 disp_.setMessage(msg);
2170 void Cursor::errorMessage(docstring const & msg) const
2172 disp_.setMessage(msg);
2173 disp_.setError(true);
2179 docstring parbreak(Cursor const * cur)
2181 odocstringstream os;
2183 // only add blank line if we're not in a ParbreakIsNewline situation
2184 if (!cur->inset().getLayout().parbreakIsNewline()
2185 && !cur->paragraph().layout().parbreak_is_newline)
2193 docstring Cursor::selectionAsString(bool with_label) const
2199 return cap::grabSelection(*this);
2201 int const label = with_label
2202 ? AS_STR_LABEL | AS_STR_INSETS : AS_STR_INSETS;
2204 idx_type const startidx = selBegin().idx();
2205 idx_type const endidx = selEnd().idx();
2206 if (startidx != endidx) {
2207 // multicell selection
2208 InsetTabular * table = inset().asInsetTabular();
2209 LASSERT(table, return docstring());
2210 return table->asString(startidx, endidx);
2213 ParagraphList const & pars = text()->paragraphs();
2215 pit_type const startpit = selBegin().pit();
2216 pit_type const endpit = selEnd().pit();
2217 size_t const startpos = selBegin().pos();
2218 size_t const endpos = selEnd().pos();
2220 if (startpit == endpit)
2221 return pars[startpit].asString(startpos, endpos, label);
2223 // First paragraph in selection
2224 docstring result = pars[startpit].
2225 asString(startpos, pars[startpit].size(), label)
2228 // The paragraphs in between (if any)
2229 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
2230 Paragraph const & par = pars[pit];
2231 result += par.asString(0, par.size(), label)
2235 // Last paragraph in selection
2236 result += pars[endpit].asString(0, endpos, label);
2242 docstring Cursor::currentState() const
2245 odocstringstream os;
2251 return text()->currentState(*this);
2257 docstring Cursor::getPossibleLabel() const
2259 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
2263 Encoding const * Cursor::getEncoding() const
2267 CursorSlice const & sl = innerTextSlice();
2268 Text const & text = *sl.text();
2269 Font font = text.getPar(sl.pit()).getFont(
2270 bv().buffer().params(), sl.pos(), text.outerFont(sl.pit()));
2271 return font.language()->encoding();
2275 void Cursor::undispatched() const
2277 disp_.dispatched(false);
2281 void Cursor::dispatched() const
2283 disp_.dispatched(true);
2287 void Cursor::screenUpdateFlags(Update::flags f) const
2289 disp_.screenUpdate(f);
2293 void Cursor::forceBufferUpdate() const
2295 disp_.forceBufferUpdate();
2299 void Cursor::clearBufferUpdate() const
2301 disp_.clearBufferUpdate();
2305 bool Cursor::needBufferUpdate() const
2307 return disp_.needBufferUpdate();
2311 void Cursor::noScreenUpdate() const
2313 disp_.screenUpdate(Update::None);
2317 Font Cursor::getFont() const
2319 // The logic here should more or less match to the
2320 // Cursor::setCurrentFont logic, i.e. the cursor height should
2321 // give a hint what will happen if a character is entered.
2323 // HACK. far from being perfect...
2325 CursorSlice const & sl = innerTextSlice();
2326 Text const & text = *sl.text();
2327 Paragraph const & par = text.getPar(sl.pit());
2329 // on boundary, so we are really at the character before
2330 pos_type pos = sl.pos();
2331 if (pos > 0 && boundary())
2334 // on space? Take the font before (only for RTL boundary stay)
2336 TextMetrics const & tm = bv().textMetrics(&text);
2337 if (pos == sl.lastpos()
2338 || (par.isSeparator(pos)
2339 && !tm.isRTLBoundary(sl.pit(), pos)))
2343 // get font at the position
2344 Font font = par.getFont(buffer()->params(), pos,
2345 text.outerFont(sl.pit()));
2351 bool Cursor::fixIfBroken()
2353 bool const broken_cursor = DocIterator::fixIfBroken();
2354 bool const broken_anchor = anchor_.fixIfBroken();
2356 if (broken_cursor || broken_anchor) {
2357 clearNewWordPosition();
2365 void Cursor::sanitize()
2367 setBuffer(&bv_->buffer());
2368 DocIterator::sanitize();
2373 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2375 // find inset in common
2377 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2378 if (&old[i].inset() != &cur[i].inset())
2382 // update words if we just moved to another paragraph
2383 if (i == old.depth() && i == cur.depth()
2384 && !cur.buffer()->isClean()
2385 && cur.inTexted() && old.inTexted()
2386 && cur.pit() != old.pit()) {
2387 old.paragraph().updateWords();
2390 // notify everything on top of the common part in old cursor,
2391 // but stop if the inset claims the cursor to be invalid now
2392 for (size_type j = i; j < old.depth(); ++j) {
2393 Cursor inset_pos = old;
2394 inset_pos.cutOff(j);
2395 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2399 // notify everything on top of the common part in new cursor,
2400 // but stop if the inset claims the cursor to be invalid now
2401 for (; i < cur.depth(); ++i) {
2402 if (cur[i].inset().notifyCursorEnters(cur))
2410 void Cursor::setCurrentFont()
2412 CursorSlice const & cs = innerTextSlice();
2413 Paragraph const & par = cs.paragraph();
2414 pos_type cpit = cs.pit();
2415 pos_type cpos = cs.pos();
2416 Text const & ctext = *cs.text();
2417 TextMetrics const & tm = bv().textMetrics(&ctext);
2419 // are we behind previous char in fact? -> go to that char
2420 if (cpos > 0 && boundary())
2423 // find position to take the font from
2425 // paragraph end? -> font of last char
2426 if (cpos == lastpos())
2428 // on space? -> look at the words in front of space
2429 else if (cpos > 0 && par.isSeparator(cpos)) {
2430 // abc| def -> font of c
2431 // abc |[WERBEH], i.e. boundary==true -> font of c
2432 // abc [WERBEH]| def, font of the space
2433 if (!tm.isRTLBoundary(cpit, cpos))
2439 BufferParams const & bufparams = buffer()->params();
2440 current_font = par.getFontSettings(bufparams, cpos);
2441 real_current_font = tm.displayFont(cpit, cpos);
2443 // special case for paragraph end
2444 if (cs.pos() == lastpos()
2445 && tm.isRTLBoundary(cpit, cs.pos())
2447 Language const * lang = par.getParLanguage(bufparams);
2448 current_font.setLanguage(lang);
2449 current_font.fontInfo().setNumber(FONT_OFF);
2450 real_current_font.setLanguage(lang);
2451 real_current_font.fontInfo().setNumber(FONT_OFF);
2456 bool Cursor::textUndo()
2458 if (!buffer()->undo().textUndo(*this))
2465 bool Cursor::textRedo()
2467 if (!buffer()->undo().textRedo(*this))
2474 void Cursor::finishUndo() const
2476 buffer()->undo().finishUndo();
2480 void Cursor::beginUndoGroup() const
2482 buffer()->undo().beginUndoGroup();
2486 void Cursor::endUndoGroup() const
2488 buffer()->undo().endUndoGroup(*this);
2492 void Cursor::recordUndo(UndoKind kind, pit_type from, pit_type to) const
2494 buffer()->undo().recordUndo(*this, kind, from, to);
2498 void Cursor::recordUndo(UndoKind kind, pit_type from) const
2500 buffer()->undo().recordUndo(*this, kind, from);
2504 void Cursor::recordUndo(UndoKind kind) const
2506 buffer()->undo().recordUndo(*this, kind);
2510 void Cursor::recordUndoInset(UndoKind kind, Inset const * inset) const
2512 buffer()->undo().recordUndoInset(*this, kind, inset);
2516 void Cursor::recordUndoFullDocument() const
2518 buffer()->undo().recordUndoFullDocument(*this);
2522 void Cursor::recordUndoSelection() const
2525 if (cap::multipleCellsSelected(*this))
2530 buffer()->undo().recordUndo(*this, ATOMIC_UNDO,
2531 selBegin().pit(), selEnd().pit());
2536 void Cursor::checkBufferStructure()
2538 Buffer const * master = buffer()->masterBuffer();
2539 master->tocBackend().updateItem(*this);
2540 if (master != buffer() && !master->hasGuiDelegate())
2541 // In case the master has no gui associated with it,
2542 // the TocItem is not updated (part of bug 5699).
2543 buffer()->tocBackend().updateItem(*this);