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/InsetMathBrace.h"
47 #include "mathed/InsetMathScript.h"
48 #include "mathed/MacroTable.h"
49 #include "mathed/MathData.h"
50 #include "mathed/MathMacro.h"
52 #include <boost/assert.hpp>
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 BOOST_ASSERT(!cursor.empty());
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 Inset & inset = bv.buffer().inset();
209 DocIterator it = doc_iterator_begin(inset);
211 DocIterator et = doc_iterator_end(inset);
213 double best_dist = numeric_limits<double>::max();
214 DocIterator best_cursor = et;
216 for ( ; it != et; it.forwardPos()) {
217 // avoid invalid nesting when selecting
218 if (bv.cursorStatus(it) == CUR_INSIDE
219 && (!cur.selection() || positionable(it, cur.anchor_))) {
220 Point p = bv.getPos(it, false);
223 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
224 double const dx = xo - x;
225 double const dy = yo - y;
226 double const d = dx * dx + dy * dy;
227 //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
228 // << " dx: " << dx << " dy: " << dy
229 // << " idx: " << it.idx() << " pos: " << it.pos()
232 // '<=' in order to take the last possible position
233 // this is important for clicking behind \sum in e.g. '\sum_i a'
234 if (d <= best_dist) {
235 //lyxerr << "*" << endl;
243 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
244 if (best_cursor == et)
246 cur.setCursor(best_cursor);
250 docstring parbreak(Paragraph const & par)
252 odocstringstream ods;
254 // only add blank line if we're not in an ERT or Listings inset
255 if (par.ownerCode() != ERT_CODE
256 && par.ownerCode() != LISTINGS_CODE)
264 // be careful: this is called from the bv's constructor, too, so
265 // bv functions are not yet available!
266 Cursor::Cursor(BufferView & bv)
267 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1), textTargetOffset_(0),
268 selection_(false), mark_(false), logicalpos_(false),
269 current_font(inherit_font)
273 void Cursor::reset(Inset & inset)
276 push_back(CursorSlice(inset));
277 anchor_ = doc_iterator_begin(inset);
285 // this (intentionally) does neither touch anchor nor selection status
286 void Cursor::setCursor(DocIterator const & cur)
288 DocIterator::operator=(cur);
292 void Cursor::dispatch(FuncRequest const & cmd0)
294 LYXERR(Debug::DEBUG, "cmd: " << cmd0 << '\n' << *this);
299 FuncRequest cmd = cmd0;
302 // store some values to be used inside of the handlers
303 beforeDispatchCursor_ = *this;
304 for (; depth(); pop(), boundary(false)) {
305 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
306 << cmd0 << endl << *this);
307 BOOST_ASSERT(pos() <= lastpos());
308 BOOST_ASSERT(idx() <= lastidx());
309 BOOST_ASSERT(pit() <= lastpit());
311 // The common case is 'LFUN handled, need update', so make the
312 // LFUN handler's life easier by assuming this as default value.
313 // The handler can reset the update and val flags if necessary.
314 disp_.update(Update::FitCursor | Update::Force);
315 disp_.dispatched(true);
316 inset().dispatch(*this, cmd);
317 if (disp_.dispatched())
321 // it completely to get a 'bomb early' behaviour in case this
322 // object will be used again.
323 if (!disp_.dispatched()) {
324 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
326 disp_.update(Update::None);
327 disp_.dispatched(false);
329 // restore the previous one because nested Cursor::dispatch calls
330 // are possible which would change it
331 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
336 DispatchResult Cursor::result() const
342 BufferView & Cursor::bv() const
349 Buffer & Cursor::buffer() const
352 return bv_->buffer();
358 BOOST_ASSERT(depth() >= 1);
363 void Cursor::push(Inset & p)
365 push_back(CursorSlice(p));
366 p.setBuffer(bv_->buffer());
370 void Cursor::pushBackward(Inset & p)
372 BOOST_ASSERT(!empty());
373 //lyxerr << "Entering inset " << t << " front" << endl;
379 bool Cursor::popBackward()
381 BOOST_ASSERT(!empty());
389 bool Cursor::popForward()
391 BOOST_ASSERT(!empty());
392 //lyxerr << "Leaving inset from in back" << endl;
393 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
397 pos() += lastpos() - lp + 1;
402 int Cursor::currentMode()
404 BOOST_ASSERT(!empty());
405 for (int i = depth() - 1; i >= 0; --i) {
406 int res = operator[](i).inset().currentMode();
407 if (res != Inset::UNDECIDED_MODE)
410 return Inset::TEXT_MODE;
414 void Cursor::getPos(int & x, int & y) const
416 Point p = bv().getPos(*this, boundary());
422 Row const & Cursor::textRow() const
424 CursorSlice const & cs = innerTextSlice();
425 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
426 BOOST_ASSERT(!pm.rows().empty());
427 return pm.getRow(pos(), boundary());
431 void Cursor::resetAnchor()
438 bool Cursor::posBackward()
447 bool Cursor::posForward()
449 if (pos() == lastpos())
456 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos)
458 // preparing bidi tables
459 Paragraph const & par = paragraph();
460 Buffer const & buf = buffer();
461 Row const & row = textRow();
463 bidi.computeTables(par, buf, row);
465 LYXERR(Debug::RTL, "bidi: " << row.pos() << "--" << row.endpos());
467 // The cursor is painted *before* the character at pos(), or, if 'boundary'
468 // is true, *after* the character at (pos() - 1). So we already have one
469 // known position around the cursor:
470 pos_type known_pos = boundary() ? pos() - 1 : pos();
472 // edge case: if we're at the end of the paragraph, things are a little
473 // different (because lastpos is a position which does not really "exist"
474 // --- there's no character there yet).
475 if (known_pos == lastpos()) {
476 if (par.isRTL(buf.params())) {
478 right_pos = bidi.vis2log(row.pos());
480 else { // LTR paragraph
482 left_pos = bidi.vis2log(row.endpos() - 1);
487 // Whether 'known_pos' is to the left or to the right of the cursor depends
488 // on whether it is an RTL or LTR character...
489 bool const cur_is_RTL =
490 par.getFontSettings(buf.params(), known_pos).isVisibleRightToLeft();
491 // ... in the following manner:
492 // For an RTL character, "before" means "to the right" and "after" means
493 // "to the left"; and for LTR, it's the reverse. So, 'known_pos' is to the
494 // right of the cursor if (RTL && boundary) or (!RTL && !boundary):
495 bool known_pos_on_right = (cur_is_RTL == boundary());
497 // So we now know one of the positions surrounding the cursor. Let's
498 // determine the other one:
500 if (known_pos_on_right) {
501 right_pos = known_pos;
502 // *visual* position of 'left_pos':
503 pos_type v_left_pos = bidi.log2vis(right_pos) - 1;
504 // If the position we just identified as 'left_pos' is a "skipped
505 // separator" (a separator which is at the logical end of a row,
506 // except for the last row in a paragraph; such separators are not
507 // painted, so they "are not really there"; note that in bidi text,
508 // such a separator could appear visually in the middle of a row),
509 // set 'left_pos' to the *next* position to the left.
510 if (bidi.inRange(v_left_pos)
511 && bidi.vis2log(v_left_pos) + 1 == row.endpos()
512 && row.endpos() < lastpos()
513 && par.isSeparator(bidi.vis2log(v_left_pos))) {
516 // calculate the logical position of 'left_pos', if in row
517 if (!bidi.inRange(v_left_pos))
520 left_pos = bidi.vis2log(v_left_pos);
521 // If the position we identified as 'right_pos' is a "skipped
522 // separator", set 'right_pos' to the *next* position to the right.
523 if (right_pos + 1 == row.endpos() && row.endpos() < lastpos()
524 && par.isSeparator(right_pos)) {
525 pos_type v_right_pos = bidi.log2vis(right_pos) + 1;
526 if (!bidi.inRange(v_right_pos))
529 right_pos = bidi.vis2log(v_right_pos);
532 else { // known_pos is on the left
533 left_pos = known_pos;
534 // *visual* position of 'right_pos'
535 pos_type v_right_pos = bidi.log2vis(left_pos) + 1;
536 // If the position we just identified as 'right_pos' is a "skipped
537 // separator", set 'right_pos' to the *next* position to the right.
538 if (bidi.inRange(v_right_pos)
539 && bidi.vis2log(v_right_pos) + 1 == row.endpos()
540 && row.endpos() < lastpos()
541 && par.isSeparator(bidi.vis2log(v_right_pos))) {
544 // calculate the logical position of 'right_pos', if in row
545 if (!bidi.inRange(v_right_pos))
548 right_pos = bidi.vis2log(v_right_pos);
549 // If the position we identified as 'left_pos' is a "skipped
550 // separator", set 'left_pos' to the *next* position to the left.
551 if (left_pos + 1 == row.endpos() && row.endpos() < lastpos()
552 && par.isSeparator(left_pos)) {
553 pos_type v_left_pos = bidi.log2vis(left_pos) - 1;
554 if (!bidi.inRange(v_left_pos))
557 left_pos = bidi.vis2log(v_left_pos);
564 bool Cursor::posVisToNewRow(bool movingLeft)
566 Paragraph const & par = paragraph();
567 Buffer const & buf = buffer();
568 Row const & row = textRow();
569 bool par_is_LTR = !par.isRTL(buf.params());
571 // if moving left in an LTR paragraph or moving right in an RTL one,
572 // move to previous row
573 if (par_is_LTR == movingLeft) {
574 if (row.pos() == 0) { // we're at first row in paragraph
575 if (pit() == 0) // no previous paragraph! don't move
577 // move to last pos in previous par
581 } else { // move to previous row in this par
582 pos() = row.pos() - 1; // this is guaranteed to be in previous row
586 // if moving left in an RTL paragraph or moving right in an LTR one,
589 if (row.endpos() == lastpos()) { // we're at last row in paragraph
590 if (pit() == lastpit()) // last paragraph! don't move
592 // move to first row in next par
596 } else { // move to next row in this par
597 pos() = row.endpos();
602 // make sure we're at left-/right-most pos in new row
603 posVisToRowExtremity(!movingLeft);
609 void Cursor::posVisToRowExtremity(bool left)
611 // prepare bidi tables
612 Paragraph const & par = paragraph();
613 Buffer const & buf = buffer();
614 Row const & row = textRow();
616 bidi.computeTables(par, buf, row);
618 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
619 << (boundary() ? 1 : 0));
621 if (left) { // move to leftmost position
622 // if this is an RTL paragraph, and we're at the last row in the
623 // paragraph, move to lastpos
624 if (par.isRTL(buf.params()) && row.endpos() == lastpos())
627 pos() = bidi.vis2log(row.pos());
629 // Moving to the leftmost position in the row, the cursor should
630 // normally be placed to the *left* of the leftmost position.
631 // A very common exception, though, is if the leftmost character
632 // also happens to be the separator at the (logical) end of the row
633 // --- in this case, the separator is positioned beyond the left
634 // margin, and we don't want to move the cursor there (moving to
635 // the left of the separator is equivalent to moving to the next
636 // line). So, in this case we actually want to place the cursor
637 // to the *right* of the leftmost position (the separator).
638 // Another exception is if we're moving to the logically last
639 // position in the row, which is *not* a separator: this means
640 // that the entire row has no separators (if there were any, the
641 // row would have been broken there); and therefore in this case
642 // we also move to the *right* of the last position (this indicates
643 // to the user that there is no space after this position, and is
644 // consistent with the behavior in the middle of a row --- moving
645 // right or left moves to the next/previous character; if we were
646 // to move to the *left* of this position, that would simulate
647 // a separator which is not really there!).
648 // Finally, there is an exception to the previous exception: if
649 // this non-separator-but-last-position-in-row is an inset, then
650 // we *do* want to stay to the left of it anyway: this is the
651 // "boundary" which we simulate at insets.
653 bool right_of_pos = false; // do we want to be to the right of pos?
655 // as explained above, if at last pos in row, stay to the right
656 if ((pos() == row.endpos() - 1) && !par.isInset(pos()))
659 // Now we know if we want to be to the left or to the right of pos,
660 // let's make sure we are where we want to be.
661 bool new_pos_is_RTL =
662 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
664 if (new_pos_is_RTL == !right_of_pos) {
671 else { // move to rightmost position
672 // if this is an LTR paragraph, and we're at the last row in the
673 // paragraph, move to lastpos
674 if (!par.isRTL(buf.params()) && row.endpos() == lastpos())
677 pos() = bidi.vis2log(row.endpos() - 1);
679 // Moving to the rightmost position in the row, the cursor should
680 // normally be placed to the *right* of the rightmost position.
681 // A very common exception, though, is if the rightmost character
682 // also happens to be the separator at the (logical) end of the row
683 // --- in this case, the separator is positioned beyond the right
684 // margin, and we don't want to move the cursor there (moving to
685 // the right of the separator is equivalent to moving to the next
686 // line). So, in this case we actually want to place the cursor
687 // to the *left* of the rightmost position (the separator).
688 // Another exception is if we're moving to the logically last
689 // position in the row, which is *not* a separator: this means
690 // that the entire row has no separators (if there were any, the
691 // row would have been broken there); and therefore in this case
692 // we also move to the *left* of the last position (this indicates
693 // to the user that there is no space after this position, and is
694 // consistent with the behavior in the middle of a row --- moving
695 // right or left moves to the next/previous character; if we were
696 // to move to the *right* of this position, that would simulate
697 // a separator which is not really there!).
698 // Finally, there is an exception to the previous exception: if
699 // this non-separator-but-last-position-in-row is an inset, then
700 // we *do* want to stay to the right of it anyway: this is the
701 // "boundary" which we simulate at insets.
703 bool left_of_pos = false; // do we want to be to the left of pos?
705 // as explained above, if at last pos in row, stay to the left
706 if ((pos() == row.endpos() - 1) && !par.isInset(pos()))
709 // Now we know if we want to be to the left or to the right of pos,
710 // let's make sure we are where we want to be.
711 bool new_pos_is_RTL =
712 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
714 if (new_pos_is_RTL == left_of_pos) {
720 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
721 << (boundary() ? 1 : 0));
725 CursorSlice Cursor::anchor() const
727 BOOST_ASSERT(anchor_.depth() >= depth());
728 CursorSlice normal = anchor_[depth() - 1];
729 if (depth() < anchor_.depth() && top() <= normal) {
730 // anchor is behind cursor -> move anchor behind the inset
737 CursorSlice Cursor::selBegin() const
741 return anchor() < top() ? anchor() : top();
745 CursorSlice Cursor::selEnd() const
749 return anchor() > top() ? anchor() : top();
753 DocIterator Cursor::selectionBegin() const
757 DocIterator di = (anchor() < top() ? anchor_ : *this);
763 DocIterator Cursor::selectionEnd() const
767 DocIterator di = (anchor() > top() ? anchor_ : *this);
768 if (di.depth() > depth()) {
776 void Cursor::setSelection()
779 // A selection with no contents is not a selection
780 // FIXME: doesnt look ok
781 if (pit() == anchor().pit() && pos() == anchor().pos())
786 void Cursor::setSelection(DocIterator const & where, int n)
795 void Cursor::clearSelection()
803 void Cursor::setTargetX(int x)
806 textTargetOffset_ = 0;
810 int Cursor::x_target() const
816 void Cursor::clearTargetX()
819 textTargetOffset_ = 0;
823 void Cursor::updateTextTargetOffset()
828 textTargetOffset_ = x - x_target_;
832 void Cursor::info(odocstream & os) const
834 for (int i = 1, n = depth(); i < n; ++i) {
835 operator[](i).inset().infoize(os);
839 Inset const * inset = prevInset();
840 // prevInset() can return 0 in certain case.
842 prevInset()->infoize2(os);
844 // overwite old message
849 bool Cursor::selHandle(bool sel)
851 //lyxerr << "Cursor::selHandle" << endl;
854 if (sel == selection())
858 cap::saveSelection(*this);
866 ostream & operator<<(ostream & os, Cursor const & cur)
868 os << "\n cursor: | anchor:\n";
869 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
870 os << " " << cur[i] << " | ";
871 if (i < cur.anchor_.depth())
872 os << cur.anchor_[i];
874 os << "-------------------------------";
877 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
878 os << "------------------------------- | " << cur.anchor_[i] << "\n";
880 os << " selection: " << cur.selection_
881 << " x_target: " << cur.x_target_ << endl;
886 LyXErr & operator<<(LyXErr & os, Cursor const & cur)
896 ///////////////////////////////////////////////////////////////////
899 // The part below is the non-integrated rest of the original math
900 // cursor. This should be either generalized for texted or moved
901 // back to mathed (in most cases to InsetMathNest).
903 ///////////////////////////////////////////////////////////////////
905 #include "mathed/InsetMathChar.h"
906 #include "mathed/InsetMathGrid.h"
907 #include "mathed/InsetMathScript.h"
908 #include "mathed/InsetMathUnknown.h"
909 #include "mathed/MathFactory.h"
910 #include "mathed/MathStream.h"
911 #include "mathed/MathSupport.h"
916 //#define FILEDEBUG 1
919 bool Cursor::isInside(Inset const * p) const
921 for (size_t i = 0; i != depth(); ++i)
922 if (&operator[](i).inset() == p)
928 void Cursor::leaveInset(Inset const & inset)
930 for (size_t i = 0; i != depth(); ++i) {
931 if (&operator[](i).inset() == &inset) {
939 bool Cursor::openable(MathAtom const & t) const
950 // we can't move into anything new during selection
951 if (depth() >= anchor_.depth())
953 if (t.nucleus() != &anchor_[depth()].inset())
960 void Cursor::setScreenPos(int x, int /*y*/)
963 //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
968 void Cursor::plainErase()
974 void Cursor::markInsert()
976 insert(char_type(0));
980 void Cursor::markErase()
986 void Cursor::plainInsert(MathAtom const & t)
988 cell().insert(pos(), t);
990 inset().setBuffer(bv_->buffer());
995 void Cursor::insert(docstring const & str)
997 for_each(str.begin(), str.end(),
998 boost::bind(static_cast<void(Cursor::*)(char_type)>
999 (&Cursor::insert), this, _1));
1003 void Cursor::insert(char_type c)
1005 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1006 BOOST_ASSERT(!empty());
1008 cap::selClearOrDel(*this);
1009 insert(new InsetMathChar(c));
1011 text()->insertChar(*this, c);
1016 void Cursor::insert(MathAtom const & t)
1018 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1020 cap::selClearOrDel(*this);
1025 void Cursor::insert(Inset * inset0)
1027 BOOST_ASSERT(inset0);
1029 insert(MathAtom(inset0));
1031 text()->insertInset(*this, inset0);
1032 inset0->setBuffer(bv_->buffer());
1038 void Cursor::niceInsert(docstring const & t)
1049 void Cursor::niceInsert(MathAtom const & t)
1052 docstring const safe = cap::grabAndEraseSelection(*this);
1054 // enter the new inset and move the contents of the selection if possible
1055 if (t->isActive()) {
1057 // be careful here: don't use 'pushBackward(t)' as this we need to
1058 // push the clone, not the original
1059 pushBackward(*nextInset());
1060 // We may not use niceInsert here (recursion)
1068 void Cursor::insert(MathData const & ar)
1072 cap::eraseSelection(*this);
1073 cell().insert(pos(), ar);
1078 bool Cursor::backspace()
1080 autocorrect() = false;
1083 cap::eraseSelection(*this);
1088 // If empty cell, and not part of a big cell
1089 if (lastpos() == 0 && inset().nargs() == 1) {
1091 // Directly delete empty cell: [|[]] => [|]
1097 // [|], can not delete from inside
1108 if (inMacroMode()) {
1109 InsetMathUnknown * p = activeMacro();
1110 if (p->name().size() > 1) {
1111 p->setName(p->name().substr(0, p->name().size() - 1));
1116 if (pos() != 0 && prevAtom()->nargs() > 0) {
1117 // let's require two backspaces for 'big stuff' and
1118 // highlight on the first
1130 bool Cursor::erase()
1132 autocorrect() = false;
1137 cap::eraseSelection(*this);
1141 // delete empty cells if possible
1142 if (pos() == lastpos() && inset().idxDelete(idx()))
1145 // special behaviour when in last position of cell
1146 if (pos() == lastpos()) {
1147 bool one_cell = inset().nargs() == 1;
1148 if (one_cell && lastpos() == 0) {
1150 // Directly delete empty cell: [|[]] => [|]
1156 // [|], can not delete from inside
1161 inset().idxGlue(idx());
1165 // 'clever' UI hack: only erase large items if previously slected
1166 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
1181 DocIterator save = *this;
1182 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1183 this->dispatch(cmd);
1184 if (disp_.dispatched())
1187 autocorrect() = false;
1195 DocIterator save = *this;
1196 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1197 this->dispatch(cmd);
1198 if (disp_.dispatched())
1201 autocorrect() = false;
1206 bool Cursor::macroModeClose()
1210 InsetMathUnknown * p = activeMacro();
1213 asArray(p->selection(), selection);
1214 docstring const s = p->name();
1216 cell().erase(pos());
1218 // do nothing if the macro name is empty
1222 // trigger updates of macros, at least, if no full
1223 // updates take place anyway
1224 updateFlags(Update::Force);
1226 docstring const name = s.substr(1);
1227 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1228 if (in && in->interpretString(*this, s))
1230 MathAtom atom = createInsetMath(name);
1232 // try to put argument into macro, if we just inserted a macro
1233 bool macroArg = false;
1234 MathMacro * atomAsMacro = atom.nucleus()->asMacro();
1236 // macros here are still unfolded (in init mode in fact). So
1237 // we have to resolve the macro here manually and check its arity
1238 // to put the selection behind it if arity > 0.
1239 MacroData const * data = buffer().getMacro(atomAsMacro->name());
1240 if (selection.size() > 0 && data && data->numargs() - data->optionals() > 0) {
1242 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1244 // non-greedy case. Do not touch the arguments behind
1245 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1248 // insert remembered selection into first argument of a non-macro
1249 else if (atom.nucleus()->nargs() > 0)
1250 atom.nucleus()->cell(0).append(selection);
1254 // finally put the macro argument behind, if needed
1256 if (selection.size() > 1)
1257 plainInsert(MathAtom(new InsetMathBrace(selection)));
1266 docstring Cursor::macroName()
1268 return inMacroMode() ? activeMacro()->name() : docstring();
1272 void Cursor::handleNest(MathAtom const & a, int c)
1274 //lyxerr << "Cursor::handleNest: " << c << endl;
1276 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1279 pushBackward(*nextInset());
1283 int Cursor::targetX() const
1285 if (x_target() != -1)
1294 int Cursor::textTargetOffset() const
1296 return textTargetOffset_;
1300 void Cursor::setTargetX()
1309 bool Cursor::inMacroMode() const
1315 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1316 return p && !p->final();
1320 InsetMathUnknown * Cursor::activeMacro()
1322 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1326 InsetMathUnknown const * Cursor::activeMacro() const
1328 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1332 void Cursor::pullArg()
1335 MathData ar = cell();
1336 if (popBackward() && inMathed()) {
1338 cell().insert(pos(), ar);
1341 //formula()->mutateToText();
1346 void Cursor::touch()
1350 DocIterator::const_iterator it = begin();
1351 DocIterator::const_iterator et = end();
1352 for ( ; it != et; ++it)
1358 void Cursor::normalize()
1360 if (idx() > lastidx()) {
1361 lyxerr << "this should not really happen - 1: "
1362 << idx() << ' ' << nargs()
1363 << " in: " << &inset() << endl;
1367 if (pos() > lastpos()) {
1368 lyxerr << "this should not really happen - 2: "
1369 << pos() << ' ' << lastpos() << " in idx: " << idx()
1371 odocstringstream os;
1372 WriteStream wi(os, false, true);
1373 inset().asInsetMath()->write(wi);
1374 lyxerr << to_utf8(os.str()) << endl;
1380 bool Cursor::upDownInMath(bool up)
1382 // Be warned: The 'logic' implemented in this function is highly
1383 // fragile. A distance of one pixel or a '<' vs '<=' _really
1384 // matters. So fiddle around with it only if you think you know
1385 // what you are doing!
1389 xo = theLyXFunc().cursorBeforeDispatchX();
1391 // check if we had something else in mind, if not, this is the future
1393 if (x_target_ == -1)
1395 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1396 // In text mode inside the line (not left or right) possibly set a new target_x,
1397 // but only if we are somewhere else than the previous target-offset.
1399 // We want to keep the x-target on subsequent up/down movements
1400 // that cross beyond the end of short lines. Thus a special
1401 // handling when the cursor is at the end of line: Use the new
1402 // x-target only if the old one was before the end of line
1403 // or the old one was after the beginning of the line
1404 bool inRTL = isWithinRtlParagraph(*this);
1408 left = pos() == textRow().endpos();
1409 right = pos() == textRow().pos();
1411 left = pos() == textRow().pos();
1412 right = pos() == textRow().endpos();
1414 if ((!left && !right) ||
1415 (left && !right && xo < x_target_) ||
1416 (!left && right && x_target_ < xo))
1423 // try neigbouring script insets
1425 if (inMathed() && !selection()) {
1428 InsetMathScript const * p = prevAtom()->asScriptInset();
1429 if (p && p->has(up)) {
1431 push(*const_cast<InsetMathScript*>(p));
1432 idx() = p->idxOfScript(up);
1435 // we went in the right direction? Otherwise don't jump into the script
1439 int oy = theLyXFunc().cursorBeforeDispatchY();
1440 if ((!up && y <= oy) ||
1449 if (pos() != lastpos()) {
1450 InsetMathScript const * p = nextAtom()->asScriptInset();
1451 if (p && p->has(up)) {
1452 push(*const_cast<InsetMathScript*>(p));
1453 idx() = p->idxOfScript(up);
1456 // we went in the right direction? Otherwise don't jump into the script
1460 int oy = theLyXFunc().cursorBeforeDispatchY();
1461 if ((!up && y <= oy) ||
1470 // try to find an inset that knows better then we,
1471 if (inset().idxUpDown(*this, up)) {
1472 //lyxerr << "idxUpDown triggered" << endl;
1473 // try to find best position within this inset
1475 setCursor(bruteFind2(*this, xo, yo));
1479 // any improvement going just out of inset?
1480 if (popBackward() && inMathed()) {
1481 //lyxerr << "updown: popBackward succeeded" << endl;
1484 int yold = theLyXFunc().cursorBeforeDispatchY();
1486 if (up ? ynew < yold : ynew > yold)
1490 // no success, we are probably at the document top or bottom
1496 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1498 BOOST_ASSERT(text());
1504 xo = theLyXFunc().cursorBeforeDispatchX();
1506 // update the targetX - this is here before the "return false"
1507 // to set a new target which can be used by InsetTexts above
1508 // if we cannot move up/down inside this inset anymore
1509 if (x_target_ == -1)
1511 else if (xo - textTargetOffset() != x_target() &&
1512 depth() == beforeDispatchCursor_.depth()) {
1513 // In text mode inside the line (not left or right) possibly set a new target_x,
1514 // but only if we are somewhere else than the previous target-offset.
1516 // We want to keep the x-target on subsequent up/down movements
1517 // that cross beyond the end of short lines. Thus a special
1518 // handling when the cursor is at the end of line: Use the new
1519 // x-target only if the old one was before the end of line
1520 // or the old one was after the beginning of the line
1521 bool inRTL = isWithinRtlParagraph(*this);
1525 left = pos() == textRow().endpos();
1526 right = pos() == textRow().pos();
1528 left = pos() == textRow().pos();
1529 right = pos() == textRow().endpos();
1531 if ((!left && !right) ||
1532 (left && !right && xo < x_target_) ||
1533 (!left && right && x_target_ < xo))
1540 // first get the current line
1541 TextMetrics & tm = bv_->textMetrics(text());
1542 ParagraphMetrics const & pm = tm.parMetrics(pit());
1544 if (pos() && boundary())
1545 row = pm.pos2row(pos() - 1);
1547 row = pm.pos2row(pos());
1549 // are we not at the start or end?
1551 if (pit() == 0 && row == 0)
1554 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1555 row + 1 >= int(pm.rows().size()))
1559 // with and without selection are handled differently
1561 int yo = bv().getPos(*this, boundary()).y_;
1563 // To next/previous row
1565 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1567 tm.editXY(*this, xo, yo + textRow().descent() + 1);
1570 // This happens when you move out of an inset.
1571 // And to give the DEPM the possibility of doing
1572 // something we must provide it with two different
1574 Cursor dummy = *this;
1577 if (bv().checkDepm(dummy, old)) {
1578 updateNeeded = true;
1579 // Make sure that cur gets back whatever happened to dummy(Lgb)
1583 // if there is a selection, we stay out of any inset, and just jump to the right position:
1587 top().pos() = min(tm.x2pos(pit(), row - 1, xo), top().lastpos());
1588 } else if (pit() > 0) {
1590 TextMetrics & tm = bv_->textMetrics(text());
1591 if (!tm.contains(pit()))
1592 tm.newParMetricsUp();
1593 ParagraphMetrics const & pmcur = tm.parMetrics(pit());
1594 top().pos() = min(tm.x2pos(pit(), pmcur.rows().size() - 1, xo), top().lastpos());
1597 if (row + 1 < int(pm.rows().size())) {
1598 top().pos() = min(tm.x2pos(pit(), row + 1, xo), top().lastpos());
1599 } else if (pit() + 1 < int(text()->paragraphs().size())) {
1601 TextMetrics & tm = bv_->textMetrics(text());
1602 if (!tm.contains(pit()))
1603 tm.newParMetricsDown();
1604 top().pos() = min(tm.x2pos(pit(), 0, xo), top().lastpos());
1608 updateNeeded |= bv().checkDepm(*this, old);
1611 updateTextTargetOffset();
1616 void Cursor::handleFont(string const & font)
1618 LYXERR(Debug::DEBUG, font);
1622 safe = cap::grabAndEraseSelection(*this);
1625 if (lastpos() != 0) {
1626 // something left in the cell
1628 // cursor in first position
1630 } else if (pos() == lastpos()) {
1631 // cursor in last position
1634 // cursor in between. split cell
1635 MathData::iterator bt = cell().begin();
1636 MathAtom at = createInsetMath(from_utf8(font));
1637 at.nucleus()->cell(0) = MathData(bt, bt + pos());
1638 cell().erase(bt, bt + pos());
1643 // nothing left in the cell
1651 void Cursor::message(docstring const & msg) const
1653 theLyXFunc().setMessage(msg);
1657 void Cursor::errorMessage(docstring const & msg) const
1659 theLyXFunc().setErrorMessage(msg);
1663 docstring Cursor::selectionAsString(bool label) const
1669 ParagraphList const & pars = text()->paragraphs();
1671 // should be const ...
1672 pit_type startpit = selBegin().pit();
1673 pit_type endpit = selEnd().pit();
1674 size_t const startpos = selBegin().pos();
1675 size_t const endpos = selEnd().pos();
1677 if (startpit == endpit)
1678 return pars[startpit].asString(startpos, endpos, label);
1680 // First paragraph in selection
1681 docstring result = pars[startpit].
1682 asString(startpos, pars[startpit].size(), label)
1683 + parbreak(pars[startpit]);
1685 // The paragraphs in between (if any)
1686 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1687 Paragraph const & par = pars[pit];
1688 result += par.asString(0, par.size(), label)
1689 + parbreak(pars[pit]);
1692 // Last paragraph in selection
1693 result += pars[endpit].asString(0, endpos, label);
1699 return cap::grabSelection(*this);
1705 docstring Cursor::currentState()
1708 odocstringstream os;
1714 return text()->currentState(*this);
1720 docstring Cursor::getPossibleLabel()
1722 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
1726 Encoding const * Cursor::getEncoding() const
1730 CursorSlice const & sl = innerTextSlice();
1731 Text const & text = *sl.text();
1732 Font font = text.getPar(sl.pit()).getFont(
1733 bv().buffer().params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1734 return font.language()->encoding();
1738 void Cursor::undispatched()
1740 disp_.dispatched(false);
1744 void Cursor::dispatched()
1746 disp_.dispatched(true);
1750 void Cursor::updateFlags(Update::flags f)
1756 void Cursor::noUpdate()
1758 disp_.update(Update::None);
1762 Font Cursor::getFont() const
1764 // The logic here should more or less match to the Cursor::setCurrentFont
1765 // logic, i.e. the cursor height should give a hint what will happen
1766 // if a character is entered.
1768 // HACK. far from being perfect...
1770 CursorSlice const & sl = innerTextSlice();
1771 Text const & text = *sl.text();
1772 Paragraph const & par = text.getPar(sl.pit());
1774 // on boundary, so we are really at the character before
1775 pos_type pos = sl.pos();
1776 if (pos > 0 && boundary())
1779 // on space? Take the font before (only for RTL boundary stay)
1781 TextMetrics const & tm = bv().textMetrics(&text);
1782 if (pos == sl.lastpos()
1783 || (par.isSeparator(pos)
1784 && !tm.isRTLBoundary(sl.pit(), pos)))
1788 // get font at the position
1789 Font font = par.getFont(bv().buffer().params(), pos,
1790 outerFont(sl.pit(), text.paragraphs()));
1796 bool Cursor::fixIfBroken()
1798 if (DocIterator::fixIfBroken()) {
1807 bool notifyCursorLeaves(Cursor const & old, Cursor & cur)
1809 // find inset in common
1811 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
1812 if (&old[i].inset() != &cur[i].inset())
1816 // update words if we just moved to another paragraph
1817 if (i == old.depth() && i == cur.depth()
1818 && !cur.buffer().isClean()
1819 && cur.inTexted() && old.inTexted()
1820 && cur.pit() != old.pit()) {
1821 old.paragraph().updateWords(old.top());
1825 // notify everything on top of the common part in old cursor,
1826 // but stop if the inset claims the cursor to be invalid now
1827 for (; i < old.depth(); ++i) {
1828 Cursor insetPos = old;
1830 if (old[i].inset().notifyCursorLeaves(insetPos, cur))
1838 void Cursor::setCurrentFont()
1840 CursorSlice const & cs = innerTextSlice();
1841 Paragraph const & par = cs.paragraph();
1842 pos_type cpit = cs.pit();
1843 pos_type cpos = cs.pos();
1844 Text const & ctext = *cs.text();
1845 TextMetrics const & tm = bv().textMetrics(&ctext);
1847 // are we behind previous char in fact? -> go to that char
1848 if (cpos > 0 && boundary())
1851 // find position to take the font from
1853 // paragraph end? -> font of last char
1854 if (cpos == lastpos())
1856 // on space? -> look at the words in front of space
1857 else if (cpos > 0 && par.isSeparator(cpos)) {
1858 // abc| def -> font of c
1859 // abc |[WERBEH], i.e. boundary==true -> font of c
1860 // abc [WERBEH]| def, font of the space
1861 if (!tm.isRTLBoundary(cpit, cpos))
1867 BufferParams const & bufparams = buffer().params();
1868 current_font = par.getFontSettings(bufparams, cpos);
1869 real_current_font = tm.displayFont(cpit, cpos);
1871 // special case for paragraph end
1872 if (cs.pos() == lastpos()
1873 && tm.isRTLBoundary(cpit, cs.pos())
1875 Language const * lang = par.getParLanguage(bufparams);
1876 current_font.setLanguage(lang);
1877 current_font.fontInfo().setNumber(FONT_OFF);
1878 real_current_font.setLanguage(lang);
1879 real_current_font.fontInfo().setNumber(FONT_OFF);
1884 bool Cursor::textUndo()
1886 DocIterator dit = *this;
1887 // Undo::textUndo() will modify dit.
1888 if (!bv_->buffer().undo().textUndo(dit))
1892 selection() = false;
1899 bool Cursor::textRedo()
1901 DocIterator dit = *this;
1902 // Undo::textRedo() will modify dit.
1903 if (!bv_->buffer().undo().textRedo(dit))
1907 selection() = false;
1914 void Cursor::finishUndo()
1916 bv_->buffer().undo().finishUndo();
1920 void Cursor::recordUndo(UndoKind kind, pit_type from, pit_type to)
1922 bv_->buffer().undo().recordUndo(*this, kind, from, to);
1926 void Cursor::recordUndo(UndoKind kind, pit_type from)
1928 bv_->buffer().undo().recordUndo(*this, kind, from);
1932 void Cursor::recordUndo(UndoKind kind)
1934 bv_->buffer().undo().recordUndo(*this, kind);
1938 void Cursor::recordUndoInset(UndoKind kind)
1940 bv_->buffer().undo().recordUndoInset(*this, kind);
1944 void Cursor::recordUndoFullDocument()
1946 bv_->buffer().undo().recordUndoFullDocument(*this);
1950 void Cursor::recordUndoSelection()
1952 bv_->buffer().undo().recordUndo(*this, ATOMIC_UNDO,
1953 selBegin().pit(), selEnd().pit());
1957 void Cursor::checkBufferStructure()
1959 if (paragraph().layout().toclevel == Layout::NOT_IN_TOC)
1961 Buffer const * master = buffer().masterBuffer();
1962 master->tocBackend().updateItem(ParConstIterator(*this));
1963 master->structureChanged();