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