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