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.depth() > anchor.depth())
75 // anchor might be deeper, should have same path then
76 for (size_t i = 0; i < cursor.depth(); ++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.top().pos() = et.top().asMathInset()->cell(et.top().idx()).size();
97 for (int i = 0; ; ++i) {
102 cur.inset().getCursorPos(cur.top(), xo, yo);
103 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
104 // '<=' in order to take the last possible position
105 // this is important for clicking behind \sum in e.g. '\sum_i a'
106 lyxerr[Debug::DEBUG] << "i: " << i << " d: " << d
107 << " best: " << best_dist << endl;
108 if (d <= best_dist) {
120 /// moves position closest to (x, y) in given box
121 bool bruteFind(LCursor & cursor,
122 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
124 BOOST_ASSERT(!cursor.empty());
125 CursorSlice bottom = cursor[0];
126 LyXText * text = bottom.text();
129 DocIterator it = doc_iterator_begin(bottom.inset());
130 DocIterator const et = doc_iterator_end(bottom.inset());
132 double best_dist = std::numeric_limits<double>::max();;
133 DocIterator best_cursor = et;
135 for ( ; it != et; it.forwardPos()) {
136 // avoid invalid nesting when selecting
137 if (bv_funcs::status(&cursor.bv(), it) == bv_funcs::CUR_INSIDE
138 && (!cursor.selection() || positionable(it, cursor.anchor_))) {
139 Point p = bv_funcs::getPos(it);
142 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
143 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
144 //lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
145 // '<=' in order to take the last possible position
146 // this is important for clicking behind \sum in e.g. '\sum_i a'
147 if (d <= best_dist) {
148 //lyxerr << "*" << endl;
156 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
157 if (best_cursor != et) {
158 cursor.setCursor(best_cursor);
168 // be careful: this is called from the bv's constructor, too, so
169 // bv functions are not yet available!
170 LCursor::LCursor(BufferView & bv)
171 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
172 selection_(false), mark_(false)
176 void LCursor::reset(InsetBase & inset)
179 push_back(CursorSlice(inset));
180 anchor_ = DocIterator(inset);
187 // this (intentionally) does neither touch anchor nor selection status
188 void LCursor::setCursor(DocIterator const & cur)
190 DocIterator::operator=(cur);
194 void LCursor::dispatch(FuncRequest const & cmd0)
196 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
197 << " cmd: " << cmd0 << '\n'
202 FuncRequest cmd = cmd0;
203 LCursor safe = *this;
205 for (; depth(); pop()) {
206 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: "
207 << cmd0 << endl << *this << endl;
208 BOOST_ASSERT(pos() <= lastpos());
209 BOOST_ASSERT(idx() <= lastidx());
210 BOOST_ASSERT(pit() <= lastpit());
212 // The common case is 'LFUN handled, need update', so make the
213 // LFUN handler's life easier by assuming this as default value.
214 // The handler can reset the update and val flags if necessary.
216 disp_.dispatched(true);
217 inset().dispatch(*this, cmd);
218 if (disp_.dispatched())
221 // it completely to get a 'bomb early' behaviour in case this
222 // object will be used again.
223 if (!disp_.dispatched()) {
224 lyxerr[Debug::DEBUG] << "RESTORING OLD CURSOR!" << endl;
226 disp_.dispatched(false);
231 DispatchResult LCursor::result() const
237 BufferView & LCursor::bv() const
244 Buffer & LCursor::buffer() const
247 BOOST_ASSERT(bv_->buffer());
248 return *bv_->buffer();
254 BOOST_ASSERT(depth() >= 1);
259 void LCursor::push(InsetBase & p)
261 push_back(CursorSlice(p));
265 void LCursor::pushLeft(InsetBase & p)
267 BOOST_ASSERT(!empty());
268 //lyxerr << "Entering inset " << t << " left" << endl;
274 bool LCursor::popLeft()
276 BOOST_ASSERT(!empty());
277 //lyxerr << "Leaving inset to the left" << endl;
278 inset().notifyCursorLeaves(*this);
286 bool LCursor::popRight()
288 BOOST_ASSERT(!empty());
289 //lyxerr << "Leaving inset to the right" << endl;
290 inset().notifyCursorLeaves(*this);
299 int LCursor::currentMode()
301 BOOST_ASSERT(!empty());
302 for (int i = depth() - 1; i >= 0; --i) {
303 int res = operator[](i).inset().currentMode();
304 if (res != InsetBase::UNDECIDED_MODE)
307 return InsetBase::TEXT_MODE;
311 void LCursor::getPos(int & x, int & y) const
313 Point p = bv_funcs::getPos(*this);
319 void LCursor::paste(string const & data)
321 dispatch(FuncRequest(LFUN_PASTE, data));
325 void LCursor::resetAnchor()
332 bool LCursor::posLeft()
341 bool LCursor::posRight()
343 if (pos() == lastpos())
350 CursorSlice LCursor::anchor() const
352 BOOST_ASSERT(anchor_.depth() >= depth());
353 CursorSlice normal = anchor_[depth() - 1];
354 if (depth() < anchor_.depth() && top() <= normal) {
355 // anchor is behind cursor -> move anchor behind the inset
362 CursorSlice LCursor::selBegin() const
366 return anchor() < top() ? anchor() : top();
370 CursorSlice LCursor::selEnd() const
374 return anchor() > top() ? anchor() : top();
378 DocIterator LCursor::selectionBegin() const
382 return anchor() < top() ? anchor_ : *this;
386 DocIterator LCursor::selectionEnd() const
390 return anchor() > top() ? anchor_ : *this;
394 void LCursor::setSelection()
397 // a selection with no contents is not a selection
399 #warning doesnt look ok
401 if (pit() == anchor().pit() && pos() == anchor().pos())
406 void LCursor::setSelection(DocIterator const & where, size_t n)
415 void LCursor::clearSelection()
424 int & LCursor::x_target()
430 int LCursor::x_target() const
436 void LCursor::clearTargetX()
443 void LCursor::info(std::ostream & os) const
445 for (int i = 1, n = depth(); i < n; ++i) {
446 operator[](i).inset().infoize(os);
450 prevInset()->infoize2(os);
451 // overwite old message
456 void LCursor::selHandle(bool sel)
458 //lyxerr << "LCursor::selHandle" << endl;
459 if (sel == selection())
467 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
469 os << "\n cursor: | anchor:\n";
470 for (size_t i = 0, n = cur.depth(); i != n; ++i) {
471 os << " " << cur[i] << " | ";
472 if (i < cur.anchor_.depth())
473 os << cur.anchor_[i];
475 os << "-------------------------------";
478 for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
479 os << "------------------------------- | " << cur.anchor_[i] << "\n";
481 os << " selection: " << cur.selection_
482 << " x_target: " << cur.x_target_ << endl;
489 ///////////////////////////////////////////////////////////////////
491 // The part below is the non-integrated rest of the original math
492 // cursor. This should be either generalized for texted or moved
493 // back to mathed (in most cases to MathNestInset).
495 ///////////////////////////////////////////////////////////////////
497 #include "mathed/math_charinset.h"
498 #include "mathed/math_factory.h"
499 #include "mathed/math_gridinset.h"
500 #include "mathed/math_macroarg.h"
501 #include "mathed/math_mathmlstream.h"
502 #include "mathed/math_scriptinset.h"
503 #include "mathed/math_support.h"
504 #include "mathed/math_unknowninset.h"
506 //#define FILEDEBUG 1
509 bool LCursor::isInside(InsetBase const * p)
511 for (unsigned i = 0; i < depth(); ++i)
512 if (&operator[](i).inset() == p)
518 bool LCursor::openable(MathAtom const & t) const
529 // we can't move into anything new during selection
530 if (depth() >= anchor_.depth())
532 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
539 void LCursor::setScreenPos(int x, int y)
542 bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
547 void LCursor::plainErase()
553 void LCursor::markInsert()
559 void LCursor::markErase()
565 void LCursor::plainInsert(MathAtom const & t)
567 cell().insert(pos(), t);
572 void LCursor::insert(string const & str)
574 for_each(str.begin(), str.end(),
575 boost::bind(static_cast<void(LCursor::*)(char)>
576 (&LCursor::insert), this, _1));
580 void LCursor::insert(char c)
582 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
583 BOOST_ASSERT(!empty());
585 lyx::cap::selClearOrDel(*this);
586 insert(new MathCharInset(c));
588 text()->insertChar(*this, c);
593 void LCursor::insert(MathAtom const & t)
595 //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
597 lyx::cap::selClearOrDel(*this);
602 void LCursor::insert(InsetBase * inset)
605 insert(MathAtom(inset));
607 text()->insertInset(*this, inset);
611 void LCursor::niceInsert(string const & t)
622 void LCursor::niceInsert(MathAtom const & t)
625 string const safe = lyx::cap::grabAndEraseSelection(*this);
627 // enter the new inset and move the contents of the selection if possible
630 // be careful here: don't use 'pushLeft(t)' as this we need to
631 // push the clone, not the original
632 pushLeft(*nextInset());
638 void LCursor::insert(MathArray const & ar)
642 lyx::cap::eraseSelection(*this);
643 cell().insert(pos(), ar);
648 bool LCursor::backspace()
650 autocorrect() = false;
653 lyx::cap::selDel(*this);
658 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
665 MathUnknownInset * p = activeMacro();
666 if (p->name().size() > 1) {
667 p->setName(p->name().substr(0, p->name().size() - 1));
672 if (pos() != 0 && prevAtom()->nargs() > 0) {
673 // let's require two backspaces for 'big stuff' and
674 // highlight on the first
686 bool LCursor::erase()
688 autocorrect() = false;
693 lyx::cap::selDel(*this);
697 // delete empty cells if possible
698 if (pos() == lastpos() && inset().idxDelete(idx()))
701 // special behaviour when in last position of cell
702 if (pos() == lastpos()) {
703 bool one_cell = inset().nargs() == 1;
704 if (one_cell && depth() == 1 && lastpos() == 0)
710 inset().idxGlue(idx());
714 // 'clever' UI hack: only erase large items if previously slected
715 if (pos() != lastpos() && inset().nargs() > 0) {
730 DocIterator save = *this;
734 autocorrect() = false;
742 DocIterator save = *this;
746 autocorrect() = false;
751 void LCursor::macroModeClose()
755 MathUnknownInset * p = activeMacro();
757 string const s = p->name();
761 // do nothing if the macro name is empty
765 string const name = s.substr(1);
767 // prevent entering of recursive macros
768 // FIXME: this is only a weak attempt... only prevents immediate
770 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
771 if (macro && macro->getInsetName() == name)
772 lyxerr << "can't enter recursive macro" << endl;
774 plainInsert(createMathInset(name));
778 string LCursor::macroName()
780 return inMacroMode() ? activeMacro()->name() : string();
784 void LCursor::handleNest(MathAtom const & a, int c)
786 //lyxerr << "LCursor::handleNest: " << c << endl;
788 asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
791 pushLeft(*nextInset());
795 int LCursor::targetX() const
797 if (x_target() != -1)
806 void LCursor::setTargetX()
808 // For now this is good enough. A better solution would be to
809 // avoid this rebreak by setting cursorX only after drawing
810 bottom().text()->redoParagraph(bottom().pit());
818 bool LCursor::inMacroMode() const
822 MathUnknownInset const * p = prevAtom()->asUnknownInset();
823 return p && !p->final();
827 MathUnknownInset * LCursor::activeMacro()
829 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
833 void LCursor::pullArg()
838 MathArray ar = cell();
839 if (popLeft() && inMathed()) {
841 cell().insert(pos(), ar);
844 //formula()->mutateToText();
849 void LCursor::touch()
855 DocIterator::const_iterator it = begin();
856 DocIterator::const_iterator et = end();
857 for ( ; it != et; ++it)
863 void LCursor::normalize()
865 if (idx() >= nargs()) {
866 lyxerr << "this should not really happen - 1: "
867 << idx() << ' ' << nargs()
868 << " in: " << &inset() << endl;
870 idx() = min(idx(), lastidx());
872 if (pos() > lastpos()) {
873 lyxerr << "this should not really happen - 2: "
874 << pos() << ' ' << lastpos() << " in idx: " << idx()
876 WriteStream wi(lyxerr, false, true);
877 inset().asMathInset()->write(wi);
880 pos() = min(pos(), lastpos());
884 bool LCursor::goUpDown(bool up)
886 // Be warned: The 'logic' implemented in this function is highly
887 // fragile. A distance of one pixel or a '<' vs '<=' _really
888 // matters. So fiddle around with it only if you think you know
889 // what you are doing!
895 // check if we had something else in mind, if not, this is the future goal
896 if (x_target() == -1)
901 // try neigbouring script insets
905 MathScriptInset const * p = prevAtom()->asScriptInset();
906 if (p && p->has(up)) {
909 idx() = up; // the superscript has index 1
911 //lyxerr << "updown: handled by scriptinset to the left" << endl;
917 if (pos() != lastpos()) {
918 MathScriptInset const * p = nextAtom()->asScriptInset();
919 if (p && p->has(up)) {
923 //lyxerr << "updown: handled by scriptinset to the right" << endl;
929 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
934 //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
935 // lyxerr << "updown: handled by brute find in the same cell" << endl;
939 // try to find an inset that knows better then we
941 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
943 if (inset().idxUpDown(*this, up)) {
944 // try to find best position within this inset
946 setCursor(bruteFind2(*this, xo, yo));
950 // no such inset found, just take something "above"
951 //lyxerr << "updown: handled by strange case" << endl;
953 int ylow = up ? 0 : yo + 1;
954 int yhigh = up ? yo - 1 : bv().workHeight();
955 return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
958 // any improvement so far?
962 if (up ? ynew < yo : ynew > yo)
966 // we should not come here.
971 void LCursor::handleFont(string const & font)
973 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << ": " << font << endl;
977 safe = lyx::cap::grabAndEraseSelection(*this);
980 if (lastpos() != 0) {
981 // something left in the cell
983 // cursor in first position
985 } else if (pos() == lastpos()) {
986 // cursor in last position
989 // cursor in between. split cell
990 MathArray::iterator bt = cell().begin();
991 MathAtom at = createMathInset(font);
992 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
993 cell().erase(bt, bt + pos());
998 // nothing left in the cell
1006 void LCursor::message(string const & msg) const
1008 bv().owner()->getLyXFunc().setMessage(msg);
1012 void LCursor::errorMessage(string const & msg) const
1014 bv().owner()->getLyXFunc().setErrorMessage(msg);
1018 string LCursor::selectionAsString(bool label) const
1024 Buffer const & buffer = *bv().buffer();
1025 ParagraphList & pars = text()->paragraphs();
1027 // should be const ...
1028 pit_type startpit = selBegin().pit();
1029 pit_type endpit = selEnd().pit();
1030 size_t const startpos = selBegin().pos();
1031 size_t const endpos = selEnd().pos();
1033 if (startpit == endpit)
1034 return pars[startpit].asString(buffer, startpos, endpos, label);
1036 // First paragraph in selection
1037 string result = pars[startpit].
1038 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1040 // The paragraphs in between (if any)
1041 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1042 Paragraph & par = pars[pit];
1043 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1046 // Last paragraph in selection
1047 result += pars[endpit].asString(buffer, 0, endpos, label);
1052 #ifdef WITH_WARNINGS
1053 #warning and mathed?
1059 string LCursor::currentState()
1062 std::ostringstream os;
1068 return text()->currentState(*this);
1074 string LCursor::getPossibleLabel()
1076 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1080 Encoding const * LCursor::getEncoding() const
1087 // go up until first non-0 text is hit
1088 // (innermost text is 0 in mathed)
1089 for (s = depth() - 1; s >= 0; --s)
1090 if (operator[](s).text())
1092 CursorSlice const & sl = operator[](s);
1093 LyXText const & text = *sl.text();
1094 LyXFont font = text.getPar(sl.pit()).getFont(
1095 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1096 return font.language()->encoding();
1100 void LCursor::undispatched()
1102 disp_.dispatched(false);
1106 void LCursor::dispatched()
1108 disp_.dispatched(true);
1112 void LCursor::needsUpdate()
1118 void LCursor::noUpdate()
1120 disp_.update(false);
1124 LyXFont LCursor::getFont() const
1126 // HACK. far from being perfect...
1128 // go up until first non-0 text is hit
1129 // (innermost text is 0 in mathed)
1130 for (s = depth() - 1; s >= 0; --s)
1131 if (operator[](s).text())
1133 CursorSlice const & sl = operator[](s);
1134 LyXText const & text = *sl.text();
1135 LyXFont font = text.getPar(sl.pit()).getFont(
1136 bv().buffer()->params(),
1138 outerFont(sl.pit(), text.paragraphs()));