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