]> git.lyx.org Git - lyx.git/blob - src/cursor.C
move everything into namespace lyx
[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 namespace lyx {
54
55 using std::string;
56 using std::vector;
57 using std::endl;
58 #ifndef CXX_GLOBAL_CSTD
59 using std::isalpha;
60 #endif
61 using std::min;
62 using std::for_each;
63
64 namespace {
65
66         bool
67         positionable(DocIterator const & cursor, DocIterator const & anchor)
68         {
69                 // avoid deeper nested insets when selecting
70                 if (cursor.depth() > anchor.depth())
71                         return false;
72
73                 // anchor might be deeper, should have same path then
74                 for (size_t i = 0; i < cursor.depth(); ++i)
75                         if (&cursor[i].inset() != &anchor[i].inset())
76                                 return false;
77
78                 // position should be ok.
79                 return true;
80         }
81
82
83         // Find position closest to (x, y) in cell given by iter.
84         // Used only in mathed
85         DocIterator bruteFind2(LCursor const & c, int x, int y)
86         {
87                 double best_dist = std::numeric_limits<double>::max();
88
89                 DocIterator result;
90
91                 DocIterator it = c;
92                 it.top().pos() = 0;
93                 DocIterator et = c;
94                 et.top().pos() = et.top().asInsetMath()->cell(et.top().idx()).size();
95                 for (size_t i = 0; ; ++i) {
96                         int xo;
97                         int yo;
98                         InsetBase const * inset = &it.inset();
99                         Point o = c.bv().coordCache().getInsets().xy(inset);
100                         inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
101                         // Convert to absolute
102                         xo += o.x_;
103                         yo += o.y_;
104                         double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
105                         // '<=' in order to take the last possible position
106                         // this is important for clicking behind \sum in e.g. '\sum_i a'
107                         lyxerr[Debug::DEBUG] << "i: " << i << " d: " << d
108                                 << " best: " << best_dist << endl;
109                         if (d <= best_dist) {
110                                 best_dist = d;
111                                 result = it;
112                         }
113                         if (it == et)
114                                 break;
115                         it.forwardPos();
116                 }
117                 return result;
118         }
119
120
121         /// moves position closest to (x, y) in given box
122         bool bruteFind(LCursor & cursor,
123                 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
124         {
125                 BOOST_ASSERT(!cursor.empty());
126                 InsetBase & inset = cursor[0].inset();
127                 BufferView & bv = cursor.bv();
128
129                 CoordCache::InnerParPosCache const & cache =
130                         bv.coordCache().getParPos().find(cursor.bottom().text())->second;
131                 // Get an iterator on the first paragraph in the cache
132                 DocIterator it(inset);
133                 it.push_back(CursorSlice(inset));
134                 it.pit() = cache.begin()->first;
135                 // Get an iterator after the last paragraph in the cache
136                 DocIterator et(inset);
137                 et.push_back(CursorSlice(inset));
138                 et.pit() = boost::prior(cache.end())->first;
139                 if (et.pit() >= et.lastpit())
140                         et = doc_iterator_end(inset);
141                 else
142                         ++et.pit();
143
144                 double best_dist = std::numeric_limits<double>::max();;
145                 DocIterator best_cursor = et;
146
147                 for ( ; it != et; it.forwardPos(true)) {
148                         // avoid invalid nesting when selecting
149                         if (!cursor.selection() || positionable(it, cursor.anchor_)) {
150                                 Point p = bv_funcs::getPos(bv, it, false);
151                                 int xo = p.x_;
152                                 int yo = p.y_;
153                                 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
154                                         double const dx = xo - x;
155                                         double const dy = yo - y;
156                                         double const d = dx * dx + dy * dy;
157                                         // '<=' in order to take the last possible position
158                                         // this is important for clicking behind \sum in e.g. '\sum_i a'
159                                         if (d <= best_dist) {
160                                                 //      lyxerr << "*" << endl;
161                                                 best_dist   = d;
162                                                 best_cursor = it;
163                                         }
164                                 }
165                         }
166                 }
167
168                 if (best_cursor != et) {
169                         cursor.setCursor(best_cursor);
170                         return true;
171                 }
172
173                 return false;
174         }
175
176
177         /// moves position closest to (x, y) in given box
178         bool bruteFind3(LCursor & cur, int x, int y, bool up)
179         {
180                 BufferView & bv = cur.bv();
181                 int ylow  = up ? 0 : y + 1;
182                 int yhigh = up ? y - 1 : bv.workHeight();
183                 int xlow = 0;
184                 int xhigh = bv.workWidth();
185
186 // FIXME: bit more work needed to get 'from' and 'to' right.
187                 pit_type from = cur.bottom().pit();
188                 //pit_type to = cur.bottom().pit();
189                 //lyxerr << "Pit start: " << from << endl;
190
191                 //lyxerr << "bruteFind3: x: " << x << " y: " << y
192                 //      << " xlow: " << xlow << " xhigh: " << xhigh
193                 //      << " ylow: " << ylow << " yhigh: " << yhigh
194                 //      << endl;
195                 InsetBase & inset = bv.buffer()->inset();
196                 DocIterator it = doc_iterator_begin(inset);
197                 it.pit() = from;
198                 DocIterator et = doc_iterator_end(inset);
199
200                 double best_dist = std::numeric_limits<double>::max();
201                 DocIterator best_cursor = et;
202
203                 for ( ; it != et; it.forwardPos()) {
204                         // avoid invalid nesting when selecting
205                         if (bv_funcs::status(&bv, it) == bv_funcs::CUR_INSIDE
206                             && (!cur.selection() || positionable(it, cur.anchor_))) {
207                                 Point p = bv_funcs::getPos(bv, it, false);
208                                 int xo = p.x_;
209                                 int yo = p.y_;
210                                 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
211                                         double const dx = xo - x;
212                                         double const dy = yo - y;
213                                         double const d = dx * dx + dy * dy;
214                                         //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
215                                         //      << " dx: " << dx << " dy: " << dy
216                                         //      << " idx: " << it.idx() << " pos: " << it.pos()
217                                         //      << " it:\n" << it
218                                         //      << endl;
219                                         // '<=' in order to take the last possible position
220                                         // this is important for clicking behind \sum in e.g. '\sum_i a'
221                                         if (d <= best_dist) {
222                                                 //lyxerr << "*" << endl;
223                                                 best_dist   = d;
224                                                 best_cursor = it;
225                                         }
226                                 }
227                         }
228                 }
229
230                 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
231                 if (best_cursor == et)
232                         return false;
233                 cur.setCursor(best_cursor);
234                 return true;
235         }
236
237 } // namespace anon
238
239
240 // be careful: this is called from the bv's constructor, too, so
241 // bv functions are not yet available!
242 LCursor::LCursor(BufferView & bv)
243         : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
244           selection_(false), mark_(false), logicalpos_(false)
245 {}
246
247
248 void LCursor::reset(InsetBase & inset)
249 {
250         clear();
251         push_back(CursorSlice(inset));
252         anchor_ = DocIterator(inset);
253         clearTargetX();
254         selection_ = false;
255         mark_ = false;
256 }
257
258
259 // this (intentionally) does neither touch anchor nor selection status
260 void LCursor::setCursor(DocIterator const & cur)
261 {
262         DocIterator::operator=(cur);
263 }
264
265
266 void LCursor::dispatch(FuncRequest const & cmd0)
267 {
268         lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
269                              << " cmd: " << cmd0 << '\n'
270                              << *this << endl;
271         if (empty())
272                 return;
273
274         fixIfBroken();
275         FuncRequest cmd = cmd0;
276         LCursor safe = *this;
277
278         for (; depth(); pop()) {
279                 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: "
280                         << cmd0 << endl << *this << endl;
281                 BOOST_ASSERT(pos() <= lastpos());
282                 BOOST_ASSERT(idx() <= lastidx());
283                 BOOST_ASSERT(pit() <= lastpit());
284
285                 // The common case is 'LFUN handled, need update', so make the
286                 // LFUN handler's life easier by assuming this as default value.
287                 // The handler can reset the update and val flags if necessary.
288                 disp_.update(true);
289                 disp_.dispatched(true);
290                 inset().dispatch(*this, cmd);
291                 if (disp_.dispatched())
292                         break;
293         }
294         // it completely to get a 'bomb early' behaviour in case this
295         // object will be used again.
296         if (!disp_.dispatched()) {
297                 lyxerr[Debug::DEBUG] << "RESTORING OLD CURSOR!" << endl;
298                 operator=(safe);
299                 disp_.dispatched(false);
300         }
301 }
302
303
304 DispatchResult LCursor::result() const
305 {
306         return disp_;
307 }
308
309
310 BufferView & LCursor::bv() const
311 {
312         BOOST_ASSERT(bv_);
313         return *bv_;
314 }
315
316
317 Buffer & LCursor::buffer() const
318 {
319         BOOST_ASSERT(bv_);
320         BOOST_ASSERT(bv_->buffer());
321         return *bv_->buffer();
322 }
323
324
325 void LCursor::pop()
326 {
327         BOOST_ASSERT(depth() >= 1);
328         pop_back();
329 }
330
331
332 void LCursor::push(InsetBase & p)
333 {
334         push_back(CursorSlice(p));
335 }
336
337
338 void LCursor::pushLeft(InsetBase & p)
339 {
340         BOOST_ASSERT(!empty());
341         //lyxerr << "Entering inset " << t << " left" << endl;
342         push(p);
343         p.idxFirst(*this);
344 }
345
346
347 bool LCursor::popLeft()
348 {
349         BOOST_ASSERT(!empty());
350         //lyxerr << "Leaving inset to the left" << endl;
351         inset().notifyCursorLeaves(*this);
352         if (depth() == 1)
353                 return false;
354         pop();
355         return true;
356 }
357
358
359 bool LCursor::popRight()
360 {
361         BOOST_ASSERT(!empty());
362         //lyxerr << "Leaving inset to the right" << endl;
363         inset().notifyCursorLeaves(*this);
364         if (depth() == 1)
365                 return false;
366         pop();
367         ++pos();
368         return true;
369 }
370
371
372 int LCursor::currentMode()
373 {
374         BOOST_ASSERT(!empty());
375         for (int i = depth() - 1; i >= 0; --i) {
376                 int res = operator[](i).inset().currentMode();
377                 if (res != InsetBase::UNDECIDED_MODE)
378                         return res;
379         }
380         return InsetBase::TEXT_MODE;
381 }
382
383
384 void LCursor::getPos(int & x, int & y) const
385 {
386         Point p = bv_funcs::getPos(bv(), *this, boundary());
387         x = p.x_;
388         y = p.y_;
389 }
390
391
392 void LCursor::resetAnchor()
393 {
394         anchor_ = *this;
395 }
396
397
398
399 bool LCursor::posLeft()
400 {
401         if (pos() == 0)
402                 return false;
403         --pos();
404         return true;
405 }
406
407
408 bool LCursor::posRight()
409 {
410         if (pos() == lastpos())
411                 return false;
412         ++pos();
413         return true;
414 }
415
416
417 CursorSlice LCursor::anchor() const
418 {
419         BOOST_ASSERT(anchor_.depth() >= depth());
420         CursorSlice normal = anchor_[depth() - 1];
421         if (depth() < anchor_.depth() && top() <= normal) {
422                 // anchor is behind cursor -> move anchor behind the inset
423                 ++normal.pos();
424         }
425         return normal;
426 }
427
428
429 CursorSlice LCursor::selBegin() const
430 {
431         if (!selection())
432                 return top();
433         return anchor() < top() ? anchor() : top();
434 }
435
436
437 CursorSlice LCursor::selEnd() const
438 {
439         if (!selection())
440                 return top();
441         return anchor() > top() ? anchor() : top();
442 }
443
444
445 DocIterator LCursor::selectionBegin() const
446 {
447         if (!selection())
448                 return *this;
449         DocIterator di = (anchor() < top() ? anchor_ : *this);
450         di.resize(depth());
451         return di;
452 }
453
454
455 DocIterator LCursor::selectionEnd() const
456 {
457         if (!selection())
458                 return *this;
459         DocIterator di = (anchor() > top() ? anchor_ : *this);
460         if (di.depth() > depth()) {
461                 di.resize(depth());
462                 ++di.pos();
463         }
464         return di;
465 }
466
467
468 void LCursor::setSelection()
469 {
470         selection() = true;
471         // A selection with no contents is not a selection
472 #ifdef WITH_WARNINGS
473 #warning doesnt look ok
474 #endif
475         if (pit() == anchor().pit() && pos() == anchor().pos())
476                 selection() = false;
477 }
478
479
480 void LCursor::setSelection(DocIterator const & where, size_t n)
481 {
482         setCursor(where);
483         selection() = true;
484         anchor_ = where;
485         pos() += n;
486 }
487
488
489 void LCursor::clearSelection()
490 {
491         selection() = false;
492         mark() = false;
493         resetAnchor();
494 }
495
496
497 int & LCursor::x_target()
498 {
499         return x_target_;
500 }
501
502
503 int LCursor::x_target() const
504 {
505         return x_target_;
506 }
507
508
509 void LCursor::clearTargetX()
510 {
511         x_target_ = -1;
512 }
513
514
515
516 void LCursor::info(std::ostream & os) const
517 {
518         for (int i = 1, n = depth(); i < n; ++i) {
519                 operator[](i).inset().infoize(os);
520                 os << "  ";
521         }
522         if (pos() != 0)
523                 prevInset()->infoize2(os);
524         // overwite old message
525         os << "                    ";
526 }
527
528
529 void LCursor::selHandle(bool sel)
530 {
531         //lyxerr << "LCursor::selHandle" << endl;
532         if (sel == selection())
533                 return;
534
535         resetAnchor();
536         selection() = sel;
537 }
538
539
540 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
541 {
542         os << "\n cursor:                                | anchor:\n";
543         for (size_t i = 0, n = cur.depth(); i != n; ++i) {
544                 os << " " << cur[i] << " | ";
545                 if (i < cur.anchor_.depth())
546                         os << cur.anchor_[i];
547                 else
548                         os << "-------------------------------";
549                 os << "\n";
550         }
551         for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
552                 os << "------------------------------- | " << cur.anchor_[i] << "\n";
553         }
554         os << " selection: " << cur.selection_
555            << " x_target: " << cur.x_target_ << endl;
556         return os;
557 }
558
559 } // namespace lyx
560
561
562 ///////////////////////////////////////////////////////////////////
563 //
564 // The part below is the non-integrated rest of the original math
565 // cursor. This should be either generalized for texted or moved
566 // back to mathed (in most cases to InsetMathNest).
567 //
568 ///////////////////////////////////////////////////////////////////
569
570 #include "mathed/InsetMathChar.h"
571 #include "mathed/MathFactory.h"
572 #include "mathed/InsetMathGrid.h"
573 #include "mathed/MathMacroArgument.h"
574 #include "mathed/MathMLStream.h"
575 #include "mathed/InsetMathScript.h"
576 #include "mathed/MathSupport.h"
577 #include "mathed/InsetMathUnknown.h"
578
579
580 namespace lyx {
581
582 //#define FILEDEBUG 1
583
584
585 bool LCursor::isInside(InsetBase const * p)
586 {
587         for (size_t i = 0; i != depth(); ++i)
588                 if (&operator[](i).inset() == p)
589                         return true;
590         return false;
591 }
592
593
594 void LCursor::leaveInset(InsetBase const & inset)
595 {
596         for (size_t i = 0; i != depth(); ++i) {
597                 if (&operator[](i).inset() == &inset) {
598                         resize(i);
599                         return;
600                 }
601         }
602 }
603
604
605 bool LCursor::openable(MathAtom const & t) const
606 {
607         if (!t->isActive())
608                 return false;
609
610         if (t->lock())
611                 return false;
612
613         if (!selection())
614                 return true;
615
616         // we can't move into anything new during selection
617         if (depth() >= anchor_.depth())
618                 return false;
619         if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
620                 return false;
621
622         return true;
623 }
624
625
626 void LCursor::setScreenPos(int x, int y)
627 {
628         x_target() = x;
629         bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
630 }
631
632
633
634 void LCursor::plainErase()
635 {
636         cell().erase(pos());
637 }
638
639
640 void LCursor::markInsert()
641 {
642         insert(char_type(0));
643 }
644
645
646 void LCursor::markErase()
647 {
648         cell().erase(pos());
649 }
650
651
652 void LCursor::plainInsert(MathAtom const & t)
653 {
654         cell().insert(pos(), t);
655         ++pos();
656 }
657
658
659 void LCursor::insert(string const & str)
660 {
661         for_each(str.begin(), str.end(),
662                  boost::bind(static_cast<void(LCursor::*)(char_type)>
663                              (&LCursor::insert), this, _1));
664 }
665
666
667 void LCursor::insert(char_type c)
668 {
669         //lyxerr << "LCursor::insert char '" << c << "'" << endl;
670         BOOST_ASSERT(!empty());
671         if (inMathed()) {
672                 cap::selClearOrDel(*this);
673                 insert(new InsetMathChar(c));
674         } else {
675                 text()->insertChar(*this, c);
676         }
677 }
678
679
680 void LCursor::insert(MathAtom const & t)
681 {
682         //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
683         macroModeClose();
684         cap::selClearOrDel(*this);
685         plainInsert(t);
686 }
687
688
689 void LCursor::insert(InsetBase * inset)
690 {
691         if (inMathed())
692                 insert(MathAtom(inset));
693         else
694                 text()->insertInset(*this, inset);
695 }
696
697
698 void LCursor::niceInsert(string const & t)
699 {
700         MathArray ar;
701         // FIXME UNICODE
702         asArray(from_utf8(t), ar);
703         if (ar.size() == 1)
704                 niceInsert(ar[0]);
705         else
706                 insert(ar);
707 }
708
709
710 void LCursor::niceInsert(MathAtom const & t)
711 {
712         macroModeClose();
713         string const safe = cap::grabAndEraseSelection(*this);
714         plainInsert(t);
715         // enter the new inset and move the contents of the selection if possible
716         if (t->isActive()) {
717                 posLeft();
718                 // be careful here: don't use 'pushLeft(t)' as this we need to
719                 // push the clone, not the original
720                 pushLeft(*nextInset());
721                 // We may not use niceInsert here (recursion)
722                 MathArray ar;
723                 // FIXME UNICODE
724                 asArray(from_utf8(safe), ar);
725                 insert(ar);
726         }
727 }
728
729
730 void LCursor::insert(MathArray const & ar)
731 {
732         macroModeClose();
733         if (selection())
734                 cap::eraseSelection(*this);
735         cell().insert(pos(), ar);
736         pos() += ar.size();
737 }
738
739
740 bool LCursor::backspace()
741 {
742         autocorrect() = false;
743
744         if (selection()) {
745                 cap::selDel(*this);
746                 return true;
747         }
748
749         if (pos() == 0) {
750                 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
751                         return false;
752                 pullArg();
753                 return true;
754         }
755
756         if (inMacroMode()) {
757                 InsetMathUnknown * p = activeMacro();
758                 if (p->name().size() > 1) {
759                         p->setName(p->name().substr(0, p->name().size() - 1));
760                         return true;
761                 }
762         }
763
764         if (pos() != 0 && prevAtom()->nargs() > 0) {
765                 // let's require two backspaces for 'big stuff' and
766                 // highlight on the first
767                 resetAnchor();
768                 selection() = true;
769                 --pos();
770         } else {
771                 --pos();
772                 plainErase();
773         }
774         return true;
775 }
776
777
778 bool LCursor::erase()
779 {
780         autocorrect() = false;
781         if (inMacroMode())
782                 return true;
783
784         if (selection()) {
785                 cap::selDel(*this);
786                 return true;
787         }
788
789         // delete empty cells if possible
790         if (pos() == lastpos() && inset().idxDelete(idx()))
791                 return true;
792
793         // special behaviour when in last position of cell
794         if (pos() == lastpos()) {
795                 bool one_cell = inset().nargs() == 1;
796                 if (one_cell && depth() == 1 && lastpos() == 0)
797                         return false;
798                 // remove markup
799                 if (one_cell)
800                         pullArg();
801                 else
802                         inset().idxGlue(idx());
803                 return true;
804         }
805
806         // 'clever' UI hack: only erase large items if previously slected
807         if (pos() != lastpos() && nextAtom()->nargs() > 0) {
808                 resetAnchor();
809                 selection() = true;
810                 ++pos();
811         } else {
812                 plainErase();
813         }
814
815         return true;
816 }
817
818
819 bool LCursor::up()
820 {
821         macroModeClose();
822         DocIterator save = *this;
823         if (goUpDown(true))
824                 return true;
825         setCursor(save);
826         autocorrect() = false;
827         return selection();
828 }
829
830
831 bool LCursor::down()
832 {
833         macroModeClose();
834         DocIterator save = *this;
835         if (goUpDown(false))
836                 return true;
837         setCursor(save);
838         autocorrect() = false;
839         return selection();
840 }
841
842
843 bool LCursor::macroModeClose()
844 {
845         if (!inMacroMode())
846                 return false;
847         InsetMathUnknown * p = activeMacro();
848         p->finalize();
849         string const s = p->name();
850         --pos();
851         cell().erase(pos());
852
853         // do nothing if the macro name is empty
854         if (s == "\\")
855                 return false;
856
857         // prevent entering of recursive macros
858         // FIXME: this is only a weak attempt... only prevents immediate
859         // recursion
860         string const name = s.substr(1);
861         InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
862         if (macro && macro->getInsetName() == name)
863                 lyxerr << "can't enter recursive macro" << endl;
864
865         InsetMathNest * const in = inset().asInsetMath()->asNestInset();
866         if (in && in->interpretString(*this, s))
867                 return true;
868         plainInsert(createInsetMath(name));
869         return true;
870 }
871
872
873 string LCursor::macroName()
874 {
875         return inMacroMode() ? activeMacro()->name() : string();
876 }
877
878
879 void LCursor::handleNest(MathAtom const & a, int c)
880 {
881         //lyxerr << "LCursor::handleNest: " << c << endl;
882         MathAtom t = a;
883         // FIXME UNICODE
884         asArray(from_utf8(cap::grabAndEraseSelection(*this)), t.nucleus()->cell(c));
885         insert(t);
886         posLeft();
887         pushLeft(*nextInset());
888 }
889
890
891 int LCursor::targetX() const
892 {
893         if (x_target() != -1)
894                 return x_target();
895         int x = 0;
896         int y = 0;
897         getPos(x, y);
898         return x;
899 }
900
901
902 void LCursor::setTargetX()
903 {
904         // For now this is good enough. A better solution would be to
905         // avoid this rebreak by setting cursorX only after drawing
906         bottom().text()->redoParagraph(bottom().pit());
907         int x;
908         int y;
909         getPos(x, y);
910         x_target_ = x;
911 }
912
913
914 bool LCursor::inMacroMode() const
915 {
916         if (pos() == 0)
917                 return false;
918         InsetMathUnknown const * p = prevAtom()->asUnknownInset();
919         return p && !p->final();
920 }
921
922
923 InsetMathUnknown * LCursor::activeMacro()
924 {
925         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
926 }
927
928
929 void LCursor::pullArg()
930 {
931 #ifdef WITH_WARNINGS
932 #warning Look here
933 #endif
934         MathArray ar = cell();
935         if (popLeft() && inMathed()) {
936                 plainErase();
937                 cell().insert(pos(), ar);
938                 resetAnchor();
939         } else {
940                 //formula()->mutateToText();
941         }
942 }
943
944
945 void LCursor::touch()
946 {
947 #ifdef WITH_WARNINGS
948 #warning look here
949 #endif
950 #if 0
951         DocIterator::const_iterator it = begin();
952         DocIterator::const_iterator et = end();
953         for ( ; it != et; ++it)
954                 it->cell().touch();
955 #endif
956 }
957
958
959 void LCursor::normalize()
960 {
961         if (idx() > lastidx()) {
962                 lyxerr << "this should not really happen - 1: "
963                        << idx() << ' ' << nargs()
964                        << " in: " << &inset() << endl;
965                 idx() = lastidx();
966         }
967
968         if (pos() > lastpos()) {
969                 lyxerr << "this should not really happen - 2: "
970                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
971                        << " in atom: '";
972                 odocstringstream os;
973                 WriteStream wi(os, false, true);
974                 inset().asInsetMath()->write(wi);
975                 lyxerr << to_utf8(os.str()) << 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 = 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 from_utf8(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 }
1285
1286
1287 } // namespace lyx