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 "coordcache.h"
19 #include "CutAndPaste.h"
21 #include "dispatchresult.h"
23 #include "funcrequest.h"
27 #include "lyxfunc.h" // only for setMessage()
31 #include "paragraph.h"
32 #include "paragraph_funcs.h"
33 #include "pariterator.h"
35 #include "insets/updatableinset.h"
36 #include "insets/insettabular.h"
37 #include "insets/insettext.h"
39 #include "mathed/math_data.h"
40 #include "mathed/math_inset.h"
41 #include "mathed/math_macrotable.h"
43 #include "support/limited_stack.h"
45 #include "frontends/LyXView.h"
46 #include "frontends/font_metrics.h"
48 #include <boost/assert.hpp>
49 #include <boost/bind.hpp>
50 #include <boost/current_function.hpp>
60 #ifndef CXX_GLOBAL_CSTD
69 positionable(DocIterator const & cursor, DocIterator const & anchor)
71 // avoid deeper nested insets when selecting
72 if (cursor.size() > anchor.size())
75 // anchor might be deeper, should have same path then
76 for (size_t i = 0; i < cursor.size(); ++i)
77 if (&cursor[i].inset() != &anchor[i].inset())
80 // position should be ok.
85 // Find position closest to (x, y) in cell given by iter.
86 // Used only in mathed
87 DocIterator bruteFind2(LCursor const & c, int x, int y)
89 double best_dist = std::numeric_limits<double>::max();
96 et.back().pos() = et.back().asMathInset()->cell(et.back().idx()).size();
97 for (int i = 0; ; ++i) {
101 cur.inset().getCursorPos(cur.top(), xo, yo);
102 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
103 // '<=' in order to take the last possible position
104 // this is important for clicking behind \sum in e.g. '\sum_i a'
105 lyxerr[Debug::DEBUG] << "i: " << i << " d: " << d
106 << " best: " << best_dist << endl;
107 if (d <= best_dist) {
119 /// moves position closest to (x, y) in given box
120 bool bruteFind(LCursor & cursor,
121 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
123 BOOST_ASSERT(!cursor.empty());
124 CursorSlice bottom = cursor[0];
125 LyXText * text = bottom.text();
128 DocIterator it = doc_iterator_begin(bottom.inset());
129 DocIterator const et = doc_iterator_end(bottom.inset());
131 double best_dist = std::numeric_limits<double>::max();;
132 DocIterator best_cursor = et;
134 for ( ; it != et; it.forwardPos()) {
135 // avoid invalid nesting when selecting
136 if (bv_funcs::status(&cursor.bv(), it) == bv_funcs::CUR_INSIDE
137 && (!cursor.selection() || positionable(it, cursor.anchor_))) {
138 Point p = bv_funcs::getPos(it);
141 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
142 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
143 //lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
144 // '<=' in order to take the last possible position
145 // this is important for clicking behind \sum in e.g. '\sum_i a'
146 if (d <= best_dist) {
147 //lyxerr << "*" << endl;
155 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
156 if (best_cursor != et) {
157 cursor.setCursor(best_cursor);
167 // be careful: this is called from the bv's constructor, too, so
168 // bv functions are not yet available!
169 LCursor::LCursor(BufferView & bv)
170 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
171 selection_(false), mark_(false)
175 void LCursor::reset(InsetBase & inset)
178 push_back(CursorSlice(inset));
179 anchor_ = DocIterator(inset);
186 // this (intentionally) does neither touch anchor nor selection status
187 void LCursor::setCursor(DocIterator const & cur)
189 DocIterator::operator=(cur);
193 void LCursor::dispatch(FuncRequest const & cmd0)
195 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: "
196 << cmd0 << endl << *this << endl;
200 FuncRequest cmd = cmd0;
201 LCursor safe = *this;
203 for (; size(); pop()) {
204 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: "
205 << cmd0 << endl << *this << endl;
206 BOOST_ASSERT(pos() <= lastpos());
207 BOOST_ASSERT(idx() <= lastidx());
208 BOOST_ASSERT(pit() <= lastpit());
210 // The common case is 'LFUN handled, need update', so make the
211 // LFUN handler's life easier by assuming this as default value.
212 // The handler can reset the update and val flags if necessary.
214 disp_.dispatched(true);
215 inset().dispatch(*this, cmd);
216 if (disp_.dispatched())
219 // it completely to get a 'bomb early' behaviour in case this
220 // object will be used again.
221 if (!disp_.dispatched()) {
222 lyxerr[Debug::DEBUG] << "RESTORING OLD CURSOR!" << endl;
224 disp_.dispatched(false);
229 DispatchResult LCursor::result() const
235 BufferView & LCursor::bv() const
242 Buffer & LCursor::buffer() const
245 BOOST_ASSERT(bv_->buffer());
246 return *bv_->buffer();
252 BOOST_ASSERT(size() >= 1);
257 void LCursor::push(InsetBase & p)
259 push_back(CursorSlice(p));
263 void LCursor::pushLeft(InsetBase & p)
265 BOOST_ASSERT(!empty());
266 //lyxerr << "Entering inset " << t << " left" << endl;
272 bool LCursor::popLeft()
274 BOOST_ASSERT(!empty());
275 //lyxerr << "Leaving inset to the left" << endl;
276 inset().notifyCursorLeaves(*this);
284 bool LCursor::popRight()
286 BOOST_ASSERT(!empty());
287 //lyxerr << "Leaving inset to the right" << endl;
288 inset().notifyCursorLeaves(*this);
297 int LCursor::currentMode()
299 BOOST_ASSERT(!empty());
300 for (int i = size() - 1; i >= 0; --i) {
301 int res = operator[](i).inset().currentMode();
302 if (res != InsetBase::UNDECIDED_MODE)
305 return InsetBase::TEXT_MODE;
309 void LCursor::getPos(int & x, int & y) const
311 Point p = bv_funcs::getPos(*this);
317 void LCursor::paste(string const & data)
319 dispatch(FuncRequest(LFUN_PASTE, data));
323 void LCursor::resetAnchor()
330 bool LCursor::posLeft()
339 bool LCursor::posRight()
341 if (pos() == lastpos())
348 CursorSlice LCursor::anchor() const
350 BOOST_ASSERT(anchor_.size() >= size());
351 CursorSlice normal = anchor_[size() - 1];
352 if (size() < anchor_.size() && back() <= normal) {
353 // anchor is behind cursor -> move anchor behind the inset
360 CursorSlice LCursor::selBegin() const
364 return anchor() < back() ? anchor() : back();
368 CursorSlice LCursor::selEnd() const
372 return anchor() > back() ? anchor() : back();
376 DocIterator LCursor::selectionBegin() const
380 return anchor() < back() ? anchor_ : *this;
384 DocIterator LCursor::selectionEnd() const
388 return anchor() > back() ? anchor_ : *this;
392 void LCursor::setSelection()
395 // a selection with no contents is not a selection
397 #warning doesnt look ok
399 if (pit() == anchor().pit() && pos() == anchor().pos())
404 void LCursor::setSelection(DocIterator const & where, size_t n)
413 void LCursor::clearSelection()
422 int & LCursor::x_target()
428 int LCursor::x_target() const
434 void LCursor::clearTargetX()
441 void LCursor::info(std::ostream & os) const
443 for (int i = 1, n = depth(); i < n; ++i) {
444 operator[](i).inset().infoize(os);
448 prevInset()->infoize2(os);
449 // overwite old message
454 void LCursor::selHandle(bool sel)
456 //lyxerr << "LCursor::selHandle" << endl;
457 if (sel == selection())
465 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
467 os << "\n cursor: | anchor:\n";
468 for (size_t i = 0, n = cur.size(); i != n; ++i) {
469 os << " " << cur.operator[](i) << " | ";
470 if (i < cur.anchor_.size())
471 os << cur.anchor_[i];
473 os << "-------------------------------";
476 for (size_t i = cur.size(), n = cur.anchor_.size(); i < n; ++i) {
477 os << "------------------------------- | " << cur.anchor_[i] << "\n";
479 os << " selection: " << cur.selection_
480 << " x_target: " << cur.x_target_ << endl;
487 ///////////////////////////////////////////////////////////////////
489 // The part below is the non-integrated rest of the original math
490 // cursor. This should be either generalized for texted or moved
491 // back to mathed (in most cases to MathNestInset).
493 ///////////////////////////////////////////////////////////////////
495 #include "mathed/math_charinset.h"
496 #include "mathed/math_factory.h"
497 #include "mathed/math_gridinset.h"
498 #include "mathed/math_macroarg.h"
499 #include "mathed/math_mathmlstream.h"
500 #include "mathed/math_scriptinset.h"
501 #include "mathed/math_support.h"
502 #include "mathed/math_unknowninset.h"
504 //#define FILEDEBUG 1
507 bool LCursor::isInside(InsetBase const * p)
509 for (unsigned i = 0; i < depth(); ++i)
510 if (&operator[](i).inset() == p)
516 bool LCursor::openable(MathAtom const & t) const
527 // we can't move into anything new during selection
528 if (depth() >= anchor_.size())
530 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
537 void LCursor::setScreenPos(int x, int y)
540 bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
545 void LCursor::plainErase()
551 void LCursor::markInsert()
557 void LCursor::markErase()
563 void LCursor::plainInsert(MathAtom const & t)
565 cell().insert(pos(), t);
570 void LCursor::insert(string const & str)
572 for_each(str.begin(), str.end(),
573 boost::bind(static_cast<void(LCursor::*)(char)>
574 (&LCursor::insert), this, _1));
578 void LCursor::insert(char c)
580 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
581 BOOST_ASSERT(!empty());
583 lyx::cap::selClearOrDel(*this);
584 insert(new MathCharInset(c));
586 text()->insertChar(*this, c);
591 void LCursor::insert(MathAtom const & t)
593 //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
595 lyx::cap::selClearOrDel(*this);
600 void LCursor::insert(InsetBase * inset)
603 insert(MathAtom(inset));
605 text()->insertInset(*this, inset);
609 void LCursor::niceInsert(string const & t)
620 void LCursor::niceInsert(MathAtom const & t)
623 string safe = lyx::cap::grabAndEraseSelection(*this);
625 // enter the new inset and move the contents of the selection if possible
628 // be careful here: don't use 'pushLeft(t)' as this we need to
629 // push the clone, not the original
630 pushLeft(*nextInset());
636 void LCursor::insert(MathArray const & ar)
640 lyx::cap::eraseSelection(*this);
641 cell().insert(pos(), ar);
646 bool LCursor::backspace()
648 autocorrect() = false;
651 lyx::cap::selDel(*this);
656 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
663 MathUnknownInset * p = activeMacro();
664 if (p->name().size() > 1) {
665 p->setName(p->name().substr(0, p->name().size() - 1));
670 if (pos() != 0 && prevAtom()->nargs() > 0) {
671 // let's require two backspaces for 'big stuff' and
672 // highlight on the first
684 bool LCursor::erase()
686 autocorrect() = false;
691 lyx::cap::selDel(*this);
695 // delete empty cells if possible
696 if (pos() == lastpos() && inset().idxDelete(idx()))
699 // special behaviour when in last position of cell
700 if (pos() == lastpos()) {
701 bool one_cell = inset().nargs() == 1;
702 if (one_cell && depth() == 1 && lastpos() == 0)
708 inset().idxGlue(idx());
712 // 'clever' UI hack: only erase large items if previously slected
713 if (pos() != lastpos() && inset().nargs() > 0) {
728 DocIterator save = *this;
732 autocorrect() = false;
740 DocIterator save = *this;
744 autocorrect() = false;
749 void LCursor::macroModeClose()
753 MathUnknownInset * p = activeMacro();
755 string s = p->name();
759 // do nothing if the macro name is empty
763 string const name = s.substr(1);
765 // prevent entering of recursive macros
766 // FIXME: this is only a weak attempt... only prevents immediate
768 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
769 if (macro && macro->getInsetName() == name)
770 lyxerr << "can't enter recursive macro" << endl;
772 plainInsert(createMathInset(name));
776 string LCursor::macroName()
778 return inMacroMode() ? activeMacro()->name() : string();
782 void LCursor::handleNest(MathAtom const & a, int c)
784 //lyxerr << "LCursor::handleNest: " << c << endl;
786 asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
789 pushLeft(*nextInset());
793 int LCursor::targetX() const
795 if (x_target() != -1)
804 void LCursor::setTargetX()
806 //for now this is good enough. A better solution would be to
807 //avoid this rebreak by setting cursorX only after drawing
808 bottom().text()->redoParagraph(bottom().pit());
815 bool LCursor::inMacroMode() const
819 MathUnknownInset const * p = prevAtom()->asUnknownInset();
820 return p && !p->final();
824 MathUnknownInset * LCursor::activeMacro()
826 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
830 void LCursor::pullArg()
835 MathArray ar = cell();
836 if (popLeft() && inMathed()) {
838 cell().insert(pos(), ar);
841 //formula()->mutateToText();
846 void LCursor::touch()
852 DocIterator::const_iterator it = begin();
853 DocIterator::const_iterator et = end();
854 for ( ; it != et; ++it)
860 void LCursor::normalize()
862 if (idx() >= nargs()) {
863 lyxerr << "this should not really happen - 1: "
864 << idx() << ' ' << nargs()
865 << " in: " << &inset() << endl;
867 idx() = min(idx(), lastidx());
869 if (pos() > lastpos()) {
870 lyxerr << "this should not really happen - 2: "
871 << pos() << ' ' << lastpos() << " in idx: " << idx()
873 WriteStream wi(lyxerr, false, true);
874 inset().asMathInset()->write(wi);
877 pos() = min(pos(), lastpos());
881 bool LCursor::goUpDown(bool up)
883 // Be warned: The 'logic' implemented in this function is highly
884 // fragile. A distance of one pixel or a '<' vs '<=' _really
885 // matters. So fiddle around with it only if you think you know
886 // what you are doing!
892 // check if we had something else in mind, if not, this is the future goal
893 if (x_target() == -1)
898 // try neigbouring script insets
902 MathScriptInset const * p = prevAtom()->asScriptInset();
903 if (p && p->has(up)) {
906 idx() = up; // the superscript has index 1
908 //lyxerr << "updown: handled by scriptinset to the left" << endl;
914 if (pos() != lastpos()) {
915 MathScriptInset const * p = nextAtom()->asScriptInset();
916 if (p && p->has(up)) {
920 //lyxerr << "updown: handled by scriptinset to the right" << endl;
926 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
931 //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
932 // lyxerr << "updown: handled by brute find in the same cell" << endl;
936 // try to find an inset that knows better then we
938 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
940 if (inset().idxUpDown(*this, up)) {
941 // try to find best position within this inset
943 setCursor(bruteFind2(*this, xo, yo));
947 // no such inset found, just take something "above"
948 //lyxerr << "updown: handled by strange case" << endl;
950 int ylow = up ? 0 : yo + 1;
951 int yhigh = up ? yo - 1 : bv().workHeight();
952 return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
955 // any improvement so far?
958 if (up ? ynew < yo : ynew > yo)
962 // we should not come here.
967 void LCursor::handleFont(string const & font)
969 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << ": " << font << endl;
973 safe = lyx::cap::grabAndEraseSelection(*this);
976 if (lastpos() != 0) {
977 // something left in the cell
979 // cursor in first position
981 } else if (pos() == lastpos()) {
982 // cursor in last position
985 // cursor in between. split cell
986 MathArray::iterator bt = cell().begin();
987 MathAtom at = createMathInset(font);
988 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
989 cell().erase(bt, bt + pos());
994 // nothing left in the cell
1002 void LCursor::message(string const & msg) const
1004 bv().owner()->getLyXFunc().setMessage(msg);
1008 void LCursor::errorMessage(string const & msg) const
1010 bv().owner()->getLyXFunc().setErrorMessage(msg);
1014 string LCursor::selectionAsString(bool label) const
1020 Buffer const & buffer = *bv().buffer();
1021 ParagraphList & pars = text()->paragraphs();
1023 // should be const ...
1024 pit_type startpit = selBegin().pit();
1025 pit_type endpit = selEnd().pit();
1026 size_t const startpos = selBegin().pos();
1027 size_t const endpos = selEnd().pos();
1029 if (startpit == endpit)
1030 return pars[startpit].asString(buffer, startpos, endpos, label);
1032 // First paragraph in selection
1033 string result = pars[startpit].
1034 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1036 // The paragraphs in between (if any)
1037 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1038 Paragraph & par = pars[pit];
1039 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1042 // Last paragraph in selection
1043 result += pars[endpit].asString(buffer, 0, endpos, label);
1048 #ifdef WITH_WARNINGS
1049 #warning and mathed?
1055 string LCursor::currentState()
1058 std::ostringstream os;
1064 return text()->currentState(*this);
1070 string LCursor::getPossibleLabel()
1072 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1076 Encoding const * LCursor::getEncoding() const
1083 // go up until first non-0 text is hit
1084 // (innermost text is 0 in mathed)
1085 for (s = size() - 1; s >= 0; --s)
1086 if (operator[](s).text())
1088 CursorSlice const & sl = operator[](s);
1089 LyXText & text = *sl.text();
1090 LyXFont font = text.getPar(sl.pit()).getFont(
1091 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1092 return font.language()->encoding();
1096 void LCursor::undispatched()
1098 disp_.dispatched(false);
1102 void LCursor::dispatched()
1104 disp_.dispatched(true);
1108 void LCursor::needsUpdate()
1114 void LCursor::noUpdate()
1116 disp_.update(false);
1120 LyXFont LCursor::getFont() const
1122 // HACK. far from being perfect...
1124 // go up until first non-0 text is hit
1125 // (innermost text is 0 in mathed)
1126 for (s = size() - 1; s >= 0; --s)
1127 if (operator[](s).text())
1129 CursorSlice const & sl = operator[](s);
1130 LyXText & text = *sl.text();
1131 LyXFont font = text.getPar(sl.pit()).getFont(
1132 bv().buffer()->params(),
1134 outerFont(sl.pit(), text.paragraphs()));
1135 for (; s < size(); ++s)