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"
26 #include "lyxfunc.h" // only for setMessage()
30 #include "paragraph.h"
31 #include "paragraph_funcs.h"
32 #include "pariterator.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"
41 #include "mathed/math_braceinset.h"
42 #include "mathed/math_macrotable.h"
44 #include "support/limited_stack.h"
45 #include "support/std_sstream.h"
47 #include "frontends/LyXView.h"
49 #include <boost/assert.hpp>
56 #ifndef CXX_GLOBAL_CSTD
65 limited_stack<string> theCutBuffer;
70 void region(CursorSlice const & i1, CursorSlice const & i2,
71 LCursor::row_type & r1, LCursor::row_type & r2,
72 LCursor::col_type & c1, LCursor::col_type & c2)
74 InsetBase & p = i1.inset();
88 LCursor::LCursor(BufferView & bv)
89 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
90 selection_(false), mark_(false)
94 void LCursor::reset(InsetBase & inset)
97 push_back(CursorSlice(inset));
98 anchor_ = DocIterator(inset);
105 void LCursor::setCursor(DocIterator const & cur, bool sel)
107 // this (intentionally) does not touch the anchor
108 DocIterator::operator=(cur);
113 DispatchResult LCursor::dispatch(FuncRequest const & cmd0)
115 lyxerr << "\nLCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
117 return DispatchResult();
119 FuncRequest cmd = cmd0;
120 LCursor safe = *this;
122 for ( ; size(); pop()) {
123 //lyxerr << "\nLCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
124 BOOST_ASSERT(pos() <= lastpos());
125 BOOST_ASSERT(idx() <= lastidx());
126 BOOST_ASSERT(par() <= lastpar());
128 // The common case is 'LFUN handled, need update', so make the
129 // LFUN handler's life easier by assuming this as default value.
130 // The handler can reset the update and val flags if necessary.
132 disp_.dispatched(true);
133 inset().dispatch(*this, cmd);
134 if (disp_.dispatched())
137 // it completely to get a 'bomb early' behaviour in case this
138 // object will be used again.
139 if (!disp_.dispatched()) {
140 lyxerr << "RESTORING OLD CURSOR!" << endl;
142 disp_.dispatched(false);
148 bool LCursor::getStatus(FuncRequest const & cmd, FuncStatus & status)
150 // This is, of course, a mess. Better create a new doc iterator and use
151 // this in Inset::getStatus. This might require an additional
152 // BufferView * arg, though (which should be avoided)
153 LCursor safe = *this;
155 for ( ; size(); pop()) {
156 //lyxerr << "\nLCursor::getStatus: cmd: " << cmd << endl << *this << endl;
157 BOOST_ASSERT(pos() <= lastpos());
158 BOOST_ASSERT(idx() <= lastidx());
159 BOOST_ASSERT(par() <= lastpar());
161 // The inset's getStatus() will return 'true' if it made
162 // a definitive decision on whether it want to handle the
163 // request or not. The result of this decision is put into
164 // the 'status' parameter.
165 if (inset().getStatus(*this, cmd, status)) {
175 BufferView & LCursor::bv() const
182 Buffer & LCursor::buffer() const
185 BOOST_ASSERT(bv_->buffer());
186 return *bv_->buffer();
192 BOOST_ASSERT(size() >= 1);
197 void LCursor::push(InsetBase & p)
199 push_back(CursorSlice(p));
203 void LCursor::pushLeft(InsetBase & p)
205 BOOST_ASSERT(!empty());
206 //lyxerr << "Entering inset " << t << " left" << endl;
212 bool LCursor::popLeft()
214 BOOST_ASSERT(!empty());
215 //lyxerr << "Leaving inset to the left" << endl;
216 inset().notifyCursorLeaves(*this);
224 bool LCursor::popRight()
226 BOOST_ASSERT(!empty());
227 //lyxerr << "Leaving inset to the right" << endl;
228 inset().notifyCursorLeaves(*this);
237 int LCursor::currentMode()
239 BOOST_ASSERT(!empty());
240 for (int i = size() - 1; i >= 0; --i) {
241 int res = operator[](i).inset().currentMode();
242 if (res != InsetBase::UNDECIDED_MODE)
245 return InsetBase::TEXT_MODE;
249 void LCursor::getDim(int & asc, int & des) const
252 BOOST_ASSERT(inset().asMathInset());
253 //inset().asMathInset()->getCursorDim(asc, des);
256 } else if (inTexted()) {
257 Row const & row = textRow();
258 asc = row.baseline();
259 des = row.height() - asc;
261 lyxerr << "should this happen?" << endl;
268 void LCursor::getPos(int & x, int & y) const
273 inset().getCursorPos(*this, x, y);
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() const
310 BOOST_ASSERT(anchor_.size() >= size());
311 CursorSlice normal = anchor_[size() - 1];
312 if (size() < anchor_.size() && back() <= normal) {
313 // anchor is behind cursor -> move anchor behind the inset
320 CursorSlice LCursor::selBegin() const
324 return anchor() < back() ? anchor() : back();
328 CursorSlice LCursor::selEnd() const
332 return anchor() > back() ? anchor() : back();
336 DocIterator LCursor::selectionBegin() const
340 return anchor() < back() ? anchor_ : *this;
344 DocIterator LCursor::selectionEnd() const
348 return anchor() > back() ? anchor_ : *this;
352 void LCursor::setSelection()
355 // a selection with no contents is not a selection
356 #warning doesnt look ok
357 if (par() == anchor().par() && pos() == anchor().pos())
362 void LCursor::setSelection(DocIterator const & where, size_t n)
364 setCursor(where, true);
370 void LCursor::clearSelection()
379 int & LCursor::x_target()
385 int LCursor::x_target() const
391 void LCursor::clearTargetX()
398 void LCursor::info(std::ostream & os) const
400 for (int i = 1, n = depth(); i < n; ++i) {
401 operator[](i).inset().infoize(os);
405 prevInset()->infoize2(os);
406 // overwite old message
411 string LCursor::grabSelection()
416 CursorSlice i1 = selBegin();
417 CursorSlice i2 = selEnd();
419 if (i1.idx() == i2.idx()) {
420 if (i1.inset().asMathInset()) {
421 MathArray::const_iterator it = i1.cell().begin();
422 return asString(MathArray(it + i1.pos(), it + i2.pos()));
424 return "unknown selection 1";
430 region(i1, i2, r1, r2, c1, c2);
433 if (i1.inset().asMathInset()) {
434 for (row_type row = r1; row <= r2; ++row) {
437 for (col_type col = c1; col <= c2; ++col) {
440 data += asString(i1.asMathInset()->cell(i1.asMathInset()->index(row, col)));
444 data = "unknown selection 2";
450 void LCursor::eraseSelection()
452 //lyxerr << "LCursor::eraseSelection" << endl;
453 CursorSlice const & i1 = selBegin();
454 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::selCopy()
492 theCutBuffer.push(grabSelection());
495 //theCutBuffer.erase();
500 void LCursor::selCut()
502 theCutBuffer.push(grabAndEraseSelection());
506 void LCursor::selDel()
508 //lyxerr << "LCursor::selDel" << endl;
516 void LCursor::selPaste(size_t n)
519 if (n < theCutBuffer.size())
520 paste(theCutBuffer[n]);
526 void LCursor::selHandle(bool sel)
528 //lyxerr << "LCursor::selHandle" << endl;
529 if (sel == selection()) {
530 #warning Alfredo: This is too strong (Andre)
541 void LCursor::selClearOrDel()
543 //lyxerr << "LCursor::selClearOrDel" << endl;
544 if (lyxrc.auto_region_delete)
551 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
553 for (size_t i = 0, n = cur.size(); i != n; ++i) {
554 os << " " << cur.operator[](i) << " | ";
555 if (i < cur.anchor_.size())
556 os << cur.anchor_[i];
558 os << "-------------------------------";
561 for (size_t i = cur.size(), n = cur.anchor_.size(); i < n; ++i) {
562 os << "------------------------------- | " << cur.anchor_[i] << "\n";
564 os << " selection: " << cur.selection_
565 << " x_target: " << cur.x_target_ << endl;
572 ///////////////////////////////////////////////////////////////////
574 // The part below is the non-integrated rest of the original math
575 // cursor. This should be either generalized for texted or moved
576 // back to mathed (in most cases to MathNestInset).
578 ///////////////////////////////////////////////////////////////////
580 #include "mathed/math_charinset.h"
581 #include "mathed/math_factory.h"
582 #include "mathed/math_gridinset.h"
583 #include "mathed/math_macroarg.h"
584 #include "mathed/math_mathmlstream.h"
585 #include "mathed/math_scriptinset.h"
586 #include "mathed/math_support.h"
587 #include "mathed/math_unknowninset.h"
589 //#define FILEDEBUG 1
592 bool LCursor::isInside(InsetBase const * p)
594 for (unsigned i = 0; i < depth(); ++i)
595 if (&operator[](i).inset() == p)
601 bool LCursor::openable(MathAtom const & t) const
612 // we can't move into anything new during selection
613 if (depth() >= anchor_.size())
615 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
622 bool positionable(DocIterator const & cursor,
623 DocIterator const & anchor)
625 // avoid deeper nested insets when selecting
626 if (cursor.size() > anchor.size())
629 // anchor might be deeper, should have same path then
630 for (size_t i = 0; i < cursor.size(); ++i)
631 if (&cursor[i].inset() != &anchor[i].inset())
634 // position should be ok.
639 void LCursor::setScreenPos(int x, int y)
642 bruteFind(x, y, 0, bv().workWidth(), 0, bv().workHeight());
647 void LCursor::plainErase()
653 void LCursor::markInsert()
659 void LCursor::markErase()
665 void LCursor::plainInsert(MathAtom const & t)
667 cell().insert(pos(), t);
672 void LCursor::insert(string const & str)
674 //lyxerr << "LCursor::insert str '" << str << "'" << endl;
675 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
680 void LCursor::insert(char c)
682 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
683 BOOST_ASSERT(!empty());
686 insert(new MathCharInset(c));
688 text()->insertChar(*this, c);
693 void LCursor::insert(MathAtom const & t)
695 //lyxerr << "LCursor::insert MathAtom: " << endl;
699 lyxerr << "LCursor::insert MathAtom: cur:\n" << *this << endl;
703 void LCursor::insert(InsetBase * inset)
706 insert(MathAtom(inset));
708 text()->insertInset(*this, inset);
712 void LCursor::niceInsert(string const & t)
723 void LCursor::niceInsert(MathAtom const & t)
726 string safe = grabAndEraseSelection();
728 // enter the new inset and move the contents of the selection if possible
731 // be careful here: don't use 'pushLeft(t)' as this we need to
732 // push the clone, not the original
733 pushLeft(*nextInset());
739 void LCursor::insert(MathArray const & ar)
744 cell().insert(pos(), ar);
749 bool LCursor::backspace()
751 autocorrect() = false;
759 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
766 MathUnknownInset * p = activeMacro();
767 if (p->name().size() > 1) {
768 p->setName(p->name().substr(0, p->name().size() - 1));
773 if (pos() != 0 && prevAtom()->nargs() > 0) {
774 // let's require two backspaces for 'big stuff' and
775 // highlight on the first
787 bool LCursor::erase()
789 autocorrect() = false;
798 // delete empty cells if possible
799 if (pos() == lastpos() && inset().idxDelete(idx()))
802 // special behaviour when in last position of cell
803 if (pos() == lastpos()) {
804 bool one_cell = inset().nargs() == 1;
805 if (one_cell && depth() == 1 && lastpos() == 0)
811 inset().idxGlue(idx());
815 // 'clever' UI hack: only erase large items if previously slected
816 if (pos() != lastpos() && inset().nargs() > 0) {
831 DocIterator save = *this;
834 setCursor(save, false);
835 autocorrect() = false;
843 DocIterator save = *this;
846 setCursor(save, false);
847 autocorrect() = false;
852 void LCursor::macroModeClose()
856 MathUnknownInset * p = activeMacro();
858 string s = p->name();
862 // do nothing if the macro name is empty
866 string const name = s.substr(1);
868 // prevent entering of recursive macros
869 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
870 if (macro && macro->getInsetName() == name)
871 lyxerr << "can't enter recursive macro" << endl;
873 niceInsert(createMathInset(name));
877 string LCursor::macroName()
879 return inMacroMode() ? activeMacro()->name() : string();
883 void LCursor::handleNest(MathAtom const & a, int c)
885 //lyxerr << "LCursor::handleNest: " << c << endl;
887 asArray(grabAndEraseSelection(), t.nucleus()->cell(c));
890 pushLeft(*nextInset());
894 int LCursor::targetX() const
896 if (x_target() != -1)
905 bool LCursor::inMacroMode() const
909 MathUnknownInset const * p = prevAtom()->asUnknownInset();
910 return p && !p->final();
914 MathUnknownInset * LCursor::activeMacro()
916 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
920 void LCursor::pullArg()
925 MathArray ar = cell();
926 if (popLeft() && inMathed()) {
928 cell().insert(pos(), ar);
931 //formula()->mutateToText();
936 void LCursor::touch()
942 DocIterator::const_iterator it = begin();
943 DocIterator::const_iterator et = end();
944 for ( ; it != et; ++it)
950 void LCursor::normalize()
952 if (idx() >= nargs()) {
953 lyxerr << "this should not really happen - 1: "
954 << idx() << ' ' << nargs()
955 << " in: " << &inset() << endl;
957 idx() = min(idx(), lastidx());
959 if (pos() > lastpos()) {
960 lyxerr << "this should not really happen - 2: "
961 << pos() << ' ' << lastpos() << " in idx: " << idx()
963 WriteStream wi(lyxerr, false, true);
964 inset().asMathInset()->write(wi);
967 pos() = min(pos(), lastpos());
971 bool LCursor::goUpDown(bool up)
973 // Be warned: The 'logic' implemented in this function is highly
974 // fragile. A distance of one pixel or a '<' vs '<=' _really
975 // matters. So fiddle around with it only if you think you know
976 // what you are doing!
982 // check if we had something else in mind, if not, this is the future goal
983 if (x_target() == -1)
988 // try neigbouring script insets
992 MathScriptInset const * p = prevAtom()->asScriptInset();
993 if (p && p->has(up)) {
996 idx() = up; // the superscript has index 1
998 //lyxerr << "updown: handled by scriptinset to the left" << endl;
1004 if (pos() != lastpos()) {
1005 MathScriptInset const * p = nextAtom()->asScriptInset();
1006 if (p && p->has(up)) {
1010 //lyxerr << "updown: handled by scriptinset to the right" << endl;
1016 // try current cell for e.g. text insets
1017 if (inset().idxUpDown2(*this, up))
1020 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1025 //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1026 // lyxerr << "updown: handled by brute find in the same cell" << endl;
1030 // try to find an inset that knows better then we
1032 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1034 if (inset().idxUpDown(*this, up)) {
1035 // try to find best position within this inset
1041 // no such inset found, just take something "above"
1042 //lyxerr << "updown: handled by strange case" << endl;
1044 int ylow = up ? 0 : yo + 1;
1045 int yhigh = up ? yo - 1 : bv().workHeight();
1046 return bruteFind(xo, yo, 0, bv().workWidth(), ylow, yhigh);
1049 // any improvement so far?
1052 if (up ? ynew < yo : ynew > yo)
1058 bool LCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1060 BOOST_ASSERT(!empty());
1062 CursorSlice bottom = operator[](0);
1063 LyXText * text = bottom.text();
1065 getParsInRange(text->paragraphs(), ylow, yhigh, beg, end);
1067 DocIterator it = doc_iterator_begin(bv().buffer()->inset());
1068 DocIterator et = doc_iterator_end(bv().buffer()->inset());
1069 //lyxerr << "x: " << x << " y: " << y << endl;
1070 //lyxerr << "xlow: " << xlow << " ylow: " << ylow << endl;
1071 //lyxerr << "xhigh: " << xhigh << " yhigh: " << yhigh << endl;
1074 //et.par() = text->parOffset(end);
1076 double best_dist = 10e10;
1077 DocIterator best_cursor = it;
1079 for ( ; it != et; it.forwardPos()) {
1080 // avoid invalid nesting when selecting
1081 if (!selection() || positionable(it, anchor_)) {
1083 LCursor cur = *this;
1084 cur.setCursor(it, false);
1085 cur.inset().getCursorPos(cur, xo, yo);
1086 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1087 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1088 //lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
1089 // '<=' in order to take the last possible position
1090 // this is important for clicking behind \sum in e.g. '\sum_i a'
1091 if (d <= best_dist) {
1092 //lyxerr << "*" << endl;
1100 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
1101 if (best_dist < 1e10)
1102 setCursor(best_cursor, false);
1103 return best_dist < 1e10;
1107 void LCursor::bruteFind2(int x, int y)
1109 double best_dist = 1e10;
1111 DocIterator it = *this;
1112 it.back().pos() = 0;
1113 DocIterator et = *this;
1114 et.back().pos() = et.back().asMathInset()->cell(et.back().idx()).size();
1115 for (int i = 0; ; ++i) {
1117 LCursor cur = *this;
1118 cur.setCursor(it, false);
1119 cur.inset().getCursorPos(cur, xo, yo);
1120 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1121 // '<=' in order to take the last possible position
1122 // this is important for clicking behind \sum in e.g. '\sum_i a'
1123 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
1124 if (d <= best_dist) {
1126 setCursor(it, false);
1135 void LCursor::handleFont(string const & font)
1137 lyxerr << "LCursor::handleFont: " << font << endl;
1141 safe = grabAndEraseSelection();
1144 if (lastpos() != 0) {
1145 // something left in the cell
1147 // cursor in first position
1149 } else if (pos() == lastpos()) {
1150 // cursor in last position
1153 // cursor in between. split cell
1154 MathArray::iterator bt = cell().begin();
1155 MathAtom at = createMathInset(font);
1156 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1157 cell().erase(bt, bt + pos());
1162 // nothing left in the cell
1170 void LCursor::message(string const & msg) const
1172 bv().owner()->getLyXFunc().setMessage(msg);
1176 void LCursor::errorMessage(string const & msg) const
1178 bv().owner()->getLyXFunc().setErrorMessage(msg);
1182 string LCursor::selectionAsString(bool label) const
1188 Buffer const & buffer = *bv().buffer();
1189 ParagraphList & pars = text()->paragraphs();
1191 // should be const ...
1192 par_type startpit = selBegin().par();
1193 par_type endpit = selEnd().par();
1194 size_t const startpos = selBegin().pos();
1195 size_t const endpos = selEnd().pos();
1197 if (startpit == endpit)
1198 return pars[startpit].asString(buffer, startpos, endpos, label);
1200 // First paragraph in selection
1201 string result = pars[startpit].
1202 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1204 // The paragraphs in between (if any)
1205 for (par_type pit = startpit + 1; pit != endpit; ++pit) {
1206 Paragraph & par = pars[pit];
1207 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1210 // Last paragraph in selection
1211 result += pars[endpit].asString(buffer, 0, endpos, label);
1216 #ifdef WITH_WARNINGS
1217 #warning and mathed?
1223 string LCursor::currentState()
1226 std::ostringstream os;
1232 return text()->currentState(*this);
1238 string LCursor::getPossibleLabel()
1240 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1244 Encoding const * LCursor::getEncoding() const
1251 // go up until first non-0 text is hit
1252 // (innermost text is 0 in mathed)
1253 for (s = size() - 1; s >= 0; --s)
1254 if (operator[](s).text())
1256 CursorSlice const & sl = operator[](s);
1257 LyXText & text = *sl.text();
1258 LyXFont font = text.getPar(sl.par()).getFont(
1259 bv().buffer()->params(), sl.pos(), outerFont(sl.par(), text.paragraphs()));
1260 return font.language()->encoding();
1264 void LCursor::undispatched()
1266 disp_.dispatched(false);
1270 void LCursor::dispatched()
1272 disp_.dispatched(true);
1276 void LCursor::noUpdate()
1278 disp_.update(false);