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