]> git.lyx.org Git - lyx.git/blob - src/cursor.C
more cleanup:
[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 "buffer.h"
17 #include "cursor.h"
18 #include "coordcache.h"
19 #include "CutAndPaste.h"
20 #include "debug.h"
21 #include "dispatchresult.h"
22 #include "encoding.h"
23 #include "funcrequest.h"
24 #include "language.h"
25 #include "lfuns.h"
26 #include "lyxfont.h"
27 #include "lyxfunc.h" // only for setMessage()
28 #include "lyxrc.h"
29 #include "lyxrow.h"
30 #include "lyxtext.h"
31 #include "paragraph.h"
32 #include "paragraph_funcs.h"
33 #include "pariterator.h"
34
35 #include "insets/insettabular.h"
36 #include "insets/insettext.h"
37
38 #include "mathed/MathData.h"
39 #include "mathed/InsetMath.h"
40 #include "mathed/InsetMathScript.h"
41 #include "mathed/MathMacroTable.h"
42 #include "mathed/MathParser.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         inset().notifyCursorLeaves(*this);
379         if (depth() == 1)
380                 return false;
381         pop();
382         ++pos();
383         return true;
384 }
385
386
387 int LCursor::currentMode()
388 {
389         BOOST_ASSERT(!empty());
390         for (int i = depth() - 1; i >= 0; --i) {
391                 int res = operator[](i).inset().currentMode();
392                 if (res != InsetBase::UNDECIDED_MODE)
393                         return res;
394         }
395         return InsetBase::TEXT_MODE;
396 }
397
398
399 void LCursor::getPos(int & x, int & y) const
400 {
401         Point p = bv_funcs::getPos(bv(), *this, boundary());
402         x = p.x_;
403         y = p.y_;
404 }
405
406
407 void LCursor::resetAnchor()
408 {
409         anchor_ = *this;
410 }
411
412
413
414 bool LCursor::posLeft()
415 {
416         if (pos() == 0)
417                 return false;
418         --pos();
419         return true;
420 }
421
422
423 bool LCursor::posRight()
424 {
425         if (pos() == lastpos())
426                 return false;
427         ++pos();
428         return true;
429 }
430
431
432 CursorSlice LCursor::anchor() const
433 {
434         BOOST_ASSERT(anchor_.depth() >= depth());
435         CursorSlice normal = anchor_[depth() - 1];
436         if (depth() < anchor_.depth() && top() <= normal) {
437                 // anchor is behind cursor -> move anchor behind the inset
438                 ++normal.pos();
439         }
440         return normal;
441 }
442
443
444 CursorSlice LCursor::selBegin() const
445 {
446         if (!selection())
447                 return top();
448         return anchor() < top() ? anchor() : top();
449 }
450
451
452 CursorSlice LCursor::selEnd() const
453 {
454         if (!selection())
455                 return top();
456         return anchor() > top() ? anchor() : top();
457 }
458
459
460 DocIterator LCursor::selectionBegin() const
461 {
462         if (!selection())
463                 return *this;
464         DocIterator di = (anchor() < top() ? anchor_ : *this);
465         di.resize(depth());
466         return di;
467 }
468
469
470 DocIterator LCursor::selectionEnd() const
471 {
472         if (!selection())
473                 return *this;
474         DocIterator di = (anchor() > top() ? anchor_ : *this);
475         if (di.depth() > depth()) {
476                 di.resize(depth());
477                 ++di.pos();
478         }
479         return di;
480 }
481
482
483 void LCursor::setSelection()
484 {
485         selection() = true;
486         // A selection with no contents is not a selection
487 #ifdef WITH_WARNINGS
488 #warning doesnt look ok
489 #endif
490         if (pit() == anchor().pit() && pos() == anchor().pos())
491                 selection() = false;
492 }
493
494
495 void LCursor::setSelection(DocIterator const & where, int n)
496 {
497         setCursor(where);
498         selection() = true;
499         anchor_ = where;
500         pos() += n;
501 }
502
503
504 void LCursor::clearSelection()
505 {
506         selection() = false;
507         mark() = false;
508         resetAnchor();
509 }
510
511
512 int & LCursor::x_target()
513 {
514         return x_target_;
515 }
516
517
518 int LCursor::x_target() const
519 {
520         return x_target_;
521 }
522
523
524 void LCursor::clearTargetX()
525 {
526         x_target_ = -1;
527 }
528
529
530
531 void LCursor::info(odocstream & os) const
532 {
533         for (int i = 1, n = depth(); i < n; ++i) {
534                 operator[](i).inset().infoize(os);
535                 os << "  ";
536         }
537         if (pos() != 0)
538                 prevInset()->infoize2(os);
539         // overwite old message
540         os << "                    ";
541 }
542
543
544 bool LCursor::selHandle(bool sel)
545 {
546         //lyxerr << "LCursor::selHandle" << endl;
547         if (sel == selection())
548                 return false;
549
550         resetAnchor();
551         selection() = sel;
552         return true;
553 }
554
555
556 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
557 {
558         os << "\n cursor:                                | anchor:\n";
559         for (size_t i = 0, n = cur.depth(); i != n; ++i) {
560                 os << " " << cur[i] << " | ";
561                 if (i < cur.anchor_.depth())
562                         os << cur.anchor_[i];
563                 else
564                         os << "-------------------------------";
565                 os << "\n";
566         }
567         for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
568                 os << "------------------------------- | " << cur.anchor_[i] << "\n";
569         }
570         os << " selection: " << cur.selection_
571            << " x_target: " << cur.x_target_ << endl;
572         return os;
573 }
574
575 } // namespace lyx
576
577
578 ///////////////////////////////////////////////////////////////////
579 //
580 // The part below is the non-integrated rest of the original math
581 // cursor. This should be either generalized for texted or moved
582 // back to mathed (in most cases to InsetMathNest).
583 //
584 ///////////////////////////////////////////////////////////////////
585
586 #include "mathed/InsetMathChar.h"
587 #include "mathed/InsetMathGrid.h"
588 #include "mathed/InsetMathScript.h"
589 #include "mathed/InsetMathUnknown.h"
590 #include "mathed/MathFactory.h"
591 #include "mathed/MathMacroArgument.h"
592 #include "mathed/MathStream.h"
593 #include "mathed/MathSupport.h"
594
595
596 namespace lyx {
597
598 //#define FILEDEBUG 1
599
600
601 bool LCursor::isInside(InsetBase const * p)
602 {
603         for (size_t i = 0; i != depth(); ++i)
604                 if (&operator[](i).inset() == p)
605                         return true;
606         return false;
607 }
608
609
610 void LCursor::leaveInset(InsetBase const & inset)
611 {
612         for (size_t i = 0; i != depth(); ++i) {
613                 if (&operator[](i).inset() == &inset) {
614                         resize(i);
615                         return;
616                 }
617         }
618 }
619
620
621 bool LCursor::openable(MathAtom const & t) const
622 {
623         if (!t->isActive())
624                 return false;
625
626         if (t->lock())
627                 return false;
628
629         if (!selection())
630                 return true;
631
632         // we can't move into anything new during selection
633         if (depth() >= anchor_.depth())
634                 return false;
635         if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
636                 return false;
637
638         return true;
639 }
640
641
642 void LCursor::setScreenPos(int x, int y)
643 {
644         x_target() = x;
645         bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
646 }
647
648
649
650 void LCursor::plainErase()
651 {
652         cell().erase(pos());
653 }
654
655
656 void LCursor::markInsert()
657 {
658         insert(char_type(0));
659 }
660
661
662 void LCursor::markErase()
663 {
664         cell().erase(pos());
665 }
666
667
668 void LCursor::plainInsert(MathAtom const & t)
669 {
670         cell().insert(pos(), t);
671         ++pos();
672 }
673
674
675 void LCursor::insert(docstring const & str)
676 {
677         for_each(str.begin(), str.end(),
678                  boost::bind(static_cast<void(LCursor::*)(char_type)>
679                              (&LCursor::insert), this, _1));
680 }
681
682
683 void LCursor::insert(char_type c)
684 {
685         //lyxerr << "LCursor::insert char '" << c << "'" << endl;
686         BOOST_ASSERT(!empty());
687         if (inMathed()) {
688                 cap::selClearOrDel(*this);
689                 insert(new InsetMathChar(c));
690         } else {
691                 text()->insertChar(*this, c);
692         }
693 }
694
695
696 void LCursor::insert(MathAtom const & t)
697 {
698         //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
699         macroModeClose();
700         cap::selClearOrDel(*this);
701         plainInsert(t);
702 }
703
704
705 void LCursor::insert(InsetBase * inset)
706 {
707         if (inMathed())
708                 insert(MathAtom(inset));
709         else
710                 text()->insertInset(*this, inset);
711 }
712
713
714 void LCursor::niceInsert(docstring const & t)
715 {
716         MathArray ar;
717         asArray(t, ar);
718         if (ar.size() == 1)
719                 niceInsert(ar[0]);
720         else
721                 insert(ar);
722 }
723
724
725 void LCursor::niceInsert(MathAtom const & t)
726 {
727         macroModeClose();
728         docstring const safe = cap::grabAndEraseSelection(*this);
729         plainInsert(t);
730         // enter the new inset and move the contents of the selection if possible
731         if (t->isActive()) {
732                 posLeft();
733                 // be careful here: don't use 'pushLeft(t)' as this we need to
734                 // push the clone, not the original
735                 pushLeft(*nextInset());
736                 // We may not use niceInsert here (recursion)
737                 MathArray ar;
738                 asArray(safe, ar);
739                 insert(ar);
740         }
741 }
742
743
744 void LCursor::insert(MathArray const & ar)
745 {
746         macroModeClose();
747         if (selection())
748                 cap::eraseSelection(*this);
749         cell().insert(pos(), ar);
750         pos() += ar.size();
751 }
752
753
754 bool LCursor::backspace()
755 {
756         autocorrect() = false;
757
758         if (selection()) {
759                 cap::selDel(*this);
760                 return true;
761         }
762
763         if (pos() == 0) {
764                 // If empty cell, and not part of a big cell
765                 if (lastpos() == 0 && inset().nargs() == 1) {
766                         popLeft();
767                         // Directly delete empty cell: [|[]] => [|] 
768                         if (inMathed()) {
769                                 plainErase();
770                                 resetAnchor();
771                                 return true;
772                         }
773                         // [|], can not delete from inside
774                         return false;
775                 } else {
776                         // move to left
777                         popLeft();
778                         return true;
779                 }
780         }
781
782         if (inMacroMode()) {
783                 InsetMathUnknown * p = activeMacro();
784                 if (p->name().size() > 1) {
785                         p->setName(p->name().substr(0, p->name().size() - 1));
786                         return true;
787                 }
788         }
789
790         if (pos() != 0 && prevAtom()->nargs() > 0) {
791                 // let's require two backspaces for 'big stuff' and
792                 // highlight on the first
793                 resetAnchor();
794                 selection() = true;
795                 --pos();
796         } else {
797                 --pos();
798                 plainErase();
799         }
800         return true;
801 }
802
803
804 bool LCursor::erase()
805 {
806         autocorrect() = false;
807         if (inMacroMode())
808                 return true;
809
810         if (selection()) {
811                 cap::selDel(*this);
812                 return true;
813         }
814
815         // delete empty cells if possible
816         if (pos() == lastpos() && inset().idxDelete(idx()))
817                 return true;
818
819         // special behaviour when in last position of cell
820         if (pos() == lastpos()) {
821                 bool one_cell = inset().nargs() == 1;
822                 if (one_cell && lastpos() == 0) {
823                         popLeft();
824                         // Directly delete empty cell: [|[]] => [|] 
825                         if (inMathed()) {
826                                 plainErase();
827                                 resetAnchor();
828                                 return true;
829                         }
830                         // [|], can not delete from inside
831                         return false;
832                 }
833                 // remove markup
834                 if (!one_cell)
835                         inset().idxGlue(idx());
836                 return true;
837         }
838
839         // 'clever' UI hack: only erase large items if previously slected
840         if (pos() != lastpos() && nextAtom()->nargs() > 0) {
841                 resetAnchor();
842                 selection() = true;
843                 ++pos();
844         } else {
845                 plainErase();
846         }
847
848         return true;
849 }
850
851
852 bool LCursor::up()
853 {
854         macroModeClose();
855         DocIterator save = *this;
856         if (goUpDown(true))
857                 return true;
858         setCursor(save);
859         autocorrect() = false;
860         return selection();
861 }
862
863
864 bool LCursor::down()
865 {
866         macroModeClose();
867         DocIterator save = *this;
868         if (goUpDown(false))
869                 return true;
870         setCursor(save);
871         autocorrect() = false;
872         return selection();
873 }
874
875
876 bool LCursor::macroModeClose()
877 {
878         if (!inMacroMode())
879                 return false;
880         InsetMathUnknown * p = activeMacro();
881         p->finalize();
882         docstring const s = p->name();
883         --pos();
884         cell().erase(pos());
885
886         // do nothing if the macro name is empty
887         if (s == "\\")
888                 return false;
889
890         // prevent entering of recursive macros
891         // FIXME: this is only a weak attempt... only prevents immediate
892         // recursion
893         docstring const name = s.substr(1);
894         InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
895         if (macro && macro->getInsetName() == name)
896                 lyxerr << "can't enter recursive macro" << endl;
897
898         InsetMathNest * const in = inset().asInsetMath()->asNestInset();
899         if (in && in->interpretString(*this, s))
900                 return true;
901         plainInsert(createInsetMath(name));
902         return true;
903 }
904
905
906 docstring LCursor::macroName()
907 {
908         return inMacroMode() ? activeMacro()->name() : docstring();
909 }
910
911
912 void LCursor::handleNest(MathAtom const & a, int c)
913 {
914         //lyxerr << "LCursor::handleNest: " << c << endl;
915         MathAtom t = a;
916         asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
917         insert(t);
918         posLeft();
919         pushLeft(*nextInset());
920 }
921
922
923 int LCursor::targetX() const
924 {
925         if (x_target() != -1)
926                 return x_target();
927         int x = 0;
928         int y = 0;
929         getPos(x, y);
930         return x;
931 }
932
933
934 void LCursor::setTargetX()
935 {
936         int x;
937         int y;
938         getPos(x, y);
939         x_target_ = x;
940 }
941
942
943 bool LCursor::inMacroMode() const
944 {
945         if (pos() == 0)
946                 return false;
947         InsetMathUnknown const * p = prevAtom()->asUnknownInset();
948         return p && !p->final();
949 }
950
951
952 InsetMathUnknown * LCursor::activeMacro()
953 {
954         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
955 }
956
957
958 void LCursor::pullArg()
959 {
960 #ifdef WITH_WARNINGS
961 #warning Look here
962 #endif
963         MathArray ar = cell();
964         if (popLeft() && inMathed()) {
965                 plainErase();
966                 cell().insert(pos(), ar);
967                 resetAnchor();
968         } else {
969                 //formula()->mutateToText();
970         }
971 }
972
973
974 void LCursor::touch()
975 {
976 #ifdef WITH_WARNINGS
977 #warning look here
978 #endif
979 #if 0
980         DocIterator::const_iterator it = begin();
981         DocIterator::const_iterator et = end();
982         for ( ; it != et; ++it)
983                 it->cell().touch();
984 #endif
985 }
986
987
988 void LCursor::normalize()
989 {
990         if (idx() > lastidx()) {
991                 lyxerr << "this should not really happen - 1: "
992                        << idx() << ' ' << nargs()
993                        << " in: " << &inset() << endl;
994                 idx() = lastidx();
995         }
996
997         if (pos() > lastpos()) {
998                 lyxerr << "this should not really happen - 2: "
999                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
1000                        << " in atom: '";
1001                 odocstringstream os;
1002                 WriteStream wi(os, false, true);
1003                 inset().asInsetMath()->write(wi);
1004                 lyxerr << to_utf8(os.str()) << endl;
1005                 pos() = lastpos();
1006         }
1007 }
1008
1009
1010 bool LCursor::goUpDown(bool up)
1011 {
1012         // Be warned: The 'logic' implemented in this function is highly
1013         // fragile. A distance of one pixel or a '<' vs '<=' _really
1014         // matters. So fiddle around with it only if you think you know
1015         // what you are doing!
1016
1017         int xo = 0;
1018         int yo = 0;
1019         getPos(xo, yo);
1020
1021         // check if we had something else in mind, if not, this is the future
1022         // target
1023         if (x_target() == -1)
1024                 x_target() = xo;
1025         else
1026                 xo = x_target();
1027
1028         // try neigbouring script insets
1029         if (!selection()) {
1030                 // try left
1031                 if (pos() != 0) {
1032                         InsetMathScript const * p = prevAtom()->asScriptInset();
1033                         if (p && p->has(up)) {
1034                                 --pos();
1035                                 push(*const_cast<InsetMathScript*>(p));
1036                                 idx() = p->idxOfScript(up);
1037                                 pos() = lastpos();
1038                                 return true;
1039                         }
1040                 }
1041
1042                 // try right
1043                 if (pos() != lastpos()) {
1044                         InsetMathScript const * p = nextAtom()->asScriptInset();
1045                         if (p && p->has(up)) {
1046                                 push(*const_cast<InsetMathScript*>(p));
1047                                 idx() = p->idxOfScript(up);
1048                                 pos() = 0;
1049                                 return true;
1050                         }
1051                 }
1052         }
1053
1054 // FIXME: Switch this on for more robust movement
1055 #if 0
1056
1057         return bruteFind3(*this, xo, yo, up);
1058
1059 #else
1060         //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1061         //if (up)
1062         //      yhigh = yo - 4;
1063         //else
1064         //      ylow = yo + 4;
1065         //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
1066         //      lyxerr << "updown: handled by brute find in the same cell" << endl;
1067         //      return true;
1068         //}
1069
1070         // try to find an inset that knows better then we
1071         while (true) {
1072                 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1073                 // ask inset first
1074                 if (inset().idxUpDown(*this, up)) {
1075                         //lyxerr << "idxUpDown triggered" << endl;
1076                         // try to find best position within this inset
1077                         if (!selection())
1078                                 setCursor(bruteFind2(*this, xo, yo));
1079                         return true;
1080                 }
1081
1082                 // no such inset found, just take something "above"
1083                 if (!popLeft()) {
1084                         //lyxerr << "updown: popleft failed (strange case)" << endl;
1085                         int ylow  = up ? 0 : yo + 1;
1086                         int yhigh = up ? yo - 1 : bv().workHeight();
1087                         return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
1088                 }
1089
1090                 // any improvement so far?
1091                 //lyxerr << "updown: popLeft succeeded" << endl;
1092                 int xnew;
1093                 int ynew;
1094                 getPos(xnew, ynew);
1095                 if (up ? ynew < yo : ynew > yo)
1096                         return true;
1097         }
1098
1099         // we should not come here.
1100         BOOST_ASSERT(false);
1101 #endif
1102 }
1103
1104
1105 void LCursor::handleFont(string const & font)
1106 {
1107         lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << ": " << font << endl;
1108         docstring safe;
1109         if (selection()) {
1110                 macroModeClose();
1111                 safe = cap::grabAndEraseSelection(*this);
1112         }
1113
1114         if (lastpos() != 0) {
1115                 // something left in the cell
1116                 if (pos() == 0) {
1117                         // cursor in first position
1118                         popLeft();
1119                 } else if (pos() == lastpos()) {
1120                         // cursor in last position
1121                         popRight();
1122                 } else {
1123                         // cursor in between. split cell
1124                         MathArray::iterator bt = cell().begin();
1125                         MathAtom at = createInsetMath(from_utf8(font));
1126                         at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1127                         cell().erase(bt, bt + pos());
1128                         popLeft();
1129                         plainInsert(at);
1130                 }
1131         } else {
1132                 // nothing left in the cell
1133                 pullArg();
1134                 plainErase();
1135         }
1136         insert(safe);
1137 }
1138
1139
1140 void LCursor::message(docstring const & msg) const
1141 {
1142         theLyXFunc().setMessage(msg);
1143 }
1144
1145
1146 void LCursor::errorMessage(docstring const & msg) const
1147 {
1148         theLyXFunc().setErrorMessage(msg);
1149 }
1150
1151
1152 docstring LCursor::selectionAsString(bool label) const
1153 {
1154         if (!selection())
1155                 return docstring();
1156
1157         if (inTexted()) {
1158                 Buffer const & buffer = *bv().buffer();
1159                 ParagraphList const & pars = text()->paragraphs();
1160
1161                 // should be const ...
1162                 pit_type startpit = selBegin().pit();
1163                 pit_type endpit = selEnd().pit();
1164                 size_t const startpos = selBegin().pos();
1165                 size_t const endpos = selEnd().pos();
1166
1167                 if (startpit == endpit)
1168                         return pars[startpit].asString(buffer, startpos, endpos, label);
1169
1170                 // First paragraph in selection
1171                 docstring result = pars[startpit].
1172                         asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1173
1174                 // The paragraphs in between (if any)
1175                 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1176                         Paragraph const & par = pars[pit];
1177                         result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1178                 }
1179
1180                 // Last paragraph in selection
1181                 result += pars[endpit].asString(buffer, 0, endpos, label);
1182
1183                 return result;
1184         }
1185
1186         if (inMathed())
1187                 return cap::grabSelection(*this);
1188
1189         return docstring();
1190 }
1191
1192
1193 string LCursor::currentState()
1194 {
1195         if (inMathed()) {
1196                 odocstringstream os;
1197                 info(os);
1198                 return to_utf8(os.str());
1199         }
1200
1201         if (inTexted())
1202                 return text()->currentState(*this);
1203
1204         return string();
1205 }
1206
1207
1208 docstring LCursor::getPossibleLabel()
1209 {
1210         return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
1211 }
1212
1213
1214 Encoding const * LCursor::getEncoding() const
1215 {
1216         if (empty())
1217                 return 0;
1218         if (!bv().buffer())
1219                 return 0;
1220         int s = 0;
1221         // go up until first non-0 text is hit
1222         // (innermost text is 0 in mathed)
1223         for (s = depth() - 1; s >= 0; --s)
1224                 if (operator[](s).text())
1225                         break;
1226         CursorSlice const & sl = operator[](s);
1227         LyXText const & text = *sl.text();
1228         LyXFont font = text.getPar(sl.pit()).getFont(
1229                 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1230         return font.language()->encoding();
1231 }
1232
1233
1234 void LCursor::undispatched()
1235 {
1236         disp_.dispatched(false);
1237 }
1238
1239
1240 void LCursor::dispatched()
1241 {
1242         disp_.dispatched(true);
1243 }
1244
1245
1246 void LCursor::updateFlags(Update::flags f)
1247 {
1248         disp_.update(f);
1249 }
1250
1251
1252 void LCursor::noUpdate()
1253 {
1254         disp_.update(Update::None);
1255 }
1256
1257
1258 LyXFont LCursor::getFont() const
1259 {
1260         // HACK. far from being perfect...
1261         int s = 0;
1262         // go up until first non-0 text is hit
1263         // (innermost text is 0 in mathed)
1264         for (s = depth() - 1; s >= 0; --s)
1265                 if (operator[](s).text())
1266                         break;
1267         CursorSlice const & sl = operator[](s);
1268         LyXText const & text = *sl.text();
1269         LyXFont font = text.getPar(sl.pit()).getFont(
1270                 bv().buffer()->params(),
1271                 sl.pos(),
1272                 outerFont(sl.pit(), text.paragraphs()));
1273
1274         return font;
1275 }
1276
1277
1278 void LCursor::fixIfBroken()
1279 {
1280         // find out last good level
1281         LCursor copy = *this;
1282         size_t newdepth = depth();
1283         while (!copy.empty()) {
1284                 if (copy.idx() > copy.lastidx()) {
1285                         lyxerr << "wrong idx " << copy.idx()
1286                                << ", max is " << copy.lastidx()
1287                                << " at level " << copy.depth()
1288                                << ". Trying to correct this."  << endl;
1289                         newdepth = copy.depth() - 1;
1290                 }
1291                 else if (copy.pit() > copy.lastpit()) {
1292                         lyxerr << "wrong pit " << copy.pit()
1293                                << ", max is " << copy.lastpit()
1294                                << " at level " << copy.depth()
1295                                << ". Trying to correct this."  << endl;
1296                         newdepth = copy.depth() - 1;
1297                 }
1298                 else if (copy.pos() > copy.lastpos()) {
1299                         lyxerr << "wrong pos " << copy.pos()
1300                                << ", max is " << copy.lastpos()
1301                                << " at level " << copy.depth()
1302                                << ". Trying to correct this."  << endl;
1303                         newdepth = copy.depth() - 1;
1304                 }
1305                 copy.pop();
1306         }
1307         // shrink cursor to a size where everything is valid, possibly
1308         // leaving insets
1309         while (depth() > newdepth) {
1310                 pop();
1311                 lyxerr << "correcting cursor to level " << depth() << endl;
1312         }
1313 }
1314
1315
1316 } // namespace lyx