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
9 * \author Stefan Schimanski
11 * Full author contact details are available in file CREDITS.
17 #include "BufferView.h"
20 #include "CoordCache.h"
21 #include "CutAndPaste.h"
23 #include "DispatchResult.h"
25 #include "FuncRequest.h"
29 #include "LyXFunc.h" // only for setMessage()
33 #include "Paragraph.h"
34 #include "paragraph_funcs.h"
35 #include "ParIterator.h"
36 #include "TextMetrics.h"
38 #include "support/docstream.h"
40 #include "insets/InsetTabular.h"
41 #include "insets/InsetText.h"
43 #include "mathed/InsetMath.h"
44 #include "mathed/InsetMathScript.h"
45 #include "mathed/MacroTable.h"
46 #include "mathed/MathData.h"
47 #include "mathed/MathMacro.h"
49 #include <boost/assert.hpp>
50 #include <boost/bind.hpp>
51 #include <boost/current_function.hpp>
69 positionable(DocIterator const & cursor, DocIterator const & anchor)
71 // avoid deeper nested insets when selecting
72 if (cursor.depth() > anchor.depth())
75 // anchor might be deeper, should have same path then
76 for (size_t i = 0; i < cursor.depth(); ++i)
77 if (&cursor[i].inset() != &anchor[i].inset())
80 // position should be ok.
85 // Find position closest to (x, y) in cell given by iter.
86 // Used only in mathed
87 DocIterator bruteFind2(Cursor const & c, int x, int y)
89 double best_dist = std::numeric_limits<double>::max();
96 et.top().pos() = et.top().asInsetMath()->cell(et.top().idx()).size();
97 for (size_t i = 0;; ++i) {
100 Inset const * inset = &it.inset();
101 std::map<Inset const *, Geometry> const & data =
102 c.bv().coordCache().getInsets().getData();
103 std::map<Inset const *, Geometry>::const_iterator I = data.find(inset);
105 // FIXME: in the case where the inset is not in the cache, this
106 // means that no part of it is visible on screen. In this case
107 // we don't do elaborate search and we just return the forwarded
108 // DocIterator at its beginning.
109 if (I == data.end()) {
114 Point o = I->second.pos;
115 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
116 // Convert to absolute
119 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
120 // '<=' in order to take the last possible position
121 // this is important for clicking behind \sum in e.g. '\sum_i a'
122 LYXERR(Debug::DEBUG) << "i: " << i << " d: " << d
123 << " best: " << best_dist << endl;
124 if (d <= best_dist) {
137 /// moves position closest to (x, y) in given box
138 bool bruteFind(Cursor & cursor,
139 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
141 BOOST_ASSERT(!cursor.empty());
142 Inset & inset = cursor[0].inset();
143 BufferView & bv = cursor.bv();
145 CoordCache::InnerParPosCache const & cache =
146 bv.coordCache().getParPos().find(cursor.bottom().text())->second;
147 // Get an iterator on the first paragraph in the cache
148 DocIterator it(inset);
149 it.push_back(CursorSlice(inset));
150 it.pit() = cache.begin()->first;
151 // Get an iterator after the last paragraph in the cache
152 DocIterator et(inset);
153 et.push_back(CursorSlice(inset));
154 et.pit() = boost::prior(cache.end())->first;
155 if (et.pit() >= et.lastpit())
156 et = doc_iterator_end(inset);
160 double best_dist = std::numeric_limits<double>::max();;
161 DocIterator best_cursor = et;
163 for ( ; it != et; it.forwardPos(true)) {
164 // avoid invalid nesting when selecting
165 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
166 Point p = bv.getPos(it, false);
169 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
170 double const dx = xo - x;
171 double const dy = yo - y;
172 double const d = dx * dx + dy * dy;
173 // '<=' in order to take the last possible position
174 // this is important for clicking behind \sum in e.g. '\sum_i a'
175 if (d <= best_dist) {
176 // lyxerr << "*" << endl;
184 if (best_cursor != et) {
185 cursor.setCursor(best_cursor);
194 /// moves position closest to (x, y) in given box
195 bool bruteFind3(Cursor & cur, int x, int y, bool up)
197 BufferView & bv = cur.bv();
198 int ylow = up ? 0 : y + 1;
199 int yhigh = up ? y - 1 : bv.workHeight();
201 int xhigh = bv.workWidth();
203 // FIXME: bit more work needed to get 'from' and 'to' right.
204 pit_type from = cur.bottom().pit();
205 //pit_type to = cur.bottom().pit();
206 //lyxerr << "Pit start: " << from << endl;
208 //lyxerr << "bruteFind3: x: " << x << " y: " << y
209 // << " xlow: " << xlow << " xhigh: " << xhigh
210 // << " ylow: " << ylow << " yhigh: " << yhigh
212 Inset & inset = bv.buffer().inset();
213 DocIterator it = doc_iterator_begin(inset);
215 DocIterator et = doc_iterator_end(inset);
217 double best_dist = std::numeric_limits<double>::max();
218 DocIterator best_cursor = et;
220 for ( ; it != et; it.forwardPos()) {
221 // avoid invalid nesting when selecting
222 if (bv.cursorStatus(it) == CUR_INSIDE
223 && (!cur.selection() || positionable(it, cur.anchor_))) {
224 Point p = bv.getPos(it, false);
227 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
228 double const dx = xo - x;
229 double const dy = yo - y;
230 double const d = dx * dx + dy * dy;
231 //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
232 // << " dx: " << dx << " dy: " << dy
233 // << " idx: " << it.idx() << " pos: " << it.pos()
236 // '<=' in order to take the last possible position
237 // this is important for clicking behind \sum in e.g. '\sum_i a'
238 if (d <= best_dist) {
239 //lyxerr << "*" << endl;
247 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
248 if (best_cursor == et)
250 cur.setCursor(best_cursor);
254 docstring parbreak(Paragraph const & par)
256 odocstringstream ods;
258 // only add blank line if we're not in an ERT or Listings inset
259 if (par.ownerCode() != ERT_CODE
260 && par.ownerCode() != LISTINGS_CODE)
268 // be careful: this is called from the bv's constructor, too, so
269 // bv functions are not yet available!
270 Cursor::Cursor(BufferView & bv)
271 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1), textTargetOffset_(0),
272 selection_(false), mark_(false), logicalpos_(false),
273 current_font(inherit_font)
277 void Cursor::reset(Inset & inset)
280 push_back(CursorSlice(inset));
281 anchor_ = DocIterator(inset);
288 // this (intentionally) does neither touch anchor nor selection status
289 void Cursor::setCursor(DocIterator const & cur)
291 DocIterator::operator=(cur);
295 void Cursor::dispatch(FuncRequest const & cmd0)
297 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
298 << " cmd: " << cmd0 << '\n'
304 FuncRequest cmd = cmd0;
307 // store some values to be used inside of the handlers
308 getPos(beforeDispX_, beforeDispY_);
309 beforeDispatchCursor_ = *this;
310 for (; depth(); pop()) {
311 LYXERR(Debug::DEBUG) << "Cursor::dispatch: cmd: "
312 << cmd0 << endl << *this << endl;
313 BOOST_ASSERT(pos() <= lastpos());
314 BOOST_ASSERT(idx() <= lastidx());
315 BOOST_ASSERT(pit() <= lastpit());
317 // The common case is 'LFUN handled, need update', so make the
318 // LFUN handler's life easier by assuming this as default value.
319 // The handler can reset the update and val flags if necessary.
320 disp_.update(Update::FitCursor | Update::Force);
321 disp_.dispatched(true);
322 inset().dispatch(*this, cmd);
323 if (disp_.dispatched())
327 // it completely to get a 'bomb early' behaviour in case this
328 // object will be used again.
329 if (!disp_.dispatched()) {
330 LYXERR(Debug::DEBUG) << "RESTORING OLD CURSOR!" << endl;
332 disp_.update(Update::None);
333 disp_.dispatched(false);
335 // restore the previous one because nested Cursor::dispatch calls
336 // are possible which would change it
337 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
342 DispatchResult Cursor::result() const
348 BufferView & Cursor::bv() const
355 Buffer & Cursor::buffer() const
358 return bv_->buffer();
364 BOOST_ASSERT(depth() >= 1);
369 void Cursor::push(Inset & p)
371 push_back(CursorSlice(p));
375 void Cursor::pushBackward(Inset & p)
377 BOOST_ASSERT(!empty());
378 //lyxerr << "Entering inset " << t << " front" << endl;
384 bool Cursor::popBackward()
386 BOOST_ASSERT(!empty());
387 //lyxerr << "Leaving inset from in front" << endl;
388 inset().notifyCursorLeaves(*this);
396 bool Cursor::popForward()
398 BOOST_ASSERT(!empty());
399 //lyxerr << "Leaving inset from in back" << endl;
400 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
401 inset().notifyCursorLeaves(*this);
405 pos() += lastpos() - lp + 1;
410 int Cursor::currentMode()
412 BOOST_ASSERT(!empty());
413 for (int i = depth() - 1; i >= 0; --i) {
414 int res = operator[](i).inset().currentMode();
415 if (res != Inset::UNDECIDED_MODE)
418 return Inset::TEXT_MODE;
422 void Cursor::getPos(int & x, int & y) const
424 Point p = bv().getPos(*this, boundary());
430 Row const & Cursor::textRow() const
432 ParagraphMetrics const & pm = bv().parMetrics(text(), pit());
433 BOOST_ASSERT(!pm.rows().empty());
434 return pm.getRow(pos(), boundary());
438 void Cursor::resetAnchor()
445 bool Cursor::posBackward()
454 bool Cursor::posForward()
456 if (pos() == lastpos())
463 CursorSlice Cursor::anchor() const
465 BOOST_ASSERT(anchor_.depth() >= depth());
466 CursorSlice normal = anchor_[depth() - 1];
467 if (depth() < anchor_.depth() && top() <= normal) {
468 // anchor is behind cursor -> move anchor behind the inset
475 CursorSlice Cursor::selBegin() const
479 return anchor() < top() ? anchor() : top();
483 CursorSlice Cursor::selEnd() const
487 return anchor() > top() ? anchor() : top();
491 DocIterator Cursor::selectionBegin() const
495 DocIterator di = (anchor() < top() ? anchor_ : *this);
501 DocIterator Cursor::selectionEnd() const
505 DocIterator di = (anchor() > top() ? anchor_ : *this);
506 if (di.depth() > depth()) {
514 void Cursor::setSelection()
517 // A selection with no contents is not a selection
518 // FIXME: doesnt look ok
519 if (pit() == anchor().pit() && pos() == anchor().pos())
524 void Cursor::setSelection(DocIterator const & where, int n)
533 void Cursor::clearSelection()
541 void Cursor::setTargetX(int x)
544 textTargetOffset_ = 0;
548 int Cursor::x_target() const
554 void Cursor::clearTargetX()
557 textTargetOffset_ = 0;
561 void Cursor::updateTextTargetOffset()
566 textTargetOffset_ = x - x_target_;
570 void Cursor::info(odocstream & os) const
572 for (int i = 1, n = depth(); i < n; ++i) {
573 operator[](i).inset().infoize(os);
577 Inset const * inset = prevInset();
578 // prevInset() can return 0 in certain case.
580 prevInset()->infoize2(os);
582 // overwite old message
587 bool Cursor::selHandle(bool sel)
589 //lyxerr << "Cursor::selHandle" << endl;
590 if (sel == selection())
594 cap::saveSelection(*this);
602 std::ostream & operator<<(std::ostream & os, Cursor const & cur)
604 os << "\n cursor: | anchor:\n";
605 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
606 os << " " << cur[i] << " | ";
607 if (i < cur.anchor_.depth())
608 os << cur.anchor_[i];
610 os << "-------------------------------";
613 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
614 os << "------------------------------- | " << cur.anchor_[i] << "\n";
616 os << " selection: " << cur.selection_
617 << " x_target: " << cur.x_target_ << endl;
624 ///////////////////////////////////////////////////////////////////
626 // The part below is the non-integrated rest of the original math
627 // cursor. This should be either generalized for texted or moved
628 // back to mathed (in most cases to InsetMathNest).
630 ///////////////////////////////////////////////////////////////////
632 #include "mathed/InsetMathChar.h"
633 #include "mathed/InsetMathGrid.h"
634 #include "mathed/InsetMathScript.h"
635 #include "mathed/InsetMathUnknown.h"
636 #include "mathed/MathFactory.h"
637 #include "mathed/MathStream.h"
638 #include "mathed/MathSupport.h"
643 //#define FILEDEBUG 1
646 bool Cursor::isInside(Inset const * p)
648 for (size_t i = 0; i != depth(); ++i)
649 if (&operator[](i).inset() == p)
655 void Cursor::leaveInset(Inset const & inset)
657 for (size_t i = 0; i != depth(); ++i) {
658 if (&operator[](i).inset() == &inset) {
666 bool Cursor::openable(MathAtom const & t) const
677 // we can't move into anything new during selection
678 if (depth() >= anchor_.depth())
680 if (t.nucleus() != &anchor_[depth()].inset())
687 void Cursor::setScreenPos(int x, int /*y*/)
690 //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
695 void Cursor::plainErase()
701 void Cursor::markInsert()
703 insert(char_type(0));
707 void Cursor::markErase()
713 void Cursor::plainInsert(MathAtom const & t)
715 cell().insert(pos(), t);
720 void Cursor::insert(docstring const & str)
722 for_each(str.begin(), str.end(),
723 boost::bind(static_cast<void(Cursor::*)(char_type)>
724 (&Cursor::insert), this, _1));
728 void Cursor::insert(char_type c)
730 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
731 BOOST_ASSERT(!empty());
733 cap::selClearOrDel(*this);
734 insert(new InsetMathChar(c));
736 text()->insertChar(*this, c);
741 void Cursor::insert(MathAtom const & t)
743 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
745 cap::selClearOrDel(*this);
750 void Cursor::insert(Inset * inset)
753 insert(MathAtom(inset));
755 text()->insertInset(*this, inset);
759 void Cursor::niceInsert(docstring const & t)
770 void Cursor::niceInsert(MathAtom const & t)
773 docstring const safe = cap::grabAndEraseSelection(*this);
775 // enter the new inset and move the contents of the selection if possible
778 // be careful here: don't use 'pushBackward(t)' as this we need to
779 // push the clone, not the original
780 pushBackward(*nextInset());
781 // We may not use niceInsert here (recursion)
789 void Cursor::insert(MathData const & ar)
793 cap::eraseSelection(*this);
794 cell().insert(pos(), ar);
799 bool Cursor::backspace()
801 autocorrect() = false;
804 cap::eraseSelection(*this);
809 // If empty cell, and not part of a big cell
810 if (lastpos() == 0 && inset().nargs() == 1) {
812 // Directly delete empty cell: [|[]] => [|]
818 // [|], can not delete from inside
830 InsetMathUnknown * p = activeMacro();
831 if (p->name().size() > 1) {
832 p->setName(p->name().substr(0, p->name().size() - 1));
837 if (pos() != 0 && prevAtom()->nargs() > 0) {
838 // let's require two backspaces for 'big stuff' and
839 // highlight on the first
853 autocorrect() = false;
858 cap::eraseSelection(*this);
862 // delete empty cells if possible
863 if (pos() == lastpos() && inset().idxDelete(idx()))
866 // special behaviour when in last position of cell
867 if (pos() == lastpos()) {
868 bool one_cell = inset().nargs() == 1;
869 if (one_cell && lastpos() == 0) {
871 // Directly delete empty cell: [|[]] => [|]
877 // [|], can not delete from inside
882 inset().idxGlue(idx());
886 // 'clever' UI hack: only erase large items if previously slected
887 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
902 DocIterator save = *this;
903 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
905 if (disp_.dispatched())
908 autocorrect() = false;
916 DocIterator save = *this;
917 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
919 if (disp_.dispatched())
922 autocorrect() = false;
927 bool Cursor::macroModeClose()
931 InsetMathUnknown * p = activeMacro();
933 docstring const s = p->name();
937 // do nothing if the macro name is empty
941 // trigger updates of macros, at least, if no full
942 // updates take place anyway
943 updateFlags(Update::Force);
945 docstring const name = s.substr(1);
946 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
947 if (in && in->interpretString(*this, s))
949 MathAtom atom = createInsetMath(name);
950 MathMacro * atomAsMacro = atom.nucleus()->asMacro();
952 // make non-greedy, i.e. don't eat parameters from the right
953 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT);
960 docstring Cursor::macroName()
962 return inMacroMode() ? activeMacro()->name() : docstring();
966 void Cursor::handleNest(MathAtom const & a, int c)
968 //lyxerr << "Cursor::handleNest: " << c << endl;
970 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
973 pushBackward(*nextInset());
977 int Cursor::targetX() const
979 if (x_target() != -1)
988 int Cursor::textTargetOffset() const
990 return textTargetOffset_;
994 void Cursor::setTargetX()
1003 bool Cursor::inMacroMode() const
1009 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1010 return p && !p->final();
1014 InsetMathUnknown * Cursor::activeMacro()
1016 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1020 void Cursor::pullArg()
1023 MathData ar = cell();
1024 if (popBackward() && inMathed()) {
1026 cell().insert(pos(), ar);
1029 //formula()->mutateToText();
1034 void Cursor::touch()
1038 DocIterator::const_iterator it = begin();
1039 DocIterator::const_iterator et = end();
1040 for ( ; it != et; ++it)
1046 void Cursor::normalize()
1048 if (idx() > lastidx()) {
1049 lyxerr << "this should not really happen - 1: "
1050 << idx() << ' ' << nargs()
1051 << " in: " << &inset() << endl;
1055 if (pos() > lastpos()) {
1056 lyxerr << "this should not really happen - 2: "
1057 << pos() << ' ' << lastpos() << " in idx: " << idx()
1059 odocstringstream os;
1060 WriteStream wi(os, false, true);
1061 inset().asInsetMath()->write(wi);
1062 lyxerr << to_utf8(os.str()) << endl;
1068 bool Cursor::upDownInMath(bool up)
1070 // Be warned: The 'logic' implemented in this function is highly
1071 // fragile. A distance of one pixel or a '<' vs '<=' _really
1072 // matters. So fiddle around with it only if you think you know
1073 // what you are doing!
1079 // check if we had something else in mind, if not, this is the future
1081 if (x_target_ == -1)
1083 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1084 // In text mode inside the line (not left or right) possibly set a new target_x,
1085 // but only if we are somewhere else than the previous target-offset.
1087 // We want to keep the x-target on subsequent up/down movements
1088 // that cross beyond the end of short lines. Thus a special
1089 // handling when the cursor is at the end of line: Use the new
1090 // x-target only if the old one was before the end of line
1091 // or the old one was after the beginning of the line
1092 bool inRTL = isWithinRtlParagraph(*this);
1096 left = pos() == textRow().endpos();
1097 right = pos() == textRow().pos();
1099 left = pos() == textRow().pos();
1100 right = pos() == textRow().endpos();
1102 if ((!left && !right) ||
1103 (left && !right && xo < x_target_) ||
1104 (!left && right && x_target_ < xo))
1111 // try neigbouring script insets
1113 if (inMathed() && !selection()) {
1116 InsetMathScript const * p = prevAtom()->asScriptInset();
1117 if (p && p->has(up)) {
1119 push(*const_cast<InsetMathScript*>(p));
1120 idx() = p->idxOfScript(up);
1123 // we went in the right direction? Otherwise don't jump into the script
1127 if ((!up && y <= beforeDispY_) ||
1128 (up && y >= beforeDispY_))
1136 if (pos() != lastpos()) {
1137 InsetMathScript const * p = nextAtom()->asScriptInset();
1138 if (p && p->has(up)) {
1139 push(*const_cast<InsetMathScript*>(p));
1140 idx() = p->idxOfScript(up);
1143 // we went in the right direction? Otherwise don't jump into the script
1147 if ((!up && y <= beforeDispY_) ||
1148 (up && y >= beforeDispY_))
1156 // try to find an inset that knows better then we,
1157 if (inset().idxUpDown(*this, up)) {
1158 //lyxerr << "idxUpDown triggered" << endl;
1159 // try to find best position within this inset
1161 setCursor(bruteFind2(*this, xo, yo));
1165 // any improvement going just out of inset?
1166 if (popBackward() && inMathed()) {
1167 //lyxerr << "updown: popBackward succeeded" << endl;
1171 if (up ? ynew < beforeDispY_ : ynew > beforeDispY_)
1175 // no success, we are probably at the document top or bottom
1181 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1183 BOOST_ASSERT(text());
1191 // update the targetX - this is here before the "return false"
1192 // to set a new target which can be used by InsetTexts above
1193 // if we cannot move up/down inside this inset anymore
1194 if (x_target_ == -1)
1196 else if (xo - textTargetOffset() != x_target() &&
1197 depth() == beforeDispatchCursor_.depth()) {
1198 // In text mode inside the line (not left or right) possibly set a new target_x,
1199 // but only if we are somewhere else than the previous target-offset.
1201 // We want to keep the x-target on subsequent up/down movements
1202 // that cross beyond the end of short lines. Thus a special
1203 // handling when the cursor is at the end of line: Use the new
1204 // x-target only if the old one was before the end of line
1205 // or the old one was after the beginning of the line
1206 bool inRTL = isWithinRtlParagraph(*this);
1210 left = pos() == textRow().endpos();
1211 right = pos() == textRow().pos();
1213 left = pos() == textRow().pos();
1214 right = pos() == textRow().endpos();
1216 if ((!left && !right) ||
1217 (left && !right && xo < x_target_) ||
1218 (!left && right && x_target_ < xo))
1225 // first get the current line
1226 TextMetrics & tm = bv_->textMetrics(text());
1227 ParagraphMetrics const & pm = tm.parMetrics(pit());
1229 if (pos() && boundary())
1230 row = pm.pos2row(pos() - 1);
1232 row = pm.pos2row(pos());
1234 // are we not at the start or end?
1236 if (pit() == 0 && row == 0)
1239 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1240 row + 1 >= int(pm.rows().size()))
1244 // with and without selection are handled differently
1246 int yo = bv().getPos(*this, boundary()).y_;
1248 // To next/previous row
1250 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1252 tm.editXY(*this, xo, yo + textRow().descent() + 1);
1255 // This happens when you move out of an inset.
1256 // And to give the DEPM the possibility of doing
1257 // something we must provide it with two different
1259 Cursor dummy = *this;
1262 if (bv().checkDepm(dummy, old)) {
1263 updateNeeded = true;
1264 // Make sure that cur gets back whatever happened to dummy(Lgb)
1268 // if there is a selection, we stay out of any inset, and just jump to the right position:
1272 top().pos() = std::min(tm.x2pos(pit(), row - 1, xo), top().lastpos());
1273 } else if (pit() > 0) {
1275 ParagraphMetrics const & pmcur = bv_->parMetrics(text(), pit());
1276 top().pos() = std::min(tm.x2pos(pit(), pmcur.rows().size() - 1, xo), top().lastpos());
1279 if (row + 1 < int(pm.rows().size())) {
1280 top().pos() = std::min(tm.x2pos(pit(), row + 1, xo), top().lastpos());
1281 } else if (pit() + 1 < int(text()->paragraphs().size())) {
1283 top().pos() = std::min(tm.x2pos(pit(), 0, xo), top().lastpos());
1287 updateNeeded |= bv().checkDepm(*this, old);
1290 updateTextTargetOffset();
1295 void Cursor::handleFont(string const & font)
1297 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << ": " << font << endl;
1301 safe = cap::grabAndEraseSelection(*this);
1304 if (lastpos() != 0) {
1305 // something left in the cell
1307 // cursor in first position
1309 } else if (pos() == lastpos()) {
1310 // cursor in last position
1313 // cursor in between. split cell
1314 MathData::iterator bt = cell().begin();
1315 MathAtom at = createInsetMath(from_utf8(font));
1316 at.nucleus()->cell(0) = MathData(bt, bt + pos());
1317 cell().erase(bt, bt + pos());
1322 // nothing left in the cell
1330 void Cursor::message(docstring const & msg) const
1332 theLyXFunc().setMessage(msg);
1336 void Cursor::errorMessage(docstring const & msg) const
1338 theLyXFunc().setErrorMessage(msg);
1342 docstring Cursor::selectionAsString(bool label) const
1348 Buffer const & buffer = bv().buffer();
1349 ParagraphList const & pars = text()->paragraphs();
1351 // should be const ...
1352 pit_type startpit = selBegin().pit();
1353 pit_type endpit = selEnd().pit();
1354 size_t const startpos = selBegin().pos();
1355 size_t const endpos = selEnd().pos();
1357 if (startpit == endpit)
1358 return pars[startpit].asString(buffer, startpos, endpos, label);
1360 // First paragraph in selection
1361 docstring result = pars[startpit].
1362 asString(buffer, startpos, pars[startpit].size(), label)
1363 + parbreak(pars[startpit]);
1365 // The paragraphs in between (if any)
1366 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1367 Paragraph const & par = pars[pit];
1368 result += par.asString(buffer, 0, par.size(), label)
1369 + parbreak(pars[pit]);
1372 // Last paragraph in selection
1373 result += pars[endpit].asString(buffer, 0, endpos, label);
1379 return cap::grabSelection(*this);
1385 docstring Cursor::currentState()
1388 odocstringstream os;
1394 return text()->currentState(*this);
1400 docstring Cursor::getPossibleLabel()
1402 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
1406 Encoding const * Cursor::getEncoding() const
1411 // go up until first non-0 text is hit
1412 // (innermost text is 0 in mathed)
1413 for (s = depth() - 1; s >= 0; --s)
1414 if (operator[](s).text())
1416 CursorSlice const & sl = operator[](s);
1417 Text const & text = *sl.text();
1418 Font font = text.getPar(sl.pit()).getFont(
1419 bv().buffer().params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1420 return font.language()->encoding();
1424 void Cursor::undispatched()
1426 disp_.dispatched(false);
1430 void Cursor::dispatched()
1432 disp_.dispatched(true);
1436 void Cursor::updateFlags(Update::flags f)
1442 void Cursor::noUpdate()
1444 disp_.update(Update::None);
1448 Font Cursor::getFont() const
1450 // The logic here should more or less match to the Cursor::setCurrentFont
1451 // logic, i.e. the cursor height should give a hint what will happen
1452 // if a character is entered.
1454 // HACK. far from being perfect...
1455 // go up until first non-0 text is hit
1456 // (innermost text is 0 in mathed)
1458 for (s = depth() - 1; s >= 0; --s)
1459 if (operator[](s).text())
1461 CursorSlice const & sl = operator[](s);
1462 Text const & text = *sl.text();
1463 Paragraph const & par = text.getPar(sl.pit());
1465 // on boundary, so we are really at the character before
1466 pos_type pos = sl.pos();
1467 if (pos > 0 && boundary())
1470 // on space? Take the font before (only for RTL boundary stay)
1472 TextMetrics const & tm = bv().textMetrics(&text);
1473 if (pos == sl.lastpos()
1474 || (par.isSeparator(pos)
1475 && !tm.isRTLBoundary(sl.pit(), pos)))
1479 // get font at the position
1480 Font font = par.getFont(bv().buffer().params(), pos,
1481 outerFont(sl.pit(), text.paragraphs()));
1487 bool Cursor::fixIfBroken()
1489 if (DocIterator::fixIfBroken()) {
1498 bool notifyCursorLeaves(DocIterator const & old, Cursor & cur)
1500 // find inset in common
1502 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
1503 if (&old.inset() != &cur.inset())
1507 // notify everything on top of the common part in old cursor,
1508 // but stop if the inset claims the cursor to be invalid now
1509 for (; i < old.depth(); ++i) {
1510 if (old[i].inset().notifyCursorLeaves(cur))
1518 void Cursor::setCurrentFont()
1520 CursorSlice const & cs = innerTextSlice();
1521 Paragraph const & par = cs.paragraph();
1522 pos_type cpit = cs.pit();
1523 pos_type cpos = cs.pos();
1524 Text const & ctext = *cs.text();
1525 TextMetrics const & tm = bv().textMetrics(&ctext);
1527 // are we behind previous char in fact? -> go to that char
1528 if (cpos > 0 && boundary())
1531 // find position to take the font from
1533 // paragraph end? -> font of last char
1534 if (cpos == lastpos())
1536 // on space? -> look at the words in front of space
1537 else if (cpos > 0 && par.isSeparator(cpos)) {
1538 // abc| def -> font of c
1539 // abc |[WERBEH], i.e. boundary==true -> font of c
1540 // abc [WERBEH]| def, font of the space
1541 if (!tm.isRTLBoundary(cpit, cpos))
1547 BufferParams const & bufparams = buffer().params();
1548 current_font = par.getFontSettings(bufparams, cpos);
1549 real_current_font = tm.getDisplayFont(cpit, cpos);
1551 // special case for paragraph end
1552 if (cs.pos() == lastpos()
1553 && tm.isRTLBoundary(cpit, cs.pos())
1555 Language const * lang = par.getParLanguage(bufparams);
1556 current_font.setLanguage(lang);
1557 current_font.fontInfo().setNumber(FONT_OFF);
1558 real_current_font.setLanguage(lang);
1559 real_current_font.fontInfo().setNumber(FONT_OFF);
1564 bool Cursor::textUndo()
1566 DocIterator dit = *this;
1567 // Undo::textUndo() will modify dit.
1568 if (!bv_->buffer().undo().textUndo(dit))
1572 selection() = false;
1579 bool Cursor::textRedo()
1581 DocIterator dit = *this;
1582 // Undo::textRedo() will modify dit.
1583 if (!bv_->buffer().undo().textRedo(dit))
1587 selection() = false;
1594 void Cursor::finishUndo()
1596 bv_->buffer().undo().finishUndo();
1600 void Cursor::recordUndo(UndoKind kind, pit_type from, pit_type to)
1602 bv_->buffer().undo().recordUndo(*this, kind, from, to);
1606 void Cursor::recordUndo(UndoKind kind, pit_type from)
1608 bv_->buffer().undo().recordUndo(*this, kind, from);
1612 void Cursor::recordUndo(UndoKind kind)
1614 bv_->buffer().undo().recordUndo(*this, kind);
1618 void Cursor::recordUndoInset(UndoKind kind)
1620 bv_->buffer().undo().recordUndoInset(*this, kind);
1624 void Cursor::recordUndoFullDocument()
1626 bv_->buffer().undo().recordUndoFullDocument(*this);
1630 void Cursor::recordUndoSelection()
1632 bv_->buffer().undo().recordUndo(*this, ATOMIC_UNDO,
1633 selBegin().pit(), selEnd().pit());