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), anchor_(), x_target_(-1),
88 selection_(false), mark_(false)
92 void LCursor::reset(InsetBase & inset)
95 push_back(CursorSlice(inset));
96 anchor_ = DocIterator(inset);
103 void LCursor::setCursor(DocIterator const & cur, bool sel)
105 // this (intentionally) does not touch the anchor
106 DocIterator::operator=(cur);
111 DispatchResult LCursor::dispatch(FuncRequest const & cmd0)
113 lyxerr << "\nLCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
115 return DispatchResult();
117 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 (!disp_.dispatched()) {
138 lyxerr << "RESTORING OLD CURSOR!" << endl;
140 disp_.dispatched(false);
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(*this);
213 bool LCursor::popRight()
215 BOOST_ASSERT(!empty());
216 //lyxerr << "Leaving inset to the right" << endl;
217 inset().notifyCursorLeaves(*this);
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::getDim(int & asc, int & des) const
241 BOOST_ASSERT(inset().asMathInset());
242 //inset().asMathInset()->getCursorDim(asc, des);
245 } else if (inTexted()) {
246 Row const & row = textRow();
247 asc = row.baseline();
248 des = row.height() - asc;
250 lyxerr << "should this happen?" << endl;
257 void LCursor::getPos(int & x, int & y) const
262 inset().getCursorPos(back(), x, y);
266 void LCursor::paste(string const & data)
268 dispatch(FuncRequest(LFUN_PASTE, data));
272 void LCursor::resetAnchor()
279 bool LCursor::posLeft()
288 bool LCursor::posRight()
290 if (pos() == lastpos())
297 CursorSlice LCursor::anchor() const
299 BOOST_ASSERT(anchor_.size() >= size());
300 CursorSlice normal = anchor_[size() - 1];
301 if (size() < anchor_.size() && back() <= normal) {
302 // anchor is behind cursor -> move anchor behind the inset
309 CursorSlice LCursor::selBegin() const
313 return anchor() < back() ? anchor() : back();
317 CursorSlice LCursor::selEnd() const
321 return anchor() > back() ? anchor() : back();
325 DocIterator LCursor::selectionBegin() const
329 return anchor() < back() ? anchor_ : *this;
333 DocIterator LCursor::selectionEnd() const
337 return anchor() > back() ? anchor_ : *this;
341 void LCursor::setSelection()
344 // a selection with no contents is not a selection
345 #warning doesnt look ok
346 if (par() == anchor().par() && pos() == anchor().pos())
351 void LCursor::setSelection(DocIterator const & where, size_t n)
353 setCursor(where, true);
359 void LCursor::clearSelection()
368 int & LCursor::x_target()
374 int LCursor::x_target() const
380 void LCursor::clearTargetX()
387 void LCursor::info(std::ostream & os) const
389 for (int i = 1, n = depth(); i < n; ++i) {
390 operator[](i).inset().infoize(os);
394 prevInset()->infoize2(os);
395 // overwite old message
400 string LCursor::grabSelection()
405 CursorSlice i1 = selBegin();
406 CursorSlice i2 = selEnd();
408 if (i1.idx() == i2.idx()) {
409 if (i1.inset().asMathInset()) {
410 MathArray::const_iterator it = i1.cell().begin();
411 return asString(MathArray(it + i1.pos(), it + i2.pos()));
413 return "unknown selection 1";
419 region(i1, i2, r1, r2, c1, c2);
422 if (i1.inset().asMathInset()) {
423 for (row_type row = r1; row <= r2; ++row) {
426 for (col_type col = c1; col <= c2; ++col) {
429 data += asString(i1.asMathInset()->cell(i1.asMathInset()->index(row, col)));
433 data = "unknown selection 2";
439 void LCursor::eraseSelection()
441 //lyxerr << "LCursor::eraseSelection" << endl;
442 CursorSlice const & i1 = selBegin();
443 CursorSlice const & i2 = selEnd();
447 if (i1.inset().asMathInset()) {
448 if (i1.idx() == i2.idx()) {
449 i1.cell().erase(i1.pos(), i2.pos());
451 MathInset * p = i1.asMathInset();
454 region(i1, i2, r1, r2, c1, c2);
455 for (row_type row = r1; row <= r2; ++row)
456 for (col_type col = c1; col <= c2; ++col)
457 p->cell(p->index(row, col)).clear();
461 lyxerr << "can't erase this selection 1" << endl;
463 //lyxerr << "LCursor::eraseSelection end" << endl;
467 string LCursor::grabAndEraseSelection()
471 string res = grabSelection();
478 void LCursor::selCopy()
481 theCutBuffer.push(grabSelection());
484 //theCutBuffer.erase();
489 void LCursor::selCut()
491 theCutBuffer.push(grabAndEraseSelection());
495 void LCursor::selDel()
497 //lyxerr << "LCursor::selDel" << endl;
505 void LCursor::selPaste(size_t n)
508 if (n < theCutBuffer.size())
509 paste(theCutBuffer[n]);
515 void LCursor::selHandle(bool sel)
517 //lyxerr << "LCursor::selHandle" << endl;
518 if (sel == selection()) {
529 void LCursor::selClearOrDel()
531 //lyxerr << "LCursor::selClearOrDel" << endl;
532 if (lyxrc.auto_region_delete)
539 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
541 for (size_t i = 0, n = cur.size(); i != n; ++i) {
542 os << " " << cur.operator[](i) << " | ";
543 if (i < cur.anchor_.size())
544 os << cur.anchor_[i];
546 os << "-------------------------------";
549 for (size_t i = cur.size(), n = cur.anchor_.size(); i < n; ++i) {
550 os << "------------------------------- | " << cur.anchor_[i] << "\n";
552 os << " selection: " << cur.selection_
553 << " x_target: " << cur.x_target_ << endl;
560 ///////////////////////////////////////////////////////////////////
562 // The part below is the non-integrated rest of the original math
563 // cursor. This should be either generalized for texted or moved
564 // back to mathed (in most cases to MathNestInset).
566 ///////////////////////////////////////////////////////////////////
568 #include "mathed/math_charinset.h"
569 #include "mathed/math_factory.h"
570 #include "mathed/math_gridinset.h"
571 #include "mathed/math_macroarg.h"
572 #include "mathed/math_mathmlstream.h"
573 #include "mathed/math_scriptinset.h"
574 #include "mathed/math_support.h"
575 #include "mathed/math_unknowninset.h"
577 //#define FILEDEBUG 1
580 bool LCursor::isInside(InsetBase const * p)
582 for (unsigned i = 0; i < depth(); ++i)
583 if (&operator[](i).inset() == p)
589 bool LCursor::openable(MathAtom const & t) const
600 // we can't move into anything new during selection
601 if (depth() >= anchor_.size())
603 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
610 bool positionable(DocIterator const & cursor,
611 DocIterator const & anchor)
613 // avoid deeper nested insets when selecting
614 if (cursor.size() > anchor.size())
617 // anchor might be deeper, should have same path then
618 for (size_t i = 0; i < cursor.size(); ++i)
619 if (&cursor[i].inset() != &anchor[i].inset())
622 // position should be ok.
627 void LCursor::setScreenPos(int x, int y)
630 bruteFind(x, y, 0, bv().workWidth(), 0, bv().workHeight());
635 void LCursor::plainErase()
641 void LCursor::markInsert()
647 void LCursor::markErase()
653 void LCursor::plainInsert(MathAtom const & t)
655 cell().insert(pos(), t);
660 void LCursor::insert(string const & str)
662 //lyxerr << "LCursor::insert str '" << str << "'" << endl;
663 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
668 void LCursor::insert(char c)
670 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
671 BOOST_ASSERT(!empty());
674 insert(new MathCharInset(c));
676 text()->insertChar(*this, c);
681 void LCursor::insert(MathAtom const & t)
683 //lyxerr << "LCursor::insert MathAtom: " << endl;
687 lyxerr << "LCursor::insert MathAtom: cur:\n" << *this << endl;
691 void LCursor::insert(InsetBase * inset)
694 insert(MathAtom(inset));
696 text()->insertInset(*this, inset);
700 void LCursor::niceInsert(string const & t)
711 void LCursor::niceInsert(MathAtom const & t)
714 string safe = grabAndEraseSelection();
716 // enter the new inset and move the contents of the selection if possible
719 // be careful here: don't use 'pushLeft(t)' as this we need to
720 // push the clone, not the original
721 pushLeft(*nextInset());
727 void LCursor::insert(MathArray const & ar)
732 cell().insert(pos(), ar);
737 bool LCursor::backspace()
739 autocorrect() = false;
747 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
754 MathUnknownInset * p = activeMacro();
755 if (p->name().size() > 1) {
756 p->setName(p->name().substr(0, p->name().size() - 1));
761 if (pos() != 0 && prevAtom()->nargs() > 0) {
762 // let's require two backspaces for 'big stuff' and
763 // highlight on the first
775 bool LCursor::erase()
777 autocorrect() = false;
786 // delete empty cells if possible
787 if (pos() == lastpos() && inset().idxDelete(idx()))
790 // special behaviour when in last position of cell
791 if (pos() == lastpos()) {
792 bool one_cell = inset().nargs() == 1;
793 if (one_cell && depth() == 1 && lastpos() == 0)
799 inset().idxGlue(idx());
803 // 'clever' UI hack: only erase large items if previously slected
804 if (pos() != lastpos() && inset().nargs() > 0) {
819 DocIterator save = *this;
822 setCursor(save, false);
823 autocorrect() = false;
831 DocIterator save = *this;
834 setCursor(save, false);
835 autocorrect() = false;
840 void LCursor::macroModeClose()
844 MathUnknownInset * p = activeMacro();
846 string s = p->name();
850 // do nothing if the macro name is empty
854 string const name = s.substr(1);
856 // prevent entering of recursive macros
857 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
858 if (macro && macro->getInsetName() == name)
859 lyxerr << "can't enter recursive macro" << endl;
861 niceInsert(createMathInset(name));
865 string LCursor::macroName()
867 return inMacroMode() ? activeMacro()->name() : string();
871 void LCursor::handleNest(MathAtom const & a, int c)
873 //lyxerr << "LCursor::handleNest: " << c << endl;
875 asArray(grabAndEraseSelection(), t.nucleus()->cell(c));
878 pushLeft(*nextInset());
882 int LCursor::targetX() const
884 if (x_target() != -1)
893 bool LCursor::inMacroMode() const
897 MathUnknownInset const * p = prevAtom()->asUnknownInset();
898 return p && !p->final();
902 MathUnknownInset * LCursor::activeMacro()
904 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
908 void LCursor::pullArg()
913 MathArray ar = cell();
914 if (popLeft() && inMathed()) {
916 cell().insert(pos(), ar);
919 //formula()->mutateToText();
924 void LCursor::touch()
930 DocIterator::const_iterator it = begin();
931 DocIterator::const_iterator et = end();
932 for ( ; it != et; ++it)
938 void LCursor::normalize()
940 if (idx() >= nargs()) {
941 lyxerr << "this should not really happen - 1: "
942 << idx() << ' ' << nargs()
943 << " in: " << &inset() << endl;
945 idx() = min(idx(), lastidx());
947 if (pos() > lastpos()) {
948 lyxerr << "this should not really happen - 2: "
949 << pos() << ' ' << lastpos() << " in idx: " << idx()
951 WriteStream wi(lyxerr, false, true);
952 inset().asMathInset()->write(wi);
955 pos() = min(pos(), lastpos());
959 bool LCursor::goUpDown(bool up)
961 // Be warned: The 'logic' implemented in this function is highly
962 // fragile. A distance of one pixel or a '<' vs '<=' _really
963 // matters. So fiddle around with it only if you think you know
964 // what you are doing!
970 // check if we had something else in mind, if not, this is the future goal
971 if (x_target() == -1)
976 // try neigbouring script insets
980 MathScriptInset const * p = prevAtom()->asScriptInset();
981 if (p && p->has(up)) {
984 idx() = up; // the superscript has index 1
986 //lyxerr << "updown: handled by scriptinset to the left" << endl;
992 if (pos() != lastpos()) {
993 MathScriptInset const * p = nextAtom()->asScriptInset();
994 if (p && p->has(up)) {
998 //lyxerr << "updown: handled by scriptinset to the right" << endl;
1004 // try current cell for e.g. text insets
1005 if (inset().idxUpDown2(*this, up))
1008 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1013 //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1014 // lyxerr << "updown: handled by brute find in the same cell" << endl;
1018 // try to find an inset that knows better then we
1020 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1022 if (inset().idxUpDown(*this, up)) {
1023 // try to find best position within this inset
1029 // no such inset found, just take something "above"
1030 //lyxerr << "updown: handled by strange case" << endl;
1032 int ylow = up ? 0 : yo + 1;
1033 int yhigh = up ? yo - 1 : bv().workHeight();
1034 return bruteFind(xo, yo, 0, bv().workWidth(), ylow, yhigh);
1037 // any improvement so far?
1040 if (up ? ynew < yo : ynew > yo)
1046 bool LCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1048 BOOST_ASSERT(!empty());
1050 CursorSlice bottom = operator[](0);
1051 LyXText * text = bottom.text();
1053 getParsInRange(text->paragraphs(), ylow, yhigh, beg, end);
1055 DocIterator it = doc_iterator_begin(bv().buffer()->inset());
1056 DocIterator et = doc_iterator_end(bv().buffer()->inset());
1057 //lyxerr << "x: " << x << " y: " << y << endl;
1058 //lyxerr << "xlow: " << xlow << " ylow: " << ylow << endl;
1059 //lyxerr << "xhigh: " << xhigh << " yhigh: " << yhigh << endl;
1062 //et.par() = text->parOffset(end);
1064 double best_dist = 10e10;
1065 DocIterator best_cursor = it;
1067 for ( ; it != et; it.forwardPos()) {
1068 // avoid invalid nesting when selecting
1069 if (!selection() || positionable(it, anchor_)) {
1071 CursorSlice & cur = it.back();
1072 cur.inset().getCursorPos(cur, xo, yo);
1073 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1074 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1075 //lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
1076 // '<=' in order to take the last possible position
1077 // this is important for clicking behind \sum in e.g. '\sum_i a'
1078 if (d <= best_dist) {
1079 //lyxerr << "*" << endl;
1087 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
1088 if (best_dist < 1e10)
1089 setCursor(best_cursor, false);
1090 return best_dist < 1e10;
1094 void LCursor::bruteFind2(int x, int y)
1096 double best_dist = 1e10;
1098 DocIterator it = *this;
1099 it.back().pos() = 0;
1100 DocIterator et = *this;
1101 et.back().pos() = et.back().asMathInset()->cell(et.back().idx()).size();
1102 for (int i = 0; ; ++i) {
1104 CursorSlice & cur = it.back();
1105 cur.inset().getCursorPos(cur, xo, yo);
1106 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1107 // '<=' in order to take the last possible position
1108 // this is important for clicking behind \sum in e.g. '\sum_i a'
1109 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
1110 if (d <= best_dist) {
1112 setCursor(it, false);
1121 void LCursor::handleFont(string const & font)
1123 lyxerr << "LCursor::handleFont: " << font << endl;
1127 safe = grabAndEraseSelection();
1130 if (lastpos() != 0) {
1131 // something left in the cell
1133 // cursor in first position
1135 } else if (pos() == lastpos()) {
1136 // cursor in last position
1139 // cursor in between. split cell
1140 MathArray::iterator bt = cell().begin();
1141 MathAtom at = createMathInset(font);
1142 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1143 cell().erase(bt, bt + pos());
1148 // nothing left in the cell
1156 void LCursor::message(string const & msg) const
1158 bv().owner()->getLyXFunc().setMessage(msg);
1162 void LCursor::errorMessage(string const & msg) const
1164 bv().owner()->getLyXFunc().setErrorMessage(msg);
1168 string LCursor::selectionAsString(bool label) const
1174 Buffer const & buffer = *bv().buffer();
1175 ParagraphList & pars = text()->paragraphs();
1177 // should be const ...
1178 par_type startpit = selBegin().par();
1179 par_type endpit = selEnd().par();
1180 size_t const startpos = selBegin().pos();
1181 size_t const endpos = selEnd().pos();
1183 if (startpit == endpit)
1184 return pars[startpit].asString(buffer, startpos, endpos, label);
1186 // First paragraph in selection
1187 string result = pars[startpit].
1188 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1190 // The paragraphs in between (if any)
1191 for (par_type pit = startpit + 1; pit != endpit; ++pit) {
1192 Paragraph & par = pars[pit];
1193 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1196 // Last paragraph in selection
1197 result += pars[endpit].asString(buffer, 0, endpos, label);
1202 #ifdef WITH_WARNINGS
1203 #warning and mathed?
1209 string LCursor::currentState()
1212 std::ostringstream os;
1218 return text()->currentState(*this);
1224 string LCursor::getPossibleLabel()
1226 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1230 Encoding const * LCursor::getEncoding() const
1237 // go up until first non-0 text is hit
1238 // (innermost text is 0 in mathed)
1239 for (s = size() - 1; s >= 0; --s)
1240 if (operator[](s).text())
1242 CursorSlice const & sl = operator[](s);
1243 LyXText & text = *sl.text();
1244 LyXFont font = text.getPar(sl.par()).getFont(
1245 bv().buffer()->params(), sl.pos(), outerFont(sl.par(), text.paragraphs()));
1246 return font.language()->encoding();
1250 void LCursor::undispatched()
1252 disp_.dispatched(false);
1256 void LCursor::dispatched()
1258 disp_.dispatched(true);
1262 void LCursor::noUpdate()
1264 disp_.update(false);