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.
16 #include "BufferView.h"
19 #include "dispatchresult.h"
20 #include "funcrequest.h"
21 #include "iterators.h"
23 #include "lyxfunc.h" // only for setMessage()
27 #include "paragraph.h"
29 #include "insets/updatableinset.h"
30 #include "insets/insettabular.h"
31 #include "insets/insettext.h"
33 #include "mathed/math_data.h"
34 #include "mathed/math_hullinset.h"
35 #include "mathed/math_support.h"
37 #include "support/limited_stack.h"
38 #include "support/std_sstream.h"
40 #include "frontends/LyXView.h"
42 #include <boost/assert.hpp>
47 #ifndef CXX_GLOBAL_CSTD
56 limited_stack<string> theCutBuffer;
59 LCursor::LCursor(BufferView & bv)
60 : cursor_(1), anchor_(1), bv_(&bv), current_(0),
61 cached_y_(0), x_target_(-1),
62 selection_(false), mark_(false)
70 cursor_.push_back(CursorSlice());
71 anchor_.push_back(CursorSlice());
80 DispatchResult LCursor::dispatch(FuncRequest const & cmd0)
82 lyxerr << "\nLCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
83 FuncRequest cmd = cmd0;
84 for (current_ = cursor_.size() - 1; current_ >= 1; --current_) {
85 DispatchResult res = inset()->dispatch(*this, cmd);
87 return DispatchResult(true, true);
89 // "Mutate" the request for semi-handled requests that need
90 // additional handling in outer levels.
93 cmd = FuncRequest(LFUN_FINISHED_LEFT);
96 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
99 cmd = FuncRequest(LFUN_FINISHED_UP);
102 cmd = FuncRequest(LFUN_FINISHED_DOWN);
105 //lyxerr << "not handled on level " << current_
106 // << " val: " << res.val() << endl;
110 BOOST_ASSERT(current_ == 0);
111 DispatchResult res = bv_->text()->dispatch(*this, cmd);
112 //lyxerr << " result: " << res.val() << endl;
117 void LCursor::push(InsetBase * inset)
119 lyxerr << "LCursor::push() inset: " << inset << endl;
120 cursor_.push_back(CursorSlice(inset));
121 anchor_.push_back(CursorSlice(inset));
127 void LCursor::pop(int depth)
129 while (int(cursor_.size()) > depth + 1)
131 lyxerr << "LCursor::pop() result: " << *this << endl;
137 BOOST_ASSERT(cursor_.size() >= 1);
140 current_ = cursor_.size() - 1;
144 void LCursor::pushLeft(InsetBase * p)
146 BOOST_ASSERT(!cursor_.empty());
147 //lyxerr << "Entering inset " << t << " left" << endl;
153 bool LCursor::popLeft()
155 BOOST_ASSERT(!cursor_.empty());
156 //lyxerr << "Leaving inset to the left" << endl;
159 inset()->notifyCursorLeaves(idx());
162 inset()->notifyCursorLeaves(idx());
168 bool LCursor::popRight()
170 BOOST_ASSERT(!cursor_.empty());
171 //lyxerr << "Leaving inset to the right" << endl;
174 inset()->notifyCursorLeaves(idx());
177 inset()->notifyCursorLeaves(idx());
184 CursorSlice & LCursor::current()
186 BOOST_ASSERT(!cursor_.empty());
187 //lyxerr << "accessing cursor slice " << current_
188 // << ": " << cursor_[current_] << endl;
189 return cursor_[current_];
193 CursorSlice const & LCursor::current() const
195 //lyxerr << "accessing cursor slice " << current_
196 // << ": " << cursor_[current_] << endl;
197 return cursor_[current_];
201 int LCursor::currentMode()
203 BOOST_ASSERT(!cursor_.empty());
204 for (int i = cursor_.size() - 1; i >= 1; --i) {
205 int res = cursor_[i].inset()->currentMode();
206 if (res != MathInset::UNDECIDED_MODE)
209 return MathInset::TEXT_MODE;
213 LyXText * LCursor::innerText() const
215 BOOST_ASSERT(!cursor_.empty());
216 if (cursor_.size() > 1) {
217 // go up until first non-0 text is hit
218 // (innermost text is 0 in mathed)
219 for (int i = cursor_.size() - 1; i >= 1; --i)
220 if (cursor_[i].text())
221 return cursor_[i].text();
227 CursorSlice const & LCursor::innerTextSlice() const
229 BOOST_ASSERT(!cursor_.empty());
230 if (cursor_.size() > 1) {
231 // go up until first non-0 text is hit
232 // (innermost text is 0 in mathed)
233 for (int i = cursor_.size() - 1; i >= 1; --i)
234 if (cursor_[i].text())
241 void LCursor::updatePos()
243 BOOST_ASSERT(!cursor_.empty());
244 if (cursor_.size() > 1)
245 cached_y_ = bv_->top_y() + cursor_.back().inset()->yo();
246 //cached_y_ = cursor_.back().inset()->yo();
250 void LCursor::getDim(int & asc, int & des) const
252 BOOST_ASSERT(!cursor_.empty());
254 BOOST_ASSERT(inset());
255 BOOST_ASSERT(inset()->asMathInset());
256 //inset()->asMathInset()->getCursorDim(asc, des);
260 Row const & row = textRow();
261 asc = row.baseline();
262 des = row.height() - asc;
267 void LCursor::getPos(int & x, int & y) const
269 BOOST_ASSERT(!cursor_.empty());
272 if (cursor_.size() == 1) {
273 x = bv_->text()->cursorX(cursor_.front());
274 y = bv_->text()->cursorY(cursor_.front());
277 lyxerr << "#### LCursor::getPos: " << *this << endl;
278 BOOST_ASSERT(inset());
280 inset()->getCursorPos(cursor_.back(), x, y);
281 // getCursorPos gives _screen_ coordinates. We need to add
282 // top_y to get document coordinates. This is hidden in cached_y_.
283 //y += cached_y_ - inset()->yo();
284 // The rest is non-obvious. The reason we have to have these
285 // extra computation is that the getCursorPos() calls rely
286 // on the inset's own knowledge of its screen position.
287 // If we scroll up or down in a big enough increment,
288 // inset->draw() is not called: this doesn't update
289 // inset.yo_, so getCursor() returns an old value.
292 //lyxerr << "#### LCursor::getPos: " << *this
293 // << " x: " << x << " y: " << y << endl;
297 void LCursor::paste(string const & data)
299 dispatch(FuncRequest(LFUN_PASTE, data));
303 InsetBase * LCursor::innerInsetOfType(int code) const
305 for (int i = cursor_.size() - 1; i >= 1; --i)
306 if (cursor_[i].inset_->lyxCode() == code)
307 return cursor_[i].inset_;
312 InsetTabular * LCursor::innerInsetTabular() const
314 return static_cast<InsetTabular *>(innerInsetOfType(InsetBase::TABULAR_CODE));
318 void LCursor::resetAnchor()
324 BufferView & LCursor::bv() const
330 MathAtom const & LCursor::prevAtom() const
332 BOOST_ASSERT(pos() > 0);
333 return cell()[pos() - 1];
337 MathAtom & LCursor::prevAtom()
339 BOOST_ASSERT(pos() > 0);
340 return cell()[pos() - 1];
344 MathAtom const & LCursor::nextAtom() const
346 BOOST_ASSERT(pos() < lastpos());
347 return cell()[pos()];
351 MathAtom & LCursor::nextAtom()
353 BOOST_ASSERT(pos() < lastpos());
354 return cell()[pos()];
358 bool LCursor::posLeft()
367 bool LCursor::posRight()
369 if (pos() == lastpos())
376 CursorSlice & LCursor::anchor()
378 return anchor_.back();
382 CursorSlice const & LCursor::anchor() const
384 return anchor_.back();
388 CursorSlice const & LCursor::selBegin() const
391 return cursor_.back();
392 return anchor() < cursor_.back() ? anchor() : cursor_.back();
396 CursorSlice & LCursor::selBegin()
399 return cursor_.back();
400 // can't use std::min as this returns a const ref
401 return anchor() < cursor_.back() ? anchor() : cursor_.back();
405 CursorSlice const & LCursor::selEnd() const
408 return cursor_.back();
409 return anchor() > cursor_.back() ? anchor() : cursor_.back();
413 CursorSlice & LCursor::selEnd()
416 return cursor_.back();
417 // can't use std::min as this returns a const ref
418 return anchor() > cursor_.back() ? anchor() : cursor_.back();
422 void LCursor::setSelection()
425 // a selection with no contents is not a selection
426 if (par() == anchor().par() && pos() == anchor().pos())
431 void LCursor::setSelection(CursorBase const & where, size_t n)
440 void LCursor::clearSelection()
449 int & LCursor::x_target()
455 int LCursor::x_target() const
461 void LCursor::clearTargetX()
467 LyXText * LCursor::text() const
469 return current_ ? current().text() : bv_->text();
473 Paragraph & LCursor::paragraph()
475 BOOST_ASSERT(inTexted());
476 return current_ ? current().paragraph() : *bv_->text()->getPar(par());
480 Paragraph const & LCursor::paragraph() const
482 BOOST_ASSERT(inTexted());
483 return current_ ? current().paragraph() : *bv_->text()->getPar(par());
487 Row & LCursor::textRow()
489 return *paragraph().getRow(pos());
493 Row const & LCursor::textRow() const
495 return *paragraph().getRow(pos());
499 LCursor::par_type LCursor::lastpar() const
501 return inMathed() ? 0 : text()->paragraphs().size() - 1;
505 LCursor::pos_type LCursor::lastpos() const
507 InsetBase * inset = current().inset();
508 return inset && inset->asMathInset() ? cell().size() : paragraph().size();
512 LCursor::row_type LCursor::crow() const
514 return paragraph().row(pos());
518 LCursor::row_type LCursor::lastcrow() const
520 return paragraph().rows.size();
524 size_t LCursor::nargs() const
526 // assume 1x1 grid for 'plain text'
527 return current_ ? current().nargs() : 1;
531 size_t LCursor::ncols() const
533 // assume 1x1 grid for 'plain text'
534 return current_ ? current().ncols() : 1;
538 size_t LCursor::nrows() const
540 // assume 1x1 grid for 'plain text'
541 return current_ ? current().nrows() : 1;
545 LCursor::row_type LCursor::row() const
547 BOOST_ASSERT(current_ > 0);
548 return current().row();
552 LCursor::col_type LCursor::col() const
554 BOOST_ASSERT(current_ > 0);
555 return current().col();
559 MathArray const & LCursor::cell() const
561 BOOST_ASSERT(current_ > 0);
562 return current().cell();
566 MathArray & LCursor::cell()
568 BOOST_ASSERT(current_ > 0);
569 return current().cell();
573 void LCursor::info(std::ostream & os) const
575 for (int i = 1, n = depth(); i < n; ++i) {
576 cursor_[i].inset()->infoize(os);
580 prevInset()->infoize2(os);
581 // overwite old message
588 void region(CursorSlice const & i1, CursorSlice const & i2,
589 LCursor::row_type & r1, LCursor::row_type & r2,
590 LCursor::col_type & c1, LCursor::col_type & c2)
592 InsetBase * p = i1.inset();
593 c1 = p->col(i1.idx_);
594 c2 = p->col(i2.idx_);
597 r1 = p->row(i1.idx_);
598 r2 = p->row(i2.idx_);
606 string LCursor::grabSelection()
611 CursorSlice i1 = selBegin();
612 CursorSlice i2 = selEnd();
614 if (i1.idx_ == i2.idx_) {
615 if (i1.inset()->asMathInset()) {
616 MathArray::const_iterator it = i1.cell().begin();
617 return asString(MathArray(it + i1.pos_, it + i2.pos_));
619 return "unknown selection 1";
625 region(i1, i2, r1, r2, c1, c2);
628 if (i1.inset()->asMathInset()) {
629 for (row_type row = r1; row <= r2; ++row) {
632 for (col_type col = c1; col <= c2; ++col) {
635 data += asString(i1.asMathInset()->cell(i1.asMathInset()->index(row, col)));
639 data = "unknown selection 2";
645 void LCursor::eraseSelection()
647 //lyxerr << "LCursor::eraseSelection" << endl;
648 CursorSlice const & i1 = selBegin();
649 CursorSlice const & i2 = selEnd();
651 if (i1.inset()->asMathInset()) {
652 if (i1.idx_ == i2.idx_) {
653 i1.cell().erase(i1.pos_, i2.pos_);
655 MathInset * p = i1.asMathInset();
658 region(i1, i2, r1, r2, c1, c2);
659 for (row_type row = r1; row <= r2; ++row)
660 for (col_type col = c1; col <= c2; ++col)
661 p->cell(p->index(row, col)).clear();
665 lyxerr << "can't erase this selection 1" << endl;
667 //lyxerr << "LCursor::eraseSelection end" << endl;
671 string LCursor::grabAndEraseSelection()
675 string res = grabSelection();
682 void LCursor::selClear()
689 void LCursor::selCopy()
692 theCutBuffer.push(grabSelection());
695 //theCutBuffer.erase();
700 void LCursor::selCut()
702 theCutBuffer.push(grabAndEraseSelection());
706 void LCursor::selDel()
708 //lyxerr << "LCursor::selDel" << endl;
716 void LCursor::selPaste(size_t n)
719 if (n < theCutBuffer.size())
720 paste(theCutBuffer[n]);
726 void LCursor::selHandle(bool sel)
728 //lyxerr << "LCursor::selHandle" << endl;
729 if (sel == selection())
736 void LCursor::selClearOrDel()
738 //lyxerr << "LCursor::selClearOrDel" << endl;
739 if (lyxrc.auto_region_delete)
746 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
748 for (size_t i = 0, n = cur.cursor_.size(); i != n; ++i)
749 os << " " << cur.cursor_[i] << " | " << cur.anchor_[i] << "\n";
750 os << " current: " << cur.current_ << endl;
751 os << " selection: " << cur.selection_ << endl;
763 void increment(CursorBase & it)
765 CursorSlice & top = it.back();
766 MathArray & ar = top.asMathInset()->cell(top.idx_);
768 // move into the current inset if possible
769 // it is impossible for pos() == size()!
771 if (top.pos() != top.lastpos())
772 n = (ar.begin() + top.pos_)->nucleus();
773 if (n && n->isActive()) {
774 it.push_back(CursorSlice(n));
778 // otherwise move on one cell back if possible
779 if (top.pos() < top.lastpos()) {
780 // pos() == lastpos() is valid!
785 // otherwise try to move on one cell if possible
786 while (top.idx() < top.lastidx()) {
788 if (top.asMathInset()->validCell(top.idx_)) {
794 // otherwise leave array, move on one back
795 // this might yield pos() == size(), but that's a ok.
797 // it certainly invalidates top
802 CursorBase ibegin(InsetBase * p)
805 it.push_back(CursorSlice(p));
810 CursorBase iend(InsetBase * p)
813 it.push_back(CursorSlice(p));
814 CursorSlice & cur = it.back();
815 cur.idx() = cur.lastidx();
816 cur.pos() = cur.lastpos();
823 ///////////////////////////////////////////////////////////////////
825 // The part below is the non-integrated rest of the original math
826 // cursor. This should be either generalized for texted or moved
827 // back to the math insets.
829 ///////////////////////////////////////////////////////////////////
831 #include "mathed/math_braceinset.h"
832 #include "mathed/math_charinset.h"
833 #include "mathed/math_commentinset.h"
834 #include "mathed/math_factory.h"
835 #include "mathed/math_gridinset.h"
836 #include "mathed/math_macroarg.h"
837 #include "mathed/math_macrotemplate.h"
838 #include "mathed/math_mathmlstream.h"
839 #include "mathed/math_scriptinset.h"
840 #include "mathed/math_spaceinset.h"
841 #include "mathed/math_support.h"
842 #include "mathed/math_unknowninset.h"
844 //#define FILEDEBUG 1
847 bool LCursor::isInside(InsetBase const * p)
849 for (unsigned i = 0; i < depth(); ++i)
850 if (cursor_[i].inset() == p)
856 bool LCursor::openable(MathAtom const & t)
867 // we can't move into anything new during selection
868 if (depth() == anchor_.size())
870 if (!ptr_cmp(t.nucleus(), anchor_[depth()].inset()))
877 bool LCursor::inNucleus()
879 return inset()->asMathInset()->asScriptInset() && idx() == 2;
885 autocorrect() = false;
892 if (pos() != 0 && openable(prevAtom())) {
894 push(nextAtom().nucleus());
895 inset()->idxLast(*this);
899 return posLeft() || idxLeft() || popLeft() || selection();
903 bool LCursor::right()
905 autocorrect() = false;
912 if (pos() != lastpos() && openable(nextAtom())) {
913 pushLeft(nextAtom().nucleus());
914 inset()->idxFirst(*this);
918 return posRight() || idxRight() || popRight() || selection();
922 bool positionable(CursorBase const & cursor, CursorBase const & anchor)
924 // avoid deeper nested insets when selecting
925 if (cursor.size() > anchor.size())
928 // anchor might be deeper, should have same path then
929 for (size_t i = 0; i < cursor.size(); ++i)
930 if (cursor[i].inset() != anchor[i].inset())
933 // position should be ok.
938 void LCursor::setScreenPos(int x, int y)
940 bool res = bruteFind(x, y, formula()->xlow(), formula()->xhigh(),
941 formula()->ylow(), formula()->yhigh());
943 // this can happen on creation of "math-display"
954 autocorrect() = false;
956 if (!inset()->idxHome(*this))
965 autocorrect() = false;
967 if (!inset()->idxEnd(*this))
974 void LCursor::plainErase()
980 void LCursor::markInsert()
982 cell().insert(pos(), MathAtom(new MathCharInset(0)));
986 void LCursor::markErase()
992 void LCursor::plainInsert(MathAtom const & t)
994 cell().insert(pos(), t);
999 void LCursor::insert(string const & str)
1001 lyxerr << "LCursor::insert str '" << str << "'" << endl;
1004 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
1005 plainInsert(MathAtom(new MathCharInset(*it)));
1014 void LCursor::insert(char c)
1016 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
1018 plainInsert(MathAtom(new MathCharInset(c)));
1022 void LCursor::insert(MathAtom const & t)
1024 //lyxerr << "LCursor::insert MathAtom: " << endl;
1031 void LCursor::insert(InsetBase * inset)
1034 insert(MathAtom(inset));
1036 text()->insertInset(*this, inset);
1040 void LCursor::niceInsert(string const & t)
1051 void LCursor::niceInsert(MathAtom const & t)
1054 string safe = grabAndEraseSelection();
1056 // enter the new inset and move the contents of the selection if possible
1057 if (t->isActive()) {
1059 // be careful here: don't use 'pushLeft(t)' as this we need to
1060 // push the clone, not the original
1061 pushLeft(nextAtom().nucleus());
1067 void LCursor::insert(MathArray const & ar)
1072 cell().insert(pos(), ar);
1077 bool LCursor::backspace()
1079 autocorrect() = false;
1087 if (inset()->nargs() == 1 && depth() == 1 && lastpos() == 0)
1093 if (inMacroMode()) {
1094 MathUnknownInset * p = activeMacro();
1095 if (p->name().size() > 1) {
1096 p->setName(p->name().substr(0, p->name().size() - 1));
1101 if (pos() != 0 && prevAtom()->nargs() > 0) {
1102 // let's require two backspaces for 'big stuff' and
1103 // highlight on the first
1114 bool LCursor::erase()
1116 autocorrect() = false;
1125 // delete empty cells if possible
1126 if (pos() == lastpos() && inset()->idxDelete(idx()))
1129 // special behaviour when in last position of cell
1130 if (pos() == lastpos()) {
1131 bool one_cell = inset()->nargs() == 1;
1132 if (one_cell && depth() == 1 && lastpos() == 0)
1138 inset()->idxGlue(idx());
1142 if (pos() != lastpos() && inset()->nargs() > 0) {
1156 CursorBase save = cursor_;
1160 autocorrect() = false;
1165 bool LCursor::down()
1168 CursorBase save = cursor_;
1169 if (goUpDown(false))
1172 autocorrect() = false;
1177 void LCursor::macroModeClose()
1181 MathUnknownInset * p = activeMacro();
1183 string s = p->name();
1185 cell().erase(pos());
1187 // do nothing if the macro name is empty
1191 string const name = s.substr(1);
1193 // prevent entering of recursive macros
1194 if (formula()->lyxCode() == InsetOld::MATHMACRO_CODE
1195 && formula()->getInsetName() == name)
1196 lyxerr << "can't enter recursive macro" << endl;
1198 niceInsert(createMathInset(name));
1202 string LCursor::macroName()
1204 return inMacroMode() ? activeMacro()->name() : string();
1208 void LCursor::handleNest(MathAtom const & a, int c)
1210 //lyxerr << "LCursor::handleNest: " << c << endl;
1212 asArray(grabAndEraseSelection(), t.nucleus()->cell(c));
1215 pushLeft(nextAtom().nucleus());
1219 int LCursor::targetX() const
1221 if (x_target() != -1)
1230 MathHullInset * LCursor::formula() const
1232 for (int i = cursor_.size() - 1; i >= 1; --i) {
1233 MathInset * inset = cursor_[i].inset()->asMathInset();
1234 if (inset && inset->asHullInset())
1235 return static_cast<MathHullInset *>(inset);
1241 void LCursor::adjust(pos_type from, int diff)
1245 if (anchor().pos_ > from)
1246 anchor().pos_ += diff;
1247 // just to be on the safe side
1248 // theoretically unecessary
1253 bool LCursor::inMacroMode() const
1257 MathUnknownInset const * p = prevAtom()->asUnknownInset();
1258 return p && !p->final();
1262 MathUnknownInset * LCursor::activeMacro()
1264 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1268 bool LCursor::inMacroArgMode() const
1270 return pos() > 0 && prevAtom()->getChar() == '#';
1274 MathGridInset * LCursor::enclosingGrid(idx_type & idx) const
1276 for (MathInset::difference_type i = depth() - 1; i >= 0; --i) {
1277 MathInset * m = cursor_[i].inset()->asMathInset();
1280 MathGridInset * p = m->asGridInset();
1282 idx = cursor_[i].idx_;
1290 void LCursor::pullArg()
1293 MathArray ar = cell();
1294 if (popLeft() && inMathed()) {
1296 cell().insert(pos(), ar);
1299 //formula()->mutateToText();
1304 void LCursor::touch()
1308 CursorBase::const_iterator it = cursor_.begin();
1309 CursorBase::const_iterator et = cursor_.end();
1310 for ( ; it != et; ++it)
1316 void LCursor::normalize()
1318 if (idx() >= nargs()) {
1319 lyxerr << "this should not really happen - 1: "
1320 << idx() << ' ' << nargs()
1321 << " in: " << inset() << endl;
1323 idx() = min(idx(), lastidx());
1325 if (pos() > lastpos()) {
1326 lyxerr << "this should not really happen - 2: "
1327 << pos() << ' ' << lastpos() << " in idx: " << idx()
1329 WriteStream wi(lyxerr, false, true);
1330 inset()->asMathInset()->write(wi);
1333 pos() = min(pos(), lastpos());
1337 char LCursor::valign()
1340 MathGridInset * p = enclosingGrid(idx);
1341 return p ? p->valign() : '\0';
1345 char LCursor::halign()
1348 MathGridInset * p = enclosingGrid(idx);
1349 return p ? p->halign(idx % p->ncols()) : '\0';
1353 bool LCursor::goUpDown(bool up)
1355 // Be warned: The 'logic' implemented in this function is highly fragile.
1356 // A distance of one pixel or a '<' vs '<=' _really_ matters.
1357 // So fiddle around with it only if you know what you are doing!
1362 // check if we had something else in mind, if not, this is the future goal
1363 if (x_target() == -1)
1368 // try neigbouring script insets
1372 MathScriptInset const * p = prevAtom()->asScriptInset();
1373 if (p && p->has(up)) {
1376 idx() = up; // the superscript has index 1
1378 //lyxerr << "updown: handled by scriptinset to the left" << endl;
1384 if (pos() != lastpos()) {
1385 MathScriptInset const * p = nextAtom()->asScriptInset();
1386 if (p && p->has(up)) {
1390 //lyxerr << "updown: handled by scriptinset to the right" << endl;
1396 // try current cell for e.g. text insets
1397 if (inset()->idxUpDown2(*this, up))
1400 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1405 //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1406 // lyxerr << "updown: handled by brute find in the same cell" << endl;
1410 // try to find an inset that knows better then we
1412 //lyxerr << "updown: We are in " << inset() << " idx: " << idx() << endl;
1414 if (inset()->idxUpDown(*this, up)) {
1415 // try to find best position within this inset
1421 // no such inset found, just take something "above"
1422 //lyxerr << "updown: handled by strange case" << endl;
1428 up ? formula()->ylow() : yo + 4,
1429 up ? yo - 4 : formula()->yhigh()
1433 // any improvement so far?
1436 if (up ? ynew < yo : ynew > yo)
1442 bool LCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1444 CursorBase best_cursor;
1445 double best_dist = 1e10;
1447 CursorBase it = ibegin(formula());
1448 CursorBase et = iend(formula());
1450 // avoid invalid nesting when selecting
1451 if (!selection() || positionable(it, anchor_)) {
1453 CursorSlice & cur = it.back();
1454 cur.inset()->getCursorPos(cur, xo, yo);
1455 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1456 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1457 //lyxerr << "x: " << x << " y: " << y << " d: " << endl;
1458 // '<=' in order to take the last possible position
1459 // this is important for clicking behind \sum in e.g. '\sum_i a'
1460 if (d <= best_dist) {
1472 if (best_dist < 1e10)
1473 cursor_ = best_cursor;
1474 return best_dist < 1e10;
1478 void LCursor::bruteFind2(int x, int y)
1480 double best_dist = 1e10;
1482 CursorBase it = cursor_;
1484 CursorBase et = cursor_;
1485 int n = et.back().asMathInset()->cell(et.back().idx_).size();
1487 for (int i = 0; ; ++i) {
1489 CursorSlice & cur = it.back();
1490 cur.inset()->getCursorPos(cur, xo, yo);
1491 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1492 // '<=' in order to take the last possible position
1493 // this is important for clicking behind \sum in e.g. '\sum_i a'
1494 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
1495 if (d <= best_dist) {
1506 bool LCursor::idxLineLast()
1508 idx() -= idx() % ncols();
1509 idx() += ncols() - 1;
1515 bool LCursor::idxLeft()
1517 return inset()->idxLeft(*this);
1521 bool LCursor::idxRight()
1523 return inset()->idxRight(*this);
1527 bool LCursor::script(bool up)
1529 // Hack to get \\^ and \\_ working
1530 lyxerr << "handling script: up: " << up << endl;
1531 if (inMacroMode() && macroName() == "\\") {
1533 niceInsert(createMathInset("mathcircumflex"));
1540 string safe = grabAndEraseSelection();
1542 // we are in a nucleus of a script inset, move to _our_ script
1543 inset()->asMathInset()->asScriptInset()->ensure(up);
1546 } else if (pos() != 0 && prevAtom()->asScriptInset()) {
1548 nextAtom().nucleus()->asScriptInset()->ensure(up);
1552 } else if (pos() != 0) {
1554 cell()[pos()] = MathAtom(new MathScriptInset(nextAtom(), up));
1559 plainInsert(MathAtom(new MathScriptInset(up)));
1561 nextAtom().nucleus()->asScriptInset()->ensure(up);
1571 bool LCursor::interpret(char c)
1573 //lyxerr << "interpret 2: '" << c << "'" << endl;
1575 if (inMacroArgMode()) {
1581 MathMacroTemplate const * p = formula()->asMacroTemplate();
1582 if (p && 1 <= n && n <= p->numargs())
1583 insert(MathAtom(new MathMacroArgument(c - '0')));
1585 insert(createMathInset("#"));
1586 interpret(c); // try again
1593 if (inMacroMode()) {
1594 string name = macroName();
1595 //lyxerr << "interpret name: '" << name << "'" << endl;
1598 activeMacro()->setName(activeMacro()->name() + c);
1602 // handle 'special char' macros
1607 if (currentMode() == MathInset::TEXT_MODE)
1608 niceInsert(createMathInset("textbackslash"));
1610 niceInsert(createMathInset("backslash"));
1611 } else if (c == '{') {
1612 niceInsert(MathAtom(new MathBraceInset));
1614 niceInsert(createMathInset(string(1, c)));
1619 // leave macro mode and try again if necessary
1622 niceInsert(MathAtom(new MathBraceInset));
1628 // This is annoying as one has to press <space> far too often.
1632 // leave autocorrect mode if necessary
1633 if (autocorrect() && c == ' ') {
1634 autocorrect() = false;
1639 // just clear selection on pressing the space bar
1640 if (selection() && c == ' ') {
1641 selection() = false;
1648 //lyxerr << "starting with macro" << endl;
1649 insert(MathAtom(new MathUnknownInset("\\", false)));
1654 if (currentMode() == MathInset::TEXT_MODE)
1660 if (currentMode() == MathInset::TEXT_MODE) {
1661 // insert spaces in text mode,
1662 // but suppress direct insertion of two spaces in a row
1663 // the still allows typing '<space>a<space>' and deleting the 'a', but
1664 // it is better than nothing...
1665 if (!pos() != 0 || prevAtom()->getChar() != ' ')
1669 if (pos() != 0 && prevAtom()->asSpaceInset()) {
1670 prevAtom().nucleus()->asSpaceInset()->incSpace();
1675 // if are at the very end, leave the formula
1676 return pos() != lastpos();
1689 if (c == '{' || c == '}' || c == '#' || c == '&' || c == '$') {
1690 niceInsert(createMathInset(string(1, c)));
1695 niceInsert(MathAtom(new MathCommentInset));
1699 // try auto-correction
1700 //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1703 // no special circumstances, so insert the character without any fuss
1705 autocorrect() = true;
1710 void LCursor::lockToggle()
1712 if (pos() != lastpos()) {
1713 // toggle previous inset ...
1714 nextAtom().nucleus()->lock(!nextAtom()->lock());
1715 } else if (popLeft() && pos() != lastpos()) {
1716 // ... or enclosing inset if we are in the last inset position
1717 nextAtom().nucleus()->lock(!nextAtom()->lock());
1723 CursorSlice LCursor::normalAnchor()
1725 if (anchor_.size() < depth()) {
1727 lyxerr << "unusual Anchor size" << endl;
1729 //lyx::BOOST_ASSERT(Anchor_.size() >= cursor.depth());
1730 // use Anchor on the same level as Cursor
1731 CursorSlice normal = anchor_[current_];
1733 if (depth() < anchor_.size() && !(normal < xx())) {
1734 // anchor is behind cursor -> move anchor behind the inset
1743 DispatchResult dispatch(LCursor & cur, FuncRequest const & cmd)
1745 // mouse clicks are somewhat special
1747 switch (cmd.action) {
1748 case LFUN_MOUSE_PRESS:
1749 case LFUN_MOUSE_MOTION:
1750 case LFUN_MOUSE_RELEASE:
1751 case LFUN_MOUSE_DOUBLE: {
1752 CursorSlice & pos = cursor_.back();
1756 if (x < cmd.x && pos() != 0) {
1757 DispatchResult const res = prevAtom().nucleus()->dispatch(cmd);
1758 if (res.dispatched())
1761 if (x > cmd.x && pos() != lastpos()) {
1762 DispatchResult const res = inset()->dispatch(cmd);
1763 if (res.dispatched())
1774 void LCursor::handleFont(string const & font)
1776 lyxerr << "LCursor::handleFont: " << font << endl;
1780 safe = grabAndEraseSelection();
1783 if (lastpos() != 0) {
1784 // something left in the cell
1786 // cursor in first position
1788 } else if (pos() == lastpos()) {
1789 // cursor in last position
1792 // cursor in between. split cell
1793 MathArray::iterator bt = cell().begin();
1794 MathAtom at = createMathInset(font);
1795 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1796 cell().erase(bt, bt + pos());
1801 // nothing left in the cell
1809 void LCursor::releaseMathCursor()
1812 formula()->insetUnlock(bv());
1816 bool LCursor::inMathed() const
1822 bool LCursor::inTexted() const
1828 InsetBase * LCursor::nextInset()
1830 if (pos() == lastpos())
1833 return nextAtom().nucleus();
1834 return paragraph().isInset(pos()) ? paragraph().getInset(pos()) : 0;
1838 InsetBase * LCursor::prevInset()
1843 return prevAtom().nucleus();
1844 return paragraph().isInset(pos() - 1) ? paragraph().getInset(pos() - 1) : 0;
1848 InsetBase const * LCursor::prevInset() const
1853 return prevAtom().nucleus();
1854 return paragraph().isInset(pos() - 1) ? paragraph().getInset(pos() - 1) : 0;
1858 void LCursor::message(string const & msg) const
1860 bv().owner()->getLyXFunc().setMessage(msg);
1864 void LCursor::errorMessage(string const & msg) const
1866 bv().owner()->getLyXFunc().setErrorMessage(msg);
1870 string LCursor::selectionAsString(bool label) const
1876 Buffer const & buffer = *bv().buffer();
1878 // should be const ...
1879 ParagraphList::iterator startpit = text()->getPar(selBegin());
1880 ParagraphList::iterator endpit = text()->getPar(selEnd());
1881 size_t const startpos = selBegin().pos();
1882 size_t const endpos = selEnd().pos();
1884 if (startpit == endpit)
1885 return startpit->asString(buffer, startpos, endpos, label);
1887 // First paragraph in selection
1889 startpit->asString(buffer, startpos, startpit->size(), label) + "\n\n";
1891 // The paragraphs in between (if any)
1892 ParagraphList::iterator pit = startpit;
1893 for (++pit; pit != endpit; ++pit)
1894 result += pit->asString(buffer, 0, pit->size(), label) + "\n\n";
1896 // Last paragraph in selection
1897 result += endpit->asString(buffer, 0, endpos, label);
1907 string LCursor::currentState()
1910 std::ostringstream os;
1914 return text()->currentState(*this);
1918 // only used by the spellchecker
1919 void LCursor::replaceWord(string const & replacestring)
1921 LyXText * t = text();
1923 t->replaceSelectionWithString(*this, replacestring);
1924 t->setSelectionRange(*this, replacestring.length());
1926 // Go back so that replacement string is also spellchecked
1927 for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
1928 t->cursorLeft(*this, true);