3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alejandro Aguilar Sierra
7 * \author Alfredo Braunstein
9 * \author Stefan Schimanski
11 * Full author contact details are available in file CREDITS.
17 #include "BufferView.h"
20 #include "CoordCache.h"
21 #include "CutAndPaste.h"
23 #include "DispatchResult.h"
25 #include "FuncRequest.h"
29 #include "LyXFunc.h" // only for setMessage()
33 #include "Paragraph.h"
34 #include "paragraph_funcs.h"
35 #include "ParIterator.h"
37 #include "insets/InsetTabular.h"
38 #include "insets/InsetText.h"
40 #include "mathed/MathData.h"
41 #include "mathed/InsetMath.h"
42 #include "mathed/InsetMathScript.h"
43 #include "mathed/MacroTable.h"
45 #include "support/limited_stack.h"
47 #include <boost/assert.hpp>
48 #include <boost/bind.hpp>
49 #include <boost/current_function.hpp>
67 positionable(DocIterator const & cursor, DocIterator const & anchor)
69 // avoid deeper nested insets when selecting
70 if (cursor.depth() > anchor.depth())
73 // anchor might be deeper, should have same path then
74 for (size_t i = 0; i < cursor.depth(); ++i)
75 if (&cursor[i].inset() != &anchor[i].inset())
78 // position should be ok.
83 // Find position closest to (x, y) in cell given by iter.
84 // Used only in mathed
85 DocIterator bruteFind2(Cursor const & c, int x, int y)
87 double best_dist = std::numeric_limits<double>::max();
94 et.top().pos() = et.top().asInsetMath()->cell(et.top().idx()).size();
95 for (size_t i = 0;; ++i) {
98 Inset const * inset = &it.inset();
99 std::map<Inset const *, Geometry> const & data =
100 c.bv().coordCache().getInsets().getData();
101 std::map<Inset const *, Geometry>::const_iterator I = data.find(inset);
103 // FIXME: in the case where the inset is not in the cache, this
104 // means that no part of it is visible on screen. In this case
105 // we don't do elaborate search and we just return the forwarded
106 // DocIterator at its beginning.
107 if (I == data.end()) {
112 Point o = I->second.pos;
113 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
114 // Convert to absolute
117 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
118 // '<=' in order to take the last possible position
119 // this is important for clicking behind \sum in e.g. '\sum_i a'
120 LYXERR(Debug::DEBUG) << "i: " << i << " d: " << d
121 << " best: " << best_dist << endl;
122 if (d <= best_dist) {
135 /// moves position closest to (x, y) in given box
136 bool bruteFind(Cursor & cursor,
137 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
139 BOOST_ASSERT(!cursor.empty());
140 Inset & inset = cursor[0].inset();
141 BufferView & bv = cursor.bv();
143 CoordCache::InnerParPosCache const & cache =
144 bv.coordCache().getParPos().find(cursor.bottom().text())->second;
145 // Get an iterator on the first paragraph in the cache
146 DocIterator it(inset);
147 it.push_back(CursorSlice(inset));
148 it.pit() = cache.begin()->first;
149 // Get an iterator after the last paragraph in the cache
150 DocIterator et(inset);
151 et.push_back(CursorSlice(inset));
152 et.pit() = boost::prior(cache.end())->first;
153 if (et.pit() >= et.lastpit())
154 et = doc_iterator_end(inset);
158 double best_dist = std::numeric_limits<double>::max();;
159 DocIterator best_cursor = et;
161 for ( ; it != et; it.forwardPos(true)) {
162 // avoid invalid nesting when selecting
163 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
164 Point p = bv.getPos(it, false);
167 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
168 double const dx = xo - x;
169 double const dy = yo - y;
170 double const d = dx * dx + dy * dy;
171 // '<=' in order to take the last possible position
172 // this is important for clicking behind \sum in e.g. '\sum_i a'
173 if (d <= best_dist) {
174 // lyxerr << "*" << endl;
182 if (best_cursor != et) {
183 cursor.setCursor(best_cursor);
192 /// moves position closest to (x, y) in given box
193 bool bruteFind3(Cursor & cur, int x, int y, bool up)
195 BufferView & bv = cur.bv();
196 int ylow = up ? 0 : y + 1;
197 int yhigh = up ? y - 1 : bv.workHeight();
199 int xhigh = bv.workWidth();
201 // FIXME: bit more work needed to get 'from' and 'to' right.
202 pit_type from = cur.bottom().pit();
203 //pit_type to = cur.bottom().pit();
204 //lyxerr << "Pit start: " << from << endl;
206 //lyxerr << "bruteFind3: x: " << x << " y: " << y
207 // << " xlow: " << xlow << " xhigh: " << xhigh
208 // << " ylow: " << ylow << " yhigh: " << yhigh
210 Inset & inset = bv.buffer().inset();
211 DocIterator it = doc_iterator_begin(inset);
213 DocIterator et = doc_iterator_end(inset);
215 double best_dist = std::numeric_limits<double>::max();
216 DocIterator best_cursor = et;
218 for ( ; it != et; it.forwardPos()) {
219 // avoid invalid nesting when selecting
220 if (bv.cursorStatus(it) == CUR_INSIDE
221 && (!cur.selection() || positionable(it, cur.anchor_))) {
222 Point p = bv.getPos(it, false);
225 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
226 double const dx = xo - x;
227 double const dy = yo - y;
228 double const d = dx * dx + dy * dy;
229 //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
230 // << " dx: " << dx << " dy: " << dy
231 // << " idx: " << it.idx() << " pos: " << it.pos()
234 // '<=' in order to take the last possible position
235 // this is important for clicking behind \sum in e.g. '\sum_i a'
236 if (d <= best_dist) {
237 //lyxerr << "*" << endl;
245 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
246 if (best_cursor == et)
248 cur.setCursor(best_cursor);
252 docstring parbreak(Paragraph const & par)
254 odocstringstream ods;
256 // only add blank line if we're not in an ERT or Listings inset
257 if (par.ownerCode() != Inset::ERT_CODE
258 && par.ownerCode() != Inset::LISTINGS_CODE)
266 // be careful: this is called from the bv's constructor, too, so
267 // bv functions are not yet available!
268 Cursor::Cursor(BufferView & bv)
269 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1), textTargetOffset_(0),
270 selection_(false), mark_(false), logicalpos_(false), current_font(Font::ALL_INHERIT)
274 void Cursor::reset(Inset & inset)
277 push_back(CursorSlice(inset));
278 anchor_ = DocIterator(inset);
285 // this (intentionally) does neither touch anchor nor selection status
286 void Cursor::setCursor(DocIterator const & cur)
288 DocIterator::operator=(cur);
292 void Cursor::dispatch(FuncRequest const & cmd0)
294 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
295 << " cmd: " << cmd0 << '\n'
301 FuncRequest cmd = cmd0;
304 // store some values to be used inside of the handlers
305 getPos(beforeDispX_, beforeDispY_);
306 beforeDispatchCursor_ = *this;
307 for (; depth(); pop()) {
308 LYXERR(Debug::DEBUG) << "Cursor::dispatch: cmd: "
309 << cmd0 << endl << *this << endl;
310 BOOST_ASSERT(pos() <= lastpos());
311 BOOST_ASSERT(idx() <= lastidx());
312 BOOST_ASSERT(pit() <= lastpit());
314 // The common case is 'LFUN handled, need update', so make the
315 // LFUN handler's life easier by assuming this as default value.
316 // The handler can reset the update and val flags if necessary.
317 disp_.update(Update::FitCursor | Update::Force);
318 disp_.dispatched(true);
319 inset().dispatch(*this, cmd);
320 if (disp_.dispatched())
324 // it completely to get a 'bomb early' behaviour in case this
325 // object will be used again.
326 if (!disp_.dispatched()) {
327 LYXERR(Debug::DEBUG) << "RESTORING OLD CURSOR!" << endl;
329 disp_.update(Update::None);
330 disp_.dispatched(false);
332 // restore the previous one because nested Cursor::dispatch calls
333 // are possible which would change it
334 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
339 DispatchResult Cursor::result() const
345 BufferView & Cursor::bv() const
352 Buffer & Cursor::buffer() const
355 return bv_->buffer();
361 BOOST_ASSERT(depth() >= 1);
366 void Cursor::push(Inset & p)
368 push_back(CursorSlice(p));
372 void Cursor::pushLeft(Inset & p)
374 BOOST_ASSERT(!empty());
375 //lyxerr << "Entering inset " << t << " left" << endl;
381 bool Cursor::popLeft()
383 BOOST_ASSERT(!empty());
384 //lyxerr << "Leaving inset to the left" << endl;
385 inset().notifyCursorLeaves(*this);
393 bool Cursor::popRight()
395 BOOST_ASSERT(!empty());
396 //lyxerr << "Leaving inset to the right" << endl;
397 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
398 inset().notifyCursorLeaves(*this);
402 pos() += lastpos() - lp + 1;
407 int Cursor::currentMode()
409 BOOST_ASSERT(!empty());
410 for (int i = depth() - 1; i >= 0; --i) {
411 int res = operator[](i).inset().currentMode();
412 if (res != Inset::UNDECIDED_MODE)
415 return Inset::TEXT_MODE;
419 void Cursor::getPos(int & x, int & y) const
421 Point p = bv().getPos(*this, boundary());
427 Row const & Cursor::textRow() const
429 ParagraphMetrics const & pm = bv().parMetrics(text(), pit());
430 BOOST_ASSERT(!pm.rows().empty());
431 return pm.getRow(pos(), boundary());
435 void Cursor::resetAnchor()
442 bool Cursor::posLeft()
451 bool Cursor::posRight()
453 if (pos() == lastpos())
460 CursorSlice Cursor::anchor() const
462 BOOST_ASSERT(anchor_.depth() >= depth());
463 CursorSlice normal = anchor_[depth() - 1];
464 if (depth() < anchor_.depth() && top() <= normal) {
465 // anchor is behind cursor -> move anchor behind the inset
472 CursorSlice Cursor::selBegin() const
476 return anchor() < top() ? anchor() : top();
480 CursorSlice Cursor::selEnd() const
484 return anchor() > top() ? anchor() : top();
488 DocIterator Cursor::selectionBegin() const
492 DocIterator di = (anchor() < top() ? anchor_ : *this);
498 DocIterator Cursor::selectionEnd() const
502 DocIterator di = (anchor() > top() ? anchor_ : *this);
503 if (di.depth() > depth()) {
511 void Cursor::setSelection()
514 // A selection with no contents is not a selection
515 // FIXME: doesnt look ok
516 if (pit() == anchor().pit() && pos() == anchor().pos())
521 void Cursor::setSelection(DocIterator const & where, int n)
530 void Cursor::clearSelection()
538 void Cursor::setTargetX(int x)
541 textTargetOffset_ = 0;
545 int Cursor::x_target() const
551 void Cursor::clearTargetX()
554 textTargetOffset_ = 0;
558 void Cursor::updateTextTargetOffset()
563 textTargetOffset_ = x - x_target_;
567 void Cursor::info(odocstream & os) const
569 for (int i = 1, n = depth(); i < n; ++i) {
570 operator[](i).inset().infoize(os);
574 Inset const * inset = prevInset();
575 // prevInset() can return 0 in certain case.
577 prevInset()->infoize2(os);
579 // overwite old message
584 bool Cursor::selHandle(bool sel)
586 //lyxerr << "Cursor::selHandle" << endl;
587 if (sel == selection())
591 cap::saveSelection(*this);
599 std::ostream & operator<<(std::ostream & os, Cursor const & cur)
601 os << "\n cursor: | anchor:\n";
602 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
603 os << " " << cur[i] << " | ";
604 if (i < cur.anchor_.depth())
605 os << cur.anchor_[i];
607 os << "-------------------------------";
610 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
611 os << "------------------------------- | " << cur.anchor_[i] << "\n";
613 os << " selection: " << cur.selection_
614 << " x_target: " << cur.x_target_ << endl;
621 ///////////////////////////////////////////////////////////////////
623 // The part below is the non-integrated rest of the original math
624 // cursor. This should be either generalized for texted or moved
625 // back to mathed (in most cases to InsetMathNest).
627 ///////////////////////////////////////////////////////////////////
629 #include "mathed/InsetMathChar.h"
630 #include "mathed/InsetMathGrid.h"
631 #include "mathed/InsetMathScript.h"
632 #include "mathed/InsetMathUnknown.h"
633 #include "mathed/MathFactory.h"
634 #include "mathed/MathStream.h"
635 #include "mathed/MathSupport.h"
640 //#define FILEDEBUG 1
643 bool Cursor::isInside(Inset const * p)
645 for (size_t i = 0; i != depth(); ++i)
646 if (&operator[](i).inset() == p)
652 void Cursor::leaveInset(Inset const & inset)
654 for (size_t i = 0; i != depth(); ++i) {
655 if (&operator[](i).inset() == &inset) {
663 bool Cursor::openable(MathAtom const & t) const
674 // we can't move into anything new during selection
675 if (depth() >= anchor_.depth())
677 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
684 void Cursor::setScreenPos(int x, int /*y*/)
687 //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
692 void Cursor::plainErase()
698 void Cursor::markInsert()
700 insert(char_type(0));
704 void Cursor::markErase()
710 void Cursor::plainInsert(MathAtom const & t)
712 cell().insert(pos(), t);
717 void Cursor::insert(docstring const & str)
719 for_each(str.begin(), str.end(),
720 boost::bind(static_cast<void(Cursor::*)(char_type)>
721 (&Cursor::insert), this, _1));
725 void Cursor::insert(char_type c)
727 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
728 BOOST_ASSERT(!empty());
730 cap::selClearOrDel(*this);
731 insert(new InsetMathChar(c));
733 text()->insertChar(*this, c);
738 void Cursor::insert(MathAtom const & t)
740 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
742 cap::selClearOrDel(*this);
747 void Cursor::insert(Inset * inset)
750 insert(MathAtom(inset));
752 text()->insertInset(*this, inset);
756 void Cursor::niceInsert(docstring const & t)
767 void Cursor::niceInsert(MathAtom const & t)
770 docstring const safe = cap::grabAndEraseSelection(*this);
772 // enter the new inset and move the contents of the selection if possible
775 // be careful here: don't use 'pushLeft(t)' as this we need to
776 // push the clone, not the original
777 pushLeft(*nextInset());
778 // We may not use niceInsert here (recursion)
786 void Cursor::insert(MathData const & ar)
790 cap::eraseSelection(*this);
791 cell().insert(pos(), ar);
796 bool Cursor::backspace()
798 autocorrect() = false;
801 cap::eraseSelection(*this);
806 // If empty cell, and not part of a big cell
807 if (lastpos() == 0 && inset().nargs() == 1) {
809 // Directly delete empty cell: [|[]] => [|]
815 // [|], can not delete from inside
827 InsetMathUnknown * p = activeMacro();
828 if (p->name().size() > 1) {
829 p->setName(p->name().substr(0, p->name().size() - 1));
834 if (pos() != 0 && prevAtom()->nargs() > 0) {
835 // let's require two backspaces for 'big stuff' and
836 // highlight on the first
850 autocorrect() = false;
855 cap::eraseSelection(*this);
859 // delete empty cells if possible
860 if (pos() == lastpos() && inset().idxDelete(idx()))
863 // special behaviour when in last position of cell
864 if (pos() == lastpos()) {
865 bool one_cell = inset().nargs() == 1;
866 if (one_cell && lastpos() == 0) {
868 // Directly delete empty cell: [|[]] => [|]
874 // [|], can not delete from inside
879 inset().idxGlue(idx());
883 // 'clever' UI hack: only erase large items if previously slected
884 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
899 DocIterator save = *this;
900 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
902 if (disp_.dispatched())
905 autocorrect() = false;
913 DocIterator save = *this;
914 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
916 if (disp_.dispatched())
919 autocorrect() = false;
924 bool Cursor::macroModeClose()
928 InsetMathUnknown * p = activeMacro();
930 docstring const s = p->name();
934 // do nothing if the macro name is empty
938 // trigger updates of macros, at least, if no full
939 // updates take place anyway
940 updateFlags(Update::Force);
942 docstring const name = s.substr(1);
943 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
944 if (in && in->interpretString(*this, s))
946 plainInsert(createInsetMath(name));
951 docstring Cursor::macroName()
953 return inMacroMode() ? activeMacro()->name() : docstring();
957 void Cursor::handleNest(MathAtom const & a, int c)
959 //lyxerr << "Cursor::handleNest: " << c << endl;
961 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
964 pushLeft(*nextInset());
968 int Cursor::targetX() const
970 if (x_target() != -1)
979 int Cursor::textTargetOffset() const
981 return textTargetOffset_;
985 void Cursor::setTargetX()
994 bool Cursor::inMacroMode() const
1000 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1001 return p && !p->final();
1005 InsetMathUnknown * Cursor::activeMacro()
1007 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1011 void Cursor::pullArg()
1014 MathData ar = cell();
1015 if (popLeft() && inMathed()) {
1017 cell().insert(pos(), ar);
1020 //formula()->mutateToText();
1025 void Cursor::touch()
1029 DocIterator::const_iterator it = begin();
1030 DocIterator::const_iterator et = end();
1031 for ( ; it != et; ++it)
1037 void Cursor::normalize()
1039 if (idx() > lastidx()) {
1040 lyxerr << "this should not really happen - 1: "
1041 << idx() << ' ' << nargs()
1042 << " in: " << &inset() << endl;
1046 if (pos() > lastpos()) {
1047 lyxerr << "this should not really happen - 2: "
1048 << pos() << ' ' << lastpos() << " in idx: " << idx()
1050 odocstringstream os;
1051 WriteStream wi(os, false, true);
1052 inset().asInsetMath()->write(wi);
1053 lyxerr << to_utf8(os.str()) << endl;
1059 bool Cursor::upDownInMath(bool up)
1061 // Be warned: The 'logic' implemented in this function is highly
1062 // fragile. A distance of one pixel or a '<' vs '<=' _really
1063 // matters. So fiddle around with it only if you think you know
1064 // what you are doing!
1070 // check if we had something else in mind, if not, this is the future
1072 if (x_target_ == -1)
1074 else if (inset().asTextInset() && xo - textTargetOffset() != x_target()) {
1075 // In text mode inside the line (not left or right) possibly set a new target_x,
1076 // but only if we are somewhere else than the previous target-offset.
1078 // We want to keep the x-target on subsequent up/down movements
1079 // that cross beyond the end of short lines. Thus a special
1080 // handling when the cursor is at the end of line: Use the new
1081 // x-target only if the old one was before the end of line
1082 // or the old one was after the beginning of the line
1083 bool inRTL = isWithinRtlParagraph(*this);
1087 left = pos() == textRow().endpos();
1088 right = pos() == textRow().pos();
1090 left = pos() == textRow().pos();
1091 right = pos() == textRow().endpos();
1093 if ((!left && !right) ||
1094 (left && !right && xo < x_target_) ||
1095 (!left && right && x_target_ < xo))
1102 // try neigbouring script insets
1104 if (inMathed() && !selection()) {
1107 InsetMathScript const * p = prevAtom()->asScriptInset();
1108 if (p && p->has(up)) {
1110 push(*const_cast<InsetMathScript*>(p));
1111 idx() = p->idxOfScript(up);
1114 // we went in the right direction? Otherwise don't jump into the script
1118 if ((!up && y <= beforeDispY_) ||
1119 (up && y >= beforeDispY_))
1127 if (pos() != lastpos()) {
1128 InsetMathScript const * p = nextAtom()->asScriptInset();
1129 if (p && p->has(up)) {
1130 push(*const_cast<InsetMathScript*>(p));
1131 idx() = p->idxOfScript(up);
1134 // we went in the right direction? Otherwise don't jump into the script
1138 if ((!up && y <= beforeDispY_) ||
1139 (up && y >= beforeDispY_))
1147 // try to find an inset that knows better then we,
1148 if (inset().idxUpDown(*this, up)) {
1149 //lyxerr << "idxUpDown triggered" << endl;
1150 // try to find best position within this inset
1152 setCursor(bruteFind2(*this, xo, yo));
1156 // any improvement going just out of inset?
1157 if (popLeft() && inMathed()) {
1158 //lyxerr << "updown: popLeft succeeded" << endl;
1162 if (up ? ynew < beforeDispY_ : ynew > beforeDispY_)
1166 // no success, we are probably at the document top or bottom
1172 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1174 BOOST_ASSERT(text());
1182 // update the targetX - this is here before the "return false"
1183 // to set a new target which can be used by InsetTexts above
1184 // if we cannot move up/down inside this inset anymore
1185 if (x_target_ == -1)
1187 else if (xo - textTargetOffset() != x_target() &&
1188 depth() == beforeDispatchCursor_.depth()) {
1189 // In text mode inside the line (not left or right) possibly set a new target_x,
1190 // but only if we are somewhere else than the previous target-offset.
1192 // We want to keep the x-target on subsequent up/down movements
1193 // that cross beyond the end of short lines. Thus a special
1194 // handling when the cursor is at the end of line: Use the new
1195 // x-target only if the old one was before the end of line
1196 // or the old one was after the beginning of the line
1197 bool inRTL = isWithinRtlParagraph(*this);
1201 left = pos() == textRow().endpos();
1202 right = pos() == textRow().pos();
1204 left = pos() == textRow().pos();
1205 right = pos() == textRow().endpos();
1207 if ((!left && !right) ||
1208 (left && !right && xo < x_target_) ||
1209 (!left && right && x_target_ < xo))
1216 // first get the current line
1217 TextMetrics & tm = bv_->textMetrics(text());
1218 ParagraphMetrics const & pm = tm.parMetrics(pit());
1220 if (pos() && boundary())
1221 row = pm.pos2row(pos() - 1);
1223 row = pm.pos2row(pos());
1225 // are we not at the start or end?
1227 if (pit() == 0 && row == 0)
1230 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1231 row + 1 >= int(pm.rows().size()))
1235 // with and without selection are handled differently
1237 int yo = bv().getPos(*this, boundary()).y_;
1239 // To next/previous row
1241 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1243 tm.editXY(*this, xo, yo + textRow().descent() + 1);
1246 // This happens when you move out of an inset.
1247 // And to give the DEPM the possibility of doing
1248 // something we must provide it with two different
1250 Cursor dummy = *this;
1253 if (bv().checkDepm(dummy, old)) {
1254 updateNeeded = true;
1255 // Make sure that cur gets back whatever happened to dummy(Lgb)
1259 // if there is a selection, we stay out of any inset, and just jump to the right position:
1263 top().pos() = std::min(tm.x2pos(pit(), row - 1, xo), top().lastpos());
1264 } else if (pit() > 0) {
1266 ParagraphMetrics const & pmcur = bv_->parMetrics(text(), pit());
1267 top().pos() = std::min(tm.x2pos(pit(), pmcur.rows().size() - 1, xo), top().lastpos());
1270 if (row + 1 < int(pm.rows().size())) {
1271 top().pos() = std::min(tm.x2pos(pit(), row + 1, xo), top().lastpos());
1272 } else if (pit() + 1 < int(text()->paragraphs().size())) {
1274 top().pos() = std::min(tm.x2pos(pit(), 0, xo), top().lastpos());
1278 updateNeeded |= bv().checkDepm(*this, old);
1281 updateTextTargetOffset();
1286 void Cursor::handleFont(string const & font)
1288 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << ": " << font << endl;
1292 safe = cap::grabAndEraseSelection(*this);
1295 if (lastpos() != 0) {
1296 // something left in the cell
1298 // cursor in first position
1300 } else if (pos() == lastpos()) {
1301 // cursor in last position
1304 // cursor in between. split cell
1305 MathData::iterator bt = cell().begin();
1306 MathAtom at = createInsetMath(from_utf8(font));
1307 at.nucleus()->cell(0) = MathData(bt, bt + pos());
1308 cell().erase(bt, bt + pos());
1313 // nothing left in the cell
1321 void Cursor::message(docstring const & msg) const
1323 theLyXFunc().setMessage(msg);
1327 void Cursor::errorMessage(docstring const & msg) const
1329 theLyXFunc().setErrorMessage(msg);
1333 docstring Cursor::selectionAsString(bool label) const
1339 Buffer const & buffer = bv().buffer();
1340 ParagraphList const & pars = text()->paragraphs();
1342 // should be const ...
1343 pit_type startpit = selBegin().pit();
1344 pit_type endpit = selEnd().pit();
1345 size_t const startpos = selBegin().pos();
1346 size_t const endpos = selEnd().pos();
1348 if (startpit == endpit)
1349 return pars[startpit].asString(buffer, startpos, endpos, label);
1351 // First paragraph in selection
1352 docstring result = pars[startpit].
1353 asString(buffer, startpos, pars[startpit].size(), label)
1354 + parbreak(pars[startpit]);
1356 // The paragraphs in between (if any)
1357 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1358 Paragraph const & par = pars[pit];
1359 result += par.asString(buffer, 0, par.size(), label)
1360 + parbreak(pars[pit]);
1363 // Last paragraph in selection
1364 result += pars[endpit].asString(buffer, 0, endpos, label);
1370 return cap::grabSelection(*this);
1376 docstring Cursor::currentState()
1379 odocstringstream os;
1385 return text()->currentState(*this);
1391 docstring Cursor::getPossibleLabel()
1393 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
1397 Encoding const * Cursor::getEncoding() const
1402 // go up until first non-0 text is hit
1403 // (innermost text is 0 in mathed)
1404 for (s = depth() - 1; s >= 0; --s)
1405 if (operator[](s).text())
1407 CursorSlice const & sl = operator[](s);
1408 Text const & text = *sl.text();
1409 Font font = text.getPar(sl.pit()).getFont(
1410 bv().buffer().params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1411 return font.language()->encoding();
1415 void Cursor::undispatched()
1417 disp_.dispatched(false);
1421 void Cursor::dispatched()
1423 disp_.dispatched(true);
1427 void Cursor::updateFlags(Update::flags f)
1433 void Cursor::noUpdate()
1435 disp_.update(Update::None);
1439 Font Cursor::getFont() const
1441 // The logic here should more or less match to the Cursor::setCurrentFont
1442 // logic, i.e. the cursor height should give a hint what will happen
1443 // if a character is entered.
1445 // HACK. far from being perfect...
1446 // go up until first non-0 text is hit
1447 // (innermost text is 0 in mathed)
1449 for (s = depth() - 1; s >= 0; --s)
1450 if (operator[](s).text())
1452 CursorSlice const & sl = operator[](s);
1453 Text const & text = *sl.text();
1454 Paragraph const & par = text.getPar(sl.pit());
1456 // on boundary, so we are really at the character before
1457 pos_type pos = sl.pos();
1458 if (pos > 0 && boundary())
1461 // on space? Take the font before (only for RTL boundary stay)
1463 TextMetrics const & tm = bv().textMetrics(&text);
1464 if (pos == sl.lastpos()
1465 || (par.isSeparator(pos)
1466 && !tm.isRTLBoundary(sl.pit(), pos)))
1470 // get font at the position
1471 Font font = par.getFont(bv().buffer().params(), pos,
1472 outerFont(sl.pit(), text.paragraphs()));
1478 bool Cursor::fixIfBroken()
1480 if (DocIterator::fixIfBroken()) {
1489 bool notifyCursorLeaves(DocIterator const & old, Cursor & cur)
1491 // find inset in common
1493 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
1494 if (&old.inset() != &cur.inset())
1498 // notify everything on top of the common part in old cursor,
1499 // but stop if the inset claims the cursor to be invalid now
1500 for (; i < old.depth(); ++i) {
1501 if (old[i].inset().notifyCursorLeaves(cur))
1509 void Cursor::setCurrentFont()
1511 CursorSlice const & cs = innerTextSlice();
1512 Paragraph const & par = cs.paragraph();
1513 pos_type cpit = cs.pit();
1514 pos_type cpos = cs.pos();
1515 Text const & ctext = *cs.text();
1516 TextMetrics const & tm = bv().textMetrics(&ctext);
1518 // are we behind previous char in fact? -> go to that char
1519 if (cpos > 0 && boundary())
1522 // find position to take the font from
1524 // paragraph end? -> font of last char
1525 if (cpos == lastpos())
1527 // on space? -> look at the words in front of space
1528 else if (cpos > 0 && par.isSeparator(cpos)) {
1529 // abc| def -> font of c
1530 // abc |[WERBEH], i.e. boundary==true -> font of c
1531 // abc [WERBEH]| def, font of the space
1532 if (!tm.isRTLBoundary(cpit, cpos))
1538 BufferParams const & bufparams = buffer().params();
1539 current_font = par.getFontSettings(bufparams, cpos);
1540 real_current_font = tm.getDisplayFont(cpit, cpos);
1542 // special case for paragraph end
1543 if (cs.pos() == lastpos()
1544 && tm.isRTLBoundary(cpit, cs.pos())
1546 Language const * lang = par.getParLanguage(bufparams);
1547 current_font.setLanguage(lang);
1548 current_font.setNumber(Font::OFF);
1549 real_current_font.setLanguage(lang);
1550 real_current_font.setNumber(Font::OFF);