]> git.lyx.org Git - lyx.git/blob - src/Cursor.cpp
EmbeddedObjects.lyx: add hint how to force a rotation direction for rotated floats
[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 namespace lyx {
57
58 using std::string;
59 using std::vector;
60 using std::endl;
61 using std::min;
62 using std::for_each;
63
64 namespace {
65
66         bool
67         positionable(DocIterator const & cursor, DocIterator const & anchor)
68         {
69                 // avoid deeper nested insets when selecting
70                 if (cursor.depth() > anchor.depth())
71                         return false;
72
73                 // anchor might be deeper, should have same path then
74                 for (size_t i = 0; i < cursor.depth(); ++i)
75                         if (&cursor[i].inset() != &anchor[i].inset())
76                                 return false;
77
78                 // position should be ok.
79                 return true;
80         }
81
82
83         // Find position closest to (x, y) in cell given by iter.
84         // Used only in mathed
85         DocIterator bruteFind2(Cursor const & c, int x, int y)
86         {
87                 double best_dist = std::numeric_limits<double>::max();
88
89                 DocIterator result;
90
91                 DocIterator it = c;
92                 it.top().pos() = 0;
93                 DocIterator et = c;
94                 et.top().pos() = et.top().asInsetMath()->cell(et.top().idx()).size();
95                 for (size_t i = 0;; ++i) {
96                         int xo;
97                         int yo;
98                         Inset const * inset = &it.inset();
99                         std::map<Inset const *, Point> const & data =
100                                 c.bv().coordCache().getInsets().getData();
101                         std::map<Inset const *, Point>::const_iterator I = data.find(inset);
102
103                         // FIXME: in the case where the inset is not in the cache, this
104                         // means that no part of it is visible on screen. In this case
105                         // we don't do elaborate search and we just return the forwarded
106                         // DocIterator at its beginning.
107                         if (I == data.end()) {
108                                 it.top().pos() = 0;
109                                 return it;
110                         }
111
112                         Point o = I->second;
113                         inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
114                         // Convert to absolute
115                         xo += o.x_;
116                         yo += o.y_;
117                         double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
118                         // '<=' in order to take the last possible position
119                         // this is important for clicking behind \sum in e.g. '\sum_i a'
120                         LYXERR(Debug::DEBUG) << "i: " << i << " d: " << d
121                                 << " best: " << best_dist << endl;
122                         if (d <= best_dist) {
123                                 best_dist = d;
124                                 result = it;
125                         }
126                         if (it == et)
127                                 break;
128                         it.forwardPos();
129                 }
130                 return result;
131         }
132
133
134         /// moves position closest to (x, y) in given box
135         bool bruteFind(Cursor & cursor,
136                 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
137         {
138                 BOOST_ASSERT(!cursor.empty());
139                 Inset & inset = cursor[0].inset();
140                 BufferView & bv = cursor.bv();
141
142                 CoordCache::InnerParPosCache const & cache =
143                         bv.coordCache().getParPos().find(cursor.bottom().text())->second;
144                 // Get an iterator on the first paragraph in the cache
145                 DocIterator it(inset);
146                 it.push_back(CursorSlice(inset));
147                 it.pit() = cache.begin()->first;
148                 // Get an iterator after the last paragraph in the cache
149                 DocIterator et(inset);
150                 et.push_back(CursorSlice(inset));
151                 et.pit() = boost::prior(cache.end())->first;
152                 if (et.pit() >= et.lastpit())
153                         et = doc_iterator_end(inset);
154                 else
155                         ++et.pit();
156
157                 double best_dist = std::numeric_limits<double>::max();;
158                 DocIterator best_cursor = et;
159
160                 for ( ; it != et; it.forwardPos(true)) {
161                         // avoid invalid nesting when selecting
162                         if (!cursor.selection() || positionable(it, cursor.anchor_)) {
163                                 Point p = bv_funcs::getPos(bv, it, false);
164                                 int xo = p.x_;
165                                 int yo = p.y_;
166                                 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
167                                         double const dx = xo - x;
168                                         double const dy = yo - y;
169                                         double const d = dx * dx + dy * dy;
170                                         // '<=' in order to take the last possible position
171                                         // this is important for clicking behind \sum in e.g. '\sum_i a'
172                                         if (d <= best_dist) {
173                                                 //      lyxerr << "*" << endl;
174                                                 best_dist   = d;
175                                                 best_cursor = it;
176                                         }
177                                 }
178                         }
179                 }
180
181                 if (best_cursor != et) {
182                         cursor.setCursor(best_cursor);
183                         return true;
184                 }
185
186                 return false;
187         }
188
189
190         /// moves position closest to (x, y) in given box
191         bool bruteFind3(Cursor & cur, int x, int y, bool up)
192         {
193                 BufferView & bv = cur.bv();
194                 int ylow  = up ? 0 : y + 1;
195                 int yhigh = up ? y - 1 : bv.workHeight();
196                 int xlow = 0;
197                 int xhigh = bv.workWidth();
198
199 // FIXME: bit more work needed to get 'from' and 'to' right.
200                 pit_type from = cur.bottom().pit();
201                 //pit_type to = cur.bottom().pit();
202                 //lyxerr << "Pit start: " << from << endl;
203
204                 //lyxerr << "bruteFind3: x: " << x << " y: " << y
205                 //      << " xlow: " << xlow << " xhigh: " << xhigh
206                 //      << " ylow: " << ylow << " yhigh: " << yhigh
207                 //      << endl;
208                 Inset & inset = bv.buffer()->inset();
209                 DocIterator it = doc_iterator_begin(inset);
210                 it.pit() = from;
211                 DocIterator et = doc_iterator_end(inset);
212
213                 double best_dist = std::numeric_limits<double>::max();
214                 DocIterator best_cursor = et;
215
216                 for ( ; it != et; it.forwardPos()) {
217                         // avoid invalid nesting when selecting
218                         if (bv_funcs::status(&bv, it) == bv_funcs::CUR_INSIDE
219                             && (!cur.selection() || positionable(it, cur.anchor_))) {
220                                 Point p = bv_funcs::getPos(bv, it, false);
221                                 int xo = p.x_;
222                                 int yo = p.y_;
223                                 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
224                                         double const dx = xo - x;
225                                         double const dy = yo - y;
226                                         double const d = dx * dx + dy * dy;
227                                         //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
228                                         //      << " dx: " << dx << " dy: " << dy
229                                         //      << " idx: " << it.idx() << " pos: " << it.pos()
230                                         //      << " it:\n" << it
231                                         //      << endl;
232                                         // '<=' in order to take the last possible position
233                                         // this is important for clicking behind \sum in e.g. '\sum_i a'
234                                         if (d <= best_dist) {
235                                                 //lyxerr << "*" << endl;
236                                                 best_dist   = d;
237                                                 best_cursor = it;
238                                         }
239                                 }
240                         }
241                 }
242
243                 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
244                 if (best_cursor == et)
245                         return false;
246                 cur.setCursor(best_cursor);
247                 return true;
248         }
249
250         docstring parbreak(Paragraph const & par)
251         {
252                 odocstringstream ods;
253                 ods << '\n';
254                 // only add blank line if we're not in an ERT or Listings inset
255                 if (par.ownerCode() != Inset::ERT_CODE
256                     && par.ownerCode() != Inset::LISTINGS_CODE)
257                         ods << '\n';
258                 return ods.str();
259         }
260
261 } // namespace anon
262
263
264 // be careful: this is called from the bv's constructor, too, so
265 // bv functions are not yet available!
266 Cursor::Cursor(BufferView & bv)
267         : DocIterator(), bv_(&bv), anchor_(), x_target_(-1), textTargetOffset_(0),
268           selection_(false), mark_(false), logicalpos_(false)
269 {}
270
271
272 void Cursor::reset(Inset & inset)
273 {
274         clear();
275         push_back(CursorSlice(inset));
276         anchor_ = DocIterator(inset);
277         clearTargetX();
278         selection_ = false;
279         mark_ = false;
280 }
281
282
283 // this (intentionally) does neither touch anchor nor selection status
284 void Cursor::setCursor(DocIterator const & cur)
285 {
286         DocIterator::operator=(cur);
287 }
288
289
290 void Cursor::dispatch(FuncRequest const & cmd0)
291 {
292         LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
293                              << " cmd: " << cmd0 << '\n'
294                              << *this << endl;
295         if (empty())
296                 return;
297
298         fixIfBroken();
299         FuncRequest cmd = cmd0;
300         Cursor safe = *this;
301         
302         // store some values to be used inside of the handlers
303         getPos(beforeDispX_, beforeDispY_);
304         beforeDispatchCursor_ = *this;
305         for (; depth(); pop()) {
306                 LYXERR(Debug::DEBUG) << "Cursor::dispatch: cmd: "
307                         << cmd0 << endl << *this << endl;
308                 BOOST_ASSERT(pos() <= lastpos());
309                 BOOST_ASSERT(idx() <= lastidx());
310                 BOOST_ASSERT(pit() <= lastpit());
311
312                 // The common case is 'LFUN handled, need update', so make the
313                 // LFUN handler's life easier by assuming this as default value.
314                 // The handler can reset the update and val flags if necessary.
315                 disp_.update(Update::FitCursor | Update::Force);
316                 disp_.dispatched(true);
317                 inset().dispatch(*this, cmd);
318                 if (disp_.dispatched())
319                         break;
320         }
321         
322         // it completely to get a 'bomb early' behaviour in case this
323         // object will be used again.
324         if (!disp_.dispatched()) {
325                 LYXERR(Debug::DEBUG) << "RESTORING OLD CURSOR!" << endl;
326                 operator=(safe);
327                 disp_.update(Update::None);
328                 disp_.dispatched(false);
329         } else {
330                 // restore the previous one because nested Cursor::dispatch calls
331                 // are possible which would change it
332                 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
333         }
334 }
335
336
337 DispatchResult Cursor::result() const
338 {
339         return disp_;
340 }
341
342
343 BufferView & Cursor::bv() const
344 {
345         BOOST_ASSERT(bv_);
346         return *bv_;
347 }
348
349
350 Buffer & Cursor::buffer() const
351 {
352         BOOST_ASSERT(bv_);
353         BOOST_ASSERT(bv_->buffer());
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 #ifdef WITH_WARNINGS
515 #warning doesnt look ok
516 #endif
517         if (pit() == anchor().pit() && pos() == anchor().pos())
518                 selection() = false;
519 }
520
521
522 void Cursor::setSelection(DocIterator const & where, int n)
523 {
524         setCursor(where);
525         selection() = true;
526         anchor_ = where;
527         pos() += n;
528 }
529
530
531 void Cursor::clearSelection()
532 {
533         selection() = false;
534         mark() = false;
535         resetAnchor();
536 }
537
538
539 void Cursor::setTargetX(int x)
540 {
541         x_target_ = x;
542         textTargetOffset_ = 0;
543 }
544
545
546 int Cursor::x_target() const
547 {
548         return x_target_;
549 }
550
551
552 void Cursor::clearTargetX()
553 {
554         x_target_ = -1;
555         textTargetOffset_ = 0;
556 }
557
558
559 void Cursor::updateTextTargetOffset()
560 {
561         int x;
562         int y;
563         getPos(x, y);
564         textTargetOffset_ = x - x_target_;
565 }
566
567
568 void Cursor::info(odocstream & os) const
569 {
570         for (int i = 1, n = depth(); i < n; ++i) {
571                 operator[](i).inset().infoize(os);
572                 os << "  ";
573         }
574         if (pos() != 0) {
575                 Inset const * inset = prevInset();
576                 // prevInset() can return 0 in certain case.
577                 if (inset)
578                         prevInset()->infoize2(os);
579         }
580         // overwite old message
581         os << "                    ";
582 }
583
584
585 bool Cursor::selHandle(bool sel)
586 {
587         //lyxerr << "Cursor::selHandle" << endl;
588         if (sel == selection())
589                 return false;
590
591         resetAnchor();
592         selection() = sel;
593         cap::saveSelection(*this);
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 #ifdef WITH_WARNINGS
1013 #warning Look here
1014 #endif
1015         MathData ar = cell();
1016         if (popLeft() && inMathed()) {
1017                 plainErase();
1018                 cell().insert(pos(), ar);
1019                 resetAnchor();
1020         } else {
1021                 //formula()->mutateToText();
1022         }
1023 }
1024
1025
1026 void Cursor::touch()
1027 {
1028 #ifdef WITH_WARNINGS
1029 #warning look here
1030 #endif
1031 #if 0
1032         DocIterator::const_iterator it = begin();
1033         DocIterator::const_iterator et = end();
1034         for ( ; it != et; ++it)
1035                 it->cell().touch();
1036 #endif
1037 }
1038
1039
1040 void Cursor::normalize()
1041 {
1042         if (idx() > lastidx()) {
1043                 lyxerr << "this should not really happen - 1: "
1044                        << idx() << ' ' << nargs()
1045                        << " in: " << &inset() << endl;
1046                 idx() = lastidx();
1047         }
1048
1049         if (pos() > lastpos()) {
1050                 lyxerr << "this should not really happen - 2: "
1051                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
1052                        << " in atom: '";
1053                 odocstringstream os;
1054                 WriteStream wi(os, false, true);
1055                 inset().asInsetMath()->write(wi);
1056                 lyxerr << to_utf8(os.str()) << endl;
1057                 pos() = lastpos();
1058         }
1059 }
1060
1061
1062 bool Cursor::upDownInMath(bool up)
1063 {
1064         // Be warned: The 'logic' implemented in this function is highly
1065         // fragile. A distance of one pixel or a '<' vs '<=' _really
1066         // matters. So fiddle around with it only if you think you know
1067         // what you are doing!
1068         int xo = 0;
1069         int yo = 0;
1070         getPos(xo, yo);
1071         xo = beforeDispX_;
1072
1073         // check if we had something else in mind, if not, this is the future
1074         // target
1075         if (x_target_ == -1)
1076                 setTargetX(xo);
1077         else if (inset().asTextInset() && xo - textTargetOffset() != x_target()) {
1078                 // In text mode inside the line (not left or right) possibly set a new target_x,
1079                 // but only if we are somewhere else than the previous target-offset.
1080                 
1081                 // We want to keep the x-target on subsequent up/down movements
1082                 // that cross beyond the end of short lines. Thus a special
1083                 // handling when the cursor is at the end of line: Use the new 
1084                 // x-target only if the old one was before the end of line
1085                 // or the old one was after the beginning of the line
1086                 bool inRTL = isWithinRtlParagraph(*this);
1087                 bool left;
1088                 bool right;
1089                 if (inRTL) {
1090                         left = pos() == textRow().endpos();
1091                         right = pos() == textRow().pos();
1092                 } else {
1093                         left = pos() == textRow().pos();
1094                         right = pos() == textRow().endpos();
1095                 }
1096                 if ((!left && !right) ||
1097                                 (left && !right && xo < x_target_) || 
1098                                 (!left && right && x_target_ < xo))
1099                         setTargetX(xo);
1100                 else
1101                         xo = targetX();
1102         } else 
1103                 xo = targetX();
1104
1105         // try neigbouring script insets
1106         Cursor old = *this;
1107         if (inMathed() && !selection()) {
1108                 // try left
1109                 if (pos() != 0) {
1110                         InsetMathScript const * p = prevAtom()->asScriptInset();
1111                         if (p && p->has(up)) {
1112                                 --pos();
1113                                 push(*const_cast<InsetMathScript*>(p));
1114                                 idx() = p->idxOfScript(up);
1115                                 pos() = lastpos();
1116                                 
1117                                 // we went in the right direction? Otherwise don't jump into the script
1118                                 int x;
1119                                 int y;
1120                                 getPos(x, y);
1121                                 if ((!up && y <= beforeDispY_) ||
1122                                                 (up && y >= beforeDispY_))
1123                                         operator=(old);
1124                                 else
1125                                         return true;
1126                         }
1127                 }
1128                 
1129                 // try right
1130                 if (pos() != lastpos()) {
1131                         InsetMathScript const * p = nextAtom()->asScriptInset();
1132                         if (p && p->has(up)) {
1133                                 push(*const_cast<InsetMathScript*>(p));
1134                                 idx() = p->idxOfScript(up);
1135                                 pos() = 0;
1136                                 
1137                                 // we went in the right direction? Otherwise don't jump into the script
1138                                 int x;
1139                                 int y;
1140                                 getPos(x, y);
1141                                 if ((!up && y <= beforeDispY_) ||
1142                                                 (up && y >= beforeDispY_))
1143                                         operator=(old);
1144                                 else
1145                                         return true;
1146                         }
1147                 }
1148         }
1149                 
1150         // try to find an inset that knows better then we,
1151         if (inset().idxUpDown(*this, up)) {
1152                 //lyxerr << "idxUpDown triggered" << endl;
1153                 // try to find best position within this inset
1154                 if (!selection())
1155                         setCursor(bruteFind2(*this, xo, yo));
1156                 return true;
1157         }
1158         
1159         // any improvement going just out of inset?
1160         if (popLeft() && inMathed()) {
1161                 //lyxerr << "updown: popLeft succeeded" << endl;
1162                 int xnew;
1163                 int ynew;
1164                 getPos(xnew, ynew);
1165                 if (up ? ynew < beforeDispY_ : ynew > beforeDispY_)
1166                         return true;
1167         }
1168         
1169         // no success, we are probably at the document top or bottom
1170         operator=(old);
1171         return false;
1172 }
1173
1174
1175 bool Cursor::upDownInText(bool up, bool & updateNeeded) 
1176 {
1177         BOOST_ASSERT(text());
1178
1179         // where are we?
1180         int xo = 0;
1181         int yo = 0;
1182         getPos(xo, yo);
1183         xo = beforeDispX_;
1184         
1185         // update the targetX - this is here before the "return false"
1186         // to set a new target which can be used by InsetTexts above
1187         // if we cannot move up/down inside this inset anymore
1188         if (x_target_ == -1)
1189                 setTargetX(xo);
1190         else if (xo - textTargetOffset() != x_target() && 
1191                                          depth() == beforeDispatchCursor_.depth()) {
1192                 // In text mode inside the line (not left or right) possibly set a new target_x,
1193                 // but only if we are somewhere else than the previous target-offset.
1194                 
1195                 // We want to keep the x-target on subsequent up/down movements
1196                 // that cross beyond the end of short lines. Thus a special
1197                 // handling when the cursor is at the end of line: Use the new 
1198                 // x-target only if the old one was before the end of line
1199                 // or the old one was after the beginning of the line
1200                 bool inRTL = isWithinRtlParagraph(*this);
1201                 bool left;
1202                 bool right;
1203                 if (inRTL) {
1204                         left = pos() == textRow().endpos();
1205                         right = pos() == textRow().pos();
1206                 } else {
1207                         left = pos() == textRow().pos();
1208                         right = pos() == textRow().endpos();
1209                 }
1210                 if ((!left && !right) ||
1211                                 (left && !right && xo < x_target_) || 
1212                                 (!left && right && x_target_ < xo))
1213                         setTargetX(xo);
1214                 else
1215                         xo = targetX();
1216         } else 
1217                 xo = targetX();
1218                 
1219         // first get the current line
1220         TextMetrics const & tm = bv_->textMetrics(text());
1221         ParagraphMetrics const & pm = tm.parMetrics(pit());
1222         int row;
1223         if (pos() && boundary())
1224                 row = pm.pos2row(pos() - 1);
1225         else
1226                 row = pm.pos2row(pos());
1227                 
1228         // are we not at the start or end?
1229         if (up) {
1230                 if (pit() == 0 && row == 0)
1231                         return false;
1232         } else {
1233                 if (pit() + 1 >= int(text()->paragraphs().size()) && 
1234                                 row + 1 >= int(pm.rows().size()))
1235                         return false;
1236         }       
1237
1238         // with and without selection are handled differently
1239         if (!selection()) {
1240                 int yo = bv_funcs::getPos(bv(), *this, boundary()).y_;
1241                 Cursor old = *this;
1242                 // To next/previous row
1243                 if (up)
1244                         text()->editXY(*this, xo, yo - textRow().ascent() - 1);
1245                 else
1246                         text()->editXY(*this, xo, yo + textRow().descent() + 1);
1247                 clearSelection();
1248                 
1249                 // This happens when you move out of an inset.
1250                 // And to give the DEPM the possibility of doing
1251                 // something we must provide it with two different
1252                 // cursors. (Lgb)
1253                 Cursor dummy = *this;
1254                 if (dummy == old)
1255                         ++dummy.pos();
1256                 if (bv().checkDepm(dummy, old)) {
1257                         updateNeeded = true;
1258                         // Make sure that cur gets back whatever happened to dummy(Lgb)
1259                         operator=(dummy);
1260                 }
1261         } else {
1262                 // if there is a selection, we stay out of any inset, and just jump to the right position:
1263                 Cursor old = *this;
1264                 if (up) {
1265                         if (row > 0) {
1266                                 top().pos() = std::min(tm.x2pos(pit(), row - 1, xo), top().lastpos());
1267                         } else if (pit() > 0) {
1268                                 --pit();
1269                                 ParagraphMetrics const & pmcur = bv_->parMetrics(text(), pit());
1270                                 top().pos() = std::min(tm.x2pos(pit(), pmcur.rows().size() - 1, xo), top().lastpos());
1271                         }
1272                 } else {
1273                         if (row + 1 < int(pm.rows().size())) {
1274                                 top().pos() = std::min(tm.x2pos(pit(), row + 1, xo), top().lastpos());
1275                         } else if (pit() + 1 < int(text()->paragraphs().size())) {
1276                                 ++pit();
1277                                 top().pos() = std::min(tm.x2pos(pit(), 0, xo), top().lastpos());
1278                         }
1279                 }
1280
1281                 updateNeeded |= bv().checkDepm(*this, old);
1282         }
1283
1284         updateTextTargetOffset();
1285         return true;
1286 }       
1287
1288
1289 void Cursor::handleFont(string const & font)
1290 {
1291         LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << ": " << font << endl;
1292         docstring safe;
1293         if (selection()) {
1294                 macroModeClose();
1295                 safe = cap::grabAndEraseSelection(*this);
1296         }
1297
1298         if (lastpos() != 0) {
1299                 // something left in the cell
1300                 if (pos() == 0) {
1301                         // cursor in first position
1302                         popLeft();
1303                 } else if (pos() == lastpos()) {
1304                         // cursor in last position
1305                         popRight();
1306                 } else {
1307                         // cursor in between. split cell
1308                         MathData::iterator bt = cell().begin();
1309                         MathAtom at = createInsetMath(from_utf8(font));
1310                         at.nucleus()->cell(0) = MathData(bt, bt + pos());
1311                         cell().erase(bt, bt + pos());
1312                         popLeft();
1313                         plainInsert(at);
1314                 }
1315         } else {
1316                 // nothing left in the cell
1317                 pullArg();
1318                 plainErase();
1319         }
1320         insert(safe);
1321 }
1322
1323
1324 void Cursor::message(docstring const & msg) const
1325 {
1326         theLyXFunc().setMessage(msg);
1327 }
1328
1329
1330 void Cursor::errorMessage(docstring const & msg) const
1331 {
1332         theLyXFunc().setErrorMessage(msg);
1333 }
1334
1335
1336 docstring Cursor::selectionAsString(bool label) const
1337 {
1338         if (!selection())
1339                 return docstring();
1340
1341         if (inTexted()) {
1342                 Buffer const & buffer = *bv().buffer();
1343                 ParagraphList const & pars = text()->paragraphs();
1344
1345                 // should be const ...
1346                 pit_type startpit = selBegin().pit();
1347                 pit_type endpit = selEnd().pit();
1348                 size_t const startpos = selBegin().pos();
1349                 size_t const endpos = selEnd().pos();
1350
1351                 if (startpit == endpit)
1352                         return pars[startpit].asString(buffer, startpos, endpos, label);
1353
1354                 // First paragraph in selection
1355                 docstring result = pars[startpit].
1356                         asString(buffer, startpos, pars[startpit].size(), label)
1357                                  + parbreak(pars[startpit]);
1358
1359                 // The paragraphs in between (if any)
1360                 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1361                         Paragraph const & par = pars[pit];
1362                         result += par.asString(buffer, 0, par.size(), label)
1363                                   + parbreak(pars[pit]);
1364                 }
1365
1366                 // Last paragraph in selection
1367                 result += pars[endpit].asString(buffer, 0, endpos, label);
1368
1369                 return result;
1370         }
1371
1372         if (inMathed())
1373                 return cap::grabSelection(*this);
1374
1375         return docstring();
1376 }
1377
1378
1379 docstring Cursor::currentState()
1380 {
1381         if (inMathed()) {
1382                 odocstringstream os;
1383                 info(os);
1384                 return os.str();
1385         }
1386
1387         if (inTexted())
1388                 return text()->currentState(*this);
1389
1390         return docstring();
1391 }
1392
1393
1394 docstring Cursor::getPossibleLabel()
1395 {
1396         return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
1397 }
1398
1399
1400 Encoding const * Cursor::getEncoding() const
1401 {
1402         if (empty())
1403                 return 0;
1404         if (!bv().buffer())
1405                 return 0;
1406         int s = 0;
1407         // go up until first non-0 text is hit
1408         // (innermost text is 0 in mathed)
1409         for (s = depth() - 1; s >= 0; --s)
1410                 if (operator[](s).text())
1411                         break;
1412         CursorSlice const & sl = operator[](s);
1413         Text const & text = *sl.text();
1414         Font font = text.getPar(sl.pit()).getFont(
1415                 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1416         return font.language()->encoding();
1417 }
1418
1419
1420 void Cursor::undispatched()
1421 {
1422         disp_.dispatched(false);
1423 }
1424
1425
1426 void Cursor::dispatched()
1427 {
1428         disp_.dispatched(true);
1429 }
1430
1431
1432 void Cursor::updateFlags(Update::flags f)
1433 {
1434         disp_.update(f);
1435 }
1436
1437
1438 void Cursor::noUpdate()
1439 {
1440         disp_.update(Update::None);
1441 }
1442
1443
1444 Font Cursor::getFont() const
1445 {
1446         // The logic here should more or less match to the Text::setCurrentFont
1447         // logic, i.e. the cursor height should give a hint what will happen
1448         // if a character is entered.
1449         
1450         // HACK. far from being perfect...
1451         // go up until first non-0 text is hit
1452         // (innermost text is 0 in mathed)
1453         int s = 0;
1454         for (s = depth() - 1; s >= 0; --s)
1455                 if (operator[](s).text())
1456                         break;
1457         CursorSlice const & sl = operator[](s);
1458         Text const & text = *sl.text();
1459         Paragraph const & par = text.getPar(sl.pit());
1460         
1461         // on boundary, so we are really at the character before
1462         pos_type pos = sl.pos();
1463         if (pos > 0 && boundary())
1464                 --pos;
1465         
1466         // on space? Take the font before (only for RTL boundary stay)
1467         if (pos > 0) {
1468                 if (pos == sl.lastpos()
1469                                 || (par.isSeparator(pos) && 
1470                                                 !text.isRTLBoundary(buffer(), par, pos)))
1471                         --pos;
1472         }
1473         
1474         // get font at the position
1475         Font font = par.getFont(bv().buffer()->params(), pos,
1476                 outerFont(sl.pit(), text.paragraphs()));
1477
1478         return font;
1479 }
1480
1481
1482 void Cursor::fixIfBroken()
1483 {
1484         if (DocIterator::fixIfBroken()) {
1485                         clearSelection();
1486                         resetAnchor();
1487         }
1488 }
1489
1490
1491 bool notifyCursorLeaves(DocIterator const & old, Cursor & cur)
1492 {
1493         // find inset in common
1494         size_type i;
1495         for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
1496                 if (&old.inset() != &cur.inset())
1497                         break;
1498         }
1499         
1500         // notify everything on top of the common part in old cursor,
1501         // but stop if the inset claims the cursor to be invalid now
1502         for (;  i < old.depth(); ++i) {
1503                 if (old[i].inset().notifyCursorLeaves(cur))
1504                         return true;
1505         }
1506         
1507         return false;
1508 }
1509
1510
1511 } // namespace lyx