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"
26 #include "FuncRequest.h"
29 #include "LyXFunc.h" // only for setMessage()
31 #include "paragraph_funcs.h"
32 #include "Paragraph.h"
33 #include "ParIterator.h"
36 #include "TextMetrics.h"
37 #include "TocBackend.h"
39 #include "support/debug.h"
40 #include "support/docstream.h"
42 #include "insets/InsetTabular.h"
43 #include "insets/InsetText.h"
45 #include "mathed/InsetMath.h"
46 #include "mathed/InsetMathScript.h"
47 #include "mathed/MacroTable.h"
48 #include "mathed/MathData.h"
49 #include "mathed/MathMacro.h"
51 #include <boost/assert.hpp>
52 #include <boost/bind.hpp>
64 bool positionable(DocIterator const & cursor, DocIterator const & anchor)
66 // avoid deeper nested insets when selecting
67 if (cursor.depth() > anchor.depth())
70 // anchor might be deeper, should have same path then
71 for (size_t i = 0; i < cursor.depth(); ++i)
72 if (&cursor[i].inset() != &anchor[i].inset())
75 // position should be ok.
80 // Find position closest to (x, y) in cell given by iter.
81 // Used only in mathed
82 DocIterator bruteFind2(Cursor const & c, int x, int y)
84 double best_dist = numeric_limits<double>::max();
91 et.top().pos() = et.top().asInsetMath()->cell(et.top().idx()).size();
92 for (size_t i = 0;; ++i) {
95 Inset const * inset = &it.inset();
96 map<Inset const *, Geometry> const & data =
97 c.bv().coordCache().getInsets().getData();
98 map<Inset const *, Geometry>::const_iterator I = data.find(inset);
100 // FIXME: in the case where the inset is not in the cache, this
101 // means that no part of it is visible on screen. In this case
102 // we don't do elaborate search and we just return the forwarded
103 // DocIterator at its beginning.
104 if (I == data.end()) {
109 Point o = I->second.pos;
110 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
111 // Convert to absolute
114 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
115 // '<=' in order to take the last possible position
116 // this is important for clicking behind \sum in e.g. '\sum_i a'
117 LYXERR(Debug::DEBUG, "i: " << i << " d: " << d
118 << " best: " << best_dist);
119 if (d <= best_dist) {
132 /// moves position closest to (x, y) in given box
133 bool bruteFind(Cursor & cursor,
134 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
136 BOOST_ASSERT(!cursor.empty());
137 Inset & inset = cursor[0].inset();
138 BufferView & bv = cursor.bv();
140 CoordCache::InnerParPosCache const & cache =
141 bv.coordCache().getParPos().find(cursor.bottom().text())->second;
142 // Get an iterator on the first paragraph in the cache
143 DocIterator it(inset);
144 it.push_back(CursorSlice(inset));
145 it.pit() = cache.begin()->first;
146 // Get an iterator after the last paragraph in the cache
147 DocIterator et(inset);
148 et.push_back(CursorSlice(inset));
149 et.pit() = boost::prior(cache.end())->first;
150 if (et.pit() >= et.lastpit())
151 et = doc_iterator_end(inset);
155 double best_dist = numeric_limits<double>::max();;
156 DocIterator best_cursor = et;
158 for ( ; it != et; it.forwardPos(true)) {
159 // avoid invalid nesting when selecting
160 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
161 Point p = bv.getPos(it, false);
164 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
165 double const dx = xo - x;
166 double const dy = yo - y;
167 double const d = dx * dx + dy * dy;
168 // '<=' in order to take the last possible position
169 // this is important for clicking behind \sum in e.g. '\sum_i a'
170 if (d <= best_dist) {
171 // lyxerr << "*" << endl;
179 if (best_cursor != et) {
180 cursor.setCursor(best_cursor);
189 /// moves position closest to (x, y) in given box
190 bool bruteFind3(Cursor & cur, int x, int y, bool up)
192 BufferView & bv = cur.bv();
193 int ylow = up ? 0 : y + 1;
194 int yhigh = up ? y - 1 : bv.workHeight();
196 int xhigh = bv.workWidth();
198 // FIXME: bit more work needed to get 'from' and 'to' right.
199 pit_type from = cur.bottom().pit();
200 //pit_type to = cur.bottom().pit();
201 //lyxerr << "Pit start: " << from << endl;
203 //lyxerr << "bruteFind3: x: " << x << " y: " << y
204 // << " xlow: " << xlow << " xhigh: " << xhigh
205 // << " ylow: " << ylow << " yhigh: " << yhigh
207 Inset & inset = bv.buffer().inset();
208 DocIterator it = doc_iterator_begin(inset);
210 DocIterator et = doc_iterator_end(inset);
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);
249 docstring parbreak(Paragraph const & par)
251 odocstringstream ods;
253 // only add blank line if we're not in an ERT or Listings inset
254 if (par.ownerCode() != ERT_CODE
255 && par.ownerCode() != LISTINGS_CODE)
263 // be careful: this is called from the bv's constructor, too, so
264 // bv functions are not yet available!
265 Cursor::Cursor(BufferView & bv)
266 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1), textTargetOffset_(0),
267 selection_(false), mark_(false), logicalpos_(false),
268 current_font(inherit_font)
272 void Cursor::reset(Inset & inset)
275 push_back(CursorSlice(inset));
276 anchor_ = doc_iterator_begin(inset);
284 // this (intentionally) does neither touch anchor nor selection status
285 void Cursor::setCursor(DocIterator const & cur)
287 DocIterator::operator=(cur);
291 void Cursor::dispatch(FuncRequest const & cmd0)
293 LYXERR(Debug::DEBUG, "cmd: " << cmd0 << '\n' << *this);
298 FuncRequest cmd = cmd0;
301 // store some values to be used inside of the handlers
302 beforeDispatchCursor_ = *this;
303 for (; depth(); pop()) {
304 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
305 << cmd0 << endl << *this);
306 BOOST_ASSERT(pos() <= lastpos());
307 BOOST_ASSERT(idx() <= lastidx());
308 BOOST_ASSERT(pit() <= lastpit());
310 // The common case is 'LFUN handled, need update', so make the
311 // LFUN handler's life easier by assuming this as default value.
312 // The handler can reset the update and val flags if necessary.
313 disp_.update(Update::FitCursor | Update::Force);
314 disp_.dispatched(true);
315 inset().dispatch(*this, cmd);
316 if (disp_.dispatched())
320 // it completely to get a 'bomb early' behaviour in case this
321 // object will be used again.
322 if (!disp_.dispatched()) {
323 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
325 disp_.update(Update::None);
326 disp_.dispatched(false);
328 // restore the previous one because nested Cursor::dispatch calls
329 // are possible which would change it
330 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
335 DispatchResult Cursor::result() const
341 BufferView & Cursor::bv() const
348 Buffer & Cursor::buffer() const
351 return bv_->buffer();
357 BOOST_ASSERT(depth() >= 1);
362 void Cursor::push(Inset & p)
364 push_back(CursorSlice(p));
368 void Cursor::pushBackward(Inset & p)
370 BOOST_ASSERT(!empty());
371 //lyxerr << "Entering inset " << t << " front" << endl;
377 bool Cursor::popBackward()
379 BOOST_ASSERT(!empty());
387 bool Cursor::popForward()
389 BOOST_ASSERT(!empty());
390 //lyxerr << "Leaving inset from in back" << endl;
391 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
395 pos() += lastpos() - lp + 1;
400 int Cursor::currentMode()
402 BOOST_ASSERT(!empty());
403 for (int i = depth() - 1; i >= 0; --i) {
404 int res = operator[](i).inset().currentMode();
405 if (res != Inset::UNDECIDED_MODE)
408 return Inset::TEXT_MODE;
412 void Cursor::getPos(int & x, int & y) const
414 Point p = bv().getPos(*this, boundary());
420 Row const & Cursor::textRow() const
422 CursorSlice const & cs = innerTextSlice();
423 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
424 BOOST_ASSERT(!pm.rows().empty());
425 return pm.getRow(pos(), boundary());
429 void Cursor::resetAnchor()
436 bool Cursor::posBackward()
445 bool Cursor::posForward()
447 if (pos() == lastpos())
454 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos)
456 // preparing bidi tables
457 Paragraph const & par = paragraph();
458 Buffer const & buf = buffer();
459 Row const & row = textRow();
461 bidi.computeTables(par, buf, row);
463 LYXERR(Debug::RTL, "bidi: " << row.pos() << "--" << row.endpos());
465 // The cursor is painted *before* the character at pos(), or, if 'boundary'
466 // is true, *after* the character at (pos() - 1). So we already have one
467 // known position around the cursor:
468 pos_type known_pos = boundary() ? pos() - 1 : pos();
470 // Whether 'known_pos' is to the left or to the right of the cursor depends
471 // on whether it is an RTL or LTR character...
472 bool const cur_is_RTL =
473 par.getFontSettings(buf.params(), known_pos).isVisibleRightToLeft();
474 // ... in the following manner:
475 // For an RTL character, "before" means "to the right" and "after" means
476 // "to the left"; and for LTR, it's the reverse. So, 'known_pos' is to the
477 // right of the cursor if (RTL && boundary) or (!RTL && !boundary):
478 bool known_pos_on_right = (cur_is_RTL == boundary());
480 // So we now know one of the positions surrounding the cursor. Let's
481 // determine the other one:
483 if (known_pos_on_right) {
484 // edge-case: we're at the end of the paragraph, there isn't really any
485 // position any further to the right
486 if (known_pos == lastpos()) {
488 left_pos = row.endpos() - 1;
492 right_pos = known_pos;
493 // *visual* position of 'left_pos':
494 pos_type v_left_pos = bidi.log2vis(right_pos) - 1;
495 // If the position we just identified as 'left_pos' is a "skipped
496 // separator" (a separator which is at the logical end of a row,
497 // except for the last row in a paragraph; such separators are not
498 // painted, so they "are not really there"; note that in bidi text,
499 // such a separator could appear visually in the middle of a row),
500 // set 'left_pos' to the *next* position to the left.
501 if (bidi.inRange(v_left_pos)
502 && bidi.vis2log(v_left_pos) + 1 == row.endpos()
503 && row.endpos() < lastpos()
504 && par.isSeparator(bidi.vis2log(v_left_pos))) {
507 // calculate the logical position of 'left_pos', if in row
508 if (!bidi.inRange(v_left_pos))
511 left_pos = bidi.vis2log(v_left_pos);
512 // If the position we identified as 'right_pos' is a "skipped
513 // separator", set 'right_pos' to the *next* position to the right.
514 if (right_pos + 1 == row.endpos() && row.endpos() < lastpos()
515 && par.isSeparator(right_pos)) {
516 pos_type v_right_pos = bidi.log2vis(right_pos) + 1;
517 if (!bidi.inRange(v_right_pos))
520 right_pos = bidi.vis2log(v_right_pos);
523 else { // known_pos is on the left
524 // edge-case: we're at the end of the paragraph, there isn't really any
525 // position any further to the left
526 if (known_pos == lastpos()) {
528 right_pos = row.endpos() - 1;
532 left_pos = known_pos;
533 // *visual* position of 'right_pos'
534 pos_type v_right_pos = bidi.log2vis(left_pos) + 1;
535 // If the position we just identified as 'right_pos' is a "skipped
536 // separator", set 'right_pos' to the *next* position to the right.
537 if (bidi.inRange(v_right_pos)
538 && bidi.vis2log(v_right_pos) + 1 == row.endpos()
539 && row.endpos() < lastpos()
540 && par.isSeparator(bidi.vis2log(v_right_pos))) {
543 // calculate the logical position of 'right_pos', if in row
544 if (!bidi.inRange(v_right_pos))
547 right_pos = bidi.vis2log(v_right_pos);
548 // If the position we identified as 'left_pos' is a "skipped
549 // separator", set 'left_pos' to the *next* position to the left.
550 if (left_pos + 1 == row.endpos() && row.endpos() < lastpos()
551 && par.isSeparator(left_pos)) {
552 pos_type v_left_pos = bidi.log2vis(left_pos) - 1;
553 if (!bidi.inRange(v_left_pos))
556 left_pos = bidi.vis2log(v_left_pos);
563 bool Cursor::posVisToNewRow(bool movingLeft)
565 Paragraph const & par = paragraph();
566 Buffer const & buf = buffer();
567 Row const & row = textRow();
568 bool par_is_LTR = !par.isRTL(buf.params());
570 // if moving left in an LTR paragraph or moving right in an RTL one,
571 // move to previous row
572 if (par_is_LTR == movingLeft) {
573 if (row.pos() == 0) { // we're at first row in paragraph
574 if (pit() == 0) // no previous paragraph! don't move
576 // move to last pos in previous par
580 } else { // move to previous row in this par
581 pos() = row.pos() - 1; // this is guaranteed to be in previous row
585 // if moving left in an RTL paragraph or moving right in an LTR one,
588 if (row.endpos() == lastpos()) { // we're at last row in paragraph
589 if (pit() == lastpit()) // last paragraph! don't move
591 // move to first row in next par
595 } else { // move to next row in this par
596 pos() = row.endpos();
601 // make sure we're at left-/right-most pos in new row
602 posVisToRowExtremity(!movingLeft);
608 void Cursor::posVisToRowExtremity(bool left)
610 // prepare bidi tables
611 Paragraph const & par = paragraph();
612 Buffer const & buf = buffer();
613 Row const & row = textRow();
615 bidi.computeTables(par, buf, row);
617 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
618 << (boundary() ? 1 : 0));
620 if (left) { // move to leftmost position
621 // if this is an RTL paragraph, and we're at the last row in the
622 // paragraph, move to lastpos
623 if (par.isRTL(buf.params()) && row.endpos() == lastpos())
626 pos() = bidi.vis2log(row.pos());
628 // Moving to the leftmost position in the row, the cursor should
629 // normally be placed to the *left* of the leftmost position.
630 // A very common exception, though, is if the leftmost character
631 // also happens to be the separator at the (logical) end of the row
632 // --- in this case, the separator is positioned beyond the left
633 // margin, and we don't want to move the cursor there (moving to
634 // the left of the separator is equivalent to moving to the next
635 // line). So, in this case we actually want to place the cursor
636 // to the *right* of the leftmost position (the separator).
637 // Another exception is if we're moving to the logically last
638 // position in the row, which is *not* a separator: this means
639 // that the entire row has no separators (if there were any, the
640 // row would have been broken there); and therefore in this case
641 // we also move to the *right* of the last position (this indicates
642 // to the user that there is no space after this position, and is
643 // consistent with the behavior in the middle of a row --- moving
644 // right or left moves to the next/previous character; if we were
645 // to move to the *left* of this position, that would simulate
646 // a separator which is not really there!).
647 // Finally, there is an exception to the previous exception: if
648 // this non-separator-but-last-position-in-row is an inset, then
649 // we *do* want to stay to the left of it anyway: this is the
650 // "boundary" which we simulate at insets.
652 bool right_of_pos = false; // do we want to be to the right of pos?
654 // as explained above, if at last pos in row, stay to the right
655 if ((pos() == row.endpos() - 1) && !par.isInset(pos()))
658 // Now we know if we want to be to the left or to the right of pos,
659 // let's make sure we are where we want to be.
660 bool new_pos_is_RTL =
661 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
663 if (new_pos_is_RTL == !right_of_pos) {
670 else { // move to rightmost position
671 // if this is an LTR paragraph, and we're at the last row in the
672 // paragraph, move to lastpos
673 if (!par.isRTL(buf.params()) && row.endpos() == lastpos())
676 pos() = bidi.vis2log(row.endpos() - 1);
678 // Moving to the rightmost position in the row, the cursor should
679 // normally be placed to the *right* of the rightmost position.
680 // A very common exception, though, is if the rightmost character
681 // also happens to be the separator at the (logical) end of the row
682 // --- in this case, the separator is positioned beyond the right
683 // margin, and we don't want to move the cursor there (moving to
684 // the right of the separator is equivalent to moving to the next
685 // line). So, in this case we actually want to place the cursor
686 // to the *left* of the rightmost position (the separator).
687 // Another exception is if we're moving to the logically last
688 // position in the row, which is *not* a separator: this means
689 // that the entire row has no separators (if there were any, the
690 // row would have been broken there); and therefore in this case
691 // we also move to the *left* of the last position (this indicates
692 // to the user that there is no space after this position, and is
693 // consistent with the behavior in the middle of a row --- moving
694 // right or left moves to the next/previous character; if we were
695 // to move to the *right* of this position, that would simulate
696 // a separator which is not really there!).
697 // Finally, there is an exception to the previous exception: if
698 // this non-separator-but-last-position-in-row is an inset, then
699 // we *do* want to stay to the right of it anyway: this is the
700 // "boundary" which we simulate at insets.
702 bool left_of_pos = false; // do we want to be to the left of pos?
704 // as explained above, if at last pos in row, stay to the left
705 if ((pos() == row.endpos() - 1) && !par.isInset(pos()))
708 // Now we know if we want to be to the left or to the right of pos,
709 // let's make sure we are where we want to be.
710 bool new_pos_is_RTL =
711 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
713 if (new_pos_is_RTL == left_of_pos) {
719 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
720 << (boundary() ? 1 : 0));
724 CursorSlice Cursor::anchor() const
726 BOOST_ASSERT(anchor_.depth() >= depth());
727 CursorSlice normal = anchor_[depth() - 1];
728 if (depth() < anchor_.depth() && top() <= normal) {
729 // anchor is behind cursor -> move anchor behind the inset
736 CursorSlice Cursor::selBegin() const
740 return anchor() < top() ? anchor() : top();
744 CursorSlice Cursor::selEnd() const
748 return anchor() > top() ? anchor() : top();
752 DocIterator Cursor::selectionBegin() const
756 DocIterator di = (anchor() < top() ? anchor_ : *this);
762 DocIterator Cursor::selectionEnd() const
766 DocIterator di = (anchor() > top() ? anchor_ : *this);
767 if (di.depth() > depth()) {
775 void Cursor::setSelection()
778 // A selection with no contents is not a selection
779 // FIXME: doesnt look ok
780 if (pit() == anchor().pit() && pos() == anchor().pos())
785 void Cursor::setSelection(DocIterator const & where, int n)
794 void Cursor::clearSelection()
802 void Cursor::setTargetX(int x)
805 textTargetOffset_ = 0;
809 int Cursor::x_target() const
815 void Cursor::clearTargetX()
818 textTargetOffset_ = 0;
822 void Cursor::updateTextTargetOffset()
827 textTargetOffset_ = x - x_target_;
831 void Cursor::info(odocstream & os) const
833 for (int i = 1, n = depth(); i < n; ++i) {
834 operator[](i).inset().infoize(os);
838 Inset const * inset = prevInset();
839 // prevInset() can return 0 in certain case.
841 prevInset()->infoize2(os);
843 // overwite old message
848 bool Cursor::selHandle(bool sel)
850 //lyxerr << "Cursor::selHandle" << endl;
853 if (sel == selection())
857 cap::saveSelection(*this);
865 ostream & operator<<(ostream & os, Cursor const & cur)
867 os << "\n cursor: | anchor:\n";
868 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
869 os << " " << cur[i] << " | ";
870 if (i < cur.anchor_.depth())
871 os << cur.anchor_[i];
873 os << "-------------------------------";
876 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
877 os << "------------------------------- | " << cur.anchor_[i] << "\n";
879 os << " selection: " << cur.selection_
880 << " x_target: " << cur.x_target_ << endl;
885 LyXErr & operator<<(LyXErr & os, Cursor const & cur)
895 ///////////////////////////////////////////////////////////////////
898 // The part below is the non-integrated rest of the original math
899 // cursor. This should be either generalized for texted or moved
900 // back to mathed (in most cases to InsetMathNest).
902 ///////////////////////////////////////////////////////////////////
904 #include "mathed/InsetMathChar.h"
905 #include "mathed/InsetMathGrid.h"
906 #include "mathed/InsetMathScript.h"
907 #include "mathed/InsetMathUnknown.h"
908 #include "mathed/MathFactory.h"
909 #include "mathed/MathStream.h"
910 #include "mathed/MathSupport.h"
915 //#define FILEDEBUG 1
918 bool Cursor::isInside(Inset const * p) const
920 for (size_t i = 0; i != depth(); ++i)
921 if (&operator[](i).inset() == p)
927 void Cursor::leaveInset(Inset const & inset)
929 for (size_t i = 0; i != depth(); ++i) {
930 if (&operator[](i).inset() == &inset) {
938 bool Cursor::openable(MathAtom const & t) const
949 // we can't move into anything new during selection
950 if (depth() >= anchor_.depth())
952 if (t.nucleus() != &anchor_[depth()].inset())
959 void Cursor::setScreenPos(int x, int /*y*/)
962 //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
967 void Cursor::plainErase()
973 void Cursor::markInsert()
975 insert(char_type(0));
979 void Cursor::markErase()
985 void Cursor::plainInsert(MathAtom const & t)
987 cell().insert(pos(), t);
992 void Cursor::insert(docstring const & str)
994 for_each(str.begin(), str.end(),
995 boost::bind(static_cast<void(Cursor::*)(char_type)>
996 (&Cursor::insert), this, _1));
1000 void Cursor::insert(char_type c)
1002 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1003 BOOST_ASSERT(!empty());
1005 cap::selClearOrDel(*this);
1006 insert(new InsetMathChar(c));
1008 text()->insertChar(*this, c);
1013 void Cursor::insert(MathAtom const & t)
1015 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1017 cap::selClearOrDel(*this);
1022 void Cursor::insert(Inset * inset)
1025 insert(MathAtom(inset));
1027 text()->insertInset(*this, inset);
1031 void Cursor::niceInsert(docstring const & t)
1042 void Cursor::niceInsert(MathAtom const & t)
1045 docstring const safe = cap::grabAndEraseSelection(*this);
1047 // enter the new inset and move the contents of the selection if possible
1048 if (t->isActive()) {
1050 // be careful here: don't use 'pushBackward(t)' as this we need to
1051 // push the clone, not the original
1052 pushBackward(*nextInset());
1053 // We may not use niceInsert here (recursion)
1061 void Cursor::insert(MathData const & ar)
1065 cap::eraseSelection(*this);
1066 cell().insert(pos(), ar);
1071 bool Cursor::backspace()
1073 autocorrect() = false;
1076 cap::eraseSelection(*this);
1081 // If empty cell, and not part of a big cell
1082 if (lastpos() == 0 && inset().nargs() == 1) {
1084 // Directly delete empty cell: [|[]] => [|]
1090 // [|], can not delete from inside
1101 if (inMacroMode()) {
1102 InsetMathUnknown * p = activeMacro();
1103 if (p->name().size() > 1) {
1104 p->setName(p->name().substr(0, p->name().size() - 1));
1109 if (pos() != 0 && prevAtom()->nargs() > 0) {
1110 // let's require two backspaces for 'big stuff' and
1111 // highlight on the first
1123 bool Cursor::erase()
1125 autocorrect() = false;
1130 cap::eraseSelection(*this);
1134 // delete empty cells if possible
1135 if (pos() == lastpos() && inset().idxDelete(idx()))
1138 // special behaviour when in last position of cell
1139 if (pos() == lastpos()) {
1140 bool one_cell = inset().nargs() == 1;
1141 if (one_cell && lastpos() == 0) {
1143 // Directly delete empty cell: [|[]] => [|]
1149 // [|], can not delete from inside
1154 inset().idxGlue(idx());
1158 // 'clever' UI hack: only erase large items if previously slected
1159 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
1174 DocIterator save = *this;
1175 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1176 this->dispatch(cmd);
1177 if (disp_.dispatched())
1180 autocorrect() = false;
1188 DocIterator save = *this;
1189 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1190 this->dispatch(cmd);
1191 if (disp_.dispatched())
1194 autocorrect() = false;
1199 bool Cursor::macroModeClose()
1203 InsetMathUnknown * p = activeMacro();
1205 docstring const s = p->name();
1207 cell().erase(pos());
1209 // do nothing if the macro name is empty
1213 // trigger updates of macros, at least, if no full
1214 // updates take place anyway
1215 updateFlags(Update::Force);
1217 docstring const name = s.substr(1);
1218 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1219 if (in && in->interpretString(*this, s))
1221 MathAtom atom = createInsetMath(name);
1222 MathMacro * atomAsMacro = atom.nucleus()->asMacro();
1224 // make non-greedy, i.e. don't eat parameters from the right
1225 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT);
1232 docstring Cursor::macroName()
1234 return inMacroMode() ? activeMacro()->name() : docstring();
1238 void Cursor::handleNest(MathAtom const & a, int c)
1240 //lyxerr << "Cursor::handleNest: " << c << endl;
1242 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1245 pushBackward(*nextInset());
1249 int Cursor::targetX() const
1251 if (x_target() != -1)
1260 int Cursor::textTargetOffset() const
1262 return textTargetOffset_;
1266 void Cursor::setTargetX()
1275 bool Cursor::inMacroMode() const
1281 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1282 return p && !p->final();
1286 InsetMathUnknown * Cursor::activeMacro()
1288 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1292 InsetMathUnknown const * Cursor::activeMacro() const
1294 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1298 void Cursor::pullArg()
1301 MathData ar = cell();
1302 if (popBackward() && inMathed()) {
1304 cell().insert(pos(), ar);
1307 //formula()->mutateToText();
1312 void Cursor::touch()
1316 DocIterator::const_iterator it = begin();
1317 DocIterator::const_iterator et = end();
1318 for ( ; it != et; ++it)
1324 void Cursor::normalize()
1326 if (idx() > lastidx()) {
1327 lyxerr << "this should not really happen - 1: "
1328 << idx() << ' ' << nargs()
1329 << " in: " << &inset() << endl;
1333 if (pos() > lastpos()) {
1334 lyxerr << "this should not really happen - 2: "
1335 << pos() << ' ' << lastpos() << " in idx: " << idx()
1337 odocstringstream os;
1338 WriteStream wi(os, false, true);
1339 inset().asInsetMath()->write(wi);
1340 lyxerr << to_utf8(os.str()) << endl;
1346 bool Cursor::upDownInMath(bool up)
1348 // Be warned: The 'logic' implemented in this function is highly
1349 // fragile. A distance of one pixel or a '<' vs '<=' _really
1350 // matters. So fiddle around with it only if you think you know
1351 // what you are doing!
1355 xo = theLyXFunc().cursorBeforeDispatchX();
1357 // check if we had something else in mind, if not, this is the future
1359 if (x_target_ == -1)
1361 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1362 // In text mode inside the line (not left or right) possibly set a new target_x,
1363 // but only if we are somewhere else than the previous target-offset.
1365 // We want to keep the x-target on subsequent up/down movements
1366 // that cross beyond the end of short lines. Thus a special
1367 // handling when the cursor is at the end of line: Use the new
1368 // x-target only if the old one was before the end of line
1369 // or the old one was after the beginning of the line
1370 bool inRTL = isWithinRtlParagraph(*this);
1374 left = pos() == textRow().endpos();
1375 right = pos() == textRow().pos();
1377 left = pos() == textRow().pos();
1378 right = pos() == textRow().endpos();
1380 if ((!left && !right) ||
1381 (left && !right && xo < x_target_) ||
1382 (!left && right && x_target_ < xo))
1389 // try neigbouring script insets
1391 if (inMathed() && !selection()) {
1394 InsetMathScript const * p = prevAtom()->asScriptInset();
1395 if (p && p->has(up)) {
1397 push(*const_cast<InsetMathScript*>(p));
1398 idx() = p->idxOfScript(up);
1401 // we went in the right direction? Otherwise don't jump into the script
1405 int oy = theLyXFunc().cursorBeforeDispatchY();
1406 if ((!up && y <= oy) ||
1415 if (pos() != lastpos()) {
1416 InsetMathScript const * p = nextAtom()->asScriptInset();
1417 if (p && p->has(up)) {
1418 push(*const_cast<InsetMathScript*>(p));
1419 idx() = p->idxOfScript(up);
1422 // we went in the right direction? Otherwise don't jump into the script
1426 int oy = theLyXFunc().cursorBeforeDispatchY();
1427 if ((!up && y <= oy) ||
1436 // try to find an inset that knows better then we,
1437 if (inset().idxUpDown(*this, up)) {
1438 //lyxerr << "idxUpDown triggered" << endl;
1439 // try to find best position within this inset
1441 setCursor(bruteFind2(*this, xo, yo));
1445 // any improvement going just out of inset?
1446 if (popBackward() && inMathed()) {
1447 //lyxerr << "updown: popBackward succeeded" << endl;
1450 int yold = theLyXFunc().cursorBeforeDispatchY();
1452 if (up ? ynew < yold : ynew > yold)
1456 // no success, we are probably at the document top or bottom
1462 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1464 BOOST_ASSERT(text());
1470 xo = theLyXFunc().cursorBeforeDispatchX();
1472 // update the targetX - this is here before the "return false"
1473 // to set a new target which can be used by InsetTexts above
1474 // if we cannot move up/down inside this inset anymore
1475 if (x_target_ == -1)
1477 else if (xo - textTargetOffset() != x_target() &&
1478 depth() == beforeDispatchCursor_.depth()) {
1479 // In text mode inside the line (not left or right) possibly set a new target_x,
1480 // but only if we are somewhere else than the previous target-offset.
1482 // We want to keep the x-target on subsequent up/down movements
1483 // that cross beyond the end of short lines. Thus a special
1484 // handling when the cursor is at the end of line: Use the new
1485 // x-target only if the old one was before the end of line
1486 // or the old one was after the beginning of the line
1487 bool inRTL = isWithinRtlParagraph(*this);
1491 left = pos() == textRow().endpos();
1492 right = pos() == textRow().pos();
1494 left = pos() == textRow().pos();
1495 right = pos() == textRow().endpos();
1497 if ((!left && !right) ||
1498 (left && !right && xo < x_target_) ||
1499 (!left && right && x_target_ < xo))
1506 // first get the current line
1507 TextMetrics & tm = bv_->textMetrics(text());
1508 ParagraphMetrics const & pm = tm.parMetrics(pit());
1510 if (pos() && boundary())
1511 row = pm.pos2row(pos() - 1);
1513 row = pm.pos2row(pos());
1515 // are we not at the start or end?
1517 if (pit() == 0 && row == 0)
1520 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1521 row + 1 >= int(pm.rows().size()))
1525 // with and without selection are handled differently
1527 int yo = bv().getPos(*this, boundary()).y_;
1529 // To next/previous row
1531 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1533 tm.editXY(*this, xo, yo + textRow().descent() + 1);
1536 // This happens when you move out of an inset.
1537 // And to give the DEPM the possibility of doing
1538 // something we must provide it with two different
1540 Cursor dummy = *this;
1543 if (bv().checkDepm(dummy, old)) {
1544 updateNeeded = true;
1545 // Make sure that cur gets back whatever happened to dummy(Lgb)
1549 // if there is a selection, we stay out of any inset, and just jump to the right position:
1553 top().pos() = min(tm.x2pos(pit(), row - 1, xo), top().lastpos());
1554 } else if (pit() > 0) {
1556 ParagraphMetrics const & pmcur = bv_->parMetrics(text(), pit());
1557 top().pos() = min(tm.x2pos(pit(), pmcur.rows().size() - 1, xo), top().lastpos());
1560 if (row + 1 < int(pm.rows().size())) {
1561 top().pos() = min(tm.x2pos(pit(), row + 1, xo), top().lastpos());
1562 } else if (pit() + 1 < int(text()->paragraphs().size())) {
1564 top().pos() = min(tm.x2pos(pit(), 0, xo), top().lastpos());
1568 updateNeeded |= bv().checkDepm(*this, old);
1571 updateTextTargetOffset();
1576 void Cursor::handleFont(string const & font)
1578 LYXERR(Debug::DEBUG, font);
1582 safe = cap::grabAndEraseSelection(*this);
1585 if (lastpos() != 0) {
1586 // something left in the cell
1588 // cursor in first position
1590 } else if (pos() == lastpos()) {
1591 // cursor in last position
1594 // cursor in between. split cell
1595 MathData::iterator bt = cell().begin();
1596 MathAtom at = createInsetMath(from_utf8(font));
1597 at.nucleus()->cell(0) = MathData(bt, bt + pos());
1598 cell().erase(bt, bt + pos());
1603 // nothing left in the cell
1611 void Cursor::message(docstring const & msg) const
1613 theLyXFunc().setMessage(msg);
1617 void Cursor::errorMessage(docstring const & msg) const
1619 theLyXFunc().setErrorMessage(msg);
1623 docstring Cursor::selectionAsString(bool label) const
1629 Buffer const & buffer = bv().buffer();
1630 ParagraphList const & pars = text()->paragraphs();
1632 // should be const ...
1633 pit_type startpit = selBegin().pit();
1634 pit_type endpit = selEnd().pit();
1635 size_t const startpos = selBegin().pos();
1636 size_t const endpos = selEnd().pos();
1638 if (startpit == endpit)
1639 return pars[startpit].asString(buffer, startpos, endpos, label);
1641 // First paragraph in selection
1642 docstring result = pars[startpit].
1643 asString(buffer, startpos, pars[startpit].size(), label)
1644 + parbreak(pars[startpit]);
1646 // The paragraphs in between (if any)
1647 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1648 Paragraph const & par = pars[pit];
1649 result += par.asString(buffer, 0, par.size(), label)
1650 + parbreak(pars[pit]);
1653 // Last paragraph in selection
1654 result += pars[endpit].asString(buffer, 0, endpos, label);
1660 return cap::grabSelection(*this);
1666 docstring Cursor::currentState()
1669 odocstringstream os;
1675 return text()->currentState(*this);
1681 docstring Cursor::getPossibleLabel()
1683 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
1687 Encoding const * Cursor::getEncoding() const
1691 CursorSlice const & sl = innerTextSlice();
1692 Text const & text = *sl.text();
1693 Font font = text.getPar(sl.pit()).getFont(
1694 bv().buffer().params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1695 return font.language()->encoding();
1699 void Cursor::undispatched()
1701 disp_.dispatched(false);
1705 void Cursor::dispatched()
1707 disp_.dispatched(true);
1711 void Cursor::updateFlags(Update::flags f)
1717 void Cursor::noUpdate()
1719 disp_.update(Update::None);
1723 Font Cursor::getFont() const
1725 // The logic here should more or less match to the Cursor::setCurrentFont
1726 // logic, i.e. the cursor height should give a hint what will happen
1727 // if a character is entered.
1729 // HACK. far from being perfect...
1731 CursorSlice const & sl = innerTextSlice();
1732 Text const & text = *sl.text();
1733 Paragraph const & par = text.getPar(sl.pit());
1735 // on boundary, so we are really at the character before
1736 pos_type pos = sl.pos();
1737 if (pos > 0 && boundary())
1740 // on space? Take the font before (only for RTL boundary stay)
1742 TextMetrics const & tm = bv().textMetrics(&text);
1743 if (pos == sl.lastpos()
1744 || (par.isSeparator(pos)
1745 && !tm.isRTLBoundary(sl.pit(), pos)))
1749 // get font at the position
1750 Font font = par.getFont(bv().buffer().params(), pos,
1751 outerFont(sl.pit(), text.paragraphs()));
1757 bool Cursor::fixIfBroken()
1759 if (DocIterator::fixIfBroken()) {
1768 bool notifyCursorLeaves(Cursor const & old, Cursor & cur)
1770 // find inset in common
1772 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
1773 if (&old[i].inset() != &cur[i].inset())
1777 // notify everything on top of the common part in old cursor,
1778 // but stop if the inset claims the cursor to be invalid now
1779 for (; i < old.depth(); ++i) {
1780 Cursor insetPos = old;
1782 if (old[i].inset().notifyCursorLeaves(insetPos, cur))
1790 void Cursor::setCurrentFont()
1792 CursorSlice const & cs = innerTextSlice();
1793 Paragraph const & par = cs.paragraph();
1794 pos_type cpit = cs.pit();
1795 pos_type cpos = cs.pos();
1796 Text const & ctext = *cs.text();
1797 TextMetrics const & tm = bv().textMetrics(&ctext);
1799 // are we behind previous char in fact? -> go to that char
1800 if (cpos > 0 && boundary())
1803 // find position to take the font from
1805 // paragraph end? -> font of last char
1806 if (cpos == lastpos())
1808 // on space? -> look at the words in front of space
1809 else if (cpos > 0 && par.isSeparator(cpos)) {
1810 // abc| def -> font of c
1811 // abc |[WERBEH], i.e. boundary==true -> font of c
1812 // abc [WERBEH]| def, font of the space
1813 if (!tm.isRTLBoundary(cpit, cpos))
1819 BufferParams const & bufparams = buffer().params();
1820 current_font = par.getFontSettings(bufparams, cpos);
1821 real_current_font = tm.getDisplayFont(cpit, cpos);
1823 // special case for paragraph end
1824 if (cs.pos() == lastpos()
1825 && tm.isRTLBoundary(cpit, cs.pos())
1827 Language const * lang = par.getParLanguage(bufparams);
1828 current_font.setLanguage(lang);
1829 current_font.fontInfo().setNumber(FONT_OFF);
1830 real_current_font.setLanguage(lang);
1831 real_current_font.fontInfo().setNumber(FONT_OFF);
1836 bool Cursor::textUndo()
1838 DocIterator dit = *this;
1839 // Undo::textUndo() will modify dit.
1840 if (!bv_->buffer().undo().textUndo(dit))
1844 selection() = false;
1851 bool Cursor::textRedo()
1853 DocIterator dit = *this;
1854 // Undo::textRedo() will modify dit.
1855 if (!bv_->buffer().undo().textRedo(dit))
1859 selection() = false;
1866 void Cursor::finishUndo()
1868 bv_->buffer().undo().finishUndo();
1872 void Cursor::recordUndo(UndoKind kind, pit_type from, pit_type to)
1874 bv_->buffer().undo().recordUndo(*this, kind, from, to);
1878 void Cursor::recordUndo(UndoKind kind, pit_type from)
1880 bv_->buffer().undo().recordUndo(*this, kind, from);
1884 void Cursor::recordUndo(UndoKind kind)
1886 bv_->buffer().undo().recordUndo(*this, kind);
1890 void Cursor::recordUndoInset(UndoKind kind)
1892 bv_->buffer().undo().recordUndoInset(*this, kind);
1896 void Cursor::recordUndoFullDocument()
1898 bv_->buffer().undo().recordUndoFullDocument(*this);
1902 void Cursor::recordUndoSelection()
1904 bv_->buffer().undo().recordUndo(*this, ATOMIC_UNDO,
1905 selBegin().pit(), selEnd().pit());
1909 void Cursor::checkBufferStructure()
1911 if (paragraph().layout()->toclevel == Layout::NOT_IN_TOC)
1913 Buffer const * master = buffer().masterBuffer();
1914 master->tocBackend().updateItem(ParConstIterator(*this));
1915 master->structureChanged();