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