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);
166 // be careful: this is called from the bv's constructor, too, so
167 // bv functions are not yet available!
168 LCursor::LCursor(BufferView & bv)
169 : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
170 selection_(false), mark_(false)
174 void LCursor::reset(InsetBase & inset)
177 push_back(CursorSlice(inset));
178 anchor_ = DocIterator(inset);
185 // this (intentionally) does neither touch anchor nor selection status
186 void LCursor::setCursor(DocIterator const & cur)
188 DocIterator::operator=(cur);
192 void LCursor::dispatch(FuncRequest const & cmd0)
194 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: "
195 << cmd0 << endl << *this << endl;
199 FuncRequest cmd = cmd0;
200 LCursor safe = *this;
202 for (; size(); pop()) {
203 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: "
204 << cmd0 << endl << *this << endl;
205 BOOST_ASSERT(pos() <= lastpos());
206 BOOST_ASSERT(idx() <= lastidx());
207 BOOST_ASSERT(pit() <= lastpit());
209 // The common case is 'LFUN handled, need update', so make the
210 // LFUN handler's life easier by assuming this as default value.
211 // The handler can reset the update and val flags if necessary.
213 disp_.dispatched(true);
214 inset().dispatch(*this, cmd);
215 if (disp_.dispatched())
218 // it completely to get a 'bomb early' behaviour in case this
219 // object will be used again.
220 if (!disp_.dispatched()) {
221 lyxerr[Debug::DEBUG] << "RESTORING OLD CURSOR!" << endl;
223 disp_.dispatched(false);
228 DispatchResult LCursor::result() const
234 BufferView & LCursor::bv() const
241 Buffer & LCursor::buffer() const
244 BOOST_ASSERT(bv_->buffer());
245 return *bv_->buffer();
251 BOOST_ASSERT(size() >= 1);
256 void LCursor::push(InsetBase & p)
258 push_back(CursorSlice(p));
262 void LCursor::pushLeft(InsetBase & p)
264 BOOST_ASSERT(!empty());
265 //lyxerr << "Entering inset " << t << " left" << endl;
271 bool LCursor::popLeft()
273 BOOST_ASSERT(!empty());
274 //lyxerr << "Leaving inset to the left" << endl;
275 inset().notifyCursorLeaves(*this);
283 bool LCursor::popRight()
285 BOOST_ASSERT(!empty());
286 //lyxerr << "Leaving inset to the right" << endl;
287 inset().notifyCursorLeaves(*this);
296 int LCursor::currentMode()
298 BOOST_ASSERT(!empty());
299 for (int i = size() - 1; i >= 0; --i) {
300 int res = operator[](i).inset().currentMode();
301 if (res != InsetBase::UNDECIDED_MODE)
304 return InsetBase::TEXT_MODE;
308 void LCursor::getPos(int & x, int & y) const
310 Point p = bv_funcs::getPos(*this);
316 void LCursor::paste(string const & data)
318 dispatch(FuncRequest(LFUN_PASTE, data));
322 void LCursor::resetAnchor()
329 bool LCursor::posLeft()
338 bool LCursor::posRight()
340 if (pos() == lastpos())
347 CursorSlice LCursor::anchor() const
349 BOOST_ASSERT(anchor_.size() >= size());
350 CursorSlice normal = anchor_[size() - 1];
351 if (size() < anchor_.size() && back() <= normal) {
352 // anchor is behind cursor -> move anchor behind the inset
359 CursorSlice LCursor::selBegin() const
363 return anchor() < back() ? anchor() : back();
367 CursorSlice LCursor::selEnd() const
371 return anchor() > back() ? anchor() : back();
375 DocIterator LCursor::selectionBegin() const
379 return anchor() < back() ? anchor_ : *this;
383 DocIterator LCursor::selectionEnd() const
387 return anchor() > back() ? anchor_ : *this;
391 void LCursor::setSelection()
394 // a selection with no contents is not a selection
396 #warning doesnt look ok
398 if (pit() == anchor().pit() && pos() == anchor().pos())
403 void LCursor::setSelection(DocIterator const & where, size_t n)
412 void LCursor::clearSelection()
421 int & LCursor::x_target()
427 int LCursor::x_target() const
433 void LCursor::clearTargetX()
440 void LCursor::info(std::ostream & os) const
442 for (int i = 1, n = depth(); i < n; ++i) {
443 operator[](i).inset().infoize(os);
447 prevInset()->infoize2(os);
448 // overwite old message
453 void LCursor::selHandle(bool sel)
455 //lyxerr << "LCursor::selHandle" << endl;
456 if (sel == selection())
464 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
466 os << "\n cursor: | anchor:\n";
467 for (size_t i = 0, n = cur.size(); i != n; ++i) {
468 os << " " << cur.operator[](i) << " | ";
469 if (i < cur.anchor_.size())
470 os << cur.anchor_[i];
472 os << "-------------------------------";
475 for (size_t i = cur.size(), n = cur.anchor_.size(); i < n; ++i) {
476 os << "------------------------------- | " << cur.anchor_[i] << "\n";
478 os << " selection: " << cur.selection_
479 << " x_target: " << cur.x_target_ << endl;
486 ///////////////////////////////////////////////////////////////////
488 // The part below is the non-integrated rest of the original math
489 // cursor. This should be either generalized for texted or moved
490 // back to mathed (in most cases to MathNestInset).
492 ///////////////////////////////////////////////////////////////////
494 #include "mathed/math_charinset.h"
495 #include "mathed/math_factory.h"
496 #include "mathed/math_gridinset.h"
497 #include "mathed/math_macroarg.h"
498 #include "mathed/math_mathmlstream.h"
499 #include "mathed/math_scriptinset.h"
500 #include "mathed/math_support.h"
501 #include "mathed/math_unknowninset.h"
503 //#define FILEDEBUG 1
506 bool LCursor::isInside(InsetBase const * p)
508 for (unsigned i = 0; i < depth(); ++i)
509 if (&operator[](i).inset() == p)
515 bool LCursor::openable(MathAtom const & t) const
526 // we can't move into anything new during selection
527 if (depth() >= anchor_.size())
529 if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
536 void LCursor::setScreenPos(int x, int y)
539 bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
544 void LCursor::plainErase()
550 void LCursor::markInsert()
556 void LCursor::markErase()
562 void LCursor::plainInsert(MathAtom const & t)
564 cell().insert(pos(), t);
569 void LCursor::insert(string const & str)
571 for_each(str.begin(), str.end(),
572 boost::bind(static_cast<void(LCursor::*)(char)>
573 (&LCursor::insert), this, _1));
577 void LCursor::insert(char c)
579 //lyxerr << "LCursor::insert char '" << c << "'" << endl;
580 BOOST_ASSERT(!empty());
582 lyx::cap::selClearOrDel(*this);
583 insert(new MathCharInset(c));
585 text()->insertChar(*this, c);
590 void LCursor::insert(MathAtom const & t)
592 //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
594 lyx::cap::selClearOrDel(*this);
599 void LCursor::insert(InsetBase * inset)
602 insert(MathAtom(inset));
604 text()->insertInset(*this, inset);
608 void LCursor::niceInsert(string const & t)
619 void LCursor::niceInsert(MathAtom const & t)
622 string safe = lyx::cap::grabAndEraseSelection(*this);
624 // enter the new inset and move the contents of the selection if possible
627 // be careful here: don't use 'pushLeft(t)' as this we need to
628 // push the clone, not the original
629 pushLeft(*nextInset());
635 void LCursor::insert(MathArray const & ar)
639 lyx::cap::eraseSelection(*this);
640 cell().insert(pos(), ar);
645 bool LCursor::backspace()
647 autocorrect() = false;
650 lyx::cap::selDel(*this);
655 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
662 MathUnknownInset * p = activeMacro();
663 if (p->name().size() > 1) {
664 p->setName(p->name().substr(0, p->name().size() - 1));
669 if (pos() != 0 && prevAtom()->nargs() > 0) {
670 // let's require two backspaces for 'big stuff' and
671 // highlight on the first
683 bool LCursor::erase()
685 autocorrect() = false;
690 lyx::cap::selDel(*this);
694 // delete empty cells if possible
695 if (pos() == lastpos() && inset().idxDelete(idx()))
698 // special behaviour when in last position of cell
699 if (pos() == lastpos()) {
700 bool one_cell = inset().nargs() == 1;
701 if (one_cell && depth() == 1 && lastpos() == 0)
707 inset().idxGlue(idx());
711 // 'clever' UI hack: only erase large items if previously slected
712 if (pos() != lastpos() && inset().nargs() > 0) {
727 DocIterator save = *this;
731 autocorrect() = false;
739 DocIterator save = *this;
743 autocorrect() = false;
748 void LCursor::macroModeClose()
752 MathUnknownInset * p = activeMacro();
754 string s = p->name();
758 // do nothing if the macro name is empty
762 string const name = s.substr(1);
764 // prevent entering of recursive macros
765 // FIXME: this is only a weak attempt... only prevents immediate
767 InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
768 if (macro && macro->getInsetName() == name)
769 lyxerr << "can't enter recursive macro" << endl;
771 plainInsert(createMathInset(name));
775 string LCursor::macroName()
777 return inMacroMode() ? activeMacro()->name() : string();
781 void LCursor::handleNest(MathAtom const & a, int c)
783 //lyxerr << "LCursor::handleNest: " << c << endl;
785 asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
788 pushLeft(*nextInset());
792 int LCursor::targetX() const
794 if (x_target() != -1)
803 void LCursor::setTargetX()
805 //for now this is good enough. A better solution would be to
806 //avoid this rebreak by setting cursorX only after drawing
807 bottom().text()->redoParagraph(bottom().pit());
814 bool LCursor::inMacroMode() const
818 MathUnknownInset const * p = prevAtom()->asUnknownInset();
819 return p && !p->final();
823 MathUnknownInset * LCursor::activeMacro()
825 return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
829 void LCursor::pullArg()
834 MathArray ar = cell();
835 if (popLeft() && inMathed()) {
837 cell().insert(pos(), ar);
840 //formula()->mutateToText();
845 void LCursor::touch()
851 DocIterator::const_iterator it = begin();
852 DocIterator::const_iterator et = end();
853 for ( ; it != et; ++it)
859 void LCursor::normalize()
861 if (idx() >= nargs()) {
862 lyxerr << "this should not really happen - 1: "
863 << idx() << ' ' << nargs()
864 << " in: " << &inset() << endl;
866 idx() = min(idx(), lastidx());
868 if (pos() > lastpos()) {
869 lyxerr << "this should not really happen - 2: "
870 << pos() << ' ' << lastpos() << " in idx: " << idx()
872 WriteStream wi(lyxerr, false, true);
873 inset().asMathInset()->write(wi);
876 pos() = min(pos(), lastpos());
880 bool LCursor::goUpDown(bool up)
882 // Be warned: The 'logic' implemented in this function is highly
883 // fragile. A distance of one pixel or a '<' vs '<=' _really
884 // matters. So fiddle around with it only if you think you know
885 // what you are doing!
891 // check if we had something else in mind, if not, this is the future goal
892 if (x_target() == -1)
897 // try neigbouring script insets
901 MathScriptInset const * p = prevAtom()->asScriptInset();
902 if (p && p->has(up)) {
905 idx() = up; // the superscript has index 1
907 //lyxerr << "updown: handled by scriptinset to the left" << endl;
913 if (pos() != lastpos()) {
914 MathScriptInset const * p = nextAtom()->asScriptInset();
915 if (p && p->has(up)) {
919 //lyxerr << "updown: handled by scriptinset to the right" << endl;
925 //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
930 //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
931 // lyxerr << "updown: handled by brute find in the same cell" << endl;
935 // try to find an inset that knows better then we
937 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
939 if (inset().idxUpDown(*this, up)) {
940 // try to find best position within this inset
942 setCursor(bruteFind2(*this, xo, yo));
946 // no such inset found, just take something "above"
947 //lyxerr << "updown: handled by strange case" << endl;
949 int ylow = up ? 0 : yo + 1;
950 int yhigh = up ? yo - 1 : bv().workHeight();
951 return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
954 // any improvement so far?
957 if (up ? ynew < yo : ynew > yo)
961 // we should not come here.
966 void LCursor::handleFont(string const & font)
968 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << ": " << font << endl;
972 safe = lyx::cap::grabAndEraseSelection(*this);
975 if (lastpos() != 0) {
976 // something left in the cell
978 // cursor in first position
980 } else if (pos() == lastpos()) {
981 // cursor in last position
984 // cursor in between. split cell
985 MathArray::iterator bt = cell().begin();
986 MathAtom at = createMathInset(font);
987 at.nucleus()->cell(0) = MathArray(bt, bt + pos());
988 cell().erase(bt, bt + pos());
993 // nothing left in the cell
1001 void LCursor::message(string const & msg) const
1003 bv().owner()->getLyXFunc().setMessage(msg);
1007 void LCursor::errorMessage(string const & msg) const
1009 bv().owner()->getLyXFunc().setErrorMessage(msg);
1013 string LCursor::selectionAsString(bool label) const
1019 Buffer const & buffer = *bv().buffer();
1020 ParagraphList & pars = text()->paragraphs();
1022 // should be const ...
1023 pit_type startpit = selBegin().pit();
1024 pit_type endpit = selEnd().pit();
1025 size_t const startpos = selBegin().pos();
1026 size_t const endpos = selEnd().pos();
1028 if (startpit == endpit)
1029 return pars[startpit].asString(buffer, startpos, endpos, label);
1031 // First paragraph in selection
1032 string result = pars[startpit].
1033 asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1035 // The paragraphs in between (if any)
1036 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1037 Paragraph & par = pars[pit];
1038 result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1041 // Last paragraph in selection
1042 result += pars[endpit].asString(buffer, 0, endpos, label);
1047 #ifdef WITH_WARNINGS
1048 #warning and mathed?
1054 string LCursor::currentState()
1057 std::ostringstream os;
1063 return text()->currentState(*this);
1069 string LCursor::getPossibleLabel()
1071 return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1075 Encoding const * LCursor::getEncoding() const
1082 // go up until first non-0 text is hit
1083 // (innermost text is 0 in mathed)
1084 for (s = size() - 1; s >= 0; --s)
1085 if (operator[](s).text())
1087 CursorSlice const & sl = operator[](s);
1088 LyXText & text = *sl.text();
1089 LyXFont font = text.getPar(sl.pit()).getFont(
1090 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1091 return font.language()->encoding();
1095 void LCursor::undispatched()
1097 disp_.dispatched(false);
1101 void LCursor::dispatched()
1103 disp_.dispatched(true);
1107 void LCursor::needsUpdate()
1113 void LCursor::noUpdate()
1115 disp_.update(false);
1119 LyXFont LCursor::getFont() const
1121 // HACK. far from being perfect...
1123 // go up until first non-0 text is hit
1124 // (innermost text is 0 in mathed)
1125 for (s = size() - 1; s >= 0; --s)
1126 if (operator[](s).text())
1128 CursorSlice const & sl = operator[](s);
1129 LyXText & text = *sl.text();
1130 LyXFont font = text.getPar(sl.pit()).getFont(
1131 bv().buffer()->params(),
1133 outerFont(sl.pit(), text.paragraphs()));
1134 for (; s < size(); ++s)