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