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 bool LCursor::getStatus(FuncRequest const & cmd, FuncStatus & status)
130 lyxerr << "\nLCursor::getStatus: cmd: " << cmd << endl << *this << endl;
131 BOOST_ASSERT(pos() <= lastpos());
132 BOOST_ASSERT(idx() <= lastidx());
133 BOOST_ASSERT(par() <= lastpar());
134 for (current_ = cursor_.size() - 1; current_ >= 1; --current_) {
135 // the inset's getStatus() will return 'true' if it made
136 // a definitive decision on whether it want to handle the
137 // request or not. The result of this decision is put into
138 // the 'status' parameter.
139 bool const res = inset()->getStatus(*this, cmd, status);
141 current_ = cursor_.size() - 1;
145 BOOST_ASSERT(current_ == 0);
146 bool const res = bv_->text()->getStatus(*this, cmd, status);
147 current_ = cursor_.size() - 1;
152 void LCursor::push(InsetBase * inset)
154 lyxerr << "LCursor::push() inset: " << inset << endl;
155 cursor_.push_back(CursorSlice(inset));
156 anchor_.push_back(CursorSlice(inset));
162 void LCursor::pop(int depth)
164 while (int(cursor_.size()) > depth + 1)
166 lyxerr << "LCursor::pop() result: " << *this << endl;
172 BOOST_ASSERT(cursor_.size() >= 1);
175 current_ = cursor_.size() - 1;
179 void LCursor::pushLeft(InsetBase * p)
181 BOOST_ASSERT(!cursor_.empty());
182 //lyxerr << "Entering inset " << t << " left" << endl;
188 bool LCursor::popLeft()
190 BOOST_ASSERT(!cursor_.empty());
191 //lyxerr << "Leaving inset to the left" << endl;
194 inset()->notifyCursorLeaves(idx());
197 inset()->notifyCursorLeaves(idx());
203 bool LCursor::popRight()
205 BOOST_ASSERT(!cursor_.empty());
206 //lyxerr << "Leaving inset to the right" << endl;
209 inset()->notifyCursorLeaves(idx());
212 inset()->notifyCursorLeaves(idx());
219 CursorSlice & LCursor::current()
221 BOOST_ASSERT(!cursor_.empty());
222 //lyxerr << "accessing cursor slice " << current_
223 // << ": " << cursor_[current_] << endl;
224 return cursor_[current_];
228 CursorSlice const & LCursor::current() const
230 //lyxerr << "accessing cursor slice " << current_
231 // << ": " << cursor_[current_] << endl;
232 return cursor_[current_];
236 int LCursor::currentMode()
238 BOOST_ASSERT(!cursor_.empty());
239 for (int i = cursor_.size() - 1; i >= 1; --i) {
240 int res = cursor_[i].inset()->currentMode();
241 if (res != MathInset::UNDECIDED_MODE)
244 return MathInset::TEXT_MODE;
248 LyXText * LCursor::innerText() const
250 BOOST_ASSERT(!cursor_.empty());
251 if (cursor_.size() > 1) {
252 // go up until first non-0 text is hit
253 // (innermost text is 0 in mathed)
254 for (int i = cursor_.size() - 1; i >= 1; --i)
255 if (cursor_[i].text())
256 return cursor_[i].text();
262 CursorSlice const & LCursor::innerTextSlice() const
264 BOOST_ASSERT(!cursor_.empty());
265 if (cursor_.size() > 1) {
266 // go up until first non-0 text is hit
267 // (innermost text is 0 in mathed)
268 for (int i = cursor_.size() - 1; i >= 1; --i)
269 if (cursor_[i].text())
276 void LCursor::updatePos()
278 BOOST_ASSERT(!cursor_.empty());
279 if (cursor_.size() > 1)
280 cached_y_ = bv_->top_y() + cursor_.back().inset()->yo();
281 //cached_y_ = cursor_.back().inset()->yo();
285 void LCursor::getDim(int & asc, int & des) const
287 BOOST_ASSERT(!cursor_.empty());
289 BOOST_ASSERT(inset());
290 BOOST_ASSERT(inset()->asMathInset());
291 //inset()->asMathInset()->getCursorDim(asc, des);
295 Row const & row = textRow();
296 asc = row.baseline();
297 des = row.height() - asc;
302 void LCursor::getPos(int & x, int & y) const
304 BOOST_ASSERT(!cursor_.empty());
307 if (cursor_.size() == 1) {
308 x = bv_->text()->cursorX(cursor_.front());
309 y = bv_->text()->cursorY(cursor_.front());
312 lyxerr << "#### LCursor::getPos: " << *this << endl;
313 BOOST_ASSERT(inset());
315 inset()->getCursorPos(cursor_.back(), x, y);
316 // getCursorPos gives _screen_ coordinates. We need to add
317 // top_y to get document coordinates. This is hidden in cached_y_.
318 //y += cached_y_ - inset()->yo();
319 // The rest is non-obvious. The reason we have to have these
320 // extra computation is that the getCursorPos() calls rely
321 // on the inset's own knowledge of its screen position.
322 // If we scroll up or down in a big enough increment,
323 // inset->draw() is not called: this doesn't update
324 // inset.yo_, so getCursor() returns an old value.
327 //lyxerr << "#### LCursor::getPos: " << *this
328 // << " x: " << x << " y: " << y << endl;
332 void LCursor::paste(string const & data)
334 dispatch(FuncRequest(LFUN_PASTE, data));
338 InsetBase * LCursor::innerInsetOfType(int code) const
340 for (int i = cursor_.size() - 1; i >= 1; --i)
341 if (cursor_[i].inset_->lyxCode() == code)
342 return cursor_[i].inset_;
347 InsetTabular * LCursor::innerInsetTabular() const
349 return static_cast<InsetTabular *>(innerInsetOfType(InsetBase::TABULAR_CODE));
353 void LCursor::resetAnchor()
359 BufferView & LCursor::bv() const
365 MathAtom const & LCursor::prevAtom() const
367 BOOST_ASSERT(pos() > 0);
368 return cell()[pos() - 1];
372 MathAtom & LCursor::prevAtom()
374 BOOST_ASSERT(pos() > 0);
375 return cell()[pos() - 1];
379 MathAtom const & LCursor::nextAtom() const
381 BOOST_ASSERT(pos() < lastpos());
382 return cell()[pos()];
386 MathAtom & LCursor::nextAtom()
388 BOOST_ASSERT(pos() < lastpos());
389 return cell()[pos()];
393 bool LCursor::posLeft()
402 bool LCursor::posRight()
404 if (pos() == lastpos())
411 CursorSlice & LCursor::anchor()
413 return anchor_.back();
417 CursorSlice const & LCursor::anchor() const
419 return anchor_.back();
423 CursorSlice const & LCursor::selBegin() const
426 return cursor_.back();
427 return anchor() < cursor_.back() ? anchor() : cursor_.back();
431 CursorSlice & LCursor::selBegin()
434 return cursor_.back();
435 // can't use std::min as this returns a const ref
436 return anchor() < cursor_.back() ? anchor() : cursor_.back();
440 CursorSlice const & LCursor::selEnd() const
443 return cursor_.back();
444 return anchor() > cursor_.back() ? anchor() : cursor_.back();
448 CursorSlice & LCursor::selEnd()
451 return cursor_.back();
452 // can't use std::min as this returns a const ref
453 return anchor() > cursor_.back() ? anchor() : cursor_.back();
457 void LCursor::setSelection()
460 // a selection with no contents is not a selection
461 if (par() == anchor().par() && pos() == anchor().pos())
466 void LCursor::setSelection(CursorBase const & where, size_t n)
475 void LCursor::clearSelection()
484 int & LCursor::x_target()
490 int LCursor::x_target() const
496 void LCursor::clearTargetX()
502 LyXText * LCursor::text() const
504 return current_ ? current().text() : bv_->text();
508 Paragraph & LCursor::paragraph()
510 BOOST_ASSERT(inTexted());
511 return current_ ? current().paragraph() : *bv_->text()->getPar(par());
515 Paragraph const & LCursor::paragraph() const
517 BOOST_ASSERT(inTexted());
518 return current_ ? current().paragraph() : *bv_->text()->getPar(par());
522 Row & LCursor::textRow()
524 return *paragraph().getRow(pos());
528 Row const & LCursor::textRow() const
530 return *paragraph().getRow(pos());
534 LCursor::par_type LCursor::lastpar() const
536 return inMathed() ? 0 : text()->paragraphs().size() - 1;
540 LCursor::pos_type LCursor::lastpos() const
542 InsetBase * inset = current().inset();
543 return inset && inset->asMathInset() ? cell().size() : paragraph().size();
547 LCursor::row_type LCursor::crow() const
549 return paragraph().row(pos());
553 LCursor::row_type LCursor::lastcrow() const
555 return paragraph().rows.size();
559 LCursor::idx_type LCursor::lastidx() const
561 return current_ ? current().lastidx() : 0;
565 size_t LCursor::nargs() const
567 // assume 1x1 grid for 'plain text'
568 return current_ ? current().nargs() : 1;
572 size_t LCursor::ncols() const
574 // assume 1x1 grid for 'plain text'
575 return current_ ? current().ncols() : 1;
579 size_t LCursor::nrows() const
581 // assume 1x1 grid for 'plain text'
582 return current_ ? current().nrows() : 1;
586 LCursor::row_type LCursor::row() const
588 BOOST_ASSERT(current_ > 0);
589 return current().row();
593 LCursor::col_type LCursor::col() const
595 BOOST_ASSERT(current_ > 0);
596 return current().col();
600 MathArray const & LCursor::cell() const
602 BOOST_ASSERT(current_ > 0);
603 return current().cell();
607 MathArray & LCursor::cell()
609 BOOST_ASSERT(current_ > 0);
610 return current().cell();
614 void LCursor::info(std::ostream & os) const
616 for (int i = 1, n = depth(); i < n; ++i) {
617 cursor_[i].inset()->infoize(os);
621 prevInset()->infoize2(os);
622 // overwite old message
629 void region(CursorSlice const & i1, CursorSlice const & i2,
630 LCursor::row_type & r1, LCursor::row_type & r2,
631 LCursor::col_type & c1, LCursor::col_type & c2)
633 InsetBase * p = i1.inset();
634 c1 = p->col(i1.idx_);
635 c2 = p->col(i2.idx_);
638 r1 = p->row(i1.idx_);
639 r2 = p->row(i2.idx_);
647 string LCursor::grabSelection()
652 CursorSlice i1 = selBegin();
653 CursorSlice i2 = selEnd();
655 if (i1.idx_ == i2.idx_) {
656 if (i1.inset()->asMathInset()) {
657 MathArray::const_iterator it = i1.cell().begin();
658 return asString(MathArray(it + i1.pos_, it + i2.pos_));
660 return "unknown selection 1";
666 region(i1, i2, r1, r2, c1, c2);
669 if (i1.inset()->asMathInset()) {
670 for (row_type row = r1; row <= r2; ++row) {
673 for (col_type col = c1; col <= c2; ++col) {
676 data += asString(i1.asMathInset()->cell(i1.asMathInset()->index(row, col)));
680 data = "unknown selection 2";
686 void LCursor::eraseSelection()
688 //lyxerr << "LCursor::eraseSelection" << endl;
689 CursorSlice const & i1 = selBegin();
690 CursorSlice const & i2 = selEnd();
692 if (i1.inset()->asMathInset()) {
693 if (i1.idx_ == i2.idx_) {
694 i1.cell().erase(i1.pos_, i2.pos_);
696 MathInset * p = i1.asMathInset();
699 region(i1, i2, r1, r2, c1, c2);
700 for (row_type row = r1; row <= r2; ++row)
701 for (col_type col = c1; col <= c2; ++col)
702 p->cell(p->index(row, col)).clear();
706 lyxerr << "can't erase this selection 1" << endl;
708 //lyxerr << "LCursor::eraseSelection end" << endl;
712 string LCursor::grabAndEraseSelection()
716 string res = grabSelection();
723 void LCursor::selClear()
730 void LCursor::selCopy()
733 theCutBuffer.push(grabSelection());
736 //theCutBuffer.erase();
741 void LCursor::selCut()
743 theCutBuffer.push(grabAndEraseSelection());
747 void LCursor::selDel()
749 //lyxerr << "LCursor::selDel" << endl;
757 void LCursor::selPaste(size_t n)
760 if (n < theCutBuffer.size())
761 paste(theCutBuffer[n]);
767 void LCursor::selHandle(bool sel)
769 //lyxerr << "LCursor::selHandle" << endl;
770 if (sel == selection())
777 void LCursor::selClearOrDel()
779 //lyxerr << "LCursor::selClearOrDel" << endl;
780 if (lyxrc.auto_region_delete)
787 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
789 for (size_t i = 0, n = cur.cursor_.size(); i != n; ++i)
790 os << " " << cur.cursor_[i] << " | " << cur.anchor_[i] << "\n";
791 os << " current: " << cur.current_ << endl;
792 os << " selection: " << cur.selection_ << endl;
804 void increment(CursorBase & it)
806 CursorSlice & top = it.back();
807 MathArray & ar = top.asMathInset()->cell(top.idx_);
809 // move into the current inset if possible
810 // it is impossible for pos() == size()!
812 if (top.pos() != top.lastpos())
813 n = (ar.begin() + top.pos_)->nucleus();
814 if (n && n->isActive()) {
815 it.push_back(CursorSlice(n));
819 // otherwise move on one cell back if possible
820 if (top.pos() < top.lastpos()) {
821 // pos() == lastpos() is valid!
826 // otherwise try to move on one cell if possible
827 while (top.idx() < top.lastidx()) {
829 if (top.asMathInset()->validCell(top.idx_)) {
835 // otherwise leave array, move on one back
836 // this might yield pos() == size(), but that's a ok.
838 // it certainly invalidates top
843 CursorBase ibegin(InsetBase * p)
846 it.push_back(CursorSlice(p));
851 CursorBase iend(InsetBase * p)
854 it.push_back(CursorSlice(p));
855 CursorSlice & cur = it.back();
856 cur.idx() = cur.lastidx();
857 cur.pos() = cur.lastpos();
864 ///////////////////////////////////////////////////////////////////
866 // The part below is the non-integrated rest of the original math
867 // cursor. This should be either generalized for texted or moved
868 // back to the math insets.
870 ///////////////////////////////////////////////////////////////////
872 #include "mathed/math_braceinset.h"
873 #include "mathed/math_charinset.h"
874 #include "mathed/math_commentinset.h"
875 #include "mathed/math_factory.h"
876 #include "mathed/math_gridinset.h"
877 #include "mathed/math_macroarg.h"
878 #include "mathed/math_macrotemplate.h"
879 #include "mathed/math_mathmlstream.h"
880 #include "mathed/math_scriptinset.h"
881 #include "mathed/math_spaceinset.h"
882 #include "mathed/math_support.h"
883 #include "mathed/math_unknowninset.h"
885 //#define FILEDEBUG 1
888 bool LCursor::isInside(InsetBase const * p)
890 for (unsigned i = 0; i < depth(); ++i)
891 if (cursor_[i].inset() == p)
897 bool LCursor::openable(MathAtom const & t)
908 // we can't move into anything new during selection
909 if (depth() == anchor_.size())
911 if (!ptr_cmp(t.nucleus(), anchor_[depth()].inset()))
918 bool LCursor::inNucleus()
920 return inset()->asMathInset()->asScriptInset() && idx() == 2;
926 autocorrect() = false;
933 if (pos() != 0 && openable(prevAtom())) {
935 push(nextAtom().nucleus());
936 inset()->idxLast(*this);
940 return posLeft() || idxLeft() || popLeft() || selection();
944 bool LCursor::right()
946 autocorrect() = false;
953 if (pos() != lastpos() && openable(nextAtom())) {
954 pushLeft(nextAtom().nucleus());
955 inset()->idxFirst(*this);
959 return posRight() || idxRight() || popRight() || selection();
963 bool positionable(CursorBase const & cursor, CursorBase const & anchor)
965 // avoid deeper nested insets when selecting
966 if (cursor.size() > anchor.size())
969 // anchor might be deeper, should have same path then
970 for (size_t i = 0; i < cursor.size(); ++i)
971 if (cursor[i].inset() != anchor[i].inset())
974 // position should be ok.
979 void LCursor::setScreenPos(int x, int y)
981 bool res = bruteFind(x, y, formula()->xlow(), formula()->xhigh(),
982 formula()->ylow(), formula()->yhigh());
984 // this can happen on creation of "math-display"
995 autocorrect() = false;
997 if (!inset()->idxHome(*this))
1006 autocorrect() = false;
1008 if (!inset()->idxEnd(*this))
1015 void LCursor::plainErase()
1017 cell().erase(pos());
1021 void LCursor::markInsert()
1023 cell().insert(pos(), MathAtom(new MathCharInset(0)));
1027 void LCursor::markErase()
1029 cell().erase(pos());
1033 void LCursor::plainInsert(MathAtom const & t)
1035 cell().insert(pos(), t);
1040 void LCursor::insert(string const & str)
1042 lyxerr << "LCursor::insert str '" << str << "'" << endl;
1045 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
1046 plainInsert(MathAtom(new MathCharInset(*it)));
1055 void LCursor::insert(char c)
1057 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
1059 plainInsert(MathAtom(new MathCharInset(c)));
1063 void LCursor::insert(MathAtom const & t)
1065 //lyxerr << "LCursor::insert MathAtom: " << endl;
1072 void LCursor::insert(InsetBase * inset)
1075 insert(MathAtom(inset));
1077 text()->insertInset(*this, inset);
1081 void LCursor::niceInsert(string const & t)
1092 void LCursor::niceInsert(MathAtom const & t)
1095 string safe = grabAndEraseSelection();
1097 // enter the new inset and move the contents of the selection if possible
1098 if (t->isActive()) {
1100 // be careful here: don't use 'pushLeft(t)' as this we need to
1101 // push the clone, not the original
1102 pushLeft(nextAtom().nucleus());
1108 void LCursor::insert(MathArray const & ar)
1113 cell().insert(pos(), ar);
1118 bool LCursor::backspace()
1120 autocorrect() = false;
1128 if (inset()->nargs() == 1 && depth() == 1 && lastpos() == 0)
1134 if (inMacroMode()) {
1135 MathUnknownInset * p = activeMacro();
1136 if (p->name().size() > 1) {
1137 p->setName(p->name().substr(0, p->name().size() - 1));
1142 if (pos() != 0 && prevAtom()->nargs() > 0) {
1143 // let's require two backspaces for 'big stuff' and
1144 // highlight on the first
1155 bool LCursor::erase()
1157 autocorrect() = false;
1166 // delete empty cells if possible
1167 if (pos() == lastpos() && inset()->idxDelete(idx()))
1170 // special behaviour when in last position of cell
1171 if (pos() == lastpos()) {
1172 bool one_cell = inset()->nargs() == 1;
1173 if (one_cell && depth() == 1 && lastpos() == 0)
1179 inset()->idxGlue(idx());
1183 if (pos() != lastpos() && inset()->nargs() > 0) {
1197 CursorBase save = cursor_;
1201 autocorrect() = false;
1206 bool LCursor::down()
1209 CursorBase save = cursor_;
1210 if (goUpDown(false))
1213 autocorrect() = false;
1218 void LCursor::macroModeClose()
1222 MathUnknownInset * p = activeMacro();
1224 string s = p->name();
1226 cell().erase(pos());
1228 // do nothing if the macro name is empty
1232 string const name = s.substr(1);
1234 // prevent entering of recursive macros
1235 if (formula()->lyxCode() == InsetOld::MATHMACRO_CODE
1236 && formula()->getInsetName() == name)
1237 lyxerr << "can't enter recursive macro" << endl;
1239 niceInsert(createMathInset(name));
1243 string LCursor::macroName()
1245 return inMacroMode() ? activeMacro()->name() : string();
1249 void LCursor::handleNest(MathAtom const & a, int c)
1251 //lyxerr << "LCursor::handleNest: " << c << endl;
1253 asArray(grabAndEraseSelection(), t.nucleus()->cell(c));
1256 pushLeft(nextAtom().nucleus());
1260 int LCursor::targetX() const
1262 if (x_target() != -1)
1271 MathHullInset * LCursor::formula() const
1273 for (int i = cursor_.size() - 1; i >= 1; --i) {
1274 MathInset * inset = cursor_[i].inset()->asMathInset();
1275 if (inset && inset->asHullInset())
1276 return static_cast<MathHullInset *>(inset);
1282 void LCursor::adjust(pos_type from, int diff)
1286 if (anchor().pos_ > from)
1287 anchor().pos_ += diff;
1288 // just to be on the safe side
1289 // theoretically unecessary
1294 bool LCursor::inMacroMode() const
1298 MathUnknownInset const * p = prevAtom()->asUnknownInset();
1299 return p && !p->final();
1303 MathUnknownInset * LCursor::activeMacro()
1305 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1309 bool LCursor::inMacroArgMode() const
1311 return pos() > 0 && prevAtom()->getChar() == '#';
1315 MathGridInset * LCursor::enclosingGrid(idx_type & idx) const
1317 for (MathInset::difference_type i = depth() - 1; i >= 0; --i) {
1318 MathInset * m = cursor_[i].inset()->asMathInset();
1321 MathGridInset * p = m->asGridInset();
1323 idx = cursor_[i].idx_;
1331 void LCursor::pullArg()
1334 MathArray ar = cell();
1335 if (popLeft() && inMathed()) {
1337 cell().insert(pos(), ar);
1340 //formula()->mutateToText();
1345 void LCursor::touch()
1349 CursorBase::const_iterator it = cursor_.begin();
1350 CursorBase::const_iterator et = cursor_.end();
1351 for ( ; it != et; ++it)
1357 void LCursor::normalize()
1359 if (idx() >= nargs()) {
1360 lyxerr << "this should not really happen - 1: "
1361 << idx() << ' ' << nargs()
1362 << " in: " << inset() << endl;
1364 idx() = min(idx(), lastidx());
1366 if (pos() > lastpos()) {
1367 lyxerr << "this should not really happen - 2: "
1368 << pos() << ' ' << lastpos() << " in idx: " << idx()
1370 WriteStream wi(lyxerr, false, true);
1371 inset()->asMathInset()->write(wi);
1374 pos() = min(pos(), lastpos());
1378 char LCursor::valign()
1381 MathGridInset * p = enclosingGrid(idx);
1382 return p ? p->valign() : '\0';
1386 char LCursor::halign()
1389 MathGridInset * p = enclosingGrid(idx);
1390 return p ? p->halign(idx % p->ncols()) : '\0';
1394 bool LCursor::goUpDown(bool up)
1396 // Be warned: The 'logic' implemented in this function is highly
1397 // fragile. A distance of one pixel or a '<' vs '<=' _really
1398 // matters. So fiddle around with it only if you think you know
1399 // what you are doing!
1404 // check if we had something else in mind, if not, this is the future goal
1405 if (x_target() == -1)
1410 // try neigbouring script insets
1414 MathScriptInset const * p = prevAtom()->asScriptInset();
1415 if (p && p->has(up)) {
1418 idx() = up; // the superscript has index 1
1420 //lyxerr << "updown: handled by scriptinset to the left" << endl;
1426 if (pos() != lastpos()) {
1427 MathScriptInset const * p = nextAtom()->asScriptInset();
1428 if (p && p->has(up)) {
1432 //lyxerr << "updown: handled by scriptinset to the right" << endl;
1438 // try current cell for e.g. text insets
1439 if (inset()->idxUpDown2(*this, up))
1442 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1447 //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1448 // lyxerr << "updown: handled by brute find in the same cell" << endl;
1452 // try to find an inset that knows better then we
1454 //lyxerr << "updown: We are in " << inset() << " idx: " << idx() << endl;
1456 if (inset()->idxUpDown(*this, up)) {
1457 // try to find best position within this inset
1463 // no such inset found, just take something "above"
1464 //lyxerr << "updown: handled by strange case" << endl;
1470 up ? formula()->ylow() : yo + 4,
1471 up ? yo - 4 : formula()->yhigh()
1475 // any improvement so far?
1478 if (up ? ynew < yo : ynew > yo)
1484 bool LCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1486 CursorBase best_cursor;
1487 double best_dist = 1e10;
1489 CursorBase it = ibegin(formula());
1490 CursorBase et = iend(formula());
1492 // avoid invalid nesting when selecting
1493 if (!selection() || positionable(it, anchor_)) {
1495 CursorSlice & cur = it.back();
1496 cur.inset()->getCursorPos(cur, xo, yo);
1497 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1498 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1499 //lyxerr << "x: " << x << " y: " << y << " d: " << endl;
1500 // '<=' in order to take the last possible position
1501 // this is important for clicking behind \sum in e.g. '\sum_i a'
1502 if (d <= best_dist) {
1514 if (best_dist < 1e10)
1515 cursor_ = best_cursor;
1516 return best_dist < 1e10;
1520 void LCursor::bruteFind2(int x, int y)
1522 double best_dist = 1e10;
1524 CursorBase it = cursor_;
1525 it.back().pos() = 0;
1526 CursorBase et = cursor_;
1527 et.back().pos() = et.back().asMathInset()->cell(et.back().idx_).size();
1528 for (int i = 0; ; ++i) {
1530 CursorSlice & cur = it.back();
1531 cur.inset()->getCursorPos(cur, xo, yo);
1532 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1533 // '<=' in order to take the last possible position
1534 // this is important for clicking behind \sum in e.g. '\sum_i a'
1535 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
1536 if (d <= best_dist) {
1547 bool LCursor::idxLineLast()
1549 idx() -= idx() % ncols();
1550 idx() += ncols() - 1;
1556 bool LCursor::idxLeft()
1558 return inset()->idxLeft(*this);
1562 bool LCursor::idxRight()
1564 return inset()->idxRight(*this);
1568 bool LCursor::script(bool up)
1570 // Hack to get \\^ and \\_ working
1571 lyxerr << "handling script: up: " << up << endl;
1572 if (inMacroMode() && macroName() == "\\") {
1574 niceInsert(createMathInset("mathcircumflex"));
1581 string safe = grabAndEraseSelection();
1583 // we are in a nucleus of a script inset, move to _our_ script
1584 inset()->asMathInset()->asScriptInset()->ensure(up);
1587 } else if (pos() != 0 && prevAtom()->asScriptInset()) {
1589 nextAtom().nucleus()->asScriptInset()->ensure(up);
1593 } else if (pos() != 0) {
1595 cell()[pos()] = MathAtom(new MathScriptInset(nextAtom(), up));
1600 plainInsert(MathAtom(new MathScriptInset(up)));
1602 nextAtom().nucleus()->asScriptInset()->ensure(up);
1612 bool LCursor::interpret(char c)
1614 //lyxerr << "interpret 2: '" << c << "'" << endl;
1616 if (inMacroArgMode()) {
1622 MathMacroTemplate const * p = formula()->asMacroTemplate();
1623 if (p && 1 <= n && n <= p->numargs())
1624 insert(MathAtom(new MathMacroArgument(c - '0')));
1626 insert(createMathInset("#"));
1627 interpret(c); // try again
1634 if (inMacroMode()) {
1635 string name = macroName();
1636 //lyxerr << "interpret name: '" << name << "'" << endl;
1639 activeMacro()->setName(activeMacro()->name() + c);
1643 // handle 'special char' macros
1648 if (currentMode() == MathInset::TEXT_MODE)
1649 niceInsert(createMathInset("textbackslash"));
1651 niceInsert(createMathInset("backslash"));
1652 } else if (c == '{') {
1653 niceInsert(MathAtom(new MathBraceInset));
1655 niceInsert(createMathInset(string(1, c)));
1660 // leave macro mode and try again if necessary
1663 niceInsert(MathAtom(new MathBraceInset));
1669 // This is annoying as one has to press <space> far too often.
1673 // leave autocorrect mode if necessary
1674 if (autocorrect() && c == ' ') {
1675 autocorrect() = false;
1680 // just clear selection on pressing the space bar
1681 if (selection() && c == ' ') {
1682 selection() = false;
1689 //lyxerr << "starting with macro" << endl;
1690 insert(MathAtom(new MathUnknownInset("\\", false)));
1695 if (currentMode() == MathInset::TEXT_MODE)
1701 if (currentMode() == MathInset::TEXT_MODE) {
1702 // insert spaces in text mode,
1703 // but suppress direct insertion of two spaces in a row
1704 // the still allows typing '<space>a<space>' and deleting the 'a', but
1705 // it is better than nothing...
1706 if (!pos() != 0 || prevAtom()->getChar() != ' ')
1710 if (pos() != 0 && prevAtom()->asSpaceInset()) {
1711 prevAtom().nucleus()->asSpaceInset()->incSpace();
1716 // if are at the very end, leave the formula
1717 return pos() != lastpos();
1730 if (c == '{' || c == '}' || c == '#' || c == '&' || c == '$') {
1731 niceInsert(createMathInset(string(1, c)));
1736 niceInsert(MathAtom(new MathCommentInset));
1740 // try auto-correction
1741 //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1744 // no special circumstances, so insert the character without any fuss
1746 autocorrect() = true;
1751 void LCursor::lockToggle()
1753 if (pos() != lastpos()) {
1754 // toggle previous inset ...
1755 nextAtom().nucleus()->lock(!nextAtom()->lock());
1756 } else if (popLeft() && pos() != lastpos()) {
1757 // ... or enclosing inset if we are in the last inset position
1758 nextAtom().nucleus()->lock(!nextAtom()->lock());
1764 CursorSlice LCursor::normalAnchor()
1766 if (anchor_.size() < depth()) {
1768 lyxerr << "unusual Anchor size" << endl;
1770 //lyx::BOOST_ASSERT(Anchor_.size() >= cursor.depth());
1771 // use Anchor on the same level as Cursor
1772 CursorSlice normal = anchor_[current_];
1774 if (depth() < anchor_.size() && !(normal < xx())) {
1775 // anchor is behind cursor -> move anchor behind the inset
1784 DispatchResult dispatch(LCursor & cur, FuncRequest const & cmd)
1786 // mouse clicks are somewhat special
1788 switch (cmd.action) {
1789 case LFUN_MOUSE_PRESS:
1790 case LFUN_MOUSE_MOTION:
1791 case LFUN_MOUSE_RELEASE:
1792 case LFUN_MOUSE_DOUBLE: {
1793 CursorSlice & pos = cursor_.back();
1797 if (x < cmd.x && pos() != 0) {
1798 DispatchResult const res = prevAtom().nucleus()->dispatch(cmd);
1799 if (res.dispatched())
1802 if (x > cmd.x && pos() != lastpos()) {
1803 DispatchResult const res = inset()->dispatch(cmd);
1804 if (res.dispatched())
1815 void LCursor::handleFont(string const & font)
1817 lyxerr << "LCursor::handleFont: " << font << endl;
1821 safe = grabAndEraseSelection();
1824 if (lastpos() != 0) {
1825 // something left in the cell
1827 // cursor in first position
1829 } else if (pos() == lastpos()) {
1830 // cursor in last position
1833 // cursor in between. split cell
1834 MathArray::iterator bt = cell().begin();
1835 MathAtom at = createMathInset(font);
1836 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1837 cell().erase(bt, bt + pos());
1842 // nothing left in the cell
1850 bool LCursor::inMathed() const
1856 bool LCursor::inTexted() const
1862 InsetBase * LCursor::nextInset()
1864 if (pos() == lastpos())
1867 return nextAtom().nucleus();
1868 return paragraph().isInset(pos()) ? paragraph().getInset(pos()) : 0;
1872 InsetBase * LCursor::prevInset()
1877 return prevAtom().nucleus();
1878 return paragraph().isInset(pos() - 1) ? paragraph().getInset(pos() - 1) : 0;
1882 InsetBase const * LCursor::prevInset() const
1887 return prevAtom().nucleus();
1888 return paragraph().isInset(pos() - 1) ? paragraph().getInset(pos() - 1) : 0;
1892 void LCursor::message(string const & msg) const
1894 bv().owner()->getLyXFunc().setMessage(msg);
1898 void LCursor::errorMessage(string const & msg) const
1900 bv().owner()->getLyXFunc().setErrorMessage(msg);
1904 string LCursor::selectionAsString(bool label) const
1910 Buffer const & buffer = *bv().buffer();
1912 // should be const ...
1913 ParagraphList::iterator startpit = text()->getPar(selBegin());
1914 ParagraphList::iterator endpit = text()->getPar(selEnd());
1915 size_t const startpos = selBegin().pos();
1916 size_t const endpos = selEnd().pos();
1918 if (startpit == endpit)
1919 return startpit->asString(buffer, startpos, endpos, label);
1921 // First paragraph in selection
1923 startpit->asString(buffer, startpos, startpit->size(), label) + "\n\n";
1925 // The paragraphs in between (if any)
1926 ParagraphList::iterator pit = startpit;
1927 for (++pit; pit != endpit; ++pit)
1928 result += pit->asString(buffer, 0, pit->size(), label) + "\n\n";
1930 // Last paragraph in selection
1931 result += endpit->asString(buffer, 0, endpos, label);
1941 string LCursor::currentState()
1944 std::ostringstream os;
1948 return text() ? text()->currentState(*this) : string();
1952 // only used by the spellchecker
1953 void LCursor::replaceWord(string const & replacestring)
1955 LyXText * t = text();
1958 t->replaceSelectionWithString(*this, replacestring);
1959 t->setSelectionRange(*this, replacestring.length());
1961 // Go back so that replacement string is also spellchecked
1962 for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
1963 t->cursorLeft(*this);
1967 void LCursor::update()
1973 string LCursor::getPossibleLabel()
1975 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1979 void LCursor::notdispatched()
1981 disp_.dispatched(false);
1985 void LCursor::dispatched(dispatch_result_t res)
1991 void LCursor::noupdate()
1993 disp_.update(false);