]> git.lyx.org Git - lyx.git/blob - src/Cursor.cpp
* src/Cursor.cpp (parbreak):
[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  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "BufferView.h"
16 #include "bufferview_funcs.h"
17 #include "Buffer.h"
18 #include "Cursor.h"
19 #include "CoordCache.h"
20 #include "CutAndPaste.h"
21 #include "debug.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
36 #include "insets/InsetTabular.h"
37 #include "insets/InsetText.h"
38
39 #include "mathed/MathData.h"
40 #include "mathed/InsetMath.h"
41 #include "mathed/InsetMathScript.h"
42 #include "mathed/MacroTable.h"
43
44 #include "support/limited_stack.h"
45
46 #include <boost/assert.hpp>
47 #include <boost/bind.hpp>
48 #include <boost/current_function.hpp>
49
50 #include <sstream>
51 #include <limits>
52 #include <map>
53
54 namespace lyx {
55
56 using std::string;
57 using std::vector;
58 using std::endl;
59 using std::min;
60 using std::for_each;
61
62 namespace {
63
64         bool
65         positionable(DocIterator const & cursor, DocIterator const & anchor)
66         {
67                 // avoid deeper nested insets when selecting
68                 if (cursor.depth() > anchor.depth())
69                         return false;
70
71                 // anchor might be deeper, should have same path then
72                 for (size_t i = 0; i < cursor.depth(); ++i)
73                         if (&cursor[i].inset() != &anchor[i].inset())
74                                 return false;
75
76                 // position should be ok.
77                 return true;
78         }
79
80
81         // Find position closest to (x, y) in cell given by iter.
82         // Used only in mathed
83         DocIterator bruteFind2(Cursor const & c, int x, int y)
84         {
85                 double best_dist = std::numeric_limits<double>::max();
86
87                 DocIterator result;
88
89                 DocIterator it = c;
90                 it.top().pos() = 0;
91                 DocIterator et = c;
92                 et.top().pos() = et.top().asInsetMath()->cell(et.top().idx()).size();
93                 for (size_t i = 0;; ++i) {
94                         int xo;
95                         int yo;
96                         Inset const * inset = &it.inset();
97                         std::map<Inset const *, Point> const & data =
98                                 c.bv().coordCache().getInsets().getData();
99                         std::map<Inset const *, Point>::const_iterator I = data.find(inset);
100
101                         // FIXME: in the case where the inset is not in the cache, this
102                         // means that no part of it is visible on screen. In this case
103                         // we don't do elaborate search and we just return the forwarded
104                         // DocIterator at its beginning.
105                         if (I == data.end()) {
106                                 it.top().pos() = 0;
107                                 return it;
108                         }
109
110                         Point o = I->second;
111                         inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
112                         // Convert to absolute
113                         xo += o.x_;
114                         yo += o.y_;
115                         double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
116                         // '<=' in order to take the last possible position
117                         // this is important for clicking behind \sum in e.g. '\sum_i a'
118                         LYXERR(Debug::DEBUG) << "i: " << i << " d: " << d
119                                 << " best: " << best_dist << endl;
120                         if (d <= best_dist) {
121                                 best_dist = d;
122                                 result = it;
123                         }
124                         if (it == et)
125                                 break;
126                         it.forwardPos();
127                 }
128                 return result;
129         }
130
131
132         /// moves position closest to (x, y) in given box
133         bool bruteFind(Cursor & cursor,
134                 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
135         {
136                 BOOST_ASSERT(!cursor.empty());
137                 Inset & inset = cursor[0].inset();
138                 BufferView & bv = cursor.bv();
139
140                 CoordCache::InnerParPosCache const & cache =
141                         bv.coordCache().getParPos().find(cursor.bottom().text())->second;
142                 // Get an iterator on the first paragraph in the cache
143                 DocIterator it(inset);
144                 it.push_back(CursorSlice(inset));
145                 it.pit() = cache.begin()->first;
146                 // Get an iterator after the last paragraph in the cache
147                 DocIterator et(inset);
148                 et.push_back(CursorSlice(inset));
149                 et.pit() = boost::prior(cache.end())->first;
150                 if (et.pit() >= et.lastpit())
151                         et = doc_iterator_end(inset);
152                 else
153                         ++et.pit();
154
155                 double best_dist = std::numeric_limits<double>::max();;
156                 DocIterator best_cursor = et;
157
158                 for ( ; it != et; it.forwardPos(true)) {
159                         // avoid invalid nesting when selecting
160                         if (!cursor.selection() || positionable(it, cursor.anchor_)) {
161                                 Point p = bv_funcs::getPos(bv, it, false);
162                                 int xo = p.x_;
163                                 int yo = p.y_;
164                                 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
165                                         double const dx = xo - x;
166                                         double const dy = yo - y;
167                                         double const d = dx * dx + dy * dy;
168                                         // '<=' in order to take the last possible position
169                                         // this is important for clicking behind \sum in e.g. '\sum_i a'
170                                         if (d <= best_dist) {
171                                                 //      lyxerr << "*" << endl;
172                                                 best_dist   = d;
173                                                 best_cursor = it;
174                                         }
175                                 }
176                         }
177                 }
178
179                 if (best_cursor != et) {
180                         cursor.setCursor(best_cursor);
181                         return true;
182                 }
183
184                 return false;
185         }
186
187
188         /// moves position closest to (x, y) in given box
189         bool bruteFind3(Cursor & cur, int x, int y, bool up)
190         {
191                 BufferView & bv = cur.bv();
192                 int ylow  = up ? 0 : y + 1;
193                 int yhigh = up ? y - 1 : bv.workHeight();
194                 int xlow = 0;
195                 int xhigh = bv.workWidth();
196
197 // FIXME: bit more work needed to get 'from' and 'to' right.
198                 pit_type from = cur.bottom().pit();
199                 //pit_type to = cur.bottom().pit();
200                 //lyxerr << "Pit start: " << from << endl;
201
202                 //lyxerr << "bruteFind3: x: " << x << " y: " << y
203                 //      << " xlow: " << xlow << " xhigh: " << xhigh
204                 //      << " ylow: " << ylow << " yhigh: " << yhigh
205                 //      << endl;
206                 Inset & inset = bv.buffer()->inset();
207                 DocIterator it = doc_iterator_begin(inset);
208                 it.pit() = from;
209                 DocIterator et = doc_iterator_end(inset);
210
211                 double best_dist = std::numeric_limits<double>::max();
212                 DocIterator best_cursor = et;
213
214                 for ( ; it != et; it.forwardPos()) {
215                         // avoid invalid nesting when selecting
216                         if (bv_funcs::status(&bv, it) == bv_funcs::CUR_INSIDE
217                             && (!cur.selection() || positionable(it, cur.anchor_))) {
218                                 Point p = bv_funcs::getPos(bv, it, false);
219                                 int xo = p.x_;
220                                 int yo = p.y_;
221                                 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
222                                         double const dx = xo - x;
223                                         double const dy = yo - y;
224                                         double const d = dx * dx + dy * dy;
225                                         //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
226                                         //      << " dx: " << dx << " dy: " << dy
227                                         //      << " idx: " << it.idx() << " pos: " << it.pos()
228                                         //      << " it:\n" << it
229                                         //      << endl;
230                                         // '<=' in order to take the last possible position
231                                         // this is important for clicking behind \sum in e.g. '\sum_i a'
232                                         if (d <= best_dist) {
233                                                 //lyxerr << "*" << endl;
234                                                 best_dist   = d;
235                                                 best_cursor = it;
236                                         }
237                                 }
238                         }
239                 }
240
241                 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
242                 if (best_cursor == et)
243                         return false;
244                 cur.setCursor(best_cursor);
245                 return true;
246         }
247
248         docstring parbreak(Paragraph const & par)
249         {
250                 odocstringstream ods;
251                 ods << '\n';
252                 // only add blank line if we're not in an ERT or Listings inset
253                 if (par.ownerCode() != Inset::ERT_CODE 
254                     && par.ownerCode() != Inset::LISTINGS_CODE)
255                         ods << '\n';
256                 return ods.str();
257         }
258
259 } // namespace anon
260
261
262 // be careful: this is called from the bv's constructor, too, so
263 // bv functions are not yet available!
264 Cursor::Cursor(BufferView & bv)
265         : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
266           selection_(false), mark_(false), logicalpos_(false)
267 {}
268
269
270 void Cursor::reset(Inset & inset)
271 {
272         clear();
273         push_back(CursorSlice(inset));
274         anchor_ = DocIterator(inset);
275         clearTargetX();
276         selection_ = false;
277         mark_ = false;
278 }
279
280
281 // this (intentionally) does neither touch anchor nor selection status
282 void Cursor::setCursor(DocIterator const & cur)
283 {
284         DocIterator::operator=(cur);
285 }
286
287
288 void Cursor::dispatch(FuncRequest const & cmd0)
289 {
290         LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
291                              << " cmd: " << cmd0 << '\n'
292                              << *this << endl;
293         if (empty())
294                 return;
295
296         fixIfBroken();
297         FuncRequest cmd = cmd0;
298         Cursor safe = *this;
299
300         for (; depth(); pop()) {
301                 LYXERR(Debug::DEBUG) << "Cursor::dispatch: cmd: "
302                         << cmd0 << endl << *this << endl;
303                 BOOST_ASSERT(pos() <= lastpos());
304                 BOOST_ASSERT(idx() <= lastidx());
305                 BOOST_ASSERT(pit() <= lastpit());
306
307                 // The common case is 'LFUN handled, need update', so make the
308                 // LFUN handler's life easier by assuming this as default value.
309                 // The handler can reset the update and val flags if necessary.
310                 disp_.update(Update::FitCursor | Update::Force);
311                 disp_.dispatched(true);
312                 inset().dispatch(*this, cmd);
313                 if (disp_.dispatched())
314                         break;
315         }
316         // it completely to get a 'bomb early' behaviour in case this
317         // object will be used again.
318         if (!disp_.dispatched()) {
319                 LYXERR(Debug::DEBUG) << "RESTORING OLD CURSOR!" << endl;
320                 operator=(safe);
321                 disp_.update(Update::None);
322                 disp_.dispatched(false);
323         }
324 }
325
326
327 DispatchResult Cursor::result() const
328 {
329         return disp_;
330 }
331
332
333 BufferView & Cursor::bv() const
334 {
335         BOOST_ASSERT(bv_);
336         return *bv_;
337 }
338
339
340 Buffer & Cursor::buffer() const
341 {
342         BOOST_ASSERT(bv_);
343         BOOST_ASSERT(bv_->buffer());
344         return *bv_->buffer();
345 }
346
347
348 void Cursor::pop()
349 {
350         BOOST_ASSERT(depth() >= 1);
351         pop_back();
352 }
353
354
355 void Cursor::push(Inset & p)
356 {
357         push_back(CursorSlice(p));
358 }
359
360
361 void Cursor::pushLeft(Inset & p)
362 {
363         BOOST_ASSERT(!empty());
364         //lyxerr << "Entering inset " << t << " left" << endl;
365         push(p);
366         p.idxFirst(*this);
367 }
368
369
370 bool Cursor::popLeft()
371 {
372         BOOST_ASSERT(!empty());
373         //lyxerr << "Leaving inset to the left" << endl;
374         inset().notifyCursorLeaves(*this);
375         if (depth() == 1)
376                 return false;
377         pop();
378         return true;
379 }
380
381
382 bool Cursor::popRight()
383 {
384         BOOST_ASSERT(!empty());
385         //lyxerr << "Leaving inset to the right" << endl;
386         const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
387         inset().notifyCursorLeaves(*this);
388         if (depth() == 1)
389                 return false;
390         pop();
391         pos() += lastpos() - lp + 1;
392         return true;
393 }
394
395
396 int Cursor::currentMode()
397 {
398         BOOST_ASSERT(!empty());
399         for (int i = depth() - 1; i >= 0; --i) {
400                 int res = operator[](i).inset().currentMode();
401                 if (res != Inset::UNDECIDED_MODE)
402                         return res;
403         }
404         return Inset::TEXT_MODE;
405 }
406
407
408 void Cursor::getPos(int & x, int & y) const
409 {
410         Point p = bv_funcs::getPos(bv(), *this, boundary());
411         x = p.x_;
412         y = p.y_;
413 }
414
415
416 Row const & Cursor::textRow() const
417 {
418         ParagraphMetrics const & pm = bv().parMetrics(text(), pit());
419         BOOST_ASSERT(!pm.rows().empty());
420         return pm.getRow(pos(), boundary());
421 }
422
423
424 void Cursor::resetAnchor()
425 {
426         anchor_ = *this;
427 }
428
429
430
431 bool Cursor::posLeft()
432 {
433         if (pos() == 0)
434                 return false;
435         --pos();
436         return true;
437 }
438
439
440 bool Cursor::posRight()
441 {
442         if (pos() == lastpos())
443                 return false;
444         ++pos();
445         return true;
446 }
447
448
449 CursorSlice Cursor::anchor() const
450 {
451         BOOST_ASSERT(anchor_.depth() >= depth());
452         CursorSlice normal = anchor_[depth() - 1];
453         if (depth() < anchor_.depth() && top() <= normal) {
454                 // anchor is behind cursor -> move anchor behind the inset
455                 ++normal.pos();
456         }
457         return normal;
458 }
459
460
461 CursorSlice Cursor::selBegin() const
462 {
463         if (!selection())
464                 return top();
465         return anchor() < top() ? anchor() : top();
466 }
467
468
469 CursorSlice Cursor::selEnd() const
470 {
471         if (!selection())
472                 return top();
473         return anchor() > top() ? anchor() : top();
474 }
475
476
477 DocIterator Cursor::selectionBegin() const
478 {
479         if (!selection())
480                 return *this;
481         DocIterator di = (anchor() < top() ? anchor_ : *this);
482         di.resize(depth());
483         return di;
484 }
485
486
487 DocIterator Cursor::selectionEnd() const
488 {
489         if (!selection())
490                 return *this;
491         DocIterator di = (anchor() > top() ? anchor_ : *this);
492         if (di.depth() > depth()) {
493                 di.resize(depth());
494                 ++di.pos();
495         }
496         return di;
497 }
498
499
500 void Cursor::setSelection()
501 {
502         selection() = true;
503         // A selection with no contents is not a selection
504 #ifdef WITH_WARNINGS
505 #warning doesnt look ok
506 #endif
507         if (pit() == anchor().pit() && pos() == anchor().pos())
508                 selection() = false;
509 }
510
511
512 void Cursor::setSelection(DocIterator const & where, int n)
513 {
514         setCursor(where);
515         selection() = true;
516         anchor_ = where;
517         pos() += n;
518 }
519
520
521 void Cursor::clearSelection()
522 {
523         selection() = false;
524         mark() = false;
525         resetAnchor();
526 }
527
528
529 int & Cursor::x_target()
530 {
531         return x_target_;
532 }
533
534
535 int Cursor::x_target() const
536 {
537         return x_target_;
538 }
539
540
541 void Cursor::clearTargetX()
542 {
543         x_target_ = -1;
544 }
545
546
547
548 void Cursor::info(odocstream & os) const
549 {
550         for (int i = 1, n = depth(); i < n; ++i) {
551                 operator[](i).inset().infoize(os);
552                 os << "  ";
553         }
554         if (pos() != 0) {
555                 Inset const * inset = prevInset();
556                 // prevInset() can return 0 in certain case.
557                 if (inset)
558                         prevInset()->infoize2(os);
559         }
560         // overwite old message
561         os << "                    ";
562 }
563
564
565 bool Cursor::selHandle(bool sel)
566 {
567         //lyxerr << "Cursor::selHandle" << endl;
568         if (sel == selection())
569                 return false;
570
571         resetAnchor();
572         selection() = sel;
573         cap::saveSelection(*this);
574         return true;
575 }
576
577
578 std::ostream & operator<<(std::ostream & os, Cursor const & cur)
579 {
580         os << "\n cursor:                                | anchor:\n";
581         for (size_t i = 0, n = cur.depth(); i != n; ++i) {
582                 os << " " << cur[i] << " | ";
583                 if (i < cur.anchor_.depth())
584                         os << cur.anchor_[i];
585                 else
586                         os << "-------------------------------";
587                 os << "\n";
588         }
589         for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
590                 os << "------------------------------- | " << cur.anchor_[i] << "\n";
591         }
592         os << " selection: " << cur.selection_
593            << " x_target: " << cur.x_target_ << endl;
594         return os;
595 }
596
597 } // namespace lyx
598
599
600 ///////////////////////////////////////////////////////////////////
601 //
602 // The part below is the non-integrated rest of the original math
603 // cursor. This should be either generalized for texted or moved
604 // back to mathed (in most cases to InsetMathNest).
605 //
606 ///////////////////////////////////////////////////////////////////
607
608 #include "mathed/InsetMathChar.h"
609 #include "mathed/InsetMathGrid.h"
610 #include "mathed/InsetMathScript.h"
611 #include "mathed/InsetMathUnknown.h"
612 #include "mathed/MathFactory.h"
613 #include "mathed/MathStream.h"
614 #include "mathed/MathSupport.h"
615
616
617 namespace lyx {
618
619 //#define FILEDEBUG 1
620
621
622 bool Cursor::isInside(Inset const * p)
623 {
624         for (size_t i = 0; i != depth(); ++i)
625                 if (&operator[](i).inset() == p)
626                         return true;
627         return false;
628 }
629
630
631 void Cursor::leaveInset(Inset const & inset)
632 {
633         for (size_t i = 0; i != depth(); ++i) {
634                 if (&operator[](i).inset() == &inset) {
635                         resize(i);
636                         return;
637                 }
638         }
639 }
640
641
642 bool Cursor::openable(MathAtom const & t) const
643 {
644         if (!t->isActive())
645                 return false;
646
647         if (t->lock())
648                 return false;
649
650         if (!selection())
651                 return true;
652
653         // we can't move into anything new during selection
654         if (depth() >= anchor_.depth())
655                 return false;
656         if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
657                 return false;
658
659         return true;
660 }
661
662
663 void Cursor::setScreenPos(int x, int y)
664 {
665         x_target() = x;
666         bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
667 }
668
669
670
671 void Cursor::plainErase()
672 {
673         cell().erase(pos());
674 }
675
676
677 void Cursor::markInsert()
678 {
679         insert(char_type(0));
680 }
681
682
683 void Cursor::markErase()
684 {
685         cell().erase(pos());
686 }
687
688
689 void Cursor::plainInsert(MathAtom const & t)
690 {
691         cell().insert(pos(), t);
692         ++pos();
693 }
694
695
696 void Cursor::insert(docstring const & str)
697 {
698         for_each(str.begin(), str.end(),
699                  boost::bind(static_cast<void(Cursor::*)(char_type)>
700                              (&Cursor::insert), this, _1));
701 }
702
703
704 void Cursor::insert(char_type c)
705 {
706         //lyxerr << "Cursor::insert char '" << c << "'" << endl;
707         BOOST_ASSERT(!empty());
708         if (inMathed()) {
709                 cap::selClearOrDel(*this);
710                 insert(new InsetMathChar(c));
711         } else {
712                 text()->insertChar(*this, c);
713         }
714 }
715
716
717 void Cursor::insert(MathAtom const & t)
718 {
719         //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
720         macroModeClose();
721         cap::selClearOrDel(*this);
722         plainInsert(t);
723 }
724
725
726 void Cursor::insert(Inset * inset)
727 {
728         if (inMathed())
729                 insert(MathAtom(inset));
730         else
731                 text()->insertInset(*this, inset);
732 }
733
734
735 void Cursor::niceInsert(docstring const & t)
736 {
737         MathData ar;
738         asArray(t, ar);
739         if (ar.size() == 1)
740                 niceInsert(ar[0]);
741         else
742                 insert(ar);
743 }
744
745
746 void Cursor::niceInsert(MathAtom const & t)
747 {
748         macroModeClose();
749         docstring const safe = cap::grabAndEraseSelection(*this);
750         plainInsert(t);
751         // enter the new inset and move the contents of the selection if possible
752         if (t->isActive()) {
753                 posLeft();
754                 // be careful here: don't use 'pushLeft(t)' as this we need to
755                 // push the clone, not the original
756                 pushLeft(*nextInset());
757                 // We may not use niceInsert here (recursion)
758                 MathData ar;
759                 asArray(safe, ar);
760                 insert(ar);
761         }
762 }
763
764
765 void Cursor::insert(MathData const & ar)
766 {
767         macroModeClose();
768         if (selection())
769                 cap::eraseSelection(*this);
770         cell().insert(pos(), ar);
771         pos() += ar.size();
772 }
773
774
775 bool Cursor::backspace()
776 {
777         autocorrect() = false;
778
779         if (selection()) {
780                 cap::eraseSelection(*this);
781                 return true;
782         }
783
784         if (pos() == 0) {
785                 // If empty cell, and not part of a big cell
786                 if (lastpos() == 0 && inset().nargs() == 1) {
787                         popLeft();
788                         // Directly delete empty cell: [|[]] => [|] 
789                         if (inMathed()) {
790                                 plainErase();
791                                 resetAnchor();
792                                 return true;
793                         }
794                         // [|], can not delete from inside
795                         return false;
796                 } else {
797                         if (inMathed())
798                                 pullArg();
799                         else
800                                 popLeft();
801                         return true;
802                 }
803         }
804
805         if (inMacroMode()) {
806                 InsetMathUnknown * p = activeMacro();
807                 if (p->name().size() > 1) {
808                         p->setName(p->name().substr(0, p->name().size() - 1));
809                         return true;
810                 }
811         }
812
813         if (pos() != 0 && prevAtom()->nargs() > 0) {
814                 // let's require two backspaces for 'big stuff' and
815                 // highlight on the first
816                 resetAnchor();
817                 selection() = true;
818                 --pos();
819         } else {
820                 --pos();
821                 plainErase();
822         }
823         return true;
824 }
825
826
827 bool Cursor::erase()
828 {
829         autocorrect() = false;
830         if (inMacroMode())
831                 return true;
832
833         if (selection()) {
834                 cap::eraseSelection(*this);
835                 return true;
836         }
837
838         // delete empty cells if possible
839         if (pos() == lastpos() && inset().idxDelete(idx()))
840                 return true;
841
842         // special behaviour when in last position of cell
843         if (pos() == lastpos()) {
844                 bool one_cell = inset().nargs() == 1;
845                 if (one_cell && lastpos() == 0) {
846                         popLeft();
847                         // Directly delete empty cell: [|[]] => [|] 
848                         if (inMathed()) {
849                                 plainErase();
850                                 resetAnchor();
851                                 return true;
852                         }
853                         // [|], can not delete from inside
854                         return false;
855                 }
856                 // remove markup
857                 if (!one_cell)
858                         inset().idxGlue(idx());
859                 return true;
860         }
861
862         // 'clever' UI hack: only erase large items if previously slected
863         if (pos() != lastpos() && nextAtom()->nargs() > 0) {
864                 resetAnchor();
865                 selection() = true;
866                 ++pos();
867         } else {
868                 plainErase();
869         }
870
871         return true;
872 }
873
874
875 bool Cursor::up()
876 {
877         macroModeClose();
878         DocIterator save = *this;
879         if (goUpDown(true))
880                 return true;
881         setCursor(save);
882         autocorrect() = false;
883         return selection();
884 }
885
886
887 bool Cursor::down()
888 {
889         macroModeClose();
890         DocIterator save = *this;
891         if (goUpDown(false))
892                 return true;
893         setCursor(save);
894         autocorrect() = false;
895         return selection();
896 }
897
898
899 bool Cursor::macroModeClose()
900 {
901         if (!inMacroMode())
902                 return false;
903         InsetMathUnknown * p = activeMacro();
904         p->finalize();
905         docstring const s = p->name();
906         --pos();
907         cell().erase(pos());
908
909         // do nothing if the macro name is empty
910         if (s == "\\")
911                 return false;
912
913         // trigger updates of macros, at least, if no full
914         // updates take place anyway
915         updateFlags(Update::Force);
916
917         docstring const name = s.substr(1);
918         InsetMathNest * const in = inset().asInsetMath()->asNestInset();
919         if (in && in->interpretString(*this, s))
920                 return true;
921         plainInsert(createInsetMath(name));
922         return true;
923 }
924
925
926 docstring Cursor::macroName()
927 {
928         return inMacroMode() ? activeMacro()->name() : docstring();
929 }
930
931
932 void Cursor::handleNest(MathAtom const & a, int c)
933 {
934         //lyxerr << "Cursor::handleNest: " << c << endl;
935         MathAtom t = a;
936         asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
937         insert(t);
938         posLeft();
939         pushLeft(*nextInset());
940 }
941
942
943 int Cursor::targetX() const
944 {
945         if (x_target() != -1)
946                 return x_target();
947         int x = 0;
948         int y = 0;
949         getPos(x, y);
950         return x;
951 }
952
953
954 void Cursor::setTargetX()
955 {
956         int x;
957         int y;
958         getPos(x, y);
959         x_target_ = x;
960 }
961
962
963 bool Cursor::inMacroMode() const
964 {
965         if (pos() == 0)
966                 return false;
967         InsetMathUnknown const * p = prevAtom()->asUnknownInset();
968         return p && !p->final();
969 }
970
971
972 InsetMathUnknown * Cursor::activeMacro()
973 {
974         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
975 }
976
977
978 void Cursor::pullArg()
979 {
980 #ifdef WITH_WARNINGS
981 #warning Look here
982 #endif
983         MathData ar = cell();
984         if (popLeft() && inMathed()) {
985                 plainErase();
986                 cell().insert(pos(), ar);
987                 resetAnchor();
988         } else {
989                 //formula()->mutateToText();
990         }
991 }
992
993
994 void Cursor::touch()
995 {
996 #ifdef WITH_WARNINGS
997 #warning look here
998 #endif
999 #if 0
1000         DocIterator::const_iterator it = begin();
1001         DocIterator::const_iterator et = end();
1002         for ( ; it != et; ++it)
1003                 it->cell().touch();
1004 #endif
1005 }
1006
1007
1008 void Cursor::normalize()
1009 {
1010         if (idx() > lastidx()) {
1011                 lyxerr << "this should not really happen - 1: "
1012                        << idx() << ' ' << nargs()
1013                        << " in: " << &inset() << endl;
1014                 idx() = lastidx();
1015         }
1016
1017         if (pos() > lastpos()) {
1018                 lyxerr << "this should not really happen - 2: "
1019                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
1020                        << " in atom: '";
1021                 odocstringstream os;
1022                 WriteStream wi(os, false, true);
1023                 inset().asInsetMath()->write(wi);
1024                 lyxerr << to_utf8(os.str()) << endl;
1025                 pos() = lastpos();
1026         }
1027 }
1028
1029
1030 bool Cursor::goUpDown(bool up)
1031 {
1032         // Be warned: The 'logic' implemented in this function is highly
1033         // fragile. A distance of one pixel or a '<' vs '<=' _really
1034         // matters. So fiddle around with it only if you think you know
1035         // what you are doing!
1036
1037         int xo = 0;
1038         int yo = 0;
1039         getPos(xo, yo);
1040
1041         // check if we had something else in mind, if not, this is the future
1042         // target
1043         if (x_target() == -1)
1044                 x_target() = xo;
1045         else
1046                 xo = x_target();
1047
1048         // try neigbouring script insets
1049         if (!selection()) {
1050                 // try left
1051                 if (pos() != 0) {
1052                         InsetMathScript const * p = prevAtom()->asScriptInset();
1053                         if (p && p->has(up)) {
1054                                 --pos();
1055                                 push(*const_cast<InsetMathScript*>(p));
1056                                 idx() = p->idxOfScript(up);
1057                                 pos() = lastpos();
1058                                 return true;
1059                         }
1060                 }
1061
1062                 // try right
1063                 if (pos() != lastpos()) {
1064                         InsetMathScript const * p = nextAtom()->asScriptInset();
1065                         if (p && p->has(up)) {
1066                                 push(*const_cast<InsetMathScript*>(p));
1067                                 idx() = p->idxOfScript(up);
1068                                 pos() = 0;
1069                                 return true;
1070                         }
1071                 }
1072         }
1073
1074 // FIXME: Switch this on for more robust movement
1075 #if 0
1076
1077         return bruteFind3(*this, xo, yo, up);
1078
1079 #else
1080         //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1081         //if (up)
1082         //      yhigh = yo - 4;
1083         //else
1084         //      ylow = yo + 4;
1085         //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
1086         //      lyxerr << "updown: handled by brute find in the same cell" << endl;
1087         //      return true;
1088         //}
1089
1090         // try to find an inset that knows better then we
1091         while (true) {
1092                 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1093                 // ask inset first
1094                 if (inset().idxUpDown(*this, up)) {
1095                         //lyxerr << "idxUpDown triggered" << endl;
1096                         // try to find best position within this inset
1097                         if (!selection())
1098                                 setCursor(bruteFind2(*this, xo, yo));
1099                         return true;
1100                 }
1101
1102                 // no such inset found, just take something "above"
1103                 if (!popLeft()) {
1104                         //lyxerr << "updown: popleft failed (strange case)" << endl;
1105                         int ylow  = up ? 0 : yo + 1;
1106                         int yhigh = up ? yo - 1 : bv().workHeight();
1107                         return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
1108                 }
1109
1110                 // any improvement so far?
1111                 //lyxerr << "updown: popLeft succeeded" << endl;
1112                 int xnew;
1113                 int ynew;
1114                 getPos(xnew, ynew);
1115                 if (up ? ynew < yo : ynew > yo)
1116                         return true;
1117         }
1118
1119         // we should not come here.
1120         BOOST_ASSERT(false);
1121 #endif
1122 }
1123
1124
1125 void Cursor::handleFont(string const & font)
1126 {
1127         LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << ": " << font << endl;
1128         docstring safe;
1129         if (selection()) {
1130                 macroModeClose();
1131                 safe = cap::grabAndEraseSelection(*this);
1132         }
1133
1134         if (lastpos() != 0) {
1135                 // something left in the cell
1136                 if (pos() == 0) {
1137                         // cursor in first position
1138                         popLeft();
1139                 } else if (pos() == lastpos()) {
1140                         // cursor in last position
1141                         popRight();
1142                 } else {
1143                         // cursor in between. split cell
1144                         MathData::iterator bt = cell().begin();
1145                         MathAtom at = createInsetMath(from_utf8(font));
1146                         at.nucleus()->cell(0) = MathData(bt, bt + pos());
1147                         cell().erase(bt, bt + pos());
1148                         popLeft();
1149                         plainInsert(at);
1150                 }
1151         } else {
1152                 // nothing left in the cell
1153                 pullArg();
1154                 plainErase();
1155         }
1156         insert(safe);
1157 }
1158
1159
1160 void Cursor::message(docstring const & msg) const
1161 {
1162         theLyXFunc().setMessage(msg);
1163 }
1164
1165
1166 void Cursor::errorMessage(docstring const & msg) const
1167 {
1168         theLyXFunc().setErrorMessage(msg);
1169 }
1170
1171
1172 docstring Cursor::selectionAsString(bool label) const
1173 {
1174         if (!selection())
1175                 return docstring();
1176
1177         if (inTexted()) {
1178                 Buffer const & buffer = *bv().buffer();
1179                 ParagraphList const & pars = text()->paragraphs();
1180
1181                 // should be const ...
1182                 pit_type startpit = selBegin().pit();
1183                 pit_type endpit = selEnd().pit();
1184                 size_t const startpos = selBegin().pos();
1185                 size_t const endpos = selEnd().pos();
1186
1187                 if (startpit == endpit)
1188                         return pars[startpit].asString(buffer, startpos, endpos, label);
1189
1190                 // First paragraph in selection
1191                 docstring result = pars[startpit].
1192                         asString(buffer, startpos, pars[startpit].size(), label)
1193                                  + parbreak(pars[startpit]);
1194
1195                 // The paragraphs in between (if any)
1196                 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1197                         Paragraph const & par = pars[pit];
1198                         result += par.asString(buffer, 0, par.size(), label)
1199                                   + parbreak(pars[pit]);
1200                 }
1201
1202                 // Last paragraph in selection
1203                 result += pars[endpit].asString(buffer, 0, endpos, label);
1204
1205                 return result;
1206         }
1207
1208         if (inMathed())
1209                 return cap::grabSelection(*this);
1210
1211         return docstring();
1212 }
1213
1214
1215 docstring Cursor::currentState()
1216 {
1217         if (inMathed()) {
1218                 odocstringstream os;
1219                 info(os);
1220                 return os.str();
1221         }
1222
1223         if (inTexted())
1224                 return text()->currentState(*this);
1225
1226         return docstring();
1227 }
1228
1229
1230 docstring Cursor::getPossibleLabel()
1231 {
1232         return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
1233 }
1234
1235
1236 Encoding const * Cursor::getEncoding() const
1237 {
1238         if (empty())
1239                 return 0;
1240         if (!bv().buffer())
1241                 return 0;
1242         int s = 0;
1243         // go up until first non-0 text is hit
1244         // (innermost text is 0 in mathed)
1245         for (s = depth() - 1; s >= 0; --s)
1246                 if (operator[](s).text())
1247                         break;
1248         CursorSlice const & sl = operator[](s);
1249         Text const & text = *sl.text();
1250         Font font = text.getPar(sl.pit()).getFont(
1251                 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1252         return font.language()->encoding();
1253 }
1254
1255
1256 void Cursor::undispatched()
1257 {
1258         disp_.dispatched(false);
1259 }
1260
1261
1262 void Cursor::dispatched()
1263 {
1264         disp_.dispatched(true);
1265 }
1266
1267
1268 void Cursor::updateFlags(Update::flags f)
1269 {
1270         disp_.update(f);
1271 }
1272
1273
1274 void Cursor::noUpdate()
1275 {
1276         disp_.update(Update::None);
1277 }
1278
1279
1280 Font Cursor::getFont() const
1281 {
1282         // HACK. far from being perfect...
1283         int s = 0;
1284         // go up until first non-0 text is hit
1285         // (innermost text is 0 in mathed)
1286         for (s = depth() - 1; s >= 0; --s)
1287                 if (operator[](s).text())
1288                         break;
1289         CursorSlice const & sl = operator[](s);
1290         Text const & text = *sl.text();
1291         Font font = text.getPar(sl.pit()).getFont(
1292                 bv().buffer()->params(),
1293                 sl.pos(),
1294                 outerFont(sl.pit(), text.paragraphs()));
1295
1296         return font;
1297 }
1298
1299
1300 void Cursor::fixIfBroken()
1301 {
1302         // find out last good level
1303         Cursor copy = *this;
1304         size_t newdepth = depth();
1305         while (!copy.empty()) {
1306                 if (copy.idx() > copy.lastidx()) {
1307                         lyxerr << "wrong idx " << copy.idx()
1308                                << ", max is " << copy.lastidx()
1309                                << " at level " << copy.depth()
1310                                << ". Trying to correct this."  << endl;
1311                         lyxerr << "old: " << *this << endl;
1312                         newdepth = copy.depth() - 1;
1313                 }
1314                 else if (copy.pit() > copy.lastpit()) {
1315                         lyxerr << "wrong pit " << copy.pit()
1316                                << ", max is " << copy.lastpit()
1317                                << " at level " << copy.depth()
1318                                << ". Trying to correct this."  << endl;
1319                         lyxerr << "old: " << *this << endl;
1320                         newdepth = copy.depth() - 1;
1321                 }
1322                 else if (copy.pos() > copy.lastpos()) {
1323                         lyxerr << "wrong pos " << copy.pos()
1324                                << ", max is " << copy.lastpos()
1325                                << " at level " << copy.depth()
1326                                << ". Trying to correct this."  << endl;
1327                         lyxerr << "old: " << *this << endl;
1328                         newdepth = copy.depth() - 1;
1329                 }
1330                 copy.pop();
1331         }
1332         // shrink cursor to a size where everything is valid, possibly
1333         // leaving insets
1334         while (depth() > newdepth) {
1335                 pop();
1336                 lyxerr << "correcting cursor to level " << depth() << endl;
1337                 lyxerr << "new: " << *this << endl;
1338                 clearSelection();
1339         }
1340 }
1341
1342
1343 } // namespace lyx