]> git.lyx.org Git - lyx.git/blob - src/Cursor.cpp
simplification
[lyx.git] / src / Cursor.cpp
1 /**
2  * \file Cursor.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alejandro Aguilar Sierra
7  * \author Alfredo Braunstein
8  * \author André Pönitz
9  * \author Stefan Schimanski
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "Bidi.h"
17 #include "BufferView.h"
18 #include "Buffer.h"
19 #include "Cursor.h"
20 #include "CoordCache.h"
21 #include "CutAndPaste.h"
22 #include "debug.h"
23 #include "DispatchResult.h"
24 #include "Encoding.h"
25 #include "FuncRequest.h"
26 #include "Language.h"
27 #include "lfuns.h"
28 #include "Font.h"
29 #include "LyXFunc.h" // only for setMessage()
30 #include "LyXRC.h"
31 #include "Row.h"
32 #include "Text.h"
33 #include "Paragraph.h"
34 #include "paragraph_funcs.h"
35 #include "ParIterator.h"
36 #include "TextMetrics.h"
37
38 #include "support/docstream.h"
39
40 #include "insets/InsetTabular.h"
41 #include "insets/InsetText.h"
42
43 #include "mathed/InsetMath.h"
44 #include "mathed/InsetMathScript.h"
45 #include "mathed/MacroTable.h"
46 #include "mathed/MathData.h"
47 #include "mathed/MathMacro.h"
48
49 #include <boost/assert.hpp>
50 #include <boost/bind.hpp>
51 #include <boost/current_function.hpp>
52
53 #include <sstream>
54 #include <limits>
55 #include <map>
56
57 using std::string;
58 using std::vector;
59 using std::endl;
60 using std::min;
61 using std::for_each;
62
63
64 namespace lyx {
65
66 namespace {
67
68         bool
69         positionable(DocIterator const & cursor, DocIterator const & anchor)
70         {
71                 // avoid deeper nested insets when selecting
72                 if (cursor.depth() > anchor.depth())
73                         return false;
74
75                 // anchor might be deeper, should have same path then
76                 for (size_t i = 0; i < cursor.depth(); ++i)
77                         if (&cursor[i].inset() != &anchor[i].inset())
78                                 return false;
79
80                 // position should be ok.
81                 return true;
82         }
83
84
85         // Find position closest to (x, y) in cell given by iter.
86         // Used only in mathed
87         DocIterator bruteFind2(Cursor const & c, int x, int y)
88         {
89                 double best_dist = std::numeric_limits<double>::max();
90
91                 DocIterator result;
92
93                 DocIterator it = c;
94                 it.top().pos() = 0;
95                 DocIterator et = c;
96                 et.top().pos() = et.top().asInsetMath()->cell(et.top().idx()).size();
97                 for (size_t i = 0;; ++i) {
98                         int xo;
99                         int yo;
100                         Inset const * inset = &it.inset();
101                         std::map<Inset const *, Geometry> const & data =
102                                 c.bv().coordCache().getInsets().getData();
103                         std::map<Inset const *, Geometry>::const_iterator I = data.find(inset);
104
105                         // FIXME: in the case where the inset is not in the cache, this
106                         // means that no part of it is visible on screen. In this case
107                         // we don't do elaborate search and we just return the forwarded
108                         // DocIterator at its beginning.
109                         if (I == data.end()) {
110                                 it.top().pos() = 0;
111                                 return it;
112                         }
113
114                         Point o = I->second.pos;
115                         inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
116                         // Convert to absolute
117                         xo += o.x_;
118                         yo += o.y_;
119                         double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
120                         // '<=' in order to take the last possible position
121                         // this is important for clicking behind \sum in e.g. '\sum_i a'
122                         LYXERR(Debug::DEBUG, "i: " << i << " d: " << d
123                                 << " best: " << best_dist);
124                         if (d <= best_dist) {
125                                 best_dist = d;
126                                 result = it;
127                         }
128                         if (it == et)
129                                 break;
130                         it.forwardPos();
131                 }
132                 return result;
133         }
134
135
136         /*
137         /// moves position closest to (x, y) in given box
138         bool bruteFind(Cursor & cursor,
139                 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
140         {
141                 BOOST_ASSERT(!cursor.empty());
142                 Inset & inset = cursor[0].inset();
143                 BufferView & bv = cursor.bv();
144
145                 CoordCache::InnerParPosCache const & cache =
146                         bv.coordCache().getParPos().find(cursor.bottom().text())->second;
147                 // Get an iterator on the first paragraph in the cache
148                 DocIterator it(inset);
149                 it.push_back(CursorSlice(inset));
150                 it.pit() = cache.begin()->first;
151                 // Get an iterator after the last paragraph in the cache
152                 DocIterator et(inset);
153                 et.push_back(CursorSlice(inset));
154                 et.pit() = boost::prior(cache.end())->first;
155                 if (et.pit() >= et.lastpit())
156                         et = doc_iterator_end(inset);
157                 else
158                         ++et.pit();
159
160                 double best_dist = std::numeric_limits<double>::max();;
161                 DocIterator best_cursor = et;
162
163                 for ( ; it != et; it.forwardPos(true)) {
164                         // avoid invalid nesting when selecting
165                         if (!cursor.selection() || positionable(it, cursor.anchor_)) {
166                                 Point p = bv.getPos(it, false);
167                                 int xo = p.x_;
168                                 int yo = p.y_;
169                                 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
170                                         double const dx = xo - x;
171                                         double const dy = yo - y;
172                                         double const d = dx * dx + dy * dy;
173                                         // '<=' in order to take the last possible position
174                                         // this is important for clicking behind \sum in e.g. '\sum_i a'
175                                         if (d <= best_dist) {
176                                                 //      lyxerr << "*" << endl;
177                                                 best_dist   = d;
178                                                 best_cursor = it;
179                                         }
180                                 }
181                         }
182                 }
183
184                 if (best_cursor != et) {
185                         cursor.setCursor(best_cursor);
186                         return true;
187                 }
188
189                 return false;
190         }
191         */
192
193
194         /// moves position closest to (x, y) in given box
195         bool bruteFind3(Cursor & cur, int x, int y, bool up)
196         {
197                 BufferView & bv = cur.bv();
198                 int ylow  = up ? 0 : y + 1;
199                 int yhigh = up ? y - 1 : bv.workHeight();
200                 int xlow = 0;
201                 int xhigh = bv.workWidth();
202
203 // FIXME: bit more work needed to get 'from' and 'to' right.
204                 pit_type from = cur.bottom().pit();
205                 //pit_type to = cur.bottom().pit();
206                 //lyxerr << "Pit start: " << from << endl;
207
208                 //lyxerr << "bruteFind3: x: " << x << " y: " << y
209                 //      << " xlow: " << xlow << " xhigh: " << xhigh
210                 //      << " ylow: " << ylow << " yhigh: " << yhigh
211                 //      << endl;
212                 Inset & inset = bv.buffer().inset();
213                 DocIterator it = doc_iterator_begin(inset);
214                 it.pit() = from;
215                 DocIterator et = doc_iterator_end(inset);
216
217                 double best_dist = std::numeric_limits<double>::max();
218                 DocIterator best_cursor = et;
219
220                 for ( ; it != et; it.forwardPos()) {
221                         // avoid invalid nesting when selecting
222                         if (bv.cursorStatus(it) == CUR_INSIDE
223                             && (!cur.selection() || positionable(it, cur.anchor_))) {
224                                 Point p = bv.getPos(it, false);
225                                 int xo = p.x_;
226                                 int yo = p.y_;
227                                 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
228                                         double const dx = xo - x;
229                                         double const dy = yo - y;
230                                         double const d = dx * dx + dy * dy;
231                                         //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
232                                         //      << " dx: " << dx << " dy: " << dy
233                                         //      << " idx: " << it.idx() << " pos: " << it.pos()
234                                         //      << " it:\n" << it
235                                         //      << endl;
236                                         // '<=' in order to take the last possible position
237                                         // this is important for clicking behind \sum in e.g. '\sum_i a'
238                                         if (d <= best_dist) {
239                                                 //lyxerr << "*" << endl;
240                                                 best_dist   = d;
241                                                 best_cursor = it;
242                                         }
243                                 }
244                         }
245                 }
246
247                 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
248                 if (best_cursor == et)
249                         return false;
250                 cur.setCursor(best_cursor);
251                 return true;
252         }
253
254         docstring parbreak(Paragraph const & par)
255         {
256                 odocstringstream ods;
257                 ods << '\n';
258                 // only add blank line if we're not in an ERT or Listings inset
259                 if (par.ownerCode() != ERT_CODE
260                     && par.ownerCode() != LISTINGS_CODE)
261                         ods << '\n';
262                 return ods.str();
263         }
264
265 } // namespace anon
266
267
268 // be careful: this is called from the bv's constructor, too, so
269 // bv functions are not yet available!
270 Cursor::Cursor(BufferView & bv)
271         : DocIterator(), bv_(&bv), anchor_(), x_target_(-1), textTargetOffset_(0),
272           selection_(false), mark_(false), logicalpos_(false),
273           current_font(inherit_font)
274 {}
275
276
277 void Cursor::reset(Inset & inset)
278 {
279         clear();
280         push_back(CursorSlice(inset));
281         anchor_ = DocIterator(inset);
282         clearTargetX();
283         selection_ = false;
284         mark_ = false;
285 }
286
287
288 // this (intentionally) does neither touch anchor nor selection status
289 void Cursor::setCursor(DocIterator const & cur)
290 {
291         DocIterator::operator=(cur);
292 }
293
294
295 void Cursor::dispatch(FuncRequest const & cmd0)
296 {
297         LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION
298                              << " cmd: " << cmd0 << '\n' << *this);
299         if (empty())
300                 return;
301
302         fixIfBroken();
303         FuncRequest cmd = cmd0;
304         Cursor safe = *this;
305         
306         // store some values to be used inside of the handlers
307         getPos(beforeDispX_, beforeDispY_);
308         beforeDispatchCursor_ = *this;
309         for (; depth(); pop()) {
310                 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
311                         << cmd0 << endl << *this);
312                 BOOST_ASSERT(pos() <= lastpos());
313                 BOOST_ASSERT(idx() <= lastidx());
314                 BOOST_ASSERT(pit() <= lastpit());
315
316                 // The common case is 'LFUN handled, need update', so make the
317                 // LFUN handler's life easier by assuming this as default value.
318                 // The handler can reset the update and val flags if necessary.
319                 disp_.update(Update::FitCursor | Update::Force);
320                 disp_.dispatched(true);
321                 inset().dispatch(*this, cmd);
322                 if (disp_.dispatched())
323                         break;
324         }
325         
326         // it completely to get a 'bomb early' behaviour in case this
327         // object will be used again.
328         if (!disp_.dispatched()) {
329                 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
330                 operator=(safe);
331                 disp_.update(Update::None);
332                 disp_.dispatched(false);
333         } else {
334                 // restore the previous one because nested Cursor::dispatch calls
335                 // are possible which would change it
336                 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
337         }
338 }
339
340
341 DispatchResult Cursor::result() const
342 {
343         return disp_;
344 }
345
346
347 BufferView & Cursor::bv() const
348 {
349         BOOST_ASSERT(bv_);
350         return *bv_;
351 }
352
353
354 Buffer & Cursor::buffer() const
355 {
356         BOOST_ASSERT(bv_);
357         return bv_->buffer();
358 }
359
360
361 void Cursor::pop()
362 {
363         BOOST_ASSERT(depth() >= 1);
364         pop_back();
365 }
366
367
368 void Cursor::push(Inset & p)
369 {
370         push_back(CursorSlice(p));
371 }
372
373
374 void Cursor::pushBackward(Inset & p)
375 {
376         BOOST_ASSERT(!empty());
377         //lyxerr << "Entering inset " << t << " front" << endl;
378         push(p);
379         p.idxFirst(*this);
380 }
381
382
383 bool Cursor::popBackward()
384 {
385         BOOST_ASSERT(!empty());
386         //lyxerr << "Leaving inset from in front" << endl;
387         inset().notifyCursorLeaves(*this);
388         if (depth() == 1)
389                 return false;
390         pop();
391         return true;
392 }
393
394
395 bool Cursor::popForward()
396 {
397         BOOST_ASSERT(!empty());
398         //lyxerr << "Leaving inset from in back" << endl;
399         const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
400         inset().notifyCursorLeaves(*this);
401         if (depth() == 1)
402                 return false;
403         pop();
404         pos() += lastpos() - lp + 1;
405         return true;
406 }
407
408
409 int Cursor::currentMode()
410 {
411         BOOST_ASSERT(!empty());
412         for (int i = depth() - 1; i >= 0; --i) {
413                 int res = operator[](i).inset().currentMode();
414                 if (res != Inset::UNDECIDED_MODE)
415                         return res;
416         }
417         return Inset::TEXT_MODE;
418 }
419
420
421 void Cursor::getPos(int & x, int & y) const
422 {
423         Point p = bv().getPos(*this, boundary());
424         x = p.x_;
425         y = p.y_;
426 }
427
428
429 Row const & Cursor::textRow() const
430 {
431         ParagraphMetrics const & pm = bv().parMetrics(text(), pit());
432         BOOST_ASSERT(!pm.rows().empty());
433         return pm.getRow(pos(), boundary());
434 }
435
436
437 void Cursor::resetAnchor()
438 {
439         anchor_ = *this;
440 }
441
442
443
444 bool Cursor::posBackward()
445 {
446         if (pos() == 0)
447                 return false;
448         --pos();
449         return true;
450 }
451
452
453 bool Cursor::posForward()
454 {
455         if (pos() == lastpos())
456                 return false;
457         ++pos();
458         return true;
459 }
460
461
462 CursorSlice Cursor::anchor() const
463 {
464         BOOST_ASSERT(anchor_.depth() >= depth());
465         CursorSlice normal = anchor_[depth() - 1];
466         if (depth() < anchor_.depth() && top() <= normal) {
467                 // anchor is behind cursor -> move anchor behind the inset
468                 ++normal.pos();
469         }
470         return normal;
471 }
472
473
474 CursorSlice Cursor::selBegin() const
475 {
476         if (!selection())
477                 return top();
478         return anchor() < top() ? anchor() : top();
479 }
480
481
482 CursorSlice Cursor::selEnd() const
483 {
484         if (!selection())
485                 return top();
486         return anchor() > top() ? anchor() : top();
487 }
488
489
490 DocIterator Cursor::selectionBegin() const
491 {
492         if (!selection())
493                 return *this;
494         DocIterator di = (anchor() < top() ? anchor_ : *this);
495         di.resize(depth());
496         return di;
497 }
498
499
500 DocIterator Cursor::selectionEnd() const
501 {
502         if (!selection())
503                 return *this;
504         DocIterator di = (anchor() > top() ? anchor_ : *this);
505         if (di.depth() > depth()) {
506                 di.resize(depth());
507                 ++di.pos();
508         }
509         return di;
510 }
511
512
513 void Cursor::setSelection()
514 {
515         selection() = true;
516         // A selection with no contents is not a selection
517         // FIXME: doesnt look ok
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 (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                 posBackward();
777                 // be careful here: don't use 'pushBackward(t)' as this we need to
778                 // push the clone, not the original
779                 pushBackward(*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                         popBackward();
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                                 popBackward();
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                         popBackward();
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         MathAtom atom = createInsetMath(name);
949         MathMacro * atomAsMacro = atom.nucleus()->asMacro();
950         if (atomAsMacro) {
951                 // make non-greedy, i.e. don't eat parameters from the right
952                 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT);
953         }
954         plainInsert(atom);
955         return true;
956 }
957
958
959 docstring Cursor::macroName()
960 {
961         return inMacroMode() ? activeMacro()->name() : docstring();
962 }
963
964
965 void Cursor::handleNest(MathAtom const & a, int c)
966 {
967         //lyxerr << "Cursor::handleNest: " << c << endl;
968         MathAtom t = a;
969         asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
970         insert(t);
971         posBackward();
972         pushBackward(*nextInset());
973 }
974
975
976 int Cursor::targetX() const
977 {
978         if (x_target() != -1)
979                 return x_target();
980         int x = 0;
981         int y = 0;
982         getPos(x, y);
983         return x;
984 }
985
986
987 int Cursor::textTargetOffset() const
988 {
989         return textTargetOffset_;
990 }
991
992
993 void Cursor::setTargetX()
994 {
995         int x;
996         int y;
997         getPos(x, y);
998         setTargetX(x);
999 }
1000
1001
1002 bool Cursor::inMacroMode() const
1003 {
1004         if (!inMathed())
1005                 return false;
1006         if (pos() == 0)
1007                 return false;
1008         InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1009         return p && !p->final();
1010 }
1011
1012
1013 InsetMathUnknown * Cursor::activeMacro()
1014 {
1015         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1016 }
1017
1018
1019 void Cursor::pullArg()
1020 {
1021         // FIXME: Look here
1022         MathData ar = cell();
1023         if (popBackward() && inMathed()) {
1024                 plainErase();
1025                 cell().insert(pos(), ar);
1026                 resetAnchor();
1027         } else {
1028                 //formula()->mutateToText();
1029         }
1030 }
1031
1032
1033 void Cursor::touch()
1034 {
1035         // FIXME: look here
1036 #if 0
1037         DocIterator::const_iterator it = begin();
1038         DocIterator::const_iterator et = end();
1039         for ( ; it != et; ++it)
1040                 it->cell().touch();
1041 #endif
1042 }
1043
1044
1045 void Cursor::normalize()
1046 {
1047         if (idx() > lastidx()) {
1048                 lyxerr << "this should not really happen - 1: "
1049                        << idx() << ' ' << nargs()
1050                        << " in: " << &inset() << endl;
1051                 idx() = lastidx();
1052         }
1053
1054         if (pos() > lastpos()) {
1055                 lyxerr << "this should not really happen - 2: "
1056                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
1057                        << " in atom: '";
1058                 odocstringstream os;
1059                 WriteStream wi(os, false, true);
1060                 inset().asInsetMath()->write(wi);
1061                 lyxerr << to_utf8(os.str()) << endl;
1062                 pos() = lastpos();
1063         }
1064 }
1065
1066
1067 bool Cursor::upDownInMath(bool up)
1068 {
1069         // Be warned: The 'logic' implemented in this function is highly
1070         // fragile. A distance of one pixel or a '<' vs '<=' _really
1071         // matters. So fiddle around with it only if you think you know
1072         // what you are doing!
1073         int xo = 0;
1074         int yo = 0;
1075         getPos(xo, yo);
1076         xo = beforeDispX_;
1077
1078         // check if we had something else in mind, if not, this is the future
1079         // target
1080         if (x_target_ == -1)
1081                 setTargetX(xo);
1082         else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1083                 // In text mode inside the line (not left or right) possibly set a new target_x,
1084                 // but only if we are somewhere else than the previous target-offset.
1085                 
1086                 // We want to keep the x-target on subsequent up/down movements
1087                 // that cross beyond the end of short lines. Thus a special
1088                 // handling when the cursor is at the end of line: Use the new
1089                 // x-target only if the old one was before the end of line
1090                 // or the old one was after the beginning of the line
1091                 bool inRTL = isWithinRtlParagraph(*this);
1092                 bool left;
1093                 bool right;
1094                 if (inRTL) {
1095                         left = pos() == textRow().endpos();
1096                         right = pos() == textRow().pos();
1097                 } else {
1098                         left = pos() == textRow().pos();
1099                         right = pos() == textRow().endpos();
1100                 }
1101                 if ((!left && !right) ||
1102                                 (left && !right && xo < x_target_) ||
1103                                 (!left && right && x_target_ < xo))
1104                         setTargetX(xo);
1105                 else
1106                         xo = targetX();
1107         } else
1108                 xo = targetX();
1109
1110         // try neigbouring script insets
1111         Cursor old = *this;
1112         if (inMathed() && !selection()) {
1113                 // try left
1114                 if (pos() != 0) {
1115                         InsetMathScript const * p = prevAtom()->asScriptInset();
1116                         if (p && p->has(up)) {
1117                                 --pos();
1118                                 push(*const_cast<InsetMathScript*>(p));
1119                                 idx() = p->idxOfScript(up);
1120                                 pos() = lastpos();
1121                                 
1122                                 // we went in the right direction? Otherwise don't jump into the script
1123                                 int x;
1124                                 int y;
1125                                 getPos(x, y);
1126                                 if ((!up && y <= beforeDispY_) ||
1127                                                 (up && y >= beforeDispY_))
1128                                         operator=(old);
1129                                 else
1130                                         return true;
1131                         }
1132                 }
1133                 
1134                 // try right
1135                 if (pos() != lastpos()) {
1136                         InsetMathScript const * p = nextAtom()->asScriptInset();
1137                         if (p && p->has(up)) {
1138                                 push(*const_cast<InsetMathScript*>(p));
1139                                 idx() = p->idxOfScript(up);
1140                                 pos() = 0;
1141                                 
1142                                 // we went in the right direction? Otherwise don't jump into the script
1143                                 int x;
1144                                 int y;
1145                                 getPos(x, y);
1146                                 if ((!up && y <= beforeDispY_) ||
1147                                                 (up && y >= beforeDispY_))
1148                                         operator=(old);
1149                                 else
1150                                         return true;
1151                         }
1152                 }
1153         }
1154                 
1155         // try to find an inset that knows better then we,
1156         if (inset().idxUpDown(*this, up)) {
1157                 //lyxerr << "idxUpDown triggered" << endl;
1158                 // try to find best position within this inset
1159                 if (!selection())
1160                         setCursor(bruteFind2(*this, xo, yo));
1161                 return true;
1162         }
1163         
1164         // any improvement going just out of inset?
1165         if (popBackward() && inMathed()) {
1166                 //lyxerr << "updown: popBackward succeeded" << endl;
1167                 int xnew;
1168                 int ynew;
1169                 getPos(xnew, ynew);
1170                 if (up ? ynew < beforeDispY_ : ynew > beforeDispY_)
1171                         return true;
1172         }
1173         
1174         // no success, we are probably at the document top or bottom
1175         operator=(old);
1176         return false;
1177 }
1178
1179
1180 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1181 {
1182         BOOST_ASSERT(text());
1183
1184         // where are we?
1185         int xo = 0;
1186         int yo = 0;
1187         getPos(xo, yo);
1188         xo = beforeDispX_;
1189         
1190         // update the targetX - this is here before the "return false"
1191         // to set a new target which can be used by InsetTexts above
1192         // if we cannot move up/down inside this inset anymore
1193         if (x_target_ == -1)
1194                 setTargetX(xo);
1195         else if (xo - textTargetOffset() != x_target() &&
1196                                          depth() == beforeDispatchCursor_.depth()) {
1197                 // In text mode inside the line (not left or right) possibly set a new target_x,
1198                 // but only if we are somewhere else than the previous target-offset.
1199                 
1200                 // We want to keep the x-target on subsequent up/down movements
1201                 // that cross beyond the end of short lines. Thus a special
1202                 // handling when the cursor is at the end of line: Use the new
1203                 // x-target only if the old one was before the end of line
1204                 // or the old one was after the beginning of the line
1205                 bool inRTL = isWithinRtlParagraph(*this);
1206                 bool left;
1207                 bool right;
1208                 if (inRTL) {
1209                         left = pos() == textRow().endpos();
1210                         right = pos() == textRow().pos();
1211                 } else {
1212                         left = pos() == textRow().pos();
1213                         right = pos() == textRow().endpos();
1214                 }
1215                 if ((!left && !right) ||
1216                                 (left && !right && xo < x_target_) ||
1217                                 (!left && right && x_target_ < xo))
1218                         setTargetX(xo);
1219                 else
1220                         xo = targetX();
1221         } else
1222                 xo = targetX();
1223                 
1224         // first get the current line
1225         TextMetrics & tm = bv_->textMetrics(text());
1226         ParagraphMetrics const & pm = tm.parMetrics(pit());
1227         int row;
1228         if (pos() && boundary())
1229                 row = pm.pos2row(pos() - 1);
1230         else
1231                 row = pm.pos2row(pos());
1232                 
1233         // are we not at the start or end?
1234         if (up) {
1235                 if (pit() == 0 && row == 0)
1236                         return false;
1237         } else {
1238                 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1239                                 row + 1 >= int(pm.rows().size()))
1240                         return false;
1241         }       
1242
1243         // with and without selection are handled differently
1244         if (!selection()) {
1245                 int yo = bv().getPos(*this, boundary()).y_;
1246                 Cursor old = *this;
1247                 // To next/previous row
1248                 if (up)
1249                         tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1250                 else
1251                         tm.editXY(*this, xo, yo + textRow().descent() + 1);
1252                 clearSelection();
1253                 
1254                 // This happens when you move out of an inset.
1255                 // And to give the DEPM the possibility of doing
1256                 // something we must provide it with two different
1257                 // cursors. (Lgb)
1258                 Cursor dummy = *this;
1259                 if (dummy == old)
1260                         ++dummy.pos();
1261                 if (bv().checkDepm(dummy, old)) {
1262                         updateNeeded = true;
1263                         // Make sure that cur gets back whatever happened to dummy(Lgb)
1264                         operator=(dummy);
1265                 }
1266         } else {
1267                 // if there is a selection, we stay out of any inset, and just jump to the right position:
1268                 Cursor old = *this;
1269                 if (up) {
1270                         if (row > 0) {
1271                                 top().pos() = std::min(tm.x2pos(pit(), row - 1, xo), top().lastpos());
1272                         } else if (pit() > 0) {
1273                                 --pit();
1274                                 ParagraphMetrics const & pmcur = bv_->parMetrics(text(), pit());
1275                                 top().pos() = std::min(tm.x2pos(pit(), pmcur.rows().size() - 1, xo), top().lastpos());
1276                         }
1277                 } else {
1278                         if (row + 1 < int(pm.rows().size())) {
1279                                 top().pos() = std::min(tm.x2pos(pit(), row + 1, xo), top().lastpos());
1280                         } else if (pit() + 1 < int(text()->paragraphs().size())) {
1281                                 ++pit();
1282                                 top().pos() = std::min(tm.x2pos(pit(), 0, xo), top().lastpos());
1283                         }
1284                 }
1285
1286                 updateNeeded |= bv().checkDepm(*this, old);
1287         }
1288
1289         updateTextTargetOffset();
1290         return true;
1291 }       
1292
1293
1294 void Cursor::handleFont(string const & font)
1295 {
1296         LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION << ": " << font);
1297         docstring safe;
1298         if (selection()) {
1299                 macroModeClose();
1300                 safe = cap::grabAndEraseSelection(*this);
1301         }
1302
1303         if (lastpos() != 0) {
1304                 // something left in the cell
1305                 if (pos() == 0) {
1306                         // cursor in first position
1307                         popBackward();
1308                 } else if (pos() == lastpos()) {
1309                         // cursor in last position
1310                         popForward();
1311                 } else {
1312                         // cursor in between. split cell
1313                         MathData::iterator bt = cell().begin();
1314                         MathAtom at = createInsetMath(from_utf8(font));
1315                         at.nucleus()->cell(0) = MathData(bt, bt + pos());
1316                         cell().erase(bt, bt + pos());
1317                         popBackward();
1318                         plainInsert(at);
1319                 }
1320         } else {
1321                 // nothing left in the cell
1322                 pullArg();
1323                 plainErase();
1324         }
1325         insert(safe);
1326 }
1327
1328
1329 void Cursor::message(docstring const & msg) const
1330 {
1331         theLyXFunc().setMessage(msg);
1332 }
1333
1334
1335 void Cursor::errorMessage(docstring const & msg) const
1336 {
1337         theLyXFunc().setErrorMessage(msg);
1338 }
1339
1340
1341 docstring Cursor::selectionAsString(bool label) const
1342 {
1343         if (!selection())
1344                 return docstring();
1345
1346         if (inTexted()) {
1347                 Buffer const & buffer = bv().buffer();
1348                 ParagraphList const & pars = text()->paragraphs();
1349
1350                 // should be const ...
1351                 pit_type startpit = selBegin().pit();
1352                 pit_type endpit = selEnd().pit();
1353                 size_t const startpos = selBegin().pos();
1354                 size_t const endpos = selEnd().pos();
1355
1356                 if (startpit == endpit)
1357                         return pars[startpit].asString(buffer, startpos, endpos, label);
1358
1359                 // First paragraph in selection
1360                 docstring result = pars[startpit].
1361                         asString(buffer, startpos, pars[startpit].size(), label)
1362                                  + parbreak(pars[startpit]);
1363
1364                 // The paragraphs in between (if any)
1365                 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1366                         Paragraph const & par = pars[pit];
1367                         result += par.asString(buffer, 0, par.size(), label)
1368                                   + parbreak(pars[pit]);
1369                 }
1370
1371                 // Last paragraph in selection
1372                 result += pars[endpit].asString(buffer, 0, endpos, label);
1373
1374                 return result;
1375         }
1376
1377         if (inMathed())
1378                 return cap::grabSelection(*this);
1379
1380         return docstring();
1381 }
1382
1383
1384 docstring Cursor::currentState()
1385 {
1386         if (inMathed()) {
1387                 odocstringstream os;
1388                 info(os);
1389                 return os.str();
1390         }
1391
1392         if (inTexted())
1393                 return text()->currentState(*this);
1394
1395         return docstring();
1396 }
1397
1398
1399 docstring Cursor::getPossibleLabel()
1400 {
1401         return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
1402 }
1403
1404
1405 Encoding const * Cursor::getEncoding() const
1406 {
1407         if (empty())
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 Cursor::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                 TextMetrics const & tm = bv().textMetrics(&text);
1472                 if (pos == sl.lastpos()
1473                         || (par.isSeparator(pos) 
1474                         && !tm.isRTLBoundary(sl.pit(), pos)))
1475                         --pos;
1476         }
1477         
1478         // get font at the position
1479         Font font = par.getFont(bv().buffer().params(), pos,
1480                 outerFont(sl.pit(), text.paragraphs()));
1481
1482         return font;
1483 }
1484
1485
1486 bool Cursor::fixIfBroken()
1487 {
1488         if (DocIterator::fixIfBroken()) {
1489                         clearSelection();
1490                         resetAnchor();
1491                         return true;
1492         }
1493         return false;
1494 }
1495
1496
1497 bool notifyCursorLeaves(DocIterator const & old, Cursor & cur)
1498 {
1499         // find inset in common
1500         size_type i;
1501         for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
1502                 if (&old.inset() != &cur.inset())
1503                         break;
1504         }
1505         
1506         // notify everything on top of the common part in old cursor,
1507         // but stop if the inset claims the cursor to be invalid now
1508         for (;  i < old.depth(); ++i) {
1509                 if (old[i].inset().notifyCursorLeaves(cur))
1510                         return true;
1511         }
1512         
1513         return false;
1514 }
1515
1516
1517 void Cursor::setCurrentFont()
1518 {
1519         CursorSlice const & cs = innerTextSlice();
1520         Paragraph const & par = cs.paragraph();
1521         pos_type cpit = cs.pit();
1522         pos_type cpos = cs.pos();
1523         Text const & ctext = *cs.text();
1524         TextMetrics const & tm = bv().textMetrics(&ctext);
1525
1526         // are we behind previous char in fact? -> go to that char
1527         if (cpos > 0 && boundary())
1528                 --cpos;
1529
1530         // find position to take the font from
1531         if (cpos != 0) {
1532                 // paragraph end? -> font of last char
1533                 if (cpos == lastpos())
1534                         --cpos;
1535                 // on space? -> look at the words in front of space
1536                 else if (cpos > 0 && par.isSeparator(cpos))     {
1537                         // abc| def -> font of c
1538                         // abc |[WERBEH], i.e. boundary==true -> font of c
1539                         // abc [WERBEH]| def, font of the space
1540                         if (!tm.isRTLBoundary(cpit, cpos))
1541                                 --cpos;
1542                 }
1543         }
1544
1545         // get font
1546         BufferParams const & bufparams = buffer().params();
1547         current_font = par.getFontSettings(bufparams, cpos);
1548         real_current_font = tm.getDisplayFont(cpit, cpos);
1549
1550         // special case for paragraph end
1551         if (cs.pos() == lastpos()
1552             && tm.isRTLBoundary(cpit, cs.pos())
1553             && !boundary()) {
1554                 Language const * lang = par.getParLanguage(bufparams);
1555                 current_font.setLanguage(lang);
1556                 current_font.fontInfo().setNumber(FONT_OFF);
1557                 real_current_font.setLanguage(lang);
1558                 real_current_font.fontInfo().setNumber(FONT_OFF);
1559         }
1560 }
1561
1562
1563 bool Cursor::textUndo()
1564 {
1565         DocIterator dit = *this;
1566         // Undo::textUndo() will modify dit.
1567         if (!bv_->buffer().undo().textUndo(dit))
1568                 return false;
1569         // Set cursor
1570         setCursor(dit);
1571         selection() = false;
1572         resetAnchor();
1573         fixIfBroken();
1574         return true;
1575 }
1576
1577
1578 bool Cursor::textRedo()
1579 {
1580         DocIterator dit = *this;
1581         // Undo::textRedo() will modify dit.
1582         if (!bv_->buffer().undo().textRedo(dit))
1583                 return false;
1584         // Set cursor
1585         setCursor(dit);
1586         selection() = false;
1587         resetAnchor();
1588         fixIfBroken();
1589         return true;
1590 }
1591
1592
1593 void Cursor::finishUndo()
1594 {
1595         bv_->buffer().undo().finishUndo();
1596 }
1597
1598
1599 void Cursor::recordUndo(UndoKind kind, pit_type from, pit_type to)
1600 {
1601         bv_->buffer().undo().recordUndo(*this, kind, from, to);
1602 }
1603
1604
1605 void Cursor::recordUndo(UndoKind kind, pit_type from)
1606 {
1607         bv_->buffer().undo().recordUndo(*this, kind, from);
1608 }
1609
1610
1611 void Cursor::recordUndo(UndoKind kind)
1612 {
1613         bv_->buffer().undo().recordUndo(*this, kind);
1614 }
1615
1616
1617 void Cursor::recordUndoInset(UndoKind kind)
1618 {
1619         bv_->buffer().undo().recordUndoInset(*this, kind);
1620 }
1621
1622
1623 void Cursor::recordUndoFullDocument()
1624 {
1625         bv_->buffer().undo().recordUndoFullDocument(*this);
1626 }
1627
1628
1629 void Cursor::recordUndoSelection()
1630 {
1631         bv_->buffer().undo().recordUndo(*this, ATOMIC_UNDO,
1632                 selBegin().pit(), selEnd().pit());
1633 }
1634
1635
1636 } // namespace lyx