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