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"
22 #include "DispatchResult.h"
24 #include "FuncRequest.h"
28 #include "LyXFunc.h" // only for setMessage()
32 #include "Paragraph.h"
33 #include "paragraph_funcs.h"
34 #include "ParIterator.h"
35 #include "TextMetrics.h"
37 #include "support/debug.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>
62 bool positionable(DocIterator const & cursor, DocIterator const & anchor)
64 // avoid deeper nested insets when selecting
65 if (cursor.depth() > anchor.depth())
68 // anchor might be deeper, should have same path then
69 for (size_t i = 0; i < cursor.depth(); ++i)
70 if (&cursor[i].inset() != &anchor[i].inset())
73 // position should be ok.
78 // Find position closest to (x, y) in cell given by iter.
79 // Used only in mathed
80 DocIterator bruteFind2(Cursor const & c, int x, int y)
82 double best_dist = numeric_limits<double>::max();
89 et.top().pos() = et.top().asInsetMath()->cell(et.top().idx()).size();
90 for (size_t i = 0;; ++i) {
93 Inset const * inset = &it.inset();
94 map<Inset const *, Geometry> const & data =
95 c.bv().coordCache().getInsets().getData();
96 map<Inset const *, Geometry>::const_iterator I = data.find(inset);
98 // FIXME: in the case where the inset is not in the cache, this
99 // means that no part of it is visible on screen. In this case
100 // we don't do elaborate search and we just return the forwarded
101 // DocIterator at its beginning.
102 if (I == data.end()) {
107 Point o = I->second.pos;
108 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
109 // Convert to absolute
112 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
113 // '<=' in order to take the last possible position
114 // this is important for clicking behind \sum in e.g. '\sum_i a'
115 LYXERR(Debug::DEBUG, "i: " << i << " d: " << d
116 << " best: " << best_dist);
117 if (d <= best_dist) {
130 /// moves position closest to (x, y) in given box
131 bool bruteFind(Cursor & cursor,
132 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
134 BOOST_ASSERT(!cursor.empty());
135 Inset & inset = cursor[0].inset();
136 BufferView & bv = cursor.bv();
138 CoordCache::InnerParPosCache const & cache =
139 bv.coordCache().getParPos().find(cursor.bottom().text())->second;
140 // Get an iterator on the first paragraph in the cache
141 DocIterator it(inset);
142 it.push_back(CursorSlice(inset));
143 it.pit() = cache.begin()->first;
144 // Get an iterator after the last paragraph in the cache
145 DocIterator et(inset);
146 et.push_back(CursorSlice(inset));
147 et.pit() = boost::prior(cache.end())->first;
148 if (et.pit() >= et.lastpit())
149 et = doc_iterator_end(inset);
153 double best_dist = numeric_limits<double>::max();;
154 DocIterator best_cursor = et;
156 for ( ; it != et; it.forwardPos(true)) {
157 // avoid invalid nesting when selecting
158 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
159 Point p = bv.getPos(it, false);
162 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
163 double const dx = xo - x;
164 double const dy = yo - y;
165 double const d = dx * dx + dy * dy;
166 // '<=' in order to take the last possible position
167 // this is important for clicking behind \sum in e.g. '\sum_i a'
168 if (d <= best_dist) {
169 // lyxerr << "*" << endl;
177 if (best_cursor != et) {
178 cursor.setCursor(best_cursor);
187 /// moves position closest to (x, y) in given box
188 bool bruteFind3(Cursor & cur, int x, int y, bool up)
190 BufferView & bv = cur.bv();
191 int ylow = up ? 0 : y + 1;
192 int yhigh = up ? y - 1 : bv.workHeight();
194 int xhigh = bv.workWidth();
196 // FIXME: bit more work needed to get 'from' and 'to' right.
197 pit_type from = cur.bottom().pit();
198 //pit_type to = cur.bottom().pit();
199 //lyxerr << "Pit start: " << from << endl;
201 //lyxerr << "bruteFind3: x: " << x << " y: " << y
202 // << " xlow: " << xlow << " xhigh: " << xhigh
203 // << " ylow: " << ylow << " yhigh: " << yhigh
205 Inset & inset = bv.buffer().inset();
206 DocIterator it = doc_iterator_begin(inset);
208 DocIterator et = doc_iterator_end(inset);
210 double best_dist = numeric_limits<double>::max();
211 DocIterator best_cursor = et;
213 for ( ; it != et; it.forwardPos()) {
214 // avoid invalid nesting when selecting
215 if (bv.cursorStatus(it) == CUR_INSIDE
216 && (!cur.selection() || positionable(it, cur.anchor_))) {
217 Point p = bv.getPos(it, false);
220 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
221 double const dx = xo - x;
222 double const dy = yo - y;
223 double const d = dx * dx + dy * dy;
224 //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
225 // << " dx: " << dx << " dy: " << dy
226 // << " idx: " << it.idx() << " pos: " << it.pos()
229 // '<=' in order to take the last possible position
230 // this is important for clicking behind \sum in e.g. '\sum_i a'
231 if (d <= best_dist) {
232 //lyxerr << "*" << endl;
240 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
241 if (best_cursor == et)
243 cur.setCursor(best_cursor);
247 docstring parbreak(Paragraph const & par)
249 odocstringstream ods;
251 // only add blank line if we're not in an ERT or Listings inset
252 if (par.ownerCode() != ERT_CODE
253 && par.ownerCode() != LISTINGS_CODE)
261 // be careful: this is called from the bv's constructor, too, so
262 // bv functions are not yet available!
263 Cursor::Cursor(BufferView & bv)
264 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1), textTargetOffset_(0),
265 selection_(false), mark_(false), logicalpos_(false),
266 current_font(inherit_font)
270 void Cursor::reset(Inset & inset)
273 push_back(CursorSlice(inset));
274 anchor_ = DocIterator(inset);
281 // this (intentionally) does neither touch anchor nor selection status
282 void Cursor::setCursor(DocIterator const & cur)
284 DocIterator::operator=(cur);
288 void Cursor::dispatch(FuncRequest const & cmd0)
290 LYXERR(Debug::DEBUG, "cmd: " << cmd0 << '\n' << *this);
295 FuncRequest cmd = cmd0;
298 // store some values to be used inside of the handlers
299 beforeDispatchCursor_ = *this;
300 for (; depth(); pop()) {
301 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
302 << cmd0 << endl << *this);
303 BOOST_ASSERT(pos() <= lastpos());
304 BOOST_ASSERT(idx() <= lastidx());
305 BOOST_ASSERT(pit() <= lastpit());
307 // The common case is 'LFUN handled, need update', so make the
308 // LFUN handler's life easier by assuming this as default value.
309 // The handler can reset the update and val flags if necessary.
310 disp_.update(Update::FitCursor | Update::Force);
311 disp_.dispatched(true);
312 inset().dispatch(*this, cmd);
313 if (disp_.dispatched())
317 // it completely to get a 'bomb early' behaviour in case this
318 // object will be used again.
319 if (!disp_.dispatched()) {
320 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
322 disp_.update(Update::None);
323 disp_.dispatched(false);
325 // restore the previous one because nested Cursor::dispatch calls
326 // are possible which would change it
327 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
332 DispatchResult Cursor::result() const
338 BufferView & Cursor::bv() const
345 Buffer & Cursor::buffer() const
348 return bv_->buffer();
354 BOOST_ASSERT(depth() >= 1);
359 void Cursor::push(Inset & p)
361 push_back(CursorSlice(p));
365 void Cursor::pushBackward(Inset & p)
367 BOOST_ASSERT(!empty());
368 //lyxerr << "Entering inset " << t << " front" << endl;
374 bool Cursor::popBackward()
376 BOOST_ASSERT(!empty());
377 //lyxerr << "Leaving inset from in front" << endl;
378 inset().notifyCursorLeaves(*this);
386 bool Cursor::popForward()
388 BOOST_ASSERT(!empty());
389 //lyxerr << "Leaving inset from in back" << endl;
390 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
391 inset().notifyCursorLeaves(*this);
395 pos() += lastpos() - lp + 1;
400 int Cursor::currentMode()
402 BOOST_ASSERT(!empty());
403 for (int i = depth() - 1; i >= 0; --i) {
404 int res = operator[](i).inset().currentMode();
405 if (res != Inset::UNDECIDED_MODE)
408 return Inset::TEXT_MODE;
412 void Cursor::getPos(int & x, int & y) const
414 Point p = bv().getPos(*this, boundary());
420 Row const & Cursor::textRow() const
422 ParagraphMetrics const & pm = bv().parMetrics(text(), pit());
423 BOOST_ASSERT(!pm.rows().empty());
424 return pm.getRow(pos(), boundary());
428 void Cursor::resetAnchor()
435 bool Cursor::posBackward()
444 bool Cursor::posForward()
446 if (pos() == lastpos())
453 CursorSlice Cursor::anchor() const
455 BOOST_ASSERT(anchor_.depth() >= depth());
456 CursorSlice normal = anchor_[depth() - 1];
457 if (depth() < anchor_.depth() && top() <= normal) {
458 // anchor is behind cursor -> move anchor behind the inset
465 CursorSlice Cursor::selBegin() const
469 return anchor() < top() ? anchor() : top();
473 CursorSlice Cursor::selEnd() const
477 return anchor() > top() ? anchor() : top();
481 DocIterator Cursor::selectionBegin() const
485 DocIterator di = (anchor() < top() ? anchor_ : *this);
491 DocIterator Cursor::selectionEnd() const
495 DocIterator di = (anchor() > top() ? anchor_ : *this);
496 if (di.depth() > depth()) {
504 void Cursor::setSelection()
507 // A selection with no contents is not a selection
508 // FIXME: doesnt look ok
509 if (pit() == anchor().pit() && pos() == anchor().pos())
514 void Cursor::setSelection(DocIterator const & where, int n)
523 void Cursor::clearSelection()
531 void Cursor::setTargetX(int x)
534 textTargetOffset_ = 0;
538 int Cursor::x_target() const
544 void Cursor::clearTargetX()
547 textTargetOffset_ = 0;
551 void Cursor::updateTextTargetOffset()
556 textTargetOffset_ = x - x_target_;
560 void Cursor::info(odocstream & os) const
562 for (int i = 1, n = depth(); i < n; ++i) {
563 operator[](i).inset().infoize(os);
567 Inset const * inset = prevInset();
568 // prevInset() can return 0 in certain case.
570 prevInset()->infoize2(os);
572 // overwite old message
577 bool Cursor::selHandle(bool sel)
579 //lyxerr << "Cursor::selHandle" << endl;
582 if (sel == selection())
586 cap::saveSelection(*this);
594 ostream & operator<<(ostream & os, Cursor const & cur)
596 os << "\n cursor: | anchor:\n";
597 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
598 os << " " << cur[i] << " | ";
599 if (i < cur.anchor_.depth())
600 os << cur.anchor_[i];
602 os << "-------------------------------";
605 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
606 os << "------------------------------- | " << cur.anchor_[i] << "\n";
608 os << " selection: " << cur.selection_
609 << " x_target: " << cur.x_target_ << endl;
614 LyXErr & operator<<(LyXErr & os, Cursor const & cur)
624 ///////////////////////////////////////////////////////////////////
627 // The part below is the non-integrated rest of the original math
628 // cursor. This should be either generalized for texted or moved
629 // back to mathed (in most cases to InsetMathNest).
631 ///////////////////////////////////////////////////////////////////
633 #include "mathed/InsetMathChar.h"
634 #include "mathed/InsetMathGrid.h"
635 #include "mathed/InsetMathScript.h"
636 #include "mathed/InsetMathUnknown.h"
637 #include "mathed/MathFactory.h"
638 #include "mathed/MathStream.h"
639 #include "mathed/MathSupport.h"
644 //#define FILEDEBUG 1
647 bool Cursor::isInside(Inset const * p)
649 for (size_t i = 0; i != depth(); ++i)
650 if (&operator[](i).inset() == p)
656 void Cursor::leaveInset(Inset const & inset)
658 for (size_t i = 0; i != depth(); ++i) {
659 if (&operator[](i).inset() == &inset) {
667 bool Cursor::openable(MathAtom const & t) const
678 // we can't move into anything new during selection
679 if (depth() >= anchor_.depth())
681 if (t.nucleus() != &anchor_[depth()].inset())
688 void Cursor::setScreenPos(int x, int /*y*/)
691 //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
696 void Cursor::plainErase()
702 void Cursor::markInsert()
704 insert(char_type(0));
708 void Cursor::markErase()
714 void Cursor::plainInsert(MathAtom const & t)
716 cell().insert(pos(), t);
721 void Cursor::insert(docstring const & str)
723 for_each(str.begin(), str.end(),
724 boost::bind(static_cast<void(Cursor::*)(char_type)>
725 (&Cursor::insert), this, _1));
729 void Cursor::insert(char_type c)
731 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
732 BOOST_ASSERT(!empty());
734 cap::selClearOrDel(*this);
735 insert(new InsetMathChar(c));
737 text()->insertChar(*this, c);
742 void Cursor::insert(MathAtom const & t)
744 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
746 cap::selClearOrDel(*this);
751 void Cursor::insert(Inset * inset)
754 insert(MathAtom(inset));
756 text()->insertInset(*this, inset);
760 void Cursor::niceInsert(docstring const & t)
771 void Cursor::niceInsert(MathAtom const & t)
774 docstring const safe = cap::grabAndEraseSelection(*this);
776 // enter the new inset and move the contents of the selection if possible
779 // be careful here: don't use 'pushBackward(t)' as this we need to
780 // push the clone, not the original
781 pushBackward(*nextInset());
782 // We may not use niceInsert here (recursion)
790 void Cursor::insert(MathData const & ar)
794 cap::eraseSelection(*this);
795 cell().insert(pos(), ar);
800 bool Cursor::backspace()
802 autocorrect() = false;
805 cap::eraseSelection(*this);
810 // If empty cell, and not part of a big cell
811 if (lastpos() == 0 && inset().nargs() == 1) {
813 // Directly delete empty cell: [|[]] => [|]
819 // [|], can not delete from inside
831 InsetMathUnknown * p = activeMacro();
832 if (p->name().size() > 1) {
833 p->setName(p->name().substr(0, p->name().size() - 1));
838 if (pos() != 0 && prevAtom()->nargs() > 0) {
839 // let's require two backspaces for 'big stuff' and
840 // highlight on the first
854 autocorrect() = false;
859 cap::eraseSelection(*this);
863 // delete empty cells if possible
864 if (pos() == lastpos() && inset().idxDelete(idx()))
867 // special behaviour when in last position of cell
868 if (pos() == lastpos()) {
869 bool one_cell = inset().nargs() == 1;
870 if (one_cell && lastpos() == 0) {
872 // Directly delete empty cell: [|[]] => [|]
878 // [|], can not delete from inside
883 inset().idxGlue(idx());
887 // 'clever' UI hack: only erase large items if previously slected
888 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
903 DocIterator save = *this;
904 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
906 if (disp_.dispatched())
909 autocorrect() = false;
917 DocIterator save = *this;
918 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
920 if (disp_.dispatched())
923 autocorrect() = false;
928 bool Cursor::macroModeClose()
932 InsetMathUnknown * p = activeMacro();
934 docstring const s = p->name();
938 // do nothing if the macro name is empty
942 // trigger updates of macros, at least, if no full
943 // updates take place anyway
944 updateFlags(Update::Force);
946 docstring const name = s.substr(1);
947 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
948 if (in && in->interpretString(*this, s))
950 MathAtom atom = createInsetMath(name);
951 MathMacro * atomAsMacro = atom.nucleus()->asMacro();
953 // make non-greedy, i.e. don't eat parameters from the right
954 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT);
961 docstring Cursor::macroName()
963 return inMacroMode() ? activeMacro()->name() : docstring();
967 void Cursor::handleNest(MathAtom const & a, int c)
969 //lyxerr << "Cursor::handleNest: " << c << endl;
971 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
974 pushBackward(*nextInset());
978 int Cursor::targetX() const
980 if (x_target() != -1)
989 int Cursor::textTargetOffset() const
991 return textTargetOffset_;
995 void Cursor::setTargetX()
1004 bool Cursor::inMacroMode() const
1010 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1011 return p && !p->final();
1015 InsetMathUnknown * Cursor::activeMacro()
1017 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1021 void Cursor::pullArg()
1024 MathData ar = cell();
1025 if (popBackward() && inMathed()) {
1027 cell().insert(pos(), ar);
1030 //formula()->mutateToText();
1035 void Cursor::touch()
1039 DocIterator::const_iterator it = begin();
1040 DocIterator::const_iterator et = end();
1041 for ( ; it != et; ++it)
1047 void Cursor::normalize()
1049 if (idx() > lastidx()) {
1050 lyxerr << "this should not really happen - 1: "
1051 << idx() << ' ' << nargs()
1052 << " in: " << &inset() << endl;
1056 if (pos() > lastpos()) {
1057 lyxerr << "this should not really happen - 2: "
1058 << pos() << ' ' << lastpos() << " in idx: " << idx()
1060 odocstringstream os;
1061 WriteStream wi(os, false, true);
1062 inset().asInsetMath()->write(wi);
1063 lyxerr << to_utf8(os.str()) << endl;
1069 bool Cursor::upDownInMath(bool up)
1071 // Be warned: The 'logic' implemented in this function is highly
1072 // fragile. A distance of one pixel or a '<' vs '<=' _really
1073 // matters. So fiddle around with it only if you think you know
1074 // what you are doing!
1078 xo = theLyXFunc().cursorBeforeDispatchX();
1080 // check if we had something else in mind, if not, this is the future
1082 if (x_target_ == -1)
1084 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1085 // In text mode inside the line (not left or right) possibly set a new target_x,
1086 // but only if we are somewhere else than the previous target-offset.
1088 // We want to keep the x-target on subsequent up/down movements
1089 // that cross beyond the end of short lines. Thus a special
1090 // handling when the cursor is at the end of line: Use the new
1091 // x-target only if the old one was before the end of line
1092 // or the old one was after the beginning of the line
1093 bool inRTL = isWithinRtlParagraph(*this);
1097 left = pos() == textRow().endpos();
1098 right = pos() == textRow().pos();
1100 left = pos() == textRow().pos();
1101 right = pos() == textRow().endpos();
1103 if ((!left && !right) ||
1104 (left && !right && xo < x_target_) ||
1105 (!left && right && x_target_ < xo))
1112 // try neigbouring script insets
1114 if (inMathed() && !selection()) {
1117 InsetMathScript const * p = prevAtom()->asScriptInset();
1118 if (p && p->has(up)) {
1120 push(*const_cast<InsetMathScript*>(p));
1121 idx() = p->idxOfScript(up);
1124 // we went in the right direction? Otherwise don't jump into the script
1128 int oy = theLyXFunc().cursorBeforeDispatchY();
1129 if ((!up && y <= oy) ||
1138 if (pos() != lastpos()) {
1139 InsetMathScript const * p = nextAtom()->asScriptInset();
1140 if (p && p->has(up)) {
1141 push(*const_cast<InsetMathScript*>(p));
1142 idx() = p->idxOfScript(up);
1145 // we went in the right direction? Otherwise don't jump into the script
1149 int oy = theLyXFunc().cursorBeforeDispatchY();
1150 if ((!up && y <= oy) ||
1159 // try to find an inset that knows better then we,
1160 if (inset().idxUpDown(*this, up)) {
1161 //lyxerr << "idxUpDown triggered" << endl;
1162 // try to find best position within this inset
1164 setCursor(bruteFind2(*this, xo, yo));
1168 // any improvement going just out of inset?
1169 if (popBackward() && inMathed()) {
1170 //lyxerr << "updown: popBackward succeeded" << endl;
1173 int yold = theLyXFunc().cursorBeforeDispatchY();
1175 if (up ? ynew < yold : ynew > yold)
1179 // no success, we are probably at the document top or bottom
1185 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1187 BOOST_ASSERT(text());
1193 xo = theLyXFunc().cursorBeforeDispatchX();
1195 // update the targetX - this is here before the "return false"
1196 // to set a new target which can be used by InsetTexts above
1197 // if we cannot move up/down inside this inset anymore
1198 if (x_target_ == -1)
1200 else if (xo - textTargetOffset() != x_target() &&
1201 depth() == beforeDispatchCursor_.depth()) {
1202 // In text mode inside the line (not left or right) possibly set a new target_x,
1203 // but only if we are somewhere else than the previous target-offset.
1205 // We want to keep the x-target on subsequent up/down movements
1206 // that cross beyond the end of short lines. Thus a special
1207 // handling when the cursor is at the end of line: Use the new
1208 // x-target only if the old one was before the end of line
1209 // or the old one was after the beginning of the line
1210 bool inRTL = isWithinRtlParagraph(*this);
1214 left = pos() == textRow().endpos();
1215 right = pos() == textRow().pos();
1217 left = pos() == textRow().pos();
1218 right = pos() == textRow().endpos();
1220 if ((!left && !right) ||
1221 (left && !right && xo < x_target_) ||
1222 (!left && right && x_target_ < xo))
1229 // first get the current line
1230 TextMetrics & tm = bv_->textMetrics(text());
1231 ParagraphMetrics const & pm = tm.parMetrics(pit());
1233 if (pos() && boundary())
1234 row = pm.pos2row(pos() - 1);
1236 row = pm.pos2row(pos());
1238 // are we not at the start or end?
1240 if (pit() == 0 && row == 0)
1243 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1244 row + 1 >= int(pm.rows().size()))
1248 // with and without selection are handled differently
1250 int yo = bv().getPos(*this, boundary()).y_;
1252 // To next/previous row
1254 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1256 tm.editXY(*this, xo, yo + textRow().descent() + 1);
1259 // This happens when you move out of an inset.
1260 // And to give the DEPM the possibility of doing
1261 // something we must provide it with two different
1263 Cursor dummy = *this;
1266 if (bv().checkDepm(dummy, old)) {
1267 updateNeeded = true;
1268 // Make sure that cur gets back whatever happened to dummy(Lgb)
1272 // if there is a selection, we stay out of any inset, and just jump to the right position:
1276 top().pos() = min(tm.x2pos(pit(), row - 1, xo), top().lastpos());
1277 } else if (pit() > 0) {
1279 ParagraphMetrics const & pmcur = bv_->parMetrics(text(), pit());
1280 top().pos() = min(tm.x2pos(pit(), pmcur.rows().size() - 1, xo), top().lastpos());
1283 if (row + 1 < int(pm.rows().size())) {
1284 top().pos() = min(tm.x2pos(pit(), row + 1, xo), top().lastpos());
1285 } else if (pit() + 1 < int(text()->paragraphs().size())) {
1287 top().pos() = min(tm.x2pos(pit(), 0, xo), top().lastpos());
1291 updateNeeded |= bv().checkDepm(*this, old);
1294 updateTextTargetOffset();
1299 void Cursor::handleFont(string const & font)
1301 LYXERR(Debug::DEBUG, font);
1305 safe = cap::grabAndEraseSelection(*this);
1308 if (lastpos() != 0) {
1309 // something left in the cell
1311 // cursor in first position
1313 } else if (pos() == lastpos()) {
1314 // cursor in last position
1317 // cursor in between. split cell
1318 MathData::iterator bt = cell().begin();
1319 MathAtom at = createInsetMath(from_utf8(font));
1320 at.nucleus()->cell(0) = MathData(bt, bt + pos());
1321 cell().erase(bt, bt + pos());
1326 // nothing left in the cell
1334 void Cursor::message(docstring const & msg) const
1336 theLyXFunc().setMessage(msg);
1340 void Cursor::errorMessage(docstring const & msg) const
1342 theLyXFunc().setErrorMessage(msg);
1346 docstring Cursor::selectionAsString(bool label) const
1352 Buffer const & buffer = bv().buffer();
1353 ParagraphList const & pars = text()->paragraphs();
1355 // should be const ...
1356 pit_type startpit = selBegin().pit();
1357 pit_type endpit = selEnd().pit();
1358 size_t const startpos = selBegin().pos();
1359 size_t const endpos = selEnd().pos();
1361 if (startpit == endpit)
1362 return pars[startpit].asString(buffer, startpos, endpos, label);
1364 // First paragraph in selection
1365 docstring result = pars[startpit].
1366 asString(buffer, startpos, pars[startpit].size(), label)
1367 + parbreak(pars[startpit]);
1369 // The paragraphs in between (if any)
1370 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1371 Paragraph const & par = pars[pit];
1372 result += par.asString(buffer, 0, par.size(), label)
1373 + parbreak(pars[pit]);
1376 // Last paragraph in selection
1377 result += pars[endpit].asString(buffer, 0, endpos, label);
1383 return cap::grabSelection(*this);
1389 docstring Cursor::currentState()
1392 odocstringstream os;
1398 return text()->currentState(*this);
1404 docstring Cursor::getPossibleLabel()
1406 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
1410 Encoding const * Cursor::getEncoding() const
1415 // go up until first non-0 text is hit
1416 // (innermost text is 0 in mathed)
1417 for (s = depth() - 1; s >= 0; --s)
1418 if (operator[](s).text())
1420 CursorSlice const & sl = operator[](s);
1421 Text const & text = *sl.text();
1422 Font font = text.getPar(sl.pit()).getFont(
1423 bv().buffer().params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1424 return font.language()->encoding();
1428 void Cursor::undispatched()
1430 disp_.dispatched(false);
1434 void Cursor::dispatched()
1436 disp_.dispatched(true);
1440 void Cursor::updateFlags(Update::flags f)
1446 void Cursor::noUpdate()
1448 disp_.update(Update::None);
1452 Font Cursor::getFont() const
1454 // The logic here should more or less match to the Cursor::setCurrentFont
1455 // logic, i.e. the cursor height should give a hint what will happen
1456 // if a character is entered.
1458 // HACK. far from being perfect...
1459 // go up until first non-0 text is hit
1460 // (innermost text is 0 in mathed)
1462 for (s = depth() - 1; s >= 0; --s)
1463 if (operator[](s).text())
1465 CursorSlice const & sl = operator[](s);
1466 Text const & text = *sl.text();
1467 Paragraph const & par = text.getPar(sl.pit());
1469 // on boundary, so we are really at the character before
1470 pos_type pos = sl.pos();
1471 if (pos > 0 && boundary())
1474 // on space? Take the font before (only for RTL boundary stay)
1476 TextMetrics const & tm = bv().textMetrics(&text);
1477 if (pos == sl.lastpos()
1478 || (par.isSeparator(pos)
1479 && !tm.isRTLBoundary(sl.pit(), pos)))
1483 // get font at the position
1484 Font font = par.getFont(bv().buffer().params(), pos,
1485 outerFont(sl.pit(), text.paragraphs()));
1491 bool Cursor::fixIfBroken()
1493 if (DocIterator::fixIfBroken()) {
1502 bool notifyCursorLeaves(DocIterator const & old, Cursor & cur)
1504 // find inset in common
1506 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
1507 if (&old.inset() != &cur.inset())
1511 // notify everything on top of the common part in old cursor,
1512 // but stop if the inset claims the cursor to be invalid now
1513 for (; i < old.depth(); ++i) {
1514 if (old[i].inset().notifyCursorLeaves(cur))
1522 void Cursor::setCurrentFont()
1524 CursorSlice const & cs = innerTextSlice();
1525 Paragraph const & par = cs.paragraph();
1526 pos_type cpit = cs.pit();
1527 pos_type cpos = cs.pos();
1528 Text const & ctext = *cs.text();
1529 TextMetrics const & tm = bv().textMetrics(&ctext);
1531 // are we behind previous char in fact? -> go to that char
1532 if (cpos > 0 && boundary())
1535 // find position to take the font from
1537 // paragraph end? -> font of last char
1538 if (cpos == lastpos())
1540 // on space? -> look at the words in front of space
1541 else if (cpos > 0 && par.isSeparator(cpos)) {
1542 // abc| def -> font of c
1543 // abc |[WERBEH], i.e. boundary==true -> font of c
1544 // abc [WERBEH]| def, font of the space
1545 if (!tm.isRTLBoundary(cpit, cpos))
1551 BufferParams const & bufparams = buffer().params();
1552 current_font = par.getFontSettings(bufparams, cpos);
1553 real_current_font = tm.getDisplayFont(cpit, cpos);
1555 // special case for paragraph end
1556 if (cs.pos() == lastpos()
1557 && tm.isRTLBoundary(cpit, cs.pos())
1559 Language const * lang = par.getParLanguage(bufparams);
1560 current_font.setLanguage(lang);
1561 current_font.fontInfo().setNumber(FONT_OFF);
1562 real_current_font.setLanguage(lang);
1563 real_current_font.fontInfo().setNumber(FONT_OFF);
1568 bool Cursor::textUndo()
1570 DocIterator dit = *this;
1571 // Undo::textUndo() will modify dit.
1572 if (!bv_->buffer().undo().textUndo(dit))
1576 selection() = false;
1583 bool Cursor::textRedo()
1585 DocIterator dit = *this;
1586 // Undo::textRedo() will modify dit.
1587 if (!bv_->buffer().undo().textRedo(dit))
1591 selection() = false;
1598 void Cursor::finishUndo()
1600 bv_->buffer().undo().finishUndo();
1604 void Cursor::recordUndo(UndoKind kind, pit_type from, pit_type to)
1606 bv_->buffer().undo().recordUndo(*this, kind, from, to);
1610 void Cursor::recordUndo(UndoKind kind, pit_type from)
1612 bv_->buffer().undo().recordUndo(*this, kind, from);
1616 void Cursor::recordUndo(UndoKind kind)
1618 bv_->buffer().undo().recordUndo(*this, kind);
1622 void Cursor::recordUndoInset(UndoKind kind)
1624 bv_->buffer().undo().recordUndoInset(*this, kind);
1628 void Cursor::recordUndoFullDocument()
1630 bv_->buffer().undo().recordUndoFullDocument(*this);
1634 void Cursor::recordUndoSelection()
1636 bv_->buffer().undo().recordUndo(*this, ATOMIC_UNDO,
1637 selBegin().pit(), selEnd().pit());