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 BOOST_ASSERT(pos() <= lastpos());
84 BOOST_ASSERT(idx() <= lastidx());
85 BOOST_ASSERT(par() <= lastpar());
86 FuncRequest cmd = cmd0;
89 for (current_ = cursor_.size() - 1; current_ >= 1; --current_) {
90 // the inset's dispatch() is supposed to reset the update and
91 // val flags if necessary
92 inset()->dispatch(*this, cmd);
94 // "Mutate" the request for semi-handled requests that need
95 // additional handling in outer levels.
96 switch (disp_.val()) {
98 // the inset handled the event fully
99 current_ = cursor_.size() - 1;
100 return DispatchResult(true, true);
102 // the inset handled the event partially
103 cmd = FuncRequest(LFUN_FINISHED_LEFT);
106 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
109 cmd = FuncRequest(LFUN_FINISHED_UP);
112 cmd = FuncRequest(LFUN_FINISHED_DOWN);
115 //lyxerr << "not handled on level " << current_
116 // << " val: " << disp_.val() << endl;
120 BOOST_ASSERT(current_ == 0);
121 bv_->text()->dispatch(*this, cmd);
122 //lyxerr << " result: " << res.val() << endl;
123 current_ = cursor_.size() - 1;
128 void LCursor::push(InsetBase * inset)
130 lyxerr << "LCursor::push() inset: " << inset << endl;
131 cursor_.push_back(CursorSlice(inset));
132 anchor_.push_back(CursorSlice(inset));
138 void LCursor::pop(int depth)
140 while (int(cursor_.size()) > depth + 1)
142 lyxerr << "LCursor::pop() result: " << *this << endl;
148 BOOST_ASSERT(cursor_.size() >= 1);
151 current_ = cursor_.size() - 1;
155 void LCursor::pushLeft(InsetBase * p)
157 BOOST_ASSERT(!cursor_.empty());
158 //lyxerr << "Entering inset " << t << " left" << endl;
164 bool LCursor::popLeft()
166 BOOST_ASSERT(!cursor_.empty());
167 //lyxerr << "Leaving inset to the left" << endl;
170 inset()->notifyCursorLeaves(idx());
173 inset()->notifyCursorLeaves(idx());
179 bool LCursor::popRight()
181 BOOST_ASSERT(!cursor_.empty());
182 //lyxerr << "Leaving inset to the right" << endl;
185 inset()->notifyCursorLeaves(idx());
188 inset()->notifyCursorLeaves(idx());
195 CursorSlice & LCursor::current()
197 BOOST_ASSERT(!cursor_.empty());
198 //lyxerr << "accessing cursor slice " << current_
199 // << ": " << cursor_[current_] << endl;
200 return cursor_[current_];
204 CursorSlice const & LCursor::current() const
206 //lyxerr << "accessing cursor slice " << current_
207 // << ": " << cursor_[current_] << endl;
208 return cursor_[current_];
212 int LCursor::currentMode()
214 BOOST_ASSERT(!cursor_.empty());
215 for (int i = cursor_.size() - 1; i >= 1; --i) {
216 int res = cursor_[i].inset()->currentMode();
217 if (res != MathInset::UNDECIDED_MODE)
220 return MathInset::TEXT_MODE;
224 LyXText * LCursor::innerText() const
226 BOOST_ASSERT(!cursor_.empty());
227 if (cursor_.size() > 1) {
228 // go up until first non-0 text is hit
229 // (innermost text is 0 in mathed)
230 for (int i = cursor_.size() - 1; i >= 1; --i)
231 if (cursor_[i].text())
232 return cursor_[i].text();
238 CursorSlice const & LCursor::innerTextSlice() const
240 BOOST_ASSERT(!cursor_.empty());
241 if (cursor_.size() > 1) {
242 // go up until first non-0 text is hit
243 // (innermost text is 0 in mathed)
244 for (int i = cursor_.size() - 1; i >= 1; --i)
245 if (cursor_[i].text())
252 void LCursor::updatePos()
254 BOOST_ASSERT(!cursor_.empty());
255 if (cursor_.size() > 1)
256 cached_y_ = bv_->top_y() + cursor_.back().inset()->yo();
257 //cached_y_ = cursor_.back().inset()->yo();
261 void LCursor::getDim(int & asc, int & des) const
263 BOOST_ASSERT(!cursor_.empty());
265 BOOST_ASSERT(inset());
266 BOOST_ASSERT(inset()->asMathInset());
267 //inset()->asMathInset()->getCursorDim(asc, des);
271 Row const & row = textRow();
272 asc = row.baseline();
273 des = row.height() - asc;
278 void LCursor::getPos(int & x, int & y) const
280 BOOST_ASSERT(!cursor_.empty());
283 if (cursor_.size() == 1) {
284 x = bv_->text()->cursorX(cursor_.front());
285 y = bv_->text()->cursorY(cursor_.front());
288 lyxerr << "#### LCursor::getPos: " << *this << endl;
289 BOOST_ASSERT(inset());
291 inset()->getCursorPos(cursor_.back(), x, y);
292 // getCursorPos gives _screen_ coordinates. We need to add
293 // top_y to get document coordinates. This is hidden in cached_y_.
294 //y += cached_y_ - inset()->yo();
295 // The rest is non-obvious. The reason we have to have these
296 // extra computation is that the getCursorPos() calls rely
297 // on the inset's own knowledge of its screen position.
298 // If we scroll up or down in a big enough increment,
299 // inset->draw() is not called: this doesn't update
300 // inset.yo_, so getCursor() returns an old value.
303 //lyxerr << "#### LCursor::getPos: " << *this
304 // << " x: " << x << " y: " << y << endl;
308 void LCursor::paste(string const & data)
310 dispatch(FuncRequest(LFUN_PASTE, data));
314 InsetBase * LCursor::innerInsetOfType(int code) const
316 for (int i = cursor_.size() - 1; i >= 1; --i)
317 if (cursor_[i].inset_->lyxCode() == code)
318 return cursor_[i].inset_;
323 InsetTabular * LCursor::innerInsetTabular() const
325 return static_cast<InsetTabular *>(innerInsetOfType(InsetBase::TABULAR_CODE));
329 void LCursor::resetAnchor()
335 BufferView & LCursor::bv() const
341 MathAtom const & LCursor::prevAtom() const
343 BOOST_ASSERT(pos() > 0);
344 return cell()[pos() - 1];
348 MathAtom & LCursor::prevAtom()
350 BOOST_ASSERT(pos() > 0);
351 return cell()[pos() - 1];
355 MathAtom const & LCursor::nextAtom() const
357 BOOST_ASSERT(pos() < lastpos());
358 return cell()[pos()];
362 MathAtom & LCursor::nextAtom()
364 BOOST_ASSERT(pos() < lastpos());
365 return cell()[pos()];
369 bool LCursor::posLeft()
378 bool LCursor::posRight()
380 if (pos() == lastpos())
387 CursorSlice & LCursor::anchor()
389 return anchor_.back();
393 CursorSlice const & LCursor::anchor() const
395 return anchor_.back();
399 CursorSlice const & LCursor::selBegin() const
402 return cursor_.back();
403 return anchor() < cursor_.back() ? anchor() : cursor_.back();
407 CursorSlice & LCursor::selBegin()
410 return cursor_.back();
411 // can't use std::min as this returns a const ref
412 return anchor() < cursor_.back() ? anchor() : cursor_.back();
416 CursorSlice const & LCursor::selEnd() const
419 return cursor_.back();
420 return anchor() > cursor_.back() ? anchor() : cursor_.back();
424 CursorSlice & LCursor::selEnd()
427 return cursor_.back();
428 // can't use std::min as this returns a const ref
429 return anchor() > cursor_.back() ? anchor() : cursor_.back();
433 void LCursor::setSelection()
436 // a selection with no contents is not a selection
437 if (par() == anchor().par() && pos() == anchor().pos())
442 void LCursor::setSelection(CursorBase const & where, size_t n)
451 void LCursor::clearSelection()
460 int & LCursor::x_target()
466 int LCursor::x_target() const
472 void LCursor::clearTargetX()
478 LyXText * LCursor::text() const
480 return current_ ? current().text() : bv_->text();
484 Paragraph & LCursor::paragraph()
486 BOOST_ASSERT(inTexted());
487 return current_ ? current().paragraph() : *bv_->text()->getPar(par());
491 Paragraph const & LCursor::paragraph() const
493 BOOST_ASSERT(inTexted());
494 return current_ ? current().paragraph() : *bv_->text()->getPar(par());
498 Row & LCursor::textRow()
500 return *paragraph().getRow(pos());
504 Row const & LCursor::textRow() const
506 return *paragraph().getRow(pos());
510 LCursor::par_type LCursor::lastpar() const
512 return inMathed() ? 0 : text()->paragraphs().size() - 1;
516 LCursor::pos_type LCursor::lastpos() const
518 InsetBase * inset = current().inset();
519 return inset && inset->asMathInset() ? cell().size() : paragraph().size();
523 LCursor::row_type LCursor::crow() const
525 return paragraph().row(pos());
529 LCursor::row_type LCursor::lastcrow() const
531 return paragraph().rows.size();
535 LCursor::idx_type LCursor::lastidx() const
537 return current_ ? current().lastidx() : 0;
541 size_t LCursor::nargs() const
543 // assume 1x1 grid for 'plain text'
544 return current_ ? current().nargs() : 1;
548 size_t LCursor::ncols() const
550 // assume 1x1 grid for 'plain text'
551 return current_ ? current().ncols() : 1;
555 size_t LCursor::nrows() const
557 // assume 1x1 grid for 'plain text'
558 return current_ ? current().nrows() : 1;
562 LCursor::row_type LCursor::row() const
564 BOOST_ASSERT(current_ > 0);
565 return current().row();
569 LCursor::col_type LCursor::col() const
571 BOOST_ASSERT(current_ > 0);
572 return current().col();
576 MathArray const & LCursor::cell() const
578 BOOST_ASSERT(current_ > 0);
579 return current().cell();
583 MathArray & LCursor::cell()
585 BOOST_ASSERT(current_ > 0);
586 return current().cell();
590 void LCursor::info(std::ostream & os) const
592 for (int i = 1, n = depth(); i < n; ++i) {
593 cursor_[i].inset()->infoize(os);
597 prevInset()->infoize2(os);
598 // overwite old message
605 void region(CursorSlice const & i1, CursorSlice const & i2,
606 LCursor::row_type & r1, LCursor::row_type & r2,
607 LCursor::col_type & c1, LCursor::col_type & c2)
609 InsetBase * p = i1.inset();
610 c1 = p->col(i1.idx_);
611 c2 = p->col(i2.idx_);
614 r1 = p->row(i1.idx_);
615 r2 = p->row(i2.idx_);
623 string LCursor::grabSelection()
628 CursorSlice i1 = selBegin();
629 CursorSlice i2 = selEnd();
631 if (i1.idx_ == i2.idx_) {
632 if (i1.inset()->asMathInset()) {
633 MathArray::const_iterator it = i1.cell().begin();
634 return asString(MathArray(it + i1.pos_, it + i2.pos_));
636 return "unknown selection 1";
642 region(i1, i2, r1, r2, c1, c2);
645 if (i1.inset()->asMathInset()) {
646 for (row_type row = r1; row <= r2; ++row) {
649 for (col_type col = c1; col <= c2; ++col) {
652 data += asString(i1.asMathInset()->cell(i1.asMathInset()->index(row, col)));
656 data = "unknown selection 2";
662 void LCursor::eraseSelection()
664 //lyxerr << "LCursor::eraseSelection" << endl;
665 CursorSlice const & i1 = selBegin();
666 CursorSlice const & i2 = selEnd();
668 if (i1.inset()->asMathInset()) {
669 if (i1.idx_ == i2.idx_) {
670 i1.cell().erase(i1.pos_, i2.pos_);
672 MathInset * p = i1.asMathInset();
675 region(i1, i2, r1, r2, c1, c2);
676 for (row_type row = r1; row <= r2; ++row)
677 for (col_type col = c1; col <= c2; ++col)
678 p->cell(p->index(row, col)).clear();
682 lyxerr << "can't erase this selection 1" << endl;
684 //lyxerr << "LCursor::eraseSelection end" << endl;
688 string LCursor::grabAndEraseSelection()
692 string res = grabSelection();
699 void LCursor::selClear()
706 void LCursor::selCopy()
709 theCutBuffer.push(grabSelection());
712 //theCutBuffer.erase();
717 void LCursor::selCut()
719 theCutBuffer.push(grabAndEraseSelection());
723 void LCursor::selDel()
725 //lyxerr << "LCursor::selDel" << endl;
733 void LCursor::selPaste(size_t n)
736 if (n < theCutBuffer.size())
737 paste(theCutBuffer[n]);
743 void LCursor::selHandle(bool sel)
745 //lyxerr << "LCursor::selHandle" << endl;
746 if (sel == selection())
753 void LCursor::selClearOrDel()
755 //lyxerr << "LCursor::selClearOrDel" << endl;
756 if (lyxrc.auto_region_delete)
763 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
765 for (size_t i = 0, n = cur.cursor_.size(); i != n; ++i)
766 os << " " << cur.cursor_[i] << " | " << cur.anchor_[i] << "\n";
767 os << " current: " << cur.current_ << endl;
768 os << " selection: " << cur.selection_ << endl;
780 void increment(CursorBase & it)
782 CursorSlice & top = it.back();
783 MathArray & ar = top.asMathInset()->cell(top.idx_);
785 // move into the current inset if possible
786 // it is impossible for pos() == size()!
788 if (top.pos() != top.lastpos())
789 n = (ar.begin() + top.pos_)->nucleus();
790 if (n && n->isActive()) {
791 it.push_back(CursorSlice(n));
795 // otherwise move on one cell back if possible
796 if (top.pos() < top.lastpos()) {
797 // pos() == lastpos() is valid!
802 // otherwise try to move on one cell if possible
803 while (top.idx() < top.lastidx()) {
805 if (top.asMathInset()->validCell(top.idx_)) {
811 // otherwise leave array, move on one back
812 // this might yield pos() == size(), but that's a ok.
814 // it certainly invalidates top
819 CursorBase ibegin(InsetBase * p)
822 it.push_back(CursorSlice(p));
827 CursorBase iend(InsetBase * p)
830 it.push_back(CursorSlice(p));
831 CursorSlice & cur = it.back();
832 cur.idx() = cur.lastidx();
833 cur.pos() = cur.lastpos();
840 ///////////////////////////////////////////////////////////////////
842 // The part below is the non-integrated rest of the original math
843 // cursor. This should be either generalized for texted or moved
844 // back to the math insets.
846 ///////////////////////////////////////////////////////////////////
848 #include "mathed/math_braceinset.h"
849 #include "mathed/math_charinset.h"
850 #include "mathed/math_commentinset.h"
851 #include "mathed/math_factory.h"
852 #include "mathed/math_gridinset.h"
853 #include "mathed/math_macroarg.h"
854 #include "mathed/math_macrotemplate.h"
855 #include "mathed/math_mathmlstream.h"
856 #include "mathed/math_scriptinset.h"
857 #include "mathed/math_spaceinset.h"
858 #include "mathed/math_support.h"
859 #include "mathed/math_unknowninset.h"
861 //#define FILEDEBUG 1
864 bool LCursor::isInside(InsetBase const * p)
866 for (unsigned i = 0; i < depth(); ++i)
867 if (cursor_[i].inset() == p)
873 bool LCursor::openable(MathAtom const & t)
884 // we can't move into anything new during selection
885 if (depth() == anchor_.size())
887 if (!ptr_cmp(t.nucleus(), anchor_[depth()].inset()))
894 bool LCursor::inNucleus()
896 return inset()->asMathInset()->asScriptInset() && idx() == 2;
902 autocorrect() = false;
909 if (pos() != 0 && openable(prevAtom())) {
911 push(nextAtom().nucleus());
912 inset()->idxLast(*this);
916 return posLeft() || idxLeft() || popLeft() || selection();
920 bool LCursor::right()
922 autocorrect() = false;
929 if (pos() != lastpos() && openable(nextAtom())) {
930 pushLeft(nextAtom().nucleus());
931 inset()->idxFirst(*this);
935 return posRight() || idxRight() || popRight() || selection();
939 bool positionable(CursorBase const & cursor, CursorBase const & anchor)
941 // avoid deeper nested insets when selecting
942 if (cursor.size() > anchor.size())
945 // anchor might be deeper, should have same path then
946 for (size_t i = 0; i < cursor.size(); ++i)
947 if (cursor[i].inset() != anchor[i].inset())
950 // position should be ok.
955 void LCursor::setScreenPos(int x, int y)
957 bool res = bruteFind(x, y, formula()->xlow(), formula()->xhigh(),
958 formula()->ylow(), formula()->yhigh());
960 // this can happen on creation of "math-display"
971 autocorrect() = false;
973 if (!inset()->idxHome(*this))
982 autocorrect() = false;
984 if (!inset()->idxEnd(*this))
991 void LCursor::plainErase()
997 void LCursor::markInsert()
999 cell().insert(pos(), MathAtom(new MathCharInset(0)));
1003 void LCursor::markErase()
1005 cell().erase(pos());
1009 void LCursor::plainInsert(MathAtom const & t)
1011 cell().insert(pos(), t);
1016 void LCursor::insert(string const & str)
1018 lyxerr << "LCursor::insert str '" << str << "'" << endl;
1021 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
1022 plainInsert(MathAtom(new MathCharInset(*it)));
1031 void LCursor::insert(char c)
1033 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
1035 plainInsert(MathAtom(new MathCharInset(c)));
1039 void LCursor::insert(MathAtom const & t)
1041 //lyxerr << "LCursor::insert MathAtom: " << endl;
1048 void LCursor::insert(InsetBase * inset)
1051 insert(MathAtom(inset));
1053 text()->insertInset(*this, inset);
1057 void LCursor::niceInsert(string const & t)
1068 void LCursor::niceInsert(MathAtom const & t)
1071 string safe = grabAndEraseSelection();
1073 // enter the new inset and move the contents of the selection if possible
1074 if (t->isActive()) {
1076 // be careful here: don't use 'pushLeft(t)' as this we need to
1077 // push the clone, not the original
1078 pushLeft(nextAtom().nucleus());
1084 void LCursor::insert(MathArray const & ar)
1089 cell().insert(pos(), ar);
1094 bool LCursor::backspace()
1096 autocorrect() = false;
1104 if (inset()->nargs() == 1 && depth() == 1 && lastpos() == 0)
1110 if (inMacroMode()) {
1111 MathUnknownInset * p = activeMacro();
1112 if (p->name().size() > 1) {
1113 p->setName(p->name().substr(0, p->name().size() - 1));
1118 if (pos() != 0 && prevAtom()->nargs() > 0) {
1119 // let's require two backspaces for 'big stuff' and
1120 // highlight on the first
1131 bool LCursor::erase()
1133 autocorrect() = false;
1142 // delete empty cells if possible
1143 if (pos() == lastpos() && inset()->idxDelete(idx()))
1146 // special behaviour when in last position of cell
1147 if (pos() == lastpos()) {
1148 bool one_cell = inset()->nargs() == 1;
1149 if (one_cell && depth() == 1 && lastpos() == 0)
1155 inset()->idxGlue(idx());
1159 if (pos() != lastpos() && inset()->nargs() > 0) {
1173 CursorBase save = cursor_;
1177 autocorrect() = false;
1182 bool LCursor::down()
1185 CursorBase save = cursor_;
1186 if (goUpDown(false))
1189 autocorrect() = false;
1194 void LCursor::macroModeClose()
1198 MathUnknownInset * p = activeMacro();
1200 string s = p->name();
1202 cell().erase(pos());
1204 // do nothing if the macro name is empty
1208 string const name = s.substr(1);
1210 // prevent entering of recursive macros
1211 if (formula()->lyxCode() == InsetOld::MATHMACRO_CODE
1212 && formula()->getInsetName() == name)
1213 lyxerr << "can't enter recursive macro" << endl;
1215 niceInsert(createMathInset(name));
1219 string LCursor::macroName()
1221 return inMacroMode() ? activeMacro()->name() : string();
1225 void LCursor::handleNest(MathAtom const & a, int c)
1227 //lyxerr << "LCursor::handleNest: " << c << endl;
1229 asArray(grabAndEraseSelection(), t.nucleus()->cell(c));
1232 pushLeft(nextAtom().nucleus());
1236 int LCursor::targetX() const
1238 if (x_target() != -1)
1247 MathHullInset * LCursor::formula() const
1249 for (int i = cursor_.size() - 1; i >= 1; --i) {
1250 MathInset * inset = cursor_[i].inset()->asMathInset();
1251 if (inset && inset->asHullInset())
1252 return static_cast<MathHullInset *>(inset);
1258 void LCursor::adjust(pos_type from, int diff)
1262 if (anchor().pos_ > from)
1263 anchor().pos_ += diff;
1264 // just to be on the safe side
1265 // theoretically unecessary
1270 bool LCursor::inMacroMode() const
1274 MathUnknownInset const * p = prevAtom()->asUnknownInset();
1275 return p && !p->final();
1279 MathUnknownInset * LCursor::activeMacro()
1281 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1285 bool LCursor::inMacroArgMode() const
1287 return pos() > 0 && prevAtom()->getChar() == '#';
1291 MathGridInset * LCursor::enclosingGrid(idx_type & idx) const
1293 for (MathInset::difference_type i = depth() - 1; i >= 0; --i) {
1294 MathInset * m = cursor_[i].inset()->asMathInset();
1297 MathGridInset * p = m->asGridInset();
1299 idx = cursor_[i].idx_;
1307 void LCursor::pullArg()
1310 MathArray ar = cell();
1311 if (popLeft() && inMathed()) {
1313 cell().insert(pos(), ar);
1316 //formula()->mutateToText();
1321 void LCursor::touch()
1325 CursorBase::const_iterator it = cursor_.begin();
1326 CursorBase::const_iterator et = cursor_.end();
1327 for ( ; it != et; ++it)
1333 void LCursor::normalize()
1335 if (idx() >= nargs()) {
1336 lyxerr << "this should not really happen - 1: "
1337 << idx() << ' ' << nargs()
1338 << " in: " << inset() << endl;
1340 idx() = min(idx(), lastidx());
1342 if (pos() > lastpos()) {
1343 lyxerr << "this should not really happen - 2: "
1344 << pos() << ' ' << lastpos() << " in idx: " << idx()
1346 WriteStream wi(lyxerr, false, true);
1347 inset()->asMathInset()->write(wi);
1350 pos() = min(pos(), lastpos());
1354 char LCursor::valign()
1357 MathGridInset * p = enclosingGrid(idx);
1358 return p ? p->valign() : '\0';
1362 char LCursor::halign()
1365 MathGridInset * p = enclosingGrid(idx);
1366 return p ? p->halign(idx % p->ncols()) : '\0';
1370 bool LCursor::goUpDown(bool up)
1372 // Be warned: The 'logic' implemented in this function is highly
1373 // fragile. A distance of one pixel or a '<' vs '<=' _really
1374 // matters. So fiddle around with it only if you think you know
1375 // what you are doing!
1380 // check if we had something else in mind, if not, this is the future goal
1381 if (x_target() == -1)
1386 // try neigbouring script insets
1390 MathScriptInset const * p = prevAtom()->asScriptInset();
1391 if (p && p->has(up)) {
1394 idx() = up; // the superscript has index 1
1396 //lyxerr << "updown: handled by scriptinset to the left" << endl;
1402 if (pos() != lastpos()) {
1403 MathScriptInset const * p = nextAtom()->asScriptInset();
1404 if (p && p->has(up)) {
1408 //lyxerr << "updown: handled by scriptinset to the right" << endl;
1414 // try current cell for e.g. text insets
1415 if (inset()->idxUpDown2(*this, up))
1418 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1423 //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1424 // lyxerr << "updown: handled by brute find in the same cell" << endl;
1428 // try to find an inset that knows better then we
1430 //lyxerr << "updown: We are in " << inset() << " idx: " << idx() << endl;
1432 if (inset()->idxUpDown(*this, up)) {
1433 // try to find best position within this inset
1439 // no such inset found, just take something "above"
1440 //lyxerr << "updown: handled by strange case" << endl;
1446 up ? formula()->ylow() : yo + 4,
1447 up ? yo - 4 : formula()->yhigh()
1451 // any improvement so far?
1454 if (up ? ynew < yo : ynew > yo)
1460 bool LCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1462 CursorBase best_cursor;
1463 double best_dist = 1e10;
1465 CursorBase it = ibegin(formula());
1466 CursorBase et = iend(formula());
1468 // avoid invalid nesting when selecting
1469 if (!selection() || positionable(it, anchor_)) {
1471 CursorSlice & cur = it.back();
1472 cur.inset()->getCursorPos(cur, xo, yo);
1473 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1474 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1475 //lyxerr << "x: " << x << " y: " << y << " d: " << endl;
1476 // '<=' in order to take the last possible position
1477 // this is important for clicking behind \sum in e.g. '\sum_i a'
1478 if (d <= best_dist) {
1490 if (best_dist < 1e10)
1491 cursor_ = best_cursor;
1492 return best_dist < 1e10;
1496 void LCursor::bruteFind2(int x, int y)
1498 double best_dist = 1e10;
1500 CursorBase it = cursor_;
1501 it.back().pos() = 0;
1502 CursorBase et = cursor_;
1503 et.back().pos() = et.back().asMathInset()->cell(et.back().idx_).size();
1504 for (int i = 0; ; ++i) {
1506 CursorSlice & cur = it.back();
1507 cur.inset()->getCursorPos(cur, xo, yo);
1508 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1509 // '<=' in order to take the last possible position
1510 // this is important for clicking behind \sum in e.g. '\sum_i a'
1511 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
1512 if (d <= best_dist) {
1523 bool LCursor::idxLineLast()
1525 idx() -= idx() % ncols();
1526 idx() += ncols() - 1;
1532 bool LCursor::idxLeft()
1534 return inset()->idxLeft(*this);
1538 bool LCursor::idxRight()
1540 return inset()->idxRight(*this);
1544 bool LCursor::script(bool up)
1546 // Hack to get \\^ and \\_ working
1547 lyxerr << "handling script: up: " << up << endl;
1548 if (inMacroMode() && macroName() == "\\") {
1550 niceInsert(createMathInset("mathcircumflex"));
1557 string safe = grabAndEraseSelection();
1559 // we are in a nucleus of a script inset, move to _our_ script
1560 inset()->asMathInset()->asScriptInset()->ensure(up);
1563 } else if (pos() != 0 && prevAtom()->asScriptInset()) {
1565 nextAtom().nucleus()->asScriptInset()->ensure(up);
1569 } else if (pos() != 0) {
1571 cell()[pos()] = MathAtom(new MathScriptInset(nextAtom(), up));
1576 plainInsert(MathAtom(new MathScriptInset(up)));
1578 nextAtom().nucleus()->asScriptInset()->ensure(up);
1588 bool LCursor::interpret(char c)
1590 //lyxerr << "interpret 2: '" << c << "'" << endl;
1592 if (inMacroArgMode()) {
1598 MathMacroTemplate const * p = formula()->asMacroTemplate();
1599 if (p && 1 <= n && n <= p->numargs())
1600 insert(MathAtom(new MathMacroArgument(c - '0')));
1602 insert(createMathInset("#"));
1603 interpret(c); // try again
1610 if (inMacroMode()) {
1611 string name = macroName();
1612 //lyxerr << "interpret name: '" << name << "'" << endl;
1615 activeMacro()->setName(activeMacro()->name() + c);
1619 // handle 'special char' macros
1624 if (currentMode() == MathInset::TEXT_MODE)
1625 niceInsert(createMathInset("textbackslash"));
1627 niceInsert(createMathInset("backslash"));
1628 } else if (c == '{') {
1629 niceInsert(MathAtom(new MathBraceInset));
1631 niceInsert(createMathInset(string(1, c)));
1636 // leave macro mode and try again if necessary
1639 niceInsert(MathAtom(new MathBraceInset));
1645 // This is annoying as one has to press <space> far too often.
1649 // leave autocorrect mode if necessary
1650 if (autocorrect() && c == ' ') {
1651 autocorrect() = false;
1656 // just clear selection on pressing the space bar
1657 if (selection() && c == ' ') {
1658 selection() = false;
1665 //lyxerr << "starting with macro" << endl;
1666 insert(MathAtom(new MathUnknownInset("\\", false)));
1671 if (currentMode() == MathInset::TEXT_MODE)
1677 if (currentMode() == MathInset::TEXT_MODE) {
1678 // insert spaces in text mode,
1679 // but suppress direct insertion of two spaces in a row
1680 // the still allows typing '<space>a<space>' and deleting the 'a', but
1681 // it is better than nothing...
1682 if (!pos() != 0 || prevAtom()->getChar() != ' ')
1686 if (pos() != 0 && prevAtom()->asSpaceInset()) {
1687 prevAtom().nucleus()->asSpaceInset()->incSpace();
1692 // if are at the very end, leave the formula
1693 return pos() != lastpos();
1706 if (c == '{' || c == '}' || c == '#' || c == '&' || c == '$') {
1707 niceInsert(createMathInset(string(1, c)));
1712 niceInsert(MathAtom(new MathCommentInset));
1716 // try auto-correction
1717 //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1720 // no special circumstances, so insert the character without any fuss
1722 autocorrect() = true;
1727 void LCursor::lockToggle()
1729 if (pos() != lastpos()) {
1730 // toggle previous inset ...
1731 nextAtom().nucleus()->lock(!nextAtom()->lock());
1732 } else if (popLeft() && pos() != lastpos()) {
1733 // ... or enclosing inset if we are in the last inset position
1734 nextAtom().nucleus()->lock(!nextAtom()->lock());
1740 CursorSlice LCursor::normalAnchor()
1742 if (anchor_.size() < depth()) {
1744 lyxerr << "unusual Anchor size" << endl;
1746 //lyx::BOOST_ASSERT(Anchor_.size() >= cursor.depth());
1747 // use Anchor on the same level as Cursor
1748 CursorSlice normal = anchor_[current_];
1750 if (depth() < anchor_.size() && !(normal < xx())) {
1751 // anchor is behind cursor -> move anchor behind the inset
1760 DispatchResult dispatch(LCursor & cur, FuncRequest const & cmd)
1762 // mouse clicks are somewhat special
1764 switch (cmd.action) {
1765 case LFUN_MOUSE_PRESS:
1766 case LFUN_MOUSE_MOTION:
1767 case LFUN_MOUSE_RELEASE:
1768 case LFUN_MOUSE_DOUBLE: {
1769 CursorSlice & pos = cursor_.back();
1773 if (x < cmd.x && pos() != 0) {
1774 DispatchResult const res = prevAtom().nucleus()->dispatch(cmd);
1775 if (res.dispatched())
1778 if (x > cmd.x && pos() != lastpos()) {
1779 DispatchResult const res = inset()->dispatch(cmd);
1780 if (res.dispatched())
1791 void LCursor::handleFont(string const & font)
1793 lyxerr << "LCursor::handleFont: " << font << endl;
1797 safe = grabAndEraseSelection();
1800 if (lastpos() != 0) {
1801 // something left in the cell
1803 // cursor in first position
1805 } else if (pos() == lastpos()) {
1806 // cursor in last position
1809 // cursor in between. split cell
1810 MathArray::iterator bt = cell().begin();
1811 MathAtom at = createMathInset(font);
1812 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1813 cell().erase(bt, bt + pos());
1818 // nothing left in the cell
1826 bool LCursor::inMathed() const
1832 bool LCursor::inTexted() const
1838 InsetBase * LCursor::nextInset()
1840 if (pos() == lastpos())
1843 return nextAtom().nucleus();
1844 return paragraph().isInset(pos()) ? paragraph().getInset(pos()) : 0;
1848 InsetBase * LCursor::prevInset()
1853 return prevAtom().nucleus();
1854 return paragraph().isInset(pos() - 1) ? paragraph().getInset(pos() - 1) : 0;
1858 InsetBase const * LCursor::prevInset() const
1863 return prevAtom().nucleus();
1864 return paragraph().isInset(pos() - 1) ? paragraph().getInset(pos() - 1) : 0;
1868 void LCursor::message(string const & msg) const
1870 bv().owner()->getLyXFunc().setMessage(msg);
1874 void LCursor::errorMessage(string const & msg) const
1876 bv().owner()->getLyXFunc().setErrorMessage(msg);
1880 string LCursor::selectionAsString(bool label) const
1886 Buffer const & buffer = *bv().buffer();
1888 // should be const ...
1889 ParagraphList::iterator startpit = text()->getPar(selBegin());
1890 ParagraphList::iterator endpit = text()->getPar(selEnd());
1891 size_t const startpos = selBegin().pos();
1892 size_t const endpos = selEnd().pos();
1894 if (startpit == endpit)
1895 return startpit->asString(buffer, startpos, endpos, label);
1897 // First paragraph in selection
1899 startpit->asString(buffer, startpos, startpit->size(), label) + "\n\n";
1901 // The paragraphs in between (if any)
1902 ParagraphList::iterator pit = startpit;
1903 for (++pit; pit != endpit; ++pit)
1904 result += pit->asString(buffer, 0, pit->size(), label) + "\n\n";
1906 // Last paragraph in selection
1907 result += endpit->asString(buffer, 0, endpos, label);
1917 string LCursor::currentState()
1920 std::ostringstream os;
1924 return text() ? text()->currentState(*this) : string();
1928 // only used by the spellchecker
1929 void LCursor::replaceWord(string const & replacestring)
1931 LyXText * t = text();
1934 t->replaceSelectionWithString(*this, replacestring);
1935 t->setSelectionRange(*this, replacestring.length());
1937 // Go back so that replacement string is also spellchecked
1938 for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
1939 t->cursorLeft(*this, true);
1943 void LCursor::update()
1949 string LCursor::getPossibleLabel()
1951 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1955 void LCursor::notdispatched()
1957 disp_.dispatched(false);
1961 void LCursor::dispatched(dispatch_result_t res)
1967 void LCursor::noupdate()
1969 disp_.update(false);