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
10 * Full author contact details are available in file CREDITS.
15 #include "BufferView.h"
16 #include "bufferview_funcs.h"
19 #include "CoordCache.h"
20 #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"
36 #include "insets/InsetTabular.h"
37 #include "insets/InsetText.h"
39 #include "mathed/MathData.h"
40 #include "mathed/InsetMath.h"
41 #include "mathed/InsetMathScript.h"
42 #include "mathed/MacroTable.h"
44 #include "support/limited_stack.h"
46 #include <boost/assert.hpp>
47 #include <boost/bind.hpp>
48 #include <boost/current_function.hpp>
65 positionable(DocIterator const & cursor, DocIterator const & anchor)
67 // avoid deeper nested insets when selecting
68 if (cursor.depth() > anchor.depth())
71 // anchor might be deeper, should have same path then
72 for (size_t i = 0; i < cursor.depth(); ++i)
73 if (&cursor[i].inset() != &anchor[i].inset())
76 // position should be ok.
81 // Find position closest to (x, y) in cell given by iter.
82 // Used only in mathed
83 DocIterator bruteFind2(Cursor const & c, int x, int y)
85 double best_dist = std::numeric_limits<double>::max();
92 et.top().pos() = et.top().asInsetMath()->cell(et.top().idx()).size();
93 for (size_t i = 0;; ++i) {
96 Inset const * inset = &it.inset();
97 std::map<Inset const *, Point> const & data =
98 c.bv().coordCache().getInsets().getData();
99 std::map<Inset const *, Point>::const_iterator I = data.find(inset);
101 // FIXME: in the case where the inset is not in the cache, this
102 // means that no part of it is visible on screen. In this case
103 // we don't do elaborate search and we just return the forwarded
104 // DocIterator at its beginning.
105 if (I == data.end()) {
111 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
112 // Convert to absolute
115 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
116 // '<=' in order to take the last possible position
117 // this is important for clicking behind \sum in e.g. '\sum_i a'
118 LYXERR(Debug::DEBUG) << "i: " << i << " d: " << d
119 << " best: " << best_dist << endl;
120 if (d <= best_dist) {
132 /// moves position closest to (x, y) in given box
133 bool bruteFind(Cursor & cursor,
134 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
136 BOOST_ASSERT(!cursor.empty());
137 Inset & inset = cursor[0].inset();
138 BufferView & bv = cursor.bv();
140 CoordCache::InnerParPosCache const & cache =
141 bv.coordCache().getParPos().find(cursor.bottom().text())->second;
142 // Get an iterator on the first paragraph in the cache
143 DocIterator it(inset);
144 it.push_back(CursorSlice(inset));
145 it.pit() = cache.begin()->first;
146 // Get an iterator after the last paragraph in the cache
147 DocIterator et(inset);
148 et.push_back(CursorSlice(inset));
149 et.pit() = boost::prior(cache.end())->first;
150 if (et.pit() >= et.lastpit())
151 et = doc_iterator_end(inset);
155 double best_dist = std::numeric_limits<double>::max();;
156 DocIterator best_cursor = et;
158 for ( ; it != et; it.forwardPos(true)) {
159 // avoid invalid nesting when selecting
160 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
161 Point p = bv_funcs::getPos(bv, it, false);
164 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
165 double const dx = xo - x;
166 double const dy = yo - y;
167 double const d = dx * dx + dy * dy;
168 // '<=' in order to take the last possible position
169 // this is important for clicking behind \sum in e.g. '\sum_i a'
170 if (d <= best_dist) {
171 // lyxerr << "*" << endl;
179 if (best_cursor != et) {
180 cursor.setCursor(best_cursor);
188 /// moves position closest to (x, y) in given box
189 bool bruteFind3(Cursor & cur, int x, int y, bool up)
191 BufferView & bv = cur.bv();
192 int ylow = up ? 0 : y + 1;
193 int yhigh = up ? y - 1 : bv.workHeight();
195 int xhigh = bv.workWidth();
197 // FIXME: bit more work needed to get 'from' and 'to' right.
198 pit_type from = cur.bottom().pit();
199 //pit_type to = cur.bottom().pit();
200 //lyxerr << "Pit start: " << from << endl;
202 //lyxerr << "bruteFind3: x: " << x << " y: " << y
203 // << " xlow: " << xlow << " xhigh: " << xhigh
204 // << " ylow: " << ylow << " yhigh: " << yhigh
206 Inset & inset = bv.buffer()->inset();
207 DocIterator it = doc_iterator_begin(inset);
209 DocIterator et = doc_iterator_end(inset);
211 double best_dist = std::numeric_limits<double>::max();
212 DocIterator best_cursor = et;
214 for ( ; it != et; it.forwardPos()) {
215 // avoid invalid nesting when selecting
216 if (bv_funcs::status(&bv, it) == bv_funcs::CUR_INSIDE
217 && (!cur.selection() || positionable(it, cur.anchor_))) {
218 Point p = bv_funcs::getPos(bv, it, false);
221 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
222 double const dx = xo - x;
223 double const dy = yo - y;
224 double const d = dx * dx + dy * dy;
225 //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
226 // << " dx: " << dx << " dy: " << dy
227 // << " idx: " << it.idx() << " pos: " << it.pos()
230 // '<=' in order to take the last possible position
231 // this is important for clicking behind \sum in e.g. '\sum_i a'
232 if (d <= best_dist) {
233 //lyxerr << "*" << endl;
241 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
242 if (best_cursor == et)
244 cur.setCursor(best_cursor);
248 docstring parbreak(Paragraph const & par)
250 odocstringstream ods;
252 // only add blank line if we're not in an ERT or Listings inset
253 if (par.ownerCode() != Inset::ERT_CODE
254 && par.ownerCode() != Inset::LISTINGS_CODE)
262 // be careful: this is called from the bv's constructor, too, so
263 // bv functions are not yet available!
264 Cursor::Cursor(BufferView & bv)
265 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
266 selection_(false), mark_(false), logicalpos_(false)
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) << BOOST_CURRENT_FUNCTION
291 << " cmd: " << cmd0 << '\n'
297 FuncRequest cmd = cmd0;
300 for (; depth(); pop()) {
301 LYXERR(Debug::DEBUG) << "Cursor::dispatch: cmd: "
302 << cmd0 << endl << *this << endl;
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())
316 // it completely to get a 'bomb early' behaviour in case this
317 // object will be used again.
318 if (!disp_.dispatched()) {
319 LYXERR(Debug::DEBUG) << "RESTORING OLD CURSOR!" << endl;
321 disp_.update(Update::None);
322 disp_.dispatched(false);
327 DispatchResult Cursor::result() const
333 BufferView & Cursor::bv() const
340 Buffer & Cursor::buffer() const
343 BOOST_ASSERT(bv_->buffer());
344 return *bv_->buffer();
350 BOOST_ASSERT(depth() >= 1);
355 void Cursor::push(Inset & p)
357 push_back(CursorSlice(p));
361 void Cursor::pushLeft(Inset & p)
363 BOOST_ASSERT(!empty());
364 //lyxerr << "Entering inset " << t << " left" << endl;
370 bool Cursor::popLeft()
372 BOOST_ASSERT(!empty());
373 //lyxerr << "Leaving inset to the left" << endl;
374 inset().notifyCursorLeaves(*this);
382 bool Cursor::popRight()
384 BOOST_ASSERT(!empty());
385 //lyxerr << "Leaving inset to the right" << endl;
386 const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
387 inset().notifyCursorLeaves(*this);
391 pos() += lastpos() - lp + 1;
396 int Cursor::currentMode()
398 BOOST_ASSERT(!empty());
399 for (int i = depth() - 1; i >= 0; --i) {
400 int res = operator[](i).inset().currentMode();
401 if (res != Inset::UNDECIDED_MODE)
404 return Inset::TEXT_MODE;
408 void Cursor::getPos(int & x, int & y) const
410 Point p = bv_funcs::getPos(bv(), *this, boundary());
416 Row const & Cursor::textRow() const
418 ParagraphMetrics const & pm = bv().parMetrics(text(), pit());
419 BOOST_ASSERT(!pm.rows().empty());
420 return pm.getRow(pos(), boundary());
424 void Cursor::resetAnchor()
431 bool Cursor::posLeft()
440 bool Cursor::posRight()
442 if (pos() == lastpos())
449 CursorSlice Cursor::anchor() const
451 BOOST_ASSERT(anchor_.depth() >= depth());
452 CursorSlice normal = anchor_[depth() - 1];
453 if (depth() < anchor_.depth() && top() <= normal) {
454 // anchor is behind cursor -> move anchor behind the inset
461 CursorSlice Cursor::selBegin() const
465 return anchor() < top() ? anchor() : top();
469 CursorSlice Cursor::selEnd() const
473 return anchor() > top() ? anchor() : top();
477 DocIterator Cursor::selectionBegin() const
481 DocIterator di = (anchor() < top() ? anchor_ : *this);
487 DocIterator Cursor::selectionEnd() const
491 DocIterator di = (anchor() > top() ? anchor_ : *this);
492 if (di.depth() > depth()) {
500 void Cursor::setSelection()
503 // A selection with no contents is not a selection
505 #warning doesnt look ok
507 if (pit() == anchor().pit() && pos() == anchor().pos())
512 void Cursor::setSelection(DocIterator const & where, int n)
521 void Cursor::clearSelection()
529 int & Cursor::x_target()
535 int Cursor::x_target() const
541 void Cursor::clearTargetX()
548 void Cursor::info(odocstream & os) const
550 for (int i = 1, n = depth(); i < n; ++i) {
551 operator[](i).inset().infoize(os);
555 Inset const * inset = prevInset();
556 // prevInset() can return 0 in certain case.
558 prevInset()->infoize2(os);
560 // overwite old message
565 bool Cursor::selHandle(bool sel)
567 //lyxerr << "Cursor::selHandle" << endl;
568 if (sel == selection())
573 cap::saveSelection(*this);
578 std::ostream & operator<<(std::ostream & os, Cursor const & cur)
580 os << "\n cursor: | anchor:\n";
581 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
582 os << " " << cur[i] << " | ";
583 if (i < cur.anchor_.depth())
584 os << cur.anchor_[i];
586 os << "-------------------------------";
589 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
590 os << "------------------------------- | " << cur.anchor_[i] << "\n";
592 os << " selection: " << cur.selection_
593 << " x_target: " << cur.x_target_ << endl;
600 ///////////////////////////////////////////////////////////////////
602 // The part below is the non-integrated rest of the original math
603 // cursor. This should be either generalized for texted or moved
604 // back to mathed (in most cases to InsetMathNest).
606 ///////////////////////////////////////////////////////////////////
608 #include "mathed/InsetMathChar.h"
609 #include "mathed/InsetMathGrid.h"
610 #include "mathed/InsetMathScript.h"
611 #include "mathed/InsetMathUnknown.h"
612 #include "mathed/MathFactory.h"
613 #include "mathed/MathStream.h"
614 #include "mathed/MathSupport.h"
619 //#define FILEDEBUG 1
622 bool Cursor::isInside(Inset const * p)
624 for (size_t i = 0; i != depth(); ++i)
625 if (&operator[](i).inset() == p)
631 void Cursor::leaveInset(Inset const & inset)
633 for (size_t i = 0; i != depth(); ++i) {
634 if (&operator[](i).inset() == &inset) {
642 bool Cursor::openable(MathAtom const & t) const
653 // we can't move into anything new during selection
654 if (depth() >= anchor_.depth())
656 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
663 void Cursor::setScreenPos(int x, int y)
666 bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
671 void Cursor::plainErase()
677 void Cursor::markInsert()
679 insert(char_type(0));
683 void Cursor::markErase()
689 void Cursor::plainInsert(MathAtom const & t)
691 cell().insert(pos(), t);
696 void Cursor::insert(docstring const & str)
698 for_each(str.begin(), str.end(),
699 boost::bind(static_cast<void(Cursor::*)(char_type)>
700 (&Cursor::insert), this, _1));
704 void Cursor::insert(char_type c)
706 //lyxerr << "Cursor::insert char '" << c << "'" << endl;
707 BOOST_ASSERT(!empty());
709 cap::selClearOrDel(*this);
710 insert(new InsetMathChar(c));
712 text()->insertChar(*this, c);
717 void Cursor::insert(MathAtom const & t)
719 //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
721 cap::selClearOrDel(*this);
726 void Cursor::insert(Inset * inset)
729 insert(MathAtom(inset));
731 text()->insertInset(*this, inset);
735 void Cursor::niceInsert(docstring const & t)
746 void Cursor::niceInsert(MathAtom const & t)
749 docstring const safe = cap::grabAndEraseSelection(*this);
751 // enter the new inset and move the contents of the selection if possible
754 // be careful here: don't use 'pushLeft(t)' as this we need to
755 // push the clone, not the original
756 pushLeft(*nextInset());
757 // We may not use niceInsert here (recursion)
765 void Cursor::insert(MathData const & ar)
769 cap::eraseSelection(*this);
770 cell().insert(pos(), ar);
775 bool Cursor::backspace()
777 autocorrect() = false;
780 cap::eraseSelection(*this);
785 // If empty cell, and not part of a big cell
786 if (lastpos() == 0 && inset().nargs() == 1) {
788 // Directly delete empty cell: [|[]] => [|]
794 // [|], can not delete from inside
806 InsetMathUnknown * p = activeMacro();
807 if (p->name().size() > 1) {
808 p->setName(p->name().substr(0, p->name().size() - 1));
813 if (pos() != 0 && prevAtom()->nargs() > 0) {
814 // let's require two backspaces for 'big stuff' and
815 // highlight on the first
829 autocorrect() = false;
834 cap::eraseSelection(*this);
838 // delete empty cells if possible
839 if (pos() == lastpos() && inset().idxDelete(idx()))
842 // special behaviour when in last position of cell
843 if (pos() == lastpos()) {
844 bool one_cell = inset().nargs() == 1;
845 if (one_cell && lastpos() == 0) {
847 // Directly delete empty cell: [|[]] => [|]
853 // [|], can not delete from inside
858 inset().idxGlue(idx());
862 // 'clever' UI hack: only erase large items if previously slected
863 if (pos() != lastpos() && nextAtom()->nargs() > 0) {
878 DocIterator save = *this;
882 autocorrect() = false;
890 DocIterator save = *this;
894 autocorrect() = false;
899 bool Cursor::macroModeClose()
903 InsetMathUnknown * p = activeMacro();
905 docstring const s = p->name();
909 // do nothing if the macro name is empty
913 // trigger updates of macros, at least, if no full
914 // updates take place anyway
915 updateFlags(Update::Force);
917 docstring const name = s.substr(1);
918 InsetMathNest * const in = inset().asInsetMath()->asNestInset();
919 if (in && in->interpretString(*this, s))
921 plainInsert(createInsetMath(name));
926 docstring Cursor::macroName()
928 return inMacroMode() ? activeMacro()->name() : docstring();
932 void Cursor::handleNest(MathAtom const & a, int c)
934 //lyxerr << "Cursor::handleNest: " << c << endl;
936 asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
939 pushLeft(*nextInset());
943 int Cursor::targetX() const
945 if (x_target() != -1)
954 void Cursor::setTargetX()
963 bool Cursor::inMacroMode() const
967 InsetMathUnknown const * p = prevAtom()->asUnknownInset();
968 return p && !p->final();
972 InsetMathUnknown * Cursor::activeMacro()
974 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
978 void Cursor::pullArg()
983 MathData ar = cell();
984 if (popLeft() && inMathed()) {
986 cell().insert(pos(), ar);
989 //formula()->mutateToText();
1000 DocIterator::const_iterator it = begin();
1001 DocIterator::const_iterator et = end();
1002 for ( ; it != et; ++it)
1008 void Cursor::normalize()
1010 if (idx() > lastidx()) {
1011 lyxerr << "this should not really happen - 1: "
1012 << idx() << ' ' << nargs()
1013 << " in: " << &inset() << endl;
1017 if (pos() > lastpos()) {
1018 lyxerr << "this should not really happen - 2: "
1019 << pos() << ' ' << lastpos() << " in idx: " << idx()
1021 odocstringstream os;
1022 WriteStream wi(os, false, true);
1023 inset().asInsetMath()->write(wi);
1024 lyxerr << to_utf8(os.str()) << endl;
1030 bool Cursor::goUpDown(bool up)
1032 // Be warned: The 'logic' implemented in this function is highly
1033 // fragile. A distance of one pixel or a '<' vs '<=' _really
1034 // matters. So fiddle around with it only if you think you know
1035 // what you are doing!
1041 // check if we had something else in mind, if not, this is the future
1043 if (x_target() == -1)
1048 // try neigbouring script insets
1052 InsetMathScript const * p = prevAtom()->asScriptInset();
1053 if (p && p->has(up)) {
1055 push(*const_cast<InsetMathScript*>(p));
1056 idx() = p->idxOfScript(up);
1063 if (pos() != lastpos()) {
1064 InsetMathScript const * p = nextAtom()->asScriptInset();
1065 if (p && p->has(up)) {
1066 push(*const_cast<InsetMathScript*>(p));
1067 idx() = p->idxOfScript(up);
1074 // FIXME: Switch this on for more robust movement
1077 return bruteFind3(*this, xo, yo, up);
1080 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1085 //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
1086 // lyxerr << "updown: handled by brute find in the same cell" << endl;
1090 // try to find an inset that knows better then we
1092 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1094 if (inset().idxUpDown(*this, up)) {
1095 //lyxerr << "idxUpDown triggered" << endl;
1096 // try to find best position within this inset
1098 setCursor(bruteFind2(*this, xo, yo));
1102 // no such inset found, just take something "above"
1104 //lyxerr << "updown: popleft failed (strange case)" << endl;
1105 int ylow = up ? 0 : yo + 1;
1106 int yhigh = up ? yo - 1 : bv().workHeight();
1107 return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
1110 // any improvement so far?
1111 //lyxerr << "updown: popLeft succeeded" << endl;
1115 if (up ? ynew < yo : ynew > yo)
1119 // we should not come here.
1120 BOOST_ASSERT(false);
1125 void Cursor::handleFont(string const & font)
1127 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << ": " << font << endl;
1131 safe = cap::grabAndEraseSelection(*this);
1134 if (lastpos() != 0) {
1135 // something left in the cell
1137 // cursor in first position
1139 } else if (pos() == lastpos()) {
1140 // cursor in last position
1143 // cursor in between. split cell
1144 MathData::iterator bt = cell().begin();
1145 MathAtom at = createInsetMath(from_utf8(font));
1146 at.nucleus()->cell(0) = MathData(bt, bt + pos());
1147 cell().erase(bt, bt + pos());
1152 // nothing left in the cell
1160 void Cursor::message(docstring const & msg) const
1162 theLyXFunc().setMessage(msg);
1166 void Cursor::errorMessage(docstring const & msg) const
1168 theLyXFunc().setErrorMessage(msg);
1172 docstring Cursor::selectionAsString(bool label) const
1178 Buffer const & buffer = *bv().buffer();
1179 ParagraphList const & pars = text()->paragraphs();
1181 // should be const ...
1182 pit_type startpit = selBegin().pit();
1183 pit_type endpit = selEnd().pit();
1184 size_t const startpos = selBegin().pos();
1185 size_t const endpos = selEnd().pos();
1187 if (startpit == endpit)
1188 return pars[startpit].asString(buffer, startpos, endpos, label);
1190 // First paragraph in selection
1191 docstring result = pars[startpit].
1192 asString(buffer, startpos, pars[startpit].size(), label)
1193 + parbreak(pars[startpit]);
1195 // The paragraphs in between (if any)
1196 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1197 Paragraph const & par = pars[pit];
1198 result += par.asString(buffer, 0, par.size(), label)
1199 + parbreak(pars[pit]);
1202 // Last paragraph in selection
1203 result += pars[endpit].asString(buffer, 0, endpos, label);
1209 return cap::grabSelection(*this);
1215 docstring Cursor::currentState()
1218 odocstringstream os;
1224 return text()->currentState(*this);
1230 docstring Cursor::getPossibleLabel()
1232 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
1236 Encoding const * Cursor::getEncoding() const
1243 // go up until first non-0 text is hit
1244 // (innermost text is 0 in mathed)
1245 for (s = depth() - 1; s >= 0; --s)
1246 if (operator[](s).text())
1248 CursorSlice const & sl = operator[](s);
1249 Text const & text = *sl.text();
1250 Font font = text.getPar(sl.pit()).getFont(
1251 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1252 return font.language()->encoding();
1256 void Cursor::undispatched()
1258 disp_.dispatched(false);
1262 void Cursor::dispatched()
1264 disp_.dispatched(true);
1268 void Cursor::updateFlags(Update::flags f)
1274 void Cursor::noUpdate()
1276 disp_.update(Update::None);
1280 Font Cursor::getFont() const
1282 // HACK. far from being perfect...
1284 // go up until first non-0 text is hit
1285 // (innermost text is 0 in mathed)
1286 for (s = depth() - 1; s >= 0; --s)
1287 if (operator[](s).text())
1289 CursorSlice const & sl = operator[](s);
1290 Text const & text = *sl.text();
1291 Font font = text.getPar(sl.pit()).getFont(
1292 bv().buffer()->params(),
1294 outerFont(sl.pit(), text.paragraphs()));
1300 void Cursor::fixIfBroken()
1302 if (DocIterator::fixIfBroken()) {