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)
89 void LCursor::reset(InsetBase & inset)
92 push_back(CursorSlice(inset));
94 anchor_.push_back(CursorSlice(inset));
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;
117 LCursor safe = *this;
119 for ( ; size(); pop()) {
120 //lyxerr << "\nLCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
121 BOOST_ASSERT(pos() <= lastpos());
122 BOOST_ASSERT(idx() <= lastidx());
123 BOOST_ASSERT(par() <= lastpar());
125 // The common case is 'LFUN handled, need update', so make the
126 // LFUN handler's life easier by assuming this as default value.
127 // The handler can reset the update and val flags if necessary.
129 disp_.dispatched(true);
130 inset().dispatch(*this, cmd);
131 if (disp_.dispatched())
134 // it completely to get a 'bomb early' behaviour in case this
135 // object will be used again.
136 if (!disp_.dispatched())
142 bool LCursor::getStatus(FuncRequest const & cmd, FuncStatus & status)
144 LCursor safe = *this;
145 for ( ; size(); pop()) {
146 //lyxerr << "\nLCursor::getStatus: cmd: " << cmd << endl << *this << endl;
147 BOOST_ASSERT(pos() <= lastpos());
148 BOOST_ASSERT(idx() <= lastidx());
149 BOOST_ASSERT(par() <= lastpar());
151 // The inset's getStatus() will return 'true' if it made
152 // a definitive decision on whether it want to handle the
153 // request or not. The result of this decision is put into
154 // the 'status' parameter.
155 if (inset().getStatus(*this, cmd, status))
163 BufferView & LCursor::bv() const
171 BOOST_ASSERT(size() >= 1);
177 void LCursor::push(InsetBase & p)
179 push_back(CursorSlice(p));
183 void LCursor::pushLeft(InsetBase & p)
185 BOOST_ASSERT(!empty());
186 //lyxerr << "Entering inset " << t << " left" << endl;
192 bool LCursor::popLeft()
194 BOOST_ASSERT(!empty());
195 //lyxerr << "Leaving inset to the left" << endl;
196 inset().notifyCursorLeaves(idx());
204 bool LCursor::popRight()
206 BOOST_ASSERT(!empty());
207 //lyxerr << "Leaving inset to the right" << endl;
208 inset().notifyCursorLeaves(idx());
217 int LCursor::currentMode()
219 BOOST_ASSERT(!empty());
220 for (int i = size() - 1; i >= 0; --i) {
221 int res = operator[](i).inset().currentMode();
222 if (res != InsetBase::UNDECIDED_MODE)
225 return InsetBase::TEXT_MODE;
229 void LCursor::updatePos()
231 BOOST_ASSERT(!empty());
233 cached_y_ = bv().top_y() + back().inset().yo();
234 //cached_y_ = back().inset().yo();
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);
263 // getCursorPos gives _screen_ coordinates. We need to add
264 // top_y to get document coordinates. This is hidden in cached_y_.
265 //y += cached_y_ - inset().yo();
266 // The rest is non-obvious. The reason we have to have these
267 // extra computation is that the getCursorPos() calls rely
268 // on the inset's own knowledge of its screen position.
269 // If we scroll up or down in a big enough increment,
270 // inset->draw() is not called: this doesn't update
271 // inset.yo_, so getCursor() returns an old value.
276 void LCursor::paste(string const & data)
278 dispatch(FuncRequest(LFUN_PASTE, data));
282 void LCursor::resetAnchor()
289 bool LCursor::posLeft()
298 bool LCursor::posRight()
300 if (pos() == lastpos())
307 CursorSlice & LCursor::anchor()
309 return anchor_.back();
313 CursorSlice const & LCursor::anchor() const
315 return anchor_.back();
319 CursorSlice const & LCursor::selBegin() const
323 return anchor() < back() ? anchor() : back();
327 CursorSlice & LCursor::selBegin()
331 // can't use std::min as this returns a const ref
332 return anchor() < back() ? anchor() : back();
336 CursorSlice const & LCursor::selEnd() const
340 return anchor() > back() ? anchor() : back();
344 CursorSlice & LCursor::selEnd()
348 // can't use std::min as this returns a const ref
349 return anchor() > back() ? anchor() : back();
353 void LCursor::setSelection()
356 // a selection with no contents is not a selection
357 if (par() == anchor().par() && pos() == anchor().pos())
362 void LCursor::setSelection(DocumentIterator const & where, size_t n)
365 setCursor(where, false);
371 void LCursor::clearSelection()
380 int & LCursor::x_target()
386 int LCursor::x_target() const
392 void LCursor::clearTargetX()
399 void LCursor::info(std::ostream & os) const
401 for (int i = 1, n = depth(); i < n; ++i) {
402 operator[](i).inset().infoize(os);
406 prevInset()->infoize2(os);
407 // overwite old message
412 string LCursor::grabSelection()
417 CursorSlice i1 = selBegin();
418 CursorSlice i2 = selEnd();
420 if (i1.idx() == i2.idx()) {
421 if (i1.inset().asMathInset()) {
422 MathArray::const_iterator it = i1.cell().begin();
423 return asString(MathArray(it + i1.pos(), it + i2.pos()));
425 return "unknown selection 1";
431 region(i1, i2, r1, r2, c1, c2);
434 if (i1.inset().asMathInset()) {
435 for (row_type row = r1; row <= r2; ++row) {
438 for (col_type col = c1; col <= c2; ++col) {
441 data += asString(i1.asMathInset()->cell(i1.asMathInset()->index(row, col)));
445 data = "unknown selection 2";
451 void LCursor::eraseSelection()
453 //lyxerr << "LCursor::eraseSelection" << endl;
454 CursorSlice const & i1 = selBegin();
455 CursorSlice const & i2 = selEnd();
457 if (i1.inset().asMathInset()) {
458 if (i1.idx() == i2.idx()) {
459 i1.cell().erase(i1.pos(), i2.pos());
461 MathInset * p = i1.asMathInset();
464 region(i1, i2, r1, r2, c1, c2);
465 for (row_type row = r1; row <= r2; ++row)
466 for (col_type col = c1; col <= c2; ++col)
467 p->cell(p->index(row, col)).clear();
471 lyxerr << "can't erase this selection 1" << endl;
473 //lyxerr << "LCursor::eraseSelection end" << endl;
477 string LCursor::grabAndEraseSelection()
481 string res = grabSelection();
488 void LCursor::selClear()
495 void LCursor::selCopy()
498 theCutBuffer.push(grabSelection());
501 //theCutBuffer.erase();
506 void LCursor::selCut()
508 theCutBuffer.push(grabAndEraseSelection());
512 void LCursor::selDel()
514 //lyxerr << "LCursor::selDel" << endl;
522 void LCursor::selPaste(size_t n)
525 if (n < theCutBuffer.size())
526 paste(theCutBuffer[n]);
532 void LCursor::selHandle(bool sel)
534 //lyxerr << "LCursor::selHandle" << endl;
535 if (sel == selection())
542 void LCursor::selClearOrDel()
544 //lyxerr << "LCursor::selClearOrDel" << endl;
545 if (lyxrc.auto_region_delete)
552 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
554 for (size_t i = 0, n = cur.size(); i != n; ++i)
555 os << " " << cur.operator[](i) << " | " << cur.anchor_[i] << "\n";
556 os << " selection: " << cur.selection_ << endl;
563 ///////////////////////////////////////////////////////////////////
565 // The part below is the non-integrated rest of the original math
566 // cursor. This should be either generalized for texted or moved
567 // back to mathed (in most cases to MathNestInset).
569 ///////////////////////////////////////////////////////////////////
571 #include "mathed/math_charinset.h"
572 #include "mathed/math_factory.h"
573 #include "mathed/math_gridinset.h"
574 #include "mathed/math_macroarg.h"
575 #include "mathed/math_macrotemplate.h"
576 #include "mathed/math_mathmlstream.h"
577 #include "mathed/math_scriptinset.h"
578 #include "mathed/math_support.h"
579 #include "mathed/math_unknowninset.h"
581 //#define FILEDEBUG 1
584 bool LCursor::isInside(InsetBase const * p)
586 for (unsigned i = 0; i < depth(); ++i)
587 if (&operator[](i).inset() == p)
593 bool LCursor::openable(MathAtom const & t) const
604 // we can't move into anything new during selection
605 if (depth() == anchor_.size())
607 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
614 bool positionable(DocumentIterator const & cursor,
615 DocumentIterator const & anchor)
617 // avoid deeper nested insets when selecting
618 if (cursor.size() > anchor.size())
621 // anchor might be deeper, should have same path then
622 for (size_t i = 0; i < cursor.size(); ++i)
623 if (&cursor[i].inset() != &anchor[i].inset())
626 // position should be ok.
631 void LCursor::setScreenPos(int x, int y)
634 bruteFind(x, y, 0, bv().workWidth(), 0, bv().workHeight());
639 void LCursor::plainErase()
645 void LCursor::markInsert()
647 cell().insert(pos(), MathAtom(new MathCharInset(0)));
651 void LCursor::markErase()
657 void LCursor::plainInsert(MathAtom const & t)
659 cell().insert(pos(), t);
664 void LCursor::insert(string const & str)
666 lyxerr << "LCursor::insert str '" << str << "'" << endl;
667 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
672 void LCursor::insert(char c)
674 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
675 BOOST_ASSERT(!empty());
678 plainInsert(MathAtom(new MathCharInset(c)));
680 text()->insertChar(*this, c);
685 void LCursor::insert(MathAtom const & t)
687 //lyxerr << "LCursor::insert MathAtom: " << endl;
694 void LCursor::insert(InsetBase * inset)
697 insert(MathAtom(inset));
699 text()->insertInset(*this, inset);
703 void LCursor::niceInsert(string const & t)
714 void LCursor::niceInsert(MathAtom const & t)
717 string safe = grabAndEraseSelection();
719 // enter the new inset and move the contents of the selection if possible
722 // be careful here: don't use 'pushLeft(t)' as this we need to
723 // push the clone, not the original
724 pushLeft(*nextInset());
730 void LCursor::insert(MathArray const & ar)
735 cell().insert(pos(), ar);
740 bool LCursor::backspace()
742 autocorrect() = false;
750 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
757 MathUnknownInset * p = activeMacro();
758 if (p->name().size() > 1) {
759 p->setName(p->name().substr(0, p->name().size() - 1));
764 if (pos() != 0 && prevAtom()->nargs() > 0) {
765 // let's require two backspaces for 'big stuff' and
766 // highlight on the first
777 bool LCursor::erase()
779 autocorrect() = false;
788 // delete empty cells if possible
789 if (pos() == lastpos() && inset().idxDelete(idx()))
792 // special behaviour when in last position of cell
793 if (pos() == lastpos()) {
794 bool one_cell = inset().nargs() == 1;
795 if (one_cell && depth() == 1 && lastpos() == 0)
801 inset().idxGlue(idx());
805 if (pos() != lastpos() && inset().nargs() > 0) {
819 DocumentIterator save = *this;
822 setCursor(save, false);
823 autocorrect() = false;
831 DocumentIterator 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 void LCursor::adjust(pos_type from, int diff)
897 if (anchor().pos() > from)
898 anchor().pos() += diff;
899 // just to be on the safe side
900 // theoretically unecessary
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 bool LCursor::inMacroArgMode() const
922 return pos() > 0 && prevAtom()->getChar() == '#';
926 MathGridInset * LCursor::enclosingGrid(idx_type & idx) const
928 for (MathInset::difference_type i = depth() - 1; i >= 0; --i) {
929 MathInset * m = operator[](i).inset().asMathInset();
932 MathGridInset * p = m->asGridInset();
934 idx = operator[](i).idx();
942 void LCursor::pullArg()
945 MathArray ar = cell();
946 if (popLeft() && inMathed()) {
948 cell().insert(pos(), ar);
951 //formula()->mutateToText();
956 void LCursor::touch()
960 DocumentIterator::const_iterator it = begin();
961 DocumentIterator::const_iterator et = end();
962 for ( ; it != et; ++it)
968 void LCursor::normalize()
970 if (idx() >= nargs()) {
971 lyxerr << "this should not really happen - 1: "
972 << idx() << ' ' << nargs()
973 << " in: " << &inset() << endl;
975 idx() = min(idx(), lastidx());
977 if (pos() > lastpos()) {
978 lyxerr << "this should not really happen - 2: "
979 << pos() << ' ' << lastpos() << " in idx: " << idx()
981 WriteStream wi(lyxerr, false, true);
982 inset().asMathInset()->write(wi);
985 pos() = min(pos(), lastpos());
989 char LCursor::valign()
992 MathGridInset * p = enclosingGrid(idx);
993 return p ? p->valign() : '\0';
997 char LCursor::halign()
1000 MathGridInset * p = enclosingGrid(idx);
1001 return p ? p->halign(idx % p->ncols()) : '\0';
1005 bool LCursor::goUpDown(bool up)
1007 // Be warned: The 'logic' implemented in this function is highly
1008 // fragile. A distance of one pixel or a '<' vs '<=' _really
1009 // matters. So fiddle around with it only if you think you know
1010 // what you are doing!
1016 // check if we had something else in mind, if not, this is the future goal
1017 if (x_target() == -1)
1022 // try neigbouring script insets
1026 MathScriptInset const * p = prevAtom()->asScriptInset();
1027 if (p && p->has(up)) {
1030 idx() = up; // the superscript has index 1
1032 //lyxerr << "updown: handled by scriptinset to the left" << endl;
1038 if (pos() != lastpos()) {
1039 MathScriptInset const * p = nextAtom()->asScriptInset();
1040 if (p && p->has(up)) {
1044 //lyxerr << "updown: handled by scriptinset to the right" << endl;
1050 // try current cell for e.g. text insets
1051 if (inset().idxUpDown2(*this, up))
1054 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1059 //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1060 // lyxerr << "updown: handled by brute find in the same cell" << endl;
1064 // try to find an inset that knows better then we
1066 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1068 if (inset().idxUpDown(*this, up)) {
1069 // try to find best position within this inset
1075 // no such inset found, just take something "above"
1076 //lyxerr << "updown: handled by strange case" << endl;
1078 int ylow = up ? 0 : yo + 1;
1079 int yhigh = up ? yo - 1 : bv().workHeight();
1080 return bruteFind(xo, yo, 0, bv().workWidth(), ylow, yhigh);
1083 // any improvement so far?
1086 if (up ? ynew < yo : ynew > yo)
1092 bool LCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1094 BOOST_ASSERT(!empty());
1095 ParagraphList::iterator beg;
1096 ParagraphList::iterator end;
1097 CursorSlice bottom = operator[](0);
1098 LyXText * text = bottom.text();
1100 getParsInRange(text->paragraphs(), ylow, yhigh, beg, end);
1102 DocumentIterator it(bv().buffer()->inset());
1103 DocumentIterator et;
1104 lyxerr << "x: " << x << " y: " << y << endl;
1105 lyxerr << "xlow: " << xlow << " ylow: " << ylow << endl;
1106 lyxerr << "xhigh: " << xhigh << " yhigh: " << yhigh << endl;
1108 it.par() = text->parOffset(beg);
1109 //et.par() = text->parOffset(end);
1111 double best_dist = 10e10;
1112 DocumentIterator best_cursor = it;
1114 for ( ; it != et; it.forwardPos()) {
1115 // avoid invalid nesting when selecting
1116 if (!selection() || positionable(it, anchor_)) {
1118 CursorSlice & cur = it.back();
1119 cur.inset().getCursorPos(cur, xo, yo);
1120 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1121 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1122 lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
1123 // '<=' in order to take the last possible position
1124 // this is important for clicking behind \sum in e.g. '\sum_i a'
1125 if (d <= best_dist) {
1126 lyxerr << "*" << endl;
1134 lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
1135 if (best_dist < 1e10)
1136 setCursor(best_cursor, false);
1137 return best_dist < 1e10;
1141 void LCursor::bruteFind2(int x, int y)
1143 double best_dist = 1e10;
1145 DocumentIterator it = *this;
1146 it.back().pos() = 0;
1147 DocumentIterator et = *this;
1148 et.back().pos() = et.back().asMathInset()->cell(et.back().idx()).size();
1149 for (int i = 0; ; ++i) {
1151 CursorSlice & cur = it.back();
1152 cur.inset().getCursorPos(cur, xo, yo);
1153 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1154 // '<=' in order to take the last possible position
1155 // this is important for clicking behind \sum in e.g. '\sum_i a'
1156 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
1157 if (d <= best_dist) {
1159 setCursor(it, false);
1168 CursorSlice LCursor::normalAnchor()
1170 if (anchor_.size() < depth()) {
1172 lyxerr << "unusual Anchor size" << endl;
1174 //lyx::BOOST_ASSERT(Anchor_.size() >= cursor.depth());
1175 // use Anchor on the same level as Cursor
1176 CursorSlice normal = anchor_[size() - 1];
1178 if (depth() < anchor_.size() && !(normal < xx())) {
1179 // anchor is behind cursor -> move anchor behind the inset
1187 void LCursor::handleFont(string const & font)
1189 lyxerr << "LCursor::handleFont: " << font << endl;
1193 safe = grabAndEraseSelection();
1196 if (lastpos() != 0) {
1197 // something left in the cell
1199 // cursor in first position
1201 } else if (pos() == lastpos()) {
1202 // cursor in last position
1205 // cursor in between. split cell
1206 MathArray::iterator bt = cell().begin();
1207 MathAtom at = createMathInset(font);
1208 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1209 cell().erase(bt, bt + pos());
1214 // nothing left in the cell
1222 void LCursor::message(string const & msg) const
1224 bv().owner()->getLyXFunc().setMessage(msg);
1228 void LCursor::errorMessage(string const & msg) const
1230 bv().owner()->getLyXFunc().setErrorMessage(msg);
1234 string LCursor::selectionAsString(bool label) const
1240 Buffer const & buffer = *bv().buffer();
1242 // should be const ...
1243 ParagraphList::iterator startpit = text()->getPar(selBegin());
1244 ParagraphList::iterator endpit = text()->getPar(selEnd());
1245 size_t const startpos = selBegin().pos();
1246 size_t const endpos = selEnd().pos();
1248 if (startpit == endpit)
1249 return startpit->asString(buffer, startpos, endpos, label);
1251 // First paragraph in selection
1253 startpit->asString(buffer, startpos, startpit->size(), label) + "\n\n";
1255 // The paragraphs in between (if any)
1256 ParagraphList::iterator pit = startpit;
1257 for (++pit; pit != endpit; ++pit)
1258 result += pit->asString(buffer, 0, pit->size(), label) + "\n\n";
1260 // Last paragraph in selection
1261 result += endpit->asString(buffer, 0, endpos, label);
1266 #warning and mathed?
1271 string LCursor::currentState()
1274 std::ostringstream os;
1280 return text()->currentState(*this);
1286 // only used by the spellchecker
1287 void LCursor::replaceWord(string const & replacestring)
1289 LyXText * t = text();
1292 t->replaceSelectionWithString(*this, replacestring);
1293 t->setSelectionRange(*this, replacestring.length());
1295 // Go back so that replacement string is also spellchecked
1296 for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
1297 t->cursorLeft(*this);
1301 void LCursor::update()
1307 string LCursor::getPossibleLabel()
1309 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1313 Encoding const * LCursor::getEncoding() const
1320 // go up until first non-0 text is hit
1321 // (innermost text is 0 in mathed)
1322 for (s = size() - 1; s >= 0; --s)
1323 if (operator[](s).text())
1325 CursorSlice const & sl = operator[](s);
1326 LyXText & text = *sl.text();
1327 ParagraphList::iterator pit = text.getPar(sl.par());
1328 LyXFont font = pit->getFont(
1329 bv().buffer()->params(), sl.pos(), outerFont(pit, text.paragraphs()));
1330 return font.language()->encoding();
1334 void LCursor::undispatched()
1336 disp_.dispatched(false);
1340 void LCursor::noUpdate()
1342 disp_.update(false);