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.
18 #include "BufferView.h"
19 #include "CoordCache.h"
21 #include "CutAndPaste.h"
22 #include "DispatchResult.h"
25 #include "FuncRequest.h"
28 #include "LyXFunc.h" // only for setMessage()
30 #include "paragraph_funcs.h"
31 #include "Paragraph.h"
32 #include "ParIterator.h"
35 #include "TextMetrics.h"
36 #include "TocBackend.h"
38 #include "support/debug.h"
39 #include "support/docstream.h"
41 #include "insets/InsetTabular.h"
42 #include "insets/InsetText.h"
44 #include "mathed/InsetMath.h"
45 #include "mathed/InsetMathScript.h"
46 #include "mathed/MacroTable.h"
47 #include "mathed/MathData.h"
48 #include "mathed/MathMacro.h"
50 #include <boost/assert.hpp>
51 #include <boost/bind.hpp>
63 bool positionable(DocIterator const & cursor, DocIterator const & anchor)
65 // avoid deeper nested insets when selecting
66 if (cursor.depth() > anchor.depth())
69 // anchor might be deeper, should have same path then
70 for (size_t i = 0; i < cursor.depth(); ++i)
71 if (&cursor[i].inset() != &anchor[i].inset())
74 // position should be ok.
79 // Find position closest to (x, y) in cell given by iter.
80 // Used only in mathed
81 DocIterator bruteFind2(Cursor const & c, int x, int y)
83 double best_dist = numeric_limits<double>::max();
90 et.top().pos() = et.top().asInsetMath()->cell(et.top().idx()).size();
91 for (size_t i = 0;; ++i) {
94 Inset const * inset = &it.inset();
95 map<Inset const *, Geometry> const & data =
96 c.bv().coordCache().getInsets().getData();
97 map<Inset const *, Geometry>::const_iterator I = data.find(inset);
99 // FIXME: in the case where the inset is not in the cache, this
100 // means that no part of it is visible on screen. In this case
101 // we don't do elaborate search and we just return the forwarded
102 // DocIterator at its beginning.
103 if (I == data.end()) {
108 Point o = I->second.pos;
109 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
110 // Convert to absolute
113 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
114 // '<=' in order to take the last possible position
115 // this is important for clicking behind \sum in e.g. '\sum_i a'
116 LYXERR(Debug::DEBUG, "i: " << i << " d: " << d
117 << " best: " << best_dist);
118 if (d <= best_dist) {
131 /// moves position closest to (x, y) in given box
132 bool bruteFind(Cursor & cursor,
133 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
135 BOOST_ASSERT(!cursor.empty());
136 Inset & inset = cursor[0].inset();
137 BufferView & bv = cursor.bv();
139 CoordCache::InnerParPosCache const & cache =
140 bv.coordCache().getParPos().find(cursor.bottom().text())->second;
141 // Get an iterator on the first paragraph in the cache
142 DocIterator it(inset);
143 it.push_back(CursorSlice(inset));
144 it.pit() = cache.begin()->first;
145 // Get an iterator after the last paragraph in the cache
146 DocIterator et(inset);
147 et.push_back(CursorSlice(inset));
148 et.pit() = boost::prior(cache.end())->first;
149 if (et.pit() >= et.lastpit())
150 et = doc_iterator_end(inset);
154 double best_dist = numeric_limits<double>::max();;
155 DocIterator best_cursor = et;
157 for ( ; it != et; it.forwardPos(true)) {
158 // avoid invalid nesting when selecting
159 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
160 Point p = bv.getPos(it, false);
163 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
164 double const dx = xo - x;
165 double const dy = yo - y;
166 double const d = dx * dx + dy * dy;
167 // '<=' in order to take the last possible position
168 // this is important for clicking behind \sum in e.g. '\sum_i a'
169 if (d <= best_dist) {
170 // lyxerr << "*" << endl;
178 if (best_cursor != et) {
179 cursor.setCursor(best_cursor);
188 /// moves position closest to (x, y) in given box
189 bool bruteFind3(Cursor & cur, int x, int y, bool up)
191 BufferView & bv = cur.bv();
192 int ylow = up ? 0 : y + 1;
193 int yhigh = up ? y - 1 : bv.workHeight();
195 int xhigh = bv.workWidth();
197 // FIXME: bit more work needed to get 'from' and 'to' right.
198 pit_type from = cur.bottom().pit();
199 //pit_type to = cur.bottom().pit();
200 //lyxerr << "Pit start: " << from << endl;
202 //lyxerr << "bruteFind3: x: " << x << " y: " << y
203 // << " xlow: " << xlow << " xhigh: " << xhigh
204 // << " ylow: " << ylow << " yhigh: " << yhigh
206 Inset & inset = bv.buffer().inset();
207 DocIterator it = doc_iterator_begin(inset);
209 DocIterator et = doc_iterator_end(inset);
211 double best_dist = numeric_limits<double>::max();
212 DocIterator best_cursor = et;
214 for ( ; it != et; it.forwardPos()) {
215 // avoid invalid nesting when selecting
216 if (bv.cursorStatus(it) == CUR_INSIDE
217 && (!cur.selection() || positionable(it, cur.anchor_))) {
218 Point p = bv.getPos(it, false);
221 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
222 double const dx = xo - x;
223 double const dy = yo - y;
224 double const d = dx * dx + dy * dy;
225 //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
226 // << " dx: " << dx << " dy: " << dy
227 // << " idx: " << it.idx() << " pos: " << it.pos()
230 // '<=' in order to take the last possible position
231 // this is important for clicking behind \sum in e.g. '\sum_i a'
232 if (d <= best_dist) {
233 //lyxerr << "*" << endl;
241 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
242 if (best_cursor == et)
244 cur.setCursor(best_cursor);
248 docstring parbreak(Paragraph const & par)
250 odocstringstream ods;
252 // only add blank line if we're not in an ERT or Listings inset
253 if (par.ownerCode() != ERT_CODE
254 && par.ownerCode() != LISTINGS_CODE)
262 // be careful: this is called from the bv's constructor, too, so
263 // bv functions are not yet available!
264 Cursor::Cursor(BufferView & bv)
265 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1), textTargetOffset_(0),
266 selection_(false), mark_(false), logicalpos_(false),
267 current_font(inherit_font)
271 void Cursor::reset(Inset & inset)
274 push_back(CursorSlice(inset));
275 anchor_ = doc_iterator_begin(inset);
283 // this (intentionally) does neither touch anchor nor selection status
284 void Cursor::setCursor(DocIterator const & cur)
286 DocIterator::operator=(cur);
290 void Cursor::dispatch(FuncRequest const & cmd0)
292 LYXERR(Debug::DEBUG, "cmd: " << cmd0 << '\n' << *this);
297 FuncRequest cmd = cmd0;
300 // store some values to be used inside of the handlers
301 beforeDispatchCursor_ = *this;
302 for (; depth(); pop()) {
303 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
304 << cmd0 << endl << *this);
305 BOOST_ASSERT(pos() <= lastpos());
306 BOOST_ASSERT(idx() <= lastidx());
307 BOOST_ASSERT(pit() <= lastpit());
309 // The common case is 'LFUN handled, need update', so make the
310 // LFUN handler's life easier by assuming this as default value.
311 // The handler can reset the update and val flags if necessary.
312 disp_.update(Update::FitCursor | Update::Force);
313 disp_.dispatched(true);
314 inset().dispatch(*this, cmd);
315 if (disp_.dispatched())
319 // it completely to get a 'bomb early' behaviour in case this
320 // object will be used again.
321 if (!disp_.dispatched()) {
322 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
324 disp_.update(Update::None);
325 disp_.dispatched(false);
327 // restore the previous one because nested Cursor::dispatch calls
328 // are possible which would change it
329 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
334 DispatchResult Cursor::result() const
340 BufferView & Cursor::bv() const
347 Buffer & Cursor::buffer() const
350 return bv_->buffer();
356 BOOST_ASSERT(depth() >= 1);
361 void Cursor::push(Inset & p)
363 push_back(CursorSlice(p));
367 void Cursor::pushBackward(Inset & p)
369 BOOST_ASSERT(!empty());
370 //lyxerr << "Entering inset " << t << " front" << endl;
376 bool Cursor::popBackward()
378 BOOST_ASSERT(!empty());
379 //lyxerr << "Leaving inset from in front" << endl;
380 inset().notifyCursorLeaves(*this);
388 bool Cursor::popForward()
390 BOOST_ASSERT(!empty());
391 //lyxerr << "Leaving inset from in back" << endl;
392 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
393 inset().notifyCursorLeaves(*this);
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 CursorSlice Cursor::anchor() const
458 BOOST_ASSERT(anchor_.depth() >= depth());
459 CursorSlice normal = anchor_[depth() - 1];
460 if (depth() < anchor_.depth() && top() <= normal) {
461 // anchor is behind cursor -> move anchor behind the inset
468 CursorSlice Cursor::selBegin() const
472 return anchor() < top() ? anchor() : top();
476 CursorSlice Cursor::selEnd() const
480 return anchor() > top() ? anchor() : top();
484 DocIterator Cursor::selectionBegin() const
488 DocIterator di = (anchor() < top() ? anchor_ : *this);
494 DocIterator Cursor::selectionEnd() const
498 DocIterator di = (anchor() > top() ? anchor_ : *this);
499 if (di.depth() > depth()) {
507 void Cursor::setSelection()
510 // A selection with no contents is not a selection
511 // FIXME: doesnt look ok
512 if (pit() == anchor().pit() && pos() == anchor().pos())
517 void Cursor::setSelection(DocIterator const & where, int n)
526 void Cursor::clearSelection()
534 void Cursor::setTargetX(int x)
537 textTargetOffset_ = 0;
541 int Cursor::x_target() const
547 void Cursor::clearTargetX()
550 textTargetOffset_ = 0;
554 void Cursor::updateTextTargetOffset()
559 textTargetOffset_ = x - x_target_;
563 void Cursor::info(odocstream & os) const
565 for (int i = 1, n = depth(); i < n; ++i) {
566 operator[](i).inset().infoize(os);
570 Inset const * inset = prevInset();
571 // prevInset() can return 0 in certain case.
573 prevInset()->infoize2(os);
575 // overwite old message
580 bool Cursor::selHandle(bool sel)
582 //lyxerr << "Cursor::selHandle" << endl;
585 if (sel == selection())
589 cap::saveSelection(*this);
597 ostream & operator<<(ostream & os, Cursor const & cur)
599 os << "\n cursor: | anchor:\n";
600 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
601 os << " " << cur[i] << " | ";
602 if (i < cur.anchor_.depth())
603 os << cur.anchor_[i];
605 os << "-------------------------------";
608 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
609 os << "------------------------------- | " << cur.anchor_[i] << "\n";
611 os << " selection: " << cur.selection_
612 << " x_target: " << cur.x_target_ << endl;
617 LyXErr & operator<<(LyXErr & os, Cursor const & cur)
627 ///////////////////////////////////////////////////////////////////
630 // The part below is the non-integrated rest of the original math
631 // cursor. This should be either generalized for texted or moved
632 // back to mathed (in most cases to InsetMathNest).
634 ///////////////////////////////////////////////////////////////////
636 #include "mathed/InsetMathChar.h"
637 #include "mathed/InsetMathGrid.h"
638 #include "mathed/InsetMathScript.h"
639 #include "mathed/InsetMathUnknown.h"
640 #include "mathed/MathFactory.h"
641 #include "mathed/MathStream.h"
642 #include "mathed/MathSupport.h"
647 //#define FILEDEBUG 1
650 bool Cursor::isInside(Inset const * p) const
652 for (size_t i = 0; i != depth(); ++i)
653 if (&operator[](i).inset() == p)
659 void Cursor::leaveInset(Inset const & inset)
661 for (size_t i = 0; i != depth(); ++i) {
662 if (&operator[](i).inset() == &inset) {
670 bool Cursor::openable(MathAtom const & t) const
681 // we can't move into anything new during selection
682 if (depth() >= anchor_.depth())
684 if (t.nucleus() != &anchor_[depth()].inset())
691 void Cursor::setScreenPos(int x, int /*y*/)
694 //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
699 void Cursor::plainErase()
705 void Cursor::markInsert()
707 insert(char_type(0));
711 void Cursor::markErase()
717 void Cursor::plainInsert(MathAtom const & t)
719 cell().insert(pos(), t);
724 void Cursor::insert(docstring const & str)
726 for_each(str.begin(), str.end(),
727 boost::bind(static_cast<void(Cursor::*)(char_type)>
728 (&Cursor::insert), this, _1));
732 void Cursor::insert(char_type c)
734 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
735 BOOST_ASSERT(!empty());
737 cap::selClearOrDel(*this);
738 insert(new InsetMathChar(c));
740 text()->insertChar(*this, c);
745 void Cursor::insert(MathAtom const & t)
747 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
749 cap::selClearOrDel(*this);
754 void Cursor::insert(Inset * inset)
757 insert(MathAtom(inset));
759 text()->insertInset(*this, inset);
763 void Cursor::niceInsert(docstring const & t)
774 void Cursor::niceInsert(MathAtom const & t)
777 docstring const safe = cap::grabAndEraseSelection(*this);
779 // enter the new inset and move the contents of the selection if possible
782 // be careful here: don't use 'pushBackward(t)' as this we need to
783 // push the clone, not the original
784 pushBackward(*nextInset());
785 // We may not use niceInsert here (recursion)
793 void Cursor::insert(MathData const & ar)
797 cap::eraseSelection(*this);
798 cell().insert(pos(), ar);
803 bool Cursor::backspace()
805 autocorrect() = false;
808 cap::eraseSelection(*this);
813 // If empty cell, and not part of a big cell
814 if (lastpos() == 0 && inset().nargs() == 1) {
816 // Directly delete empty cell: [|[]] => [|]
822 // [|], can not delete from inside
834 InsetMathUnknown * p = activeMacro();
835 if (p->name().size() > 1) {
836 p->setName(p->name().substr(0, p->name().size() - 1));
841 if (pos() != 0 && prevAtom()->nargs() > 0) {
842 // let's require two backspaces for 'big stuff' and
843 // highlight on the first
857 autocorrect() = false;
862 cap::eraseSelection(*this);
866 // delete empty cells if possible
867 if (pos() == lastpos() && inset().idxDelete(idx()))
870 // special behaviour when in last position of cell
871 if (pos() == lastpos()) {
872 bool one_cell = inset().nargs() == 1;
873 if (one_cell && lastpos() == 0) {
875 // Directly delete empty cell: [|[]] => [|]
881 // [|], can not delete from inside
886 inset().idxGlue(idx());
890 // 'clever' UI hack: only erase large items if previously slected
891 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
906 DocIterator save = *this;
907 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
909 if (disp_.dispatched())
912 autocorrect() = false;
920 DocIterator save = *this;
921 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
923 if (disp_.dispatched())
926 autocorrect() = false;
931 bool Cursor::macroModeClose()
935 InsetMathUnknown * p = activeMacro();
937 docstring const s = p->name();
941 // do nothing if the macro name is empty
945 // trigger updates of macros, at least, if no full
946 // updates take place anyway
947 updateFlags(Update::Force);
949 docstring const name = s.substr(1);
950 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
951 if (in && in->interpretString(*this, s))
953 MathAtom atom = createInsetMath(name);
954 MathMacro * atomAsMacro = atom.nucleus()->asMacro();
956 // make non-greedy, i.e. don't eat parameters from the right
957 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT);
964 docstring Cursor::macroName()
966 return inMacroMode() ? activeMacro()->name() : docstring();
970 void Cursor::handleNest(MathAtom const & a, int c)
972 //lyxerr << "Cursor::handleNest: " << c << endl;
974 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
977 pushBackward(*nextInset());
981 int Cursor::targetX() const
983 if (x_target() != -1)
992 int Cursor::textTargetOffset() const
994 return textTargetOffset_;
998 void Cursor::setTargetX()
1007 bool Cursor::inMacroMode() const
1013 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1014 return p && !p->final();
1018 InsetMathUnknown * Cursor::activeMacro()
1020 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1024 void Cursor::pullArg()
1027 MathData ar = cell();
1028 if (popBackward() && inMathed()) {
1030 cell().insert(pos(), ar);
1033 //formula()->mutateToText();
1038 void Cursor::touch()
1042 DocIterator::const_iterator it = begin();
1043 DocIterator::const_iterator et = end();
1044 for ( ; it != et; ++it)
1050 void Cursor::normalize()
1052 if (idx() > lastidx()) {
1053 lyxerr << "this should not really happen - 1: "
1054 << idx() << ' ' << nargs()
1055 << " in: " << &inset() << endl;
1059 if (pos() > lastpos()) {
1060 lyxerr << "this should not really happen - 2: "
1061 << pos() << ' ' << lastpos() << " in idx: " << idx()
1063 odocstringstream os;
1064 WriteStream wi(os, false, true);
1065 inset().asInsetMath()->write(wi);
1066 lyxerr << to_utf8(os.str()) << endl;
1072 bool Cursor::upDownInMath(bool up)
1074 // Be warned: The 'logic' implemented in this function is highly
1075 // fragile. A distance of one pixel or a '<' vs '<=' _really
1076 // matters. So fiddle around with it only if you think you know
1077 // what you are doing!
1081 xo = theLyXFunc().cursorBeforeDispatchX();
1083 // check if we had something else in mind, if not, this is the future
1085 if (x_target_ == -1)
1087 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1088 // In text mode inside the line (not left or right) possibly set a new target_x,
1089 // but only if we are somewhere else than the previous target-offset.
1091 // We want to keep the x-target on subsequent up/down movements
1092 // that cross beyond the end of short lines. Thus a special
1093 // handling when the cursor is at the end of line: Use the new
1094 // x-target only if the old one was before the end of line
1095 // or the old one was after the beginning of the line
1096 bool inRTL = isWithinRtlParagraph(*this);
1100 left = pos() == textRow().endpos();
1101 right = pos() == textRow().pos();
1103 left = pos() == textRow().pos();
1104 right = pos() == textRow().endpos();
1106 if ((!left && !right) ||
1107 (left && !right && xo < x_target_) ||
1108 (!left && right && x_target_ < xo))
1115 // try neigbouring script insets
1117 if (inMathed() && !selection()) {
1120 InsetMathScript const * p = prevAtom()->asScriptInset();
1121 if (p && p->has(up)) {
1123 push(*const_cast<InsetMathScript*>(p));
1124 idx() = p->idxOfScript(up);
1127 // we went in the right direction? Otherwise don't jump into the script
1131 int oy = theLyXFunc().cursorBeforeDispatchY();
1132 if ((!up && y <= oy) ||
1141 if (pos() != lastpos()) {
1142 InsetMathScript const * p = nextAtom()->asScriptInset();
1143 if (p && p->has(up)) {
1144 push(*const_cast<InsetMathScript*>(p));
1145 idx() = p->idxOfScript(up);
1148 // we went in the right direction? Otherwise don't jump into the script
1152 int oy = theLyXFunc().cursorBeforeDispatchY();
1153 if ((!up && y <= oy) ||
1162 // try to find an inset that knows better then we,
1163 if (inset().idxUpDown(*this, up)) {
1164 //lyxerr << "idxUpDown triggered" << endl;
1165 // try to find best position within this inset
1167 setCursor(bruteFind2(*this, xo, yo));
1171 // any improvement going just out of inset?
1172 if (popBackward() && inMathed()) {
1173 //lyxerr << "updown: popBackward succeeded" << endl;
1176 int yold = theLyXFunc().cursorBeforeDispatchY();
1178 if (up ? ynew < yold : ynew > yold)
1182 // no success, we are probably at the document top or bottom
1188 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1190 BOOST_ASSERT(text());
1196 xo = theLyXFunc().cursorBeforeDispatchX();
1198 // update the targetX - this is here before the "return false"
1199 // to set a new target which can be used by InsetTexts above
1200 // if we cannot move up/down inside this inset anymore
1201 if (x_target_ == -1)
1203 else if (xo - textTargetOffset() != x_target() &&
1204 depth() == beforeDispatchCursor_.depth()) {
1205 // In text mode inside the line (not left or right) possibly set a new target_x,
1206 // but only if we are somewhere else than the previous target-offset.
1208 // We want to keep the x-target on subsequent up/down movements
1209 // that cross beyond the end of short lines. Thus a special
1210 // handling when the cursor is at the end of line: Use the new
1211 // x-target only if the old one was before the end of line
1212 // or the old one was after the beginning of the line
1213 bool inRTL = isWithinRtlParagraph(*this);
1217 left = pos() == textRow().endpos();
1218 right = pos() == textRow().pos();
1220 left = pos() == textRow().pos();
1221 right = pos() == textRow().endpos();
1223 if ((!left && !right) ||
1224 (left && !right && xo < x_target_) ||
1225 (!left && right && x_target_ < xo))
1232 // first get the current line
1233 TextMetrics & tm = bv_->textMetrics(text());
1234 ParagraphMetrics const & pm = tm.parMetrics(pit());
1236 if (pos() && boundary())
1237 row = pm.pos2row(pos() - 1);
1239 row = pm.pos2row(pos());
1241 // are we not at the start or end?
1243 if (pit() == 0 && row == 0)
1246 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1247 row + 1 >= int(pm.rows().size()))
1251 // with and without selection are handled differently
1253 int yo = bv().getPos(*this, boundary()).y_;
1255 // To next/previous row
1257 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1259 tm.editXY(*this, xo, yo + textRow().descent() + 1);
1262 // This happens when you move out of an inset.
1263 // And to give the DEPM the possibility of doing
1264 // something we must provide it with two different
1266 Cursor dummy = *this;
1269 if (bv().checkDepm(dummy, old)) {
1270 updateNeeded = true;
1271 // Make sure that cur gets back whatever happened to dummy(Lgb)
1275 // if there is a selection, we stay out of any inset, and just jump to the right position:
1279 top().pos() = min(tm.x2pos(pit(), row - 1, xo), top().lastpos());
1280 } else if (pit() > 0) {
1282 ParagraphMetrics const & pmcur = bv_->parMetrics(text(), pit());
1283 top().pos() = min(tm.x2pos(pit(), pmcur.rows().size() - 1, xo), top().lastpos());
1286 if (row + 1 < int(pm.rows().size())) {
1287 top().pos() = min(tm.x2pos(pit(), row + 1, xo), top().lastpos());
1288 } else if (pit() + 1 < int(text()->paragraphs().size())) {
1290 top().pos() = min(tm.x2pos(pit(), 0, xo), top().lastpos());
1294 updateNeeded |= bv().checkDepm(*this, old);
1297 updateTextTargetOffset();
1302 void Cursor::handleFont(string const & font)
1304 LYXERR(Debug::DEBUG, font);
1308 safe = cap::grabAndEraseSelection(*this);
1311 if (lastpos() != 0) {
1312 // something left in the cell
1314 // cursor in first position
1316 } else if (pos() == lastpos()) {
1317 // cursor in last position
1320 // cursor in between. split cell
1321 MathData::iterator bt = cell().begin();
1322 MathAtom at = createInsetMath(from_utf8(font));
1323 at.nucleus()->cell(0) = MathData(bt, bt + pos());
1324 cell().erase(bt, bt + pos());
1329 // nothing left in the cell
1337 void Cursor::message(docstring const & msg) const
1339 theLyXFunc().setMessage(msg);
1343 void Cursor::errorMessage(docstring const & msg) const
1345 theLyXFunc().setErrorMessage(msg);
1349 docstring Cursor::selectionAsString(bool label) const
1355 Buffer const & buffer = bv().buffer();
1356 ParagraphList const & pars = text()->paragraphs();
1358 // should be const ...
1359 pit_type startpit = selBegin().pit();
1360 pit_type endpit = selEnd().pit();
1361 size_t const startpos = selBegin().pos();
1362 size_t const endpos = selEnd().pos();
1364 if (startpit == endpit)
1365 return pars[startpit].asString(buffer, startpos, endpos, label);
1367 // First paragraph in selection
1368 docstring result = pars[startpit].
1369 asString(buffer, startpos, pars[startpit].size(), label)
1370 + parbreak(pars[startpit]);
1372 // The paragraphs in between (if any)
1373 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1374 Paragraph const & par = pars[pit];
1375 result += par.asString(buffer, 0, par.size(), label)
1376 + parbreak(pars[pit]);
1379 // Last paragraph in selection
1380 result += pars[endpit].asString(buffer, 0, endpos, label);
1386 return cap::grabSelection(*this);
1392 docstring Cursor::currentState()
1395 odocstringstream os;
1401 return text()->currentState(*this);
1407 docstring Cursor::getPossibleLabel()
1409 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
1413 Encoding const * Cursor::getEncoding() const
1417 CursorSlice const & sl = innerTextSlice();
1418 Text const & text = *sl.text();
1419 Font font = text.getPar(sl.pit()).getFont(
1420 bv().buffer().params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1421 return font.language()->encoding();
1425 void Cursor::undispatched()
1427 disp_.dispatched(false);
1431 void Cursor::dispatched()
1433 disp_.dispatched(true);
1437 void Cursor::updateFlags(Update::flags f)
1443 void Cursor::noUpdate()
1445 disp_.update(Update::None);
1449 Font Cursor::getFont() const
1451 // The logic here should more or less match to the Cursor::setCurrentFont
1452 // logic, i.e. the cursor height should give a hint what will happen
1453 // if a character is entered.
1455 // HACK. far from being perfect...
1457 CursorSlice const & sl = innerTextSlice();
1458 Text const & text = *sl.text();
1459 Paragraph const & par = text.getPar(sl.pit());
1461 // on boundary, so we are really at the character before
1462 pos_type pos = sl.pos();
1463 if (pos > 0 && boundary())
1466 // on space? Take the font before (only for RTL boundary stay)
1468 TextMetrics const & tm = bv().textMetrics(&text);
1469 if (pos == sl.lastpos()
1470 || (par.isSeparator(pos)
1471 && !tm.isRTLBoundary(sl.pit(), pos)))
1475 // get font at the position
1476 Font font = par.getFont(bv().buffer().params(), pos,
1477 outerFont(sl.pit(), text.paragraphs()));
1483 bool Cursor::fixIfBroken()
1485 if (DocIterator::fixIfBroken()) {
1494 bool notifyCursorLeaves(DocIterator const & old, Cursor & cur)
1496 // find inset in common
1498 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
1499 if (&old.inset() != &cur.inset())
1503 // notify everything on top of the common part in old cursor,
1504 // but stop if the inset claims the cursor to be invalid now
1505 for (; i < old.depth(); ++i) {
1506 if (old[i].inset().notifyCursorLeaves(cur))
1514 void Cursor::setCurrentFont()
1516 CursorSlice const & cs = innerTextSlice();
1517 Paragraph const & par = cs.paragraph();
1518 pos_type cpit = cs.pit();
1519 pos_type cpos = cs.pos();
1520 Text const & ctext = *cs.text();
1521 TextMetrics const & tm = bv().textMetrics(&ctext);
1523 // are we behind previous char in fact? -> go to that char
1524 if (cpos > 0 && boundary())
1527 // find position to take the font from
1529 // paragraph end? -> font of last char
1530 if (cpos == lastpos())
1532 // on space? -> look at the words in front of space
1533 else if (cpos > 0 && par.isSeparator(cpos)) {
1534 // abc| def -> font of c
1535 // abc |[WERBEH], i.e. boundary==true -> font of c
1536 // abc [WERBEH]| def, font of the space
1537 if (!tm.isRTLBoundary(cpit, cpos))
1543 BufferParams const & bufparams = buffer().params();
1544 current_font = par.getFontSettings(bufparams, cpos);
1545 real_current_font = tm.getDisplayFont(cpit, cpos);
1547 // special case for paragraph end
1548 if (cs.pos() == lastpos()
1549 && tm.isRTLBoundary(cpit, cs.pos())
1551 Language const * lang = par.getParLanguage(bufparams);
1552 current_font.setLanguage(lang);
1553 current_font.fontInfo().setNumber(FONT_OFF);
1554 real_current_font.setLanguage(lang);
1555 real_current_font.fontInfo().setNumber(FONT_OFF);
1560 bool Cursor::textUndo()
1562 DocIterator dit = *this;
1563 // Undo::textUndo() will modify dit.
1564 if (!bv_->buffer().undo().textUndo(dit))
1568 selection() = false;
1575 bool Cursor::textRedo()
1577 DocIterator dit = *this;
1578 // Undo::textRedo() will modify dit.
1579 if (!bv_->buffer().undo().textRedo(dit))
1583 selection() = false;
1590 void Cursor::finishUndo()
1592 bv_->buffer().undo().finishUndo();
1596 void Cursor::recordUndo(UndoKind kind, pit_type from, pit_type to)
1598 bv_->buffer().undo().recordUndo(*this, kind, from, to);
1602 void Cursor::recordUndo(UndoKind kind, pit_type from)
1604 bv_->buffer().undo().recordUndo(*this, kind, from);
1608 void Cursor::recordUndo(UndoKind kind)
1610 bv_->buffer().undo().recordUndo(*this, kind);
1614 void Cursor::recordUndoInset(UndoKind kind)
1616 bv_->buffer().undo().recordUndoInset(*this, kind);
1620 void Cursor::recordUndoFullDocument()
1622 bv_->buffer().undo().recordUndoFullDocument(*this);
1626 void Cursor::recordUndoSelection()
1628 bv_->buffer().undo().recordUndo(*this, ATOMIC_UNDO,
1629 selBegin().pit(), selEnd().pit());
1633 void Cursor::checkBufferStructure()
1635 if (paragraph().layout()->toclevel == Layout::NOT_IN_TOC)
1637 Buffer const * master = buffer().masterBuffer();
1638 master->tocBackend().updateItem(ParConstIterator(*this));
1639 master->structureChanged();