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_ = DocIterator(inset);
282 // this (intentionally) does neither touch anchor nor selection status
283 void Cursor::setCursor(DocIterator const & cur)
285 DocIterator::operator=(cur);
289 void Cursor::dispatch(FuncRequest const & cmd0)
291 LYXERR(Debug::DEBUG, "cmd: " << cmd0 << '\n' << *this);
296 FuncRequest cmd = cmd0;
299 // store some values to be used inside of the handlers
300 beforeDispatchCursor_ = *this;
301 for (; depth(); pop()) {
302 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
303 << cmd0 << endl << *this);
304 BOOST_ASSERT(pos() <= lastpos());
305 BOOST_ASSERT(idx() <= lastidx());
306 BOOST_ASSERT(pit() <= lastpit());
308 // The common case is 'LFUN handled, need update', so make the
309 // LFUN handler's life easier by assuming this as default value.
310 // The handler can reset the update and val flags if necessary.
311 disp_.update(Update::FitCursor | Update::Force);
312 disp_.dispatched(true);
313 inset().dispatch(*this, cmd);
314 if (disp_.dispatched())
318 // it completely to get a 'bomb early' behaviour in case this
319 // object will be used again.
320 if (!disp_.dispatched()) {
321 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
323 disp_.update(Update::None);
324 disp_.dispatched(false);
326 // restore the previous one because nested Cursor::dispatch calls
327 // are possible which would change it
328 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
333 DispatchResult Cursor::result() const
339 BufferView & Cursor::bv() const
346 Buffer & Cursor::buffer() const
349 return bv_->buffer();
355 BOOST_ASSERT(depth() >= 1);
360 void Cursor::push(Inset & p)
362 push_back(CursorSlice(p));
366 void Cursor::pushBackward(Inset & p)
368 BOOST_ASSERT(!empty());
369 //lyxerr << "Entering inset " << t << " front" << endl;
375 bool Cursor::popBackward()
377 BOOST_ASSERT(!empty());
378 //lyxerr << "Leaving inset from in front" << endl;
379 inset().notifyCursorLeaves(*this);
387 bool Cursor::popForward()
389 BOOST_ASSERT(!empty());
390 //lyxerr << "Leaving inset from in back" << endl;
391 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
392 inset().notifyCursorLeaves(*this);
396 pos() += lastpos() - lp + 1;
401 int Cursor::currentMode()
403 BOOST_ASSERT(!empty());
404 for (int i = depth() - 1; i >= 0; --i) {
405 int res = operator[](i).inset().currentMode();
406 if (res != Inset::UNDECIDED_MODE)
409 return Inset::TEXT_MODE;
413 void Cursor::getPos(int & x, int & y) const
415 Point p = bv().getPos(*this, boundary());
421 Row const & Cursor::textRow() const
423 CursorSlice const & cs = innerTextSlice();
424 ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
425 BOOST_ASSERT(!pm.rows().empty());
426 return pm.getRow(pos(), boundary());
430 void Cursor::resetAnchor()
437 bool Cursor::posBackward()
446 bool Cursor::posForward()
448 if (pos() == lastpos())
455 CursorSlice Cursor::anchor() const
457 BOOST_ASSERT(anchor_.depth() >= depth());
458 CursorSlice normal = anchor_[depth() - 1];
459 if (depth() < anchor_.depth() && top() <= normal) {
460 // anchor is behind cursor -> move anchor behind the inset
467 CursorSlice Cursor::selBegin() const
471 return anchor() < top() ? anchor() : top();
475 CursorSlice Cursor::selEnd() const
479 return anchor() > top() ? anchor() : top();
483 DocIterator Cursor::selectionBegin() const
487 DocIterator di = (anchor() < top() ? anchor_ : *this);
493 DocIterator Cursor::selectionEnd() const
497 DocIterator di = (anchor() > top() ? anchor_ : *this);
498 if (di.depth() > depth()) {
506 void Cursor::setSelection()
509 // A selection with no contents is not a selection
510 // FIXME: doesnt look ok
511 if (pit() == anchor().pit() && pos() == anchor().pos())
516 void Cursor::setSelection(DocIterator const & where, int n)
525 void Cursor::clearSelection()
533 void Cursor::setTargetX(int x)
536 textTargetOffset_ = 0;
540 int Cursor::x_target() const
546 void Cursor::clearTargetX()
549 textTargetOffset_ = 0;
553 void Cursor::updateTextTargetOffset()
558 textTargetOffset_ = x - x_target_;
562 void Cursor::info(odocstream & os) const
564 for (int i = 1, n = depth(); i < n; ++i) {
565 operator[](i).inset().infoize(os);
569 Inset const * inset = prevInset();
570 // prevInset() can return 0 in certain case.
572 prevInset()->infoize2(os);
574 // overwite old message
579 bool Cursor::selHandle(bool sel)
581 //lyxerr << "Cursor::selHandle" << endl;
584 if (sel == selection())
588 cap::saveSelection(*this);
596 ostream & operator<<(ostream & os, Cursor const & cur)
598 os << "\n cursor: | anchor:\n";
599 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
600 os << " " << cur[i] << " | ";
601 if (i < cur.anchor_.depth())
602 os << cur.anchor_[i];
604 os << "-------------------------------";
607 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
608 os << "------------------------------- | " << cur.anchor_[i] << "\n";
610 os << " selection: " << cur.selection_
611 << " x_target: " << cur.x_target_ << endl;
616 LyXErr & operator<<(LyXErr & os, Cursor const & cur)
626 ///////////////////////////////////////////////////////////////////
629 // The part below is the non-integrated rest of the original math
630 // cursor. This should be either generalized for texted or moved
631 // back to mathed (in most cases to InsetMathNest).
633 ///////////////////////////////////////////////////////////////////
635 #include "mathed/InsetMathChar.h"
636 #include "mathed/InsetMathGrid.h"
637 #include "mathed/InsetMathScript.h"
638 #include "mathed/InsetMathUnknown.h"
639 #include "mathed/MathFactory.h"
640 #include "mathed/MathStream.h"
641 #include "mathed/MathSupport.h"
646 //#define FILEDEBUG 1
649 bool Cursor::isInside(Inset const * p) const
651 for (size_t i = 0; i != depth(); ++i)
652 if (&operator[](i).inset() == p)
658 void Cursor::leaveInset(Inset const & inset)
660 for (size_t i = 0; i != depth(); ++i) {
661 if (&operator[](i).inset() == &inset) {
669 bool Cursor::openable(MathAtom const & t) const
680 // we can't move into anything new during selection
681 if (depth() >= anchor_.depth())
683 if (t.nucleus() != &anchor_[depth()].inset())
690 void Cursor::setScreenPos(int x, int /*y*/)
693 //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
698 void Cursor::plainErase()
704 void Cursor::markInsert()
706 insert(char_type(0));
710 void Cursor::markErase()
716 void Cursor::plainInsert(MathAtom const & t)
718 cell().insert(pos(), t);
723 void Cursor::insert(docstring const & str)
725 for_each(str.begin(), str.end(),
726 boost::bind(static_cast<void(Cursor::*)(char_type)>
727 (&Cursor::insert), this, _1));
731 void Cursor::insert(char_type c)
733 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
734 BOOST_ASSERT(!empty());
736 cap::selClearOrDel(*this);
737 insert(new InsetMathChar(c));
739 text()->insertChar(*this, c);
744 void Cursor::insert(MathAtom const & t)
746 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
748 cap::selClearOrDel(*this);
753 void Cursor::insert(Inset * inset)
756 insert(MathAtom(inset));
758 text()->insertInset(*this, inset);
762 void Cursor::niceInsert(docstring const & t)
773 void Cursor::niceInsert(MathAtom const & t)
776 docstring const safe = cap::grabAndEraseSelection(*this);
778 // enter the new inset and move the contents of the selection if possible
781 // be careful here: don't use 'pushBackward(t)' as this we need to
782 // push the clone, not the original
783 pushBackward(*nextInset());
784 // We may not use niceInsert here (recursion)
792 void Cursor::insert(MathData const & ar)
796 cap::eraseSelection(*this);
797 cell().insert(pos(), ar);
802 bool Cursor::backspace()
804 autocorrect() = false;
807 cap::eraseSelection(*this);
812 // If empty cell, and not part of a big cell
813 if (lastpos() == 0 && inset().nargs() == 1) {
815 // Directly delete empty cell: [|[]] => [|]
821 // [|], can not delete from inside
833 InsetMathUnknown * p = activeMacro();
834 if (p->name().size() > 1) {
835 p->setName(p->name().substr(0, p->name().size() - 1));
840 if (pos() != 0 && prevAtom()->nargs() > 0) {
841 // let's require two backspaces for 'big stuff' and
842 // highlight on the first
856 autocorrect() = false;
861 cap::eraseSelection(*this);
865 // delete empty cells if possible
866 if (pos() == lastpos() && inset().idxDelete(idx()))
869 // special behaviour when in last position of cell
870 if (pos() == lastpos()) {
871 bool one_cell = inset().nargs() == 1;
872 if (one_cell && lastpos() == 0) {
874 // Directly delete empty cell: [|[]] => [|]
880 // [|], can not delete from inside
885 inset().idxGlue(idx());
889 // 'clever' UI hack: only erase large items if previously slected
890 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
905 DocIterator save = *this;
906 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
908 if (disp_.dispatched())
911 autocorrect() = false;
919 DocIterator save = *this;
920 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
922 if (disp_.dispatched())
925 autocorrect() = false;
930 bool Cursor::macroModeClose()
934 InsetMathUnknown * p = activeMacro();
936 docstring const s = p->name();
940 // do nothing if the macro name is empty
944 // trigger updates of macros, at least, if no full
945 // updates take place anyway
946 updateFlags(Update::Force);
948 docstring const name = s.substr(1);
949 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
950 if (in && in->interpretString(*this, s))
952 MathAtom atom = createInsetMath(name);
953 MathMacro * atomAsMacro = atom.nucleus()->asMacro();
955 // make non-greedy, i.e. don't eat parameters from the right
956 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT);
963 docstring Cursor::macroName()
965 return inMacroMode() ? activeMacro()->name() : docstring();
969 void Cursor::handleNest(MathAtom const & a, int c)
971 //lyxerr << "Cursor::handleNest: " << c << endl;
973 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
976 pushBackward(*nextInset());
980 int Cursor::targetX() const
982 if (x_target() != -1)
991 int Cursor::textTargetOffset() const
993 return textTargetOffset_;
997 void Cursor::setTargetX()
1006 bool Cursor::inMacroMode() const
1012 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1013 return p && !p->final();
1017 InsetMathUnknown * Cursor::activeMacro()
1019 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1023 void Cursor::pullArg()
1026 MathData ar = cell();
1027 if (popBackward() && inMathed()) {
1029 cell().insert(pos(), ar);
1032 //formula()->mutateToText();
1037 void Cursor::touch()
1041 DocIterator::const_iterator it = begin();
1042 DocIterator::const_iterator et = end();
1043 for ( ; it != et; ++it)
1049 void Cursor::normalize()
1051 if (idx() > lastidx()) {
1052 lyxerr << "this should not really happen - 1: "
1053 << idx() << ' ' << nargs()
1054 << " in: " << &inset() << endl;
1058 if (pos() > lastpos()) {
1059 lyxerr << "this should not really happen - 2: "
1060 << pos() << ' ' << lastpos() << " in idx: " << idx()
1062 odocstringstream os;
1063 WriteStream wi(os, false, true);
1064 inset().asInsetMath()->write(wi);
1065 lyxerr << to_utf8(os.str()) << endl;
1071 bool Cursor::upDownInMath(bool up)
1073 // Be warned: The 'logic' implemented in this function is highly
1074 // fragile. A distance of one pixel or a '<' vs '<=' _really
1075 // matters. So fiddle around with it only if you think you know
1076 // what you are doing!
1080 xo = theLyXFunc().cursorBeforeDispatchX();
1082 // check if we had something else in mind, if not, this is the future
1084 if (x_target_ == -1)
1086 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1087 // In text mode inside the line (not left or right) possibly set a new target_x,
1088 // but only if we are somewhere else than the previous target-offset.
1090 // We want to keep the x-target on subsequent up/down movements
1091 // that cross beyond the end of short lines. Thus a special
1092 // handling when the cursor is at the end of line: Use the new
1093 // x-target only if the old one was before the end of line
1094 // or the old one was after the beginning of the line
1095 bool inRTL = isWithinRtlParagraph(*this);
1099 left = pos() == textRow().endpos();
1100 right = pos() == textRow().pos();
1102 left = pos() == textRow().pos();
1103 right = pos() == textRow().endpos();
1105 if ((!left && !right) ||
1106 (left && !right && xo < x_target_) ||
1107 (!left && right && x_target_ < xo))
1114 // try neigbouring script insets
1116 if (inMathed() && !selection()) {
1119 InsetMathScript const * p = prevAtom()->asScriptInset();
1120 if (p && p->has(up)) {
1122 push(*const_cast<InsetMathScript*>(p));
1123 idx() = p->idxOfScript(up);
1126 // we went in the right direction? Otherwise don't jump into the script
1130 int oy = theLyXFunc().cursorBeforeDispatchY();
1131 if ((!up && y <= oy) ||
1140 if (pos() != lastpos()) {
1141 InsetMathScript const * p = nextAtom()->asScriptInset();
1142 if (p && p->has(up)) {
1143 push(*const_cast<InsetMathScript*>(p));
1144 idx() = p->idxOfScript(up);
1147 // we went in the right direction? Otherwise don't jump into the script
1151 int oy = theLyXFunc().cursorBeforeDispatchY();
1152 if ((!up && y <= oy) ||
1161 // try to find an inset that knows better then we,
1162 if (inset().idxUpDown(*this, up)) {
1163 //lyxerr << "idxUpDown triggered" << endl;
1164 // try to find best position within this inset
1166 setCursor(bruteFind2(*this, xo, yo));
1170 // any improvement going just out of inset?
1171 if (popBackward() && inMathed()) {
1172 //lyxerr << "updown: popBackward succeeded" << endl;
1175 int yold = theLyXFunc().cursorBeforeDispatchY();
1177 if (up ? ynew < yold : ynew > yold)
1181 // no success, we are probably at the document top or bottom
1187 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1189 BOOST_ASSERT(text());
1195 xo = theLyXFunc().cursorBeforeDispatchX();
1197 // update the targetX - this is here before the "return false"
1198 // to set a new target which can be used by InsetTexts above
1199 // if we cannot move up/down inside this inset anymore
1200 if (x_target_ == -1)
1202 else if (xo - textTargetOffset() != x_target() &&
1203 depth() == beforeDispatchCursor_.depth()) {
1204 // In text mode inside the line (not left or right) possibly set a new target_x,
1205 // but only if we are somewhere else than the previous target-offset.
1207 // We want to keep the x-target on subsequent up/down movements
1208 // that cross beyond the end of short lines. Thus a special
1209 // handling when the cursor is at the end of line: Use the new
1210 // x-target only if the old one was before the end of line
1211 // or the old one was after the beginning of the line
1212 bool inRTL = isWithinRtlParagraph(*this);
1216 left = pos() == textRow().endpos();
1217 right = pos() == textRow().pos();
1219 left = pos() == textRow().pos();
1220 right = pos() == textRow().endpos();
1222 if ((!left && !right) ||
1223 (left && !right && xo < x_target_) ||
1224 (!left && right && x_target_ < xo))
1231 // first get the current line
1232 TextMetrics & tm = bv_->textMetrics(text());
1233 ParagraphMetrics const & pm = tm.parMetrics(pit());
1235 if (pos() && boundary())
1236 row = pm.pos2row(pos() - 1);
1238 row = pm.pos2row(pos());
1240 // are we not at the start or end?
1242 if (pit() == 0 && row == 0)
1245 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1246 row + 1 >= int(pm.rows().size()))
1250 // with and without selection are handled differently
1252 int yo = bv().getPos(*this, boundary()).y_;
1254 // To next/previous row
1256 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1258 tm.editXY(*this, xo, yo + textRow().descent() + 1);
1261 // This happens when you move out of an inset.
1262 // And to give the DEPM the possibility of doing
1263 // something we must provide it with two different
1265 Cursor dummy = *this;
1268 if (bv().checkDepm(dummy, old)) {
1269 updateNeeded = true;
1270 // Make sure that cur gets back whatever happened to dummy(Lgb)
1274 // if there is a selection, we stay out of any inset, and just jump to the right position:
1278 top().pos() = min(tm.x2pos(pit(), row - 1, xo), top().lastpos());
1279 } else if (pit() > 0) {
1281 ParagraphMetrics const & pmcur = bv_->parMetrics(text(), pit());
1282 top().pos() = min(tm.x2pos(pit(), pmcur.rows().size() - 1, xo), top().lastpos());
1285 if (row + 1 < int(pm.rows().size())) {
1286 top().pos() = min(tm.x2pos(pit(), row + 1, xo), top().lastpos());
1287 } else if (pit() + 1 < int(text()->paragraphs().size())) {
1289 top().pos() = min(tm.x2pos(pit(), 0, xo), top().lastpos());
1293 updateNeeded |= bv().checkDepm(*this, old);
1296 updateTextTargetOffset();
1301 void Cursor::handleFont(string const & font)
1303 LYXERR(Debug::DEBUG, font);
1307 safe = cap::grabAndEraseSelection(*this);
1310 if (lastpos() != 0) {
1311 // something left in the cell
1313 // cursor in first position
1315 } else if (pos() == lastpos()) {
1316 // cursor in last position
1319 // cursor in between. split cell
1320 MathData::iterator bt = cell().begin();
1321 MathAtom at = createInsetMath(from_utf8(font));
1322 at.nucleus()->cell(0) = MathData(bt, bt + pos());
1323 cell().erase(bt, bt + pos());
1328 // nothing left in the cell
1336 void Cursor::message(docstring const & msg) const
1338 theLyXFunc().setMessage(msg);
1342 void Cursor::errorMessage(docstring const & msg) const
1344 theLyXFunc().setErrorMessage(msg);
1348 docstring Cursor::selectionAsString(bool label) const
1354 Buffer const & buffer = bv().buffer();
1355 ParagraphList const & pars = text()->paragraphs();
1357 // should be const ...
1358 pit_type startpit = selBegin().pit();
1359 pit_type endpit = selEnd().pit();
1360 size_t const startpos = selBegin().pos();
1361 size_t const endpos = selEnd().pos();
1363 if (startpit == endpit)
1364 return pars[startpit].asString(buffer, startpos, endpos, label);
1366 // First paragraph in selection
1367 docstring result = pars[startpit].
1368 asString(buffer, startpos, pars[startpit].size(), label)
1369 + parbreak(pars[startpit]);
1371 // The paragraphs in between (if any)
1372 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1373 Paragraph const & par = pars[pit];
1374 result += par.asString(buffer, 0, par.size(), label)
1375 + parbreak(pars[pit]);
1378 // Last paragraph in selection
1379 result += pars[endpit].asString(buffer, 0, endpos, label);
1385 return cap::grabSelection(*this);
1391 docstring Cursor::currentState()
1394 odocstringstream os;
1400 return text()->currentState(*this);
1406 docstring Cursor::getPossibleLabel()
1408 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
1412 Encoding const * Cursor::getEncoding() const
1417 // go up until first non-0 text is hit
1418 // (innermost text is 0 in mathed)
1419 for (s = depth() - 1; s >= 0; --s)
1420 if (operator[](s).text())
1422 CursorSlice const & sl = operator[](s);
1423 Text const & text = *sl.text();
1424 Font font = text.getPar(sl.pit()).getFont(
1425 bv().buffer().params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1426 return font.language()->encoding();
1430 void Cursor::undispatched()
1432 disp_.dispatched(false);
1436 void Cursor::dispatched()
1438 disp_.dispatched(true);
1442 void Cursor::updateFlags(Update::flags f)
1448 void Cursor::noUpdate()
1450 disp_.update(Update::None);
1454 Font Cursor::getFont() const
1456 // The logic here should more or less match to the Cursor::setCurrentFont
1457 // logic, i.e. the cursor height should give a hint what will happen
1458 // if a character is entered.
1460 // HACK. far from being perfect...
1461 // go up until first non-0 text is hit
1462 // (innermost text is 0 in mathed)
1464 for (s = depth() - 1; s >= 0; --s)
1465 if (operator[](s).text())
1467 CursorSlice const & sl = operator[](s);
1468 Text const & text = *sl.text();
1469 Paragraph const & par = text.getPar(sl.pit());
1471 // on boundary, so we are really at the character before
1472 pos_type pos = sl.pos();
1473 if (pos > 0 && boundary())
1476 // on space? Take the font before (only for RTL boundary stay)
1478 TextMetrics const & tm = bv().textMetrics(&text);
1479 if (pos == sl.lastpos()
1480 || (par.isSeparator(pos)
1481 && !tm.isRTLBoundary(sl.pit(), pos)))
1485 // get font at the position
1486 Font font = par.getFont(bv().buffer().params(), pos,
1487 outerFont(sl.pit(), text.paragraphs()));
1493 bool Cursor::fixIfBroken()
1495 if (DocIterator::fixIfBroken()) {
1504 bool notifyCursorLeaves(DocIterator const & old, Cursor & cur)
1506 // find inset in common
1508 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
1509 if (&old.inset() != &cur.inset())
1513 // notify everything on top of the common part in old cursor,
1514 // but stop if the inset claims the cursor to be invalid now
1515 for (; i < old.depth(); ++i) {
1516 if (old[i].inset().notifyCursorLeaves(cur))
1524 void Cursor::setCurrentFont()
1526 CursorSlice const & cs = innerTextSlice();
1527 Paragraph const & par = cs.paragraph();
1528 pos_type cpit = cs.pit();
1529 pos_type cpos = cs.pos();
1530 Text const & ctext = *cs.text();
1531 TextMetrics const & tm = bv().textMetrics(&ctext);
1533 // are we behind previous char in fact? -> go to that char
1534 if (cpos > 0 && boundary())
1537 // find position to take the font from
1539 // paragraph end? -> font of last char
1540 if (cpos == lastpos())
1542 // on space? -> look at the words in front of space
1543 else if (cpos > 0 && par.isSeparator(cpos)) {
1544 // abc| def -> font of c
1545 // abc |[WERBEH], i.e. boundary==true -> font of c
1546 // abc [WERBEH]| def, font of the space
1547 if (!tm.isRTLBoundary(cpit, cpos))
1553 BufferParams const & bufparams = buffer().params();
1554 current_font = par.getFontSettings(bufparams, cpos);
1555 real_current_font = tm.getDisplayFont(cpit, cpos);
1557 // special case for paragraph end
1558 if (cs.pos() == lastpos()
1559 && tm.isRTLBoundary(cpit, cs.pos())
1561 Language const * lang = par.getParLanguage(bufparams);
1562 current_font.setLanguage(lang);
1563 current_font.fontInfo().setNumber(FONT_OFF);
1564 real_current_font.setLanguage(lang);
1565 real_current_font.fontInfo().setNumber(FONT_OFF);
1570 bool Cursor::textUndo()
1572 DocIterator dit = *this;
1573 // Undo::textUndo() will modify dit.
1574 if (!bv_->buffer().undo().textUndo(dit))
1578 selection() = false;
1585 bool Cursor::textRedo()
1587 DocIterator dit = *this;
1588 // Undo::textRedo() will modify dit.
1589 if (!bv_->buffer().undo().textRedo(dit))
1593 selection() = false;
1600 void Cursor::finishUndo()
1602 bv_->buffer().undo().finishUndo();
1606 void Cursor::recordUndo(UndoKind kind, pit_type from, pit_type to)
1608 bv_->buffer().undo().recordUndo(*this, kind, from, to);
1612 void Cursor::recordUndo(UndoKind kind, pit_type from)
1614 bv_->buffer().undo().recordUndo(*this, kind, from);
1618 void Cursor::recordUndo(UndoKind kind)
1620 bv_->buffer().undo().recordUndo(*this, kind);
1624 void Cursor::recordUndoInset(UndoKind kind)
1626 bv_->buffer().undo().recordUndoInset(*this, kind);
1630 void Cursor::recordUndoFullDocument()
1632 bv_->buffer().undo().recordUndoFullDocument(*this);
1636 void Cursor::recordUndoSelection()
1638 bv_->buffer().undo().recordUndo(*this, ATOMIC_UNDO,
1639 selBegin().pit(), selEnd().pit());
1643 void Cursor::checkBufferStructure()
1645 if (paragraph().layout()->toclevel == Layout::NOT_IN_TOC)
1647 Buffer const * master = buffer().masterBuffer();
1648 master->tocBackend().updateItem(ParConstIterator(*this));
1649 master->structureChanged();