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) const
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;
924 bool positionable(CursorBase const & cursor, CursorBase const & anchor)
926 // avoid deeper nested insets when selecting
927 if (cursor.size() > anchor.size())
930 // anchor might be deeper, should have same path then
931 for (size_t i = 0; i < cursor.size(); ++i)
932 if (cursor[i].inset() != anchor[i].inset())
935 // position should be ok.
940 void LCursor::setScreenPos(int x, int y)
942 bool res = bruteFind(x, y, formula()->xlow(), formula()->xhigh(),
943 formula()->ylow(), formula()->yhigh());
945 // this can happen on creation of "math-display"
954 void LCursor::plainErase()
960 void LCursor::markInsert()
962 cell().insert(pos(), MathAtom(new MathCharInset(0)));
966 void LCursor::markErase()
972 void LCursor::plainInsert(MathAtom const & t)
974 cell().insert(pos(), t);
979 void LCursor::insert(string const & str)
981 lyxerr << "LCursor::insert str '" << str << "'" << endl;
984 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
985 plainInsert(MathAtom(new MathCharInset(*it)));
994 void LCursor::insert(char c)
996 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
998 plainInsert(MathAtom(new MathCharInset(c)));
1002 void LCursor::insert(MathAtom const & t)
1004 //lyxerr << "LCursor::insert MathAtom: " << endl;
1011 void LCursor::insert(InsetBase * inset)
1014 insert(MathAtom(inset));
1016 text()->insertInset(*this, inset);
1020 void LCursor::niceInsert(string const & t)
1031 void LCursor::niceInsert(MathAtom const & t)
1034 string safe = grabAndEraseSelection();
1036 // enter the new inset and move the contents of the selection if possible
1037 if (t->isActive()) {
1039 // be careful here: don't use 'pushLeft(t)' as this we need to
1040 // push the clone, not the original
1041 pushLeft(nextAtom().nucleus());
1047 void LCursor::insert(MathArray const & ar)
1052 cell().insert(pos(), ar);
1057 bool LCursor::backspace()
1059 autocorrect() = false;
1067 if (inset()->nargs() == 1 && depth() == 1 && lastpos() == 0)
1073 if (inMacroMode()) {
1074 MathUnknownInset * p = activeMacro();
1075 if (p->name().size() > 1) {
1076 p->setName(p->name().substr(0, p->name().size() - 1));
1081 if (pos() != 0 && prevAtom()->nargs() > 0) {
1082 // let's require two backspaces for 'big stuff' and
1083 // highlight on the first
1094 bool LCursor::erase()
1096 autocorrect() = false;
1105 // delete empty cells if possible
1106 if (pos() == lastpos() && inset()->idxDelete(idx()))
1109 // special behaviour when in last position of cell
1110 if (pos() == lastpos()) {
1111 bool one_cell = inset()->nargs() == 1;
1112 if (one_cell && depth() == 1 && lastpos() == 0)
1118 inset()->idxGlue(idx());
1122 if (pos() != lastpos() && inset()->nargs() > 0) {
1136 CursorBase save = cursor_;
1140 autocorrect() = false;
1145 bool LCursor::down()
1148 CursorBase save = cursor_;
1149 if (goUpDown(false))
1152 autocorrect() = false;
1157 void LCursor::macroModeClose()
1161 MathUnknownInset * p = activeMacro();
1163 string s = p->name();
1165 cell().erase(pos());
1167 // do nothing if the macro name is empty
1171 string const name = s.substr(1);
1173 // prevent entering of recursive macros
1174 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
1175 if (macro && macro->getInsetName() == name)
1176 lyxerr << "can't enter recursive macro" << endl;
1178 niceInsert(createMathInset(name));
1182 string LCursor::macroName()
1184 return inMacroMode() ? activeMacro()->name() : string();
1188 void LCursor::handleNest(MathAtom const & a, int c)
1190 //lyxerr << "LCursor::handleNest: " << c << endl;
1192 asArray(grabAndEraseSelection(), t.nucleus()->cell(c));
1195 pushLeft(nextAtom().nucleus());
1199 int LCursor::targetX() const
1201 if (x_target() != -1)
1210 MathHullInset * LCursor::formula() const
1212 for (int i = cursor_.size() - 1; i >= 1; --i) {
1213 MathInset * inset = cursor_[i].inset()->asMathInset();
1214 if (inset && inset->asHullInset())
1215 return static_cast<MathHullInset *>(inset);
1221 void LCursor::adjust(pos_type from, int diff)
1225 if (anchor().pos_ > from)
1226 anchor().pos_ += diff;
1227 // just to be on the safe side
1228 // theoretically unecessary
1233 bool LCursor::inMacroMode() const
1237 MathUnknownInset const * p = prevAtom()->asUnknownInset();
1238 return p && !p->final();
1242 MathUnknownInset * LCursor::activeMacro()
1244 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1248 bool LCursor::inMacroArgMode() const
1250 return pos() > 0 && prevAtom()->getChar() == '#';
1254 MathGridInset * LCursor::enclosingGrid(idx_type & idx) const
1256 for (MathInset::difference_type i = depth() - 1; i >= 0; --i) {
1257 MathInset * m = cursor_[i].inset()->asMathInset();
1260 MathGridInset * p = m->asGridInset();
1262 idx = cursor_[i].idx_;
1270 void LCursor::pullArg()
1273 MathArray ar = cell();
1274 if (popLeft() && inMathed()) {
1276 cell().insert(pos(), ar);
1279 //formula()->mutateToText();
1284 void LCursor::touch()
1288 CursorBase::const_iterator it = cursor_.begin();
1289 CursorBase::const_iterator et = cursor_.end();
1290 for ( ; it != et; ++it)
1296 void LCursor::normalize()
1298 if (idx() >= nargs()) {
1299 lyxerr << "this should not really happen - 1: "
1300 << idx() << ' ' << nargs()
1301 << " in: " << inset() << endl;
1303 idx() = min(idx(), lastidx());
1305 if (pos() > lastpos()) {
1306 lyxerr << "this should not really happen - 2: "
1307 << pos() << ' ' << lastpos() << " in idx: " << idx()
1309 WriteStream wi(lyxerr, false, true);
1310 inset()->asMathInset()->write(wi);
1313 pos() = min(pos(), lastpos());
1317 char LCursor::valign()
1320 MathGridInset * p = enclosingGrid(idx);
1321 return p ? p->valign() : '\0';
1325 char LCursor::halign()
1328 MathGridInset * p = enclosingGrid(idx);
1329 return p ? p->halign(idx % p->ncols()) : '\0';
1333 bool LCursor::goUpDown(bool up)
1335 // Be warned: The 'logic' implemented in this function is highly
1336 // fragile. A distance of one pixel or a '<' vs '<=' _really
1337 // matters. So fiddle around with it only if you think you know
1338 // what you are doing!
1343 // check if we had something else in mind, if not, this is the future goal
1344 if (x_target() == -1)
1349 // try neigbouring script insets
1353 MathScriptInset const * p = prevAtom()->asScriptInset();
1354 if (p && p->has(up)) {
1357 idx() = up; // the superscript has index 1
1359 //lyxerr << "updown: handled by scriptinset to the left" << endl;
1365 if (pos() != lastpos()) {
1366 MathScriptInset const * p = nextAtom()->asScriptInset();
1367 if (p && p->has(up)) {
1371 //lyxerr << "updown: handled by scriptinset to the right" << endl;
1377 // try current cell for e.g. text insets
1378 if (inset()->idxUpDown2(*this, up))
1381 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1386 //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1387 // lyxerr << "updown: handled by brute find in the same cell" << endl;
1391 // try to find an inset that knows better then we
1393 //lyxerr << "updown: We are in " << inset() << " idx: " << idx() << endl;
1395 if (inset()->idxUpDown(*this, up)) {
1396 // try to find best position within this inset
1402 // no such inset found, just take something "above"
1403 //lyxerr << "updown: handled by strange case" << endl;
1409 up ? formula()->ylow() : yo + 4,
1410 up ? yo - 4 : formula()->yhigh()
1414 // any improvement so far?
1417 if (up ? ynew < yo : ynew > yo)
1423 bool LCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1425 CursorBase best_cursor;
1426 double best_dist = 1e10;
1428 CursorBase it = ibegin(formula());
1429 CursorBase et = iend(formula());
1431 // avoid invalid nesting when selecting
1432 if (!selection() || positionable(it, anchor_)) {
1434 CursorSlice & cur = it.back();
1435 cur.inset()->getCursorPos(cur, xo, yo);
1436 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1437 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1438 //lyxerr << "x: " << x << " y: " << y << " d: " << endl;
1439 // '<=' in order to take the last possible position
1440 // this is important for clicking behind \sum in e.g. '\sum_i a'
1441 if (d <= best_dist) {
1453 if (best_dist < 1e10)
1454 cursor_ = best_cursor;
1455 return best_dist < 1e10;
1459 void LCursor::bruteFind2(int x, int y)
1461 double best_dist = 1e10;
1463 CursorBase it = cursor_;
1464 it.back().pos() = 0;
1465 CursorBase et = cursor_;
1466 et.back().pos() = et.back().asMathInset()->cell(et.back().idx_).size();
1467 for (int i = 0; ; ++i) {
1469 CursorSlice & cur = it.back();
1470 cur.inset()->getCursorPos(cur, xo, yo);
1471 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1472 // '<=' in order to take the last possible position
1473 // this is important for clicking behind \sum in e.g. '\sum_i a'
1474 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
1475 if (d <= best_dist) {
1486 bool LCursor::script(bool up)
1488 // Hack to get \\^ and \\_ working
1489 lyxerr << "handling script: up: " << up << endl;
1490 if (inMacroMode() && macroName() == "\\") {
1492 niceInsert(createMathInset("mathcircumflex"));
1499 string safe = grabAndEraseSelection();
1501 // we are in a nucleus of a script inset, move to _our_ script
1502 inset()->asMathInset()->asScriptInset()->ensure(up);
1505 } else if (pos() != 0 && prevAtom()->asScriptInset()) {
1507 nextAtom().nucleus()->asScriptInset()->ensure(up);
1511 } else if (pos() != 0) {
1513 cell()[pos()] = MathAtom(new MathScriptInset(nextAtom(), up));
1518 plainInsert(MathAtom(new MathScriptInset(up)));
1520 nextAtom().nucleus()->asScriptInset()->ensure(up);
1530 bool LCursor::interpret(char c)
1532 //lyxerr << "interpret 2: '" << c << "'" << endl;
1534 if (inMacroArgMode()) {
1540 MathMacroTemplate const * p = formula()->asMacroTemplate();
1541 if (p && 1 <= n && n <= p->numargs())
1542 insert(MathAtom(new MathMacroArgument(c - '0')));
1544 insert(createMathInset("#"));
1545 interpret(c); // try again
1552 if (inMacroMode()) {
1553 string name = macroName();
1554 //lyxerr << "interpret name: '" << name << "'" << endl;
1557 activeMacro()->setName(activeMacro()->name() + c);
1561 // handle 'special char' macros
1566 if (currentMode() == MathInset::TEXT_MODE)
1567 niceInsert(createMathInset("textbackslash"));
1569 niceInsert(createMathInset("backslash"));
1570 } else if (c == '{') {
1571 niceInsert(MathAtom(new MathBraceInset));
1573 niceInsert(createMathInset(string(1, c)));
1578 // leave macro mode and try again if necessary
1581 niceInsert(MathAtom(new MathBraceInset));
1587 // This is annoying as one has to press <space> far too often.
1591 // leave autocorrect mode if necessary
1592 if (autocorrect() && c == ' ') {
1593 autocorrect() = false;
1598 // just clear selection on pressing the space bar
1599 if (selection() && c == ' ') {
1600 selection() = false;
1607 //lyxerr << "starting with macro" << endl;
1608 insert(MathAtom(new MathUnknownInset("\\", false)));
1613 if (currentMode() == MathInset::TEXT_MODE)
1619 if (currentMode() == MathInset::TEXT_MODE) {
1620 // insert spaces in text mode,
1621 // but suppress direct insertion of two spaces in a row
1622 // the still allows typing '<space>a<space>' and deleting the 'a', but
1623 // it is better than nothing...
1624 if (!pos() != 0 || prevAtom()->getChar() != ' ')
1628 if (pos() != 0 && prevAtom()->asSpaceInset()) {
1629 prevAtom().nucleus()->asSpaceInset()->incSpace();
1634 // if are at the very end, leave the formula
1635 return pos() != lastpos();
1648 if (c == '{' || c == '}' || c == '#' || c == '&' || c == '$') {
1649 niceInsert(createMathInset(string(1, c)));
1654 niceInsert(MathAtom(new MathCommentInset));
1658 // try auto-correction
1659 //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1662 // no special circumstances, so insert the character without any fuss
1664 autocorrect() = true;
1669 void LCursor::lockToggle()
1671 if (pos() != lastpos()) {
1672 // toggle previous inset ...
1673 nextAtom().nucleus()->lock(!nextAtom()->lock());
1674 } else if (popLeft() && pos() != lastpos()) {
1675 // ... or enclosing inset if we are in the last inset position
1676 nextAtom().nucleus()->lock(!nextAtom()->lock());
1682 CursorSlice LCursor::normalAnchor()
1684 if (anchor_.size() < depth()) {
1686 lyxerr << "unusual Anchor size" << endl;
1688 //lyx::BOOST_ASSERT(Anchor_.size() >= cursor.depth());
1689 // use Anchor on the same level as Cursor
1690 CursorSlice normal = anchor_[current_];
1692 if (depth() < anchor_.size() && !(normal < xx())) {
1693 // anchor is behind cursor -> move anchor behind the inset
1702 DispatchResult dispatch(LCursor & cur, FuncRequest const & cmd)
1704 // mouse clicks are somewhat special
1706 switch (cmd.action) {
1707 case LFUN_MOUSE_PRESS:
1708 case LFUN_MOUSE_MOTION:
1709 case LFUN_MOUSE_RELEASE:
1710 case LFUN_MOUSE_DOUBLE: {
1711 CursorSlice & pos = cursor_.back();
1715 if (x < cmd.x && pos() != 0) {
1716 DispatchResult const res = prevAtom().nucleus()->dispatch(cmd);
1717 if (res.dispatched())
1720 if (x > cmd.x && pos() != lastpos()) {
1721 DispatchResult const res = inset()->dispatch(cmd);
1722 if (res.dispatched())
1733 void LCursor::handleFont(string const & font)
1735 lyxerr << "LCursor::handleFont: " << font << endl;
1739 safe = grabAndEraseSelection();
1742 if (lastpos() != 0) {
1743 // something left in the cell
1745 // cursor in first position
1747 } else if (pos() == lastpos()) {
1748 // cursor in last position
1751 // cursor in between. split cell
1752 MathArray::iterator bt = cell().begin();
1753 MathAtom at = createMathInset(font);
1754 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1755 cell().erase(bt, bt + pos());
1760 // nothing left in the cell
1768 bool LCursor::inMathed() const
1770 return current_ && inset()->inMathed();
1774 bool LCursor::inTexted() const
1780 InsetBase * LCursor::nextInset()
1782 if (pos() == lastpos())
1785 return nextAtom().nucleus();
1786 return paragraph().isInset(pos()) ? paragraph().getInset(pos()) : 0;
1790 InsetBase * LCursor::prevInset()
1795 return prevAtom().nucleus();
1796 return paragraph().isInset(pos() - 1) ? paragraph().getInset(pos() - 1) : 0;
1800 InsetBase const * LCursor::prevInset() const
1805 return prevAtom().nucleus();
1806 return paragraph().isInset(pos() - 1) ? paragraph().getInset(pos() - 1) : 0;
1810 void LCursor::message(string const & msg) const
1812 bv().owner()->getLyXFunc().setMessage(msg);
1816 void LCursor::errorMessage(string const & msg) const
1818 bv().owner()->getLyXFunc().setErrorMessage(msg);
1822 string LCursor::selectionAsString(bool label) const
1828 Buffer const & buffer = *bv().buffer();
1830 // should be const ...
1831 ParagraphList::iterator startpit = text()->getPar(selBegin());
1832 ParagraphList::iterator endpit = text()->getPar(selEnd());
1833 size_t const startpos = selBegin().pos();
1834 size_t const endpos = selEnd().pos();
1836 if (startpit == endpit)
1837 return startpit->asString(buffer, startpos, endpos, label);
1839 // First paragraph in selection
1841 startpit->asString(buffer, startpos, startpit->size(), label) + "\n\n";
1843 // The paragraphs in between (if any)
1844 ParagraphList::iterator pit = startpit;
1845 for (++pit; pit != endpit; ++pit)
1846 result += pit->asString(buffer, 0, pit->size(), label) + "\n\n";
1848 // Last paragraph in selection
1849 result += endpit->asString(buffer, 0, endpos, label);
1859 string LCursor::currentState()
1862 std::ostringstream os;
1866 return text() ? text()->currentState(*this) : string();
1870 // only used by the spellchecker
1871 void LCursor::replaceWord(string const & replacestring)
1873 LyXText * t = text();
1876 t->replaceSelectionWithString(*this, replacestring);
1877 t->setSelectionRange(*this, replacestring.length());
1879 // Go back so that replacement string is also spellchecked
1880 for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
1881 t->cursorLeft(*this);
1885 void LCursor::update()
1891 string LCursor::getPossibleLabel()
1893 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1897 void LCursor::notdispatched()
1899 disp_.dispatched(false);
1903 void LCursor::dispatched(dispatch_result_t res)
1909 void LCursor::noupdate()
1911 disp_.update(false);