3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alejandro Aguilar Sierra
7 * \author Alfredo Braunstein
10 * Full author contact details are available in file CREDITS.
16 #include "BufferView.h"
19 #include "dispatchresult.h"
20 #include "funcrequest.h"
21 #include "iterators.h"
23 #include "lyxfunc.h" // only for setMessage()
27 #include "paragraph.h"
29 #include "insets/updatableinset.h"
30 #include "insets/insettabular.h"
31 #include "insets/insettext.h"
33 #include "mathed/math_data.h"
34 #include "mathed/math_hullinset.h"
35 #include "mathed/math_support.h"
37 #include "support/limited_stack.h"
38 #include "support/std_sstream.h"
40 #include "frontends/LyXView.h"
42 #include <boost/assert.hpp>
47 #ifndef CXX_GLOBAL_CSTD
56 limited_stack<string> theCutBuffer;
59 LCursor::LCursor(BufferView & bv)
60 : cursor_(1), anchor_(1), bv_(&bv), current_(0),
61 cached_y_(0), x_target_(-1),
62 selection_(false), mark_(false)
70 cursor_.push_back(CursorSlice());
71 anchor_.push_back(CursorSlice());
80 DispatchResult LCursor::dispatch(FuncRequest const & cmd0)
82 lyxerr << "\nLCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
83 FuncRequest cmd = cmd0;
84 for (current_ = cursor_.size() - 1; current_ >= 1; --current_) {
85 DispatchResult res = inset()->dispatch(*this, cmd);
86 if (res.dispatched()) {
87 current_ = cursor_.size() - 1;
88 return DispatchResult(true, true);
92 // "Mutate" the request for semi-handled requests that need
93 // additional handling in outer levels.
96 cmd = FuncRequest(LFUN_FINISHED_LEFT);
99 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
102 cmd = FuncRequest(LFUN_FINISHED_UP);
105 cmd = FuncRequest(LFUN_FINISHED_DOWN);
108 //lyxerr << "not handled on level " << current_
109 // << " val: " << res.val() << endl;
113 BOOST_ASSERT(current_ == 0);
114 DispatchResult res = bv_->text()->dispatch(*this, cmd);
115 //lyxerr << " result: " << res.val() << endl;
116 current_ = cursor_.size() - 1;
121 void LCursor::push(InsetBase * inset)
123 lyxerr << "LCursor::push() inset: " << inset << endl;
124 cursor_.push_back(CursorSlice(inset));
125 anchor_.push_back(CursorSlice(inset));
131 void LCursor::pop(int depth)
133 while (int(cursor_.size()) > depth + 1)
135 lyxerr << "LCursor::pop() result: " << *this << endl;
141 BOOST_ASSERT(cursor_.size() >= 1);
144 current_ = cursor_.size() - 1;
148 void LCursor::pushLeft(InsetBase * p)
150 BOOST_ASSERT(!cursor_.empty());
151 //lyxerr << "Entering inset " << t << " left" << endl;
157 bool LCursor::popLeft()
159 BOOST_ASSERT(!cursor_.empty());
160 //lyxerr << "Leaving inset to the left" << endl;
163 inset()->notifyCursorLeaves(idx());
166 inset()->notifyCursorLeaves(idx());
172 bool LCursor::popRight()
174 BOOST_ASSERT(!cursor_.empty());
175 //lyxerr << "Leaving inset to the right" << endl;
178 inset()->notifyCursorLeaves(idx());
181 inset()->notifyCursorLeaves(idx());
188 CursorSlice & LCursor::current()
190 BOOST_ASSERT(!cursor_.empty());
191 //lyxerr << "accessing cursor slice " << current_
192 // << ": " << cursor_[current_] << endl;
193 return cursor_[current_];
197 CursorSlice const & LCursor::current() const
199 //lyxerr << "accessing cursor slice " << current_
200 // << ": " << cursor_[current_] << endl;
201 return cursor_[current_];
205 int LCursor::currentMode()
207 BOOST_ASSERT(!cursor_.empty());
208 for (int i = cursor_.size() - 1; i >= 1; --i) {
209 int res = cursor_[i].inset()->currentMode();
210 if (res != MathInset::UNDECIDED_MODE)
213 return MathInset::TEXT_MODE;
217 LyXText * LCursor::innerText() const
219 BOOST_ASSERT(!cursor_.empty());
220 if (cursor_.size() > 1) {
221 // go up until first non-0 text is hit
222 // (innermost text is 0 in mathed)
223 for (int i = cursor_.size() - 1; i >= 1; --i)
224 if (cursor_[i].text())
225 return cursor_[i].text();
231 CursorSlice const & LCursor::innerTextSlice() const
233 BOOST_ASSERT(!cursor_.empty());
234 if (cursor_.size() > 1) {
235 // go up until first non-0 text is hit
236 // (innermost text is 0 in mathed)
237 for (int i = cursor_.size() - 1; i >= 1; --i)
238 if (cursor_[i].text())
245 void LCursor::updatePos()
247 BOOST_ASSERT(!cursor_.empty());
248 if (cursor_.size() > 1)
249 cached_y_ = bv_->top_y() + cursor_.back().inset()->yo();
250 //cached_y_ = cursor_.back().inset()->yo();
254 void LCursor::getDim(int & asc, int & des) const
256 BOOST_ASSERT(!cursor_.empty());
258 BOOST_ASSERT(inset());
259 BOOST_ASSERT(inset()->asMathInset());
260 //inset()->asMathInset()->getCursorDim(asc, des);
264 Row const & row = textRow();
265 asc = row.baseline();
266 des = row.height() - asc;
271 void LCursor::getPos(int & x, int & y) const
273 BOOST_ASSERT(!cursor_.empty());
276 if (cursor_.size() == 1) {
277 x = bv_->text()->cursorX(cursor_.front());
278 y = bv_->text()->cursorY(cursor_.front());
281 lyxerr << "#### LCursor::getPos: " << *this << endl;
282 BOOST_ASSERT(inset());
284 inset()->getCursorPos(cursor_.back(), x, y);
285 // getCursorPos gives _screen_ coordinates. We need to add
286 // top_y to get document coordinates. This is hidden in cached_y_.
287 //y += cached_y_ - inset()->yo();
288 // The rest is non-obvious. The reason we have to have these
289 // extra computation is that the getCursorPos() calls rely
290 // on the inset's own knowledge of its screen position.
291 // If we scroll up or down in a big enough increment,
292 // inset->draw() is not called: this doesn't update
293 // inset.yo_, so getCursor() returns an old value.
296 //lyxerr << "#### LCursor::getPos: " << *this
297 // << " x: " << x << " y: " << y << endl;
301 void LCursor::paste(string const & data)
303 dispatch(FuncRequest(LFUN_PASTE, data));
307 InsetBase * LCursor::innerInsetOfType(int code) const
309 for (int i = cursor_.size() - 1; i >= 1; --i)
310 if (cursor_[i].inset_->lyxCode() == code)
311 return cursor_[i].inset_;
316 InsetTabular * LCursor::innerInsetTabular() const
318 return static_cast<InsetTabular *>(innerInsetOfType(InsetBase::TABULAR_CODE));
322 void LCursor::resetAnchor()
328 BufferView & LCursor::bv() const
334 MathAtom const & LCursor::prevAtom() const
336 BOOST_ASSERT(pos() > 0);
337 return cell()[pos() - 1];
341 MathAtom & LCursor::prevAtom()
343 BOOST_ASSERT(pos() > 0);
344 return cell()[pos() - 1];
348 MathAtom const & LCursor::nextAtom() const
350 BOOST_ASSERT(pos() < lastpos());
351 return cell()[pos()];
355 MathAtom & LCursor::nextAtom()
357 BOOST_ASSERT(pos() < lastpos());
358 return cell()[pos()];
362 bool LCursor::posLeft()
371 bool LCursor::posRight()
373 if (pos() == lastpos())
380 CursorSlice & LCursor::anchor()
382 return anchor_.back();
386 CursorSlice const & LCursor::anchor() const
388 return anchor_.back();
392 CursorSlice const & LCursor::selBegin() const
395 return cursor_.back();
396 return anchor() < cursor_.back() ? anchor() : cursor_.back();
400 CursorSlice & LCursor::selBegin()
403 return cursor_.back();
404 // can't use std::min as this returns a const ref
405 return anchor() < cursor_.back() ? anchor() : cursor_.back();
409 CursorSlice const & LCursor::selEnd() const
412 return cursor_.back();
413 return anchor() > cursor_.back() ? anchor() : cursor_.back();
417 CursorSlice & LCursor::selEnd()
420 return cursor_.back();
421 // can't use std::min as this returns a const ref
422 return anchor() > cursor_.back() ? anchor() : cursor_.back();
426 void LCursor::setSelection()
429 // a selection with no contents is not a selection
430 if (par() == anchor().par() && pos() == anchor().pos())
435 void LCursor::setSelection(CursorBase const & where, size_t n)
444 void LCursor::clearSelection()
453 int & LCursor::x_target()
459 int LCursor::x_target() const
465 void LCursor::clearTargetX()
471 LyXText * LCursor::text() const
473 return current_ ? current().text() : bv_->text();
477 Paragraph & LCursor::paragraph()
479 BOOST_ASSERT(inTexted());
480 return current_ ? current().paragraph() : *bv_->text()->getPar(par());
484 Paragraph const & LCursor::paragraph() const
486 BOOST_ASSERT(inTexted());
487 return current_ ? current().paragraph() : *bv_->text()->getPar(par());
491 Row & LCursor::textRow()
493 return *paragraph().getRow(pos());
497 Row const & LCursor::textRow() const
499 return *paragraph().getRow(pos());
503 LCursor::par_type LCursor::lastpar() const
505 return inMathed() ? 0 : text()->paragraphs().size() - 1;
509 LCursor::pos_type LCursor::lastpos() const
511 InsetBase * inset = current().inset();
512 return inset && inset->asMathInset() ? cell().size() : paragraph().size();
516 LCursor::row_type LCursor::crow() const
518 return paragraph().row(pos());
522 LCursor::row_type LCursor::lastcrow() const
524 return paragraph().rows.size();
528 size_t LCursor::nargs() const
530 // assume 1x1 grid for 'plain text'
531 return current_ ? current().nargs() : 1;
535 size_t LCursor::ncols() const
537 // assume 1x1 grid for 'plain text'
538 return current_ ? current().ncols() : 1;
542 size_t LCursor::nrows() const
544 // assume 1x1 grid for 'plain text'
545 return current_ ? current().nrows() : 1;
549 LCursor::row_type LCursor::row() const
551 BOOST_ASSERT(current_ > 0);
552 return current().row();
556 LCursor::col_type LCursor::col() const
558 BOOST_ASSERT(current_ > 0);
559 return current().col();
563 MathArray const & LCursor::cell() const
565 BOOST_ASSERT(current_ > 0);
566 return current().cell();
570 MathArray & LCursor::cell()
572 BOOST_ASSERT(current_ > 0);
573 return current().cell();
577 void LCursor::info(std::ostream & os) const
579 for (int i = 1, n = depth(); i < n; ++i) {
580 cursor_[i].inset()->infoize(os);
584 prevInset()->infoize2(os);
585 // overwite old message
592 void region(CursorSlice const & i1, CursorSlice const & i2,
593 LCursor::row_type & r1, LCursor::row_type & r2,
594 LCursor::col_type & c1, LCursor::col_type & c2)
596 InsetBase * p = i1.inset();
597 c1 = p->col(i1.idx_);
598 c2 = p->col(i2.idx_);
601 r1 = p->row(i1.idx_);
602 r2 = p->row(i2.idx_);
610 string LCursor::grabSelection()
615 CursorSlice i1 = selBegin();
616 CursorSlice i2 = selEnd();
618 if (i1.idx_ == i2.idx_) {
619 if (i1.inset()->asMathInset()) {
620 MathArray::const_iterator it = i1.cell().begin();
621 return asString(MathArray(it + i1.pos_, it + i2.pos_));
623 return "unknown selection 1";
629 region(i1, i2, r1, r2, c1, c2);
632 if (i1.inset()->asMathInset()) {
633 for (row_type row = r1; row <= r2; ++row) {
636 for (col_type col = c1; col <= c2; ++col) {
639 data += asString(i1.asMathInset()->cell(i1.asMathInset()->index(row, col)));
643 data = "unknown selection 2";
649 void LCursor::eraseSelection()
651 //lyxerr << "LCursor::eraseSelection" << endl;
652 CursorSlice const & i1 = selBegin();
653 CursorSlice const & i2 = selEnd();
655 if (i1.inset()->asMathInset()) {
656 if (i1.idx_ == i2.idx_) {
657 i1.cell().erase(i1.pos_, i2.pos_);
659 MathInset * p = i1.asMathInset();
662 region(i1, i2, r1, r2, c1, c2);
663 for (row_type row = r1; row <= r2; ++row)
664 for (col_type col = c1; col <= c2; ++col)
665 p->cell(p->index(row, col)).clear();
669 lyxerr << "can't erase this selection 1" << endl;
671 //lyxerr << "LCursor::eraseSelection end" << endl;
675 string LCursor::grabAndEraseSelection()
679 string res = grabSelection();
686 void LCursor::selClear()
693 void LCursor::selCopy()
696 theCutBuffer.push(grabSelection());
699 //theCutBuffer.erase();
704 void LCursor::selCut()
706 theCutBuffer.push(grabAndEraseSelection());
710 void LCursor::selDel()
712 //lyxerr << "LCursor::selDel" << endl;
720 void LCursor::selPaste(size_t n)
723 if (n < theCutBuffer.size())
724 paste(theCutBuffer[n]);
730 void LCursor::selHandle(bool sel)
732 //lyxerr << "LCursor::selHandle" << endl;
733 if (sel == selection())
740 void LCursor::selClearOrDel()
742 //lyxerr << "LCursor::selClearOrDel" << endl;
743 if (lyxrc.auto_region_delete)
750 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
752 for (size_t i = 0, n = cur.cursor_.size(); i != n; ++i)
753 os << " " << cur.cursor_[i] << " | " << cur.anchor_[i] << "\n";
754 os << " current: " << cur.current_ << endl;
755 os << " selection: " << cur.selection_ << endl;
767 void increment(CursorBase & it)
769 CursorSlice & top = it.back();
770 MathArray & ar = top.asMathInset()->cell(top.idx_);
772 // move into the current inset if possible
773 // it is impossible for pos() == size()!
775 if (top.pos() != top.lastpos())
776 n = (ar.begin() + top.pos_)->nucleus();
777 if (n && n->isActive()) {
778 it.push_back(CursorSlice(n));
782 // otherwise move on one cell back if possible
783 if (top.pos() < top.lastpos()) {
784 // pos() == lastpos() is valid!
789 // otherwise try to move on one cell if possible
790 while (top.idx() < top.lastidx()) {
792 if (top.asMathInset()->validCell(top.idx_)) {
798 // otherwise leave array, move on one back
799 // this might yield pos() == size(), but that's a ok.
801 // it certainly invalidates top
806 CursorBase ibegin(InsetBase * p)
809 it.push_back(CursorSlice(p));
814 CursorBase iend(InsetBase * p)
817 it.push_back(CursorSlice(p));
818 CursorSlice & cur = it.back();
819 cur.idx() = cur.lastidx();
820 cur.pos() = cur.lastpos();
827 ///////////////////////////////////////////////////////////////////
829 // The part below is the non-integrated rest of the original math
830 // cursor. This should be either generalized for texted or moved
831 // back to the math insets.
833 ///////////////////////////////////////////////////////////////////
835 #include "mathed/math_braceinset.h"
836 #include "mathed/math_charinset.h"
837 #include "mathed/math_commentinset.h"
838 #include "mathed/math_factory.h"
839 #include "mathed/math_gridinset.h"
840 #include "mathed/math_macroarg.h"
841 #include "mathed/math_macrotemplate.h"
842 #include "mathed/math_mathmlstream.h"
843 #include "mathed/math_scriptinset.h"
844 #include "mathed/math_spaceinset.h"
845 #include "mathed/math_support.h"
846 #include "mathed/math_unknowninset.h"
848 //#define FILEDEBUG 1
851 bool LCursor::isInside(InsetBase const * p)
853 for (unsigned i = 0; i < depth(); ++i)
854 if (cursor_[i].inset() == p)
860 bool LCursor::openable(MathAtom const & t)
871 // we can't move into anything new during selection
872 if (depth() == anchor_.size())
874 if (!ptr_cmp(t.nucleus(), anchor_[depth()].inset()))
881 bool LCursor::inNucleus()
883 return inset()->asMathInset()->asScriptInset() && idx() == 2;
889 autocorrect() = false;
896 if (pos() != 0 && openable(prevAtom())) {
898 push(nextAtom().nucleus());
899 inset()->idxLast(*this);
903 return posLeft() || idxLeft() || popLeft() || selection();
907 bool LCursor::right()
909 autocorrect() = false;
916 if (pos() != lastpos() && openable(nextAtom())) {
917 pushLeft(nextAtom().nucleus());
918 inset()->idxFirst(*this);
922 return posRight() || idxRight() || popRight() || selection();
926 bool positionable(CursorBase const & cursor, CursorBase const & anchor)
928 // avoid deeper nested insets when selecting
929 if (cursor.size() > anchor.size())
932 // anchor might be deeper, should have same path then
933 for (size_t i = 0; i < cursor.size(); ++i)
934 if (cursor[i].inset() != anchor[i].inset())
937 // position should be ok.
942 void LCursor::setScreenPos(int x, int y)
944 bool res = bruteFind(x, y, formula()->xlow(), formula()->xhigh(),
945 formula()->ylow(), formula()->yhigh());
947 // this can happen on creation of "math-display"
958 autocorrect() = false;
960 if (!inset()->idxHome(*this))
969 autocorrect() = false;
971 if (!inset()->idxEnd(*this))
978 void LCursor::plainErase()
984 void LCursor::markInsert()
986 cell().insert(pos(), MathAtom(new MathCharInset(0)));
990 void LCursor::markErase()
996 void LCursor::plainInsert(MathAtom const & t)
998 cell().insert(pos(), t);
1003 void LCursor::insert(string const & str)
1005 lyxerr << "LCursor::insert str '" << str << "'" << endl;
1008 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
1009 plainInsert(MathAtom(new MathCharInset(*it)));
1018 void LCursor::insert(char c)
1020 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
1022 plainInsert(MathAtom(new MathCharInset(c)));
1026 void LCursor::insert(MathAtom const & t)
1028 //lyxerr << "LCursor::insert MathAtom: " << endl;
1035 void LCursor::insert(InsetBase * inset)
1038 insert(MathAtom(inset));
1040 text()->insertInset(*this, inset);
1044 void LCursor::niceInsert(string const & t)
1055 void LCursor::niceInsert(MathAtom const & t)
1058 string safe = grabAndEraseSelection();
1060 // enter the new inset and move the contents of the selection if possible
1061 if (t->isActive()) {
1063 // be careful here: don't use 'pushLeft(t)' as this we need to
1064 // push the clone, not the original
1065 pushLeft(nextAtom().nucleus());
1071 void LCursor::insert(MathArray const & ar)
1076 cell().insert(pos(), ar);
1081 bool LCursor::backspace()
1083 autocorrect() = false;
1091 if (inset()->nargs() == 1 && depth() == 1 && lastpos() == 0)
1097 if (inMacroMode()) {
1098 MathUnknownInset * p = activeMacro();
1099 if (p->name().size() > 1) {
1100 p->setName(p->name().substr(0, p->name().size() - 1));
1105 if (pos() != 0 && prevAtom()->nargs() > 0) {
1106 // let's require two backspaces for 'big stuff' and
1107 // highlight on the first
1118 bool LCursor::erase()
1120 autocorrect() = false;
1129 // delete empty cells if possible
1130 if (pos() == lastpos() && inset()->idxDelete(idx()))
1133 // special behaviour when in last position of cell
1134 if (pos() == lastpos()) {
1135 bool one_cell = inset()->nargs() == 1;
1136 if (one_cell && depth() == 1 && lastpos() == 0)
1142 inset()->idxGlue(idx());
1146 if (pos() != lastpos() && inset()->nargs() > 0) {
1160 CursorBase save = cursor_;
1164 autocorrect() = false;
1169 bool LCursor::down()
1172 CursorBase save = cursor_;
1173 if (goUpDown(false))
1176 autocorrect() = false;
1181 void LCursor::macroModeClose()
1185 MathUnknownInset * p = activeMacro();
1187 string s = p->name();
1189 cell().erase(pos());
1191 // do nothing if the macro name is empty
1195 string const name = s.substr(1);
1197 // prevent entering of recursive macros
1198 if (formula()->lyxCode() == InsetOld::MATHMACRO_CODE
1199 && formula()->getInsetName() == name)
1200 lyxerr << "can't enter recursive macro" << endl;
1202 niceInsert(createMathInset(name));
1206 string LCursor::macroName()
1208 return inMacroMode() ? activeMacro()->name() : string();
1212 void LCursor::handleNest(MathAtom const & a, int c)
1214 //lyxerr << "LCursor::handleNest: " << c << endl;
1216 asArray(grabAndEraseSelection(), t.nucleus()->cell(c));
1219 pushLeft(nextAtom().nucleus());
1223 int LCursor::targetX() const
1225 if (x_target() != -1)
1234 MathHullInset * LCursor::formula() const
1236 for (int i = cursor_.size() - 1; i >= 1; --i) {
1237 MathInset * inset = cursor_[i].inset()->asMathInset();
1238 if (inset && inset->asHullInset())
1239 return static_cast<MathHullInset *>(inset);
1245 void LCursor::adjust(pos_type from, int diff)
1249 if (anchor().pos_ > from)
1250 anchor().pos_ += diff;
1251 // just to be on the safe side
1252 // theoretically unecessary
1257 bool LCursor::inMacroMode() const
1261 MathUnknownInset const * p = prevAtom()->asUnknownInset();
1262 return p && !p->final();
1266 MathUnknownInset * LCursor::activeMacro()
1268 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1272 bool LCursor::inMacroArgMode() const
1274 return pos() > 0 && prevAtom()->getChar() == '#';
1278 MathGridInset * LCursor::enclosingGrid(idx_type & idx) const
1280 for (MathInset::difference_type i = depth() - 1; i >= 0; --i) {
1281 MathInset * m = cursor_[i].inset()->asMathInset();
1284 MathGridInset * p = m->asGridInset();
1286 idx = cursor_[i].idx_;
1294 void LCursor::pullArg()
1297 MathArray ar = cell();
1298 if (popLeft() && inMathed()) {
1300 cell().insert(pos(), ar);
1303 //formula()->mutateToText();
1308 void LCursor::touch()
1312 CursorBase::const_iterator it = cursor_.begin();
1313 CursorBase::const_iterator et = cursor_.end();
1314 for ( ; it != et; ++it)
1320 void LCursor::normalize()
1322 if (idx() >= nargs()) {
1323 lyxerr << "this should not really happen - 1: "
1324 << idx() << ' ' << nargs()
1325 << " in: " << inset() << endl;
1327 idx() = min(idx(), lastidx());
1329 if (pos() > lastpos()) {
1330 lyxerr << "this should not really happen - 2: "
1331 << pos() << ' ' << lastpos() << " in idx: " << idx()
1333 WriteStream wi(lyxerr, false, true);
1334 inset()->asMathInset()->write(wi);
1337 pos() = min(pos(), lastpos());
1341 char LCursor::valign()
1344 MathGridInset * p = enclosingGrid(idx);
1345 return p ? p->valign() : '\0';
1349 char LCursor::halign()
1352 MathGridInset * p = enclosingGrid(idx);
1353 return p ? p->halign(idx % p->ncols()) : '\0';
1357 bool LCursor::goUpDown(bool up)
1359 // Be warned: The 'logic' implemented in this function is highly fragile.
1360 // A distance of one pixel or a '<' vs '<=' _really_ matters.
1361 // So fiddle around with it only if you know what you are doing!
1366 // check if we had something else in mind, if not, this is the future goal
1367 if (x_target() == -1)
1372 // try neigbouring script insets
1376 MathScriptInset const * p = prevAtom()->asScriptInset();
1377 if (p && p->has(up)) {
1380 idx() = up; // the superscript has index 1
1382 //lyxerr << "updown: handled by scriptinset to the left" << endl;
1388 if (pos() != lastpos()) {
1389 MathScriptInset const * p = nextAtom()->asScriptInset();
1390 if (p && p->has(up)) {
1394 //lyxerr << "updown: handled by scriptinset to the right" << endl;
1400 // try current cell for e.g. text insets
1401 if (inset()->idxUpDown2(*this, up))
1404 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1409 //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1410 // lyxerr << "updown: handled by brute find in the same cell" << endl;
1414 // try to find an inset that knows better then we
1416 //lyxerr << "updown: We are in " << inset() << " idx: " << idx() << endl;
1418 if (inset()->idxUpDown(*this, up)) {
1419 // try to find best position within this inset
1425 // no such inset found, just take something "above"
1426 //lyxerr << "updown: handled by strange case" << endl;
1432 up ? formula()->ylow() : yo + 4,
1433 up ? yo - 4 : formula()->yhigh()
1437 // any improvement so far?
1440 if (up ? ynew < yo : ynew > yo)
1446 bool LCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1448 CursorBase best_cursor;
1449 double best_dist = 1e10;
1451 CursorBase it = ibegin(formula());
1452 CursorBase et = iend(formula());
1454 // avoid invalid nesting when selecting
1455 if (!selection() || positionable(it, anchor_)) {
1457 CursorSlice & cur = it.back();
1458 cur.inset()->getCursorPos(cur, xo, yo);
1459 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1460 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1461 //lyxerr << "x: " << x << " y: " << y << " d: " << endl;
1462 // '<=' in order to take the last possible position
1463 // this is important for clicking behind \sum in e.g. '\sum_i a'
1464 if (d <= best_dist) {
1476 if (best_dist < 1e10)
1477 cursor_ = best_cursor;
1478 return best_dist < 1e10;
1482 void LCursor::bruteFind2(int x, int y)
1484 double best_dist = 1e10;
1486 CursorBase it = cursor_;
1488 CursorBase et = cursor_;
1489 int n = et.back().asMathInset()->cell(et.back().idx_).size();
1491 for (int i = 0; ; ++i) {
1493 CursorSlice & cur = it.back();
1494 cur.inset()->getCursorPos(cur, xo, yo);
1495 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1496 // '<=' in order to take the last possible position
1497 // this is important for clicking behind \sum in e.g. '\sum_i a'
1498 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
1499 if (d <= best_dist) {
1510 bool LCursor::idxLineLast()
1512 idx() -= idx() % ncols();
1513 idx() += ncols() - 1;
1519 bool LCursor::idxLeft()
1521 return inset()->idxLeft(*this);
1525 bool LCursor::idxRight()
1527 return inset()->idxRight(*this);
1531 bool LCursor::script(bool up)
1533 // Hack to get \\^ and \\_ working
1534 lyxerr << "handling script: up: " << up << endl;
1535 if (inMacroMode() && macroName() == "\\") {
1537 niceInsert(createMathInset("mathcircumflex"));
1544 string safe = grabAndEraseSelection();
1546 // we are in a nucleus of a script inset, move to _our_ script
1547 inset()->asMathInset()->asScriptInset()->ensure(up);
1550 } else if (pos() != 0 && prevAtom()->asScriptInset()) {
1552 nextAtom().nucleus()->asScriptInset()->ensure(up);
1556 } else if (pos() != 0) {
1558 cell()[pos()] = MathAtom(new MathScriptInset(nextAtom(), up));
1563 plainInsert(MathAtom(new MathScriptInset(up)));
1565 nextAtom().nucleus()->asScriptInset()->ensure(up);
1575 bool LCursor::interpret(char c)
1577 //lyxerr << "interpret 2: '" << c << "'" << endl;
1579 if (inMacroArgMode()) {
1585 MathMacroTemplate const * p = formula()->asMacroTemplate();
1586 if (p && 1 <= n && n <= p->numargs())
1587 insert(MathAtom(new MathMacroArgument(c - '0')));
1589 insert(createMathInset("#"));
1590 interpret(c); // try again
1597 if (inMacroMode()) {
1598 string name = macroName();
1599 //lyxerr << "interpret name: '" << name << "'" << endl;
1602 activeMacro()->setName(activeMacro()->name() + c);
1606 // handle 'special char' macros
1611 if (currentMode() == MathInset::TEXT_MODE)
1612 niceInsert(createMathInset("textbackslash"));
1614 niceInsert(createMathInset("backslash"));
1615 } else if (c == '{') {
1616 niceInsert(MathAtom(new MathBraceInset));
1618 niceInsert(createMathInset(string(1, c)));
1623 // leave macro mode and try again if necessary
1626 niceInsert(MathAtom(new MathBraceInset));
1632 // This is annoying as one has to press <space> far too often.
1636 // leave autocorrect mode if necessary
1637 if (autocorrect() && c == ' ') {
1638 autocorrect() = false;
1643 // just clear selection on pressing the space bar
1644 if (selection() && c == ' ') {
1645 selection() = false;
1652 //lyxerr << "starting with macro" << endl;
1653 insert(MathAtom(new MathUnknownInset("\\", false)));
1658 if (currentMode() == MathInset::TEXT_MODE)
1664 if (currentMode() == MathInset::TEXT_MODE) {
1665 // insert spaces in text mode,
1666 // but suppress direct insertion of two spaces in a row
1667 // the still allows typing '<space>a<space>' and deleting the 'a', but
1668 // it is better than nothing...
1669 if (!pos() != 0 || prevAtom()->getChar() != ' ')
1673 if (pos() != 0 && prevAtom()->asSpaceInset()) {
1674 prevAtom().nucleus()->asSpaceInset()->incSpace();
1679 // if are at the very end, leave the formula
1680 return pos() != lastpos();
1693 if (c == '{' || c == '}' || c == '#' || c == '&' || c == '$') {
1694 niceInsert(createMathInset(string(1, c)));
1699 niceInsert(MathAtom(new MathCommentInset));
1703 // try auto-correction
1704 //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1707 // no special circumstances, so insert the character without any fuss
1709 autocorrect() = true;
1714 void LCursor::lockToggle()
1716 if (pos() != lastpos()) {
1717 // toggle previous inset ...
1718 nextAtom().nucleus()->lock(!nextAtom()->lock());
1719 } else if (popLeft() && pos() != lastpos()) {
1720 // ... or enclosing inset if we are in the last inset position
1721 nextAtom().nucleus()->lock(!nextAtom()->lock());
1727 CursorSlice LCursor::normalAnchor()
1729 if (anchor_.size() < depth()) {
1731 lyxerr << "unusual Anchor size" << endl;
1733 //lyx::BOOST_ASSERT(Anchor_.size() >= cursor.depth());
1734 // use Anchor on the same level as Cursor
1735 CursorSlice normal = anchor_[current_];
1737 if (depth() < anchor_.size() && !(normal < xx())) {
1738 // anchor is behind cursor -> move anchor behind the inset
1747 DispatchResult dispatch(LCursor & cur, FuncRequest const & cmd)
1749 // mouse clicks are somewhat special
1751 switch (cmd.action) {
1752 case LFUN_MOUSE_PRESS:
1753 case LFUN_MOUSE_MOTION:
1754 case LFUN_MOUSE_RELEASE:
1755 case LFUN_MOUSE_DOUBLE: {
1756 CursorSlice & pos = cursor_.back();
1760 if (x < cmd.x && pos() != 0) {
1761 DispatchResult const res = prevAtom().nucleus()->dispatch(cmd);
1762 if (res.dispatched())
1765 if (x > cmd.x && pos() != lastpos()) {
1766 DispatchResult const res = inset()->dispatch(cmd);
1767 if (res.dispatched())
1778 void LCursor::handleFont(string const & font)
1780 lyxerr << "LCursor::handleFont: " << font << endl;
1784 safe = grabAndEraseSelection();
1787 if (lastpos() != 0) {
1788 // something left in the cell
1790 // cursor in first position
1792 } else if (pos() == lastpos()) {
1793 // cursor in last position
1796 // cursor in between. split cell
1797 MathArray::iterator bt = cell().begin();
1798 MathAtom at = createMathInset(font);
1799 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1800 cell().erase(bt, bt + pos());
1805 // nothing left in the cell
1813 void LCursor::releaseMathCursor()
1816 formula()->insetUnlock(bv());
1820 bool LCursor::inMathed() const
1826 bool LCursor::inTexted() const
1832 InsetBase * LCursor::nextInset()
1834 if (pos() == lastpos())
1837 return nextAtom().nucleus();
1838 return paragraph().isInset(pos()) ? paragraph().getInset(pos()) : 0;
1842 InsetBase * LCursor::prevInset()
1847 return prevAtom().nucleus();
1848 return paragraph().isInset(pos() - 1) ? paragraph().getInset(pos() - 1) : 0;
1852 InsetBase const * LCursor::prevInset() const
1857 return prevAtom().nucleus();
1858 return paragraph().isInset(pos() - 1) ? paragraph().getInset(pos() - 1) : 0;
1862 void LCursor::message(string const & msg) const
1864 bv().owner()->getLyXFunc().setMessage(msg);
1868 void LCursor::errorMessage(string const & msg) const
1870 bv().owner()->getLyXFunc().setErrorMessage(msg);
1874 string LCursor::selectionAsString(bool label) const
1880 Buffer const & buffer = *bv().buffer();
1882 // should be const ...
1883 ParagraphList::iterator startpit = text()->getPar(selBegin());
1884 ParagraphList::iterator endpit = text()->getPar(selEnd());
1885 size_t const startpos = selBegin().pos();
1886 size_t const endpos = selEnd().pos();
1888 if (startpit == endpit)
1889 return startpit->asString(buffer, startpos, endpos, label);
1891 // First paragraph in selection
1893 startpit->asString(buffer, startpos, startpit->size(), label) + "\n\n";
1895 // The paragraphs in between (if any)
1896 ParagraphList::iterator pit = startpit;
1897 for (++pit; pit != endpit; ++pit)
1898 result += pit->asString(buffer, 0, pit->size(), label) + "\n\n";
1900 // Last paragraph in selection
1901 result += endpit->asString(buffer, 0, endpos, label);
1911 string LCursor::currentState()
1914 std::ostringstream os;
1918 return text()->currentState(*this);
1922 // only used by the spellchecker
1923 void LCursor::replaceWord(string const & replacestring)
1925 LyXText * t = text();
1927 t->replaceSelectionWithString(*this, replacestring);
1928 t->setSelectionRange(*this, replacestring.length());
1930 // Go back so that replacement string is also spellchecked
1931 for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
1932 t->cursorLeft(*this, true);