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"
36 #include "TextMetrics.h"
38 #include "insets/InsetTabular.h"
39 #include "insets/InsetText.h"
41 #include "mathed/MathData.h"
42 #include "mathed/InsetMath.h"
43 #include "mathed/InsetMathScript.h"
44 #include "mathed/MacroTable.h"
46 #include "support/limited_stack.h"
48 #include <boost/assert.hpp>
49 #include <boost/bind.hpp>
50 #include <boost/current_function.hpp>
68 positionable(DocIterator const & cursor, DocIterator const & anchor)
70 // avoid deeper nested insets when selecting
71 if (cursor.depth() > anchor.depth())
74 // anchor might be deeper, should have same path then
75 for (size_t i = 0; i < cursor.depth(); ++i)
76 if (&cursor[i].inset() != &anchor[i].inset())
79 // position should be ok.
84 // Find position closest to (x, y) in cell given by iter.
85 // Used only in mathed
86 DocIterator bruteFind2(Cursor const & c, int x, int y)
88 double best_dist = std::numeric_limits<double>::max();
95 et.top().pos() = et.top().asInsetMath()->cell(et.top().idx()).size();
96 for (size_t i = 0;; ++i) {
99 Inset const * inset = &it.inset();
100 std::map<Inset const *, Geometry> const & data =
101 c.bv().coordCache().getInsets().getData();
102 std::map<Inset const *, Geometry>::const_iterator I = data.find(inset);
104 // FIXME: in the case where the inset is not in the cache, this
105 // means that no part of it is visible on screen. In this case
106 // we don't do elaborate search and we just return the forwarded
107 // DocIterator at its beginning.
108 if (I == data.end()) {
113 Point o = I->second.pos;
114 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
115 // Convert to absolute
118 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
119 // '<=' in order to take the last possible position
120 // this is important for clicking behind \sum in e.g. '\sum_i a'
121 LYXERR(Debug::DEBUG) << "i: " << i << " d: " << d
122 << " best: " << best_dist << endl;
123 if (d <= best_dist) {
136 /// moves position closest to (x, y) in given box
137 bool bruteFind(Cursor & cursor,
138 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
140 BOOST_ASSERT(!cursor.empty());
141 Inset & inset = cursor[0].inset();
142 BufferView & bv = cursor.bv();
144 CoordCache::InnerParPosCache const & cache =
145 bv.coordCache().getParPos().find(cursor.bottom().text())->second;
146 // Get an iterator on the first paragraph in the cache
147 DocIterator it(inset);
148 it.push_back(CursorSlice(inset));
149 it.pit() = cache.begin()->first;
150 // Get an iterator after the last paragraph in the cache
151 DocIterator et(inset);
152 et.push_back(CursorSlice(inset));
153 et.pit() = boost::prior(cache.end())->first;
154 if (et.pit() >= et.lastpit())
155 et = doc_iterator_end(inset);
159 double best_dist = std::numeric_limits<double>::max();;
160 DocIterator best_cursor = et;
162 for ( ; it != et; it.forwardPos(true)) {
163 // avoid invalid nesting when selecting
164 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
165 Point p = bv.getPos(it, false);
168 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
169 double const dx = xo - x;
170 double const dy = yo - y;
171 double const d = dx * dx + dy * dy;
172 // '<=' in order to take the last possible position
173 // this is important for clicking behind \sum in e.g. '\sum_i a'
174 if (d <= best_dist) {
175 // lyxerr << "*" << endl;
183 if (best_cursor != et) {
184 cursor.setCursor(best_cursor);
193 /// moves position closest to (x, y) in given box
194 bool bruteFind3(Cursor & cur, int x, int y, bool up)
196 BufferView & bv = cur.bv();
197 int ylow = up ? 0 : y + 1;
198 int yhigh = up ? y - 1 : bv.workHeight();
200 int xhigh = bv.workWidth();
202 // FIXME: bit more work needed to get 'from' and 'to' right.
203 pit_type from = cur.bottom().pit();
204 //pit_type to = cur.bottom().pit();
205 //lyxerr << "Pit start: " << from << endl;
207 //lyxerr << "bruteFind3: x: " << x << " y: " << y
208 // << " xlow: " << xlow << " xhigh: " << xhigh
209 // << " ylow: " << ylow << " yhigh: " << yhigh
211 Inset & inset = bv.buffer().inset();
212 DocIterator it = doc_iterator_begin(inset);
214 DocIterator et = doc_iterator_end(inset);
216 double best_dist = std::numeric_limits<double>::max();
217 DocIterator best_cursor = et;
219 for ( ; it != et; it.forwardPos()) {
220 // avoid invalid nesting when selecting
221 if (bv.cursorStatus(it) == CUR_INSIDE
222 && (!cur.selection() || positionable(it, cur.anchor_))) {
223 Point p = bv.getPos(it, false);
226 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
227 double const dx = xo - x;
228 double const dy = yo - y;
229 double const d = dx * dx + dy * dy;
230 //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
231 // << " dx: " << dx << " dy: " << dy
232 // << " idx: " << it.idx() << " pos: " << it.pos()
235 // '<=' in order to take the last possible position
236 // this is important for clicking behind \sum in e.g. '\sum_i a'
237 if (d <= best_dist) {
238 //lyxerr << "*" << endl;
246 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
247 if (best_cursor == et)
249 cur.setCursor(best_cursor);
253 docstring parbreak(Paragraph const & par)
255 odocstringstream ods;
257 // only add blank line if we're not in an ERT or Listings inset
258 if (par.ownerCode() != Inset::ERT_CODE
259 && par.ownerCode() != Inset::LISTINGS_CODE)
267 // be careful: this is called from the bv's constructor, too, so
268 // bv functions are not yet available!
269 Cursor::Cursor(BufferView & bv)
270 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1), textTargetOffset_(0),
271 selection_(false), mark_(false), logicalpos_(false), current_font(Font::ALL_INHERIT)
275 void Cursor::reset(Inset & inset)
278 push_back(CursorSlice(inset));
279 anchor_ = DocIterator(inset);
286 // this (intentionally) does neither touch anchor nor selection status
287 void Cursor::setCursor(DocIterator const & cur)
289 DocIterator::operator=(cur);
293 void Cursor::dispatch(FuncRequest const & cmd0)
295 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
296 << " cmd: " << cmd0 << '\n'
302 FuncRequest cmd = cmd0;
305 // store some values to be used inside of the handlers
306 getPos(beforeDispX_, beforeDispY_);
307 beforeDispatchCursor_ = *this;
308 for (; depth(); pop()) {
309 LYXERR(Debug::DEBUG) << "Cursor::dispatch: cmd: "
310 << cmd0 << endl << *this << endl;
311 BOOST_ASSERT(pos() <= lastpos());
312 BOOST_ASSERT(idx() <= lastidx());
313 BOOST_ASSERT(pit() <= lastpit());
315 // The common case is 'LFUN handled, need update', so make the
316 // LFUN handler's life easier by assuming this as default value.
317 // The handler can reset the update and val flags if necessary.
318 disp_.update(Update::FitCursor | Update::Force);
319 disp_.dispatched(true);
320 inset().dispatch(*this, cmd);
321 if (disp_.dispatched())
325 // it completely to get a 'bomb early' behaviour in case this
326 // object will be used again.
327 if (!disp_.dispatched()) {
328 LYXERR(Debug::DEBUG) << "RESTORING OLD CURSOR!" << endl;
330 disp_.update(Update::None);
331 disp_.dispatched(false);
333 // restore the previous one because nested Cursor::dispatch calls
334 // are possible which would change it
335 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
340 DispatchResult Cursor::result() const
346 BufferView & Cursor::bv() const
353 Buffer & Cursor::buffer() const
356 return bv_->buffer();
362 BOOST_ASSERT(depth() >= 1);
367 void Cursor::push(Inset & p)
369 push_back(CursorSlice(p));
373 void Cursor::pushLeft(Inset & p)
375 BOOST_ASSERT(!empty());
376 //lyxerr << "Entering inset " << t << " left" << endl;
382 bool Cursor::popLeft()
384 BOOST_ASSERT(!empty());
385 //lyxerr << "Leaving inset to the left" << endl;
386 inset().notifyCursorLeaves(*this);
394 bool Cursor::popRight()
396 BOOST_ASSERT(!empty());
397 //lyxerr << "Leaving inset to the right" << endl;
398 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
399 inset().notifyCursorLeaves(*this);
403 pos() += lastpos() - lp + 1;
408 int Cursor::currentMode()
410 BOOST_ASSERT(!empty());
411 for (int i = depth() - 1; i >= 0; --i) {
412 int res = operator[](i).inset().currentMode();
413 if (res != Inset::UNDECIDED_MODE)
416 return Inset::TEXT_MODE;
420 void Cursor::getPos(int & x, int & y) const
422 Point p = bv().getPos(*this, boundary());
428 Row const & Cursor::textRow() const
430 ParagraphMetrics const & pm = bv().parMetrics(text(), pit());
431 BOOST_ASSERT(!pm.rows().empty());
432 return pm.getRow(pos(), boundary());
436 void Cursor::resetAnchor()
443 bool Cursor::posLeft()
452 bool Cursor::posRight()
454 if (pos() == lastpos())
461 CursorSlice Cursor::anchor() const
463 BOOST_ASSERT(anchor_.depth() >= depth());
464 CursorSlice normal = anchor_[depth() - 1];
465 if (depth() < anchor_.depth() && top() <= normal) {
466 // anchor is behind cursor -> move anchor behind the inset
473 CursorSlice Cursor::selBegin() const
477 return anchor() < top() ? anchor() : top();
481 CursorSlice Cursor::selEnd() const
485 return anchor() > top() ? anchor() : top();
489 DocIterator Cursor::selectionBegin() const
493 DocIterator di = (anchor() < top() ? anchor_ : *this);
499 DocIterator Cursor::selectionEnd() const
503 DocIterator di = (anchor() > top() ? anchor_ : *this);
504 if (di.depth() > depth()) {
512 void Cursor::setSelection()
515 // A selection with no contents is not a selection
516 // FIXME: doesnt look ok
517 if (pit() == anchor().pit() && pos() == anchor().pos())
522 void Cursor::setSelection(DocIterator const & where, int n)
531 void Cursor::clearSelection()
539 void Cursor::setTargetX(int x)
542 textTargetOffset_ = 0;
546 int Cursor::x_target() const
552 void Cursor::clearTargetX()
555 textTargetOffset_ = 0;
559 void Cursor::updateTextTargetOffset()
564 textTargetOffset_ = x - x_target_;
568 void Cursor::info(odocstream & os) const
570 for (int i = 1, n = depth(); i < n; ++i) {
571 operator[](i).inset().infoize(os);
575 Inset const * inset = prevInset();
576 // prevInset() can return 0 in certain case.
578 prevInset()->infoize2(os);
580 // overwite old message
585 bool Cursor::selHandle(bool sel)
587 //lyxerr << "Cursor::selHandle" << endl;
588 if (sel == selection())
592 cap::saveSelection(*this);
600 std::ostream & operator<<(std::ostream & os, Cursor const & cur)
602 os << "\n cursor: | anchor:\n";
603 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
604 os << " " << cur[i] << " | ";
605 if (i < cur.anchor_.depth())
606 os << cur.anchor_[i];
608 os << "-------------------------------";
611 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
612 os << "------------------------------- | " << cur.anchor_[i] << "\n";
614 os << " selection: " << cur.selection_
615 << " x_target: " << cur.x_target_ << endl;
622 ///////////////////////////////////////////////////////////////////
624 // The part below is the non-integrated rest of the original math
625 // cursor. This should be either generalized for texted or moved
626 // back to mathed (in most cases to InsetMathNest).
628 ///////////////////////////////////////////////////////////////////
630 #include "mathed/InsetMathChar.h"
631 #include "mathed/InsetMathGrid.h"
632 #include "mathed/InsetMathScript.h"
633 #include "mathed/InsetMathUnknown.h"
634 #include "mathed/MathFactory.h"
635 #include "mathed/MathStream.h"
636 #include "mathed/MathSupport.h"
641 //#define FILEDEBUG 1
644 bool Cursor::isInside(Inset const * p)
646 for (size_t i = 0; i != depth(); ++i)
647 if (&operator[](i).inset() == p)
653 void Cursor::leaveInset(Inset const & inset)
655 for (size_t i = 0; i != depth(); ++i) {
656 if (&operator[](i).inset() == &inset) {
664 bool Cursor::openable(MathAtom const & t) const
675 // we can't move into anything new during selection
676 if (depth() >= anchor_.depth())
678 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
685 void Cursor::setScreenPos(int x, int /*y*/)
688 //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
693 void Cursor::plainErase()
699 void Cursor::markInsert()
701 insert(char_type(0));
705 void Cursor::markErase()
711 void Cursor::plainInsert(MathAtom const & t)
713 cell().insert(pos(), t);
718 void Cursor::insert(docstring const & str)
720 for_each(str.begin(), str.end(),
721 boost::bind(static_cast<void(Cursor::*)(char_type)>
722 (&Cursor::insert), this, _1));
726 void Cursor::insert(char_type c)
728 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
729 BOOST_ASSERT(!empty());
731 cap::selClearOrDel(*this);
732 insert(new InsetMathChar(c));
734 text()->insertChar(*this, c);
739 void Cursor::insert(MathAtom const & t)
741 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
743 cap::selClearOrDel(*this);
748 void Cursor::insert(Inset * inset)
751 insert(MathAtom(inset));
753 text()->insertInset(*this, inset);
757 void Cursor::niceInsert(docstring const & t)
768 void Cursor::niceInsert(MathAtom const & t)
771 docstring const safe = cap::grabAndEraseSelection(*this);
773 // enter the new inset and move the contents of the selection if possible
776 // be careful here: don't use 'pushLeft(t)' as this we need to
777 // push the clone, not the original
778 pushLeft(*nextInset());
779 // We may not use niceInsert here (recursion)
787 void Cursor::insert(MathData const & ar)
791 cap::eraseSelection(*this);
792 cell().insert(pos(), ar);
797 bool Cursor::backspace()
799 autocorrect() = false;
802 cap::eraseSelection(*this);
807 // If empty cell, and not part of a big cell
808 if (lastpos() == 0 && inset().nargs() == 1) {
810 // Directly delete empty cell: [|[]] => [|]
816 // [|], can not delete from inside
828 InsetMathUnknown * p = activeMacro();
829 if (p->name().size() > 1) {
830 p->setName(p->name().substr(0, p->name().size() - 1));
835 if (pos() != 0 && prevAtom()->nargs() > 0) {
836 // let's require two backspaces for 'big stuff' and
837 // highlight on the first
851 autocorrect() = false;
856 cap::eraseSelection(*this);
860 // delete empty cells if possible
861 if (pos() == lastpos() && inset().idxDelete(idx()))
864 // special behaviour when in last position of cell
865 if (pos() == lastpos()) {
866 bool one_cell = inset().nargs() == 1;
867 if (one_cell && lastpos() == 0) {
869 // Directly delete empty cell: [|[]] => [|]
875 // [|], can not delete from inside
880 inset().idxGlue(idx());
884 // 'clever' UI hack: only erase large items if previously slected
885 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
900 DocIterator save = *this;
901 FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
903 if (disp_.dispatched())
906 autocorrect() = false;
914 DocIterator save = *this;
915 FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
917 if (disp_.dispatched())
920 autocorrect() = false;
925 bool Cursor::macroModeClose()
929 InsetMathUnknown * p = activeMacro();
931 docstring const s = p->name();
935 // do nothing if the macro name is empty
939 // trigger updates of macros, at least, if no full
940 // updates take place anyway
941 updateFlags(Update::Force);
943 docstring const name = s.substr(1);
944 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
945 if (in && in->interpretString(*this, s))
947 plainInsert(createInsetMath(name));
952 docstring Cursor::macroName()
954 return inMacroMode() ? activeMacro()->name() : docstring();
958 void Cursor::handleNest(MathAtom const & a, int c)
960 //lyxerr << "Cursor::handleNest: " << c << endl;
962 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
965 pushLeft(*nextInset());
969 int Cursor::targetX() const
971 if (x_target() != -1)
980 int Cursor::textTargetOffset() const
982 return textTargetOffset_;
986 void Cursor::setTargetX()
995 bool Cursor::inMacroMode() const
1001 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1002 return p && !p->final();
1006 InsetMathUnknown * Cursor::activeMacro()
1008 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1012 void Cursor::pullArg()
1015 MathData ar = cell();
1016 if (popLeft() && inMathed()) {
1018 cell().insert(pos(), ar);
1021 //formula()->mutateToText();
1026 void Cursor::touch()
1030 DocIterator::const_iterator it = begin();
1031 DocIterator::const_iterator et = end();
1032 for ( ; it != et; ++it)
1038 void Cursor::normalize()
1040 if (idx() > lastidx()) {
1041 lyxerr << "this should not really happen - 1: "
1042 << idx() << ' ' << nargs()
1043 << " in: " << &inset() << endl;
1047 if (pos() > lastpos()) {
1048 lyxerr << "this should not really happen - 2: "
1049 << pos() << ' ' << lastpos() << " in idx: " << idx()
1051 odocstringstream os;
1052 WriteStream wi(os, false, true);
1053 inset().asInsetMath()->write(wi);
1054 lyxerr << to_utf8(os.str()) << endl;
1060 bool Cursor::upDownInMath(bool up)
1062 // Be warned: The 'logic' implemented in this function is highly
1063 // fragile. A distance of one pixel or a '<' vs '<=' _really
1064 // matters. So fiddle around with it only if you think you know
1065 // what you are doing!
1071 // check if we had something else in mind, if not, this is the future
1073 if (x_target_ == -1)
1075 else if (inset().asTextInset() && xo - textTargetOffset() != x_target()) {
1076 // In text mode inside the line (not left or right) possibly set a new target_x,
1077 // but only if we are somewhere else than the previous target-offset.
1079 // We want to keep the x-target on subsequent up/down movements
1080 // that cross beyond the end of short lines. Thus a special
1081 // handling when the cursor is at the end of line: Use the new
1082 // x-target only if the old one was before the end of line
1083 // or the old one was after the beginning of the line
1084 bool inRTL = isWithinRtlParagraph(*this);
1088 left = pos() == textRow().endpos();
1089 right = pos() == textRow().pos();
1091 left = pos() == textRow().pos();
1092 right = pos() == textRow().endpos();
1094 if ((!left && !right) ||
1095 (left && !right && xo < x_target_) ||
1096 (!left && right && x_target_ < xo))
1103 // try neigbouring script insets
1105 if (inMathed() && !selection()) {
1108 InsetMathScript const * p = prevAtom()->asScriptInset();
1109 if (p && p->has(up)) {
1111 push(*const_cast<InsetMathScript*>(p));
1112 idx() = p->idxOfScript(up);
1115 // we went in the right direction? Otherwise don't jump into the script
1119 if ((!up && y <= beforeDispY_) ||
1120 (up && y >= beforeDispY_))
1128 if (pos() != lastpos()) {
1129 InsetMathScript const * p = nextAtom()->asScriptInset();
1130 if (p && p->has(up)) {
1131 push(*const_cast<InsetMathScript*>(p));
1132 idx() = p->idxOfScript(up);
1135 // we went in the right direction? Otherwise don't jump into the script
1139 if ((!up && y <= beforeDispY_) ||
1140 (up && y >= beforeDispY_))
1148 // try to find an inset that knows better then we,
1149 if (inset().idxUpDown(*this, up)) {
1150 //lyxerr << "idxUpDown triggered" << endl;
1151 // try to find best position within this inset
1153 setCursor(bruteFind2(*this, xo, yo));
1157 // any improvement going just out of inset?
1158 if (popLeft() && inMathed()) {
1159 //lyxerr << "updown: popLeft succeeded" << endl;
1163 if (up ? ynew < beforeDispY_ : ynew > beforeDispY_)
1167 // no success, we are probably at the document top or bottom
1173 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1175 BOOST_ASSERT(text());
1183 // update the targetX - this is here before the "return false"
1184 // to set a new target which can be used by InsetTexts above
1185 // if we cannot move up/down inside this inset anymore
1186 if (x_target_ == -1)
1188 else if (xo - textTargetOffset() != x_target() &&
1189 depth() == beforeDispatchCursor_.depth()) {
1190 // In text mode inside the line (not left or right) possibly set a new target_x,
1191 // but only if we are somewhere else than the previous target-offset.
1193 // We want to keep the x-target on subsequent up/down movements
1194 // that cross beyond the end of short lines. Thus a special
1195 // handling when the cursor is at the end of line: Use the new
1196 // x-target only if the old one was before the end of line
1197 // or the old one was after the beginning of the line
1198 bool inRTL = isWithinRtlParagraph(*this);
1202 left = pos() == textRow().endpos();
1203 right = pos() == textRow().pos();
1205 left = pos() == textRow().pos();
1206 right = pos() == textRow().endpos();
1208 if ((!left && !right) ||
1209 (left && !right && xo < x_target_) ||
1210 (!left && right && x_target_ < xo))
1217 // first get the current line
1218 TextMetrics & tm = bv_->textMetrics(text());
1219 ParagraphMetrics const & pm = tm.parMetrics(pit());
1221 if (pos() && boundary())
1222 row = pm.pos2row(pos() - 1);
1224 row = pm.pos2row(pos());
1226 // are we not at the start or end?
1228 if (pit() == 0 && row == 0)
1231 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1232 row + 1 >= int(pm.rows().size()))
1236 // with and without selection are handled differently
1238 int yo = bv().getPos(*this, boundary()).y_;
1240 // To next/previous row
1242 tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1244 tm.editXY(*this, xo, yo + textRow().descent() + 1);
1247 // This happens when you move out of an inset.
1248 // And to give the DEPM the possibility of doing
1249 // something we must provide it with two different
1251 Cursor dummy = *this;
1254 if (bv().checkDepm(dummy, old)) {
1255 updateNeeded = true;
1256 // Make sure that cur gets back whatever happened to dummy(Lgb)
1260 // if there is a selection, we stay out of any inset, and just jump to the right position:
1264 top().pos() = std::min(tm.x2pos(pit(), row - 1, xo), top().lastpos());
1265 } else if (pit() > 0) {
1267 ParagraphMetrics const & pmcur = bv_->parMetrics(text(), pit());
1268 top().pos() = std::min(tm.x2pos(pit(), pmcur.rows().size() - 1, xo), top().lastpos());
1271 if (row + 1 < int(pm.rows().size())) {
1272 top().pos() = std::min(tm.x2pos(pit(), row + 1, xo), top().lastpos());
1273 } else if (pit() + 1 < int(text()->paragraphs().size())) {
1275 top().pos() = std::min(tm.x2pos(pit(), 0, xo), top().lastpos());
1279 updateNeeded |= bv().checkDepm(*this, old);
1282 updateTextTargetOffset();
1287 void Cursor::handleFont(string const & font)
1289 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << ": " << font << endl;
1293 safe = cap::grabAndEraseSelection(*this);
1296 if (lastpos() != 0) {
1297 // something left in the cell
1299 // cursor in first position
1301 } else if (pos() == lastpos()) {
1302 // cursor in last position
1305 // cursor in between. split cell
1306 MathData::iterator bt = cell().begin();
1307 MathAtom at = createInsetMath(from_utf8(font));
1308 at.nucleus()->cell(0) = MathData(bt, bt + pos());
1309 cell().erase(bt, bt + pos());
1314 // nothing left in the cell
1322 void Cursor::message(docstring const & msg) const
1324 theLyXFunc().setMessage(msg);
1328 void Cursor::errorMessage(docstring const & msg) const
1330 theLyXFunc().setErrorMessage(msg);
1334 docstring Cursor::selectionAsString(bool label) const
1340 Buffer const & buffer = bv().buffer();
1341 ParagraphList const & pars = text()->paragraphs();
1343 // should be const ...
1344 pit_type startpit = selBegin().pit();
1345 pit_type endpit = selEnd().pit();
1346 size_t const startpos = selBegin().pos();
1347 size_t const endpos = selEnd().pos();
1349 if (startpit == endpit)
1350 return pars[startpit].asString(buffer, startpos, endpos, label);
1352 // First paragraph in selection
1353 docstring result = pars[startpit].
1354 asString(buffer, startpos, pars[startpit].size(), label)
1355 + parbreak(pars[startpit]);
1357 // The paragraphs in between (if any)
1358 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1359 Paragraph const & par = pars[pit];
1360 result += par.asString(buffer, 0, par.size(), label)
1361 + parbreak(pars[pit]);
1364 // Last paragraph in selection
1365 result += pars[endpit].asString(buffer, 0, endpos, label);
1371 return cap::grabSelection(*this);
1377 docstring Cursor::currentState()
1380 odocstringstream os;
1386 return text()->currentState(*this);
1392 docstring Cursor::getPossibleLabel()
1394 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
1398 Encoding const * Cursor::getEncoding() const
1403 // go up until first non-0 text is hit
1404 // (innermost text is 0 in mathed)
1405 for (s = depth() - 1; s >= 0; --s)
1406 if (operator[](s).text())
1408 CursorSlice const & sl = operator[](s);
1409 Text const & text = *sl.text();
1410 Font font = text.getPar(sl.pit()).getFont(
1411 bv().buffer().params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1412 return font.language()->encoding();
1416 void Cursor::undispatched()
1418 disp_.dispatched(false);
1422 void Cursor::dispatched()
1424 disp_.dispatched(true);
1428 void Cursor::updateFlags(Update::flags f)
1434 void Cursor::noUpdate()
1436 disp_.update(Update::None);
1440 Font Cursor::getFont() const
1442 // The logic here should more or less match to the Cursor::setCurrentFont
1443 // logic, i.e. the cursor height should give a hint what will happen
1444 // if a character is entered.
1446 // HACK. far from being perfect...
1447 // go up until first non-0 text is hit
1448 // (innermost text is 0 in mathed)
1450 for (s = depth() - 1; s >= 0; --s)
1451 if (operator[](s).text())
1453 CursorSlice const & sl = operator[](s);
1454 Text const & text = *sl.text();
1455 Paragraph const & par = text.getPar(sl.pit());
1457 // on boundary, so we are really at the character before
1458 pos_type pos = sl.pos();
1459 if (pos > 0 && boundary())
1462 // on space? Take the font before (only for RTL boundary stay)
1464 TextMetrics const & tm = bv().textMetrics(&text);
1465 if (pos == sl.lastpos()
1466 || (par.isSeparator(pos)
1467 && !tm.isRTLBoundary(sl.pit(), pos)))
1471 // get font at the position
1472 Font font = par.getFont(bv().buffer().params(), pos,
1473 outerFont(sl.pit(), text.paragraphs()));
1479 bool Cursor::fixIfBroken()
1481 if (DocIterator::fixIfBroken()) {
1490 bool notifyCursorLeaves(DocIterator const & old, Cursor & cur)
1492 // find inset in common
1494 for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
1495 if (&old.inset() != &cur.inset())
1499 // notify everything on top of the common part in old cursor,
1500 // but stop if the inset claims the cursor to be invalid now
1501 for (; i < old.depth(); ++i) {
1502 if (old[i].inset().notifyCursorLeaves(cur))
1510 void Cursor::setCurrentFont()
1512 CursorSlice const & cs = innerTextSlice();
1513 Paragraph const & par = cs.paragraph();
1514 pos_type cpit = cs.pit();
1515 pos_type cpos = cs.pos();
1516 Text const & ctext = *cs.text();
1517 TextMetrics const & tm = bv().textMetrics(&ctext);
1519 // are we behind previous char in fact? -> go to that char
1520 if (cpos > 0 && boundary())
1523 // find position to take the font from
1525 // paragraph end? -> font of last char
1526 if (cpos == lastpos())
1528 // on space? -> look at the words in front of space
1529 else if (cpos > 0 && par.isSeparator(cpos)) {
1530 // abc| def -> font of c
1531 // abc |[WERBEH], i.e. boundary==true -> font of c
1532 // abc [WERBEH]| def, font of the space
1533 if (!tm.isRTLBoundary(cpit, cpos))
1539 BufferParams const & bufparams = buffer().params();
1540 current_font = par.getFontSettings(bufparams, cpos);
1541 real_current_font = tm.getDisplayFont(cpit, cpos);
1543 // special case for paragraph end
1544 if (cs.pos() == lastpos()
1545 && tm.isRTLBoundary(cpit, cs.pos())
1547 Language const * lang = par.getParLanguage(bufparams);
1548 current_font.setLanguage(lang);
1549 current_font.setNumber(Font::OFF);
1550 real_current_font.setLanguage(lang);
1551 real_current_font.setNumber(Font::OFF);