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