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>
59 #ifndef CXX_GLOBAL_CSTD
68 positionable(DocIterator const & cursor, DocIterator const & anchor)
70 // avoid deeper nested insets when selecting
71 if (cursor.size() > anchor.size())
74 // anchor might be deeper, should have same path then
75 for (size_t i = 0; i < cursor.size(); ++i)
76 if (&cursor[i].inset() != &anchor[i].inset())
79 // position should be ok.
84 // Find position closest to (x, y) in cell given by iter.
85 // Used only in mathed
86 DocIterator bruteFind2(LCursor const & c, int x, int y)
88 double best_dist = std::numeric_limits<double>::max();
95 et.back().pos() = et.back().asMathInset()->cell(et.back().idx()).size();
96 for (int i = 0; ; ++i) {
100 cur.inset().getCursorPos(cur.top(), xo, yo);
101 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
102 // '<=' in order to take the last possible position
103 // this is important for clicking behind \sum in e.g. '\sum_i a'
104 lyxerr[Debug::DEBUG] << "i: " << i << " d: " << d
105 << " best: " << best_dist << endl;
106 if (d <= best_dist) {
118 /// moves position closest to (x, y) in given box
119 bool bruteFind(LCursor & cursor,
120 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
122 BOOST_ASSERT(!cursor.empty());
123 CursorSlice bottom = cursor[0];
124 LyXText * text = bottom.text();
127 DocIterator it = doc_iterator_begin(bottom.inset());
128 DocIterator const et = doc_iterator_end(bottom.inset());
130 double best_dist = std::numeric_limits<double>::max();;
131 DocIterator best_cursor = et;
133 for ( ; it != et; it.forwardPos()) {
134 // avoid invalid nesting when selecting
135 if (bv_funcs::status(&cursor.bv(), it) == bv_funcs::CUR_INSIDE
136 && (!cursor.selection() || positionable(it, cursor.anchor_))) {
137 Point p = bv_funcs::getPos(it);
140 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
141 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
142 //lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
143 // '<=' in order to take the last possible position
144 // this is important for clicking behind \sum in e.g. '\sum_i a'
145 if (d <= best_dist) {
146 //lyxerr << "*" << endl;
154 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
155 if (best_cursor != et) {
156 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: " << cmd0 << endl << *this << endl;
199 FuncRequest cmd = cmd0;
200 LCursor safe = *this;
202 for (; size(); pop()) {
203 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
204 BOOST_ASSERT(pos() <= lastpos());
205 BOOST_ASSERT(idx() <= lastidx());
206 BOOST_ASSERT(pit() <= lastpit());
208 // The common case is 'LFUN handled, need update', so make the
209 // LFUN handler's life easier by assuming this as default value.
210 // The handler can reset the update and val flags if necessary.
212 disp_.dispatched(true);
213 inset().dispatch(*this, cmd);
214 if (disp_.dispatched())
217 // it completely to get a 'bomb early' behaviour in case this
218 // object will be used again.
219 if (!disp_.dispatched()) {
220 lyxerr[Debug::DEBUG] << "RESTORING OLD CURSOR!" << endl;
222 disp_.dispatched(false);
227 DispatchResult LCursor::result() const
233 BufferView & LCursor::bv() const
240 Buffer & LCursor::buffer() const
243 BOOST_ASSERT(bv_->buffer());
244 return *bv_->buffer();
250 BOOST_ASSERT(size() >= 1);
255 void LCursor::push(InsetBase & p)
257 push_back(CursorSlice(p));
261 void LCursor::pushLeft(InsetBase & p)
263 BOOST_ASSERT(!empty());
264 //lyxerr << "Entering inset " << t << " left" << endl;
270 bool LCursor::popLeft()
272 BOOST_ASSERT(!empty());
273 //lyxerr << "Leaving inset to the left" << endl;
274 inset().notifyCursorLeaves(*this);
282 bool LCursor::popRight()
284 BOOST_ASSERT(!empty());
285 //lyxerr << "Leaving inset to the right" << endl;
286 inset().notifyCursorLeaves(*this);
295 int LCursor::currentMode()
297 BOOST_ASSERT(!empty());
298 for (int i = size() - 1; i >= 0; --i) {
299 int res = operator[](i).inset().currentMode();
300 if (res != InsetBase::UNDECIDED_MODE)
303 return InsetBase::TEXT_MODE;
307 void LCursor::getDim(int & asc, int & des) const
310 BOOST_ASSERT(inset().asMathInset());
311 //inset().asMathInset()->getCursorDim(asc, des);
314 } else if (inTexted()) {
315 LyXFont const & realfont = text()->real_current_font;
316 asc = font_metrics::maxAscent(realfont);
317 des = font_metrics::maxDescent(realfont);
319 lyxerr << "should this happen?" << endl;
326 void LCursor::getPos(int & x, int & y) const
328 Point p = bv_funcs::getPos(*this);
334 void LCursor::paste(string const & data)
336 dispatch(FuncRequest(LFUN_PASTE, data));
340 void LCursor::resetAnchor()
347 bool LCursor::posLeft()
356 bool LCursor::posRight()
358 if (pos() == lastpos())
365 CursorSlice LCursor::anchor() const
367 BOOST_ASSERT(anchor_.size() >= size());
368 CursorSlice normal = anchor_[size() - 1];
369 if (size() < anchor_.size() && back() <= normal) {
370 // anchor is behind cursor -> move anchor behind the inset
377 CursorSlice LCursor::selBegin() const
381 return anchor() < back() ? anchor() : back();
385 CursorSlice LCursor::selEnd() const
389 return anchor() > back() ? anchor() : back();
393 DocIterator LCursor::selectionBegin() const
397 return anchor() < back() ? anchor_ : *this;
401 DocIterator LCursor::selectionEnd() const
405 return anchor() > back() ? anchor_ : *this;
409 void LCursor::setSelection()
412 // a selection with no contents is not a selection
414 #warning doesnt look ok
416 if (pit() == anchor().pit() && pos() == anchor().pos())
421 void LCursor::setSelection(DocIterator const & where, size_t n)
430 void LCursor::clearSelection()
439 int & LCursor::x_target()
445 int LCursor::x_target() const
451 void LCursor::clearTargetX()
458 void LCursor::info(std::ostream & os) const
460 for (int i = 1, n = depth(); i < n; ++i) {
461 operator[](i).inset().infoize(os);
465 prevInset()->infoize2(os);
466 // overwite old message
471 void LCursor::selHandle(bool sel)
473 //lyxerr << "LCursor::selHandle" << endl;
474 if (sel == selection())
482 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
484 os << "\n cursor: | anchor:\n";
485 for (size_t i = 0, n = cur.size(); i != n; ++i) {
486 os << " " << cur.operator[](i) << " | ";
487 if (i < cur.anchor_.size())
488 os << cur.anchor_[i];
490 os << "-------------------------------";
493 for (size_t i = cur.size(), n = cur.anchor_.size(); i < n; ++i) {
494 os << "------------------------------- | " << cur.anchor_[i] << "\n";
496 os << " selection: " << cur.selection_
497 << " x_target: " << cur.x_target_ << endl;
504 ///////////////////////////////////////////////////////////////////
506 // The part below is the non-integrated rest of the original math
507 // cursor. This should be either generalized for texted or moved
508 // back to mathed (in most cases to MathNestInset).
510 ///////////////////////////////////////////////////////////////////
512 #include "mathed/math_charinset.h"
513 #include "mathed/math_factory.h"
514 #include "mathed/math_gridinset.h"
515 #include "mathed/math_macroarg.h"
516 #include "mathed/math_mathmlstream.h"
517 #include "mathed/math_scriptinset.h"
518 #include "mathed/math_support.h"
519 #include "mathed/math_unknowninset.h"
521 //#define FILEDEBUG 1
524 bool LCursor::isInside(InsetBase const * p)
526 for (unsigned i = 0; i < depth(); ++i)
527 if (&operator[](i).inset() == p)
533 bool LCursor::openable(MathAtom const & t) const
544 // we can't move into anything new during selection
545 if (depth() >= anchor_.size())
547 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
554 void LCursor::setScreenPos(int x, int y)
557 bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
562 void LCursor::plainErase()
568 void LCursor::markInsert()
574 void LCursor::markErase()
580 void LCursor::plainInsert(MathAtom const & t)
582 cell().insert(pos(), t);
587 void LCursor::insert(string const & str)
589 for_each(str.begin(), str.end(),
590 boost::bind(static_cast<void(LCursor::*)(char)>
591 (&LCursor::insert), this, _1));
595 void LCursor::insert(char c)
597 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
598 BOOST_ASSERT(!empty());
600 lyx::cap::selClearOrDel(*this);
601 insert(new MathCharInset(c));
603 text()->insertChar(*this, c);
608 void LCursor::insert(MathAtom const & t)
610 //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
612 lyx::cap::selClearOrDel(*this);
617 void LCursor::insert(InsetBase * inset)
620 insert(MathAtom(inset));
622 text()->insertInset(*this, inset);
626 void LCursor::niceInsert(string const & t)
637 void LCursor::niceInsert(MathAtom const & t)
640 string safe = lyx::cap::grabAndEraseSelection(*this);
642 // enter the new inset and move the contents of the selection if possible
645 // be careful here: don't use 'pushLeft(t)' as this we need to
646 // push the clone, not the original
647 pushLeft(*nextInset());
653 void LCursor::insert(MathArray const & ar)
657 lyx::cap::eraseSelection(*this);
658 cell().insert(pos(), ar);
663 bool LCursor::backspace()
665 autocorrect() = false;
668 lyx::cap::selDel(*this);
673 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
680 MathUnknownInset * p = activeMacro();
681 if (p->name().size() > 1) {
682 p->setName(p->name().substr(0, p->name().size() - 1));
687 if (pos() != 0 && prevAtom()->nargs() > 0) {
688 // let's require two backspaces for 'big stuff' and
689 // highlight on the first
701 bool LCursor::erase()
703 autocorrect() = false;
708 lyx::cap::selDel(*this);
712 // delete empty cells if possible
713 if (pos() == lastpos() && inset().idxDelete(idx()))
716 // special behaviour when in last position of cell
717 if (pos() == lastpos()) {
718 bool one_cell = inset().nargs() == 1;
719 if (one_cell && depth() == 1 && lastpos() == 0)
725 inset().idxGlue(idx());
729 // 'clever' UI hack: only erase large items if previously slected
730 if (pos() != lastpos() && inset().nargs() > 0) {
745 DocIterator save = *this;
749 autocorrect() = false;
757 DocIterator save = *this;
761 autocorrect() = false;
766 void LCursor::macroModeClose()
770 MathUnknownInset * p = activeMacro();
772 string s = p->name();
776 // do nothing if the macro name is empty
780 string const name = s.substr(1);
782 // prevent entering of recursive macros
783 // FIXME: this is only a weak attempt... only prevents immediate
785 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
786 if (macro && macro->getInsetName() == name)
787 lyxerr << "can't enter recursive macro" << endl;
789 plainInsert(createMathInset(name));
793 string LCursor::macroName()
795 return inMacroMode() ? activeMacro()->name() : string();
799 void LCursor::handleNest(MathAtom const & a, int c)
801 //lyxerr << "LCursor::handleNest: " << c << endl;
803 asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
806 pushLeft(*nextInset());
810 int LCursor::targetX() const
812 if (x_target() != -1)
821 void LCursor::setTargetX()
823 //for now this is good enough. A better solution would be to
824 //avoid this rebreak by setting cursorX only after drawing
825 bottom().text()->redoParagraph(bottom().pit());
832 bool LCursor::inMacroMode() const
836 MathUnknownInset const * p = prevAtom()->asUnknownInset();
837 return p && !p->final();
841 MathUnknownInset * LCursor::activeMacro()
843 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
847 void LCursor::pullArg()
852 MathArray ar = cell();
853 if (popLeft() && inMathed()) {
855 cell().insert(pos(), ar);
858 //formula()->mutateToText();
863 void LCursor::touch()
869 DocIterator::const_iterator it = begin();
870 DocIterator::const_iterator et = end();
871 for ( ; it != et; ++it)
877 void LCursor::normalize()
879 if (idx() >= nargs()) {
880 lyxerr << "this should not really happen - 1: "
881 << idx() << ' ' << nargs()
882 << " in: " << &inset() << endl;
884 idx() = min(idx(), lastidx());
886 if (pos() > lastpos()) {
887 lyxerr << "this should not really happen - 2: "
888 << pos() << ' ' << lastpos() << " in idx: " << idx()
890 WriteStream wi(lyxerr, false, true);
891 inset().asMathInset()->write(wi);
894 pos() = min(pos(), lastpos());
898 bool LCursor::goUpDown(bool up)
900 // Be warned: The 'logic' implemented in this function is highly
901 // fragile. A distance of one pixel or a '<' vs '<=' _really
902 // matters. So fiddle around with it only if you think you know
903 // what you are doing!
909 // check if we had something else in mind, if not, this is the future goal
910 if (x_target() == -1)
915 // try neigbouring script insets
919 MathScriptInset const * p = prevAtom()->asScriptInset();
920 if (p && p->has(up)) {
923 idx() = up; // the superscript has index 1
925 //lyxerr << "updown: handled by scriptinset to the left" << endl;
931 if (pos() != lastpos()) {
932 MathScriptInset const * p = nextAtom()->asScriptInset();
933 if (p && p->has(up)) {
937 //lyxerr << "updown: handled by scriptinset to the right" << endl;
943 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
948 //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
949 // lyxerr << "updown: handled by brute find in the same cell" << endl;
953 // try to find an inset that knows better then we
955 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
957 if (inset().idxUpDown(*this, up)) {
958 // try to find best position within this inset
960 setCursor(bruteFind2(*this, xo, yo));
964 // no such inset found, just take something "above"
965 //lyxerr << "updown: handled by strange case" << endl;
967 int ylow = up ? 0 : yo + 1;
968 int yhigh = up ? yo - 1 : bv().workHeight();
969 return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
972 // any improvement so far?
975 if (up ? ynew < yo : ynew > yo)
979 // we should not come here.
984 void LCursor::handleFont(string const & font)
986 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << ": " << font << endl;
990 safe = lyx::cap::grabAndEraseSelection(*this);
993 if (lastpos() != 0) {
994 // something left in the cell
996 // cursor in first position
998 } else if (pos() == lastpos()) {
999 // cursor in last position
1002 // cursor in between. split cell
1003 MathArray::iterator bt = cell().begin();
1004 MathAtom at = createMathInset(font);
1005 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1006 cell().erase(bt, bt + pos());
1011 // nothing left in the cell
1019 void LCursor::message(string const & msg) const
1021 bv().owner()->getLyXFunc().setMessage(msg);
1025 void LCursor::errorMessage(string const & msg) const
1027 bv().owner()->getLyXFunc().setErrorMessage(msg);
1031 string LCursor::selectionAsString(bool label) const
1037 Buffer const & buffer = *bv().buffer();
1038 ParagraphList & pars = text()->paragraphs();
1040 // should be const ...
1041 pit_type startpit = selBegin().pit();
1042 pit_type endpit = selEnd().pit();
1043 size_t const startpos = selBegin().pos();
1044 size_t const endpos = selEnd().pos();
1046 if (startpit == endpit)
1047 return pars[startpit].asString(buffer, startpos, endpos, label);
1049 // First paragraph in selection
1050 string result = pars[startpit].
1051 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1053 // The paragraphs in between (if any)
1054 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1055 Paragraph & par = pars[pit];
1056 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1059 // Last paragraph in selection
1060 result += pars[endpit].asString(buffer, 0, endpos, label);
1065 #ifdef WITH_WARNINGS
1066 #warning and mathed?
1072 string LCursor::currentState()
1075 std::ostringstream os;
1081 return text()->currentState(*this);
1087 string LCursor::getPossibleLabel()
1089 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1093 Encoding const * LCursor::getEncoding() const
1100 // go up until first non-0 text is hit
1101 // (innermost text is 0 in mathed)
1102 for (s = size() - 1; s >= 0; --s)
1103 if (operator[](s).text())
1105 CursorSlice const & sl = operator[](s);
1106 LyXText & text = *sl.text();
1107 LyXFont font = text.getPar(sl.pit()).getFont(
1108 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1109 return font.language()->encoding();
1113 void LCursor::undispatched()
1115 disp_.dispatched(false);
1119 void LCursor::dispatched()
1121 disp_.dispatched(true);
1125 void LCursor::needsUpdate()
1131 void LCursor::noUpdate()
1133 disp_.update(false);