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/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::saveBeforeDispatchPosXY()
320 getPos(beforeDispatchPosX_, beforeDispatchPosY_);
324 void Cursor::dispatch(FuncRequest const & cmd0)
326 LYXERR(Debug::DEBUG, "cmd: " << cmd0 << '\n' << *this);
331 FuncRequest cmd = cmd0;
334 buffer()->undo().beginUndoGroup();
336 // Is this a function that acts on inset at point?
337 if (lyxaction.funcHasFlag(cmd.action, LyXAction::AtPoint)
339 result().dispatched(true);
340 result().update(Update::FitCursor | Update::Force);
341 FuncRequest tmpcmd = cmd;
342 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
343 << cmd0 << endl << *this);
344 nextInset()->dispatch(*this, tmpcmd);
345 if (result().dispatched()) {
346 buffer()->undo().endUndoGroup();
351 // store some values to be used inside of the handlers
352 beforeDispatchCursor_ = *this;
353 for (; depth(); pop(), boundary(false)) {
354 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
355 << cmd0 << endl << *this);
356 LASSERT(pos() <= lastpos(), /**/);
357 LASSERT(idx() <= lastidx(), /**/);
358 LASSERT(pit() <= lastpit(), /**/);
360 // The common case is 'LFUN handled, need update', so make the
361 // LFUN handler's life easier by assuming this as default value.
362 // The handler can reset the update and val flags if necessary.
363 disp_.update(Update::FitCursor | Update::Force);
364 disp_.dispatched(true);
365 inset().dispatch(*this, cmd);
366 if (disp_.dispatched())
370 // it completely to get a 'bomb early' behaviour in case this
371 // object will be used again.
372 if (!disp_.dispatched()) {
373 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
374 // We might have invalidated the cursor when removing an empty
375 // paragraph while the cursor could not be moved out the inset
376 // while we initially thought we could. This might happen when
377 // a multiline inset becomes an inline inset when the second
378 // paragraph is removed.
379 if (safe.pit() > safe.lastpit()) {
380 safe.pit() = safe.lastpit();
381 safe.pos() = safe.lastpos();
384 disp_.update(Update::None);
385 disp_.dispatched(false);
387 // restore the previous one because nested Cursor::dispatch calls
388 // are possible which would change it
389 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
391 buffer()->undo().endUndoGroup();
395 DispatchResult Cursor::result() const
401 BufferView & Cursor::bv() const
410 LASSERT(depth() >= 1, /**/);
415 void Cursor::push(Inset & p)
417 push_back(CursorSlice(p));
418 p.setBuffer(*buffer());
422 void Cursor::pushBackward(Inset & p)
424 LASSERT(!empty(), return);
425 //lyxerr << "Entering inset " << t << " front" << endl;
431 bool Cursor::popBackward()
433 LASSERT(!empty(), return false);
441 bool Cursor::popForward()
443 LASSERT(!empty(), return false);
444 //lyxerr << "Leaving inset from in back" << endl;
445 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
449 pos() += lastpos() - lp + 1;
454 int Cursor::currentMode()
456 LASSERT(!empty(), /**/);
457 for (int i = depth() - 1; i >= 0; --i) {
458 int res = operator[](i).inset().currentMode();
459 bool locked_mode = operator[](i).inset().lockedMode();
460 // Also return UNDECIDED_MODE when the mode is locked,
461 // as in this case it is treated the same as TEXT_MODE
462 if (res != Inset::UNDECIDED_MODE || locked_mode)
465 return Inset::TEXT_MODE;
469 void Cursor::getPos(int & x, int & y) const
471 Point p = bv().getPos(*this, boundary());
477 Row const & Cursor::textRow() const
479 CursorSlice const & cs = innerTextSlice();
480 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
481 LASSERT(!pm.rows().empty(), /**/);
482 return pm.getRow(pos(), boundary());
486 void Cursor::resetAnchor()
492 void Cursor::setCursorToAnchor()
495 DocIterator normal = anchor_;
496 while (depth() < normal.depth())
498 if (depth() < anchor_.depth() && top() <= anchor_[depth() - 1])
505 bool Cursor::posBackward()
514 bool Cursor::posForward()
516 if (pos() == lastpos())
523 bool Cursor::posVisRight(bool skip_inset)
525 Cursor new_cur = *this; // where we will move to
526 pos_type left_pos; // position visually left of current cursor
527 pos_type right_pos; // position visually right of current cursor
528 bool new_pos_is_RTL; // is new position we're moving to RTL?
530 getSurroundingPos(left_pos, right_pos);
532 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
534 // Are we at an inset?
535 new_cur.pos() = right_pos;
536 new_cur.boundary(false);
538 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
539 // we actually move the cursor at the end of this function, for now
540 // we just keep track of the new position in new_cur...
541 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
544 // Are we already at rightmost pos in row?
545 else if (text()->empty() || right_pos == -1) {
548 if (!new_cur.posVisToNewRow(false)) {
549 LYXERR(Debug::RTL, "not moving!");
553 // we actually move the cursor at the end of this function, for now
554 // just keep track of the new position in new_cur...
555 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
556 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
559 // normal movement to the right
562 // Recall, if the cursor is at position 'x', that means *before*
563 // the character at position 'x'. In RTL, "before" means "to the
564 // right of", in LTR, "to the left of". So currently our situation
565 // is this: the position to our right is 'right_pos' (i.e., we're
566 // currently to the left of 'right_pos'). In order to move to the
567 // right, it depends whether or not the character at 'right_pos' is RTL.
568 new_pos_is_RTL = paragraph().getFontSettings(
569 buffer()->params(), right_pos).isVisibleRightToLeft();
570 // If the character at 'right_pos' *is* LTR, then in order to move to
571 // the right of it, we need to be *after* 'right_pos', i.e., move to
572 // position 'right_pos' + 1.
573 if (!new_pos_is_RTL) {
574 new_cur.pos() = right_pos + 1;
575 // set the boundary to true in two situations:
577 // 1. if new_pos is now lastpos, and we're in an RTL paragraph
578 // (this means that we're moving right to the end of an LTR chunk
579 // which is at the end of an RTL paragraph);
580 (new_cur.pos() == lastpos()
581 && paragraph().isRTL(buffer()->params()))
582 // 2. if the position *after* right_pos is RTL (we want to be
583 // *after* right_pos, not before right_pos + 1!)
584 || paragraph().getFontSettings(buffer()->params(),
585 new_cur.pos()).isVisibleRightToLeft()
587 new_cur.boundary(true);
588 else // set the boundary to false
589 new_cur.boundary(false);
591 // Otherwise (if the character at position 'right_pos' is RTL), then
592 // moving to the right of it is as easy as setting the new position
595 new_cur.pos() = right_pos;
596 new_cur.boundary(false);
601 bool moved = (new_cur.pos() != pos()
602 || new_cur.pit() != pit()
603 || new_cur.boundary() != boundary()
604 || &new_cur.inset() != &inset());
607 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
608 << (new_cur.boundary() ? " (boundary)" : ""));
616 bool Cursor::posVisLeft(bool skip_inset)
618 Cursor new_cur = *this; // where we will move to
619 pos_type left_pos; // position visually left of current cursor
620 pos_type right_pos; // position visually right of current cursor
621 bool new_pos_is_RTL; // is new position we're moving to RTL?
623 getSurroundingPos(left_pos, right_pos);
625 LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
627 // Are we at an inset?
628 new_cur.pos() = left_pos;
629 new_cur.boundary(false);
631 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
632 // we actually move the cursor at the end of this function, for now
633 // we just keep track of the new position in new_cur...
634 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
637 // Are we already at leftmost pos in row?
638 else if (text()->empty() || left_pos == -1) {
641 if (!new_cur.posVisToNewRow(true)) {
642 LYXERR(Debug::RTL, "not moving!");
646 // we actually move the cursor at the end of this function, for now
647 // just keep track of the new position in new_cur...
648 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
649 << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
652 // normal movement to the left
655 // Recall, if the cursor is at position 'x', that means *before*
656 // the character at position 'x'. In RTL, "before" means "to the
657 // right of", in LTR, "to the left of". So currently our situation
658 // is this: the position to our left is 'left_pos' (i.e., we're
659 // currently to the right of 'left_pos'). In order to move to the
660 // left, it depends whether or not the character at 'left_pos' is RTL.
661 new_pos_is_RTL = paragraph().getFontSettings(
662 buffer()->params(), left_pos).isVisibleRightToLeft();
663 // If the character at 'left_pos' *is* RTL, then in order to move to
664 // the left of it, we need to be *after* 'left_pos', i.e., move to
665 // position 'left_pos' + 1.
666 if (new_pos_is_RTL) {
667 new_cur.pos() = left_pos + 1;
668 // set the boundary to true in two situations:
670 // 1. if new_pos is now lastpos and we're in an LTR paragraph
671 // (this means that we're moving left to the end of an RTL chunk
672 // which is at the end of an LTR paragraph);
673 (new_cur.pos() == lastpos()
674 && !paragraph().isRTL(buffer()->params()))
675 // 2. if the position *after* left_pos is not RTL (we want to be
676 // *after* left_pos, not before left_pos + 1!)
677 || !paragraph().getFontSettings(buffer()->params(),
678 new_cur.pos()).isVisibleRightToLeft()
680 new_cur.boundary(true);
681 else // set the boundary to false
682 new_cur.boundary(false);
684 // Otherwise (if the character at position 'left_pos' is LTR), then
685 // moving to the left of it is as easy as setting the new position
688 new_cur.pos() = left_pos;
689 new_cur.boundary(false);
694 bool moved = (new_cur.pos() != pos()
695 || new_cur.pit() != pit()
696 || new_cur.boundary() != boundary());
699 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
700 << (new_cur.boundary() ? " (boundary)" : ""));
708 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos)
710 // preparing bidi tables
711 Paragraph const & par = paragraph();
712 Buffer const & buf = *buffer();
713 Row const & row = textRow();
715 bidi.computeTables(par, buf, row);
717 LYXERR(Debug::RTL, "bidi: " << row.pos() << "--" << row.endpos());
719 // The cursor is painted *before* the character at pos(), or, if 'boundary'
720 // is true, *after* the character at (pos() - 1). So we already have one
721 // known position around the cursor:
722 pos_type const known_pos = boundary() && pos() > 0 ? pos() - 1 : pos();
724 // edge case: if we're at the end of the paragraph, things are a little
725 // different (because lastpos is a position which does not really "exist"
726 // --- there's no character there yet).
727 if (known_pos == lastpos()) {
728 if (par.isRTL(buf.params())) {
730 right_pos = bidi.vis2log(row.pos());
734 left_pos = bidi.vis2log(row.endpos() - 1);
739 // Whether 'known_pos' is to the left or to the right of the cursor depends
740 // on whether it is an RTL or LTR character...
741 bool const cur_is_RTL =
742 par.getFontSettings(buf.params(), known_pos).isVisibleRightToLeft();
743 // ... in the following manner:
744 // For an RTL character, "before" means "to the right" and "after" means
745 // "to the left"; and for LTR, it's the reverse. So, 'known_pos' is to the
746 // right of the cursor if (RTL && boundary) or (!RTL && !boundary):
747 bool const known_pos_on_right = cur_is_RTL == boundary();
749 // So we now know one of the positions surrounding the cursor. Let's
750 // determine the other one:
751 if (known_pos_on_right) {
752 right_pos = known_pos;
753 // *visual* position of 'left_pos':
754 pos_type v_left_pos = bidi.log2vis(right_pos) - 1;
755 // If the position we just identified as 'left_pos' is a "skipped
756 // separator" (a separator which is at the logical end of a row,
757 // except for the last row in a paragraph; such separators are not
758 // painted, so they "are not really there"; note that in bidi text,
759 // such a separator could appear visually in the middle of a row),
760 // set 'left_pos' to the *next* position to the left.
761 if (bidi.inRange(v_left_pos)
762 && bidi.vis2log(v_left_pos) + 1 == row.endpos()
763 && row.endpos() < lastpos()
764 && par.isSeparator(bidi.vis2log(v_left_pos)))
767 // calculate the logical position of 'left_pos', if in row
768 if (!bidi.inRange(v_left_pos))
771 left_pos = bidi.vis2log(v_left_pos);
772 // If the position we identified as 'right_pos' is a "skipped
773 // separator", set 'right_pos' to the *next* position to the right.
774 if (right_pos + 1 == row.endpos() && row.endpos() < lastpos()
775 && par.isSeparator(right_pos)) {
776 pos_type const v_right_pos = bidi.log2vis(right_pos) + 1;
777 if (!bidi.inRange(v_right_pos))
780 right_pos = bidi.vis2log(v_right_pos);
783 // known_pos is on the left
784 left_pos = known_pos;
785 // *visual* position of 'right_pos'
786 pos_type v_right_pos = bidi.log2vis(left_pos) + 1;
787 // If the position we just identified as 'right_pos' is a "skipped
788 // separator", set 'right_pos' to the *next* position to the right.
789 if (bidi.inRange(v_right_pos)
790 && bidi.vis2log(v_right_pos) + 1 == row.endpos()
791 && row.endpos() < lastpos()
792 && par.isSeparator(bidi.vis2log(v_right_pos)))
795 // calculate the logical position of 'right_pos', if in row
796 if (!bidi.inRange(v_right_pos))
799 right_pos = bidi.vis2log(v_right_pos);
800 // If the position we identified as 'left_pos' is a "skipped
801 // separator", set 'left_pos' to the *next* position to the left.
802 if (left_pos + 1 == row.endpos() && row.endpos() < lastpos()
803 && par.isSeparator(left_pos)) {
804 pos_type const v_left_pos = bidi.log2vis(left_pos) - 1;
805 if (!bidi.inRange(v_left_pos))
808 left_pos = bidi.vis2log(v_left_pos);
815 bool Cursor::posVisToNewRow(bool movingLeft)
817 Paragraph const & par = paragraph();
818 Buffer const & buf = *buffer();
819 Row const & row = textRow();
820 bool par_is_LTR = !par.isRTL(buf.params());
822 // Inside a table, determining whether to move to the next or previous row
823 // should be done based on the table's direction.
825 if (s >= 1 && (*this)[s].inset().asInsetTabular()) {
826 par_is_LTR = !(*this)[s].inset().asInsetTabular()->isRightToLeft(*this);
827 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
830 // if moving left in an LTR paragraph or moving right in an RTL one,
831 // move to previous row
832 if (par_is_LTR == movingLeft) {
833 if (row.pos() == 0) { // we're at first row in paragraph
834 if (pit() == 0) // no previous paragraph! don't move
836 // move to last pos in previous par
840 } else { // move to previous row in this par
841 pos() = row.pos() - 1; // this is guaranteed to be in previous row
845 // if moving left in an RTL paragraph or moving right in an LTR one,
848 if (row.endpos() == lastpos()) { // we're at last row in paragraph
849 if (pit() == lastpit()) // last paragraph! don't move
851 // move to first row in next par
855 } else { // move to next row in this par
856 pos() = row.endpos();
861 // make sure we're at left-/right-most pos in new row
862 posVisToRowExtremity(!movingLeft);
868 void Cursor::posVisToRowExtremity(bool left)
870 // prepare bidi tables
871 Paragraph const & par = paragraph();
872 Buffer const & buf = *buffer();
873 Row const & row = textRow();
875 bidi.computeTables(par, buf, row);
877 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
878 << (boundary() ? 1 : 0));
880 if (left) { // move to leftmost position
881 // if this is an RTL paragraph, and we're at the last row in the
882 // paragraph, move to lastpos
883 if (par.isRTL(buf.params()) && row.endpos() == lastpos())
886 pos() = bidi.vis2log(row.pos());
888 // Moving to the leftmost position in the row, the cursor should
889 // normally be placed to the *left* of the leftmost position.
890 // A very common exception, though, is if the leftmost character
891 // also happens to be the separator at the (logical) end of the row
892 // --- in this case, the separator is positioned beyond the left
893 // margin, and we don't want to move the cursor there (moving to
894 // the left of the separator is equivalent to moving to the next
895 // line). So, in this case we actually want to place the cursor
896 // to the *right* of the leftmost position (the separator).
897 // Another exception is if we're moving to the logically last
898 // position in the row, which is *not* a separator: this means
899 // that the entire row has no separators (if there were any, the
900 // row would have been broken there); and therefore in this case
901 // we also move to the *right* of the last position (this indicates
902 // to the user that there is no space after this position, and is
903 // consistent with the behavior in the middle of a row --- moving
904 // right or left moves to the next/previous character; if we were
905 // to move to the *left* of this position, that would simulate
906 // a separator which is not really there!).
907 // Finally, there is an exception to the previous exception: if
908 // this non-separator-but-last-position-in-row is an inset, then
909 // we *do* want to stay to the left of it anyway: this is the
910 // "boundary" which we simulate at insets.
911 // Another exception is when row.endpos() is 0.
913 // do we want to be to the right of pos?
914 // as explained above, if at last pos in row, stay to the right
915 bool const right_of_pos = row.endpos() > 0
916 && pos() == row.endpos() - 1 && !par.isInset(pos());
918 // Now we know if we want to be to the left or to the right of pos,
919 // let's make sure we are where we want to be.
920 bool const new_pos_is_RTL =
921 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
923 if (new_pos_is_RTL != right_of_pos) {
929 // move to rightmost position
930 // if this is an LTR paragraph, and we're at the last row in the
931 // paragraph, move to lastpos
932 if (!par.isRTL(buf.params()) && row.endpos() == lastpos())
935 pos() = row.endpos() > 0 ? bidi.vis2log(row.endpos() - 1) : 0;
937 // Moving to the rightmost position in the row, the cursor should
938 // normally be placed to the *right* of the rightmost position.
939 // A very common exception, though, is if the rightmost character
940 // also happens to be the separator at the (logical) end of the row
941 // --- in this case, the separator is positioned beyond the right
942 // margin, and we don't want to move the cursor there (moving to
943 // the right of the separator is equivalent to moving to the next
944 // line). So, in this case we actually want to place the cursor
945 // to the *left* of the rightmost position (the separator).
946 // Another exception is if we're moving to the logically last
947 // position in the row, which is *not* a separator: this means
948 // that the entire row has no separators (if there were any, the
949 // row would have been broken there); and therefore in this case
950 // we also move to the *left* of the last position (this indicates
951 // to the user that there is no space after this position, and is
952 // consistent with the behavior in the middle of a row --- moving
953 // right or left moves to the next/previous character; if we were
954 // to move to the *right* of this position, that would simulate
955 // a separator which is not really there!).
956 // Finally, there is an exception to the previous exception: if
957 // this non-separator-but-last-position-in-row is an inset, then
958 // we *do* want to stay to the right of it anyway: this is the
959 // "boundary" which we simulate at insets.
960 // Another exception is when row.endpos() is 0.
962 // do we want to be to the left of pos?
963 // as explained above, if at last pos in row, stay to the left,
964 // unless the last position is the same as the first.
965 bool const left_of_pos = row.endpos() > 0
966 && pos() == row.endpos() - 1 && !par.isInset(pos());
968 // Now we know if we want to be to the left or to the right of pos,
969 // let's make sure we are where we want to be.
970 bool const new_pos_is_RTL =
971 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
973 if (new_pos_is_RTL == left_of_pos) {
979 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
980 << (boundary() ? 1 : 0));
984 CursorSlice Cursor::anchor() const
988 LASSERT(anchor_.depth() >= depth(), /**/);
989 CursorSlice normal = anchor_[depth() - 1];
990 if (depth() < anchor_.depth() && top() <= normal) {
991 // anchor is behind cursor -> move anchor behind the inset
998 CursorSlice Cursor::selBegin() const
1002 return anchor() < top() ? anchor() : top();
1006 CursorSlice Cursor::selEnd() const
1010 return anchor() > top() ? anchor() : top();
1014 DocIterator Cursor::selectionBegin() const
1020 // FIXME: This is a work-around for the problem that
1021 // CursorSlice doesn't keep track of the boundary.
1022 if (anchor() == top())
1023 di = anchor_.boundary() > boundary() ? anchor_ : *this;
1025 di = anchor() < top() ? anchor_ : *this;
1031 DocIterator Cursor::selectionEnd() const
1037 // FIXME: This is a work-around for the problem that
1038 // CursorSlice doesn't keep track of the boundary.
1039 if (anchor() == top())
1040 di = anchor_.boundary() < boundary() ? anchor_ : *this;
1042 di = anchor() > top() ? anchor_ : *this;
1044 if (di.depth() > depth()) {
1052 void Cursor::setSelection()
1055 // A selection with no contents is not a selection
1056 // FIXME: doesnt look ok
1057 if (idx() == anchor().idx() &&
1058 pit() == anchor().pit() &&
1059 pos() == anchor().pos())
1060 setSelection(false);
1064 void Cursor::setSelection(DocIterator const & where, int n)
1073 void Cursor::clearSelection()
1075 setSelection(false);
1076 setWordSelection(false);
1082 void Cursor::setTargetX(int x)
1085 textTargetOffset_ = 0;
1089 int Cursor::x_target() const
1095 void Cursor::clearTargetX()
1098 textTargetOffset_ = 0;
1102 void Cursor::updateTextTargetOffset()
1107 textTargetOffset_ = x - x_target_;
1111 void Cursor::info(odocstream & os) const
1113 for (int i = 1, n = depth(); i < n; ++i) {
1114 operator[](i).inset().infoize(os);
1118 Inset const * inset = prevInset();
1119 // prevInset() can return 0 in certain case.
1121 prevInset()->infoize2(os);
1123 // overwite old message
1128 bool Cursor::selHandle(bool sel)
1130 //lyxerr << "Cursor::selHandle" << endl;
1133 if (sel == selection())
1137 cap::saveSelection(*this);
1145 ostream & operator<<(ostream & os, Cursor const & cur)
1147 os << "\n cursor: | anchor:\n";
1148 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
1149 os << " " << cur[i] << " | ";
1150 if (i < cur.anchor_.depth())
1151 os << cur.anchor_[i];
1153 os << "-------------------------------";
1156 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
1157 os << "------------------------------- | " << cur.anchor_[i] << "\n";
1159 os << " selection: " << cur.selection_
1160 << " x_target: " << cur.x_target_ << endl;
1165 LyXErr & operator<<(LyXErr & os, Cursor const & cur)
1175 ///////////////////////////////////////////////////////////////////
1178 // The part below is the non-integrated rest of the original math
1179 // cursor. This should be either generalized for texted or moved
1180 // back to mathed (in most cases to InsetMathNest).
1182 ///////////////////////////////////////////////////////////////////
1184 #include "mathed/InsetMathChar.h"
1185 #include "mathed/InsetMathGrid.h"
1186 #include "mathed/InsetMathScript.h"
1187 #include "mathed/InsetMathUnknown.h"
1188 #include "mathed/MathFactory.h"
1189 #include "mathed/MathStream.h"
1190 #include "mathed/MathSupport.h"
1195 //#define FILEDEBUG 1
1198 bool Cursor::isInside(Inset const * p) const
1200 for (size_t i = 0; i != depth(); ++i)
1201 if (&operator[](i).inset() == p)
1207 void Cursor::leaveInset(Inset const & inset)
1209 for (size_t i = 0; i != depth(); ++i) {
1210 if (&operator[](i).inset() == &inset) {
1218 bool Cursor::openable(MathAtom const & t) const
1229 // we can't move into anything new during selection
1230 if (depth() >= anchor_.depth())
1232 if (t.nucleus() != &anchor_[depth()].inset())
1239 void Cursor::setScreenPos(int x, int /*y*/)
1242 //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
1247 void Cursor::plainErase()
1249 cell().erase(pos());
1253 void Cursor::markInsert()
1255 insert(char_type(0));
1259 void Cursor::markErase()
1261 cell().erase(pos());
1265 void Cursor::plainInsert(MathAtom const & t)
1267 cell().insert(pos(), t);
1269 inset().setBuffer(bv_->buffer());
1274 void Cursor::insert(docstring const & str)
1276 for_each(str.begin(), str.end(),
1277 boost::bind(static_cast<void(Cursor::*)(char_type)>
1278 (&Cursor::insert), this, _1));
1282 void Cursor::insert(char_type c)
1284 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1285 LASSERT(!empty(), /**/);
1287 cap::selClearOrDel(*this);
1288 insert(new InsetMathChar(c));
1290 text()->insertChar(*this, c);
1295 void Cursor::insert(MathAtom const & t)
1297 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1299 cap::selClearOrDel(*this);
1304 void Cursor::insert(Inset * inset0)
1306 LASSERT(inset0, /**/);
1308 insert(MathAtom(inset0));
1310 text()->insertInset(*this, inset0);
1311 inset0->setBuffer(bv_->buffer());
1317 void Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1319 MathData ar(buffer());
1321 if (ar.size() == 1 && (enter || selection()))
1328 void Cursor::niceInsert(MathAtom const & t)
1331 docstring const safe = cap::grabAndEraseSelection(*this);
1333 // If possible, enter the new inset and move the contents of the selection
1334 if (t->isActive()) {
1336 // be careful here: don't use 'pushBackward(t)' as this we need to
1337 // push the clone, not the original
1338 pushBackward(*nextInset());
1339 // We may not use niceInsert here (recursion)
1340 MathData ar(buffer());
1347 void Cursor::insert(MathData const & ar)
1351 cap::eraseSelection(*this);
1352 cell().insert(pos(), ar);
1354 // FIXME audit setBuffer/updateLabels calls
1355 inset().setBuffer(bv_->buffer());
1359 bool Cursor::backspace()
1361 autocorrect() = false;
1364 cap::eraseSelection(*this);
1369 // If empty cell, and not part of a big cell
1370 if (lastpos() == 0 && inset().nargs() == 1) {
1372 // Directly delete empty cell: [|[]] => [|]
1378 // [|], can not delete from inside
1389 if (inMacroMode()) {
1390 InsetMathUnknown * p = activeMacro();
1391 if (p->name().size() > 1) {
1392 p->setName(p->name().substr(0, p->name().size() - 1));
1397 if (pos() != 0 && prevAtom()->nargs() > 0) {
1398 // let's require two backspaces for 'big stuff' and
1399 // highlight on the first
1411 bool Cursor::erase()
1413 autocorrect() = false;
1418 cap::eraseSelection(*this);
1422 // delete empty cells if possible
1423 if (pos() == lastpos() && inset().idxDelete(idx()))
1426 // special behaviour when in last position of cell
1427 if (pos() == lastpos()) {
1428 bool one_cell = inset().nargs() == 1;
1429 if (one_cell && lastpos() == 0) {
1431 // Directly delete empty cell: [|[]] => [|]
1437 // [|], can not delete from inside
1442 inset().idxGlue(idx());
1446 // 'clever' UI hack: only erase large items if previously slected
1447 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
1462 DocIterator save = *this;
1463 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1464 this->dispatch(cmd);
1465 if (disp_.dispatched())
1468 autocorrect() = false;
1476 DocIterator save = *this;
1477 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1478 this->dispatch(cmd);
1479 if (disp_.dispatched())
1482 autocorrect() = false;
1487 bool Cursor::macroModeClose()
1491 InsetMathUnknown * p = activeMacro();
1493 MathData selection(buffer());
1494 asArray(p->selection(), selection);
1495 docstring const s = p->name();
1497 cell().erase(pos());
1499 // do nothing if the macro name is empty
1503 // trigger updates of macros, at least, if no full
1504 // updates take place anyway
1505 updateFlags(Update::Force);
1507 docstring const name = s.substr(1);
1508 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1509 if (in && in->interpretString(*this, s))
1511 MathAtom atom = buffer()->getMacro(name, *this, false) ?
1512 MathAtom(new MathMacro(buffer(), name)) : createInsetMath(name, buffer());
1514 // try to put argument into macro, if we just inserted a macro
1515 bool macroArg = false;
1516 MathMacro * atomAsMacro = atom.nucleus()->asMacro();
1518 // macros here are still unfolded (in init mode in fact). So
1519 // we have to resolve the macro here manually and check its arity
1520 // to put the selection behind it if arity > 0.
1521 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1522 if (selection.size() > 0 && data && data->numargs() - data->optionals() > 0) {
1524 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1526 // non-greedy case. Do not touch the arguments behind
1527 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1530 // insert remembered selection into first argument of a non-macro
1531 else if (atom.nucleus()->nargs() > 0)
1532 atom.nucleus()->cell(0).append(selection);
1536 // finally put the macro argument behind, if needed
1538 if (selection.size() > 1 || selection[0]->asScriptInset())
1539 plainInsert(MathAtom(new InsetMathBrace(selection)));
1548 docstring Cursor::macroName()
1550 return inMacroMode() ? activeMacro()->name() : docstring();
1554 void Cursor::handleNest(MathAtom const & a, int c)
1556 //lyxerr << "Cursor::handleNest: " << c << endl;
1558 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1561 pushBackward(*nextInset());
1565 int Cursor::targetX() const
1567 if (x_target() != -1)
1576 int Cursor::textTargetOffset() const
1578 return textTargetOffset_;
1582 void Cursor::setTargetX()
1591 bool Cursor::inMacroMode() const
1597 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1598 return p && !p->final();
1602 InsetMathUnknown * Cursor::activeMacro()
1604 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1608 InsetMathUnknown const * Cursor::activeMacro() const
1610 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1614 void Cursor::pullArg()
1617 MathData ar = cell();
1618 if (popBackward() && inMathed()) {
1620 cell().insert(pos(), ar);
1623 //formula()->mutateToText();
1628 void Cursor::touch()
1632 DocIterator::const_iterator it = begin();
1633 DocIterator::const_iterator et = end();
1634 for ( ; it != et; ++it)
1640 void Cursor::normalize()
1642 if (idx() > lastidx()) {
1643 lyxerr << "this should not really happen - 1: "
1644 << idx() << ' ' << nargs()
1645 << " in: " << &inset() << endl;
1649 if (pos() > lastpos()) {
1650 lyxerr << "this should not really happen - 2: "
1651 << pos() << ' ' << lastpos() << " in idx: " << idx()
1653 odocstringstream os;
1654 WriteStream wi(os, false, true, WriteStream::wsDefault);
1655 inset().asInsetMath()->write(wi);
1656 lyxerr << to_utf8(os.str()) << endl;
1662 bool Cursor::upDownInMath(bool up)
1664 // Be warned: The 'logic' implemented in this function is highly
1665 // fragile. A distance of one pixel or a '<' vs '<=' _really
1666 // matters. So fiddle around with it only if you think you know
1667 // what you are doing!
1671 xo = beforeDispatchPosX_;
1673 // check if we had something else in mind, if not, this is the future
1675 if (x_target_ == -1)
1677 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1678 // In text mode inside the line (not left or right) possibly set a new target_x,
1679 // but only if we are somewhere else than the previous target-offset.
1681 // We want to keep the x-target on subsequent up/down movements
1682 // that cross beyond the end of short lines. Thus a special
1683 // handling when the cursor is at the end of line: Use the new
1684 // x-target only if the old one was before the end of line
1685 // or the old one was after the beginning of the line
1686 bool inRTL = isWithinRtlParagraph(*this);
1690 left = pos() == textRow().endpos();
1691 right = pos() == textRow().pos();
1693 left = pos() == textRow().pos();
1694 right = pos() == textRow().endpos();
1696 if ((!left && !right) ||
1697 (left && !right && xo < x_target_) ||
1698 (!left && right && x_target_ < xo))
1705 // try neigbouring script insets
1707 if (inMathed() && !selection()) {
1710 InsetMathScript const * p = prevAtom()->asScriptInset();
1711 if (p && p->has(up)) {
1713 push(*const_cast<InsetMathScript*>(p));
1714 idx() = p->idxOfScript(up);
1717 // we went in the right direction? Otherwise don't jump into the script
1721 int oy = beforeDispatchPosY_;
1722 if ((!up && y <= oy) ||
1731 if (pos() != lastpos()) {
1732 InsetMathScript const * p = nextAtom()->asScriptInset();
1733 if (p && p->has(up)) {
1734 push(*const_cast<InsetMathScript*>(p));
1735 idx() = p->idxOfScript(up);
1738 // we went in the right direction? Otherwise don't jump into the script
1742 int oy = beforeDispatchPosY_;
1743 if ((!up && y <= oy) ||
1752 // try to find an inset that knows better then we,
1753 if (inset().idxUpDown(*this, up)) {
1754 //lyxerr << "idxUpDown triggered" << endl;
1755 // try to find best position within this inset
1757 setCursor(bruteFind2(*this, xo, yo));
1761 // any improvement going just out of inset?
1762 if (popBackward() && inMathed()) {
1763 //lyxerr << "updown: popBackward succeeded" << endl;
1766 int yold = beforeDispatchPosY_;
1768 if (up ? ynew < yold : ynew > yold)
1772 // no success, we are probably at the document top or bottom
1778 bool Cursor::atFirstOrLastRow(bool up)
1780 TextMetrics const & tm = bv_->textMetrics(text());
1781 ParagraphMetrics const & pm = tm.parMetrics(pit());
1784 if (pos() && boundary())
1785 row = pm.pos2row(pos() - 1);
1787 row = pm.pos2row(pos());
1790 if (pit() == 0 && row == 0)
1793 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1794 row + 1 >= int(pm.rows().size()))
1800 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1802 LASSERT(text(), /**/);
1808 xo = beforeDispatchPosX_;
1810 // update the targetX - this is here before the "return false"
1811 // to set a new target which can be used by InsetTexts above
1812 // if we cannot move up/down inside this inset anymore
1813 if (x_target_ == -1)
1815 else if (xo - textTargetOffset() != x_target() &&
1816 depth() == beforeDispatchCursor_.depth()) {
1817 // In text mode inside the line (not left or right) possibly set a new target_x,
1818 // but only if we are somewhere else than the previous target-offset.
1820 // We want to keep the x-target on subsequent up/down movements
1821 // that cross beyond the end of short lines. Thus a special
1822 // handling when the cursor is at the end of line: Use the new
1823 // x-target only if the old one was before the end of line
1824 // or the old one was after the beginning of the line
1825 bool inRTL = isWithinRtlParagraph(*this);
1829 left = pos() == textRow().endpos();
1830 right = pos() == textRow().pos();
1832 left = pos() == textRow().pos();
1833 right = pos() == textRow().endpos();
1835 if ((!left && !right) ||
1836 (left && !right && xo < x_target_) ||
1837 (!left && right && x_target_ < xo))
1844 // first get the current line
1845 TextMetrics & tm = bv_->textMetrics(text());
1846 ParagraphMetrics const & pm = tm.parMetrics(pit());
1848 if (pos() && boundary())
1849 row = pm.pos2row(pos() - 1);
1851 row = pm.pos2row(pos());
1853 if (atFirstOrLastRow(up)) {
1854 // Is there a place for the cursor to go ? If yes, we
1855 // can execute the DEPM, otherwise we should keep the
1856 // paragraph to host the cursor.
1857 Cursor dummy = *this;
1858 bool valid_destination = false;
1859 for(; dummy.depth(); dummy.pop())
1860 if (!dummy.atFirstOrLastRow(up)) {
1861 valid_destination = true;
1865 // will a next dispatch follow and if there is a new
1866 // dispatch will it move the cursor out ?
1867 if (depth() > 1 && valid_destination) {
1868 // The cursor hasn't changed yet. This happens when
1869 // you e.g. move out of an inset. And to give the
1870 // DEPM the possibility of doing something we must
1871 // provide it with two different cursors. (Lgb, vfr)
1873 dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
1874 dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
1876 updateNeeded |= bv().checkDepm(dummy, *this);
1877 updateTextTargetOffset();
1882 // with and without selection are handled differently
1884 int yo = bv().getPos(*this, boundary()).y_;
1886 // To next/previous row
1888 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1890 tm.editXY(*this, xo, yo + textRow().descent() + 1);
1893 // This happens when you move out of an inset.
1894 // And to give the DEPM the possibility of doing
1895 // something we must provide it with two different
1897 Cursor dummy = *this;
1900 if (bv().checkDepm(dummy, old)) {
1901 updateNeeded = true;
1902 // Make sure that cur gets back whatever happened to dummy(Lgb)
1906 // if there is a selection, we stay out of any inset,
1907 // and just jump to the right position:
1913 } else if (pit() > 0) {
1915 TextMetrics & tm = bv_->textMetrics(text());
1916 if (!tm.contains(pit()))
1917 tm.newParMetricsUp();
1918 ParagraphMetrics const & pmcur = tm.parMetrics(pit());
1919 next_row = pmcur.rows().size() - 1;
1922 if (row + 1 < int(pm.rows().size())) {
1924 } else if (pit() + 1 < int(text()->paragraphs().size())) {
1926 TextMetrics & tm = bv_->textMetrics(text());
1927 if (!tm.contains(pit()))
1928 tm.newParMetricsDown();
1932 top().pos() = min(tm.x2pos(pit(), next_row, xo), top().lastpos());
1934 int const xpos = tm.x2pos(pit(), next_row, xo);
1935 bool const at_end_row = xpos == tm.x2pos(pit(), next_row, tm.width());
1936 bool const at_beg_row = xpos == tm.x2pos(pit(), next_row, 0);
1938 if (at_end_row && at_beg_row)
1939 // make sure the cursor ends up on this row
1942 boundary(at_end_row);
1944 updateNeeded |= bv().checkDepm(*this, old);
1947 updateTextTargetOffset();
1952 void Cursor::handleFont(string const & font)
1954 LYXERR(Debug::DEBUG, font);
1958 safe = cap::grabAndEraseSelection(*this);
1963 if (lastpos() != 0) {
1964 // something left in the cell
1966 // cursor in first position
1968 } else if (pos() == lastpos()) {
1969 // cursor in last position
1972 // cursor in between. split cell
1973 MathData::iterator bt = cell().begin();
1974 MathAtom at = createInsetMath(from_utf8(font), buffer());
1975 at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
1976 cell().erase(bt, bt + pos());
1981 // nothing left in the cell
1990 void Cursor::message(docstring const & msg) const
1992 disp_.setMessage(msg);
1996 void Cursor::errorMessage(docstring const & msg) const
1998 disp_.setMessage(msg);
1999 disp_.setError(true);
2003 static docstring parbreak(InsetCode code)
2005 odocstringstream os;
2007 // only add blank line if we're not in an ERT or Listings inset
2008 if (code != ERT_CODE && code != LISTINGS_CODE)
2014 docstring Cursor::selectionAsString(bool with_label) const
2020 return cap::grabSelection(*this);
2022 int const label = with_label
2023 ? AS_STR_LABEL | AS_STR_INSETS : AS_STR_INSETS;
2025 idx_type const startidx = selBegin().idx();
2026 idx_type const endidx = selEnd().idx();
2027 if (startidx != endidx) {
2028 // multicell selection
2029 InsetTabular * table = inset().asInsetTabular();
2030 LASSERT(table, return docstring());
2031 return table->asString(startidx, endidx);
2034 ParagraphList const & pars = text()->paragraphs();
2036 pit_type const startpit = selBegin().pit();
2037 pit_type const endpit = selEnd().pit();
2038 size_t const startpos = selBegin().pos();
2039 size_t const endpos = selEnd().pos();
2041 if (startpit == endpit)
2042 return pars[startpit].asString(startpos, endpos, label);
2044 // First paragraph in selection
2045 docstring result = pars[startpit].
2046 asString(startpos, pars[startpit].size(), label)
2047 + parbreak(inset().lyxCode());
2049 // The paragraphs in between (if any)
2050 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
2051 Paragraph const & par = pars[pit];
2052 result += par.asString(0, par.size(), label)
2053 + parbreak(inset().lyxCode());
2056 // Last paragraph in selection
2057 result += pars[endpit].asString(0, endpos, label);
2063 docstring Cursor::currentState() const
2066 odocstringstream os;
2072 return text()->currentState(*this);
2078 docstring Cursor::getPossibleLabel() const
2080 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
2084 Encoding const * Cursor::getEncoding() const
2088 CursorSlice const & sl = innerTextSlice();
2089 Text const & text = *sl.text();
2090 Font font = text.getPar(sl.pit()).getFont(
2091 bv().buffer().params(), sl.pos(), text.outerFont(sl.pit()));
2092 return font.language()->encoding();
2096 void Cursor::undispatched()
2098 disp_.dispatched(false);
2102 void Cursor::dispatched()
2104 disp_.dispatched(true);
2108 void Cursor::updateFlags(Update::flags f)
2114 void Cursor::noUpdate()
2116 disp_.update(Update::None);
2120 Font Cursor::getFont() const
2122 // The logic here should more or less match to the Cursor::setCurrentFont
2123 // logic, i.e. the cursor height should give a hint what will happen
2124 // if a character is entered.
2126 // HACK. far from being perfect...
2128 CursorSlice const & sl = innerTextSlice();
2129 Text const & text = *sl.text();
2130 Paragraph const & par = text.getPar(sl.pit());
2132 // on boundary, so we are really at the character before
2133 pos_type pos = sl.pos();
2134 if (pos > 0 && boundary())
2137 // on space? Take the font before (only for RTL boundary stay)
2139 TextMetrics const & tm = bv().textMetrics(&text);
2140 if (pos == sl.lastpos()
2141 || (par.isSeparator(pos)
2142 && !tm.isRTLBoundary(sl.pit(), pos)))
2146 // get font at the position
2147 Font font = par.getFont(buffer()->params(), pos,
2148 text.outerFont(sl.pit()));
2154 bool Cursor::fixIfBroken()
2156 bool const broken_cursor = DocIterator::fixIfBroken();
2157 bool const broken_anchor = anchor_.fixIfBroken();
2159 if (broken_cursor || broken_anchor) {
2167 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2169 // find inset in common
2171 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2172 if (&old[i].inset() != &cur[i].inset())
2176 // update words if we just moved to another paragraph
2177 if (i == old.depth() && i == cur.depth()
2178 && !cur.buffer()->isClean()
2179 && cur.inTexted() && old.inTexted()
2180 && cur.pit() != old.pit()) {
2181 old.paragraph().updateWords();
2184 // notify everything on top of the common part in old cursor,
2185 // but stop if the inset claims the cursor to be invalid now
2186 for (size_type j = i; j < old.depth(); ++j) {
2187 Cursor inset_pos = old;
2188 inset_pos.cutOff(j);
2189 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2193 // notify everything on top of the common part in new cursor,
2194 // but stop if the inset claims the cursor to be invalid now
2195 for (; i < cur.depth(); ++i) {
2196 if (cur[i].inset().notifyCursorEnters(cur))
2204 void Cursor::setCurrentFont()
2206 CursorSlice const & cs = innerTextSlice();
2207 Paragraph const & par = cs.paragraph();
2208 pos_type cpit = cs.pit();
2209 pos_type cpos = cs.pos();
2210 Text const & ctext = *cs.text();
2211 TextMetrics const & tm = bv().textMetrics(&ctext);
2213 // are we behind previous char in fact? -> go to that char
2214 if (cpos > 0 && boundary())
2217 // find position to take the font from
2219 // paragraph end? -> font of last char
2220 if (cpos == lastpos())
2222 // on space? -> look at the words in front of space
2223 else if (cpos > 0 && par.isSeparator(cpos)) {
2224 // abc| def -> font of c
2225 // abc |[WERBEH], i.e. boundary==true -> font of c
2226 // abc [WERBEH]| def, font of the space
2227 if (!tm.isRTLBoundary(cpit, cpos))
2233 BufferParams const & bufparams = buffer()->params();
2234 current_font = par.getFontSettings(bufparams, cpos);
2235 real_current_font = tm.displayFont(cpit, cpos);
2237 // special case for paragraph end
2238 if (cs.pos() == lastpos()
2239 && tm.isRTLBoundary(cpit, cs.pos())
2241 Language const * lang = par.getParLanguage(bufparams);
2242 current_font.setLanguage(lang);
2243 current_font.fontInfo().setNumber(FONT_OFF);
2244 real_current_font.setLanguage(lang);
2245 real_current_font.fontInfo().setNumber(FONT_OFF);
2250 bool Cursor::textUndo()
2252 DocIterator dit = *this;
2253 // Undo::textUndo() will modify dit.
2254 if (!buffer()->undo().textUndo(dit))
2264 bool Cursor::textRedo()
2266 DocIterator dit = *this;
2267 // Undo::textRedo() will modify dit.
2268 if (!buffer()->undo().textRedo(dit))
2278 void Cursor::finishUndo() const
2280 buffer()->undo().finishUndo();
2284 void Cursor::beginUndoGroup() const
2286 buffer()->undo().beginUndoGroup();
2290 void Cursor::endUndoGroup() const
2292 buffer()->undo().endUndoGroup();
2296 void Cursor::recordUndo(UndoKind kind, pit_type from, pit_type to) const
2298 buffer()->undo().recordUndo(*this, kind, from, to);
2302 void Cursor::recordUndo(UndoKind kind, pit_type from) const
2304 buffer()->undo().recordUndo(*this, kind, from);
2308 void Cursor::recordUndo(UndoKind kind) const
2310 buffer()->undo().recordUndo(*this, kind);
2314 void Cursor::recordUndoInset(UndoKind kind) const
2316 buffer()->undo().recordUndoInset(*this, kind);
2320 void Cursor::recordUndoFullDocument() const
2322 buffer()->undo().recordUndoFullDocument(*this);
2326 void Cursor::recordUndoSelection() const
2329 if (cap::multipleCellsSelected(*this))
2334 buffer()->undo().recordUndo(*this, ATOMIC_UNDO,
2335 selBegin().pit(), selEnd().pit());
2340 void Cursor::checkBufferStructure()
2342 Buffer const * master = buffer()->masterBuffer();
2343 master->tocBackend().updateItem(*this);
2344 if (master != buffer() && !master->hasGuiDelegate())
2345 // In case the master has no gui associated with it,
2346 // the TocItem is not updated (part of bug 5699).
2347 buffer()->tocBackend().updateItem(*this);