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;
86 for (current_ = cursor_.size() - 1; current_ >= 1; --current_) {
87 // the inset's dispatch() is supposed to reset the update and
88 // val flags if necessary
89 inset()->dispatch(*this, cmd);
91 // "Mutate" the request for semi-handled requests that need
92 // additional handling in outer levels.
93 switch (disp_.val()) {
95 // the inset handled the event fully
96 current_ = cursor_.size() - 1;
97 return DispatchResult(true, true);
99 // the inset handled the event partially
100 cmd = FuncRequest(LFUN_FINISHED_LEFT);
103 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
106 cmd = FuncRequest(LFUN_FINISHED_UP);
109 cmd = FuncRequest(LFUN_FINISHED_DOWN);
112 //lyxerr << "not handled on level " << current_
113 // << " val: " << disp_.val() << endl;
117 BOOST_ASSERT(current_ == 0);
118 bv_->text()->dispatch(*this, cmd);
119 //lyxerr << " result: " << res.val() << endl;
120 current_ = cursor_.size() - 1;
125 void LCursor::push(InsetBase * inset)
127 lyxerr << "LCursor::push() inset: " << inset << endl;
128 cursor_.push_back(CursorSlice(inset));
129 anchor_.push_back(CursorSlice(inset));
135 void LCursor::pop(int depth)
137 while (int(cursor_.size()) > depth + 1)
139 lyxerr << "LCursor::pop() result: " << *this << endl;
145 BOOST_ASSERT(cursor_.size() >= 1);
148 current_ = cursor_.size() - 1;
152 void LCursor::pushLeft(InsetBase * p)
154 BOOST_ASSERT(!cursor_.empty());
155 //lyxerr << "Entering inset " << t << " left" << endl;
161 bool LCursor::popLeft()
163 BOOST_ASSERT(!cursor_.empty());
164 //lyxerr << "Leaving inset to the left" << endl;
167 inset()->notifyCursorLeaves(idx());
170 inset()->notifyCursorLeaves(idx());
176 bool LCursor::popRight()
178 BOOST_ASSERT(!cursor_.empty());
179 //lyxerr << "Leaving inset to the right" << endl;
182 inset()->notifyCursorLeaves(idx());
185 inset()->notifyCursorLeaves(idx());
192 CursorSlice & LCursor::current()
194 BOOST_ASSERT(!cursor_.empty());
195 //lyxerr << "accessing cursor slice " << current_
196 // << ": " << cursor_[current_] << endl;
197 return cursor_[current_];
201 CursorSlice const & LCursor::current() const
203 //lyxerr << "accessing cursor slice " << current_
204 // << ": " << cursor_[current_] << endl;
205 return cursor_[current_];
209 int LCursor::currentMode()
211 BOOST_ASSERT(!cursor_.empty());
212 for (int i = cursor_.size() - 1; i >= 1; --i) {
213 int res = cursor_[i].inset()->currentMode();
214 if (res != MathInset::UNDECIDED_MODE)
217 return MathInset::TEXT_MODE;
221 LyXText * LCursor::innerText() const
223 BOOST_ASSERT(!cursor_.empty());
224 if (cursor_.size() > 1) {
225 // go up until first non-0 text is hit
226 // (innermost text is 0 in mathed)
227 for (int i = cursor_.size() - 1; i >= 1; --i)
228 if (cursor_[i].text())
229 return cursor_[i].text();
235 CursorSlice const & LCursor::innerTextSlice() const
237 BOOST_ASSERT(!cursor_.empty());
238 if (cursor_.size() > 1) {
239 // go up until first non-0 text is hit
240 // (innermost text is 0 in mathed)
241 for (int i = cursor_.size() - 1; i >= 1; --i)
242 if (cursor_[i].text())
249 void LCursor::updatePos()
251 BOOST_ASSERT(!cursor_.empty());
252 if (cursor_.size() > 1)
253 cached_y_ = bv_->top_y() + cursor_.back().inset()->yo();
254 //cached_y_ = cursor_.back().inset()->yo();
258 void LCursor::getDim(int & asc, int & des) const
260 BOOST_ASSERT(!cursor_.empty());
262 BOOST_ASSERT(inset());
263 BOOST_ASSERT(inset()->asMathInset());
264 //inset()->asMathInset()->getCursorDim(asc, des);
268 Row const & row = textRow();
269 asc = row.baseline();
270 des = row.height() - asc;
275 void LCursor::getPos(int & x, int & y) const
277 BOOST_ASSERT(!cursor_.empty());
280 if (cursor_.size() == 1) {
281 x = bv_->text()->cursorX(cursor_.front());
282 y = bv_->text()->cursorY(cursor_.front());
285 lyxerr << "#### LCursor::getPos: " << *this << endl;
286 BOOST_ASSERT(inset());
288 inset()->getCursorPos(cursor_.back(), x, y);
289 // getCursorPos gives _screen_ coordinates. We need to add
290 // top_y to get document coordinates. This is hidden in cached_y_.
291 //y += cached_y_ - inset()->yo();
292 // The rest is non-obvious. The reason we have to have these
293 // extra computation is that the getCursorPos() calls rely
294 // on the inset's own knowledge of its screen position.
295 // If we scroll up or down in a big enough increment,
296 // inset->draw() is not called: this doesn't update
297 // inset.yo_, so getCursor() returns an old value.
300 //lyxerr << "#### LCursor::getPos: " << *this
301 // << " x: " << x << " y: " << y << endl;
305 void LCursor::paste(string const & data)
307 dispatch(FuncRequest(LFUN_PASTE, data));
311 InsetBase * LCursor::innerInsetOfType(int code) const
313 for (int i = cursor_.size() - 1; i >= 1; --i)
314 if (cursor_[i].inset_->lyxCode() == code)
315 return cursor_[i].inset_;
320 InsetTabular * LCursor::innerInsetTabular() const
322 return static_cast<InsetTabular *>(innerInsetOfType(InsetBase::TABULAR_CODE));
326 void LCursor::resetAnchor()
332 BufferView & LCursor::bv() const
338 MathAtom const & LCursor::prevAtom() const
340 BOOST_ASSERT(pos() > 0);
341 return cell()[pos() - 1];
345 MathAtom & LCursor::prevAtom()
347 BOOST_ASSERT(pos() > 0);
348 return cell()[pos() - 1];
352 MathAtom const & LCursor::nextAtom() const
354 BOOST_ASSERT(pos() < lastpos());
355 return cell()[pos()];
359 MathAtom & LCursor::nextAtom()
361 BOOST_ASSERT(pos() < lastpos());
362 return cell()[pos()];
366 bool LCursor::posLeft()
375 bool LCursor::posRight()
377 if (pos() == lastpos())
384 CursorSlice & LCursor::anchor()
386 return anchor_.back();
390 CursorSlice const & LCursor::anchor() const
392 return anchor_.back();
396 CursorSlice const & LCursor::selBegin() const
399 return cursor_.back();
400 return anchor() < cursor_.back() ? anchor() : cursor_.back();
404 CursorSlice & LCursor::selBegin()
407 return cursor_.back();
408 // can't use std::min as this returns a const ref
409 return anchor() < cursor_.back() ? anchor() : cursor_.back();
413 CursorSlice const & LCursor::selEnd() const
416 return cursor_.back();
417 return anchor() > cursor_.back() ? anchor() : cursor_.back();
421 CursorSlice & LCursor::selEnd()
424 return cursor_.back();
425 // can't use std::min as this returns a const ref
426 return anchor() > cursor_.back() ? anchor() : cursor_.back();
430 void LCursor::setSelection()
433 // a selection with no contents is not a selection
434 if (par() == anchor().par() && pos() == anchor().pos())
439 void LCursor::setSelection(CursorBase const & where, size_t n)
448 void LCursor::clearSelection()
457 int & LCursor::x_target()
463 int LCursor::x_target() const
469 void LCursor::clearTargetX()
475 LyXText * LCursor::text() const
477 return current_ ? current().text() : bv_->text();
481 Paragraph & LCursor::paragraph()
483 BOOST_ASSERT(inTexted());
484 return current_ ? current().paragraph() : *bv_->text()->getPar(par());
488 Paragraph const & LCursor::paragraph() const
490 BOOST_ASSERT(inTexted());
491 return current_ ? current().paragraph() : *bv_->text()->getPar(par());
495 Row & LCursor::textRow()
497 return *paragraph().getRow(pos());
501 Row const & LCursor::textRow() const
503 return *paragraph().getRow(pos());
507 LCursor::par_type LCursor::lastpar() const
509 return inMathed() ? 0 : text()->paragraphs().size() - 1;
513 LCursor::pos_type LCursor::lastpos() const
515 InsetBase * inset = current().inset();
516 return inset && inset->asMathInset() ? cell().size() : paragraph().size();
520 LCursor::row_type LCursor::crow() const
522 return paragraph().row(pos());
526 LCursor::row_type LCursor::lastcrow() const
528 return paragraph().rows.size();
532 size_t LCursor::nargs() const
534 // assume 1x1 grid for 'plain text'
535 return current_ ? current().nargs() : 1;
539 size_t LCursor::ncols() const
541 // assume 1x1 grid for 'plain text'
542 return current_ ? current().ncols() : 1;
546 size_t LCursor::nrows() const
548 // assume 1x1 grid for 'plain text'
549 return current_ ? current().nrows() : 1;
553 LCursor::row_type LCursor::row() const
555 BOOST_ASSERT(current_ > 0);
556 return current().row();
560 LCursor::col_type LCursor::col() const
562 BOOST_ASSERT(current_ > 0);
563 return current().col();
567 MathArray const & LCursor::cell() const
569 BOOST_ASSERT(current_ > 0);
570 return current().cell();
574 MathArray & LCursor::cell()
576 BOOST_ASSERT(current_ > 0);
577 return current().cell();
581 void LCursor::info(std::ostream & os) const
583 for (int i = 1, n = depth(); i < n; ++i) {
584 cursor_[i].inset()->infoize(os);
588 prevInset()->infoize2(os);
589 // overwite old message
596 void region(CursorSlice const & i1, CursorSlice const & i2,
597 LCursor::row_type & r1, LCursor::row_type & r2,
598 LCursor::col_type & c1, LCursor::col_type & c2)
600 InsetBase * p = i1.inset();
601 c1 = p->col(i1.idx_);
602 c2 = p->col(i2.idx_);
605 r1 = p->row(i1.idx_);
606 r2 = p->row(i2.idx_);
614 string LCursor::grabSelection()
619 CursorSlice i1 = selBegin();
620 CursorSlice i2 = selEnd();
622 if (i1.idx_ == i2.idx_) {
623 if (i1.inset()->asMathInset()) {
624 MathArray::const_iterator it = i1.cell().begin();
625 return asString(MathArray(it + i1.pos_, it + i2.pos_));
627 return "unknown selection 1";
633 region(i1, i2, r1, r2, c1, c2);
636 if (i1.inset()->asMathInset()) {
637 for (row_type row = r1; row <= r2; ++row) {
640 for (col_type col = c1; col <= c2; ++col) {
643 data += asString(i1.asMathInset()->cell(i1.asMathInset()->index(row, col)));
647 data = "unknown selection 2";
653 void LCursor::eraseSelection()
655 //lyxerr << "LCursor::eraseSelection" << endl;
656 CursorSlice const & i1 = selBegin();
657 CursorSlice const & i2 = selEnd();
659 if (i1.inset()->asMathInset()) {
660 if (i1.idx_ == i2.idx_) {
661 i1.cell().erase(i1.pos_, i2.pos_);
663 MathInset * p = i1.asMathInset();
666 region(i1, i2, r1, r2, c1, c2);
667 for (row_type row = r1; row <= r2; ++row)
668 for (col_type col = c1; col <= c2; ++col)
669 p->cell(p->index(row, col)).clear();
673 lyxerr << "can't erase this selection 1" << endl;
675 //lyxerr << "LCursor::eraseSelection end" << endl;
679 string LCursor::grabAndEraseSelection()
683 string res = grabSelection();
690 void LCursor::selClear()
697 void LCursor::selCopy()
700 theCutBuffer.push(grabSelection());
703 //theCutBuffer.erase();
708 void LCursor::selCut()
710 theCutBuffer.push(grabAndEraseSelection());
714 void LCursor::selDel()
716 //lyxerr << "LCursor::selDel" << endl;
724 void LCursor::selPaste(size_t n)
727 if (n < theCutBuffer.size())
728 paste(theCutBuffer[n]);
734 void LCursor::selHandle(bool sel)
736 //lyxerr << "LCursor::selHandle" << endl;
737 if (sel == selection())
744 void LCursor::selClearOrDel()
746 //lyxerr << "LCursor::selClearOrDel" << endl;
747 if (lyxrc.auto_region_delete)
754 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
756 for (size_t i = 0, n = cur.cursor_.size(); i != n; ++i)
757 os << " " << cur.cursor_[i] << " | " << cur.anchor_[i] << "\n";
758 os << " current: " << cur.current_ << endl;
759 os << " selection: " << cur.selection_ << endl;
771 void increment(CursorBase & it)
773 CursorSlice & top = it.back();
774 MathArray & ar = top.asMathInset()->cell(top.idx_);
776 // move into the current inset if possible
777 // it is impossible for pos() == size()!
779 if (top.pos() != top.lastpos())
780 n = (ar.begin() + top.pos_)->nucleus();
781 if (n && n->isActive()) {
782 it.push_back(CursorSlice(n));
786 // otherwise move on one cell back if possible
787 if (top.pos() < top.lastpos()) {
788 // pos() == lastpos() is valid!
793 // otherwise try to move on one cell if possible
794 while (top.idx() < top.lastidx()) {
796 if (top.asMathInset()->validCell(top.idx_)) {
802 // otherwise leave array, move on one back
803 // this might yield pos() == size(), but that's a ok.
805 // it certainly invalidates top
810 CursorBase ibegin(InsetBase * p)
813 it.push_back(CursorSlice(p));
818 CursorBase iend(InsetBase * p)
821 it.push_back(CursorSlice(p));
822 CursorSlice & cur = it.back();
823 cur.idx() = cur.lastidx();
824 cur.pos() = cur.lastpos();
831 ///////////////////////////////////////////////////////////////////
833 // The part below is the non-integrated rest of the original math
834 // cursor. This should be either generalized for texted or moved
835 // back to the math insets.
837 ///////////////////////////////////////////////////////////////////
839 #include "mathed/math_braceinset.h"
840 #include "mathed/math_charinset.h"
841 #include "mathed/math_commentinset.h"
842 #include "mathed/math_factory.h"
843 #include "mathed/math_gridinset.h"
844 #include "mathed/math_macroarg.h"
845 #include "mathed/math_macrotemplate.h"
846 #include "mathed/math_mathmlstream.h"
847 #include "mathed/math_scriptinset.h"
848 #include "mathed/math_spaceinset.h"
849 #include "mathed/math_support.h"
850 #include "mathed/math_unknowninset.h"
852 //#define FILEDEBUG 1
855 bool LCursor::isInside(InsetBase const * p)
857 for (unsigned i = 0; i < depth(); ++i)
858 if (cursor_[i].inset() == p)
864 bool LCursor::openable(MathAtom const & t)
875 // we can't move into anything new during selection
876 if (depth() == anchor_.size())
878 if (!ptr_cmp(t.nucleus(), anchor_[depth()].inset()))
885 bool LCursor::inNucleus()
887 return inset()->asMathInset()->asScriptInset() && idx() == 2;
893 autocorrect() = false;
900 if (pos() != 0 && openable(prevAtom())) {
902 push(nextAtom().nucleus());
903 inset()->idxLast(*this);
907 return posLeft() || idxLeft() || popLeft() || selection();
911 bool LCursor::right()
913 autocorrect() = false;
920 if (pos() != lastpos() && openable(nextAtom())) {
921 pushLeft(nextAtom().nucleus());
922 inset()->idxFirst(*this);
926 return posRight() || idxRight() || popRight() || selection();
930 bool positionable(CursorBase const & cursor, CursorBase const & anchor)
932 // avoid deeper nested insets when selecting
933 if (cursor.size() > anchor.size())
936 // anchor might be deeper, should have same path then
937 for (size_t i = 0; i < cursor.size(); ++i)
938 if (cursor[i].inset() != anchor[i].inset())
941 // position should be ok.
946 void LCursor::setScreenPos(int x, int y)
948 bool res = bruteFind(x, y, formula()->xlow(), formula()->xhigh(),
949 formula()->ylow(), formula()->yhigh());
951 // this can happen on creation of "math-display"
962 autocorrect() = false;
964 if (!inset()->idxHome(*this))
973 autocorrect() = false;
975 if (!inset()->idxEnd(*this))
982 void LCursor::plainErase()
988 void LCursor::markInsert()
990 cell().insert(pos(), MathAtom(new MathCharInset(0)));
994 void LCursor::markErase()
1000 void LCursor::plainInsert(MathAtom const & t)
1002 cell().insert(pos(), t);
1007 void LCursor::insert(string const & str)
1009 lyxerr << "LCursor::insert str '" << str << "'" << endl;
1012 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
1013 plainInsert(MathAtom(new MathCharInset(*it)));
1022 void LCursor::insert(char c)
1024 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
1026 plainInsert(MathAtom(new MathCharInset(c)));
1030 void LCursor::insert(MathAtom const & t)
1032 //lyxerr << "LCursor::insert MathAtom: " << endl;
1039 void LCursor::insert(InsetBase * inset)
1042 insert(MathAtom(inset));
1044 text()->insertInset(*this, inset);
1048 void LCursor::niceInsert(string const & t)
1059 void LCursor::niceInsert(MathAtom const & t)
1062 string safe = grabAndEraseSelection();
1064 // enter the new inset and move the contents of the selection if possible
1065 if (t->isActive()) {
1067 // be careful here: don't use 'pushLeft(t)' as this we need to
1068 // push the clone, not the original
1069 pushLeft(nextAtom().nucleus());
1075 void LCursor::insert(MathArray const & ar)
1080 cell().insert(pos(), ar);
1085 bool LCursor::backspace()
1087 autocorrect() = false;
1095 if (inset()->nargs() == 1 && depth() == 1 && lastpos() == 0)
1101 if (inMacroMode()) {
1102 MathUnknownInset * p = activeMacro();
1103 if (p->name().size() > 1) {
1104 p->setName(p->name().substr(0, p->name().size() - 1));
1109 if (pos() != 0 && prevAtom()->nargs() > 0) {
1110 // let's require two backspaces for 'big stuff' and
1111 // highlight on the first
1122 bool LCursor::erase()
1124 autocorrect() = false;
1133 // delete empty cells if possible
1134 if (pos() == lastpos() && inset()->idxDelete(idx()))
1137 // special behaviour when in last position of cell
1138 if (pos() == lastpos()) {
1139 bool one_cell = inset()->nargs() == 1;
1140 if (one_cell && depth() == 1 && lastpos() == 0)
1146 inset()->idxGlue(idx());
1150 if (pos() != lastpos() && inset()->nargs() > 0) {
1164 CursorBase save = cursor_;
1168 autocorrect() = false;
1173 bool LCursor::down()
1176 CursorBase save = cursor_;
1177 if (goUpDown(false))
1180 autocorrect() = false;
1185 void LCursor::macroModeClose()
1189 MathUnknownInset * p = activeMacro();
1191 string s = p->name();
1193 cell().erase(pos());
1195 // do nothing if the macro name is empty
1199 string const name = s.substr(1);
1201 // prevent entering of recursive macros
1202 if (formula()->lyxCode() == InsetOld::MATHMACRO_CODE
1203 && formula()->getInsetName() == name)
1204 lyxerr << "can't enter recursive macro" << endl;
1206 niceInsert(createMathInset(name));
1210 string LCursor::macroName()
1212 return inMacroMode() ? activeMacro()->name() : string();
1216 void LCursor::handleNest(MathAtom const & a, int c)
1218 //lyxerr << "LCursor::handleNest: " << c << endl;
1220 asArray(grabAndEraseSelection(), t.nucleus()->cell(c));
1223 pushLeft(nextAtom().nucleus());
1227 int LCursor::targetX() const
1229 if (x_target() != -1)
1238 MathHullInset * LCursor::formula() const
1240 for (int i = cursor_.size() - 1; i >= 1; --i) {
1241 MathInset * inset = cursor_[i].inset()->asMathInset();
1242 if (inset && inset->asHullInset())
1243 return static_cast<MathHullInset *>(inset);
1249 void LCursor::adjust(pos_type from, int diff)
1253 if (anchor().pos_ > from)
1254 anchor().pos_ += diff;
1255 // just to be on the safe side
1256 // theoretically unecessary
1261 bool LCursor::inMacroMode() const
1265 MathUnknownInset const * p = prevAtom()->asUnknownInset();
1266 return p && !p->final();
1270 MathUnknownInset * LCursor::activeMacro()
1272 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1276 bool LCursor::inMacroArgMode() const
1278 return pos() > 0 && prevAtom()->getChar() == '#';
1282 MathGridInset * LCursor::enclosingGrid(idx_type & idx) const
1284 for (MathInset::difference_type i = depth() - 1; i >= 0; --i) {
1285 MathInset * m = cursor_[i].inset()->asMathInset();
1288 MathGridInset * p = m->asGridInset();
1290 idx = cursor_[i].idx_;
1298 void LCursor::pullArg()
1301 MathArray ar = cell();
1302 if (popLeft() && inMathed()) {
1304 cell().insert(pos(), ar);
1307 //formula()->mutateToText();
1312 void LCursor::touch()
1316 CursorBase::const_iterator it = cursor_.begin();
1317 CursorBase::const_iterator et = cursor_.end();
1318 for ( ; it != et; ++it)
1324 void LCursor::normalize()
1326 if (idx() >= nargs()) {
1327 lyxerr << "this should not really happen - 1: "
1328 << idx() << ' ' << nargs()
1329 << " in: " << inset() << endl;
1331 idx() = min(idx(), lastidx());
1333 if (pos() > lastpos()) {
1334 lyxerr << "this should not really happen - 2: "
1335 << pos() << ' ' << lastpos() << " in idx: " << idx()
1337 WriteStream wi(lyxerr, false, true);
1338 inset()->asMathInset()->write(wi);
1341 pos() = min(pos(), lastpos());
1345 char LCursor::valign()
1348 MathGridInset * p = enclosingGrid(idx);
1349 return p ? p->valign() : '\0';
1353 char LCursor::halign()
1356 MathGridInset * p = enclosingGrid(idx);
1357 return p ? p->halign(idx % p->ncols()) : '\0';
1361 bool LCursor::goUpDown(bool up)
1363 // Be warned: The 'logic' implemented in this function is highly
1364 // fragile. A distance of one pixel or a '<' vs '<=' _really
1365 // matters. So fiddle around with it only if you think you know
1366 // what you are doing!
1371 // check if we had something else in mind, if not, this is the future goal
1372 if (x_target() == -1)
1377 // try neigbouring script insets
1381 MathScriptInset const * p = prevAtom()->asScriptInset();
1382 if (p && p->has(up)) {
1385 idx() = up; // the superscript has index 1
1387 //lyxerr << "updown: handled by scriptinset to the left" << endl;
1393 if (pos() != lastpos()) {
1394 MathScriptInset const * p = nextAtom()->asScriptInset();
1395 if (p && p->has(up)) {
1399 //lyxerr << "updown: handled by scriptinset to the right" << endl;
1405 // try current cell for e.g. text insets
1406 if (inset()->idxUpDown2(*this, up))
1409 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1414 //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1415 // lyxerr << "updown: handled by brute find in the same cell" << endl;
1419 // try to find an inset that knows better then we
1421 //lyxerr << "updown: We are in " << inset() << " idx: " << idx() << endl;
1423 if (inset()->idxUpDown(*this, up)) {
1424 // try to find best position within this inset
1430 // no such inset found, just take something "above"
1431 //lyxerr << "updown: handled by strange case" << endl;
1437 up ? formula()->ylow() : yo + 4,
1438 up ? yo - 4 : formula()->yhigh()
1442 // any improvement so far?
1445 if (up ? ynew < yo : ynew > yo)
1451 bool LCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1453 CursorBase best_cursor;
1454 double best_dist = 1e10;
1456 CursorBase it = ibegin(formula());
1457 CursorBase et = iend(formula());
1459 // avoid invalid nesting when selecting
1460 if (!selection() || positionable(it, anchor_)) {
1462 CursorSlice & cur = it.back();
1463 cur.inset()->getCursorPos(cur, xo, yo);
1464 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1465 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1466 //lyxerr << "x: " << x << " y: " << y << " d: " << endl;
1467 // '<=' in order to take the last possible position
1468 // this is important for clicking behind \sum in e.g. '\sum_i a'
1469 if (d <= best_dist) {
1481 if (best_dist < 1e10)
1482 cursor_ = best_cursor;
1483 return best_dist < 1e10;
1487 void LCursor::bruteFind2(int x, int y)
1489 double best_dist = 1e10;
1491 CursorBase it = cursor_;
1492 it.back().pos() = 0;
1493 CursorBase et = cursor_;
1494 et.back().pos() = et.back().asMathInset()->cell(et.back().idx_).size();
1495 for (int i = 0; ; ++i) {
1497 CursorSlice & cur = it.back();
1498 cur.inset()->getCursorPos(cur, xo, yo);
1499 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1500 // '<=' in order to take the last possible position
1501 // this is important for clicking behind \sum in e.g. '\sum_i a'
1502 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
1503 if (d <= best_dist) {
1514 bool LCursor::idxLineLast()
1516 idx() -= idx() % ncols();
1517 idx() += ncols() - 1;
1523 bool LCursor::idxLeft()
1525 return inset()->idxLeft(*this);
1529 bool LCursor::idxRight()
1531 return inset()->idxRight(*this);
1535 bool LCursor::script(bool up)
1537 // Hack to get \\^ and \\_ working
1538 lyxerr << "handling script: up: " << up << endl;
1539 if (inMacroMode() && macroName() == "\\") {
1541 niceInsert(createMathInset("mathcircumflex"));
1548 string safe = grabAndEraseSelection();
1550 // we are in a nucleus of a script inset, move to _our_ script
1551 inset()->asMathInset()->asScriptInset()->ensure(up);
1554 } else if (pos() != 0 && prevAtom()->asScriptInset()) {
1556 nextAtom().nucleus()->asScriptInset()->ensure(up);
1560 } else if (pos() != 0) {
1562 cell()[pos()] = MathAtom(new MathScriptInset(nextAtom(), up));
1567 plainInsert(MathAtom(new MathScriptInset(up)));
1569 nextAtom().nucleus()->asScriptInset()->ensure(up);
1579 bool LCursor::interpret(char c)
1581 //lyxerr << "interpret 2: '" << c << "'" << endl;
1583 if (inMacroArgMode()) {
1589 MathMacroTemplate const * p = formula()->asMacroTemplate();
1590 if (p && 1 <= n && n <= p->numargs())
1591 insert(MathAtom(new MathMacroArgument(c - '0')));
1593 insert(createMathInset("#"));
1594 interpret(c); // try again
1601 if (inMacroMode()) {
1602 string name = macroName();
1603 //lyxerr << "interpret name: '" << name << "'" << endl;
1606 activeMacro()->setName(activeMacro()->name() + c);
1610 // handle 'special char' macros
1615 if (currentMode() == MathInset::TEXT_MODE)
1616 niceInsert(createMathInset("textbackslash"));
1618 niceInsert(createMathInset("backslash"));
1619 } else if (c == '{') {
1620 niceInsert(MathAtom(new MathBraceInset));
1622 niceInsert(createMathInset(string(1, c)));
1627 // leave macro mode and try again if necessary
1630 niceInsert(MathAtom(new MathBraceInset));
1636 // This is annoying as one has to press <space> far too often.
1640 // leave autocorrect mode if necessary
1641 if (autocorrect() && c == ' ') {
1642 autocorrect() = false;
1647 // just clear selection on pressing the space bar
1648 if (selection() && c == ' ') {
1649 selection() = false;
1656 //lyxerr << "starting with macro" << endl;
1657 insert(MathAtom(new MathUnknownInset("\\", false)));
1662 if (currentMode() == MathInset::TEXT_MODE)
1668 if (currentMode() == MathInset::TEXT_MODE) {
1669 // insert spaces in text mode,
1670 // but suppress direct insertion of two spaces in a row
1671 // the still allows typing '<space>a<space>' and deleting the 'a', but
1672 // it is better than nothing...
1673 if (!pos() != 0 || prevAtom()->getChar() != ' ')
1677 if (pos() != 0 && prevAtom()->asSpaceInset()) {
1678 prevAtom().nucleus()->asSpaceInset()->incSpace();
1683 // if are at the very end, leave the formula
1684 return pos() != lastpos();
1697 if (c == '{' || c == '}' || c == '#' || c == '&' || c == '$') {
1698 niceInsert(createMathInset(string(1, c)));
1703 niceInsert(MathAtom(new MathCommentInset));
1707 // try auto-correction
1708 //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1711 // no special circumstances, so insert the character without any fuss
1713 autocorrect() = true;
1718 void LCursor::lockToggle()
1720 if (pos() != lastpos()) {
1721 // toggle previous inset ...
1722 nextAtom().nucleus()->lock(!nextAtom()->lock());
1723 } else if (popLeft() && pos() != lastpos()) {
1724 // ... or enclosing inset if we are in the last inset position
1725 nextAtom().nucleus()->lock(!nextAtom()->lock());
1731 CursorSlice LCursor::normalAnchor()
1733 if (anchor_.size() < depth()) {
1735 lyxerr << "unusual Anchor size" << endl;
1737 //lyx::BOOST_ASSERT(Anchor_.size() >= cursor.depth());
1738 // use Anchor on the same level as Cursor
1739 CursorSlice normal = anchor_[current_];
1741 if (depth() < anchor_.size() && !(normal < xx())) {
1742 // anchor is behind cursor -> move anchor behind the inset
1751 DispatchResult dispatch(LCursor & cur, FuncRequest const & cmd)
1753 // mouse clicks are somewhat special
1755 switch (cmd.action) {
1756 case LFUN_MOUSE_PRESS:
1757 case LFUN_MOUSE_MOTION:
1758 case LFUN_MOUSE_RELEASE:
1759 case LFUN_MOUSE_DOUBLE: {
1760 CursorSlice & pos = cursor_.back();
1764 if (x < cmd.x && pos() != 0) {
1765 DispatchResult const res = prevAtom().nucleus()->dispatch(cmd);
1766 if (res.dispatched())
1769 if (x > cmd.x && pos() != lastpos()) {
1770 DispatchResult const res = inset()->dispatch(cmd);
1771 if (res.dispatched())
1782 void LCursor::handleFont(string const & font)
1784 lyxerr << "LCursor::handleFont: " << font << endl;
1788 safe = grabAndEraseSelection();
1791 if (lastpos() != 0) {
1792 // something left in the cell
1794 // cursor in first position
1796 } else if (pos() == lastpos()) {
1797 // cursor in last position
1800 // cursor in between. split cell
1801 MathArray::iterator bt = cell().begin();
1802 MathAtom at = createMathInset(font);
1803 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1804 cell().erase(bt, bt + pos());
1809 // nothing left in the cell
1817 bool LCursor::inMathed() const
1823 bool LCursor::inTexted() const
1829 InsetBase * LCursor::nextInset()
1831 if (pos() == lastpos())
1834 return nextAtom().nucleus();
1835 return paragraph().isInset(pos()) ? paragraph().getInset(pos()) : 0;
1839 InsetBase * LCursor::prevInset()
1844 return prevAtom().nucleus();
1845 return paragraph().isInset(pos() - 1) ? paragraph().getInset(pos() - 1) : 0;
1849 InsetBase const * LCursor::prevInset() const
1854 return prevAtom().nucleus();
1855 return paragraph().isInset(pos() - 1) ? paragraph().getInset(pos() - 1) : 0;
1859 void LCursor::message(string const & msg) const
1861 bv().owner()->getLyXFunc().setMessage(msg);
1865 void LCursor::errorMessage(string const & msg) const
1867 bv().owner()->getLyXFunc().setErrorMessage(msg);
1871 string LCursor::selectionAsString(bool label) const
1877 Buffer const & buffer = *bv().buffer();
1879 // should be const ...
1880 ParagraphList::iterator startpit = text()->getPar(selBegin());
1881 ParagraphList::iterator endpit = text()->getPar(selEnd());
1882 size_t const startpos = selBegin().pos();
1883 size_t const endpos = selEnd().pos();
1885 if (startpit == endpit)
1886 return startpit->asString(buffer, startpos, endpos, label);
1888 // First paragraph in selection
1890 startpit->asString(buffer, startpos, startpit->size(), label) + "\n\n";
1892 // The paragraphs in between (if any)
1893 ParagraphList::iterator pit = startpit;
1894 for (++pit; pit != endpit; ++pit)
1895 result += pit->asString(buffer, 0, pit->size(), label) + "\n\n";
1897 // Last paragraph in selection
1898 result += endpit->asString(buffer, 0, endpos, label);
1908 string LCursor::currentState()
1911 std::ostringstream os;
1915 return text()->currentState(*this);
1919 // only used by the spellchecker
1920 void LCursor::replaceWord(string const & replacestring)
1922 LyXText * t = text();
1924 t->replaceSelectionWithString(*this, replacestring);
1925 t->setSelectionRange(*this, replacestring.length());
1927 // Go back so that replacement string is also spellchecked
1928 for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
1929 t->cursorLeft(*this, true);
1933 void LCursor::update()
1939 string LCursor::getPossibleLabel()
1941 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1945 void LCursor::notdispatched()
1947 disp_.dispatched(false);
1951 void LCursor::dispatched(dispatch_result_t res)
1957 void LCursor::noupdate()
1959 disp_.update(false);