3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alejandro Aguilar Sierra
7 * \author Alfredo Braunstein
8 * \author Dov Feldstern
10 * \author Stefan Schimanski
12 * Full author contact details are available in file CREDITS.
19 #include "BufferView.h"
20 #include "CoordCache.h"
22 #include "CutAndPaste.h"
23 #include "DispatchResult.h"
27 #include "FuncRequest.h"
29 #include "LyXAction.h"
30 #include "LyXFunc.h" // only for setMessage()
32 #include "Paragraph.h"
33 #include "ParIterator.h"
36 #include "TextMetrics.h"
37 #include "TocBackend.h"
39 #include "support/lassert.h"
40 #include "support/debug.h"
41 #include "support/docstream.h"
43 #include "insets/InsetTabular.h"
44 #include "insets/InsetText.h"
46 #include "mathed/InsetMath.h"
47 #include "mathed/InsetMathBrace.h"
48 #include "mathed/InsetMathScript.h"
49 #include "mathed/MacroTable.h"
50 #include "mathed/MathData.h"
51 #include "mathed/MathMacro.h"
53 #include <boost/bind.hpp>
65 bool positionable(DocIterator const & cursor, DocIterator const & anchor)
67 // avoid deeper nested insets when selecting
68 if (cursor.depth() > anchor.depth())
71 // anchor might be deeper, should have same path then
72 for (size_t i = 0; i < cursor.depth(); ++i)
73 if (&cursor[i].inset() != &anchor[i].inset())
76 // position should be ok.
81 // Find position closest to (x, y) in cell given by iter.
82 // Used only in mathed
83 DocIterator bruteFind2(Cursor const & c, int x, int y)
85 double best_dist = numeric_limits<double>::max();
92 et.top().pos() = et.top().asInsetMath()->cell(et.top().idx()).size();
93 for (size_t i = 0;; ++i) {
96 Inset const * inset = &it.inset();
97 map<Inset const *, Geometry> const & data =
98 c.bv().coordCache().getInsets().getData();
99 map<Inset const *, Geometry>::const_iterator I = data.find(inset);
101 // FIXME: in the case where the inset is not in the cache, this
102 // means that no part of it is visible on screen. In this case
103 // we don't do elaborate search and we just return the forwarded
104 // DocIterator at its beginning.
105 if (I == data.end()) {
110 Point o = I->second.pos;
111 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
112 // Convert to absolute
115 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
116 // '<=' in order to take the last possible position
117 // this is important for clicking behind \sum in e.g. '\sum_i a'
118 LYXERR(Debug::DEBUG, "i: " << i << " d: " << d
119 << " best: " << best_dist);
120 if (d <= best_dist) {
133 /// moves position closest to (x, y) in given box
134 bool bruteFind(Cursor & cursor,
135 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
137 LASSERT(!cursor.empty(), return false);
138 Inset & inset = cursor[0].inset();
139 BufferView & bv = cursor.bv();
141 CoordCache::InnerParPosCache const & cache =
142 bv.coordCache().getParPos().find(cursor.bottom().text())->second;
143 // Get an iterator on the first paragraph in the cache
144 DocIterator it(inset);
145 it.push_back(CursorSlice(inset));
146 it.pit() = cache.begin()->first;
147 // Get an iterator after the last paragraph in the cache
148 DocIterator et(inset);
149 et.push_back(CursorSlice(inset));
150 et.pit() = boost::prior(cache.end())->first;
151 if (et.pit() >= et.lastpit())
152 et = doc_iterator_end(inset);
156 double best_dist = numeric_limits<double>::max();;
157 DocIterator best_cursor = et;
159 for ( ; it != et; it.forwardPos(true)) {
160 // avoid invalid nesting when selecting
161 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
162 Point p = bv.getPos(it, false);
165 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
166 double const dx = xo - x;
167 double const dy = yo - y;
168 double const d = dx * dx + dy * dy;
169 // '<=' in order to take the last possible position
170 // this is important for clicking behind \sum in e.g. '\sum_i a'
171 if (d <= best_dist) {
172 // lyxerr << "*" << endl;
180 if (best_cursor != et) {
181 cursor.setCursor(best_cursor);
190 /// moves position closest to (x, y) in given box
191 bool bruteFind3(Cursor & cur, int x, int y, bool up)
193 BufferView & bv = cur.bv();
194 int ylow = up ? 0 : y + 1;
195 int yhigh = up ? y - 1 : bv.workHeight();
197 int xhigh = bv.workWidth();
199 // FIXME: bit more work needed to get 'from' and 'to' right.
200 pit_type from = cur.bottom().pit();
201 //pit_type to = cur.bottom().pit();
202 //lyxerr << "Pit start: " << from << endl;
204 //lyxerr << "bruteFind3: x: " << x << " y: " << y
205 // << " xlow: " << xlow << " xhigh: " << xhigh
206 // << " ylow: " << ylow << " yhigh: " << yhigh
208 DocIterator it = doc_iterator_begin(cur.buffer());
210 DocIterator et = doc_iterator_end(cur.buffer());
212 double best_dist = numeric_limits<double>::max();
213 DocIterator best_cursor = et;
215 for ( ; it != et; it.forwardPos()) {
216 // avoid invalid nesting when selecting
217 if (bv.cursorStatus(it) == CUR_INSIDE
218 && (!cur.selection() || positionable(it, cur.anchor_))) {
219 Point p = bv.getPos(it, false);
222 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
223 double const dx = xo - x;
224 double const dy = yo - y;
225 double const d = dx * dx + dy * dy;
226 //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
227 // << " dx: " << dx << " dy: " << dy
228 // << " idx: " << it.idx() << " pos: " << it.pos()
231 // '<=' in order to take the last possible position
232 // this is important for clicking behind \sum in e.g. '\sum_i a'
233 if (d <= best_dist) {
234 //lyxerr << "*" << endl;
242 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
243 if (best_cursor == et)
245 cur.setCursor(best_cursor);
252 // be careful: this is called from the bv's constructor, too, so
253 // bv functions are not yet available!
254 Cursor::Cursor(BufferView & bv)
255 : DocIterator(&bv.buffer()), bv_(&bv), anchor_(),
256 x_target_(-1), textTargetOffset_(0),
257 selection_(false), mark_(false), word_selection_(false),
258 logicalpos_(false), current_font(inherit_font)
265 push_back(CursorSlice(buffer()->inset()));
266 anchor_ = doc_iterator_begin(buffer());
274 // this (intentionally) does neither touch anchor nor selection status
275 void Cursor::setCursor(DocIterator const & cur)
277 DocIterator::operator=(cur);
281 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
285 // Try to fix cursor in case it is broken.
288 // Is this a function that acts on inset at point?
289 Inset * inset = cur.nextInset();
290 if (lyxaction.funcHasFlag(cmd.action, LyXAction::AtPoint)
291 && inset && inset->getStatus(cur, cmd, status))
294 // This is, of course, a mess. Better create a new doc iterator and use
295 // this in Inset::getStatus. This might require an additional
296 // BufferView * arg, though (which should be avoided)
297 //Cursor safe = *this;
299 for ( ; cur.depth(); cur.pop()) {
300 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
301 LASSERT(cur.idx() <= cur.lastidx(), /**/);
302 LASSERT(cur.pit() <= cur.lastpit(), /**/);
303 LASSERT(cur.pos() <= cur.lastpos(), /**/);
305 // The inset's getStatus() will return 'true' if it made
306 // a definitive decision on whether it want to handle the
307 // request or not. The result of this decision is put into
308 // the 'status' parameter.
309 if (cur.inset().getStatus(cur, cmd, status)) {
318 void Cursor::dispatch(FuncRequest const & cmd0)
320 LYXERR(Debug::DEBUG, "cmd: " << cmd0 << '\n' << *this);
325 FuncRequest cmd = cmd0;
328 buffer()->undo().beginUndoGroup();
330 // Is this a function that acts on inset at point?
331 if (lyxaction.funcHasFlag(cmd.action, LyXAction::AtPoint)
333 result().dispatched(true);
334 result().update(Update::FitCursor | Update::Force);
335 FuncRequest tmpcmd = cmd;
336 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
337 << cmd0 << endl << *this);
338 nextInset()->dispatch(*this, tmpcmd);
339 if (result().dispatched()) {
340 buffer()->undo().endUndoGroup();
345 // store some values to be used inside of the handlers
346 beforeDispatchCursor_ = *this;
347 for (; depth(); pop(), boundary(false)) {
348 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
349 << cmd0 << endl << *this);
350 LASSERT(pos() <= lastpos(), /**/);
351 LASSERT(idx() <= lastidx(), /**/);
352 LASSERT(pit() <= lastpit(), /**/);
354 // The common case is 'LFUN handled, need update', so make the
355 // LFUN handler's life easier by assuming this as default value.
356 // The handler can reset the update and val flags if necessary.
357 disp_.update(Update::FitCursor | Update::Force);
358 disp_.dispatched(true);
359 inset().dispatch(*this, cmd);
360 if (disp_.dispatched())
364 // it completely to get a 'bomb early' behaviour in case this
365 // object will be used again.
366 if (!disp_.dispatched()) {
367 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
368 // We might have invalidated the cursor when removing an empty
369 // paragraph while the cursor could not be moved out the inset
370 // while we initially thought we could. This might happen when
371 // a multiline inset becomes an inline inset when the second
372 // paragraph is removed.
373 if (safe.pit() > safe.lastpit()) {
374 safe.pit() = safe.lastpit();
375 safe.pos() = safe.lastpos();
378 disp_.update(Update::None);
379 disp_.dispatched(false);
381 // restore the previous one because nested Cursor::dispatch calls
382 // are possible which would change it
383 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
385 buffer()->undo().endUndoGroup();
389 DispatchResult Cursor::result() const
395 BufferView & Cursor::bv() const
404 LASSERT(depth() >= 1, /**/);
409 void Cursor::push(Inset & p)
411 push_back(CursorSlice(p));
412 p.setBuffer(*buffer());
416 void Cursor::pushBackward(Inset & p)
418 LASSERT(!empty(), return);
419 //lyxerr << "Entering inset " << t << " front" << endl;
425 bool Cursor::popBackward()
427 LASSERT(!empty(), return false);
435 bool Cursor::popForward()
437 LASSERT(!empty(), return false);
438 //lyxerr << "Leaving inset from in back" << endl;
439 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
443 pos() += lastpos() - lp + 1;
448 int Cursor::currentMode()
450 LASSERT(!empty(), /**/);
451 for (int i = depth() - 1; i >= 0; --i) {
452 int res = operator[](i).inset().currentMode();
453 bool locked_mode = operator[](i).inset().lockedMode();
454 // Also return UNDECIDED_MODE when the mode is locked,
455 // as in this case it is treated the same as TEXT_MODE
456 if (res != Inset::UNDECIDED_MODE || locked_mode)
459 return Inset::TEXT_MODE;
463 void Cursor::getPos(int & x, int & y) const
465 Point p = bv().getPos(*this, boundary());
471 Row const & Cursor::textRow() const
473 CursorSlice const & cs = innerTextSlice();
474 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
475 LASSERT(!pm.rows().empty(), /**/);
476 return pm.getRow(pos(), boundary());
480 void Cursor::resetAnchor()
486 void Cursor::setCursorToAnchor()
489 DocIterator normal = anchor_;
490 while (depth() < normal.depth())
492 if (depth() < anchor_.depth() && top() <= anchor_[depth() - 1])
499 bool Cursor::posBackward()
508 bool Cursor::posForward()
510 if (pos() == lastpos())
517 bool Cursor::posVisRight(bool skip_inset)
519 Cursor new_cur = *this; // where we will move to
520 pos_type left_pos; // position visually left of current cursor
521 pos_type right_pos; // position visually right of current cursor
522 bool new_pos_is_RTL; // is new position we're moving to RTL?
524 getSurroundingPos(left_pos, right_pos);
526 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
528 // Are we at an inset?
529 new_cur.pos() = right_pos;
530 new_cur.boundary(false);
532 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
533 // we actually move the cursor at the end of this function, for now
534 // we just keep track of the new position in new_cur...
535 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
538 // Are we already at rightmost pos in row?
539 else if (text()->empty() || right_pos == -1) {
542 if (!new_cur.posVisToNewRow(false)) {
543 LYXERR(Debug::RTL, "not moving!");
547 // we actually move the cursor at the end of this function, for now
548 // just keep track of the new position in new_cur...
549 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
550 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
553 // normal movement to the right
556 // Recall, if the cursor is at position 'x', that means *before*
557 // the character at position 'x'. In RTL, "before" means "to the
558 // right of", in LTR, "to the left of". So currently our situation
559 // is this: the position to our right is 'right_pos' (i.e., we're
560 // currently to the left of 'right_pos'). In order to move to the
561 // right, it depends whether or not the character at 'right_pos' is RTL.
562 new_pos_is_RTL = paragraph().getFontSettings(
563 buffer()->params(), right_pos).isVisibleRightToLeft();
564 // If the character at 'right_pos' *is* LTR, then in order to move to
565 // the right of it, we need to be *after* 'right_pos', i.e., move to
566 // position 'right_pos' + 1.
567 if (!new_pos_is_RTL) {
568 new_cur.pos() = right_pos + 1;
569 // set the boundary to true in two situations:
571 // 1. if new_pos is now lastpos, and we're in an RTL paragraph
572 // (this means that we're moving right to the end of an LTR chunk
573 // which is at the end of an RTL paragraph);
574 (new_cur.pos() == lastpos()
575 && paragraph().isRTL(buffer()->params()))
576 // 2. if the position *after* right_pos is RTL (we want to be
577 // *after* right_pos, not before right_pos + 1!)
578 || paragraph().getFontSettings(buffer()->params(),
579 new_cur.pos()).isVisibleRightToLeft()
581 new_cur.boundary(true);
582 else // set the boundary to false
583 new_cur.boundary(false);
585 // Otherwise (if the character at position 'right_pos' is RTL), then
586 // moving to the right of it is as easy as setting the new position
589 new_cur.pos() = right_pos;
590 new_cur.boundary(false);
595 bool moved = (new_cur.pos() != pos()
596 || new_cur.pit() != pit()
597 || new_cur.boundary() != boundary()
598 || &new_cur.inset() != &inset());
601 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
602 << (new_cur.boundary() ? " (boundary)" : ""));
610 bool Cursor::posVisLeft(bool skip_inset)
612 Cursor new_cur = *this; // where we will move to
613 pos_type left_pos; // position visually left of current cursor
614 pos_type right_pos; // position visually right of current cursor
615 bool new_pos_is_RTL; // is new position we're moving to RTL?
617 getSurroundingPos(left_pos, right_pos);
619 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
621 // Are we at an inset?
622 new_cur.pos() = left_pos;
623 new_cur.boundary(false);
625 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
626 // we actually move the cursor at the end of this function, for now
627 // we just keep track of the new position in new_cur...
628 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
631 // Are we already at leftmost pos in row?
632 else if (text()->empty() || left_pos == -1) {
635 if (!new_cur.posVisToNewRow(true)) {
636 LYXERR(Debug::RTL, "not moving!");
640 // we actually move the cursor at the end of this function, for now
641 // just keep track of the new position in new_cur...
642 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
643 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
646 // normal movement to the left
649 // Recall, if the cursor is at position 'x', that means *before*
650 // the character at position 'x'. In RTL, "before" means "to the
651 // right of", in LTR, "to the left of". So currently our situation
652 // is this: the position to our left is 'left_pos' (i.e., we're
653 // currently to the right of 'left_pos'). In order to move to the
654 // left, it depends whether or not the character at 'left_pos' is RTL.
655 new_pos_is_RTL = paragraph().getFontSettings(
656 buffer()->params(), left_pos).isVisibleRightToLeft();
657 // If the character at 'left_pos' *is* RTL, then in order to move to
658 // the left of it, we need to be *after* 'left_pos', i.e., move to
659 // position 'left_pos' + 1.
660 if (new_pos_is_RTL) {
661 new_cur.pos() = left_pos + 1;
662 // set the boundary to true in two situations:
664 // 1. if new_pos is now lastpos and we're in an LTR paragraph
665 // (this means that we're moving left to the end of an RTL chunk
666 // which is at the end of an LTR paragraph);
667 (new_cur.pos() == lastpos()
668 && !paragraph().isRTL(buffer()->params()))
669 // 2. if the position *after* left_pos is not RTL (we want to be
670 // *after* left_pos, not before left_pos + 1!)
671 || !paragraph().getFontSettings(buffer()->params(),
672 new_cur.pos()).isVisibleRightToLeft()
674 new_cur.boundary(true);
675 else // set the boundary to false
676 new_cur.boundary(false);
678 // Otherwise (if the character at position 'left_pos' is LTR), then
679 // moving to the left of it is as easy as setting the new position
682 new_cur.pos() = left_pos;
683 new_cur.boundary(false);
688 bool moved = (new_cur.pos() != pos()
689 || new_cur.pit() != pit()
690 || new_cur.boundary() != boundary());
693 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
694 << (new_cur.boundary() ? " (boundary)" : ""));
702 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos)
704 // preparing bidi tables
705 Paragraph const & par = paragraph();
706 Buffer const & buf = *buffer();
707 Row const & row = textRow();
709 bidi.computeTables(par, buf, row);
711 LYXERR(Debug::RTL, "bidi: " << row.pos() << "--" << row.endpos());
713 // The cursor is painted *before* the character at pos(), or, if 'boundary'
714 // is true, *after* the character at (pos() - 1). So we already have one
715 // known position around the cursor:
716 pos_type const known_pos = boundary() && pos() > 0 ? pos() - 1 : pos();
718 // edge case: if we're at the end of the paragraph, things are a little
719 // different (because lastpos is a position which does not really "exist"
720 // --- there's no character there yet).
721 if (known_pos == lastpos()) {
722 if (par.isRTL(buf.params())) {
724 right_pos = bidi.vis2log(row.pos());
728 left_pos = bidi.vis2log(row.endpos() - 1);
733 // Whether 'known_pos' is to the left or to the right of the cursor depends
734 // on whether it is an RTL or LTR character...
735 bool const cur_is_RTL =
736 par.getFontSettings(buf.params(), known_pos).isVisibleRightToLeft();
737 // ... in the following manner:
738 // For an RTL character, "before" means "to the right" and "after" means
739 // "to the left"; and for LTR, it's the reverse. So, 'known_pos' is to the
740 // right of the cursor if (RTL && boundary) or (!RTL && !boundary):
741 bool const known_pos_on_right = cur_is_RTL == boundary();
743 // So we now know one of the positions surrounding the cursor. Let's
744 // determine the other one:
745 if (known_pos_on_right) {
746 right_pos = known_pos;
747 // *visual* position of 'left_pos':
748 pos_type v_left_pos = bidi.log2vis(right_pos) - 1;
749 // If the position we just identified as 'left_pos' is a "skipped
750 // separator" (a separator which is at the logical end of a row,
751 // except for the last row in a paragraph; such separators are not
752 // painted, so they "are not really there"; note that in bidi text,
753 // such a separator could appear visually in the middle of a row),
754 // set 'left_pos' to the *next* position to the left.
755 if (bidi.inRange(v_left_pos)
756 && bidi.vis2log(v_left_pos) + 1 == row.endpos()
757 && row.endpos() < lastpos()
758 && par.isSeparator(bidi.vis2log(v_left_pos)))
761 // calculate the logical position of 'left_pos', if in row
762 if (!bidi.inRange(v_left_pos))
765 left_pos = bidi.vis2log(v_left_pos);
766 // If the position we identified as 'right_pos' is a "skipped
767 // separator", set 'right_pos' to the *next* position to the right.
768 if (right_pos + 1 == row.endpos() && row.endpos() < lastpos()
769 && par.isSeparator(right_pos)) {
770 pos_type const v_right_pos = bidi.log2vis(right_pos) + 1;
771 if (!bidi.inRange(v_right_pos))
774 right_pos = bidi.vis2log(v_right_pos);
777 // known_pos is on the left
778 left_pos = known_pos;
779 // *visual* position of 'right_pos'
780 pos_type v_right_pos = bidi.log2vis(left_pos) + 1;
781 // If the position we just identified as 'right_pos' is a "skipped
782 // separator", set 'right_pos' to the *next* position to the right.
783 if (bidi.inRange(v_right_pos)
784 && bidi.vis2log(v_right_pos) + 1 == row.endpos()
785 && row.endpos() < lastpos()
786 && par.isSeparator(bidi.vis2log(v_right_pos)))
789 // calculate the logical position of 'right_pos', if in row
790 if (!bidi.inRange(v_right_pos))
793 right_pos = bidi.vis2log(v_right_pos);
794 // If the position we identified as 'left_pos' is a "skipped
795 // separator", set 'left_pos' to the *next* position to the left.
796 if (left_pos + 1 == row.endpos() && row.endpos() < lastpos()
797 && par.isSeparator(left_pos)) {
798 pos_type const v_left_pos = bidi.log2vis(left_pos) - 1;
799 if (!bidi.inRange(v_left_pos))
802 left_pos = bidi.vis2log(v_left_pos);
809 bool Cursor::posVisToNewRow(bool movingLeft)
811 Paragraph const & par = paragraph();
812 Buffer const & buf = *buffer();
813 Row const & row = textRow();
814 bool par_is_LTR = !par.isRTL(buf.params());
816 // Inside a table, determining whether to move to the next or previous row
817 // should be done based on the table's direction.
819 if (s >= 1 && (*this)[s].inset().asInsetTabular()) {
820 par_is_LTR = !(*this)[s].inset().asInsetTabular()->isRightToLeft(*this);
821 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
824 // if moving left in an LTR paragraph or moving right in an RTL one,
825 // move to previous row
826 if (par_is_LTR == movingLeft) {
827 if (row.pos() == 0) { // we're at first row in paragraph
828 if (pit() == 0) // no previous paragraph! don't move
830 // move to last pos in previous par
834 } else { // move to previous row in this par
835 pos() = row.pos() - 1; // this is guaranteed to be in previous row
839 // if moving left in an RTL paragraph or moving right in an LTR one,
842 if (row.endpos() == lastpos()) { // we're at last row in paragraph
843 if (pit() == lastpit()) // last paragraph! don't move
845 // move to first row in next par
849 } else { // move to next row in this par
850 pos() = row.endpos();
855 // make sure we're at left-/right-most pos in new row
856 posVisToRowExtremity(!movingLeft);
862 void Cursor::posVisToRowExtremity(bool left)
864 // prepare bidi tables
865 Paragraph const & par = paragraph();
866 Buffer const & buf = *buffer();
867 Row const & row = textRow();
869 bidi.computeTables(par, buf, row);
871 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
872 << (boundary() ? 1 : 0));
874 if (left) { // move to leftmost position
875 // if this is an RTL paragraph, and we're at the last row in the
876 // paragraph, move to lastpos
877 if (par.isRTL(buf.params()) && row.endpos() == lastpos())
880 pos() = bidi.vis2log(row.pos());
882 // Moving to the leftmost position in the row, the cursor should
883 // normally be placed to the *left* of the leftmost position.
884 // A very common exception, though, is if the leftmost character
885 // also happens to be the separator at the (logical) end of the row
886 // --- in this case, the separator is positioned beyond the left
887 // margin, and we don't want to move the cursor there (moving to
888 // the left of the separator is equivalent to moving to the next
889 // line). So, in this case we actually want to place the cursor
890 // to the *right* of the leftmost position (the separator).
891 // Another exception is if we're moving to the logically last
892 // position in the row, which is *not* a separator: this means
893 // that the entire row has no separators (if there were any, the
894 // row would have been broken there); and therefore in this case
895 // we also move to the *right* of the last position (this indicates
896 // to the user that there is no space after this position, and is
897 // consistent with the behavior in the middle of a row --- moving
898 // right or left moves to the next/previous character; if we were
899 // to move to the *left* of this position, that would simulate
900 // a separator which is not really there!).
901 // Finally, there is an exception to the previous exception: if
902 // this non-separator-but-last-position-in-row is an inset, then
903 // we *do* want to stay to the left of it anyway: this is the
904 // "boundary" which we simulate at insets.
905 // Another exception is when row.endpos() is 0.
907 // do we want to be to the right of pos?
908 // as explained above, if at last pos in row, stay to the right
909 bool const right_of_pos = row.endpos() > 0
910 && pos() == row.endpos() - 1 && !par.isInset(pos());
912 // Now we know if we want to be to the left or to the right of pos,
913 // let's make sure we are where we want to be.
914 bool const new_pos_is_RTL =
915 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
917 if (new_pos_is_RTL != right_of_pos) {
923 // move to rightmost position
924 // if this is an LTR paragraph, and we're at the last row in the
925 // paragraph, move to lastpos
926 if (!par.isRTL(buf.params()) && row.endpos() == lastpos())
929 pos() = row.endpos() > 0 ? bidi.vis2log(row.endpos() - 1) : 0;
931 // Moving to the rightmost position in the row, the cursor should
932 // normally be placed to the *right* of the rightmost position.
933 // A very common exception, though, is if the rightmost character
934 // also happens to be the separator at the (logical) end of the row
935 // --- in this case, the separator is positioned beyond the right
936 // margin, and we don't want to move the cursor there (moving to
937 // the right of the separator is equivalent to moving to the next
938 // line). So, in this case we actually want to place the cursor
939 // to the *left* of the rightmost position (the separator).
940 // Another exception is if we're moving to the logically last
941 // position in the row, which is *not* a separator: this means
942 // that the entire row has no separators (if there were any, the
943 // row would have been broken there); and therefore in this case
944 // we also move to the *left* of the last position (this indicates
945 // to the user that there is no space after this position, and is
946 // consistent with the behavior in the middle of a row --- moving
947 // right or left moves to the next/previous character; if we were
948 // to move to the *right* of this position, that would simulate
949 // a separator which is not really there!).
950 // Finally, there is an exception to the previous exception: if
951 // this non-separator-but-last-position-in-row is an inset, then
952 // we *do* want to stay to the right of it anyway: this is the
953 // "boundary" which we simulate at insets.
954 // Another exception is when row.endpos() is 0.
956 // do we want to be to the left of pos?
957 // as explained above, if at last pos in row, stay to the left,
958 // unless the last position is the same as the first.
959 bool const left_of_pos = row.endpos() > 0
960 && pos() == row.endpos() - 1 && !par.isInset(pos());
962 // Now we know if we want to be to the left or to the right of pos,
963 // let's make sure we are where we want to be.
964 bool const new_pos_is_RTL =
965 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
967 if (new_pos_is_RTL == left_of_pos) {
973 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
974 << (boundary() ? 1 : 0));
978 CursorSlice Cursor::anchor() const
982 LASSERT(anchor_.depth() >= depth(), /**/);
983 CursorSlice normal = anchor_[depth() - 1];
984 if (depth() < anchor_.depth() && top() <= normal) {
985 // anchor is behind cursor -> move anchor behind the inset
992 CursorSlice Cursor::selBegin() const
996 return anchor() < top() ? anchor() : top();
1000 CursorSlice Cursor::selEnd() const
1004 return anchor() > top() ? anchor() : top();
1008 DocIterator Cursor::selectionBegin() const
1014 // FIXME: This is a work-around for the problem that
1015 // CursorSlice doesn't keep track of the boundary.
1016 if (anchor() == top())
1017 di = anchor_.boundary() > boundary() ? anchor_ : *this;
1019 di = anchor() < top() ? anchor_ : *this;
1025 DocIterator Cursor::selectionEnd() const
1031 // FIXME: This is a work-around for the problem that
1032 // CursorSlice doesn't keep track of the boundary.
1033 if (anchor() == top())
1034 di = anchor_.boundary() < boundary() ? anchor_ : *this;
1036 di = anchor() > top() ? anchor_ : *this;
1038 if (di.depth() > depth()) {
1046 void Cursor::setSelection()
1049 // A selection with no contents is not a selection
1050 // FIXME: doesnt look ok
1051 if (idx() == anchor().idx() &&
1052 pit() == anchor().pit() &&
1053 pos() == anchor().pos())
1054 setSelection(false);
1058 void Cursor::setSelection(DocIterator const & where, int n)
1067 void Cursor::clearSelection()
1069 setSelection(false);
1070 setWordSelection(false);
1076 void Cursor::setTargetX(int x)
1079 textTargetOffset_ = 0;
1083 int Cursor::x_target() const
1089 void Cursor::clearTargetX()
1092 textTargetOffset_ = 0;
1096 void Cursor::updateTextTargetOffset()
1101 textTargetOffset_ = x - x_target_;
1105 void Cursor::info(odocstream & os) const
1107 for (int i = 1, n = depth(); i < n; ++i) {
1108 operator[](i).inset().infoize(os);
1112 Inset const * inset = prevInset();
1113 // prevInset() can return 0 in certain case.
1115 prevInset()->infoize2(os);
1117 // overwite old message
1122 bool Cursor::selHandle(bool sel)
1124 //lyxerr << "Cursor::selHandle" << endl;
1127 if (sel == selection())
1131 cap::saveSelection(*this);
1139 ostream & operator<<(ostream & os, Cursor const & cur)
1141 os << "\n cursor: | anchor:\n";
1142 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
1143 os << " " << cur[i] << " | ";
1144 if (i < cur.anchor_.depth())
1145 os << cur.anchor_[i];
1147 os << "-------------------------------";
1150 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
1151 os << "------------------------------- | " << cur.anchor_[i] << "\n";
1153 os << " selection: " << cur.selection_
1154 << " x_target: " << cur.x_target_ << endl;
1159 LyXErr & operator<<(LyXErr & os, Cursor const & cur)
1169 ///////////////////////////////////////////////////////////////////
1172 // The part below is the non-integrated rest of the original math
1173 // cursor. This should be either generalized for texted or moved
1174 // back to mathed (in most cases to InsetMathNest).
1176 ///////////////////////////////////////////////////////////////////
1178 #include "mathed/InsetMathChar.h"
1179 #include "mathed/InsetMathGrid.h"
1180 #include "mathed/InsetMathScript.h"
1181 #include "mathed/InsetMathUnknown.h"
1182 #include "mathed/MathFactory.h"
1183 #include "mathed/MathStream.h"
1184 #include "mathed/MathSupport.h"
1189 //#define FILEDEBUG 1
1192 bool Cursor::isInside(Inset const * p) const
1194 for (size_t i = 0; i != depth(); ++i)
1195 if (&operator[](i).inset() == p)
1201 void Cursor::leaveInset(Inset const & inset)
1203 for (size_t i = 0; i != depth(); ++i) {
1204 if (&operator[](i).inset() == &inset) {
1212 bool Cursor::openable(MathAtom const & t) const
1223 // we can't move into anything new during selection
1224 if (depth() >= anchor_.depth())
1226 if (t.nucleus() != &anchor_[depth()].inset())
1233 void Cursor::setScreenPos(int x, int /*y*/)
1236 //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
1241 void Cursor::plainErase()
1243 cell().erase(pos());
1247 void Cursor::markInsert()
1249 insert(char_type(0));
1253 void Cursor::markErase()
1255 cell().erase(pos());
1259 void Cursor::plainInsert(MathAtom const & t)
1261 cell().insert(pos(), t);
1263 inset().setBuffer(bv_->buffer());
1268 void Cursor::insert(docstring const & str)
1270 for_each(str.begin(), str.end(),
1271 boost::bind(static_cast<void(Cursor::*)(char_type)>
1272 (&Cursor::insert), this, _1));
1276 void Cursor::insert(char_type c)
1278 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1279 LASSERT(!empty(), /**/);
1281 cap::selClearOrDel(*this);
1282 insert(new InsetMathChar(c));
1284 text()->insertChar(*this, c);
1289 void Cursor::insert(MathAtom const & t)
1291 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1293 cap::selClearOrDel(*this);
1298 void Cursor::insert(Inset * inset0)
1300 LASSERT(inset0, /**/);
1302 insert(MathAtom(inset0));
1304 text()->insertInset(*this, inset0);
1305 inset0->setBuffer(bv_->buffer());
1311 void Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1313 MathData ar(buffer());
1315 if (ar.size() == 1 && (enter || selection()))
1322 void Cursor::niceInsert(MathAtom const & t)
1325 docstring const safe = cap::grabAndEraseSelection(*this);
1327 // If possible, enter the new inset and move the contents of the selection
1328 if (t->isActive()) {
1330 // be careful here: don't use 'pushBackward(t)' as this we need to
1331 // push the clone, not the original
1332 pushBackward(*nextInset());
1333 // We may not use niceInsert here (recursion)
1334 MathData ar(buffer());
1341 void Cursor::insert(MathData const & ar)
1345 cap::eraseSelection(*this);
1346 cell().insert(pos(), ar);
1351 bool Cursor::backspace()
1353 autocorrect() = false;
1356 cap::eraseSelection(*this);
1361 // If empty cell, and not part of a big cell
1362 if (lastpos() == 0 && inset().nargs() == 1) {
1364 // Directly delete empty cell: [|[]] => [|]
1370 // [|], can not delete from inside
1381 if (inMacroMode()) {
1382 InsetMathUnknown * p = activeMacro();
1383 if (p->name().size() > 1) {
1384 p->setName(p->name().substr(0, p->name().size() - 1));
1389 if (pos() != 0 && prevAtom()->nargs() > 0) {
1390 // let's require two backspaces for 'big stuff' and
1391 // highlight on the first
1403 bool Cursor::erase()
1405 autocorrect() = false;
1410 cap::eraseSelection(*this);
1414 // delete empty cells if possible
1415 if (pos() == lastpos() && inset().idxDelete(idx()))
1418 // special behaviour when in last position of cell
1419 if (pos() == lastpos()) {
1420 bool one_cell = inset().nargs() == 1;
1421 if (one_cell && lastpos() == 0) {
1423 // Directly delete empty cell: [|[]] => [|]
1429 // [|], can not delete from inside
1434 inset().idxGlue(idx());
1438 // 'clever' UI hack: only erase large items if previously slected
1439 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
1454 DocIterator save = *this;
1455 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1456 this->dispatch(cmd);
1457 if (disp_.dispatched())
1460 autocorrect() = false;
1468 DocIterator save = *this;
1469 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1470 this->dispatch(cmd);
1471 if (disp_.dispatched())
1474 autocorrect() = false;
1479 bool Cursor::macroModeClose()
1483 InsetMathUnknown * p = activeMacro();
1485 MathData selection(buffer());
1486 asArray(p->selection(), selection);
1487 docstring const s = p->name();
1489 cell().erase(pos());
1491 // do nothing if the macro name is empty
1495 // trigger updates of macros, at least, if no full
1496 // updates take place anyway
1497 updateFlags(Update::Force);
1499 docstring const name = s.substr(1);
1500 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1501 if (in && in->interpretString(*this, s))
1503 MathAtom atom = buffer()->getMacro(name, *this, false) ?
1504 MathAtom(new MathMacro(buffer(), name)) : createInsetMath(name, buffer());
1506 // try to put argument into macro, if we just inserted a macro
1507 bool macroArg = false;
1508 MathMacro * atomAsMacro = atom.nucleus()->asMacro();
1510 // macros here are still unfolded (in init mode in fact). So
1511 // we have to resolve the macro here manually and check its arity
1512 // to put the selection behind it if arity > 0.
1513 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1514 if (selection.size() > 0 && data && data->numargs() - data->optionals() > 0) {
1516 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1518 // non-greedy case. Do not touch the arguments behind
1519 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1522 // insert remembered selection into first argument of a non-macro
1523 else if (atom.nucleus()->nargs() > 0)
1524 atom.nucleus()->cell(0).append(selection);
1528 // finally put the macro argument behind, if needed
1530 if (selection.size() > 1 || selection[0]->asScriptInset())
1531 plainInsert(MathAtom(new InsetMathBrace(selection)));
1540 docstring Cursor::macroName()
1542 return inMacroMode() ? activeMacro()->name() : docstring();
1546 void Cursor::handleNest(MathAtom const & a, int c)
1548 //lyxerr << "Cursor::handleNest: " << c << endl;
1550 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1553 pushBackward(*nextInset());
1557 int Cursor::targetX() const
1559 if (x_target() != -1)
1568 int Cursor::textTargetOffset() const
1570 return textTargetOffset_;
1574 void Cursor::setTargetX()
1583 bool Cursor::inMacroMode() const
1589 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1590 return p && !p->final();
1594 InsetMathUnknown * Cursor::activeMacro()
1596 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1600 InsetMathUnknown const * Cursor::activeMacro() const
1602 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1606 void Cursor::pullArg()
1609 MathData ar = cell();
1610 if (popBackward() && inMathed()) {
1612 cell().insert(pos(), ar);
1615 //formula()->mutateToText();
1620 void Cursor::touch()
1624 DocIterator::const_iterator it = begin();
1625 DocIterator::const_iterator et = end();
1626 for ( ; it != et; ++it)
1632 void Cursor::normalize()
1634 if (idx() > lastidx()) {
1635 lyxerr << "this should not really happen - 1: "
1636 << idx() << ' ' << nargs()
1637 << " in: " << &inset() << endl;
1641 if (pos() > lastpos()) {
1642 lyxerr << "this should not really happen - 2: "
1643 << pos() << ' ' << lastpos() << " in idx: " << idx()
1645 odocstringstream os;
1646 WriteStream wi(os, false, true, WriteStream::wsDefault);
1647 inset().asInsetMath()->write(wi);
1648 lyxerr << to_utf8(os.str()) << endl;
1654 bool Cursor::upDownInMath(bool up)
1656 // Be warned: The 'logic' implemented in this function is highly
1657 // fragile. A distance of one pixel or a '<' vs '<=' _really
1658 // matters. So fiddle around with it only if you think you know
1659 // what you are doing!
1663 xo = theLyXFunc().cursorBeforeDispatchX();
1665 // check if we had something else in mind, if not, this is the future
1667 if (x_target_ == -1)
1669 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1670 // In text mode inside the line (not left or right) possibly set a new target_x,
1671 // but only if we are somewhere else than the previous target-offset.
1673 // We want to keep the x-target on subsequent up/down movements
1674 // that cross beyond the end of short lines. Thus a special
1675 // handling when the cursor is at the end of line: Use the new
1676 // x-target only if the old one was before the end of line
1677 // or the old one was after the beginning of the line
1678 bool inRTL = isWithinRtlParagraph(*this);
1682 left = pos() == textRow().endpos();
1683 right = pos() == textRow().pos();
1685 left = pos() == textRow().pos();
1686 right = pos() == textRow().endpos();
1688 if ((!left && !right) ||
1689 (left && !right && xo < x_target_) ||
1690 (!left && right && x_target_ < xo))
1697 // try neigbouring script insets
1699 if (inMathed() && !selection()) {
1702 InsetMathScript const * p = prevAtom()->asScriptInset();
1703 if (p && p->has(up)) {
1705 push(*const_cast<InsetMathScript*>(p));
1706 idx() = p->idxOfScript(up);
1709 // we went in the right direction? Otherwise don't jump into the script
1713 int oy = theLyXFunc().cursorBeforeDispatchY();
1714 if ((!up && y <= oy) ||
1723 if (pos() != lastpos()) {
1724 InsetMathScript const * p = nextAtom()->asScriptInset();
1725 if (p && p->has(up)) {
1726 push(*const_cast<InsetMathScript*>(p));
1727 idx() = p->idxOfScript(up);
1730 // we went in the right direction? Otherwise don't jump into the script
1734 int oy = theLyXFunc().cursorBeforeDispatchY();
1735 if ((!up && y <= oy) ||
1744 // try to find an inset that knows better then we,
1745 if (inset().idxUpDown(*this, up)) {
1746 //lyxerr << "idxUpDown triggered" << endl;
1747 // try to find best position within this inset
1749 setCursor(bruteFind2(*this, xo, yo));
1753 // any improvement going just out of inset?
1754 if (popBackward() && inMathed()) {
1755 //lyxerr << "updown: popBackward succeeded" << endl;
1758 int yold = theLyXFunc().cursorBeforeDispatchY();
1760 if (up ? ynew < yold : ynew > yold)
1764 // no success, we are probably at the document top or bottom
1770 bool Cursor::atFirstOrLastRow(bool up)
1772 TextMetrics const & tm = bv_->textMetrics(text());
1773 ParagraphMetrics const & pm = tm.parMetrics(pit());
1776 if (pos() && boundary())
1777 row = pm.pos2row(pos() - 1);
1779 row = pm.pos2row(pos());
1782 if (pit() == 0 && row == 0)
1785 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1786 row + 1 >= int(pm.rows().size()))
1792 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1794 LASSERT(text(), /**/);
1800 xo = theLyXFunc().cursorBeforeDispatchX();
1802 // update the targetX - this is here before the "return false"
1803 // to set a new target which can be used by InsetTexts above
1804 // if we cannot move up/down inside this inset anymore
1805 if (x_target_ == -1)
1807 else if (xo - textTargetOffset() != x_target() &&
1808 depth() == beforeDispatchCursor_.depth()) {
1809 // In text mode inside the line (not left or right) possibly set a new target_x,
1810 // but only if we are somewhere else than the previous target-offset.
1812 // We want to keep the x-target on subsequent up/down movements
1813 // that cross beyond the end of short lines. Thus a special
1814 // handling when the cursor is at the end of line: Use the new
1815 // x-target only if the old one was before the end of line
1816 // or the old one was after the beginning of the line
1817 bool inRTL = isWithinRtlParagraph(*this);
1821 left = pos() == textRow().endpos();
1822 right = pos() == textRow().pos();
1824 left = pos() == textRow().pos();
1825 right = pos() == textRow().endpos();
1827 if ((!left && !right) ||
1828 (left && !right && xo < x_target_) ||
1829 (!left && right && x_target_ < xo))
1836 // first get the current line
1837 TextMetrics & tm = bv_->textMetrics(text());
1838 ParagraphMetrics const & pm = tm.parMetrics(pit());
1840 if (pos() && boundary())
1841 row = pm.pos2row(pos() - 1);
1843 row = pm.pos2row(pos());
1845 if (atFirstOrLastRow(up)) {
1846 // Is there a place for the cursor to go ? If yes, we
1847 // can execute the DEPM, otherwise we should keep the
1848 // paragraph to host the cursor.
1849 Cursor dummy = *this;
1850 bool valid_destination = false;
1851 for(; dummy.depth(); dummy.pop())
1852 if (!dummy.atFirstOrLastRow(up)) {
1853 valid_destination = true;
1857 // will a next dispatch follow and if there is a new
1858 // dispatch will it move the cursor out ?
1859 if (depth() > 1 && valid_destination) {
1860 // The cursor hasn't changed yet. This happens when
1861 // you e.g. move out of an inset. And to give the
1862 // DEPM the possibility of doing something we must
1863 // provide it with two different cursors. (Lgb, vfr)
1865 dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
1866 dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
1868 updateNeeded |= bv().checkDepm(dummy, *this);
1869 updateTextTargetOffset();
1874 // with and without selection are handled differently
1876 int yo = bv().getPos(*this, boundary()).y_;
1878 // To next/previous row
1880 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1882 tm.editXY(*this, xo, yo + textRow().descent() + 1);
1885 // This happens when you move out of an inset.
1886 // And to give the DEPM the possibility of doing
1887 // something we must provide it with two different
1889 Cursor dummy = *this;
1892 if (bv().checkDepm(dummy, old)) {
1893 updateNeeded = true;
1894 // Make sure that cur gets back whatever happened to dummy(Lgb)
1898 // if there is a selection, we stay out of any inset,
1899 // and just jump to the right position:
1905 } else if (pit() > 0) {
1907 TextMetrics & tm = bv_->textMetrics(text());
1908 if (!tm.contains(pit()))
1909 tm.newParMetricsUp();
1910 ParagraphMetrics const & pmcur = tm.parMetrics(pit());
1911 next_row = pmcur.rows().size() - 1;
1914 if (row + 1 < int(pm.rows().size())) {
1916 } else if (pit() + 1 < int(text()->paragraphs().size())) {
1918 TextMetrics & tm = bv_->textMetrics(text());
1919 if (!tm.contains(pit()))
1920 tm.newParMetricsDown();
1924 top().pos() = min(tm.x2pos(pit(), next_row, xo), top().lastpos());
1926 int const xpos = tm.x2pos(pit(), next_row, xo);
1927 bool const at_end_row = xpos == tm.x2pos(pit(), next_row, tm.width());
1928 bool const at_beg_row = xpos == tm.x2pos(pit(), next_row, 0);
1930 if (at_end_row && at_beg_row)
1931 // make sure the cursor ends up on this row
1934 boundary(at_end_row);
1936 updateNeeded |= bv().checkDepm(*this, old);
1939 updateTextTargetOffset();
1944 void Cursor::handleFont(string const & font)
1946 LYXERR(Debug::DEBUG, font);
1950 safe = cap::grabAndEraseSelection(*this);
1955 if (lastpos() != 0) {
1956 // something left in the cell
1958 // cursor in first position
1960 } else if (pos() == lastpos()) {
1961 // cursor in last position
1964 // cursor in between. split cell
1965 MathData::iterator bt = cell().begin();
1966 MathAtom at = createInsetMath(from_utf8(font), buffer());
1967 at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
1968 cell().erase(bt, bt + pos());
1973 // nothing left in the cell
1982 void Cursor::message(docstring const & msg) const
1984 theLyXFunc().setMessage(msg);
1988 void Cursor::errorMessage(docstring const & msg) const
1990 theLyXFunc().setErrorMessage(msg);
1994 static docstring parbreak(InsetCode code)
1996 odocstringstream os;
1998 // only add blank line if we're not in an ERT or Listings inset
1999 if (code != ERT_CODE && code != LISTINGS_CODE)
2005 docstring Cursor::selectionAsString(bool with_label) const
2011 return cap::grabSelection(*this);
2013 int const label = with_label
2014 ? AS_STR_LABEL | AS_STR_INSETS : AS_STR_INSETS;
2016 idx_type const startidx = selBegin().idx();
2017 idx_type const endidx = selEnd().idx();
2018 if (startidx != endidx) {
2019 // multicell selection
2020 InsetTabular * table = inset().asInsetTabular();
2021 LASSERT(table, return docstring());
2022 return table->asString(startidx, endidx);
2025 ParagraphList const & pars = text()->paragraphs();
2027 pit_type const startpit = selBegin().pit();
2028 pit_type const endpit = selEnd().pit();
2029 size_t const startpos = selBegin().pos();
2030 size_t const endpos = selEnd().pos();
2032 if (startpit == endpit)
2033 return pars[startpit].asString(startpos, endpos, label);
2035 // First paragraph in selection
2036 docstring result = pars[startpit].
2037 asString(startpos, pars[startpit].size(), label)
2038 + parbreak(inset().lyxCode());
2040 // The paragraphs in between (if any)
2041 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
2042 Paragraph const & par = pars[pit];
2043 result += par.asString(0, par.size(), label)
2044 + parbreak(inset().lyxCode());
2047 // Last paragraph in selection
2048 result += pars[endpit].asString(0, endpos, label);
2054 docstring Cursor::currentState() const
2057 odocstringstream os;
2063 return text()->currentState(*this);
2069 docstring Cursor::getPossibleLabel() const
2071 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
2075 Encoding const * Cursor::getEncoding() const
2079 CursorSlice const & sl = innerTextSlice();
2080 Text const & text = *sl.text();
2081 Font font = text.getPar(sl.pit()).getFont(
2082 bv().buffer().params(), sl.pos(), text.outerFont(sl.pit()));
2083 return font.language()->encoding();
2087 void Cursor::undispatched()
2089 disp_.dispatched(false);
2093 void Cursor::dispatched()
2095 disp_.dispatched(true);
2099 void Cursor::updateFlags(Update::flags f)
2105 void Cursor::noUpdate()
2107 disp_.update(Update::None);
2111 Font Cursor::getFont() const
2113 // The logic here should more or less match to the Cursor::setCurrentFont
2114 // logic, i.e. the cursor height should give a hint what will happen
2115 // if a character is entered.
2117 // HACK. far from being perfect...
2119 CursorSlice const & sl = innerTextSlice();
2120 Text const & text = *sl.text();
2121 Paragraph const & par = text.getPar(sl.pit());
2123 // on boundary, so we are really at the character before
2124 pos_type pos = sl.pos();
2125 if (pos > 0 && boundary())
2128 // on space? Take the font before (only for RTL boundary stay)
2130 TextMetrics const & tm = bv().textMetrics(&text);
2131 if (pos == sl.lastpos()
2132 || (par.isSeparator(pos)
2133 && !tm.isRTLBoundary(sl.pit(), pos)))
2137 // get font at the position
2138 Font font = par.getFont(buffer()->params(), pos,
2139 text.outerFont(sl.pit()));
2145 bool Cursor::fixIfBroken()
2147 bool const broken_cursor = DocIterator::fixIfBroken();
2148 bool const broken_anchor = anchor_.fixIfBroken();
2150 if (broken_cursor || broken_anchor) {
2158 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2160 // find inset in common
2162 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2163 if (&old[i].inset() != &cur[i].inset())
2167 // update words if we just moved to another paragraph
2168 if (i == old.depth() && i == cur.depth()
2169 && !cur.buffer()->isClean()
2170 && cur.inTexted() && old.inTexted()
2171 && cur.pit() != old.pit()) {
2172 old.paragraph().updateWords();
2175 // notify everything on top of the common part in old cursor,
2176 // but stop if the inset claims the cursor to be invalid now
2177 for (size_type j = i; j < old.depth(); ++j) {
2178 Cursor inset_pos = old;
2179 inset_pos.cutOff(j);
2180 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2184 // notify everything on top of the common part in new cursor,
2185 // but stop if the inset claims the cursor to be invalid now
2186 for (; i < cur.depth(); ++i) {
2187 if (cur[i].inset().notifyCursorEnters(cur))
2195 void Cursor::setCurrentFont()
2197 CursorSlice const & cs = innerTextSlice();
2198 Paragraph const & par = cs.paragraph();
2199 pos_type cpit = cs.pit();
2200 pos_type cpos = cs.pos();
2201 Text const & ctext = *cs.text();
2202 TextMetrics const & tm = bv().textMetrics(&ctext);
2204 // are we behind previous char in fact? -> go to that char
2205 if (cpos > 0 && boundary())
2208 // find position to take the font from
2210 // paragraph end? -> font of last char
2211 if (cpos == lastpos())
2213 // on space? -> look at the words in front of space
2214 else if (cpos > 0 && par.isSeparator(cpos)) {
2215 // abc| def -> font of c
2216 // abc |[WERBEH], i.e. boundary==true -> font of c
2217 // abc [WERBEH]| def, font of the space
2218 if (!tm.isRTLBoundary(cpit, cpos))
2224 BufferParams const & bufparams = buffer()->params();
2225 current_font = par.getFontSettings(bufparams, cpos);
2226 real_current_font = tm.displayFont(cpit, cpos);
2228 // special case for paragraph end
2229 if (cs.pos() == lastpos()
2230 && tm.isRTLBoundary(cpit, cs.pos())
2232 Language const * lang = par.getParLanguage(bufparams);
2233 current_font.setLanguage(lang);
2234 current_font.fontInfo().setNumber(FONT_OFF);
2235 real_current_font.setLanguage(lang);
2236 real_current_font.fontInfo().setNumber(FONT_OFF);
2241 bool Cursor::textUndo()
2243 DocIterator dit = *this;
2244 // Undo::textUndo() will modify dit.
2245 if (!buffer()->undo().textUndo(dit))
2255 bool Cursor::textRedo()
2257 DocIterator dit = *this;
2258 // Undo::textRedo() will modify dit.
2259 if (!buffer()->undo().textRedo(dit))
2269 void Cursor::finishUndo() const
2271 buffer()->undo().finishUndo();
2275 void Cursor::beginUndoGroup() const
2277 buffer()->undo().beginUndoGroup();
2281 void Cursor::endUndoGroup() const
2283 buffer()->undo().endUndoGroup();
2287 void Cursor::recordUndo(UndoKind kind, pit_type from, pit_type to) const
2289 buffer()->undo().recordUndo(*this, kind, from, to);
2293 void Cursor::recordUndo(UndoKind kind, pit_type from) const
2295 buffer()->undo().recordUndo(*this, kind, from);
2299 void Cursor::recordUndo(UndoKind kind) const
2301 buffer()->undo().recordUndo(*this, kind);
2305 void Cursor::recordUndoInset(UndoKind kind) const
2307 buffer()->undo().recordUndoInset(*this, kind);
2311 void Cursor::recordUndoFullDocument() const
2313 buffer()->undo().recordUndoFullDocument(*this);
2317 void Cursor::recordUndoSelection() const
2320 if (cap::multipleCellsSelected(*this))
2325 buffer()->undo().recordUndo(*this, ATOMIC_UNDO,
2326 selBegin().pit(), selEnd().pit());
2331 void Cursor::checkBufferStructure()
2333 Buffer const * master = buffer()->masterBuffer();
2334 master->tocBackend().updateItem(*this);
2335 if (master != buffer() && !master->hasGuiDelegate())
2336 // In case the master has no gui associated with it,
2337 // the TocItem is not updated (part of bug 5699).
2338 buffer()->tocBackend().updateItem(*this);