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