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"
19 #include "dispatchresult.h"
21 #include "funcrequest.h"
22 #include "iterators.h"
26 #include "lyxfunc.h" // only for setMessage()
30 #include "paragraph.h"
31 #include "paragraph_funcs.h"
33 #include "insets/updatableinset.h"
34 #include "insets/insettabular.h"
35 #include "insets/insettext.h"
37 #include "mathed/math_data.h"
38 #include "mathed/math_hullinset.h"
39 #include "mathed/math_support.h"
41 #include "support/limited_stack.h"
42 #include "support/std_sstream.h"
44 #include "frontends/LyXView.h"
46 #include <boost/assert.hpp>
51 #ifndef CXX_GLOBAL_CSTD
60 limited_stack<string> theCutBuffer;
63 LCursor::LCursor(BufferView & bv)
64 : DocumentIterator(), bv_(&bv), anchor_(),
65 cached_y_(0), x_target_(-1), selection_(false), mark_(false)
72 push_back(CursorSlice());
74 anchor_.push_back(CursorSlice());
82 void LCursor::setCursor(DocumentIterator const & cur, bool sel)
84 // this (intentionally) does not touch the anchor
85 DocumentIterator::operator=(cur);
90 DispatchResult LCursor::dispatch(FuncRequest const & cmd0)
93 return DispatchResult();
95 //lyxerr << "\nLCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
96 FuncRequest cmd = cmd0;
98 DocumentIterator safe = *this;
100 for ( ; size(); pop_back()) {
101 lyxerr << "\nLCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
102 BOOST_ASSERT(pos() <= lastpos());
103 BOOST_ASSERT(idx() <= lastidx());
104 BOOST_ASSERT(par() <= lastpar());
106 // The common case is 'LFUN handled, need update', so make the
107 // LFUN handler's life easier by assuming this as default value.
108 // The handler can reset the update and val flags if necessary.
110 disp_.dispatched(true);
111 inset().dispatch(*this, cmd);
112 if (disp_.dispatched())
115 // it completely to get a 'bomb early' behaviour in case this
116 // object will be used again.
117 if (nopop_ || !disp_.dispatched())
118 DocumentIterator::operator=(safe);
123 bool LCursor::getStatus(FuncRequest const & cmd, FuncStatus & status)
125 lyxerr << "\nLCursor::getStatus: cmd: " << cmd << endl << *this << endl;
126 DocumentIterator safe = *this;
127 for ( ; size(); pop_back()) {
128 BOOST_ASSERT(pos() <= lastpos());
129 BOOST_ASSERT(idx() <= lastidx());
130 BOOST_ASSERT(par() <= lastpar());
132 // The inset's getStatus() will return 'true' if it made
133 // a definitive decision on whether it want to handle the
134 // request or not. The result of this decision is put into
135 // the 'status' parameter.
136 if (inset().getStatus(*this, cmd, status))
139 DocumentIterator::operator=(safe);
144 BufferView & LCursor::bv() const
152 BOOST_ASSERT(size() >= 1);
158 void LCursor::push(InsetBase & p)
160 push_back(CursorSlice(p));
164 void LCursor::pushLeft(InsetBase & p)
166 BOOST_ASSERT(!empty());
167 //lyxerr << "Entering inset " << t << " left" << endl;
173 bool LCursor::popLeft()
175 BOOST_ASSERT(!empty());
176 //lyxerr << "Leaving inset to the left" << endl;
179 inset().notifyCursorLeaves(idx());
182 inset().notifyCursorLeaves(idx());
188 bool LCursor::popRight()
190 BOOST_ASSERT(!empty());
191 //lyxerr << "Leaving inset to the right" << endl;
194 inset().notifyCursorLeaves(idx());
197 inset().notifyCursorLeaves(idx());
204 int LCursor::currentMode()
206 BOOST_ASSERT(!empty());
207 for (int i = size() - 1; i >= 1; --i) {
208 int res = operator[](i).inset().currentMode();
209 if (res != MathInset::UNDECIDED_MODE)
212 return MathInset::TEXT_MODE;
216 void LCursor::updatePos()
218 BOOST_ASSERT(!empty());
220 cached_y_ = bv().top_y() + back().inset().yo();
221 //cached_y_ = back().inset().yo();
225 void LCursor::getDim(int & asc, int & des) const
228 BOOST_ASSERT(inset().asMathInset());
229 //inset().asMathInset()->getCursorDim(asc, des);
232 } else if (inTexted()) {
233 Row const & row = textRow();
234 asc = row.baseline();
235 des = row.height() - asc;
237 lyxerr << "should this happen?" << endl;
244 void LCursor::getPos(int & x, int & y) const
249 inset().getCursorPos(back(), x, y);
250 // getCursorPos gives _screen_ coordinates. We need to add
251 // top_y to get document coordinates. This is hidden in cached_y_.
252 //y += cached_y_ - inset().yo();
253 // The rest is non-obvious. The reason we have to have these
254 // extra computation is that the getCursorPos() calls rely
255 // on the inset's own knowledge of its screen position.
256 // If we scroll up or down in a big enough increment,
257 // inset->draw() is not called: this doesn't update
258 // inset.yo_, so getCursor() returns an old value.
263 void LCursor::paste(string const & data)
265 dispatch(FuncRequest(LFUN_PASTE, data));
269 void LCursor::resetAnchor()
276 bool LCursor::posLeft()
285 bool LCursor::posRight()
287 if (pos() == lastpos())
294 CursorSlice & LCursor::anchor()
296 return anchor_.back();
300 CursorSlice const & LCursor::anchor() const
302 return anchor_.back();
306 CursorSlice const & LCursor::selBegin() const
310 return anchor() < back() ? anchor() : back();
314 CursorSlice & LCursor::selBegin()
318 // can't use std::min as this returns a const ref
319 return anchor() < back() ? anchor() : back();
323 CursorSlice const & LCursor::selEnd() const
327 return anchor() > back() ? anchor() : back();
331 CursorSlice & LCursor::selEnd()
335 // can't use std::min as this returns a const ref
336 return anchor() > back() ? anchor() : back();
340 void LCursor::setSelection()
343 // a selection with no contents is not a selection
344 if (par() == anchor().par() && pos() == anchor().pos())
349 void LCursor::setSelection(DocumentIterator const & where, size_t n)
352 setCursor(where, false);
358 void LCursor::clearSelection()
367 int & LCursor::x_target()
373 int LCursor::x_target() const
379 void LCursor::clearTargetX()
386 void LCursor::info(std::ostream & os) const
388 for (int i = 1, n = depth(); i < n; ++i) {
389 operator[](i).inset().infoize(os);
393 prevInset()->infoize2(os);
394 // overwite old message
401 void region(CursorSlice const & i1, CursorSlice const & i2,
402 LCursor::row_type & r1, LCursor::row_type & r2,
403 LCursor::col_type & c1, LCursor::col_type & c2)
405 InsetBase & p = i1.inset();
419 string LCursor::grabSelection()
424 CursorSlice i1 = selBegin();
425 CursorSlice i2 = selEnd();
427 if (i1.idx_ == i2.idx_) {
428 if (i1.inset().asMathInset()) {
429 MathArray::const_iterator it = i1.cell().begin();
430 return asString(MathArray(it + i1.pos_, it + i2.pos_));
432 return "unknown selection 1";
438 region(i1, i2, r1, r2, c1, c2);
441 if (i1.inset().asMathInset()) {
442 for (row_type row = r1; row <= r2; ++row) {
445 for (col_type col = c1; col <= c2; ++col) {
448 data += asString(i1.asMathInset()->cell(i1.asMathInset()->index(row, col)));
452 data = "unknown selection 2";
458 void LCursor::eraseSelection()
460 //lyxerr << "LCursor::eraseSelection" << endl;
461 CursorSlice const & i1 = selBegin();
462 CursorSlice const & i2 = selEnd();
464 if (i1.inset().asMathInset()) {
465 if (i1.idx_ == i2.idx_) {
466 i1.cell().erase(i1.pos_, i2.pos_);
468 MathInset * p = i1.asMathInset();
471 region(i1, i2, r1, r2, c1, c2);
472 for (row_type row = r1; row <= r2; ++row)
473 for (col_type col = c1; col <= c2; ++col)
474 p->cell(p->index(row, col)).clear();
478 lyxerr << "can't erase this selection 1" << endl;
480 //lyxerr << "LCursor::eraseSelection end" << endl;
484 string LCursor::grabAndEraseSelection()
488 string res = grabSelection();
495 void LCursor::selClear()
502 void LCursor::selCopy()
505 theCutBuffer.push(grabSelection());
508 //theCutBuffer.erase();
513 void LCursor::selCut()
515 theCutBuffer.push(grabAndEraseSelection());
519 void LCursor::selDel()
521 //lyxerr << "LCursor::selDel" << endl;
529 void LCursor::selPaste(size_t n)
532 if (n < theCutBuffer.size())
533 paste(theCutBuffer[n]);
539 void LCursor::selHandle(bool sel)
541 //lyxerr << "LCursor::selHandle" << endl;
542 if (sel == selection())
549 void LCursor::selClearOrDel()
551 //lyxerr << "LCursor::selClearOrDel" << endl;
552 if (lyxrc.auto_region_delete)
559 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
561 for (size_t i = 0, n = cur.size(); i != n; ++i)
562 os << " " << cur.operator[](i) << " | " << cur.anchor_[i] << "\n";
563 os << " selection: " << cur.selection_ << endl;
570 ///////////////////////////////////////////////////////////////////
572 // The part below is the non-integrated rest of the original math
573 // cursor. This should be either generalized for texted or moved
574 // back to mathed (in most cases to MathNestInset).
576 ///////////////////////////////////////////////////////////////////
578 #include "mathed/math_charinset.h"
579 #include "mathed/math_factory.h"
580 #include "mathed/math_gridinset.h"
581 #include "mathed/math_macroarg.h"
582 #include "mathed/math_macrotemplate.h"
583 #include "mathed/math_mathmlstream.h"
584 #include "mathed/math_scriptinset.h"
585 #include "mathed/math_support.h"
586 #include "mathed/math_unknowninset.h"
588 //#define FILEDEBUG 1
591 bool LCursor::isInside(InsetBase const * p)
593 for (unsigned i = 0; i < depth(); ++i)
594 if (&operator[](i).inset() == p)
600 bool LCursor::openable(MathAtom const & t) const
611 // we can't move into anything new during selection
612 if (depth() == anchor_.size())
614 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
621 bool positionable(DocumentIterator const & cursor,
622 DocumentIterator const & anchor)
624 // avoid deeper nested insets when selecting
625 if (cursor.size() > anchor.size())
628 // anchor might be deeper, should have same path then
629 for (size_t i = 0; i < cursor.size(); ++i)
630 if (&cursor[i].inset() != &anchor[i].inset())
633 // position should be ok.
638 void LCursor::setScreenPos(int x, int y)
640 bool res = bruteFind(x, y, formula()->xlow(), formula()->xhigh(),
641 formula()->ylow(), formula()->yhigh());
643 // this can happen on creation of "math-display"
652 void LCursor::plainErase()
658 void LCursor::markInsert()
660 cell().insert(pos(), MathAtom(new MathCharInset(0)));
664 void LCursor::markErase()
670 void LCursor::plainInsert(MathAtom const & t)
672 cell().insert(pos(), t);
677 void LCursor::insert(string const & str)
679 lyxerr << "LCursor::insert str '" << str << "'" << endl;
680 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
685 void LCursor::insert(char c)
687 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
688 BOOST_ASSERT(!empty());
691 plainInsert(MathAtom(new MathCharInset(c)));
693 text()->insertChar(*this, c);
698 void LCursor::insert(MathAtom const & t)
700 //lyxerr << "LCursor::insert MathAtom: " << endl;
707 void LCursor::insert(InsetBase * inset)
710 insert(MathAtom(inset));
712 text()->insertInset(*this, inset);
716 void LCursor::niceInsert(string const & t)
727 void LCursor::niceInsert(MathAtom const & t)
730 string safe = grabAndEraseSelection();
732 // enter the new inset and move the contents of the selection if possible
735 // be careful here: don't use 'pushLeft(t)' as this we need to
736 // push the clone, not the original
737 pushLeft(*nextInset());
743 void LCursor::insert(MathArray const & ar)
748 cell().insert(pos(), ar);
753 bool LCursor::backspace()
755 autocorrect() = false;
763 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
770 MathUnknownInset * p = activeMacro();
771 if (p->name().size() > 1) {
772 p->setName(p->name().substr(0, p->name().size() - 1));
777 if (pos() != 0 && prevAtom()->nargs() > 0) {
778 // let's require two backspaces for 'big stuff' and
779 // highlight on the first
790 bool LCursor::erase()
792 autocorrect() = false;
801 // delete empty cells if possible
802 if (pos() == lastpos() && inset().idxDelete(idx()))
805 // special behaviour when in last position of cell
806 if (pos() == lastpos()) {
807 bool one_cell = inset().nargs() == 1;
808 if (one_cell && depth() == 1 && lastpos() == 0)
814 inset().idxGlue(idx());
818 if (pos() != lastpos() && inset().nargs() > 0) {
832 DocumentIterator save = *this;
835 setCursor(save, false);
836 autocorrect() = false;
844 DocumentIterator save = *this;
847 setCursor(save, false);
848 autocorrect() = false;
853 void LCursor::macroModeClose()
857 MathUnknownInset * p = activeMacro();
859 string s = p->name();
863 // do nothing if the macro name is empty
867 string const name = s.substr(1);
869 // prevent entering of recursive macros
870 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
871 if (macro && macro->getInsetName() == name)
872 lyxerr << "can't enter recursive macro" << endl;
874 niceInsert(createMathInset(name));
878 string LCursor::macroName()
880 return inMacroMode() ? activeMacro()->name() : string();
884 void LCursor::handleNest(MathAtom const & a, int c)
886 //lyxerr << "LCursor::handleNest: " << c << endl;
888 asArray(grabAndEraseSelection(), t.nucleus()->cell(c));
891 pushLeft(*nextInset());
895 int LCursor::targetX() const
897 if (x_target() != -1)
906 MathHullInset * LCursor::formula() const
908 for (int i = size() - 1; i >= 1; --i) {
909 MathInset * inset = operator[](i).inset().asMathInset();
910 if (inset && inset->asHullInset())
911 return static_cast<MathHullInset *>(inset);
917 void LCursor::adjust(pos_type from, int diff)
921 if (anchor().pos_ > from)
922 anchor().pos_ += diff;
923 // just to be on the safe side
924 // theoretically unecessary
929 bool LCursor::inMacroMode() const
933 MathUnknownInset const * p = prevAtom()->asUnknownInset();
934 return p && !p->final();
938 MathUnknownInset * LCursor::activeMacro()
940 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
944 bool LCursor::inMacroArgMode() const
946 return pos() > 0 && prevAtom()->getChar() == '#';
950 MathGridInset * LCursor::enclosingGrid(idx_type & idx) const
952 for (MathInset::difference_type i = depth() - 1; i >= 0; --i) {
953 MathInset * m = operator[](i).inset().asMathInset();
956 MathGridInset * p = m->asGridInset();
958 idx = operator[](i).idx_;
966 void LCursor::pullArg()
969 MathArray ar = cell();
970 if (popLeft() && inMathed()) {
972 cell().insert(pos(), ar);
975 //formula()->mutateToText();
980 void LCursor::touch()
984 DocumentIterator::const_iterator it = begin();
985 DocumentIterator::const_iterator et = end();
986 for ( ; it != et; ++it)
992 void LCursor::normalize()
994 if (idx() >= nargs()) {
995 lyxerr << "this should not really happen - 1: "
996 << idx() << ' ' << nargs()
997 << " in: " << &inset() << endl;
999 idx() = min(idx(), lastidx());
1001 if (pos() > lastpos()) {
1002 lyxerr << "this should not really happen - 2: "
1003 << pos() << ' ' << lastpos() << " in idx: " << idx()
1005 WriteStream wi(lyxerr, false, true);
1006 inset().asMathInset()->write(wi);
1009 pos() = min(pos(), lastpos());
1013 char LCursor::valign()
1016 MathGridInset * p = enclosingGrid(idx);
1017 return p ? p->valign() : '\0';
1021 char LCursor::halign()
1024 MathGridInset * p = enclosingGrid(idx);
1025 return p ? p->halign(idx % p->ncols()) : '\0';
1029 bool LCursor::goUpDown(bool up)
1031 // Be warned: The 'logic' implemented in this function is highly
1032 // fragile. A distance of one pixel or a '<' vs '<=' _really
1033 // matters. So fiddle around with it only if you think you know
1034 // what you are doing!
1039 // check if we had something else in mind, if not, this is the future goal
1040 if (x_target() == -1)
1045 // try neigbouring script insets
1049 MathScriptInset const * p = prevAtom()->asScriptInset();
1050 if (p && p->has(up)) {
1053 idx() = up; // the superscript has index 1
1055 //lyxerr << "updown: handled by scriptinset to the left" << endl;
1061 if (pos() != lastpos()) {
1062 MathScriptInset const * p = nextAtom()->asScriptInset();
1063 if (p && p->has(up)) {
1067 //lyxerr << "updown: handled by scriptinset to the right" << endl;
1073 // try current cell for e.g. text insets
1074 if (inset().idxUpDown2(*this, up))
1077 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1082 //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1083 // lyxerr << "updown: handled by brute find in the same cell" << endl;
1087 // try to find an inset that knows better then we
1089 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1091 if (inset().idxUpDown(*this, up)) {
1092 // try to find best position within this inset
1098 // no such inset found, just take something "above"
1099 //lyxerr << "updown: handled by strange case" << endl;
1105 up ? formula()->ylow() : yo + 4,
1106 up ? yo - 4 : formula()->yhigh()
1110 // any improvement so far?
1113 if (up ? ynew < yo : ynew > yo)
1119 bool LCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1121 DocumentIterator best_cursor;
1122 double best_dist = 1e10;
1124 DocumentIterator it = insetBegin(bv().buffer()->inset());
1125 DocumentIterator et = insetEnd();
1127 // avoid invalid nesting when selecting
1128 if (!selection() || positionable(it, anchor_)) {
1130 CursorSlice & cur = it.back();
1131 cur.inset().getCursorPos(cur, xo, yo);
1132 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1133 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1134 //lyxerr << "x: " << x << " y: " << y << " d: " << endl;
1135 // '<=' in order to take the last possible position
1136 // this is important for clicking behind \sum in e.g. '\sum_i a'
1137 if (d <= best_dist) {
1149 if (best_dist < 1e10)
1150 setCursor(best_cursor, false);
1151 return best_dist < 1e10;
1155 void LCursor::bruteFind2(int x, int y)
1157 double best_dist = 1e10;
1159 DocumentIterator it = *this;
1160 it.back().pos() = 0;
1161 DocumentIterator et = *this;
1162 et.back().pos() = et.back().asMathInset()->cell(et.back().idx_).size();
1163 for (int i = 0; ; ++i) {
1165 CursorSlice & cur = it.back();
1166 cur.inset().getCursorPos(cur, xo, yo);
1167 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1168 // '<=' in order to take the last possible position
1169 // this is important for clicking behind \sum in e.g. '\sum_i a'
1170 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
1171 if (d <= best_dist) {
1173 setCursor(it, false);
1182 CursorSlice LCursor::normalAnchor()
1184 if (anchor_.size() < depth()) {
1186 lyxerr << "unusual Anchor size" << endl;
1188 //lyx::BOOST_ASSERT(Anchor_.size() >= cursor.depth());
1189 // use Anchor on the same level as Cursor
1190 CursorSlice normal = anchor_[size() - 1];
1192 if (depth() < anchor_.size() && !(normal < xx())) {
1193 // anchor is behind cursor -> move anchor behind the inset
1201 void LCursor::handleFont(string const & font)
1203 lyxerr << "LCursor::handleFont: " << font << endl;
1207 safe = grabAndEraseSelection();
1210 if (lastpos() != 0) {
1211 // something left in the cell
1213 // cursor in first position
1215 } else if (pos() == lastpos()) {
1216 // cursor in last position
1219 // cursor in between. split cell
1220 MathArray::iterator bt = cell().begin();
1221 MathAtom at = createMathInset(font);
1222 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1223 cell().erase(bt, bt + pos());
1228 // nothing left in the cell
1236 void LCursor::message(string const & msg) const
1238 bv().owner()->getLyXFunc().setMessage(msg);
1242 void LCursor::errorMessage(string const & msg) const
1244 bv().owner()->getLyXFunc().setErrorMessage(msg);
1248 string LCursor::selectionAsString(bool label) const
1254 Buffer const & buffer = *bv().buffer();
1256 // should be const ...
1257 ParagraphList::iterator startpit = text()->getPar(selBegin());
1258 ParagraphList::iterator endpit = text()->getPar(selEnd());
1259 size_t const startpos = selBegin().pos();
1260 size_t const endpos = selEnd().pos();
1262 if (startpit == endpit)
1263 return startpit->asString(buffer, startpos, endpos, label);
1265 // First paragraph in selection
1267 startpit->asString(buffer, startpos, startpit->size(), label) + "\n\n";
1269 // The paragraphs in between (if any)
1270 ParagraphList::iterator pit = startpit;
1271 for (++pit; pit != endpit; ++pit)
1272 result += pit->asString(buffer, 0, pit->size(), label) + "\n\n";
1274 // Last paragraph in selection
1275 result += endpit->asString(buffer, 0, endpos, label);
1280 #warning and mathed?
1285 string LCursor::currentState()
1288 std::ostringstream os;
1294 return text()->currentState(*this);
1300 // only used by the spellchecker
1301 void LCursor::replaceWord(string const & replacestring)
1303 LyXText * t = text();
1306 t->replaceSelectionWithString(*this, replacestring);
1307 t->setSelectionRange(*this, replacestring.length());
1309 // Go back so that replacement string is also spellchecked
1310 for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
1311 t->cursorLeft(*this);
1315 void LCursor::update()
1321 string LCursor::getPossibleLabel()
1323 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1327 Encoding const * LCursor::getEncoding() const
1334 // go up until first non-0 text is hit
1335 // (innermost text is 0 in mathed)
1336 for (s = size() - 1; s >= 0; --s)
1337 if (operator[](s).text())
1339 CursorSlice const & sl = operator[](s);
1340 LyXText & text = *sl.text();
1341 ParagraphList::iterator pit = text.getPar(sl.par());
1342 LyXFont font = pit->getFont(
1343 bv().buffer()->params(), sl.pos(), outerFont(pit, text.paragraphs()));
1344 return font.language()->encoding();
1348 void LCursor::undispatched()
1350 disp_.dispatched(false);
1354 void LCursor::noUpdate()
1356 disp_.update(false);