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"
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 : DocIterator(), bv_(&bv),
88 anchor_(), cached_y_(0), x_target_(-1),
89 selection_(false), mark_(false)
93 void LCursor::reset(InsetBase & inset)
96 push_back(CursorSlice(inset));
97 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;
147 bool LCursor::getStatus(FuncRequest const & cmd, FuncStatus & status)
149 // This is, of course, a mess. Better create a new doc iterator and use
150 // this in Inset::getStatus. This might require an additional
151 // BufferView * arg, though (which should be avoided)
152 LCursor safe = *this;
154 for ( ; size(); pop()) {
155 //lyxerr << "\nLCursor::getStatus: cmd: " << cmd << endl << *this << endl;
156 BOOST_ASSERT(pos() <= lastpos());
157 BOOST_ASSERT(idx() <= lastidx());
158 BOOST_ASSERT(par() <= lastpar());
160 // The inset's getStatus() will return 'true' if it made
161 // a definitive decision on whether it want to handle the
162 // request or not. The result of this decision is put into
163 // the 'status' parameter.
164 if (inset().getStatus(*this, cmd, status)) {
174 BufferView & LCursor::bv() const
182 BOOST_ASSERT(size() >= 1);
187 void LCursor::push(InsetBase & p)
189 push_back(CursorSlice(p));
193 void LCursor::pushLeft(InsetBase & p)
195 BOOST_ASSERT(!empty());
196 //lyxerr << "Entering inset " << t << " left" << endl;
202 bool LCursor::popLeft()
204 BOOST_ASSERT(!empty());
205 //lyxerr << "Leaving inset to the left" << endl;
206 inset().notifyCursorLeaves(*this);
214 bool LCursor::popRight()
216 BOOST_ASSERT(!empty());
217 //lyxerr << "Leaving inset to the right" << endl;
218 inset().notifyCursorLeaves(*this);
227 int LCursor::currentMode()
229 BOOST_ASSERT(!empty());
230 for (int i = size() - 1; i >= 0; --i) {
231 int res = operator[](i).inset().currentMode();
232 if (res != InsetBase::UNDECIDED_MODE)
235 return InsetBase::TEXT_MODE;
239 void LCursor::updatePos()
241 BOOST_ASSERT(!empty());
243 cached_y_ = bv().top_y() + back().inset().yo();
244 //cached_y_ = back().inset().yo();
248 void LCursor::getDim(int & asc, int & des) const
251 BOOST_ASSERT(inset().asMathInset());
252 //inset().asMathInset()->getCursorDim(asc, des);
255 } else if (inTexted()) {
256 Row const & row = textRow();
257 asc = row.baseline();
258 des = row.height() - asc;
260 lyxerr << "should this happen?" << endl;
267 void LCursor::getPos(int & x, int & y) const
272 inset().getCursorPos(back(), x, y);
273 // getCursorPos gives _screen_ coordinates. We need to add
274 // top_y to get document coordinates. This is hidden in cached_y_.
275 //y += cached_y_ - inset().yo();
276 // The rest is non-obvious. The reason we have to have these
277 // extra computation is that the getCursorPos() calls rely
278 // on the inset's own knowledge of its screen position.
279 // If we scroll up or down in a big enough increment,
280 // inset->draw() is not called: this doesn't update
281 // inset.yo_, so getCursor() returns an old value.
286 void LCursor::paste(string const & data)
288 dispatch(FuncRequest(LFUN_PASTE, data));
292 void LCursor::resetAnchor()
299 bool LCursor::posLeft()
308 bool LCursor::posRight()
310 if (pos() == lastpos())
317 CursorSlice & LCursor::anchor()
319 if (anchor_.size() < size()) {
320 lyxerr << "anchor_.size() < cursor_.size() "
321 "should not happen when accessing the anchor" << endl;
324 BOOST_ASSERT(!anchor_.empty());
325 // this size is cursor_.size()
326 return anchor_[size() - 1];
330 CursorSlice const & LCursor::anchor() const
332 if (anchor_.size() < size()) {
333 lyxerr << "anchor_.size() < cursor_.size() "
334 "should not happen when accessing the anchor" << endl;
337 // this size is cursor_.size()
338 BOOST_ASSERT(!anchor_.empty());
339 return anchor_[size() - 1];
343 CursorSlice const & LCursor::selBegin() const
347 return anchor() < back() ? anchor() : back();
351 CursorSlice const & LCursor::selEnd() const
355 return anchor() > back() ? anchor() : back();
359 DocIterator LCursor::selectionBegin() const
363 return anchor() < back() ? anchor_ : *this;
367 DocIterator LCursor::selectionEnd() const
371 return anchor() > back() ? anchor_ : *this;
375 void LCursor::setSelection()
378 // a selection with no contents is not a selection
379 #warning doesnt look ok
380 if (par() == anchor().par() && pos() == anchor().pos())
385 void LCursor::setSelection(DocIterator const & where, size_t n)
387 setCursor(where, true);
393 void LCursor::clearSelection()
402 int & LCursor::x_target()
408 int LCursor::x_target() const
414 void LCursor::clearTargetX()
421 void LCursor::info(std::ostream & os) const
423 for (int i = 1, n = depth(); i < n; ++i) {
424 operator[](i).inset().infoize(os);
428 prevInset()->infoize2(os);
429 // overwite old message
434 string LCursor::grabSelection()
439 CursorSlice i1 = selBegin();
440 CursorSlice i2 = selEnd();
442 if (i1.idx() == i2.idx()) {
443 if (i1.inset().asMathInset()) {
444 MathArray::const_iterator it = i1.cell().begin();
445 return asString(MathArray(it + i1.pos(), it + i2.pos()));
447 return "unknown selection 1";
453 region(i1, i2, r1, r2, c1, c2);
456 if (i1.inset().asMathInset()) {
457 for (row_type row = r1; row <= r2; ++row) {
460 for (col_type col = c1; col <= c2; ++col) {
463 data += asString(i1.asMathInset()->cell(i1.asMathInset()->index(row, col)));
467 data = "unknown selection 2";
473 void LCursor::eraseSelection()
475 //lyxerr << "LCursor::eraseSelection" << endl;
476 CursorSlice const & i1 = selBegin();
477 CursorSlice const & i2 = selEnd();
481 if (i1.inset().asMathInset()) {
482 if (i1.idx() == i2.idx()) {
483 i1.cell().erase(i1.pos(), i2.pos());
485 MathInset * p = i1.asMathInset();
488 region(i1, i2, r1, r2, c1, c2);
489 for (row_type row = r1; row <= r2; ++row)
490 for (col_type col = c1; col <= c2; ++col)
491 p->cell(p->index(row, col)).clear();
495 lyxerr << "can't erase this selection 1" << endl;
497 //lyxerr << "LCursor::eraseSelection end" << endl;
501 string LCursor::grabAndEraseSelection()
505 string res = grabSelection();
512 void LCursor::selCopy()
515 theCutBuffer.push(grabSelection());
518 //theCutBuffer.erase();
523 void LCursor::selCut()
525 theCutBuffer.push(grabAndEraseSelection());
529 void LCursor::selDel()
531 //lyxerr << "LCursor::selDel" << endl;
539 void LCursor::selPaste(size_t n)
542 if (n < theCutBuffer.size())
543 paste(theCutBuffer[n]);
549 void LCursor::selHandle(bool sel)
551 //lyxerr << "LCursor::selHandle" << endl;
552 if (sel == selection())
559 void LCursor::selClearOrDel()
561 //lyxerr << "LCursor::selClearOrDel" << endl;
562 if (lyxrc.auto_region_delete)
569 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
571 for (size_t i = 0, n = cur.size(); i != n; ++i) {
572 os << " " << cur.operator[](i) << " | ";
573 if (i < cur.anchor_.size())
574 os << cur.anchor_[i];
576 os << "-------------------------------";
579 for (size_t i = cur.size(), n = cur.anchor_.size(); i < n; ++i) {
580 os << "------------------------------- | " << cur.anchor_[i] << "\n";
582 os << " selection: " << cur.selection_
583 << " x_target: " << cur.x_target_ << endl;
590 ///////////////////////////////////////////////////////////////////
592 // The part below is the non-integrated rest of the original math
593 // cursor. This should be either generalized for texted or moved
594 // back to mathed (in most cases to MathNestInset).
596 ///////////////////////////////////////////////////////////////////
598 #include "mathed/math_charinset.h"
599 #include "mathed/math_factory.h"
600 #include "mathed/math_gridinset.h"
601 #include "mathed/math_macroarg.h"
602 #include "mathed/math_mathmlstream.h"
603 #include "mathed/math_scriptinset.h"
604 #include "mathed/math_support.h"
605 #include "mathed/math_unknowninset.h"
607 //#define FILEDEBUG 1
610 bool LCursor::isInside(InsetBase const * p)
612 for (unsigned i = 0; i < depth(); ++i)
613 if (&operator[](i).inset() == p)
619 bool LCursor::openable(MathAtom const & t) const
630 // we can't move into anything new during selection
631 if (depth() >= anchor_.size())
633 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
640 bool positionable(DocIterator const & cursor,
641 DocIterator const & anchor)
643 // avoid deeper nested insets when selecting
644 if (cursor.size() > anchor.size())
647 // anchor might be deeper, should have same path then
648 for (size_t i = 0; i < cursor.size(); ++i)
649 if (&cursor[i].inset() != &anchor[i].inset())
652 // position should be ok.
657 void LCursor::setScreenPos(int x, int y)
660 bruteFind(x, y, 0, bv().workWidth(), 0, bv().workHeight());
665 void LCursor::plainErase()
671 void LCursor::markInsert()
677 void LCursor::markErase()
683 void LCursor::plainInsert(MathAtom const & t)
685 cell().insert(pos(), t);
690 void LCursor::insert(string const & str)
692 //lyxerr << "LCursor::insert str '" << str << "'" << endl;
693 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
698 void LCursor::insert(char c)
700 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
701 BOOST_ASSERT(!empty());
704 insert(new MathCharInset(c));
706 text()->insertChar(*this, c);
711 void LCursor::insert(MathAtom const & t)
713 //lyxerr << "LCursor::insert MathAtom: " << endl;
717 lyxerr << "LCursor::insert MathAtom: cur:\n" << *this << endl;
721 void LCursor::insert(InsetBase * inset)
724 insert(MathAtom(inset));
726 text()->insertInset(*this, inset);
730 void LCursor::niceInsert(string const & t)
741 void LCursor::niceInsert(MathAtom const & t)
744 string safe = grabAndEraseSelection();
746 // enter the new inset and move the contents of the selection if possible
749 // be careful here: don't use 'pushLeft(t)' as this we need to
750 // push the clone, not the original
751 pushLeft(*nextInset());
757 void LCursor::insert(MathArray const & ar)
762 cell().insert(pos(), ar);
767 bool LCursor::backspace()
769 autocorrect() = false;
777 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
784 MathUnknownInset * p = activeMacro();
785 if (p->name().size() > 1) {
786 p->setName(p->name().substr(0, p->name().size() - 1));
791 if (pos() != 0 && prevAtom()->nargs() > 0) {
792 // let's require two backspaces for 'big stuff' and
793 // highlight on the first
805 bool LCursor::erase()
807 autocorrect() = false;
816 // delete empty cells if possible
817 if (pos() == lastpos() && inset().idxDelete(idx()))
820 // special behaviour when in last position of cell
821 if (pos() == lastpos()) {
822 bool one_cell = inset().nargs() == 1;
823 if (one_cell && depth() == 1 && lastpos() == 0)
829 inset().idxGlue(idx());
833 // 'clever' UI hack: only erase large items if previously slected
834 if (pos() != lastpos() && inset().nargs() > 0) {
849 DocIterator save = *this;
852 setCursor(save, false);
853 autocorrect() = false;
861 DocIterator save = *this;
864 setCursor(save, false);
865 autocorrect() = false;
870 void LCursor::macroModeClose()
874 MathUnknownInset * p = activeMacro();
876 string s = p->name();
880 // do nothing if the macro name is empty
884 string const name = s.substr(1);
886 // prevent entering of recursive macros
887 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
888 if (macro && macro->getInsetName() == name)
889 lyxerr << "can't enter recursive macro" << endl;
891 niceInsert(createMathInset(name));
895 string LCursor::macroName()
897 return inMacroMode() ? activeMacro()->name() : string();
901 void LCursor::handleNest(MathAtom const & a, int c)
903 //lyxerr << "LCursor::handleNest: " << c << endl;
905 asArray(grabAndEraseSelection(), t.nucleus()->cell(c));
908 pushLeft(*nextInset());
912 int LCursor::targetX() const
914 if (x_target() != -1)
923 void LCursor::adjust(pos_type from, int diff)
927 if (anchor().pos() > from)
928 anchor().pos() += diff;
929 // just to be on the safe side
930 // theoretically unecessary
935 bool LCursor::inMacroMode() const
939 MathUnknownInset const * p = prevAtom()->asUnknownInset();
940 return p && !p->final();
944 MathUnknownInset * LCursor::activeMacro()
946 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
950 void LCursor::pullArg()
955 MathArray ar = cell();
956 if (popLeft() && inMathed()) {
958 cell().insert(pos(), ar);
961 //formula()->mutateToText();
966 void LCursor::touch()
972 DocIterator::const_iterator it = begin();
973 DocIterator::const_iterator et = end();
974 for ( ; it != et; ++it)
980 void LCursor::normalize()
982 if (idx() >= nargs()) {
983 lyxerr << "this should not really happen - 1: "
984 << idx() << ' ' << nargs()
985 << " in: " << &inset() << endl;
987 idx() = min(idx(), lastidx());
989 if (pos() > lastpos()) {
990 lyxerr << "this should not really happen - 2: "
991 << pos() << ' ' << lastpos() << " in idx: " << idx()
993 WriteStream wi(lyxerr, false, true);
994 inset().asMathInset()->write(wi);
997 pos() = min(pos(), lastpos());
1001 bool LCursor::goUpDown(bool up)
1003 // Be warned: The 'logic' implemented in this function is highly
1004 // fragile. A distance of one pixel or a '<' vs '<=' _really
1005 // matters. So fiddle around with it only if you think you know
1006 // what you are doing!
1012 // check if we had something else in mind, if not, this is the future goal
1013 if (x_target() == -1)
1018 // try neigbouring script insets
1022 MathScriptInset const * p = prevAtom()->asScriptInset();
1023 if (p && p->has(up)) {
1026 idx() = up; // the superscript has index 1
1028 //lyxerr << "updown: handled by scriptinset to the left" << endl;
1034 if (pos() != lastpos()) {
1035 MathScriptInset const * p = nextAtom()->asScriptInset();
1036 if (p && p->has(up)) {
1040 //lyxerr << "updown: handled by scriptinset to the right" << endl;
1046 // try current cell for e.g. text insets
1047 if (inset().idxUpDown2(*this, up))
1050 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1055 //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1056 // lyxerr << "updown: handled by brute find in the same cell" << endl;
1060 // try to find an inset that knows better then we
1062 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1064 if (inset().idxUpDown(*this, up)) {
1065 // try to find best position within this inset
1071 // no such inset found, just take something "above"
1072 //lyxerr << "updown: handled by strange case" << endl;
1074 int ylow = up ? 0 : yo + 1;
1075 int yhigh = up ? yo - 1 : bv().workHeight();
1076 return bruteFind(xo, yo, 0, bv().workWidth(), ylow, yhigh);
1079 // any improvement so far?
1082 if (up ? ynew < yo : ynew > yo)
1088 bool LCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1090 BOOST_ASSERT(!empty());
1092 CursorSlice bottom = operator[](0);
1093 LyXText * text = bottom.text();
1095 getParsInRange(text->paragraphs(), ylow, yhigh, beg, end);
1097 DocIterator it = doc_iterator_begin(bv().buffer()->inset());
1098 DocIterator et = doc_iterator_end(bv().buffer()->inset());
1099 //lyxerr << "x: " << x << " y: " << y << endl;
1100 //lyxerr << "xlow: " << xlow << " ylow: " << ylow << endl;
1101 //lyxerr << "xhigh: " << xhigh << " yhigh: " << yhigh << endl;
1104 //et.par() = text->parOffset(end);
1106 double best_dist = 10e10;
1107 DocIterator best_cursor = it;
1109 for ( ; it != et; it.forwardPos()) {
1110 // avoid invalid nesting when selecting
1111 if (!selection() || positionable(it, anchor_)) {
1113 CursorSlice & cur = it.back();
1114 cur.inset().getCursorPos(cur, xo, yo);
1115 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1116 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1117 //lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
1118 // '<=' in order to take the last possible position
1119 // this is important for clicking behind \sum in e.g. '\sum_i a'
1120 if (d <= best_dist) {
1121 //lyxerr << "*" << endl;
1129 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
1130 if (best_dist < 1e10)
1131 setCursor(best_cursor, false);
1132 return best_dist < 1e10;
1136 void LCursor::bruteFind2(int x, int y)
1138 double best_dist = 1e10;
1140 DocIterator it = *this;
1141 it.back().pos() = 0;
1142 DocIterator et = *this;
1143 et.back().pos() = et.back().asMathInset()->cell(et.back().idx()).size();
1144 for (int i = 0; ; ++i) {
1146 CursorSlice & cur = it.back();
1147 cur.inset().getCursorPos(cur, xo, yo);
1148 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1149 // '<=' in order to take the last possible position
1150 // this is important for clicking behind \sum in e.g. '\sum_i a'
1151 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
1152 if (d <= best_dist) {
1154 setCursor(it, false);
1163 CursorSlice LCursor::normalAnchor()
1165 if (anchor_.size() < depth()) {
1167 lyxerr << "unusual Anchor size" << endl;
1169 //lyx::BOOST_ASSERT(Anchor_.size() >= cursor.depth());
1170 // use Anchor on the same level as Cursor
1171 CursorSlice normal = anchor_[size() - 1];
1173 if (depth() < anchor_.size() && !(normal < xx())) {
1174 // anchor is behind cursor -> move anchor behind the inset
1182 void LCursor::handleFont(string const & font)
1184 lyxerr << "LCursor::handleFont: " << font << endl;
1188 safe = grabAndEraseSelection();
1191 if (lastpos() != 0) {
1192 // something left in the cell
1194 // cursor in first position
1196 } else if (pos() == lastpos()) {
1197 // cursor in last position
1200 // cursor in between. split cell
1201 MathArray::iterator bt = cell().begin();
1202 MathAtom at = createMathInset(font);
1203 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1204 cell().erase(bt, bt + pos());
1209 // nothing left in the cell
1217 void LCursor::message(string const & msg) const
1219 bv().owner()->getLyXFunc().setMessage(msg);
1223 void LCursor::errorMessage(string const & msg) const
1225 bv().owner()->getLyXFunc().setErrorMessage(msg);
1229 string LCursor::selectionAsString(bool label) const
1235 Buffer const & buffer = *bv().buffer();
1236 ParagraphList & pars = text()->paragraphs();
1238 // should be const ...
1239 par_type startpit = selBegin().par();
1240 par_type endpit = selEnd().par();
1241 size_t const startpos = selBegin().pos();
1242 size_t const endpos = selEnd().pos();
1244 if (startpit == endpit)
1245 return pars[startpit].asString(buffer, startpos, endpos, label);
1247 // First paragraph in selection
1248 string result = pars[startpit].
1249 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1251 // The paragraphs in between (if any)
1252 for (par_type pit = startpit + 1; pit != endpit; ++pit) {
1253 Paragraph & par = pars[pit];
1254 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1257 // Last paragraph in selection
1258 result += pars[endpit].asString(buffer, 0, endpos, label);
1263 #ifdef WITH_WARNINGS
1264 #warning and mathed?
1270 string LCursor::currentState()
1273 std::ostringstream os;
1279 return text()->currentState(*this);
1285 string LCursor::getPossibleLabel()
1287 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1291 Encoding const * LCursor::getEncoding() const
1298 // go up until first non-0 text is hit
1299 // (innermost text is 0 in mathed)
1300 for (s = size() - 1; s >= 0; --s)
1301 if (operator[](s).text())
1303 CursorSlice const & sl = operator[](s);
1304 LyXText & text = *sl.text();
1305 LyXFont font = text.getPar(sl.par()).getFont(
1306 bv().buffer()->params(), sl.pos(), outerFont(sl.par(), text.paragraphs()));
1307 return font.language()->encoding();
1311 void LCursor::undispatched()
1313 disp_.dispatched(false);
1317 void LCursor::dispatched()
1319 disp_.dispatched(true);
1323 void LCursor::noUpdate()
1325 disp_.update(false);