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