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_support.h"
39 #include "mathed/math_inset.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;
65 void region(CursorSlice const & i1, CursorSlice const & i2,
66 LCursor::row_type & r1, LCursor::row_type & r2,
67 LCursor::col_type & c1, LCursor::col_type & c2)
69 InsetBase & p = i1.inset();
83 LCursor::LCursor(BufferView & bv)
84 : DocumentIterator(), bv_(&bv), anchor_(),
85 cached_y_(0), x_target_(-1), selection_(false), mark_(false)
92 push_back(CursorSlice());
94 anchor_.push_back(CursorSlice());
102 void LCursor::setCursor(DocumentIterator const & cur, bool sel)
104 // this (intentionally) does not touch the anchor
105 DocumentIterator::operator=(cur);
110 DispatchResult LCursor::dispatch(FuncRequest const & cmd0)
113 return DispatchResult();
115 //lyxerr << "\nLCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
116 FuncRequest cmd = cmd0;
118 LCursor safe = *this;
120 for ( ; size(); pop()) {
121 //lyxerr << "\nLCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
122 BOOST_ASSERT(pos() <= lastpos());
123 BOOST_ASSERT(idx() <= lastidx());
124 BOOST_ASSERT(par() <= lastpar());
126 // The common case is 'LFUN handled, need update', so make the
127 // LFUN handler's life easier by assuming this as default value.
128 // The handler can reset the update and val flags if necessary.
130 disp_.dispatched(true);
131 inset().dispatch(*this, cmd);
132 if (disp_.dispatched())
135 // it completely to get a 'bomb early' behaviour in case this
136 // object will be used again.
137 if (nopop_ || !disp_.dispatched())
143 bool LCursor::getStatus(FuncRequest const & cmd, FuncStatus & status)
145 LCursor safe = *this;
146 for ( ; size(); pop()) {
147 //lyxerr << "\nLCursor::getStatus: cmd: " << cmd << endl << *this << endl;
148 BOOST_ASSERT(pos() <= lastpos());
149 BOOST_ASSERT(idx() <= lastidx());
150 BOOST_ASSERT(par() <= lastpar());
152 // The inset's getStatus() will return 'true' if it made
153 // a definitive decision on whether it want to handle the
154 // request or not. The result of this decision is put into
155 // the 'status' parameter.
156 if (inset().getStatus(*this, cmd, status))
164 BufferView & LCursor::bv() const
172 BOOST_ASSERT(size() >= 1);
178 void LCursor::push(InsetBase & p)
180 push_back(CursorSlice(p));
184 void LCursor::pushLeft(InsetBase & p)
186 BOOST_ASSERT(!empty());
187 //lyxerr << "Entering inset " << t << " left" << endl;
193 bool LCursor::popLeft()
195 BOOST_ASSERT(!empty());
196 //lyxerr << "Leaving inset to the left" << endl;
197 inset().notifyCursorLeaves(idx());
205 bool LCursor::popRight()
207 BOOST_ASSERT(!empty());
208 //lyxerr << "Leaving inset to the right" << endl;
209 inset().notifyCursorLeaves(idx());
218 int LCursor::currentMode()
220 BOOST_ASSERT(!empty());
221 for (int i = size() - 1; i >= 0; --i) {
222 int res = operator[](i).inset().currentMode();
223 if (res != InsetBase::UNDECIDED_MODE)
226 return InsetBase::TEXT_MODE;
230 void LCursor::updatePos()
232 BOOST_ASSERT(!empty());
234 cached_y_ = bv().top_y() + back().inset().yo();
235 //cached_y_ = back().inset().yo();
239 void LCursor::getDim(int & asc, int & des) const
242 BOOST_ASSERT(inset().asMathInset());
243 //inset().asMathInset()->getCursorDim(asc, des);
246 } else if (inTexted()) {
247 Row const & row = textRow();
248 asc = row.baseline();
249 des = row.height() - asc;
251 lyxerr << "should this happen?" << endl;
258 void LCursor::getPos(int & x, int & y) const
263 inset().getCursorPos(back(), x, y);
264 // getCursorPos gives _screen_ coordinates. We need to add
265 // top_y to get document coordinates. This is hidden in cached_y_.
266 //y += cached_y_ - inset().yo();
267 // The rest is non-obvious. The reason we have to have these
268 // extra computation is that the getCursorPos() calls rely
269 // on the inset's own knowledge of its screen position.
270 // If we scroll up or down in a big enough increment,
271 // inset->draw() is not called: this doesn't update
272 // inset.yo_, so getCursor() returns an old value.
277 void LCursor::paste(string const & data)
279 dispatch(FuncRequest(LFUN_PASTE, data));
283 void LCursor::resetAnchor()
290 bool LCursor::posLeft()
299 bool LCursor::posRight()
301 if (pos() == lastpos())
308 CursorSlice & LCursor::anchor()
310 return anchor_.back();
314 CursorSlice const & LCursor::anchor() const
316 return anchor_.back();
320 CursorSlice const & LCursor::selBegin() const
324 return anchor() < back() ? anchor() : back();
328 CursorSlice & LCursor::selBegin()
332 // can't use std::min as this returns a const ref
333 return anchor() < back() ? anchor() : back();
337 CursorSlice const & LCursor::selEnd() const
341 return anchor() > back() ? anchor() : back();
345 CursorSlice & LCursor::selEnd()
349 // can't use std::min as this returns a const ref
350 return anchor() > back() ? anchor() : back();
354 void LCursor::setSelection()
357 // a selection with no contents is not a selection
358 if (par() == anchor().par() && pos() == anchor().pos())
363 void LCursor::setSelection(DocumentIterator const & where, size_t n)
366 setCursor(where, false);
372 void LCursor::clearSelection()
381 int & LCursor::x_target()
387 int LCursor::x_target() const
393 void LCursor::clearTargetX()
400 void LCursor::info(std::ostream & os) const
402 for (int i = 1, n = depth(); i < n; ++i) {
403 operator[](i).inset().infoize(os);
407 prevInset()->infoize2(os);
408 // overwite old message
413 string LCursor::grabSelection()
418 CursorSlice i1 = selBegin();
419 CursorSlice i2 = selEnd();
421 if (i1.idx_ == i2.idx_) {
422 if (i1.inset().asMathInset()) {
423 MathArray::const_iterator it = i1.cell().begin();
424 return asString(MathArray(it + i1.pos_, it + i2.pos_));
426 return "unknown selection 1";
432 region(i1, i2, r1, r2, c1, c2);
435 if (i1.inset().asMathInset()) {
436 for (row_type row = r1; row <= r2; ++row) {
439 for (col_type col = c1; col <= c2; ++col) {
442 data += asString(i1.asMathInset()->cell(i1.asMathInset()->index(row, col)));
446 data = "unknown selection 2";
452 void LCursor::eraseSelection()
454 //lyxerr << "LCursor::eraseSelection" << endl;
455 CursorSlice const & i1 = selBegin();
456 CursorSlice const & i2 = selEnd();
458 if (i1.inset().asMathInset()) {
459 if (i1.idx_ == i2.idx_) {
460 i1.cell().erase(i1.pos_, i2.pos_);
462 MathInset * p = i1.asMathInset();
465 region(i1, i2, r1, r2, c1, c2);
466 for (row_type row = r1; row <= r2; ++row)
467 for (col_type col = c1; col <= c2; ++col)
468 p->cell(p->index(row, col)).clear();
472 lyxerr << "can't erase this selection 1" << endl;
474 //lyxerr << "LCursor::eraseSelection end" << endl;
478 string LCursor::grabAndEraseSelection()
482 string res = grabSelection();
489 void LCursor::selClear()
496 void LCursor::selCopy()
499 theCutBuffer.push(grabSelection());
502 //theCutBuffer.erase();
507 void LCursor::selCut()
509 theCutBuffer.push(grabAndEraseSelection());
513 void LCursor::selDel()
515 //lyxerr << "LCursor::selDel" << endl;
523 void LCursor::selPaste(size_t n)
526 if (n < theCutBuffer.size())
527 paste(theCutBuffer[n]);
533 void LCursor::selHandle(bool sel)
535 //lyxerr << "LCursor::selHandle" << endl;
536 if (sel == selection())
543 void LCursor::selClearOrDel()
545 //lyxerr << "LCursor::selClearOrDel" << endl;
546 if (lyxrc.auto_region_delete)
553 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
555 for (size_t i = 0, n = cur.size(); i != n; ++i)
556 os << " " << cur.operator[](i) << " | " << cur.anchor_[i] << "\n";
557 os << " selection: " << cur.selection_ << endl;
564 ///////////////////////////////////////////////////////////////////
566 // The part below is the non-integrated rest of the original math
567 // cursor. This should be either generalized for texted or moved
568 // back to mathed (in most cases to MathNestInset).
570 ///////////////////////////////////////////////////////////////////
572 #include "mathed/math_charinset.h"
573 #include "mathed/math_factory.h"
574 #include "mathed/math_gridinset.h"
575 #include "mathed/math_macroarg.h"
576 #include "mathed/math_macrotemplate.h"
577 #include "mathed/math_mathmlstream.h"
578 #include "mathed/math_scriptinset.h"
579 #include "mathed/math_support.h"
580 #include "mathed/math_unknowninset.h"
582 //#define FILEDEBUG 1
585 bool LCursor::isInside(InsetBase const * p)
587 for (unsigned i = 0; i < depth(); ++i)
588 if (&operator[](i).inset() == p)
594 bool LCursor::openable(MathAtom const & t) const
605 // we can't move into anything new during selection
606 if (depth() == anchor_.size())
608 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
615 bool positionable(DocumentIterator const & cursor,
616 DocumentIterator const & anchor)
618 // avoid deeper nested insets when selecting
619 if (cursor.size() > anchor.size())
622 // anchor might be deeper, should have same path then
623 for (size_t i = 0; i < cursor.size(); ++i)
624 if (&cursor[i].inset() != &anchor[i].inset())
627 // position should be ok.
632 void LCursor::setScreenPos(int x, int y)
635 bruteFind(x, y, 0, bv().workWidth(), 0, bv().workHeight());
640 void LCursor::plainErase()
646 void LCursor::markInsert()
648 cell().insert(pos(), MathAtom(new MathCharInset(0)));
652 void LCursor::markErase()
658 void LCursor::plainInsert(MathAtom const & t)
660 cell().insert(pos(), t);
665 void LCursor::insert(string const & str)
667 lyxerr << "LCursor::insert str '" << str << "'" << endl;
668 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
673 void LCursor::insert(char c)
675 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
676 BOOST_ASSERT(!empty());
679 plainInsert(MathAtom(new MathCharInset(c)));
681 text()->insertChar(*this, c);
686 void LCursor::insert(MathAtom const & t)
688 //lyxerr << "LCursor::insert MathAtom: " << endl;
695 void LCursor::insert(InsetBase * inset)
698 insert(MathAtom(inset));
700 text()->insertInset(*this, inset);
704 void LCursor::niceInsert(string const & t)
715 void LCursor::niceInsert(MathAtom const & t)
718 string safe = grabAndEraseSelection();
720 // enter the new inset and move the contents of the selection if possible
723 // be careful here: don't use 'pushLeft(t)' as this we need to
724 // push the clone, not the original
725 pushLeft(*nextInset());
731 void LCursor::insert(MathArray const & ar)
736 cell().insert(pos(), ar);
741 bool LCursor::backspace()
743 autocorrect() = false;
751 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
758 MathUnknownInset * p = activeMacro();
759 if (p->name().size() > 1) {
760 p->setName(p->name().substr(0, p->name().size() - 1));
765 if (pos() != 0 && prevAtom()->nargs() > 0) {
766 // let's require two backspaces for 'big stuff' and
767 // highlight on the first
778 bool LCursor::erase()
780 autocorrect() = false;
789 // delete empty cells if possible
790 if (pos() == lastpos() && inset().idxDelete(idx()))
793 // special behaviour when in last position of cell
794 if (pos() == lastpos()) {
795 bool one_cell = inset().nargs() == 1;
796 if (one_cell && depth() == 1 && lastpos() == 0)
802 inset().idxGlue(idx());
806 if (pos() != lastpos() && inset().nargs() > 0) {
820 DocumentIterator save = *this;
823 setCursor(save, false);
824 autocorrect() = false;
832 DocumentIterator save = *this;
835 setCursor(save, false);
836 autocorrect() = false;
841 void LCursor::macroModeClose()
845 MathUnknownInset * p = activeMacro();
847 string s = p->name();
851 // do nothing if the macro name is empty
855 string const name = s.substr(1);
857 // prevent entering of recursive macros
858 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
859 if (macro && macro->getInsetName() == name)
860 lyxerr << "can't enter recursive macro" << endl;
862 niceInsert(createMathInset(name));
866 string LCursor::macroName()
868 return inMacroMode() ? activeMacro()->name() : string();
872 void LCursor::handleNest(MathAtom const & a, int c)
874 //lyxerr << "LCursor::handleNest: " << c << endl;
876 asArray(grabAndEraseSelection(), t.nucleus()->cell(c));
879 pushLeft(*nextInset());
883 int LCursor::targetX() const
885 if (x_target() != -1)
894 void LCursor::adjust(pos_type from, int diff)
898 if (anchor().pos_ > from)
899 anchor().pos_ += diff;
900 // just to be on the safe side
901 // theoretically unecessary
906 bool LCursor::inMacroMode() const
910 MathUnknownInset const * p = prevAtom()->asUnknownInset();
911 return p && !p->final();
915 MathUnknownInset * LCursor::activeMacro()
917 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
921 bool LCursor::inMacroArgMode() const
923 return pos() > 0 && prevAtom()->getChar() == '#';
927 MathGridInset * LCursor::enclosingGrid(idx_type & idx) const
929 for (MathInset::difference_type i = depth() - 1; i >= 0; --i) {
930 MathInset * m = operator[](i).inset().asMathInset();
933 MathGridInset * p = m->asGridInset();
935 idx = operator[](i).idx_;
943 void LCursor::pullArg()
946 MathArray ar = cell();
947 if (popLeft() && inMathed()) {
949 cell().insert(pos(), ar);
952 //formula()->mutateToText();
957 void LCursor::touch()
961 DocumentIterator::const_iterator it = begin();
962 DocumentIterator::const_iterator et = end();
963 for ( ; it != et; ++it)
969 void LCursor::normalize()
971 if (idx() >= nargs()) {
972 lyxerr << "this should not really happen - 1: "
973 << idx() << ' ' << nargs()
974 << " in: " << &inset() << endl;
976 idx() = min(idx(), lastidx());
978 if (pos() > lastpos()) {
979 lyxerr << "this should not really happen - 2: "
980 << pos() << ' ' << lastpos() << " in idx: " << idx()
982 WriteStream wi(lyxerr, false, true);
983 inset().asMathInset()->write(wi);
986 pos() = min(pos(), lastpos());
990 char LCursor::valign()
993 MathGridInset * p = enclosingGrid(idx);
994 return p ? p->valign() : '\0';
998 char LCursor::halign()
1001 MathGridInset * p = enclosingGrid(idx);
1002 return p ? p->halign(idx % p->ncols()) : '\0';
1006 bool LCursor::goUpDown(bool up)
1008 // Be warned: The 'logic' implemented in this function is highly
1009 // fragile. A distance of one pixel or a '<' vs '<=' _really
1010 // matters. So fiddle around with it only if you think you know
1011 // what you are doing!
1017 // check if we had something else in mind, if not, this is the future goal
1018 if (x_target() == -1)
1023 // try neigbouring script insets
1027 MathScriptInset const * p = prevAtom()->asScriptInset();
1028 if (p && p->has(up)) {
1031 idx() = up; // the superscript has index 1
1033 //lyxerr << "updown: handled by scriptinset to the left" << endl;
1039 if (pos() != lastpos()) {
1040 MathScriptInset const * p = nextAtom()->asScriptInset();
1041 if (p && p->has(up)) {
1045 //lyxerr << "updown: handled by scriptinset to the right" << endl;
1051 // try current cell for e.g. text insets
1052 if (inset().idxUpDown2(*this, up))
1055 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1060 //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1061 // lyxerr << "updown: handled by brute find in the same cell" << endl;
1065 // try to find an inset that knows better then we
1067 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1069 if (inset().idxUpDown(*this, up)) {
1070 // try to find best position within this inset
1076 // no such inset found, just take something "above"
1077 //lyxerr << "updown: handled by strange case" << endl;
1079 int ylow = up ? 0 : yo + 1;
1080 int yhigh = up ? yo - 1 : bv().workHeight();
1081 return bruteFind(xo, yo, 0, bv().workWidth(), ylow, yhigh);
1084 // any improvement so far?
1087 if (up ? ynew < yo : ynew > yo)
1093 bool LCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1095 BOOST_ASSERT(!empty());
1096 ParagraphList::iterator beg;
1097 ParagraphList::iterator end;
1098 CursorSlice bottom = operator[](0);
1099 LyXText * text = bottom.text();
1101 getParsInRange(text->paragraphs(), ylow, yhigh, beg, end);
1103 DocumentIterator it = insetBegin(bv().buffer()->inset());
1104 DocumentIterator et;
1105 lyxerr << "x: " << x << " y: " << y << endl;
1106 lyxerr << "xlow: " << xlow << " ylow: " << ylow << endl;
1107 lyxerr << "xhigh: " << xhigh << " yhigh: " << yhigh << endl;
1109 it.par() = text->parOffset(beg);
1110 //et.par() = text->parOffset(end);
1112 double best_dist = 10e10;
1113 DocumentIterator best_cursor = it;
1115 for ( ; it != et; it.forwardPos()) {
1116 // avoid invalid nesting when selecting
1117 if (!selection() || positionable(it, anchor_)) {
1119 CursorSlice & cur = it.back();
1120 cur.inset().getCursorPos(cur, xo, yo);
1121 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1122 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1123 lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
1124 // '<=' in order to take the last possible position
1125 // this is important for clicking behind \sum in e.g. '\sum_i a'
1126 if (d <= best_dist) {
1127 lyxerr << "*" << endl;
1135 lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
1136 if (best_dist < 1e10)
1137 setCursor(best_cursor, false);
1138 return best_dist < 1e10;
1142 void LCursor::bruteFind2(int x, int y)
1144 double best_dist = 1e10;
1146 DocumentIterator it = *this;
1147 it.back().pos() = 0;
1148 DocumentIterator et = *this;
1149 et.back().pos() = et.back().asMathInset()->cell(et.back().idx_).size();
1150 for (int i = 0; ; ++i) {
1152 CursorSlice & cur = it.back();
1153 cur.inset().getCursorPos(cur, xo, yo);
1154 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1155 // '<=' in order to take the last possible position
1156 // this is important for clicking behind \sum in e.g. '\sum_i a'
1157 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
1158 if (d <= best_dist) {
1160 setCursor(it, false);
1169 CursorSlice LCursor::normalAnchor()
1171 if (anchor_.size() < depth()) {
1173 lyxerr << "unusual Anchor size" << endl;
1175 //lyx::BOOST_ASSERT(Anchor_.size() >= cursor.depth());
1176 // use Anchor on the same level as Cursor
1177 CursorSlice normal = anchor_[size() - 1];
1179 if (depth() < anchor_.size() && !(normal < xx())) {
1180 // anchor is behind cursor -> move anchor behind the inset
1188 void LCursor::handleFont(string const & font)
1190 lyxerr << "LCursor::handleFont: " << font << endl;
1194 safe = grabAndEraseSelection();
1197 if (lastpos() != 0) {
1198 // something left in the cell
1200 // cursor in first position
1202 } else if (pos() == lastpos()) {
1203 // cursor in last position
1206 // cursor in between. split cell
1207 MathArray::iterator bt = cell().begin();
1208 MathAtom at = createMathInset(font);
1209 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1210 cell().erase(bt, bt + pos());
1215 // nothing left in the cell
1223 void LCursor::message(string const & msg) const
1225 bv().owner()->getLyXFunc().setMessage(msg);
1229 void LCursor::errorMessage(string const & msg) const
1231 bv().owner()->getLyXFunc().setErrorMessage(msg);
1235 string LCursor::selectionAsString(bool label) const
1241 Buffer const & buffer = *bv().buffer();
1243 // should be const ...
1244 ParagraphList::iterator startpit = text()->getPar(selBegin());
1245 ParagraphList::iterator endpit = text()->getPar(selEnd());
1246 size_t const startpos = selBegin().pos();
1247 size_t const endpos = selEnd().pos();
1249 if (startpit == endpit)
1250 return startpit->asString(buffer, startpos, endpos, label);
1252 // First paragraph in selection
1254 startpit->asString(buffer, startpos, startpit->size(), label) + "\n\n";
1256 // The paragraphs in between (if any)
1257 ParagraphList::iterator pit = startpit;
1258 for (++pit; pit != endpit; ++pit)
1259 result += pit->asString(buffer, 0, pit->size(), label) + "\n\n";
1261 // Last paragraph in selection
1262 result += endpit->asString(buffer, 0, endpos, label);
1267 #warning and mathed?
1272 string LCursor::currentState()
1275 std::ostringstream os;
1281 return text()->currentState(*this);
1287 // only used by the spellchecker
1288 void LCursor::replaceWord(string const & replacestring)
1290 LyXText * t = text();
1293 t->replaceSelectionWithString(*this, replacestring);
1294 t->setSelectionRange(*this, replacestring.length());
1296 // Go back so that replacement string is also spellchecked
1297 for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
1298 t->cursorLeft(*this);
1302 void LCursor::update()
1308 string LCursor::getPossibleLabel()
1310 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1314 Encoding const * LCursor::getEncoding() const
1321 // go up until first non-0 text is hit
1322 // (innermost text is 0 in mathed)
1323 for (s = size() - 1; s >= 0; --s)
1324 if (operator[](s).text())
1326 CursorSlice const & sl = operator[](s);
1327 LyXText & text = *sl.text();
1328 ParagraphList::iterator pit = text.getPar(sl.par());
1329 LyXFont font = pit->getFont(
1330 bv().buffer()->params(), sl.pos(), outerFont(pit, text.paragraphs()));
1331 return font.language()->encoding();
1335 void LCursor::undispatched()
1337 disp_.dispatched(false);
1341 void LCursor::noUpdate()
1343 disp_.update(false);