]> git.lyx.org Git - lyx.git/blob - src/Cursor.cpp
6868651e212bfed80d54da1defde1fad39b06e67
[lyx.git] / src / Cursor.cpp
1 /**
2  * \file Cursor.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alejandro Aguilar Sierra
7  * \author Alfredo Braunstein
8  * \author André Pönitz
9  * \author Stefan Schimanski
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "Bidi.h"
17 #include "Buffer.h"
18 #include "BufferView.h"
19 #include "CoordCache.h"
20 #include "Cursor.h"
21 #include "CutAndPaste.h"
22 #include "DispatchResult.h"
23 #include "Encoding.h"
24 #include "Font.h"
25 #include "FuncRequest.h"
26 #include "Language.h"
27 #include "lfuns.h"
28 #include "LyXFunc.h" // only for setMessage()
29 #include "LyXRC.h"
30 #include "paragraph_funcs.h"
31 #include "Paragraph.h"
32 #include "ParIterator.h"
33 #include "Row.h"
34 #include "Text.h"
35 #include "TextMetrics.h"
36 #include "TocBackend.h"
37
38 #include "support/debug.h"
39 #include "support/docstream.h"
40
41 #include "insets/InsetTabular.h"
42 #include "insets/InsetText.h"
43
44 #include "mathed/InsetMath.h"
45 #include "mathed/InsetMathScript.h"
46 #include "mathed/MacroTable.h"
47 #include "mathed/MathData.h"
48 #include "mathed/MathMacro.h"
49
50 #include <boost/assert.hpp>
51 #include <boost/bind.hpp>
52
53 #include <sstream>
54 #include <limits>
55 #include <map>
56
57 using namespace std;
58
59 namespace lyx {
60
61 namespace {
62
63 bool positionable(DocIterator const & cursor, DocIterator const & anchor)
64 {
65         // avoid deeper nested insets when selecting
66         if (cursor.depth() > anchor.depth())
67                 return false;
68
69         // anchor might be deeper, should have same path then
70         for (size_t i = 0; i < cursor.depth(); ++i)
71                 if (&cursor[i].inset() != &anchor[i].inset())
72                         return false;
73
74         // position should be ok.
75         return true;
76 }
77
78
79 // Find position closest to (x, y) in cell given by iter.
80 // Used only in mathed
81 DocIterator bruteFind2(Cursor const & c, int x, int y)
82 {
83         double best_dist = numeric_limits<double>::max();
84
85         DocIterator result;
86
87         DocIterator it = c;
88         it.top().pos() = 0;
89         DocIterator et = c;
90         et.top().pos() = et.top().asInsetMath()->cell(et.top().idx()).size();
91         for (size_t i = 0;; ++i) {
92                 int xo;
93                 int yo;
94                 Inset const * inset = &it.inset();
95                 map<Inset const *, Geometry> const & data =
96                         c.bv().coordCache().getInsets().getData();
97                 map<Inset const *, Geometry>::const_iterator I = data.find(inset);
98
99                 // FIXME: in the case where the inset is not in the cache, this
100                 // means that no part of it is visible on screen. In this case
101                 // we don't do elaborate search and we just return the forwarded
102                 // DocIterator at its beginning.
103                 if (I == data.end()) {
104                         it.top().pos() = 0;
105                         return it;
106                 }
107
108                 Point o = I->second.pos;
109                 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
110                 // Convert to absolute
111                 xo += o.x_;
112                 yo += o.y_;
113                 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
114                 // '<=' in order to take the last possible position
115                 // this is important for clicking behind \sum in e.g. '\sum_i a'
116                 LYXERR(Debug::DEBUG, "i: " << i << " d: " << d
117                         << " best: " << best_dist);
118                 if (d <= best_dist) {
119                         best_dist = d;
120                         result = it;
121                 }
122                 if (it == et)
123                         break;
124                 it.forwardPos();
125         }
126         return result;
127 }
128
129
130 /*
131 /// moves position closest to (x, y) in given box
132 bool bruteFind(Cursor & cursor,
133         int x, int y, int xlow, int xhigh, int ylow, int yhigh)
134 {
135         BOOST_ASSERT(!cursor.empty());
136         Inset & inset = cursor[0].inset();
137         BufferView & bv = cursor.bv();
138
139         CoordCache::InnerParPosCache const & cache =
140                 bv.coordCache().getParPos().find(cursor.bottom().text())->second;
141         // Get an iterator on the first paragraph in the cache
142         DocIterator it(inset);
143         it.push_back(CursorSlice(inset));
144         it.pit() = cache.begin()->first;
145         // Get an iterator after the last paragraph in the cache
146         DocIterator et(inset);
147         et.push_back(CursorSlice(inset));
148         et.pit() = boost::prior(cache.end())->first;
149         if (et.pit() >= et.lastpit())
150                 et = doc_iterator_end(inset);
151         else
152                 ++et.pit();
153
154         double best_dist = numeric_limits<double>::max();;
155         DocIterator best_cursor = et;
156
157         for ( ; it != et; it.forwardPos(true)) {
158                 // avoid invalid nesting when selecting
159                 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
160                         Point p = bv.getPos(it, false);
161                         int xo = p.x_;
162                         int yo = p.y_;
163                         if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
164                                 double const dx = xo - x;
165                                 double const dy = yo - y;
166                                 double const d = dx * dx + dy * dy;
167                                 // '<=' in order to take the last possible position
168                                 // this is important for clicking behind \sum in e.g. '\sum_i a'
169                                 if (d <= best_dist) {
170                                         //      lyxerr << "*" << endl;
171                                         best_dist   = d;
172                                         best_cursor = it;
173                                 }
174                         }
175                 }
176         }
177
178         if (best_cursor != et) {
179                 cursor.setCursor(best_cursor);
180                 return true;
181         }
182
183         return false;
184 }
185 */
186
187
188 /// moves position closest to (x, y) in given box
189 bool bruteFind3(Cursor & cur, int x, int y, bool up)
190 {
191         BufferView & bv = cur.bv();
192         int ylow  = up ? 0 : y + 1;
193         int yhigh = up ? y - 1 : bv.workHeight();
194         int xlow = 0;
195         int xhigh = bv.workWidth();
196
197 // FIXME: bit more work needed to get 'from' and 'to' right.
198         pit_type from = cur.bottom().pit();
199         //pit_type to = cur.bottom().pit();
200         //lyxerr << "Pit start: " << from << endl;
201
202         //lyxerr << "bruteFind3: x: " << x << " y: " << y
203         //      << " xlow: " << xlow << " xhigh: " << xhigh
204         //      << " ylow: " << ylow << " yhigh: " << yhigh
205         //      << endl;
206         Inset & inset = bv.buffer().inset();
207         DocIterator it = doc_iterator_begin(inset);
208         it.pit() = from;
209         DocIterator et = doc_iterator_end(inset);
210
211         double best_dist = numeric_limits<double>::max();
212         DocIterator best_cursor = et;
213
214         for ( ; it != et; it.forwardPos()) {
215                 // avoid invalid nesting when selecting
216                 if (bv.cursorStatus(it) == CUR_INSIDE
217                                 && (!cur.selection() || positionable(it, cur.anchor_))) {
218                         Point p = bv.getPos(it, false);
219                         int xo = p.x_;
220                         int yo = p.y_;
221                         if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
222                                 double const dx = xo - x;
223                                 double const dy = yo - y;
224                                 double const d = dx * dx + dy * dy;
225                                 //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
226                                 //      << " dx: " << dx << " dy: " << dy
227                                 //      << " idx: " << it.idx() << " pos: " << it.pos()
228                                 //      << " it:\n" << it
229                                 //      << endl;
230                                 // '<=' in order to take the last possible position
231                                 // this is important for clicking behind \sum in e.g. '\sum_i a'
232                                 if (d <= best_dist) {
233                                         //lyxerr << "*" << endl;
234                                         best_dist   = d;
235                                         best_cursor = it;
236                                 }
237                         }
238                 }
239         }
240
241         //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
242         if (best_cursor == et)
243                 return false;
244         cur.setCursor(best_cursor);
245         return true;
246 }
247
248 docstring parbreak(Paragraph const & par)
249 {
250         odocstringstream ods;
251         ods << '\n';
252         // only add blank line if we're not in an ERT or Listings inset
253         if (par.ownerCode() != ERT_CODE
254                         && par.ownerCode() != LISTINGS_CODE)
255                 ods << '\n';
256         return ods.str();
257 }
258
259 } // namespace anon
260
261
262 // be careful: this is called from the bv's constructor, too, so
263 // bv functions are not yet available!
264 Cursor::Cursor(BufferView & bv)
265         : DocIterator(), bv_(&bv), anchor_(), x_target_(-1), textTargetOffset_(0),
266           selection_(false), mark_(false), logicalpos_(false),
267           current_font(inherit_font)
268 {}
269
270
271 void Cursor::reset(Inset & inset)
272 {
273         clear();
274         push_back(CursorSlice(inset));
275         anchor_ = doc_iterator_begin(inset);
276         anchor_.clear();
277         clearTargetX();
278         selection_ = false;
279         mark_ = false;
280 }
281
282
283 // this (intentionally) does neither touch anchor nor selection status
284 void Cursor::setCursor(DocIterator const & cur)
285 {
286         DocIterator::operator=(cur);
287 }
288
289
290 void Cursor::dispatch(FuncRequest const & cmd0)
291 {
292         LYXERR(Debug::DEBUG, "cmd: " << cmd0 << '\n' << *this);
293         if (empty())
294                 return;
295
296         fixIfBroken();
297         FuncRequest cmd = cmd0;
298         Cursor safe = *this;
299         
300         // store some values to be used inside of the handlers
301         beforeDispatchCursor_ = *this;
302         for (; depth(); pop()) {
303                 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
304                         << cmd0 << endl << *this);
305                 BOOST_ASSERT(pos() <= lastpos());
306                 BOOST_ASSERT(idx() <= lastidx());
307                 BOOST_ASSERT(pit() <= lastpit());
308
309                 // The common case is 'LFUN handled, need update', so make the
310                 // LFUN handler's life easier by assuming this as default value.
311                 // The handler can reset the update and val flags if necessary.
312                 disp_.update(Update::FitCursor | Update::Force);
313                 disp_.dispatched(true);
314                 inset().dispatch(*this, cmd);
315                 if (disp_.dispatched())
316                         break;
317         }
318         
319         // it completely to get a 'bomb early' behaviour in case this
320         // object will be used again.
321         if (!disp_.dispatched()) {
322                 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
323                 operator=(safe);
324                 disp_.update(Update::None);
325                 disp_.dispatched(false);
326         } else {
327                 // restore the previous one because nested Cursor::dispatch calls
328                 // are possible which would change it
329                 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
330         }
331 }
332
333
334 DispatchResult Cursor::result() const
335 {
336         return disp_;
337 }
338
339
340 BufferView & Cursor::bv() const
341 {
342         BOOST_ASSERT(bv_);
343         return *bv_;
344 }
345
346
347 Buffer & Cursor::buffer() const
348 {
349         BOOST_ASSERT(bv_);
350         return bv_->buffer();
351 }
352
353
354 void Cursor::pop()
355 {
356         BOOST_ASSERT(depth() >= 1);
357         pop_back();
358 }
359
360
361 void Cursor::push(Inset & p)
362 {
363         push_back(CursorSlice(p));
364 }
365
366
367 void Cursor::pushBackward(Inset & p)
368 {
369         BOOST_ASSERT(!empty());
370         //lyxerr << "Entering inset " << t << " front" << endl;
371         push(p);
372         p.idxFirst(*this);
373 }
374
375
376 bool Cursor::popBackward()
377 {
378         BOOST_ASSERT(!empty());
379         //lyxerr << "Leaving inset from in front" << endl;
380         inset().notifyCursorLeaves(*this);
381         if (depth() == 1)
382                 return false;
383         pop();
384         return true;
385 }
386
387
388 bool Cursor::popForward()
389 {
390         BOOST_ASSERT(!empty());
391         //lyxerr << "Leaving inset from in back" << endl;
392         const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
393         inset().notifyCursorLeaves(*this);
394         if (depth() == 1)
395                 return false;
396         pop();
397         pos() += lastpos() - lp + 1;
398         return true;
399 }
400
401
402 int Cursor::currentMode()
403 {
404         BOOST_ASSERT(!empty());
405         for (int i = depth() - 1; i >= 0; --i) {
406                 int res = operator[](i).inset().currentMode();
407                 if (res != Inset::UNDECIDED_MODE)
408                         return res;
409         }
410         return Inset::TEXT_MODE;
411 }
412
413
414 void Cursor::getPos(int & x, int & y) const
415 {
416         Point p = bv().getPos(*this, boundary());
417         x = p.x_;
418         y = p.y_;
419 }
420
421
422 Row const & Cursor::textRow() const
423 {
424         CursorSlice const & cs = innerTextSlice();
425         ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
426         BOOST_ASSERT(!pm.rows().empty());
427         return pm.getRow(pos(), boundary());
428 }
429
430
431 void Cursor::resetAnchor()
432 {
433         anchor_ = *this;
434 }
435
436
437
438 bool Cursor::posBackward()
439 {
440         if (pos() == 0)
441                 return false;
442         --pos();
443         return true;
444 }
445
446
447 bool Cursor::posForward()
448 {
449         if (pos() == lastpos())
450                 return false;
451         ++pos();
452         return true;
453 }
454
455
456 CursorSlice Cursor::anchor() const
457 {
458         BOOST_ASSERT(anchor_.depth() >= depth());
459         CursorSlice normal = anchor_[depth() - 1];
460         if (depth() < anchor_.depth() && top() <= normal) {
461                 // anchor is behind cursor -> move anchor behind the inset
462                 ++normal.pos();
463         }
464         return normal;
465 }
466
467
468 CursorSlice Cursor::selBegin() const
469 {
470         if (!selection())
471                 return top();
472         return anchor() < top() ? anchor() : top();
473 }
474
475
476 CursorSlice Cursor::selEnd() const
477 {
478         if (!selection())
479                 return top();
480         return anchor() > top() ? anchor() : top();
481 }
482
483
484 DocIterator Cursor::selectionBegin() const
485 {
486         if (!selection())
487                 return *this;
488         DocIterator di = (anchor() < top() ? anchor_ : *this);
489         di.resize(depth());
490         return di;
491 }
492
493
494 DocIterator Cursor::selectionEnd() const
495 {
496         if (!selection())
497                 return *this;
498         DocIterator di = (anchor() > top() ? anchor_ : *this);
499         if (di.depth() > depth()) {
500                 di.resize(depth());
501                 ++di.pos();
502         }
503         return di;
504 }
505
506
507 void Cursor::setSelection()
508 {
509         selection() = true;
510         // A selection with no contents is not a selection
511         // FIXME: doesnt look ok
512         if (pit() == anchor().pit() && pos() == anchor().pos())
513                 selection() = false;
514 }
515
516
517 void Cursor::setSelection(DocIterator const & where, int n)
518 {
519         setCursor(where);
520         selection() = true;
521         anchor_ = where;
522         pos() += n;
523 }
524
525
526 void Cursor::clearSelection()
527 {
528         selection() = false;
529         mark() = false;
530         resetAnchor();
531 }
532
533
534 void Cursor::setTargetX(int x)
535 {
536         x_target_ = x;
537         textTargetOffset_ = 0;
538 }
539
540
541 int Cursor::x_target() const
542 {
543         return x_target_;
544 }
545
546
547 void Cursor::clearTargetX()
548 {
549         x_target_ = -1;
550         textTargetOffset_ = 0;
551 }
552
553
554 void Cursor::updateTextTargetOffset()
555 {
556         int x;
557         int y;
558         getPos(x, y);
559         textTargetOffset_ = x - x_target_;
560 }
561
562
563 void Cursor::info(odocstream & os) const
564 {
565         for (int i = 1, n = depth(); i < n; ++i) {
566                 operator[](i).inset().infoize(os);
567                 os << "  ";
568         }
569         if (pos() != 0) {
570                 Inset const * inset = prevInset();
571                 // prevInset() can return 0 in certain case.
572                 if (inset)
573                         prevInset()->infoize2(os);
574         }
575         // overwite old message
576         os << "                    ";
577 }
578
579
580 bool Cursor::selHandle(bool sel)
581 {
582         //lyxerr << "Cursor::selHandle" << endl;
583         if (mark())
584                 sel = true;
585         if (sel == selection())
586                 return false;
587
588         if (!sel)
589                 cap::saveSelection(*this);
590
591         resetAnchor();
592         selection() = sel;
593         return true;
594 }
595
596
597 ostream & operator<<(ostream & os, Cursor const & cur)
598 {
599         os << "\n cursor:                                | anchor:\n";
600         for (size_t i = 0, n = cur.depth(); i != n; ++i) {
601                 os << " " << cur[i] << " | ";
602                 if (i < cur.anchor_.depth())
603                         os << cur.anchor_[i];
604                 else
605                         os << "-------------------------------";
606                 os << "\n";
607         }
608         for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
609                 os << "------------------------------- | " << cur.anchor_[i] << "\n";
610         }
611         os << " selection: " << cur.selection_
612            << " x_target: " << cur.x_target_ << endl;
613         return os;
614 }
615
616
617 LyXErr & operator<<(LyXErr & os, Cursor const & cur)
618 {
619         os.stream() << cur;
620         return os;
621 }
622
623
624 } // namespace lyx
625
626
627 ///////////////////////////////////////////////////////////////////
628 //
629 // FIXME: Look here
630 // The part below is the non-integrated rest of the original math
631 // cursor. This should be either generalized for texted or moved
632 // back to mathed (in most cases to InsetMathNest).
633 //
634 ///////////////////////////////////////////////////////////////////
635
636 #include "mathed/InsetMathChar.h"
637 #include "mathed/InsetMathGrid.h"
638 #include "mathed/InsetMathScript.h"
639 #include "mathed/InsetMathUnknown.h"
640 #include "mathed/MathFactory.h"
641 #include "mathed/MathStream.h"
642 #include "mathed/MathSupport.h"
643
644
645 namespace lyx {
646
647 //#define FILEDEBUG 1
648
649
650 bool Cursor::isInside(Inset const * p) const
651 {
652         for (size_t i = 0; i != depth(); ++i)
653                 if (&operator[](i).inset() == p)
654                         return true;
655         return false;
656 }
657
658
659 void Cursor::leaveInset(Inset const & inset)
660 {
661         for (size_t i = 0; i != depth(); ++i) {
662                 if (&operator[](i).inset() == &inset) {
663                         resize(i);
664                         return;
665                 }
666         }
667 }
668
669
670 bool Cursor::openable(MathAtom const & t) const
671 {
672         if (!t->isActive())
673                 return false;
674
675         if (t->lock())
676                 return false;
677
678         if (!selection())
679                 return true;
680
681         // we can't move into anything new during selection
682         if (depth() >= anchor_.depth())
683                 return false;
684         if (t.nucleus() != &anchor_[depth()].inset())
685                 return false;
686
687         return true;
688 }
689
690
691 void Cursor::setScreenPos(int x, int /*y*/)
692 {
693         setTargetX(x);
694         //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
695 }
696
697
698
699 void Cursor::plainErase()
700 {
701         cell().erase(pos());
702 }
703
704
705 void Cursor::markInsert()
706 {
707         insert(char_type(0));
708 }
709
710
711 void Cursor::markErase()
712 {
713         cell().erase(pos());
714 }
715
716
717 void Cursor::plainInsert(MathAtom const & t)
718 {
719         cell().insert(pos(), t);
720         ++pos();
721 }
722
723
724 void Cursor::insert(docstring const & str)
725 {
726         for_each(str.begin(), str.end(),
727                  boost::bind(static_cast<void(Cursor::*)(char_type)>
728                              (&Cursor::insert), this, _1));
729 }
730
731
732 void Cursor::insert(char_type c)
733 {
734         //lyxerr << "Cursor::insert char '" << c << "'" << endl;
735         BOOST_ASSERT(!empty());
736         if (inMathed()) {
737                 cap::selClearOrDel(*this);
738                 insert(new InsetMathChar(c));
739         } else {
740                 text()->insertChar(*this, c);
741         }
742 }
743
744
745 void Cursor::insert(MathAtom const & t)
746 {
747         //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
748         macroModeClose();
749         cap::selClearOrDel(*this);
750         plainInsert(t);
751 }
752
753
754 void Cursor::insert(Inset * inset)
755 {
756         if (inMathed())
757                 insert(MathAtom(inset));
758         else
759                 text()->insertInset(*this, inset);
760 }
761
762
763 void Cursor::niceInsert(docstring const & t)
764 {
765         MathData ar;
766         asArray(t, ar);
767         if (ar.size() == 1)
768                 niceInsert(ar[0]);
769         else
770                 insert(ar);
771 }
772
773
774 void Cursor::niceInsert(MathAtom const & t)
775 {
776         macroModeClose();
777         docstring const safe = cap::grabAndEraseSelection(*this);
778         plainInsert(t);
779         // enter the new inset and move the contents of the selection if possible
780         if (t->isActive()) {
781                 posBackward();
782                 // be careful here: don't use 'pushBackward(t)' as this we need to
783                 // push the clone, not the original
784                 pushBackward(*nextInset());
785                 // We may not use niceInsert here (recursion)
786                 MathData ar;
787                 asArray(safe, ar);
788                 insert(ar);
789         }
790 }
791
792
793 void Cursor::insert(MathData const & ar)
794 {
795         macroModeClose();
796         if (selection())
797                 cap::eraseSelection(*this);
798         cell().insert(pos(), ar);
799         pos() += ar.size();
800 }
801
802
803 bool Cursor::backspace()
804 {
805         autocorrect() = false;
806
807         if (selection()) {
808                 cap::eraseSelection(*this);
809                 return true;
810         }
811
812         if (pos() == 0) {
813                 // If empty cell, and not part of a big cell
814                 if (lastpos() == 0 && inset().nargs() == 1) {
815                         popBackward();
816                         // Directly delete empty cell: [|[]] => [|]
817                         if (inMathed()) {
818                                 plainErase();
819                                 resetAnchor();
820                                 return true;
821                         }
822                         // [|], can not delete from inside
823                         return false;
824                 } else {
825                         if (inMathed())
826                                 pullArg();
827                         else
828                                 popBackward();
829                         return true;
830                 }
831         }
832
833         if (inMacroMode()) {
834                 InsetMathUnknown * p = activeMacro();
835                 if (p->name().size() > 1) {
836                         p->setName(p->name().substr(0, p->name().size() - 1));
837                         return true;
838                 }
839         }
840
841         if (pos() != 0 && prevAtom()->nargs() > 0) {
842                 // let's require two backspaces for 'big stuff' and
843                 // highlight on the first
844                 resetAnchor();
845                 selection() = true;
846                 --pos();
847         } else {
848                 --pos();
849                 plainErase();
850         }
851         return true;
852 }
853
854
855 bool Cursor::erase()
856 {
857         autocorrect() = false;
858         if (inMacroMode())
859                 return true;
860
861         if (selection()) {
862                 cap::eraseSelection(*this);
863                 return true;
864         }
865
866         // delete empty cells if possible
867         if (pos() == lastpos() && inset().idxDelete(idx()))
868                 return true;
869
870         // special behaviour when in last position of cell
871         if (pos() == lastpos()) {
872                 bool one_cell = inset().nargs() == 1;
873                 if (one_cell && lastpos() == 0) {
874                         popBackward();
875                         // Directly delete empty cell: [|[]] => [|]
876                         if (inMathed()) {
877                                 plainErase();
878                                 resetAnchor();
879                                 return true;
880                         }
881                         // [|], can not delete from inside
882                         return false;
883                 }
884                 // remove markup
885                 if (!one_cell)
886                         inset().idxGlue(idx());
887                 return true;
888         }
889
890         // 'clever' UI hack: only erase large items if previously slected
891         if (pos() != lastpos() && nextAtom()->nargs() > 0) {
892                 resetAnchor();
893                 selection() = true;
894                 ++pos();
895         } else {
896                 plainErase();
897         }
898
899         return true;
900 }
901
902
903 bool Cursor::up()
904 {
905         macroModeClose();
906         DocIterator save = *this;
907         FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
908         this->dispatch(cmd);
909         if (disp_.dispatched())
910                 return true;
911         setCursor(save);
912         autocorrect() = false;
913         return false;
914 }
915
916
917 bool Cursor::down()
918 {
919         macroModeClose();
920         DocIterator save = *this;
921         FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
922         this->dispatch(cmd);
923         if (disp_.dispatched())
924                 return true;
925         setCursor(save);
926         autocorrect() = false;
927         return false;
928 }
929
930
931 bool Cursor::macroModeClose()
932 {
933         if (!inMacroMode())
934                 return false;
935         InsetMathUnknown * p = activeMacro();
936         p->finalize();
937         docstring const s = p->name();
938         --pos();
939         cell().erase(pos());
940
941         // do nothing if the macro name is empty
942         if (s == "\\")
943                 return false;
944
945         // trigger updates of macros, at least, if no full
946         // updates take place anyway
947         updateFlags(Update::Force);
948
949         docstring const name = s.substr(1);
950         InsetMathNest * const in = inset().asInsetMath()->asNestInset();
951         if (in && in->interpretString(*this, s))
952                 return true;
953         MathAtom atom = createInsetMath(name);
954         MathMacro * atomAsMacro = atom.nucleus()->asMacro();
955         if (atomAsMacro) {
956                 // make non-greedy, i.e. don't eat parameters from the right
957                 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT);
958         }
959         plainInsert(atom);
960         return true;
961 }
962
963
964 docstring Cursor::macroName()
965 {
966         return inMacroMode() ? activeMacro()->name() : docstring();
967 }
968
969
970 void Cursor::handleNest(MathAtom const & a, int c)
971 {
972         //lyxerr << "Cursor::handleNest: " << c << endl;
973         MathAtom t = a;
974         asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
975         insert(t);
976         posBackward();
977         pushBackward(*nextInset());
978 }
979
980
981 int Cursor::targetX() const
982 {
983         if (x_target() != -1)
984                 return x_target();
985         int x = 0;
986         int y = 0;
987         getPos(x, y);
988         return x;
989 }
990
991
992 int Cursor::textTargetOffset() const
993 {
994         return textTargetOffset_;
995 }
996
997
998 void Cursor::setTargetX()
999 {
1000         int x;
1001         int y;
1002         getPos(x, y);
1003         setTargetX(x);
1004 }
1005
1006
1007 bool Cursor::inMacroMode() const
1008 {
1009         if (!inMathed())
1010                 return false;
1011         if (pos() == 0)
1012                 return false;
1013         InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1014         return p && !p->final();
1015 }
1016
1017
1018 InsetMathUnknown * Cursor::activeMacro()
1019 {
1020         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1021 }
1022
1023
1024 void Cursor::pullArg()
1025 {
1026         // FIXME: Look here
1027         MathData ar = cell();
1028         if (popBackward() && inMathed()) {
1029                 plainErase();
1030                 cell().insert(pos(), ar);
1031                 resetAnchor();
1032         } else {
1033                 //formula()->mutateToText();
1034         }
1035 }
1036
1037
1038 void Cursor::touch()
1039 {
1040         // FIXME: look here
1041 #if 0
1042         DocIterator::const_iterator it = begin();
1043         DocIterator::const_iterator et = end();
1044         for ( ; it != et; ++it)
1045                 it->cell().touch();
1046 #endif
1047 }
1048
1049
1050 void Cursor::normalize()
1051 {
1052         if (idx() > lastidx()) {
1053                 lyxerr << "this should not really happen - 1: "
1054                        << idx() << ' ' << nargs()
1055                        << " in: " << &inset() << endl;
1056                 idx() = lastidx();
1057         }
1058
1059         if (pos() > lastpos()) {
1060                 lyxerr << "this should not really happen - 2: "
1061                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
1062                        << " in atom: '";
1063                 odocstringstream os;
1064                 WriteStream wi(os, false, true);
1065                 inset().asInsetMath()->write(wi);
1066                 lyxerr << to_utf8(os.str()) << endl;
1067                 pos() = lastpos();
1068         }
1069 }
1070
1071
1072 bool Cursor::upDownInMath(bool up)
1073 {
1074         // Be warned: The 'logic' implemented in this function is highly
1075         // fragile. A distance of one pixel or a '<' vs '<=' _really
1076         // matters. So fiddle around with it only if you think you know
1077         // what you are doing!
1078         int xo = 0;
1079         int yo = 0;
1080         getPos(xo, yo);
1081         xo = theLyXFunc().cursorBeforeDispatchX();
1082         
1083         // check if we had something else in mind, if not, this is the future
1084         // target
1085         if (x_target_ == -1)
1086                 setTargetX(xo);
1087         else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1088                 // In text mode inside the line (not left or right) possibly set a new target_x,
1089                 // but only if we are somewhere else than the previous target-offset.
1090                 
1091                 // We want to keep the x-target on subsequent up/down movements
1092                 // that cross beyond the end of short lines. Thus a special
1093                 // handling when the cursor is at the end of line: Use the new
1094                 // x-target only if the old one was before the end of line
1095                 // or the old one was after the beginning of the line
1096                 bool inRTL = isWithinRtlParagraph(*this);
1097                 bool left;
1098                 bool right;
1099                 if (inRTL) {
1100                         left = pos() == textRow().endpos();
1101                         right = pos() == textRow().pos();
1102                 } else {
1103                         left = pos() == textRow().pos();
1104                         right = pos() == textRow().endpos();
1105                 }
1106                 if ((!left && !right) ||
1107                                 (left && !right && xo < x_target_) ||
1108                                 (!left && right && x_target_ < xo))
1109                         setTargetX(xo);
1110                 else
1111                         xo = targetX();
1112         } else
1113                 xo = targetX();
1114
1115         // try neigbouring script insets
1116         Cursor old = *this;
1117         if (inMathed() && !selection()) {
1118                 // try left
1119                 if (pos() != 0) {
1120                         InsetMathScript const * p = prevAtom()->asScriptInset();
1121                         if (p && p->has(up)) {
1122                                 --pos();
1123                                 push(*const_cast<InsetMathScript*>(p));
1124                                 idx() = p->idxOfScript(up);
1125                                 pos() = lastpos();
1126                                 
1127                                 // we went in the right direction? Otherwise don't jump into the script
1128                                 int x;
1129                                 int y;
1130                                 getPos(x, y);
1131                                 int oy = theLyXFunc().cursorBeforeDispatchY();
1132                                 if ((!up && y <= oy) ||
1133                                                 (up && y >= oy))
1134                                         operator=(old);
1135                                 else
1136                                         return true;
1137                         }
1138                 }
1139                 
1140                 // try right
1141                 if (pos() != lastpos()) {
1142                         InsetMathScript const * p = nextAtom()->asScriptInset();
1143                         if (p && p->has(up)) {
1144                                 push(*const_cast<InsetMathScript*>(p));
1145                                 idx() = p->idxOfScript(up);
1146                                 pos() = 0;
1147                                 
1148                                 // we went in the right direction? Otherwise don't jump into the script
1149                                 int x;
1150                                 int y;
1151                                 getPos(x, y);
1152                                 int oy = theLyXFunc().cursorBeforeDispatchY();
1153                                 if ((!up && y <= oy) ||
1154                                                 (up && y >= oy))
1155                                         operator=(old);
1156                                 else
1157                                         return true;
1158                         }
1159                 }
1160         }
1161                 
1162         // try to find an inset that knows better then we,
1163         if (inset().idxUpDown(*this, up)) {
1164                 //lyxerr << "idxUpDown triggered" << endl;
1165                 // try to find best position within this inset
1166                 if (!selection())
1167                         setCursor(bruteFind2(*this, xo, yo));
1168                 return true;
1169         }
1170         
1171         // any improvement going just out of inset?
1172         if (popBackward() && inMathed()) {
1173                 //lyxerr << "updown: popBackward succeeded" << endl;
1174                 int xnew;
1175                 int ynew;
1176                 int yold = theLyXFunc().cursorBeforeDispatchY();
1177                 getPos(xnew, ynew);
1178                 if (up ? ynew < yold : ynew > yold)
1179                         return true;
1180         }
1181         
1182         // no success, we are probably at the document top or bottom
1183         operator=(old);
1184         return false;
1185 }
1186
1187
1188 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1189 {
1190         BOOST_ASSERT(text());
1191
1192         // where are we?
1193         int xo = 0;
1194         int yo = 0;
1195         getPos(xo, yo);
1196         xo = theLyXFunc().cursorBeforeDispatchX();
1197
1198         // update the targetX - this is here before the "return false"
1199         // to set a new target which can be used by InsetTexts above
1200         // if we cannot move up/down inside this inset anymore
1201         if (x_target_ == -1)
1202                 setTargetX(xo);
1203         else if (xo - textTargetOffset() != x_target() &&
1204                                          depth() == beforeDispatchCursor_.depth()) {
1205                 // In text mode inside the line (not left or right) possibly set a new target_x,
1206                 // but only if we are somewhere else than the previous target-offset.
1207                 
1208                 // We want to keep the x-target on subsequent up/down movements
1209                 // that cross beyond the end of short lines. Thus a special
1210                 // handling when the cursor is at the end of line: Use the new
1211                 // x-target only if the old one was before the end of line
1212                 // or the old one was after the beginning of the line
1213                 bool inRTL = isWithinRtlParagraph(*this);
1214                 bool left;
1215                 bool right;
1216                 if (inRTL) {
1217                         left = pos() == textRow().endpos();
1218                         right = pos() == textRow().pos();
1219                 } else {
1220                         left = pos() == textRow().pos();
1221                         right = pos() == textRow().endpos();
1222                 }
1223                 if ((!left && !right) ||
1224                                 (left && !right && xo < x_target_) ||
1225                                 (!left && right && x_target_ < xo))
1226                         setTargetX(xo);
1227                 else
1228                         xo = targetX();
1229         } else
1230                 xo = targetX();
1231                 
1232         // first get the current line
1233         TextMetrics & tm = bv_->textMetrics(text());
1234         ParagraphMetrics const & pm = tm.parMetrics(pit());
1235         int row;
1236         if (pos() && boundary())
1237                 row = pm.pos2row(pos() - 1);
1238         else
1239                 row = pm.pos2row(pos());
1240                 
1241         // are we not at the start or end?
1242         if (up) {
1243                 if (pit() == 0 && row == 0)
1244                         return false;
1245         } else {
1246                 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1247                                 row + 1 >= int(pm.rows().size()))
1248                         return false;
1249         }       
1250
1251         // with and without selection are handled differently
1252         if (!selection()) {
1253                 int yo = bv().getPos(*this, boundary()).y_;
1254                 Cursor old = *this;
1255                 // To next/previous row
1256                 if (up)
1257                         tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1258                 else
1259                         tm.editXY(*this, xo, yo + textRow().descent() + 1);
1260                 clearSelection();
1261                 
1262                 // This happens when you move out of an inset.
1263                 // And to give the DEPM the possibility of doing
1264                 // something we must provide it with two different
1265                 // cursors. (Lgb)
1266                 Cursor dummy = *this;
1267                 if (dummy == old)
1268                         ++dummy.pos();
1269                 if (bv().checkDepm(dummy, old)) {
1270                         updateNeeded = true;
1271                         // Make sure that cur gets back whatever happened to dummy(Lgb)
1272                         operator=(dummy);
1273                 }
1274         } else {
1275                 // if there is a selection, we stay out of any inset, and just jump to the right position:
1276                 Cursor old = *this;
1277                 if (up) {
1278                         if (row > 0) {
1279                                 top().pos() = min(tm.x2pos(pit(), row - 1, xo), top().lastpos());
1280                         } else if (pit() > 0) {
1281                                 --pit();
1282                                 ParagraphMetrics const & pmcur = bv_->parMetrics(text(), pit());
1283                                 top().pos() = min(tm.x2pos(pit(), pmcur.rows().size() - 1, xo), top().lastpos());
1284                         }
1285                 } else {
1286                         if (row + 1 < int(pm.rows().size())) {
1287                                 top().pos() = min(tm.x2pos(pit(), row + 1, xo), top().lastpos());
1288                         } else if (pit() + 1 < int(text()->paragraphs().size())) {
1289                                 ++pit();
1290                                 top().pos() = min(tm.x2pos(pit(), 0, xo), top().lastpos());
1291                         }
1292                 }
1293
1294                 updateNeeded |= bv().checkDepm(*this, old);
1295         }
1296
1297         updateTextTargetOffset();
1298         return true;
1299 }       
1300
1301
1302 void Cursor::handleFont(string const & font)
1303 {
1304         LYXERR(Debug::DEBUG, font);
1305         docstring safe;
1306         if (selection()) {
1307                 macroModeClose();
1308                 safe = cap::grabAndEraseSelection(*this);
1309         }
1310
1311         if (lastpos() != 0) {
1312                 // something left in the cell
1313                 if (pos() == 0) {
1314                         // cursor in first position
1315                         popBackward();
1316                 } else if (pos() == lastpos()) {
1317                         // cursor in last position
1318                         popForward();
1319                 } else {
1320                         // cursor in between. split cell
1321                         MathData::iterator bt = cell().begin();
1322                         MathAtom at = createInsetMath(from_utf8(font));
1323                         at.nucleus()->cell(0) = MathData(bt, bt + pos());
1324                         cell().erase(bt, bt + pos());
1325                         popBackward();
1326                         plainInsert(at);
1327                 }
1328         } else {
1329                 // nothing left in the cell
1330                 pullArg();
1331                 plainErase();
1332         }
1333         insert(safe);
1334 }
1335
1336
1337 void Cursor::message(docstring const & msg) const
1338 {
1339         theLyXFunc().setMessage(msg);
1340 }
1341
1342
1343 void Cursor::errorMessage(docstring const & msg) const
1344 {
1345         theLyXFunc().setErrorMessage(msg);
1346 }
1347
1348
1349 docstring Cursor::selectionAsString(bool label) const
1350 {
1351         if (!selection())
1352                 return docstring();
1353
1354         if (inTexted()) {
1355                 Buffer const & buffer = bv().buffer();
1356                 ParagraphList const & pars = text()->paragraphs();
1357
1358                 // should be const ...
1359                 pit_type startpit = selBegin().pit();
1360                 pit_type endpit = selEnd().pit();
1361                 size_t const startpos = selBegin().pos();
1362                 size_t const endpos = selEnd().pos();
1363
1364                 if (startpit == endpit)
1365                         return pars[startpit].asString(buffer, startpos, endpos, label);
1366
1367                 // First paragraph in selection
1368                 docstring result = pars[startpit].
1369                         asString(buffer, startpos, pars[startpit].size(), label)
1370                                  + parbreak(pars[startpit]);
1371
1372                 // The paragraphs in between (if any)
1373                 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1374                         Paragraph const & par = pars[pit];
1375                         result += par.asString(buffer, 0, par.size(), label)
1376                                   + parbreak(pars[pit]);
1377                 }
1378
1379                 // Last paragraph in selection
1380                 result += pars[endpit].asString(buffer, 0, endpos, label);
1381
1382                 return result;
1383         }
1384
1385         if (inMathed())
1386                 return cap::grabSelection(*this);
1387
1388         return docstring();
1389 }
1390
1391
1392 docstring Cursor::currentState()
1393 {
1394         if (inMathed()) {
1395                 odocstringstream os;
1396                 info(os);
1397                 return os.str();
1398         }
1399
1400         if (inTexted())
1401                 return text()->currentState(*this);
1402
1403         return docstring();
1404 }
1405
1406
1407 docstring Cursor::getPossibleLabel()
1408 {
1409         return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
1410 }
1411
1412
1413 Encoding const * Cursor::getEncoding() const
1414 {
1415         if (empty())
1416                 return 0;
1417         CursorSlice const & sl = innerTextSlice();
1418         Text const & text = *sl.text();
1419         Font font = text.getPar(sl.pit()).getFont(
1420                 bv().buffer().params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1421         return font.language()->encoding();
1422 }
1423
1424
1425 void Cursor::undispatched()
1426 {
1427         disp_.dispatched(false);
1428 }
1429
1430
1431 void Cursor::dispatched()
1432 {
1433         disp_.dispatched(true);
1434 }
1435
1436
1437 void Cursor::updateFlags(Update::flags f)
1438 {
1439         disp_.update(f);
1440 }
1441
1442
1443 void Cursor::noUpdate()
1444 {
1445         disp_.update(Update::None);
1446 }
1447
1448
1449 Font Cursor::getFont() const
1450 {
1451         // The logic here should more or less match to the Cursor::setCurrentFont
1452         // logic, i.e. the cursor height should give a hint what will happen
1453         // if a character is entered.
1454         
1455         // HACK. far from being perfect...
1456
1457         CursorSlice const & sl = innerTextSlice();
1458         Text const & text = *sl.text();
1459         Paragraph const & par = text.getPar(sl.pit());
1460         
1461         // on boundary, so we are really at the character before
1462         pos_type pos = sl.pos();
1463         if (pos > 0 && boundary())
1464                 --pos;
1465         
1466         // on space? Take the font before (only for RTL boundary stay)
1467         if (pos > 0) {
1468                 TextMetrics const & tm = bv().textMetrics(&text);
1469                 if (pos == sl.lastpos()
1470                         || (par.isSeparator(pos) 
1471                         && !tm.isRTLBoundary(sl.pit(), pos)))
1472                         --pos;
1473         }
1474         
1475         // get font at the position
1476         Font font = par.getFont(bv().buffer().params(), pos,
1477                 outerFont(sl.pit(), text.paragraphs()));
1478
1479         return font;
1480 }
1481
1482
1483 bool Cursor::fixIfBroken()
1484 {
1485         if (DocIterator::fixIfBroken()) {
1486                         clearSelection();
1487                         resetAnchor();
1488                         return true;
1489         }
1490         return false;
1491 }
1492
1493
1494 bool notifyCursorLeaves(DocIterator const & old, Cursor & cur)
1495 {
1496         // find inset in common
1497         size_type i;
1498         for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
1499                 if (&old.inset() != &cur.inset())
1500                         break;
1501         }
1502         
1503         // notify everything on top of the common part in old cursor,
1504         // but stop if the inset claims the cursor to be invalid now
1505         for (;  i < old.depth(); ++i) {
1506                 if (old[i].inset().notifyCursorLeaves(cur))
1507                         return true;
1508         }
1509         
1510         return false;
1511 }
1512
1513
1514 void Cursor::setCurrentFont()
1515 {
1516         CursorSlice const & cs = innerTextSlice();
1517         Paragraph const & par = cs.paragraph();
1518         pos_type cpit = cs.pit();
1519         pos_type cpos = cs.pos();
1520         Text const & ctext = *cs.text();
1521         TextMetrics const & tm = bv().textMetrics(&ctext);
1522
1523         // are we behind previous char in fact? -> go to that char
1524         if (cpos > 0 && boundary())
1525                 --cpos;
1526
1527         // find position to take the font from
1528         if (cpos != 0) {
1529                 // paragraph end? -> font of last char
1530                 if (cpos == lastpos())
1531                         --cpos;
1532                 // on space? -> look at the words in front of space
1533                 else if (cpos > 0 && par.isSeparator(cpos))     {
1534                         // abc| def -> font of c
1535                         // abc |[WERBEH], i.e. boundary==true -> font of c
1536                         // abc [WERBEH]| def, font of the space
1537                         if (!tm.isRTLBoundary(cpit, cpos))
1538                                 --cpos;
1539                 }
1540         }
1541
1542         // get font
1543         BufferParams const & bufparams = buffer().params();
1544         current_font = par.getFontSettings(bufparams, cpos);
1545         real_current_font = tm.getDisplayFont(cpit, cpos);
1546
1547         // special case for paragraph end
1548         if (cs.pos() == lastpos()
1549             && tm.isRTLBoundary(cpit, cs.pos())
1550             && !boundary()) {
1551                 Language const * lang = par.getParLanguage(bufparams);
1552                 current_font.setLanguage(lang);
1553                 current_font.fontInfo().setNumber(FONT_OFF);
1554                 real_current_font.setLanguage(lang);
1555                 real_current_font.fontInfo().setNumber(FONT_OFF);
1556         }
1557 }
1558
1559
1560 bool Cursor::textUndo()
1561 {
1562         DocIterator dit = *this;
1563         // Undo::textUndo() will modify dit.
1564         if (!bv_->buffer().undo().textUndo(dit))
1565                 return false;
1566         // Set cursor
1567         setCursor(dit);
1568         selection() = false;
1569         resetAnchor();
1570         fixIfBroken();
1571         return true;
1572 }
1573
1574
1575 bool Cursor::textRedo()
1576 {
1577         DocIterator dit = *this;
1578         // Undo::textRedo() will modify dit.
1579         if (!bv_->buffer().undo().textRedo(dit))
1580                 return false;
1581         // Set cursor
1582         setCursor(dit);
1583         selection() = false;
1584         resetAnchor();
1585         fixIfBroken();
1586         return true;
1587 }
1588
1589
1590 void Cursor::finishUndo()
1591 {
1592         bv_->buffer().undo().finishUndo();
1593 }
1594
1595
1596 void Cursor::recordUndo(UndoKind kind, pit_type from, pit_type to)
1597 {
1598         bv_->buffer().undo().recordUndo(*this, kind, from, to);
1599 }
1600
1601
1602 void Cursor::recordUndo(UndoKind kind, pit_type from)
1603 {
1604         bv_->buffer().undo().recordUndo(*this, kind, from);
1605 }
1606
1607
1608 void Cursor::recordUndo(UndoKind kind)
1609 {
1610         bv_->buffer().undo().recordUndo(*this, kind);
1611 }
1612
1613
1614 void Cursor::recordUndoInset(UndoKind kind)
1615 {
1616         bv_->buffer().undo().recordUndoInset(*this, kind);
1617 }
1618
1619
1620 void Cursor::recordUndoFullDocument()
1621 {
1622         bv_->buffer().undo().recordUndoFullDocument(*this);
1623 }
1624
1625
1626 void Cursor::recordUndoSelection()
1627 {
1628         bv_->buffer().undo().recordUndo(*this, ATOMIC_UNDO,
1629                 selBegin().pit(), selEnd().pit());
1630 }
1631
1632
1633 void Cursor::checkBufferStructure()
1634 {
1635         if (paragraph().layout()->toclevel == Layout::NOT_IN_TOC)
1636                 return;
1637         Buffer const * master = buffer().masterBuffer();
1638         master->tocBackend().updateItem(ParConstIterator(*this));
1639         master->structureChanged();
1640 }
1641
1642
1643 } // namespace lyx