3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alejandro Aguilar Sierra
7 * \author Alfredo Braunstein
8 * \author Dov Feldstern
10 * \author Stefan Schimanski
12 * Full author contact details are available in file CREDITS.
19 #include "BufferView.h"
20 #include "CoordCache.h"
22 #include "CutAndPaste.h"
23 #include "DispatchResult.h"
27 #include "FuncRequest.h"
29 #include "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/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 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 LASSERT(pos() <= lastpos(), /**/);
308 LASSERT(idx() <= lastidx(), /**/);
309 LASSERT(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 LASSERT(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 LASSERT(!empty(), /**/);
373 //lyxerr << "Entering inset " << t << " front" << endl;
379 bool Cursor::popBackward()
381 LASSERT(!empty(), /**/);
389 bool Cursor::popForward()
391 LASSERT(!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 LASSERT(!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 LASSERT(!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 // Inside a table, determining whether to move to the next or previous row
572 // should be done based on the table's direction.
574 if (s >= 1 && (*this)[s].inset().asInsetTabular()) {
575 par_is_LTR = !(*this)[s].inset().asInsetTabular()->isRightToLeft(*this);
576 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
579 // if moving left in an LTR paragraph or moving right in an RTL one,
580 // move to previous row
581 if (par_is_LTR == movingLeft) {
582 if (row.pos() == 0) { // we're at first row in paragraph
583 if (pit() == 0) // no previous paragraph! don't move
585 // move to last pos in previous par
589 } else { // move to previous row in this par
590 pos() = row.pos() - 1; // this is guaranteed to be in previous row
594 // if moving left in an RTL paragraph or moving right in an LTR one,
597 if (row.endpos() == lastpos()) { // we're at last row in paragraph
598 if (pit() == lastpit()) // last paragraph! don't move
600 // move to first row in next par
604 } else { // move to next row in this par
605 pos() = row.endpos();
610 // make sure we're at left-/right-most pos in new row
611 posVisToRowExtremity(!movingLeft);
617 void Cursor::posVisToRowExtremity(bool left)
619 // prepare bidi tables
620 Paragraph const & par = paragraph();
621 Buffer const & buf = buffer();
622 Row const & row = textRow();
624 bidi.computeTables(par, buf, row);
626 LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
627 << (boundary() ? 1 : 0));
629 if (left) { // move to leftmost position
630 // if this is an RTL paragraph, and we're at the last row in the
631 // paragraph, move to lastpos
632 if (par.isRTL(buf.params()) && row.endpos() == lastpos())
635 pos() = bidi.vis2log(row.pos());
637 // Moving to the leftmost position in the row, the cursor should
638 // normally be placed to the *left* of the leftmost position.
639 // A very common exception, though, is if the leftmost character
640 // also happens to be the separator at the (logical) end of the row
641 // --- in this case, the separator is positioned beyond the left
642 // margin, and we don't want to move the cursor there (moving to
643 // the left of the separator is equivalent to moving to the next
644 // line). So, in this case we actually want to place the cursor
645 // to the *right* of the leftmost position (the separator).
646 // Another exception is if we're moving to the logically last
647 // position in the row, which is *not* a separator: this means
648 // that the entire row has no separators (if there were any, the
649 // row would have been broken there); and therefore in this case
650 // we also move to the *right* of the last position (this indicates
651 // to the user that there is no space after this position, and is
652 // consistent with the behavior in the middle of a row --- moving
653 // right or left moves to the next/previous character; if we were
654 // to move to the *left* of this position, that would simulate
655 // a separator which is not really there!).
656 // Finally, there is an exception to the previous exception: if
657 // this non-separator-but-last-position-in-row is an inset, then
658 // we *do* want to stay to the left of it anyway: this is the
659 // "boundary" which we simulate at insets.
661 bool right_of_pos = false; // do we want to be to the right of pos?
663 // as explained above, if at last pos in row, stay to the right
664 if ((pos() == row.endpos() - 1) && !par.isInset(pos()))
667 // Now we know if we want to be to the left or to the right of pos,
668 // let's make sure we are where we want to be.
669 bool new_pos_is_RTL =
670 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
672 if (new_pos_is_RTL == !right_of_pos) {
679 else { // move to rightmost position
680 // if this is an LTR paragraph, and we're at the last row in the
681 // paragraph, move to lastpos
682 if (!par.isRTL(buf.params()) && row.endpos() == lastpos())
685 pos() = bidi.vis2log(row.endpos() - 1);
687 // Moving to the rightmost position in the row, the cursor should
688 // normally be placed to the *right* of the rightmost position.
689 // A very common exception, though, is if the rightmost character
690 // also happens to be the separator at the (logical) end of the row
691 // --- in this case, the separator is positioned beyond the right
692 // margin, and we don't want to move the cursor there (moving to
693 // the right of the separator is equivalent to moving to the next
694 // line). So, in this case we actually want to place the cursor
695 // to the *left* of the rightmost position (the separator).
696 // Another exception is if we're moving to the logically last
697 // position in the row, which is *not* a separator: this means
698 // that the entire row has no separators (if there were any, the
699 // row would have been broken there); and therefore in this case
700 // we also move to the *left* of the last position (this indicates
701 // to the user that there is no space after this position, and is
702 // consistent with the behavior in the middle of a row --- moving
703 // right or left moves to the next/previous character; if we were
704 // to move to the *right* of this position, that would simulate
705 // a separator which is not really there!).
706 // Finally, there is an exception to the previous exception: if
707 // this non-separator-but-last-position-in-row is an inset, then
708 // we *do* want to stay to the right of it anyway: this is the
709 // "boundary" which we simulate at insets.
711 bool left_of_pos = false; // do we want to be to the left of pos?
713 // as explained above, if at last pos in row, stay to the left
714 if ((pos() == row.endpos() - 1) && !par.isInset(pos()))
717 // Now we know if we want to be to the left or to the right of pos,
718 // let's make sure we are where we want to be.
719 bool new_pos_is_RTL =
720 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
722 if (new_pos_is_RTL == left_of_pos) {
728 LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
729 << (boundary() ? 1 : 0));
733 CursorSlice Cursor::anchor() const
735 LASSERT(anchor_.depth() >= depth(), /**/);
736 CursorSlice normal = anchor_[depth() - 1];
737 if (depth() < anchor_.depth() && top() <= normal) {
738 // anchor is behind cursor -> move anchor behind the inset
745 CursorSlice Cursor::selBegin() const
749 return anchor() < top() ? anchor() : top();
753 CursorSlice Cursor::selEnd() const
757 return anchor() > top() ? anchor() : top();
761 DocIterator Cursor::selectionBegin() const
765 DocIterator di = (anchor() < top() ? anchor_ : *this);
771 DocIterator Cursor::selectionEnd() const
775 DocIterator di = (anchor() > top() ? anchor_ : *this);
776 if (di.depth() > depth()) {
784 void Cursor::setSelection()
787 // A selection with no contents is not a selection
788 // FIXME: doesnt look ok
789 if (pit() == anchor().pit() && pos() == anchor().pos())
794 void Cursor::setSelection(DocIterator const & where, int n)
803 void Cursor::clearSelection()
811 void Cursor::setTargetX(int x)
814 textTargetOffset_ = 0;
818 int Cursor::x_target() const
824 void Cursor::clearTargetX()
827 textTargetOffset_ = 0;
831 void Cursor::updateTextTargetOffset()
836 textTargetOffset_ = x - x_target_;
840 void Cursor::info(odocstream & os) const
842 for (int i = 1, n = depth(); i < n; ++i) {
843 operator[](i).inset().infoize(os);
847 Inset const * inset = prevInset();
848 // prevInset() can return 0 in certain case.
850 prevInset()->infoize2(os);
852 // overwite old message
857 bool Cursor::selHandle(bool sel)
859 //lyxerr << "Cursor::selHandle" << endl;
862 if (sel == selection())
866 cap::saveSelection(*this);
874 ostream & operator<<(ostream & os, Cursor const & cur)
876 os << "\n cursor: | anchor:\n";
877 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
878 os << " " << cur[i] << " | ";
879 if (i < cur.anchor_.depth())
880 os << cur.anchor_[i];
882 os << "-------------------------------";
885 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
886 os << "------------------------------- | " << cur.anchor_[i] << "\n";
888 os << " selection: " << cur.selection_
889 << " x_target: " << cur.x_target_ << endl;
894 LyXErr & operator<<(LyXErr & os, Cursor const & cur)
904 ///////////////////////////////////////////////////////////////////
907 // The part below is the non-integrated rest of the original math
908 // cursor. This should be either generalized for texted or moved
909 // back to mathed (in most cases to InsetMathNest).
911 ///////////////////////////////////////////////////////////////////
913 #include "mathed/InsetMathChar.h"
914 #include "mathed/InsetMathGrid.h"
915 #include "mathed/InsetMathScript.h"
916 #include "mathed/InsetMathUnknown.h"
917 #include "mathed/MathFactory.h"
918 #include "mathed/MathStream.h"
919 #include "mathed/MathSupport.h"
924 //#define FILEDEBUG 1
927 bool Cursor::isInside(Inset const * p) const
929 for (size_t i = 0; i != depth(); ++i)
930 if (&operator[](i).inset() == p)
936 void Cursor::leaveInset(Inset const & inset)
938 for (size_t i = 0; i != depth(); ++i) {
939 if (&operator[](i).inset() == &inset) {
947 bool Cursor::openable(MathAtom const & t) const
958 // we can't move into anything new during selection
959 if (depth() >= anchor_.depth())
961 if (t.nucleus() != &anchor_[depth()].inset())
968 void Cursor::setScreenPos(int x, int /*y*/)
971 //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
976 void Cursor::plainErase()
982 void Cursor::markInsert()
984 insert(char_type(0));
988 void Cursor::markErase()
994 void Cursor::plainInsert(MathAtom const & t)
996 cell().insert(pos(), t);
998 inset().setBuffer(bv_->buffer());
1003 void Cursor::insert(docstring const & str)
1005 for_each(str.begin(), str.end(),
1006 boost::bind(static_cast<void(Cursor::*)(char_type)>
1007 (&Cursor::insert), this, _1));
1011 void Cursor::insert(char_type c)
1013 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1014 LASSERT(!empty(), /**/);
1016 cap::selClearOrDel(*this);
1017 insert(new InsetMathChar(c));
1019 text()->insertChar(*this, c);
1024 void Cursor::insert(MathAtom const & t)
1026 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1028 cap::selClearOrDel(*this);
1033 void Cursor::insert(Inset * inset0)
1035 LASSERT(inset0, /**/);
1037 insert(MathAtom(inset0));
1039 text()->insertInset(*this, inset0);
1040 inset0->setBuffer(bv_->buffer());
1046 void Cursor::niceInsert(docstring const & t)
1057 void Cursor::niceInsert(MathAtom const & t)
1060 docstring const safe = cap::grabAndEraseSelection(*this);
1062 // enter the new inset and move the contents of the selection if possible
1063 if (t->isActive()) {
1065 // be careful here: don't use 'pushBackward(t)' as this we need to
1066 // push the clone, not the original
1067 pushBackward(*nextInset());
1068 // We may not use niceInsert here (recursion)
1076 void Cursor::insert(MathData const & ar)
1080 cap::eraseSelection(*this);
1081 cell().insert(pos(), ar);
1086 bool Cursor::backspace()
1088 autocorrect() = false;
1091 cap::eraseSelection(*this);
1096 // If empty cell, and not part of a big cell
1097 if (lastpos() == 0 && inset().nargs() == 1) {
1099 // Directly delete empty cell: [|[]] => [|]
1105 // [|], can not delete from inside
1116 if (inMacroMode()) {
1117 InsetMathUnknown * p = activeMacro();
1118 if (p->name().size() > 1) {
1119 p->setName(p->name().substr(0, p->name().size() - 1));
1124 if (pos() != 0 && prevAtom()->nargs() > 0) {
1125 // let's require two backspaces for 'big stuff' and
1126 // highlight on the first
1138 bool Cursor::erase()
1140 autocorrect() = false;
1145 cap::eraseSelection(*this);
1149 // delete empty cells if possible
1150 if (pos() == lastpos() && inset().idxDelete(idx()))
1153 // special behaviour when in last position of cell
1154 if (pos() == lastpos()) {
1155 bool one_cell = inset().nargs() == 1;
1156 if (one_cell && lastpos() == 0) {
1158 // Directly delete empty cell: [|[]] => [|]
1164 // [|], can not delete from inside
1169 inset().idxGlue(idx());
1173 // 'clever' UI hack: only erase large items if previously slected
1174 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
1189 DocIterator save = *this;
1190 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1191 this->dispatch(cmd);
1192 if (disp_.dispatched())
1195 autocorrect() = false;
1203 DocIterator save = *this;
1204 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1205 this->dispatch(cmd);
1206 if (disp_.dispatched())
1209 autocorrect() = false;
1214 bool Cursor::macroModeClose()
1218 InsetMathUnknown * p = activeMacro();
1221 asArray(p->selection(), selection);
1222 docstring const s = p->name();
1224 cell().erase(pos());
1226 // do nothing if the macro name is empty
1230 // trigger updates of macros, at least, if no full
1231 // updates take place anyway
1232 updateFlags(Update::Force);
1234 docstring const name = s.substr(1);
1235 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1236 if (in && in->interpretString(*this, s))
1238 MathAtom atom = createInsetMath(name);
1240 // try to put argument into macro, if we just inserted a macro
1241 bool macroArg = false;
1242 MathMacro * atomAsMacro = atom.nucleus()->asMacro();
1244 // macros here are still unfolded (in init mode in fact). So
1245 // we have to resolve the macro here manually and check its arity
1246 // to put the selection behind it if arity > 0.
1247 MacroData const * data = buffer().getMacro(atomAsMacro->name());
1248 if (selection.size() > 0 && data && data->numargs() - data->optionals() > 0) {
1250 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1252 // non-greedy case. Do not touch the arguments behind
1253 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1256 // insert remembered selection into first argument of a non-macro
1257 else if (atom.nucleus()->nargs() > 0)
1258 atom.nucleus()->cell(0).append(selection);
1262 // finally put the macro argument behind, if needed
1264 if (selection.size() > 1)
1265 plainInsert(MathAtom(new InsetMathBrace(selection)));
1274 docstring Cursor::macroName()
1276 return inMacroMode() ? activeMacro()->name() : docstring();
1280 void Cursor::handleNest(MathAtom const & a, int c)
1282 //lyxerr << "Cursor::handleNest: " << c << endl;
1284 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1287 pushBackward(*nextInset());
1291 int Cursor::targetX() const
1293 if (x_target() != -1)
1302 int Cursor::textTargetOffset() const
1304 return textTargetOffset_;
1308 void Cursor::setTargetX()
1317 bool Cursor::inMacroMode() const
1323 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1324 return p && !p->final();
1328 InsetMathUnknown * Cursor::activeMacro()
1330 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1334 InsetMathUnknown const * Cursor::activeMacro() const
1336 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1340 void Cursor::pullArg()
1343 MathData ar = cell();
1344 if (popBackward() && inMathed()) {
1346 cell().insert(pos(), ar);
1349 //formula()->mutateToText();
1354 void Cursor::touch()
1358 DocIterator::const_iterator it = begin();
1359 DocIterator::const_iterator et = end();
1360 for ( ; it != et; ++it)
1366 void Cursor::normalize()
1368 if (idx() > lastidx()) {
1369 lyxerr << "this should not really happen - 1: "
1370 << idx() << ' ' << nargs()
1371 << " in: " << &inset() << endl;
1375 if (pos() > lastpos()) {
1376 lyxerr << "this should not really happen - 2: "
1377 << pos() << ' ' << lastpos() << " in idx: " << idx()
1379 odocstringstream os;
1380 WriteStream wi(os, false, true);
1381 inset().asInsetMath()->write(wi);
1382 lyxerr << to_utf8(os.str()) << endl;
1388 bool Cursor::upDownInMath(bool up)
1390 // Be warned: The 'logic' implemented in this function is highly
1391 // fragile. A distance of one pixel or a '<' vs '<=' _really
1392 // matters. So fiddle around with it only if you think you know
1393 // what you are doing!
1397 xo = theLyXFunc().cursorBeforeDispatchX();
1399 // check if we had something else in mind, if not, this is the future
1401 if (x_target_ == -1)
1403 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1404 // In text mode inside the line (not left or right) possibly set a new target_x,
1405 // but only if we are somewhere else than the previous target-offset.
1407 // We want to keep the x-target on subsequent up/down movements
1408 // that cross beyond the end of short lines. Thus a special
1409 // handling when the cursor is at the end of line: Use the new
1410 // x-target only if the old one was before the end of line
1411 // or the old one was after the beginning of the line
1412 bool inRTL = isWithinRtlParagraph(*this);
1416 left = pos() == textRow().endpos();
1417 right = pos() == textRow().pos();
1419 left = pos() == textRow().pos();
1420 right = pos() == textRow().endpos();
1422 if ((!left && !right) ||
1423 (left && !right && xo < x_target_) ||
1424 (!left && right && x_target_ < xo))
1431 // try neigbouring script insets
1433 if (inMathed() && !selection()) {
1436 InsetMathScript const * p = prevAtom()->asScriptInset();
1437 if (p && p->has(up)) {
1439 push(*const_cast<InsetMathScript*>(p));
1440 idx() = p->idxOfScript(up);
1443 // we went in the right direction? Otherwise don't jump into the script
1447 int oy = theLyXFunc().cursorBeforeDispatchY();
1448 if ((!up && y <= oy) ||
1457 if (pos() != lastpos()) {
1458 InsetMathScript const * p = nextAtom()->asScriptInset();
1459 if (p && p->has(up)) {
1460 push(*const_cast<InsetMathScript*>(p));
1461 idx() = p->idxOfScript(up);
1464 // we went in the right direction? Otherwise don't jump into the script
1468 int oy = theLyXFunc().cursorBeforeDispatchY();
1469 if ((!up && y <= oy) ||
1478 // try to find an inset that knows better then we,
1479 if (inset().idxUpDown(*this, up)) {
1480 //lyxerr << "idxUpDown triggered" << endl;
1481 // try to find best position within this inset
1483 setCursor(bruteFind2(*this, xo, yo));
1487 // any improvement going just out of inset?
1488 if (popBackward() && inMathed()) {
1489 //lyxerr << "updown: popBackward succeeded" << endl;
1492 int yold = theLyXFunc().cursorBeforeDispatchY();
1494 if (up ? ynew < yold : ynew > yold)
1498 // no success, we are probably at the document top or bottom
1504 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1506 LASSERT(text(), /**/);
1512 xo = theLyXFunc().cursorBeforeDispatchX();
1514 // update the targetX - this is here before the "return false"
1515 // to set a new target which can be used by InsetTexts above
1516 // if we cannot move up/down inside this inset anymore
1517 if (x_target_ == -1)
1519 else if (xo - textTargetOffset() != x_target() &&
1520 depth() == beforeDispatchCursor_.depth()) {
1521 // In text mode inside the line (not left or right) possibly set a new target_x,
1522 // but only if we are somewhere else than the previous target-offset.
1524 // We want to keep the x-target on subsequent up/down movements
1525 // that cross beyond the end of short lines. Thus a special
1526 // handling when the cursor is at the end of line: Use the new
1527 // x-target only if the old one was before the end of line
1528 // or the old one was after the beginning of the line
1529 bool inRTL = isWithinRtlParagraph(*this);
1533 left = pos() == textRow().endpos();
1534 right = pos() == textRow().pos();
1536 left = pos() == textRow().pos();
1537 right = pos() == textRow().endpos();
1539 if ((!left && !right) ||
1540 (left && !right && xo < x_target_) ||
1541 (!left && right && x_target_ < xo))
1548 // first get the current line
1549 TextMetrics & tm = bv_->textMetrics(text());
1550 ParagraphMetrics const & pm = tm.parMetrics(pit());
1552 if (pos() && boundary())
1553 row = pm.pos2row(pos() - 1);
1555 row = pm.pos2row(pos());
1557 // are we not at the start or end?
1559 if (pit() == 0 && row == 0)
1562 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1563 row + 1 >= int(pm.rows().size()))
1567 // with and without selection are handled differently
1569 int yo = bv().getPos(*this, boundary()).y_;
1571 // To next/previous row
1573 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1575 tm.editXY(*this, xo, yo + textRow().descent() + 1);
1578 // This happens when you move out of an inset.
1579 // And to give the DEPM the possibility of doing
1580 // something we must provide it with two different
1582 Cursor dummy = *this;
1585 if (bv().checkDepm(dummy, old)) {
1586 updateNeeded = true;
1587 // Make sure that cur gets back whatever happened to dummy(Lgb)
1591 // if there is a selection, we stay out of any inset, and just jump to the right position:
1595 top().pos() = min(tm.x2pos(pit(), row - 1, xo), top().lastpos());
1596 } else if (pit() > 0) {
1598 TextMetrics & tm = bv_->textMetrics(text());
1599 if (!tm.contains(pit()))
1600 tm.newParMetricsUp();
1601 ParagraphMetrics const & pmcur = tm.parMetrics(pit());
1602 top().pos() = min(tm.x2pos(pit(), pmcur.rows().size() - 1, xo), top().lastpos());
1605 if (row + 1 < int(pm.rows().size())) {
1606 top().pos() = min(tm.x2pos(pit(), row + 1, xo), top().lastpos());
1607 } else if (pit() + 1 < int(text()->paragraphs().size())) {
1609 TextMetrics & tm = bv_->textMetrics(text());
1610 if (!tm.contains(pit()))
1611 tm.newParMetricsDown();
1612 top().pos() = min(tm.x2pos(pit(), 0, xo), top().lastpos());
1616 updateNeeded |= bv().checkDepm(*this, old);
1619 updateTextTargetOffset();
1624 void Cursor::handleFont(string const & font)
1626 LYXERR(Debug::DEBUG, font);
1630 safe = cap::grabAndEraseSelection(*this);
1633 if (lastpos() != 0) {
1634 // something left in the cell
1636 // cursor in first position
1638 } else if (pos() == lastpos()) {
1639 // cursor in last position
1642 // cursor in between. split cell
1643 MathData::iterator bt = cell().begin();
1644 MathAtom at = createInsetMath(from_utf8(font));
1645 at.nucleus()->cell(0) = MathData(bt, bt + pos());
1646 cell().erase(bt, bt + pos());
1651 // nothing left in the cell
1659 void Cursor::message(docstring const & msg) const
1661 theLyXFunc().setMessage(msg);
1665 void Cursor::errorMessage(docstring const & msg) const
1667 theLyXFunc().setErrorMessage(msg);
1671 docstring Cursor::selectionAsString(bool label) const
1677 ParagraphList const & pars = text()->paragraphs();
1679 // should be const ...
1680 pit_type startpit = selBegin().pit();
1681 pit_type endpit = selEnd().pit();
1682 size_t const startpos = selBegin().pos();
1683 size_t const endpos = selEnd().pos();
1685 if (startpit == endpit)
1686 return pars[startpit].asString(startpos, endpos, label);
1688 // First paragraph in selection
1689 docstring result = pars[startpit].
1690 asString(startpos, pars[startpit].size(), label)
1691 + parbreak(pars[startpit]);
1693 // The paragraphs in between (if any)
1694 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1695 Paragraph const & par = pars[pit];
1696 result += par.asString(0, par.size(), label)
1697 + parbreak(pars[pit]);
1700 // Last paragraph in selection
1701 result += pars[endpit].asString(0, endpos, label);
1707 return cap::grabSelection(*this);
1713 docstring Cursor::currentState()
1716 odocstringstream os;
1722 return text()->currentState(*this);
1728 docstring Cursor::getPossibleLabel()
1730 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
1734 Encoding const * Cursor::getEncoding() const
1738 CursorSlice const & sl = innerTextSlice();
1739 Text const & text = *sl.text();
1740 Font font = text.getPar(sl.pit()).getFont(
1741 bv().buffer().params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1742 return font.language()->encoding();
1746 void Cursor::undispatched()
1748 disp_.dispatched(false);
1752 void Cursor::dispatched()
1754 disp_.dispatched(true);
1758 void Cursor::updateFlags(Update::flags f)
1764 void Cursor::noUpdate()
1766 disp_.update(Update::None);
1770 Font Cursor::getFont() const
1772 // The logic here should more or less match to the Cursor::setCurrentFont
1773 // logic, i.e. the cursor height should give a hint what will happen
1774 // if a character is entered.
1776 // HACK. far from being perfect...
1778 CursorSlice const & sl = innerTextSlice();
1779 Text const & text = *sl.text();
1780 Paragraph const & par = text.getPar(sl.pit());
1782 // on boundary, so we are really at the character before
1783 pos_type pos = sl.pos();
1784 if (pos > 0 && boundary())
1787 // on space? Take the font before (only for RTL boundary stay)
1789 TextMetrics const & tm = bv().textMetrics(&text);
1790 if (pos == sl.lastpos()
1791 || (par.isSeparator(pos)
1792 && !tm.isRTLBoundary(sl.pit(), pos)))
1796 // get font at the position
1797 Font font = par.getFont(bv().buffer().params(), pos,
1798 outerFont(sl.pit(), text.paragraphs()));
1804 bool Cursor::fixIfBroken()
1806 if (DocIterator::fixIfBroken()) {
1815 bool notifyCursorLeaves(Cursor const & old, Cursor & cur)
1817 // find inset in common
1819 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
1820 if (&old[i].inset() != &cur[i].inset())
1824 // update words if we just moved to another paragraph
1825 if (i == old.depth() && i == cur.depth()
1826 && !cur.buffer().isClean()
1827 && cur.inTexted() && old.inTexted()
1828 && cur.pit() != old.pit()) {
1829 old.paragraph().updateWords(old.top());
1833 // notify everything on top of the common part in old cursor,
1834 // but stop if the inset claims the cursor to be invalid now
1835 for (; i < old.depth(); ++i) {
1836 Cursor insetPos = old;
1838 if (old[i].inset().notifyCursorLeaves(insetPos, cur))
1846 void Cursor::setCurrentFont()
1848 CursorSlice const & cs = innerTextSlice();
1849 Paragraph const & par = cs.paragraph();
1850 pos_type cpit = cs.pit();
1851 pos_type cpos = cs.pos();
1852 Text const & ctext = *cs.text();
1853 TextMetrics const & tm = bv().textMetrics(&ctext);
1855 // are we behind previous char in fact? -> go to that char
1856 if (cpos > 0 && boundary())
1859 // find position to take the font from
1861 // paragraph end? -> font of last char
1862 if (cpos == lastpos())
1864 // on space? -> look at the words in front of space
1865 else if (cpos > 0 && par.isSeparator(cpos)) {
1866 // abc| def -> font of c
1867 // abc |[WERBEH], i.e. boundary==true -> font of c
1868 // abc [WERBEH]| def, font of the space
1869 if (!tm.isRTLBoundary(cpit, cpos))
1875 BufferParams const & bufparams = buffer().params();
1876 current_font = par.getFontSettings(bufparams, cpos);
1877 real_current_font = tm.displayFont(cpit, cpos);
1879 // special case for paragraph end
1880 if (cs.pos() == lastpos()
1881 && tm.isRTLBoundary(cpit, cs.pos())
1883 Language const * lang = par.getParLanguage(bufparams);
1884 current_font.setLanguage(lang);
1885 current_font.fontInfo().setNumber(FONT_OFF);
1886 real_current_font.setLanguage(lang);
1887 real_current_font.fontInfo().setNumber(FONT_OFF);
1892 bool Cursor::textUndo()
1894 DocIterator dit = *this;
1895 // Undo::textUndo() will modify dit.
1896 if (!bv_->buffer().undo().textUndo(dit))
1900 selection() = false;
1907 bool Cursor::textRedo()
1909 DocIterator dit = *this;
1910 // Undo::textRedo() will modify dit.
1911 if (!bv_->buffer().undo().textRedo(dit))
1915 selection() = false;
1922 void Cursor::finishUndo()
1924 bv_->buffer().undo().finishUndo();
1928 void Cursor::recordUndo(UndoKind kind, pit_type from, pit_type to)
1930 bv_->buffer().undo().recordUndo(*this, kind, from, to);
1934 void Cursor::recordUndo(UndoKind kind, pit_type from)
1936 bv_->buffer().undo().recordUndo(*this, kind, from);
1940 void Cursor::recordUndo(UndoKind kind)
1942 bv_->buffer().undo().recordUndo(*this, kind);
1946 void Cursor::recordUndoInset(UndoKind kind)
1948 bv_->buffer().undo().recordUndoInset(*this, kind);
1952 void Cursor::recordUndoFullDocument()
1954 bv_->buffer().undo().recordUndoFullDocument(*this);
1958 void Cursor::recordUndoSelection()
1961 if (cap::multipleCellsSelected(*this))
1966 bv_->buffer().undo().recordUndo(*this, ATOMIC_UNDO,
1967 selBegin().pit(), selEnd().pit());
1971 void Cursor::checkBufferStructure()
1973 if (paragraph().layout().toclevel == Layout::NOT_IN_TOC)
1975 Buffer const * master = buffer().masterBuffer();
1976 master->tocBackend().updateItem(ParConstIterator(*this));
1977 master->structureChanged();