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