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.
15 #include "BufferView.h"
18 #include "CutAndPaste.h"
20 #include "dispatchresult.h"
22 #include "funcrequest.h"
26 #include "lyxfunc.h" // only for setMessage()
30 #include "paragraph.h"
31 #include "paragraph_funcs.h"
32 #include "pariterator.h"
34 #include "insets/updatableinset.h"
35 #include "insets/insettabular.h"
36 #include "insets/insettext.h"
38 #include "mathed/math_data.h"
39 #include "mathed/math_inset.h"
40 #include "mathed/math_macrotable.h"
42 #include "support/limited_stack.h"
44 #include "frontends/LyXView.h"
46 #include <boost/assert.hpp>
55 #ifndef CXX_GLOBAL_CSTD
62 LCursor::LCursor(BufferView & bv)
63 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
64 selection_(false), mark_(false)
68 void LCursor::reset(InsetBase & inset)
71 push_back(CursorSlice(inset));
72 anchor_ = DocIterator(inset);
79 void LCursor::setCursor(DocIterator const & cur, bool sel)
81 // this (intentionally) does not touch the anchor
82 DocIterator::operator=(cur);
87 void LCursor::dispatch(FuncRequest const & cmd0)
89 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
93 FuncRequest cmd = cmd0;
96 for ( ; size(); pop()) {
97 lyxerr << "LCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
98 BOOST_ASSERT(pos() <= lastpos());
99 BOOST_ASSERT(idx() <= lastidx());
100 BOOST_ASSERT(par() <= lastpar());
102 // The common case is 'LFUN handled, need update', so make the
103 // LFUN handler's life easier by assuming this as default value.
104 // The handler can reset the update and val flags if necessary.
106 disp_.dispatched(true);
107 inset().dispatch(*this, cmd);
108 if (disp_.dispatched())
111 // it completely to get a 'bomb early' behaviour in case this
112 // object will be used again.
113 if (!disp_.dispatched()) {
114 lyxerr[Debug::DEBUG] << "RESTORING OLD CURSOR!" << endl;
116 disp_.dispatched(false);
121 DispatchResult LCursor::result() const
127 bool LCursor::getStatus(FuncRequest const & cmd, FuncStatus & status)
129 // This is, of course, a mess. Better create a new doc iterator and use
130 // this in Inset::getStatus. This might require an additional
131 // BufferView * arg, though (which should be avoided)
132 LCursor safe = *this;
134 for ( ; size(); pop()) {
135 //lyxerr << "\nLCursor::getStatus: cmd: " << cmd << endl << *this << endl;
136 BOOST_ASSERT(pos() <= lastpos());
137 BOOST_ASSERT(idx() <= lastidx());
138 BOOST_ASSERT(par() <= lastpar());
140 // The inset's getStatus() will return 'true' if it made
141 // a definitive decision on whether it want to handle the
142 // request or not. The result of this decision is put into
143 // the 'status' parameter.
144 if (inset().getStatus(*this, cmd, status)) {
154 BufferView & LCursor::bv() const
161 Buffer & LCursor::buffer() const
164 BOOST_ASSERT(bv_->buffer());
165 return *bv_->buffer();
171 BOOST_ASSERT(size() >= 1);
176 void LCursor::push(InsetBase & p)
178 push_back(CursorSlice(p));
182 void LCursor::pushLeft(InsetBase & p)
184 BOOST_ASSERT(!empty());
185 //lyxerr << "Entering inset " << t << " left" << endl;
191 bool LCursor::popLeft()
193 BOOST_ASSERT(!empty());
194 //lyxerr << "Leaving inset to the left" << endl;
195 inset().notifyCursorLeaves(*this);
203 bool LCursor::popRight()
205 BOOST_ASSERT(!empty());
206 //lyxerr << "Leaving inset to the right" << endl;
207 inset().notifyCursorLeaves(*this);
216 int LCursor::currentMode()
218 BOOST_ASSERT(!empty());
219 for (int i = size() - 1; i >= 0; --i) {
220 int res = operator[](i).inset().currentMode();
221 if (res != InsetBase::UNDECIDED_MODE)
224 return InsetBase::TEXT_MODE;
228 void LCursor::getDim(int & asc, int & des) const
231 BOOST_ASSERT(inset().asMathInset());
232 //inset().asMathInset()->getCursorDim(asc, des);
235 } else if (inTexted()) {
236 Row const & row = textRow();
237 asc = row.baseline();
238 des = row.height() - asc;
240 lyxerr << "should this happen?" << endl;
247 void LCursor::getPos(int & x, int & y) const
252 inset().getCursorPos(*this, x, y);
256 void LCursor::paste(string const & data)
258 dispatch(FuncRequest(LFUN_PASTE, data));
262 void LCursor::resetAnchor()
269 bool LCursor::posLeft()
278 bool LCursor::posRight()
280 if (pos() == lastpos())
287 CursorSlice LCursor::anchor() const
289 BOOST_ASSERT(anchor_.size() >= size());
290 CursorSlice normal = anchor_[size() - 1];
291 if (size() < anchor_.size() && back() <= normal) {
292 // anchor is behind cursor -> move anchor behind the inset
299 CursorSlice LCursor::selBegin() const
303 return anchor() < back() ? anchor() : back();
307 CursorSlice LCursor::selEnd() const
311 return anchor() > back() ? anchor() : back();
315 DocIterator LCursor::selectionBegin() const
319 return anchor() < back() ? anchor_ : *this;
323 DocIterator LCursor::selectionEnd() const
327 return anchor() > back() ? anchor_ : *this;
331 void LCursor::setSelection()
334 // a selection with no contents is not a selection
336 #warning doesnt look ok
338 if (par() == anchor().par() && pos() == anchor().pos())
343 void LCursor::setSelection(DocIterator const & where, size_t n)
345 setCursor(where, true);
351 void LCursor::clearSelection()
360 int & LCursor::x_target()
366 int LCursor::x_target() const
372 void LCursor::clearTargetX()
379 void LCursor::info(std::ostream & os) const
381 for (int i = 1, n = depth(); i < n; ++i) {
382 operator[](i).inset().infoize(os);
386 prevInset()->infoize2(os);
387 // overwite old message
392 void LCursor::selHandle(bool sel)
394 //lyxerr << "LCursor::selHandle" << endl;
395 if (sel == selection())
403 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
405 os << "\n cursor: | anchor:\n";
406 for (size_t i = 0, n = cur.size(); i != n; ++i) {
407 os << " " << cur.operator[](i) << " | ";
408 if (i < cur.anchor_.size())
409 os << cur.anchor_[i];
411 os << "-------------------------------";
414 for (size_t i = cur.size(), n = cur.anchor_.size(); i < n; ++i) {
415 os << "------------------------------- | " << cur.anchor_[i] << "\n";
417 os << " selection: " << cur.selection_
418 << " x_target: " << cur.x_target_ << endl;
425 ///////////////////////////////////////////////////////////////////
427 // The part below is the non-integrated rest of the original math
428 // cursor. This should be either generalized for texted or moved
429 // back to mathed (in most cases to MathNestInset).
431 ///////////////////////////////////////////////////////////////////
433 #include "mathed/math_charinset.h"
434 #include "mathed/math_factory.h"
435 #include "mathed/math_gridinset.h"
436 #include "mathed/math_macroarg.h"
437 #include "mathed/math_mathmlstream.h"
438 #include "mathed/math_scriptinset.h"
439 #include "mathed/math_support.h"
440 #include "mathed/math_unknowninset.h"
442 //#define FILEDEBUG 1
445 bool LCursor::isInside(InsetBase const * p)
447 for (unsigned i = 0; i < depth(); ++i)
448 if (&operator[](i).inset() == p)
454 bool LCursor::openable(MathAtom const & t) const
465 // we can't move into anything new during selection
466 if (depth() >= anchor_.size())
468 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
475 bool positionable(DocIterator const & cursor,
476 DocIterator const & anchor)
478 // avoid deeper nested insets when selecting
479 if (cursor.size() > anchor.size())
482 // anchor might be deeper, should have same path then
483 for (size_t i = 0; i < cursor.size(); ++i)
484 if (&cursor[i].inset() != &anchor[i].inset())
487 // position should be ok.
492 void LCursor::setScreenPos(int x, int y)
495 bruteFind(x, y, 0, bv().workWidth(), 0, bv().workHeight());
500 void LCursor::plainErase()
506 void LCursor::markInsert()
512 void LCursor::markErase()
518 void LCursor::plainInsert(MathAtom const & t)
520 cell().insert(pos(), t);
525 void LCursor::insert(string const & str)
527 //lyxerr << "LCursor::insert str '" << str << "'" << endl;
528 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
533 void LCursor::insert(char c)
535 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
536 BOOST_ASSERT(!empty());
538 lyx::cap::selClearOrDel(*this);
539 insert(new MathCharInset(c));
541 text()->insertChar(*this, c);
546 void LCursor::insert(MathAtom const & t)
548 //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
550 lyx::cap::selClearOrDel(*this);
555 void LCursor::insert(InsetBase * inset)
558 insert(MathAtom(inset));
560 text()->insertInset(*this, inset);
564 void LCursor::niceInsert(string const & t)
575 void LCursor::niceInsert(MathAtom const & t)
578 string safe = lyx::cap::grabAndEraseSelection(*this);
580 // enter the new inset and move the contents of the selection if possible
583 // be careful here: don't use 'pushLeft(t)' as this we need to
584 // push the clone, not the original
585 pushLeft(*nextInset());
591 void LCursor::insert(MathArray const & ar)
595 lyx::cap::eraseSelection(*this);
596 cell().insert(pos(), ar);
601 bool LCursor::backspace()
603 autocorrect() = false;
606 lyx::cap::selDel(*this);
611 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
618 MathUnknownInset * p = activeMacro();
619 if (p->name().size() > 1) {
620 p->setName(p->name().substr(0, p->name().size() - 1));
625 if (pos() != 0 && prevAtom()->nargs() > 0) {
626 // let's require two backspaces for 'big stuff' and
627 // highlight on the first
639 bool LCursor::erase()
641 autocorrect() = false;
646 lyx::cap::selDel(*this);
650 // delete empty cells if possible
651 if (pos() == lastpos() && inset().idxDelete(idx()))
654 // special behaviour when in last position of cell
655 if (pos() == lastpos()) {
656 bool one_cell = inset().nargs() == 1;
657 if (one_cell && depth() == 1 && lastpos() == 0)
663 inset().idxGlue(idx());
667 // 'clever' UI hack: only erase large items if previously slected
668 if (pos() != lastpos() && inset().nargs() > 0) {
683 DocIterator save = *this;
686 setCursor(save, false);
687 autocorrect() = false;
695 DocIterator save = *this;
698 setCursor(save, false);
699 autocorrect() = false;
704 void LCursor::macroModeClose()
708 MathUnknownInset * p = activeMacro();
710 string s = p->name();
714 // do nothing if the macro name is empty
718 string const name = s.substr(1);
720 // prevent entering of recursive macros
721 // FIXME: this is only a weak attempt... only prevents immediate
723 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
724 if (macro && macro->getInsetName() == name)
725 lyxerr << "can't enter recursive macro" << endl;
727 //niceInsert(createMathInset(name));
728 plainInsert(createMathInset(name));
732 string LCursor::macroName()
734 return inMacroMode() ? activeMacro()->name() : string();
738 void LCursor::handleNest(MathAtom const & a, int c)
740 //lyxerr << "LCursor::handleNest: " << c << endl;
742 asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
745 pushLeft(*nextInset());
749 int LCursor::targetX() const
751 if (x_target() != -1)
760 bool LCursor::inMacroMode() const
764 MathUnknownInset const * p = prevAtom()->asUnknownInset();
765 return p && !p->final();
769 MathUnknownInset * LCursor::activeMacro()
771 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
775 void LCursor::pullArg()
780 MathArray ar = cell();
781 if (popLeft() && inMathed()) {
783 cell().insert(pos(), ar);
786 //formula()->mutateToText();
791 void LCursor::touch()
797 DocIterator::const_iterator it = begin();
798 DocIterator::const_iterator et = end();
799 for ( ; it != et; ++it)
805 void LCursor::normalize()
807 if (idx() >= nargs()) {
808 lyxerr << "this should not really happen - 1: "
809 << idx() << ' ' << nargs()
810 << " in: " << &inset() << endl;
812 idx() = min(idx(), lastidx());
814 if (pos() > lastpos()) {
815 lyxerr << "this should not really happen - 2: "
816 << pos() << ' ' << lastpos() << " in idx: " << idx()
818 WriteStream wi(lyxerr, false, true);
819 inset().asMathInset()->write(wi);
822 pos() = min(pos(), lastpos());
826 bool LCursor::goUpDown(bool up)
828 // Be warned: The 'logic' implemented in this function is highly
829 // fragile. A distance of one pixel or a '<' vs '<=' _really
830 // matters. So fiddle around with it only if you think you know
831 // what you are doing!
837 // check if we had something else in mind, if not, this is the future goal
838 if (x_target() == -1)
843 // try neigbouring script insets
847 MathScriptInset const * p = prevAtom()->asScriptInset();
848 if (p && p->has(up)) {
851 idx() = up; // the superscript has index 1
853 //lyxerr << "updown: handled by scriptinset to the left" << endl;
859 if (pos() != lastpos()) {
860 MathScriptInset const * p = nextAtom()->asScriptInset();
861 if (p && p->has(up)) {
865 //lyxerr << "updown: handled by scriptinset to the right" << endl;
871 // try current cell for e.g. text insets
872 if (inset().idxUpDown2(*this, up))
875 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
880 //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
881 // lyxerr << "updown: handled by brute find in the same cell" << endl;
885 // try to find an inset that knows better then we
887 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
889 if (inset().idxUpDown(*this, up)) {
890 // try to find best position within this inset
896 // no such inset found, just take something "above"
897 //lyxerr << "updown: handled by strange case" << endl;
899 int ylow = up ? 0 : yo + 1;
900 int yhigh = up ? yo - 1 : bv().workHeight();
901 return bruteFind(xo, yo, 0, bv().workWidth(), ylow, yhigh);
904 // any improvement so far?
907 if (up ? ynew < yo : ynew > yo)
913 bool LCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
915 BOOST_ASSERT(!empty());
917 CursorSlice bottom = operator[](0);
918 LyXText * text = bottom.text();
920 getParsInRange(text->paragraphs(), ylow, yhigh, beg, end);
922 DocIterator it = doc_iterator_begin(bv().buffer()->inset());
923 DocIterator et = doc_iterator_end(bv().buffer()->inset());
924 //lyxerr << "x: " << x << " y: " << y << endl;
925 //lyxerr << "xlow: " << xlow << " ylow: " << ylow << endl;
926 //lyxerr << "xhigh: " << xhigh << " yhigh: " << yhigh << endl;
929 //et.par() = text->parOffset(end);
931 double best_dist = 10e10;
932 DocIterator best_cursor = it;
934 for ( ; it != et; it.forwardPos()) {
935 // avoid invalid nesting when selecting
936 if (!selection() || positionable(it, anchor_)) {
939 cur.setCursor(it, false);
940 cur.inset().getCursorPos(cur, xo, yo);
941 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
942 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
943 //lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
944 // '<=' in order to take the last possible position
945 // this is important for clicking behind \sum in e.g. '\sum_i a'
946 if (d <= best_dist) {
947 //lyxerr << "*" << endl;
955 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
956 if (best_dist < 1e10)
957 setCursor(best_cursor, false);
958 return best_dist < 1e10;
962 void LCursor::bruteFind2(int x, int y)
964 double best_dist = 1e10;
966 DocIterator it = *this;
968 DocIterator et = *this;
969 et.back().pos() = et.back().asMathInset()->cell(et.back().idx()).size();
970 for (int i = 0; ; ++i) {
973 cur.setCursor(it, false);
974 cur.inset().getCursorPos(cur, xo, yo);
975 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
976 // '<=' in order to take the last possible position
977 // this is important for clicking behind \sum in e.g. '\sum_i a'
978 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
979 if (d <= best_dist) {
981 setCursor(it, false);
990 void LCursor::handleFont(string const & font)
992 lyxerr << "LCursor::handleFont: " << font << endl;
996 safe = lyx::cap::grabAndEraseSelection(*this);
999 if (lastpos() != 0) {
1000 // something left in the cell
1002 // cursor in first position
1004 } else if (pos() == lastpos()) {
1005 // cursor in last position
1008 // cursor in between. split cell
1009 MathArray::iterator bt = cell().begin();
1010 MathAtom at = createMathInset(font);
1011 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1012 cell().erase(bt, bt + pos());
1017 // nothing left in the cell
1025 void LCursor::message(string const & msg) const
1027 bv().owner()->getLyXFunc().setMessage(msg);
1031 void LCursor::errorMessage(string const & msg) const
1033 bv().owner()->getLyXFunc().setErrorMessage(msg);
1037 string LCursor::selectionAsString(bool label) const
1043 Buffer const & buffer = *bv().buffer();
1044 ParagraphList & pars = text()->paragraphs();
1046 // should be const ...
1047 par_type startpit = selBegin().par();
1048 par_type endpit = selEnd().par();
1049 size_t const startpos = selBegin().pos();
1050 size_t const endpos = selEnd().pos();
1052 if (startpit == endpit)
1053 return pars[startpit].asString(buffer, startpos, endpos, label);
1055 // First paragraph in selection
1056 string result = pars[startpit].
1057 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1059 // The paragraphs in between (if any)
1060 for (par_type pit = startpit + 1; pit != endpit; ++pit) {
1061 Paragraph & par = pars[pit];
1062 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1065 // Last paragraph in selection
1066 result += pars[endpit].asString(buffer, 0, endpos, label);
1071 #ifdef WITH_WARNINGS
1072 #warning and mathed?
1078 string LCursor::currentState()
1081 std::ostringstream os;
1087 return text()->currentState(*this);
1093 string LCursor::getPossibleLabel()
1095 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1099 Encoding const * LCursor::getEncoding() const
1106 // go up until first non-0 text is hit
1107 // (innermost text is 0 in mathed)
1108 for (s = size() - 1; s >= 0; --s)
1109 if (operator[](s).text())
1111 CursorSlice const & sl = operator[](s);
1112 LyXText & text = *sl.text();
1113 LyXFont font = text.getPar(sl.par()).getFont(
1114 bv().buffer()->params(), sl.pos(), outerFont(sl.par(), text.paragraphs()));
1115 return font.language()->encoding();
1119 void LCursor::undispatched()
1121 disp_.dispatched(false);
1125 void LCursor::dispatched()
1127 disp_.dispatched(true);
1131 void LCursor::needsUpdate()
1137 void LCursor::noUpdate()
1139 disp_.update(false);