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"
18 #include "CutAndPaste.h"
20 #include "dispatchresult.h"
22 #include "funcrequest.h"
23 #include "iterators.h"
27 #include "lyxfunc.h" // only for setMessage()
31 #include "paragraph.h"
32 #include "paragraph_funcs.h"
34 #include "insets/updatableinset.h"
35 #include "insets/insettabular.h"
36 #include "insets/insettext.h"
38 #include "mathed/math_data.h"
39 #include "mathed/math_support.h"
40 #include "mathed/math_inset.h"
42 #include "support/limited_stack.h"
43 #include "support/std_sstream.h"
45 #include "frontends/LyXView.h"
47 #include <boost/assert.hpp>
54 #ifndef CXX_GLOBAL_CSTD
63 limited_stack<string> theCutBuffer;
68 void region(CursorSlice const & i1, CursorSlice const & i2,
69 LCursor::row_type & r1, LCursor::row_type & r2,
70 LCursor::col_type & c1, LCursor::col_type & c2)
72 InsetBase & p = i1.inset();
86 LCursor::LCursor(BufferView & bv)
87 : DocumentIterator(), bv_(&bv), anchor_(),
88 cached_y_(0), x_target_(-1), selection_(false), mark_(false)
92 void LCursor::reset(InsetBase & inset)
95 push_back(CursorSlice(inset));
104 void LCursor::setCursor(DocumentIterator const & cur, bool sel)
106 // this (intentionally) does not touch the anchor
107 DocumentIterator::operator=(cur);
112 DispatchResult LCursor::dispatch(FuncRequest const & cmd0)
114 lyxerr << "\nLCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
116 return DispatchResult();
118 FuncRequest cmd = cmd0;
119 LCursor safe = *this;
121 for ( ; size(); pop()) {
122 //lyxerr << "\nLCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
123 BOOST_ASSERT(pos() <= lastpos());
124 BOOST_ASSERT(idx() <= lastidx());
125 BOOST_ASSERT(par() <= lastpar());
127 // The common case is 'LFUN handled, need update', so make the
128 // LFUN handler's life easier by assuming this as default value.
129 // The handler can reset the update and val flags if necessary.
131 disp_.dispatched(true);
132 inset().dispatch(*this, cmd);
133 if (disp_.dispatched())
136 // it completely to get a 'bomb early' behaviour in case this
137 // object will be used again.
138 if (!disp_.dispatched()) {
139 lyxerr << "RESTORING OLD CURSOR!" << endl;
146 bool LCursor::getStatus(FuncRequest const & cmd, FuncStatus & status)
148 // This is, of course, a mess. Better create a new doc iterator and use
149 // this in Inset::getStatus. This might require an additional
150 // BufferView * arg, though (which should be avoided)
151 LCursor safe = *this;
153 for ( ; size(); pop()) {
154 //lyxerr << "\nLCursor::getStatus: cmd: " << cmd << endl << *this << endl;
155 BOOST_ASSERT(pos() <= lastpos());
156 BOOST_ASSERT(idx() <= lastidx());
157 BOOST_ASSERT(par() <= lastpar());
159 // The inset's getStatus() will return 'true' if it made
160 // a definitive decision on whether it want to handle the
161 // request or not. The result of this decision is put into
162 // the 'status' parameter.
163 if (inset().getStatus(*this, cmd, status)) {
173 BufferView & LCursor::bv() const
181 BOOST_ASSERT(size() >= 1);
186 void LCursor::push(InsetBase & p)
188 push_back(CursorSlice(p));
192 void LCursor::pushLeft(InsetBase & p)
194 BOOST_ASSERT(!empty());
195 //lyxerr << "Entering inset " << t << " left" << endl;
201 bool LCursor::popLeft()
203 BOOST_ASSERT(!empty());
204 //lyxerr << "Leaving inset to the left" << endl;
205 inset().notifyCursorLeaves(idx());
213 bool LCursor::popRight()
215 BOOST_ASSERT(!empty());
216 //lyxerr << "Leaving inset to the right" << endl;
217 inset().notifyCursorLeaves(idx());
226 int LCursor::currentMode()
228 BOOST_ASSERT(!empty());
229 for (int i = size() - 1; i >= 0; --i) {
230 int res = operator[](i).inset().currentMode();
231 if (res != InsetBase::UNDECIDED_MODE)
234 return InsetBase::TEXT_MODE;
238 void LCursor::updatePos()
240 BOOST_ASSERT(!empty());
242 cached_y_ = bv().top_y() + back().inset().yo();
243 //cached_y_ = back().inset().yo();
247 void LCursor::getDim(int & asc, int & des) const
250 BOOST_ASSERT(inset().asMathInset());
251 //inset().asMathInset()->getCursorDim(asc, des);
254 } else if (inTexted()) {
255 Row const & row = textRow();
256 asc = row.baseline();
257 des = row.height() - asc;
259 lyxerr << "should this happen?" << endl;
266 void LCursor::getPos(int & x, int & y) const
271 inset().getCursorPos(back(), x, y);
272 // getCursorPos gives _screen_ coordinates. We need to add
273 // top_y to get document coordinates. This is hidden in cached_y_.
274 //y += cached_y_ - inset().yo();
275 // The rest is non-obvious. The reason we have to have these
276 // extra computation is that the getCursorPos() calls rely
277 // on the inset's own knowledge of its screen position.
278 // If we scroll up or down in a big enough increment,
279 // inset->draw() is not called: this doesn't update
280 // inset.yo_, so getCursor() returns an old value.
285 void LCursor::paste(string const & data)
287 dispatch(FuncRequest(LFUN_PASTE, data));
291 void LCursor::resetAnchor()
298 bool LCursor::posLeft()
307 bool LCursor::posRight()
309 if (pos() == lastpos())
316 CursorSlice & LCursor::anchor()
318 BOOST_ASSERT(!anchor_.empty());
319 return anchor_.back();
323 CursorSlice const & LCursor::anchor() const
325 BOOST_ASSERT(!anchor_.empty());
326 return anchor_.back();
330 CursorSlice const & LCursor::selBegin() const
334 return anchor() < back() ? anchor() : back();
338 CursorSlice const & LCursor::selEnd() const
342 return anchor() > back() ? anchor() : back();
346 DocumentIterator LCursor::selectionBegin() const
350 return anchor() < back() ? anchor_ : *this;
354 DocumentIterator LCursor::selectionEnd() const
358 return anchor() > back() ? anchor_ : *this;
362 void LCursor::setSelection()
365 // a selection with no contents is not a selection
366 if (par() == anchor().par() && pos() == anchor().pos())
371 void LCursor::setSelection(DocumentIterator const & where, size_t n)
374 setCursor(where, false);
380 void LCursor::clearSelection()
389 int & LCursor::x_target()
395 int LCursor::x_target() const
401 void LCursor::clearTargetX()
408 void LCursor::info(std::ostream & os) const
410 for (int i = 1, n = depth(); i < n; ++i) {
411 operator[](i).inset().infoize(os);
415 prevInset()->infoize2(os);
416 // overwite old message
421 string LCursor::grabSelection()
426 CursorSlice i1 = selBegin();
427 CursorSlice i2 = selEnd();
429 if (i1.idx() == i2.idx()) {
430 if (i1.inset().asMathInset()) {
431 MathArray::const_iterator it = i1.cell().begin();
432 return asString(MathArray(it + i1.pos(), it + i2.pos()));
434 return "unknown selection 1";
440 region(i1, i2, r1, r2, c1, c2);
443 if (i1.inset().asMathInset()) {
444 for (row_type row = r1; row <= r2; ++row) {
447 for (col_type col = c1; col <= c2; ++col) {
450 data += asString(i1.asMathInset()->cell(i1.asMathInset()->index(row, col)));
454 data = "unknown selection 2";
460 void LCursor::eraseSelection()
462 //lyxerr << "LCursor::eraseSelection" << endl;
463 CursorSlice const & i1 = selBegin();
464 CursorSlice const & i2 = selEnd();
466 if (i1.inset().asMathInset()) {
467 if (i1.idx() == i2.idx()) {
468 i1.cell().erase(i1.pos(), i2.pos());
470 MathInset * p = i1.asMathInset();
473 region(i1, i2, r1, r2, c1, c2);
474 for (row_type row = r1; row <= r2; ++row)
475 for (col_type col = c1; col <= c2; ++col)
476 p->cell(p->index(row, col)).clear();
480 lyxerr << "can't erase this selection 1" << endl;
482 //lyxerr << "LCursor::eraseSelection end" << endl;
486 string LCursor::grabAndEraseSelection()
490 string res = grabSelection();
497 void LCursor::selClear()
504 void LCursor::selCopy()
507 theCutBuffer.push(grabSelection());
510 //theCutBuffer.erase();
515 void LCursor::selCut()
517 theCutBuffer.push(grabAndEraseSelection());
521 void LCursor::selDel()
523 //lyxerr << "LCursor::selDel" << endl;
531 void LCursor::selPaste(size_t n)
534 if (n < theCutBuffer.size())
535 paste(theCutBuffer[n]);
541 void LCursor::selHandle(bool sel)
543 //lyxerr << "LCursor::selHandle" << endl;
544 if (sel == selection())
551 void LCursor::selClearOrDel()
553 //lyxerr << "LCursor::selClearOrDel" << endl;
554 if (lyxrc.auto_region_delete)
561 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
563 for (size_t i = 0, n = cur.size(); i != n; ++i) {
564 os << " " << cur.operator[](i) << " | ";
565 if (i < cur.anchor_.size())
566 os << cur.anchor_[i];
568 os << "-------------------------------";
571 for (size_t i = cur.size(), n = cur.anchor_.size(); i < n; ++i) {
572 os << "------------------------------- | " << cur.anchor_[i] << "\n";
574 os << " selection: " << cur.selection_
575 << " x_target: " << cur.x_target_ << endl;
582 ///////////////////////////////////////////////////////////////////
584 // The part below is the non-integrated rest of the original math
585 // cursor. This should be either generalized for texted or moved
586 // back to mathed (in most cases to MathNestInset).
588 ///////////////////////////////////////////////////////////////////
590 #include "mathed/math_charinset.h"
591 #include "mathed/math_factory.h"
592 #include "mathed/math_gridinset.h"
593 #include "mathed/math_macroarg.h"
594 #include "mathed/math_macrotemplate.h"
595 #include "mathed/math_mathmlstream.h"
596 #include "mathed/math_scriptinset.h"
597 #include "mathed/math_support.h"
598 #include "mathed/math_unknowninset.h"
600 //#define FILEDEBUG 1
603 bool LCursor::isInside(InsetBase const * p)
605 for (unsigned i = 0; i < depth(); ++i)
606 if (&operator[](i).inset() == p)
612 bool LCursor::openable(MathAtom const & t) const
623 // we can't move into anything new during selection
624 if (depth() >= anchor_.size())
626 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
633 bool positionable(DocumentIterator const & cursor,
634 DocumentIterator const & anchor)
636 // avoid deeper nested insets when selecting
637 if (cursor.size() > anchor.size())
640 // anchor might be deeper, should have same path then
641 for (size_t i = 0; i < cursor.size(); ++i)
642 if (&cursor[i].inset() != &anchor[i].inset())
645 // position should be ok.
650 void LCursor::setScreenPos(int x, int y)
653 bruteFind(x, y, 0, bv().workWidth(), 0, bv().workHeight());
658 void LCursor::plainErase()
664 void LCursor::markInsert()
666 cell().insert(pos(), MathAtom(new MathCharInset(0)));
670 void LCursor::markErase()
676 void LCursor::plainInsert(MathAtom const & t)
678 cell().insert(pos(), t);
683 void LCursor::insert(string const & str)
685 lyxerr << "LCursor::insert str '" << str << "'" << endl;
686 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
691 void LCursor::insert(char c)
693 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
694 BOOST_ASSERT(!empty());
697 plainInsert(MathAtom(new MathCharInset(c)));
699 text()->insertChar(*this, c);
704 void LCursor::insert(MathAtom const & t)
706 //lyxerr << "LCursor::insert MathAtom: " << endl;
713 void LCursor::insert(InsetBase * inset)
716 insert(MathAtom(inset));
718 text()->insertInset(*this, inset);
722 void LCursor::niceInsert(string const & t)
733 void LCursor::niceInsert(MathAtom const & t)
736 string safe = grabAndEraseSelection();
738 // enter the new inset and move the contents of the selection if possible
741 // be careful here: don't use 'pushLeft(t)' as this we need to
742 // push the clone, not the original
743 pushLeft(*nextInset());
749 void LCursor::insert(MathArray const & ar)
754 cell().insert(pos(), ar);
759 bool LCursor::backspace()
761 autocorrect() = false;
769 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
776 MathUnknownInset * p = activeMacro();
777 if (p->name().size() > 1) {
778 p->setName(p->name().substr(0, p->name().size() - 1));
783 if (pos() != 0 && prevAtom()->nargs() > 0) {
784 // let's require two backspaces for 'big stuff' and
785 // highlight on the first
796 bool LCursor::erase()
798 autocorrect() = false;
807 // delete empty cells if possible
808 if (pos() == lastpos() && inset().idxDelete(idx()))
811 // special behaviour when in last position of cell
812 if (pos() == lastpos()) {
813 bool one_cell = inset().nargs() == 1;
814 if (one_cell && depth() == 1 && lastpos() == 0)
820 inset().idxGlue(idx());
824 if (pos() != lastpos() && inset().nargs() > 0) {
838 DocumentIterator save = *this;
841 setCursor(save, false);
842 autocorrect() = false;
850 DocumentIterator save = *this;
853 setCursor(save, false);
854 autocorrect() = false;
859 void LCursor::macroModeClose()
863 MathUnknownInset * p = activeMacro();
865 string s = p->name();
869 // do nothing if the macro name is empty
873 string const name = s.substr(1);
875 // prevent entering of recursive macros
876 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
877 if (macro && macro->getInsetName() == name)
878 lyxerr << "can't enter recursive macro" << endl;
880 niceInsert(createMathInset(name));
884 string LCursor::macroName()
886 return inMacroMode() ? activeMacro()->name() : string();
890 void LCursor::handleNest(MathAtom const & a, int c)
892 //lyxerr << "LCursor::handleNest: " << c << endl;
894 asArray(grabAndEraseSelection(), t.nucleus()->cell(c));
897 pushLeft(*nextInset());
901 int LCursor::targetX() const
903 if (x_target() != -1)
912 void LCursor::adjust(pos_type from, int diff)
916 if (anchor().pos() > from)
917 anchor().pos() += diff;
918 // just to be on the safe side
919 // theoretically unecessary
924 bool LCursor::inMacroMode() const
928 MathUnknownInset const * p = prevAtom()->asUnknownInset();
929 return p && !p->final();
933 MathUnknownInset * LCursor::activeMacro()
935 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
939 bool LCursor::inMacroArgMode() const
941 return pos() > 0 && prevAtom()->getChar() == '#';
945 MathGridInset * LCursor::enclosingGrid(idx_type & idx) const
947 for (MathInset::difference_type i = depth() - 1; i >= 0; --i) {
948 MathInset * m = operator[](i).inset().asMathInset();
951 MathGridInset * p = m->asGridInset();
953 idx = operator[](i).idx();
961 void LCursor::pullArg()
964 MathArray ar = cell();
965 if (popLeft() && inMathed()) {
967 cell().insert(pos(), ar);
970 //formula()->mutateToText();
975 void LCursor::touch()
979 DocumentIterator::const_iterator it = begin();
980 DocumentIterator::const_iterator et = end();
981 for ( ; it != et; ++it)
987 void LCursor::normalize()
989 if (idx() >= nargs()) {
990 lyxerr << "this should not really happen - 1: "
991 << idx() << ' ' << nargs()
992 << " in: " << &inset() << endl;
994 idx() = min(idx(), lastidx());
996 if (pos() > lastpos()) {
997 lyxerr << "this should not really happen - 2: "
998 << pos() << ' ' << lastpos() << " in idx: " << idx()
1000 WriteStream wi(lyxerr, false, true);
1001 inset().asMathInset()->write(wi);
1004 pos() = min(pos(), lastpos());
1008 char LCursor::valign()
1011 MathGridInset * p = enclosingGrid(idx);
1012 return p ? p->valign() : '\0';
1016 char LCursor::halign()
1019 MathGridInset * p = enclosingGrid(idx);
1020 return p ? p->halign(idx % p->ncols()) : '\0';
1024 bool LCursor::goUpDown(bool up)
1026 // Be warned: The 'logic' implemented in this function is highly
1027 // fragile. A distance of one pixel or a '<' vs '<=' _really
1028 // matters. So fiddle around with it only if you think you know
1029 // what you are doing!
1035 // check if we had something else in mind, if not, this is the future goal
1036 if (x_target() == -1)
1041 // try neigbouring script insets
1045 MathScriptInset const * p = prevAtom()->asScriptInset();
1046 if (p && p->has(up)) {
1049 idx() = up; // the superscript has index 1
1051 //lyxerr << "updown: handled by scriptinset to the left" << endl;
1057 if (pos() != lastpos()) {
1058 MathScriptInset const * p = nextAtom()->asScriptInset();
1059 if (p && p->has(up)) {
1063 //lyxerr << "updown: handled by scriptinset to the right" << endl;
1069 // try current cell for e.g. text insets
1070 if (inset().idxUpDown2(*this, up))
1073 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1078 //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1079 // lyxerr << "updown: handled by brute find in the same cell" << endl;
1083 // try to find an inset that knows better then we
1085 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1087 if (inset().idxUpDown(*this, up)) {
1088 // try to find best position within this inset
1094 // no such inset found, just take something "above"
1095 //lyxerr << "updown: handled by strange case" << endl;
1097 int ylow = up ? 0 : yo + 1;
1098 int yhigh = up ? yo - 1 : bv().workHeight();
1099 return bruteFind(xo, yo, 0, bv().workWidth(), ylow, yhigh);
1102 // any improvement so far?
1105 if (up ? ynew < yo : ynew > yo)
1111 bool LCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1113 BOOST_ASSERT(!empty());
1115 CursorSlice bottom = operator[](0);
1116 LyXText * text = bottom.text();
1118 getParsInRange(text->paragraphs(), ylow, yhigh, beg, end);
1120 DocumentIterator it(bv().buffer()->inset());
1121 DocumentIterator et;
1122 //lyxerr << "x: " << x << " y: " << y << endl;
1123 //lyxerr << "xlow: " << xlow << " ylow: " << ylow << endl;
1124 //lyxerr << "xhigh: " << xhigh << " yhigh: " << yhigh << endl;
1127 //et.par() = text->parOffset(end);
1129 double best_dist = 10e10;
1130 DocumentIterator best_cursor = it;
1132 for ( ; it != et; it.forwardPos()) {
1133 // avoid invalid nesting when selecting
1134 if (!selection() || positionable(it, anchor_)) {
1136 CursorSlice & cur = it.back();
1137 cur.inset().getCursorPos(cur, xo, yo);
1138 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1139 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1140 //lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
1141 // '<=' in order to take the last possible position
1142 // this is important for clicking behind \sum in e.g. '\sum_i a'
1143 if (d <= best_dist) {
1144 //lyxerr << "*" << endl;
1152 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
1153 if (best_dist < 1e10)
1154 setCursor(best_cursor, false);
1155 return best_dist < 1e10;
1159 void LCursor::bruteFind2(int x, int y)
1161 double best_dist = 1e10;
1163 DocumentIterator it = *this;
1164 it.back().pos() = 0;
1165 DocumentIterator et = *this;
1166 et.back().pos() = et.back().asMathInset()->cell(et.back().idx()).size();
1167 for (int i = 0; ; ++i) {
1169 CursorSlice & cur = it.back();
1170 cur.inset().getCursorPos(cur, xo, yo);
1171 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1172 // '<=' in order to take the last possible position
1173 // this is important for clicking behind \sum in e.g. '\sum_i a'
1174 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
1175 if (d <= best_dist) {
1177 setCursor(it, false);
1186 CursorSlice LCursor::normalAnchor()
1188 if (anchor_.size() < depth()) {
1190 lyxerr << "unusual Anchor size" << endl;
1192 //lyx::BOOST_ASSERT(Anchor_.size() >= cursor.depth());
1193 // use Anchor on the same level as Cursor
1194 CursorSlice normal = anchor_[size() - 1];
1196 if (depth() < anchor_.size() && !(normal < xx())) {
1197 // anchor is behind cursor -> move anchor behind the inset
1205 void LCursor::handleFont(string const & font)
1207 lyxerr << "LCursor::handleFont: " << font << endl;
1211 safe = grabAndEraseSelection();
1214 if (lastpos() != 0) {
1215 // something left in the cell
1217 // cursor in first position
1219 } else if (pos() == lastpos()) {
1220 // cursor in last position
1223 // cursor in between. split cell
1224 MathArray::iterator bt = cell().begin();
1225 MathAtom at = createMathInset(font);
1226 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1227 cell().erase(bt, bt + pos());
1232 // nothing left in the cell
1240 void LCursor::message(string const & msg) const
1242 bv().owner()->getLyXFunc().setMessage(msg);
1246 void LCursor::errorMessage(string const & msg) const
1248 bv().owner()->getLyXFunc().setErrorMessage(msg);
1252 string LCursor::selectionAsString(bool label) const
1258 Buffer const & buffer = *bv().buffer();
1259 ParagraphList & pars = text()->paragraphs();
1261 // should be const ...
1262 par_type startpit = selBegin().par();
1263 par_type endpit = selEnd().par();
1264 size_t const startpos = selBegin().pos();
1265 size_t const endpos = selEnd().pos();
1267 if (startpit == endpit)
1268 return pars[startpit].asString(buffer, startpos, endpos, label);
1270 // First paragraph in selection
1271 string result = pars[startpit].
1272 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1274 // The paragraphs in between (if any)
1275 for (par_type pit = startpit + 1; pit != endpit; ++pit) {
1276 Paragraph & par = pars[pit];
1277 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1280 // Last paragraph in selection
1281 result += pars[endpit].asString(buffer, 0, endpos, label);
1286 #warning and mathed?
1291 string LCursor::currentState()
1294 std::ostringstream os;
1300 return text()->currentState(*this);
1306 string LCursor::getPossibleLabel()
1308 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1312 Encoding const * LCursor::getEncoding() const
1319 // go up until first non-0 text is hit
1320 // (innermost text is 0 in mathed)
1321 for (s = size() - 1; s >= 0; --s)
1322 if (operator[](s).text())
1324 CursorSlice const & sl = operator[](s);
1325 LyXText & text = *sl.text();
1326 LyXFont font = text.getPar(sl.par()).getFont(
1327 bv().buffer()->params(), sl.pos(), outerFont(sl.par(), text.paragraphs()));
1328 return font.language()->encoding();
1332 void LCursor::undispatched()
1334 disp_.dispatched(false);
1338 void LCursor::dispatched()
1340 disp_.dispatched(true);
1344 void LCursor::noUpdate()
1346 disp_.update(false);