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;
580 if (sel == selection())
584 cap::saveSelection(*this);
592 ostream & operator<<(ostream & os, Cursor const & cur)
594 os << "\n cursor: | anchor:\n";
595 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
596 os << " " << cur[i] << " | ";
597 if (i < cur.anchor_.depth())
598 os << cur.anchor_[i];
600 os << "-------------------------------";
603 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
604 os << "------------------------------- | " << cur.anchor_[i] << "\n";
606 os << " selection: " << cur.selection_
607 << " x_target: " << cur.x_target_ << endl;
612 LyXErr & operator<<(LyXErr & os, Cursor const & cur)
622 ///////////////////////////////////////////////////////////////////
625 // The part below is the non-integrated rest of the original math
626 // cursor. This should be either generalized for texted or moved
627 // back to mathed (in most cases to InsetMathNest).
629 ///////////////////////////////////////////////////////////////////
631 #include "mathed/InsetMathChar.h"
632 #include "mathed/InsetMathGrid.h"
633 #include "mathed/InsetMathScript.h"
634 #include "mathed/InsetMathUnknown.h"
635 #include "mathed/MathFactory.h"
636 #include "mathed/MathStream.h"
637 #include "mathed/MathSupport.h"
642 //#define FILEDEBUG 1
645 bool Cursor::isInside(Inset const * p)
647 for (size_t i = 0; i != depth(); ++i)
648 if (&operator[](i).inset() == p)
654 void Cursor::leaveInset(Inset const & inset)
656 for (size_t i = 0; i != depth(); ++i) {
657 if (&operator[](i).inset() == &inset) {
665 bool Cursor::openable(MathAtom const & t) const
676 // we can't move into anything new during selection
677 if (depth() >= anchor_.depth())
679 if (t.nucleus() != &anchor_[depth()].inset())
686 void Cursor::setScreenPos(int x, int /*y*/)
689 //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
694 void Cursor::plainErase()
700 void Cursor::markInsert()
702 insert(char_type(0));
706 void Cursor::markErase()
712 void Cursor::plainInsert(MathAtom const & t)
714 cell().insert(pos(), t);
719 void Cursor::insert(docstring const & str)
721 for_each(str.begin(), str.end(),
722 boost::bind(static_cast<void(Cursor::*)(char_type)>
723 (&Cursor::insert), this, _1));
727 void Cursor::insert(char_type c)
729 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
730 BOOST_ASSERT(!empty());
732 cap::selClearOrDel(*this);
733 insert(new InsetMathChar(c));
735 text()->insertChar(*this, c);
740 void Cursor::insert(MathAtom const & t)
742 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
744 cap::selClearOrDel(*this);
749 void Cursor::insert(Inset * inset)
752 insert(MathAtom(inset));
754 text()->insertInset(*this, inset);
758 void Cursor::niceInsert(docstring const & t)
769 void Cursor::niceInsert(MathAtom const & t)
772 docstring const safe = cap::grabAndEraseSelection(*this);
774 // enter the new inset and move the contents of the selection if possible
777 // be careful here: don't use 'pushBackward(t)' as this we need to
778 // push the clone, not the original
779 pushBackward(*nextInset());
780 // We may not use niceInsert here (recursion)
788 void Cursor::insert(MathData const & ar)
792 cap::eraseSelection(*this);
793 cell().insert(pos(), ar);
798 bool Cursor::backspace()
800 autocorrect() = false;
803 cap::eraseSelection(*this);
808 // If empty cell, and not part of a big cell
809 if (lastpos() == 0 && inset().nargs() == 1) {
811 // Directly delete empty cell: [|[]] => [|]
817 // [|], can not delete from inside
829 InsetMathUnknown * p = activeMacro();
830 if (p->name().size() > 1) {
831 p->setName(p->name().substr(0, p->name().size() - 1));
836 if (pos() != 0 && prevAtom()->nargs() > 0) {
837 // let's require two backspaces for 'big stuff' and
838 // highlight on the first
852 autocorrect() = false;
857 cap::eraseSelection(*this);
861 // delete empty cells if possible
862 if (pos() == lastpos() && inset().idxDelete(idx()))
865 // special behaviour when in last position of cell
866 if (pos() == lastpos()) {
867 bool one_cell = inset().nargs() == 1;
868 if (one_cell && lastpos() == 0) {
870 // Directly delete empty cell: [|[]] => [|]
876 // [|], can not delete from inside
881 inset().idxGlue(idx());
885 // 'clever' UI hack: only erase large items if previously slected
886 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
901 DocIterator save = *this;
902 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
904 if (disp_.dispatched())
907 autocorrect() = false;
915 DocIterator save = *this;
916 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
918 if (disp_.dispatched())
921 autocorrect() = false;
926 bool Cursor::macroModeClose()
930 InsetMathUnknown * p = activeMacro();
932 docstring const s = p->name();
936 // do nothing if the macro name is empty
940 // trigger updates of macros, at least, if no full
941 // updates take place anyway
942 updateFlags(Update::Force);
944 docstring const name = s.substr(1);
945 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
946 if (in && in->interpretString(*this, s))
948 MathAtom atom = createInsetMath(name);
949 MathMacro * atomAsMacro = atom.nucleus()->asMacro();
951 // make non-greedy, i.e. don't eat parameters from the right
952 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT);
959 docstring Cursor::macroName()
961 return inMacroMode() ? activeMacro()->name() : docstring();
965 void Cursor::handleNest(MathAtom const & a, int c)
967 //lyxerr << "Cursor::handleNest: " << c << endl;
969 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
972 pushBackward(*nextInset());
976 int Cursor::targetX() const
978 if (x_target() != -1)
987 int Cursor::textTargetOffset() const
989 return textTargetOffset_;
993 void Cursor::setTargetX()
1002 bool Cursor::inMacroMode() const
1008 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1009 return p && !p->final();
1013 InsetMathUnknown * Cursor::activeMacro()
1015 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1019 void Cursor::pullArg()
1022 MathData ar = cell();
1023 if (popBackward() && inMathed()) {
1025 cell().insert(pos(), ar);
1028 //formula()->mutateToText();
1033 void Cursor::touch()
1037 DocIterator::const_iterator it = begin();
1038 DocIterator::const_iterator et = end();
1039 for ( ; it != et; ++it)
1045 void Cursor::normalize()
1047 if (idx() > lastidx()) {
1048 lyxerr << "this should not really happen - 1: "
1049 << idx() << ' ' << nargs()
1050 << " in: " << &inset() << endl;
1054 if (pos() > lastpos()) {
1055 lyxerr << "this should not really happen - 2: "
1056 << pos() << ' ' << lastpos() << " in idx: " << idx()
1058 odocstringstream os;
1059 WriteStream wi(os, false, true);
1060 inset().asInsetMath()->write(wi);
1061 lyxerr << to_utf8(os.str()) << endl;
1067 bool Cursor::upDownInMath(bool up)
1069 // Be warned: The 'logic' implemented in this function is highly
1070 // fragile. A distance of one pixel or a '<' vs '<=' _really
1071 // matters. So fiddle around with it only if you think you know
1072 // what you are doing!
1076 xo = theLyXFunc().cursorBeforeDispatchX();
1078 // check if we had something else in mind, if not, this is the future
1080 if (x_target_ == -1)
1082 else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1083 // In text mode inside the line (not left or right) possibly set a new target_x,
1084 // but only if we are somewhere else than the previous target-offset.
1086 // We want to keep the x-target on subsequent up/down movements
1087 // that cross beyond the end of short lines. Thus a special
1088 // handling when the cursor is at the end of line: Use the new
1089 // x-target only if the old one was before the end of line
1090 // or the old one was after the beginning of the line
1091 bool inRTL = isWithinRtlParagraph(*this);
1095 left = pos() == textRow().endpos();
1096 right = pos() == textRow().pos();
1098 left = pos() == textRow().pos();
1099 right = pos() == textRow().endpos();
1101 if ((!left && !right) ||
1102 (left && !right && xo < x_target_) ||
1103 (!left && right && x_target_ < xo))
1110 // try neigbouring script insets
1112 if (inMathed() && !selection()) {
1115 InsetMathScript const * p = prevAtom()->asScriptInset();
1116 if (p && p->has(up)) {
1118 push(*const_cast<InsetMathScript*>(p));
1119 idx() = p->idxOfScript(up);
1122 // we went in the right direction? Otherwise don't jump into the script
1126 int oy = theLyXFunc().cursorBeforeDispatchY();
1127 if ((!up && y <= oy) ||
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 int oy = theLyXFunc().cursorBeforeDispatchY();
1148 if ((!up && y <= oy) ||
1157 // try to find an inset that knows better then we,
1158 if (inset().idxUpDown(*this, up)) {
1159 //lyxerr << "idxUpDown triggered" << endl;
1160 // try to find best position within this inset
1162 setCursor(bruteFind2(*this, xo, yo));
1166 // any improvement going just out of inset?
1167 if (popBackward() && inMathed()) {
1168 //lyxerr << "updown: popBackward succeeded" << endl;
1171 int yold = theLyXFunc().cursorBeforeDispatchY();
1173 if (up ? ynew < yold : ynew > yold)
1177 // no success, we are probably at the document top or bottom
1183 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1185 BOOST_ASSERT(text());
1191 xo = theLyXFunc().cursorBeforeDispatchX();
1193 // update the targetX - this is here before the "return false"
1194 // to set a new target which can be used by InsetTexts above
1195 // if we cannot move up/down inside this inset anymore
1196 if (x_target_ == -1)
1198 else if (xo - textTargetOffset() != x_target() &&
1199 depth() == beforeDispatchCursor_.depth()) {
1200 // In text mode inside the line (not left or right) possibly set a new target_x,
1201 // but only if we are somewhere else than the previous target-offset.
1203 // We want to keep the x-target on subsequent up/down movements
1204 // that cross beyond the end of short lines. Thus a special
1205 // handling when the cursor is at the end of line: Use the new
1206 // x-target only if the old one was before the end of line
1207 // or the old one was after the beginning of the line
1208 bool inRTL = isWithinRtlParagraph(*this);
1212 left = pos() == textRow().endpos();
1213 right = pos() == textRow().pos();
1215 left = pos() == textRow().pos();
1216 right = pos() == textRow().endpos();
1218 if ((!left && !right) ||
1219 (left && !right && xo < x_target_) ||
1220 (!left && right && x_target_ < xo))
1227 // first get the current line
1228 TextMetrics & tm = bv_->textMetrics(text());
1229 ParagraphMetrics const & pm = tm.parMetrics(pit());
1231 if (pos() && boundary())
1232 row = pm.pos2row(pos() - 1);
1234 row = pm.pos2row(pos());
1236 // are we not at the start or end?
1238 if (pit() == 0 && row == 0)
1241 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1242 row + 1 >= int(pm.rows().size()))
1246 // with and without selection are handled differently
1248 int yo = bv().getPos(*this, boundary()).y_;
1250 // To next/previous row
1252 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1254 tm.editXY(*this, xo, yo + textRow().descent() + 1);
1257 // This happens when you move out of an inset.
1258 // And to give the DEPM the possibility of doing
1259 // something we must provide it with two different
1261 Cursor dummy = *this;
1264 if (bv().checkDepm(dummy, old)) {
1265 updateNeeded = true;
1266 // Make sure that cur gets back whatever happened to dummy(Lgb)
1270 // if there is a selection, we stay out of any inset, and just jump to the right position:
1274 top().pos() = min(tm.x2pos(pit(), row - 1, xo), top().lastpos());
1275 } else if (pit() > 0) {
1277 ParagraphMetrics const & pmcur = bv_->parMetrics(text(), pit());
1278 top().pos() = min(tm.x2pos(pit(), pmcur.rows().size() - 1, xo), top().lastpos());
1281 if (row + 1 < int(pm.rows().size())) {
1282 top().pos() = min(tm.x2pos(pit(), row + 1, xo), top().lastpos());
1283 } else if (pit() + 1 < int(text()->paragraphs().size())) {
1285 top().pos() = min(tm.x2pos(pit(), 0, xo), top().lastpos());
1289 updateNeeded |= bv().checkDepm(*this, old);
1292 updateTextTargetOffset();
1297 void Cursor::handleFont(string const & font)
1299 LYXERR(Debug::DEBUG, font);
1303 safe = cap::grabAndEraseSelection(*this);
1306 if (lastpos() != 0) {
1307 // something left in the cell
1309 // cursor in first position
1311 } else if (pos() == lastpos()) {
1312 // cursor in last position
1315 // cursor in between. split cell
1316 MathData::iterator bt = cell().begin();
1317 MathAtom at = createInsetMath(from_utf8(font));
1318 at.nucleus()->cell(0) = MathData(bt, bt + pos());
1319 cell().erase(bt, bt + pos());
1324 // nothing left in the cell
1332 void Cursor::message(docstring const & msg) const
1334 theLyXFunc().setMessage(msg);
1338 void Cursor::errorMessage(docstring const & msg) const
1340 theLyXFunc().setErrorMessage(msg);
1344 docstring Cursor::selectionAsString(bool label) const
1350 Buffer const & buffer = bv().buffer();
1351 ParagraphList const & pars = text()->paragraphs();
1353 // should be const ...
1354 pit_type startpit = selBegin().pit();
1355 pit_type endpit = selEnd().pit();
1356 size_t const startpos = selBegin().pos();
1357 size_t const endpos = selEnd().pos();
1359 if (startpit == endpit)
1360 return pars[startpit].asString(buffer, startpos, endpos, label);
1362 // First paragraph in selection
1363 docstring result = pars[startpit].
1364 asString(buffer, startpos, pars[startpit].size(), label)
1365 + parbreak(pars[startpit]);
1367 // The paragraphs in between (if any)
1368 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1369 Paragraph const & par = pars[pit];
1370 result += par.asString(buffer, 0, par.size(), label)
1371 + parbreak(pars[pit]);
1374 // Last paragraph in selection
1375 result += pars[endpit].asString(buffer, 0, endpos, label);
1381 return cap::grabSelection(*this);
1387 docstring Cursor::currentState()
1390 odocstringstream os;
1396 return text()->currentState(*this);
1402 docstring Cursor::getPossibleLabel()
1404 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
1408 Encoding const * Cursor::getEncoding() const
1413 // go up until first non-0 text is hit
1414 // (innermost text is 0 in mathed)
1415 for (s = depth() - 1; s >= 0; --s)
1416 if (operator[](s).text())
1418 CursorSlice const & sl = operator[](s);
1419 Text const & text = *sl.text();
1420 Font font = text.getPar(sl.pit()).getFont(
1421 bv().buffer().params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1422 return font.language()->encoding();
1426 void Cursor::undispatched()
1428 disp_.dispatched(false);
1432 void Cursor::dispatched()
1434 disp_.dispatched(true);
1438 void Cursor::updateFlags(Update::flags f)
1444 void Cursor::noUpdate()
1446 disp_.update(Update::None);
1450 Font Cursor::getFont() const
1452 // The logic here should more or less match to the Cursor::setCurrentFont
1453 // logic, i.e. the cursor height should give a hint what will happen
1454 // if a character is entered.
1456 // HACK. far from being perfect...
1457 // go up until first non-0 text is hit
1458 // (innermost text is 0 in mathed)
1460 for (s = depth() - 1; s >= 0; --s)
1461 if (operator[](s).text())
1463 CursorSlice const & sl = operator[](s);
1464 Text const & text = *sl.text();
1465 Paragraph const & par = text.getPar(sl.pit());
1467 // on boundary, so we are really at the character before
1468 pos_type pos = sl.pos();
1469 if (pos > 0 && boundary())
1472 // on space? Take the font before (only for RTL boundary stay)
1474 TextMetrics const & tm = bv().textMetrics(&text);
1475 if (pos == sl.lastpos()
1476 || (par.isSeparator(pos)
1477 && !tm.isRTLBoundary(sl.pit(), pos)))
1481 // get font at the position
1482 Font font = par.getFont(bv().buffer().params(), pos,
1483 outerFont(sl.pit(), text.paragraphs()));
1489 bool Cursor::fixIfBroken()
1491 if (DocIterator::fixIfBroken()) {
1500 bool notifyCursorLeaves(DocIterator const & old, Cursor & cur)
1502 // find inset in common
1504 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
1505 if (&old.inset() != &cur.inset())
1509 // notify everything on top of the common part in old cursor,
1510 // but stop if the inset claims the cursor to be invalid now
1511 for (; i < old.depth(); ++i) {
1512 if (old[i].inset().notifyCursorLeaves(cur))
1520 void Cursor::setCurrentFont()
1522 CursorSlice const & cs = innerTextSlice();
1523 Paragraph const & par = cs.paragraph();
1524 pos_type cpit = cs.pit();
1525 pos_type cpos = cs.pos();
1526 Text const & ctext = *cs.text();
1527 TextMetrics const & tm = bv().textMetrics(&ctext);
1529 // are we behind previous char in fact? -> go to that char
1530 if (cpos > 0 && boundary())
1533 // find position to take the font from
1535 // paragraph end? -> font of last char
1536 if (cpos == lastpos())
1538 // on space? -> look at the words in front of space
1539 else if (cpos > 0 && par.isSeparator(cpos)) {
1540 // abc| def -> font of c
1541 // abc |[WERBEH], i.e. boundary==true -> font of c
1542 // abc [WERBEH]| def, font of the space
1543 if (!tm.isRTLBoundary(cpit, cpos))
1549 BufferParams const & bufparams = buffer().params();
1550 current_font = par.getFontSettings(bufparams, cpos);
1551 real_current_font = tm.getDisplayFont(cpit, cpos);
1553 // special case for paragraph end
1554 if (cs.pos() == lastpos()
1555 && tm.isRTLBoundary(cpit, cs.pos())
1557 Language const * lang = par.getParLanguage(bufparams);
1558 current_font.setLanguage(lang);
1559 current_font.fontInfo().setNumber(FONT_OFF);
1560 real_current_font.setLanguage(lang);
1561 real_current_font.fontInfo().setNumber(FONT_OFF);
1566 bool Cursor::textUndo()
1568 DocIterator dit = *this;
1569 // Undo::textUndo() will modify dit.
1570 if (!bv_->buffer().undo().textUndo(dit))
1574 selection() = false;
1581 bool Cursor::textRedo()
1583 DocIterator dit = *this;
1584 // Undo::textRedo() will modify dit.
1585 if (!bv_->buffer().undo().textRedo(dit))
1589 selection() = false;
1596 void Cursor::finishUndo()
1598 bv_->buffer().undo().finishUndo();
1602 void Cursor::recordUndo(UndoKind kind, pit_type from, pit_type to)
1604 bv_->buffer().undo().recordUndo(*this, kind, from, to);
1608 void Cursor::recordUndo(UndoKind kind, pit_type from)
1610 bv_->buffer().undo().recordUndo(*this, kind, from);
1614 void Cursor::recordUndo(UndoKind kind)
1616 bv_->buffer().undo().recordUndo(*this, kind);
1620 void Cursor::recordUndoInset(UndoKind kind)
1622 bv_->buffer().undo().recordUndoInset(*this, kind);
1626 void Cursor::recordUndoFullDocument()
1628 bv_->buffer().undo().recordUndoFullDocument(*this);
1632 void Cursor::recordUndoSelection()
1634 bv_->buffer().undo().recordUndo(*this, ATOMIC_UNDO,
1635 selBegin().pit(), selEnd().pit());