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