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