]> git.lyx.org Git - lyx.git/blob - src/cursor.C
remove part of old texted<->mathed interface
[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 "debug.h"
19 #include "dispatchresult.h"
20 #include "encoding.h"
21 #include "funcrequest.h"
22 #include "iterators.h"
23 #include "language.h"
24 #include "lfuns.h"
25 #include "lyxfont.h"
26 #include "lyxfunc.h" // only for setMessage()
27 #include "lyxrc.h"
28 #include "lyxrow.h"
29 #include "lyxtext.h"
30 #include "paragraph.h"
31 #include "paragraph_funcs.h"
32
33 #include "insets/updatableinset.h"
34 #include "insets/insettabular.h"
35 #include "insets/insettext.h"
36
37 #include "mathed/math_data.h"
38 #include "mathed/math_support.h"
39 #include "mathed/math_inset.h"
40
41 #include "support/limited_stack.h"
42 #include "support/std_sstream.h"
43
44 #include "frontends/LyXView.h"
45
46 #include <boost/assert.hpp>
47
48 using std::string;
49 using std::vector;
50 using std::endl;
51 #ifndef CXX_GLOBAL_CSTD
52 using std::isalpha;
53 #endif
54 using std::min;
55 using std::swap;
56
57
58
59 // our own cut buffer
60 limited_stack<string> theCutBuffer;
61
62
63 namespace {
64
65 void region(CursorSlice const & i1, CursorSlice const & i2,
66         LCursor::row_type & r1, LCursor::row_type & r2,
67         LCursor::col_type & c1, LCursor::col_type & c2)
68 {
69         InsetBase & p = i1.inset();
70         c1 = p.col(i1.idx_);
71         c2 = p.col(i2.idx_);
72         if (c1 > c2)
73                 swap(c1, c2);
74         r1 = p.row(i1.idx_);
75         r2 = p.row(i2.idx_);
76         if (r1 > r2)
77                 swap(r1, r2);
78 }
79
80 }
81
82
83 LCursor::LCursor(BufferView & bv)
84         : DocumentIterator(), bv_(&bv), anchor_(),
85           cached_y_(0), x_target_(-1), selection_(false), mark_(false)
86 {}
87
88
89 void LCursor::reset()
90 {
91         clear();
92         push_back(CursorSlice());
93         anchor_.clear();
94         anchor_.push_back(CursorSlice());
95         cached_y_ = 0;
96         clearTargetX();
97         selection_ = false;
98         mark_ = false;
99 }
100
101
102 void LCursor::setCursor(DocumentIterator const & cur, bool sel)
103 {
104         // this (intentionally) does not touch the anchor
105         DocumentIterator::operator=(cur);
106         selection() = sel;
107 }
108
109
110 DispatchResult LCursor::dispatch(FuncRequest const & cmd0)
111 {
112         if (empty())
113                 return DispatchResult();
114
115         //lyxerr << "\nLCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
116         FuncRequest cmd = cmd0;
117         nopop_ = false;
118         LCursor safe = *this;
119
120         for ( ; size(); pop()) {
121                 lyxerr << "\nLCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
122                 BOOST_ASSERT(pos() <= lastpos());
123                 BOOST_ASSERT(idx() <= lastidx());
124                 BOOST_ASSERT(par() <= lastpar());
125
126                 // The common case is 'LFUN handled, need update', so make the 
127                 // LFUN handler's life easier by assuming this as default value.
128                 // The handler can reset the update and val flags if necessary.
129                 disp_.update(true);
130                 disp_.dispatched(true);
131                 inset().dispatch(*this, cmd);
132                 if (disp_.dispatched())
133                         break;
134         }
135         // it completely to get a 'bomb early' behaviour in case this
136         // object will be used again.
137         if (nopop_ || !disp_.dispatched())
138                 operator=(safe);
139         return disp_;
140 }
141
142
143 bool LCursor::getStatus(FuncRequest const & cmd, FuncStatus & status)
144 {
145         LCursor safe = *this;
146         for ( ; size(); pop()) {
147                 //lyxerr << "\nLCursor::getStatus: cmd: " << cmd << endl << *this << endl;
148                 BOOST_ASSERT(pos() <= lastpos());
149                 BOOST_ASSERT(idx() <= lastidx());
150                 BOOST_ASSERT(par() <= lastpar());
151
152                 // The inset's getStatus() will return 'true' if it made
153                 // a definitive decision on whether it want to handle the
154                 // request or not. The result of this decision is put into
155                 // the 'status' parameter.
156                 if (inset().getStatus(*this, cmd, status))
157                         break;
158         }
159         operator=(safe);
160         return true;
161 }
162
163
164 BufferView & LCursor::bv() const
165 {
166         return *bv_;
167 }
168
169
170 void LCursor::pop()
171 {
172         BOOST_ASSERT(size() >= 1);
173         pop_back();
174         anchor_.pop_back();
175 }
176
177
178 void LCursor::push(InsetBase & p)
179 {
180         push_back(CursorSlice(p));
181 }
182
183
184 void LCursor::pushLeft(InsetBase & p)
185 {
186         BOOST_ASSERT(!empty());
187         //lyxerr << "Entering inset " << t << " left" << endl;
188         push(p);
189         p.idxFirst(*this);
190 }
191
192
193 bool LCursor::popLeft()
194 {
195         BOOST_ASSERT(!empty());
196         //lyxerr << "Leaving inset to the left" << endl;
197         inset().notifyCursorLeaves(idx());
198         if (depth() == 1)
199                 return false;
200         pop();
201         return true;
202 }
203
204
205 bool LCursor::popRight()
206 {
207         BOOST_ASSERT(!empty());
208         //lyxerr << "Leaving inset to the right" << endl;
209         inset().notifyCursorLeaves(idx());
210         if (depth() == 1)
211                 return false;
212         pop();
213         ++pos();
214         return true;
215 }
216
217
218 int LCursor::currentMode()
219 {
220         BOOST_ASSERT(!empty());
221         for (int i = size() - 1; i >= 0; --i) {
222                 int res = operator[](i).inset().currentMode();
223                 if (res != InsetBase::UNDECIDED_MODE)
224                         return res;
225         }
226         return InsetBase::TEXT_MODE;
227 }
228
229
230 void LCursor::updatePos()
231 {
232         BOOST_ASSERT(!empty());
233         if (size() > 1)
234                 cached_y_ = bv().top_y() + back().inset().yo();
235                 //cached_y_ = back().inset().yo();
236 }
237
238
239 void LCursor::getDim(int & asc, int & des) const
240 {
241         if (inMathed()) {
242                 BOOST_ASSERT(inset().asMathInset());
243                 //inset().asMathInset()->getCursorDim(asc, des);
244                 asc = 10;
245                 des = 10;
246         } else if (inTexted()) {
247                 Row const & row = textRow();
248                 asc = row.baseline();
249                 des = row.height() - asc;
250         } else {
251                 lyxerr << "should this happen?" << endl;
252                 asc = 10;
253                 des = 10;
254         }
255 }
256
257
258 void LCursor::getPos(int & x, int & y) const
259 {
260         x = 0;
261         y = 0;
262         if (!empty())
263                 inset().getCursorPos(back(), x, y);
264         // getCursorPos gives _screen_ coordinates. We need to add
265         // top_y to get document coordinates. This is hidden in cached_y_.
266         //y += cached_y_ - inset().yo();
267         // The rest is non-obvious. The reason we have to have these
268         // extra computation is that the getCursorPos() calls rely
269         // on the inset's own knowledge of its screen position.
270         // If we scroll up or down in a big enough increment,
271         // inset->draw() is not called: this doesn't update
272         // inset.yo_, so getCursor() returns an old value.
273         // Ugly as you like.
274 }
275
276
277 void LCursor::paste(string const & data)
278 {
279         dispatch(FuncRequest(LFUN_PASTE, data));
280 }
281
282
283 void LCursor::resetAnchor()
284 {
285         anchor_ = *this;
286 }
287
288
289
290 bool LCursor::posLeft()
291 {
292         if (pos() == 0)
293                 return false;
294         --pos();
295         return true;
296 }
297
298
299 bool LCursor::posRight()
300 {
301         if (pos() == lastpos())
302                 return false;
303         ++pos();
304         return true;
305 }
306
307
308 CursorSlice & LCursor::anchor()
309 {
310         return anchor_.back();
311 }
312
313
314 CursorSlice const & LCursor::anchor() const
315 {
316         return anchor_.back();
317 }
318
319
320 CursorSlice const & LCursor::selBegin() const
321 {
322         if (!selection())
323                 return back();
324         return anchor() < back() ? anchor() : back();
325 }
326
327
328 CursorSlice & LCursor::selBegin()
329 {
330         if (!selection())
331                 return back();
332         // can't use std::min as this returns a const ref
333         return anchor() < back() ? anchor() : back();
334 }
335
336
337 CursorSlice const & LCursor::selEnd() const
338 {
339         if (!selection())
340                 return back();
341         return anchor() > back() ? anchor() : back();
342 }
343
344
345 CursorSlice & LCursor::selEnd()
346 {
347         if (!selection())
348                 return back();
349         // can't use std::min as this returns a const ref
350         return anchor() > back() ? anchor() : back();
351 }
352
353
354 void LCursor::setSelection()
355 {
356         selection() = true;
357         // a selection with no contents is not a selection
358         if (par() == anchor().par() && pos() == anchor().pos())
359                 selection() = false;
360 }
361
362
363 void LCursor::setSelection(DocumentIterator const & where, size_t n)
364 {
365         selection() = true;
366         setCursor(where, false);
367         anchor_ = where;
368         pos() += n;
369 }
370
371
372 void LCursor::clearSelection()
373 {
374         selection() = false;
375         mark() = false;
376         resetAnchor();
377         bv().unsetXSel();
378 }
379
380
381 int & LCursor::x_target()
382 {
383         return x_target_;
384 }
385
386
387 int LCursor::x_target() const
388 {
389         return x_target_;
390 }
391
392
393 void LCursor::clearTargetX()
394 {
395         x_target_ = -1;
396 }
397
398
399
400 void LCursor::info(std::ostream & os) const
401 {
402         for (int i = 1, n = depth(); i < n; ++i) {
403                 operator[](i).inset().infoize(os);
404                 os << "  ";
405         }
406         if (pos() != 0)
407                 prevInset()->infoize2(os);
408         // overwite old message
409         os << "                    ";
410 }
411
412
413 string LCursor::grabSelection()
414 {
415         if (!selection())
416                 return string();
417
418         CursorSlice i1 = selBegin();
419         CursorSlice i2 = selEnd();
420
421         if (i1.idx_ == i2.idx_) {
422                 if (i1.inset().asMathInset()) {
423                         MathArray::const_iterator it = i1.cell().begin();
424                         return asString(MathArray(it + i1.pos_, it + i2.pos_));
425                 } else {
426                         return "unknown selection 1";
427                 }
428         }
429
430         row_type r1, r2;
431         col_type c1, c2;
432         region(i1, i2, r1, r2, c1, c2);
433
434         string data;
435         if (i1.inset().asMathInset()) {
436                 for (row_type row = r1; row <= r2; ++row) {
437                         if (row > r1)
438                                 data += "\\\\";
439                         for (col_type col = c1; col <= c2; ++col) {
440                                 if (col > c1)
441                                         data += '&';
442                                 data += asString(i1.asMathInset()->cell(i1.asMathInset()->index(row, col)));
443                         }
444                 }
445         } else {
446                 data = "unknown selection 2";
447         }
448         return data;
449 }
450
451
452 void LCursor::eraseSelection()
453 {
454         //lyxerr << "LCursor::eraseSelection" << endl;
455         CursorSlice const & i1 = selBegin();
456         CursorSlice const & i2 = selEnd();
457 #warning FIXME
458         if (i1.inset().asMathInset()) {
459                 if (i1.idx_ == i2.idx_) {
460                         i1.cell().erase(i1.pos_, i2.pos_);
461                 } else {
462                         MathInset * p = i1.asMathInset();
463                         row_type r1, r2;
464                         col_type c1, c2;
465                         region(i1, i2, r1, r2, c1, c2);
466                         for (row_type row = r1; row <= r2; ++row)
467                                 for (col_type col = c1; col <= c2; ++col)
468                                         p->cell(p->index(row, col)).clear();
469                 }
470                 back() = i1;
471         } else {
472                 lyxerr << "can't erase this selection 1" << endl;
473         }
474         //lyxerr << "LCursor::eraseSelection end" << endl;
475 }
476
477
478 string LCursor::grabAndEraseSelection()
479 {
480         if (!selection())
481                 return string();
482         string res = grabSelection();
483         eraseSelection();
484         selection() = false;
485         return res;
486 }
487
488
489 void LCursor::selClear()
490 {
491         resetAnchor();
492         clearSelection();
493 }
494
495
496 void LCursor::selCopy()
497 {
498         if (selection()) {
499                 theCutBuffer.push(grabSelection());
500                 selection() = false;
501         } else {
502                 //theCutBuffer.erase();
503         }
504 }
505
506
507 void LCursor::selCut()
508 {
509         theCutBuffer.push(grabAndEraseSelection());
510 }
511
512
513 void LCursor::selDel()
514 {
515         //lyxerr << "LCursor::selDel" << endl;
516         if (selection()) {
517                 eraseSelection();
518                 selection() = false;
519         }
520 }
521
522
523 void LCursor::selPaste(size_t n)
524 {
525         selClearOrDel();
526         if (n < theCutBuffer.size())
527                 paste(theCutBuffer[n]);
528         //grabSelection();
529         selection() = false;
530 }
531
532
533 void LCursor::selHandle(bool sel)
534 {
535         //lyxerr << "LCursor::selHandle" << endl;
536         if (sel == selection())
537                 return;
538         resetAnchor();
539         selection() = sel;
540 }
541
542
543 void LCursor::selClearOrDel()
544 {
545         //lyxerr << "LCursor::selClearOrDel" << endl;
546         if (lyxrc.auto_region_delete)
547                 selDel();
548         else
549                 selection() = false;
550 }
551
552
553 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
554 {
555         for (size_t i = 0, n = cur.size(); i != n; ++i)
556                 os << " " << cur.operator[](i) << " | " << cur.anchor_[i] << "\n";
557         os << " selection: " << cur.selection_ << endl;
558         return os;
559 }
560
561
562
563
564 ///////////////////////////////////////////////////////////////////
565 //
566 // The part below is the non-integrated rest of the original math
567 // cursor. This should be either generalized for texted or moved
568 // back to mathed (in most cases to MathNestInset).
569 //
570 ///////////////////////////////////////////////////////////////////
571
572 #include "mathed/math_charinset.h"
573 #include "mathed/math_factory.h"
574 #include "mathed/math_gridinset.h"
575 #include "mathed/math_macroarg.h"
576 #include "mathed/math_macrotemplate.h"
577 #include "mathed/math_mathmlstream.h"
578 #include "mathed/math_scriptinset.h"
579 #include "mathed/math_support.h"
580 #include "mathed/math_unknowninset.h"
581
582 //#define FILEDEBUG 1
583
584
585 bool LCursor::isInside(InsetBase const * p)
586 {
587         for (unsigned i = 0; i < depth(); ++i)
588                 if (&operator[](i).inset() == p)
589                         return true;
590         return false;
591 }
592
593
594 bool LCursor::openable(MathAtom const & t) const
595 {
596         if (!t->isActive())
597                 return false;
598
599         if (t->lock())
600                 return false;
601
602         if (!selection())
603                 return true;
604
605         // we can't move into anything new during selection
606         if (depth() == anchor_.size())
607                 return false;
608         if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
609                 return false;
610
611         return true;
612 }
613
614
615 bool positionable(DocumentIterator const & cursor,
616         DocumentIterator const & anchor)
617 {
618         // avoid deeper nested insets when selecting
619         if (cursor.size() > anchor.size())
620                 return false;
621
622         // anchor might be deeper, should have same path then
623         for (size_t i = 0; i < cursor.size(); ++i)
624                 if (&cursor[i].inset() != &anchor[i].inset())
625                         return false;
626
627         // position should be ok.
628         return true;
629 }
630
631
632 void LCursor::setScreenPos(int x, int y)
633 {
634         x_target() = x;
635         bruteFind(x, y, 0, bv().workWidth(), 0, bv().workHeight());
636 }
637
638
639
640 void LCursor::plainErase()
641 {
642         cell().erase(pos());
643 }
644
645
646 void LCursor::markInsert()
647 {
648         cell().insert(pos(), MathAtom(new MathCharInset(0)));
649 }
650
651
652 void LCursor::markErase()
653 {
654         cell().erase(pos());
655 }
656
657
658 void LCursor::plainInsert(MathAtom const & t)
659 {
660         cell().insert(pos(), t);
661         ++pos();
662 }
663
664
665 void LCursor::insert(string const & str)
666 {
667         lyxerr << "LCursor::insert str '" << str << "'" << endl;
668         for (string::const_iterator it = str.begin(); it != str.end(); ++it)
669                 insert(*it);
670 }
671
672
673 void LCursor::insert(char c)
674 {
675         //lyxerr << "LCursor::insert char '" << c << "'" << endl;
676         BOOST_ASSERT(!empty());
677         if (inMathed()) {
678                 selClearOrDel();
679                 plainInsert(MathAtom(new MathCharInset(c)));
680         } else {
681                 text()->insertChar(*this, c);
682         }
683 }
684
685
686 void LCursor::insert(MathAtom const & t)
687 {
688         //lyxerr << "LCursor::insert MathAtom: " << endl;
689         macroModeClose();
690         selClearOrDel();
691         plainInsert(t);
692 }
693
694
695 void LCursor::insert(InsetBase * inset)
696 {
697         if (inMathed())
698                 insert(MathAtom(inset));
699         else
700                 text()->insertInset(*this, inset);
701 }
702
703
704 void LCursor::niceInsert(string const & t)
705 {
706         MathArray ar;
707         asArray(t, ar);
708         if (ar.size() == 1)
709                 niceInsert(ar[0]);
710         else
711                 insert(ar);
712 }
713
714
715 void LCursor::niceInsert(MathAtom const & t)
716 {
717         macroModeClose();
718         string safe = grabAndEraseSelection();
719         plainInsert(t);
720         // enter the new inset and move the contents of the selection if possible
721         if (t->isActive()) {
722                 posLeft();
723                 // be careful here: don't use 'pushLeft(t)' as this we need to
724                 // push the clone, not the original
725                 pushLeft(*nextInset());
726                 paste(safe);
727         }
728 }
729
730
731 void LCursor::insert(MathArray const & ar)
732 {
733         macroModeClose();
734         if (selection())
735                 eraseSelection();
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                 selDel();
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                 MathUnknownInset * 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                 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                 selDel();
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         if (pos() != lastpos() && inset().nargs() > 0) {
807                 selection() = true;
808                 ++pos();
809         } else {
810                 plainErase();
811         }
812
813         return true;
814 }
815
816
817 bool LCursor::up()
818 {
819         macroModeClose();
820         DocumentIterator save = *this;
821         if (goUpDown(true))
822                 return true;
823         setCursor(save, false);
824         autocorrect() = false;
825         return selection();
826 }
827
828
829 bool LCursor::down()
830 {
831         macroModeClose();
832         DocumentIterator save = *this;
833         if (goUpDown(false))
834                 return true;
835         setCursor(save, false);
836         autocorrect() = false;
837         return selection();
838 }
839
840
841 void LCursor::macroModeClose()
842 {
843         if (!inMacroMode())
844                 return;
845         MathUnknownInset * p = activeMacro();
846         p->finalize();
847         string s = p->name();
848         --pos();
849         cell().erase(pos());
850
851         // do nothing if the macro name is empty
852         if (s == "\\")
853                 return;
854
855         string const name = s.substr(1);
856
857         // prevent entering of recursive macros
858         InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
859         if (macro && macro->getInsetName() == name)
860                 lyxerr << "can't enter recursive macro" << endl;
861
862         niceInsert(createMathInset(name));
863 }
864
865
866 string LCursor::macroName()
867 {
868         return inMacroMode() ? activeMacro()->name() : string();
869 }
870
871
872 void LCursor::handleNest(MathAtom const & a, int c)
873 {
874         //lyxerr << "LCursor::handleNest: " << c << endl;
875         MathAtom t = a;
876         asArray(grabAndEraseSelection(), t.nucleus()->cell(c));
877         insert(t);
878         posLeft();
879         pushLeft(*nextInset());
880 }
881
882
883 int LCursor::targetX() const
884 {
885         if (x_target() != -1)
886                 return x_target();
887         int x = 0;
888         int y = 0;
889         getPos(x, y);
890         return x;
891 }
892
893
894 void LCursor::adjust(pos_type from, int diff)
895 {
896         if (pos() > from)
897                 pos() += diff;
898         if (anchor().pos_ > from)
899                 anchor().pos_ += diff;
900         // just to be on the safe side
901         // theoretically unecessary
902         normalize();
903 }
904
905
906 bool LCursor::inMacroMode() const
907 {
908         if (!pos() != 0)
909                 return false;
910         MathUnknownInset const * p = prevAtom()->asUnknownInset();
911         return p && !p->final();
912 }
913
914
915 MathUnknownInset * LCursor::activeMacro()
916 {
917         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
918 }
919
920
921 bool LCursor::inMacroArgMode() const
922 {
923         return pos() > 0 && prevAtom()->getChar() == '#';
924 }
925
926
927 MathGridInset * LCursor::enclosingGrid(idx_type & idx) const
928 {
929         for (MathInset::difference_type i = depth() - 1; i >= 0; --i) {
930                 MathInset * m = operator[](i).inset().asMathInset();
931                 if (!m)
932                         return 0;
933                 MathGridInset * p = m->asGridInset();
934                 if (p) {
935                         idx = operator[](i).idx_;
936                         return p;
937                 }
938         }
939         return 0;
940 }
941
942
943 void LCursor::pullArg()
944 {
945 #warning Look here
946         MathArray ar = cell();
947         if (popLeft() && inMathed()) {
948                 plainErase();
949                 cell().insert(pos(), ar);
950                 resetAnchor();
951         } else {
952                 //formula()->mutateToText();
953         }
954 }
955
956
957 void LCursor::touch()
958 {
959 #warning look here
960 #if 0
961         DocumentIterator::const_iterator it = begin();
962         DocumentIterator::const_iterator et = end();
963         for ( ; it != et; ++it)
964                 it->cell().touch();
965 #endif
966 }
967
968
969 void LCursor::normalize()
970 {
971         if (idx() >= nargs()) {
972                 lyxerr << "this should not really happen - 1: "
973                        << idx() << ' ' << nargs()
974                        << " in: " << &inset() << endl;
975         }
976         idx() = min(idx(), lastidx());
977
978         if (pos() > lastpos()) {
979                 lyxerr << "this should not really happen - 2: "
980                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
981                        << " in atom: '";
982                 WriteStream wi(lyxerr, false, true);
983                 inset().asMathInset()->write(wi);
984                 lyxerr << endl;
985         }
986         pos() = min(pos(), lastpos());
987 }
988
989
990 char LCursor::valign()
991 {
992         idx_type idx;
993         MathGridInset * p = enclosingGrid(idx);
994         return p ? p->valign() : '\0';
995 }
996
997
998 char LCursor::halign()
999 {
1000         idx_type idx;
1001         MathGridInset * p = enclosingGrid(idx);
1002         return p ? p->halign(idx % p->ncols()) : '\0';
1003 }
1004
1005
1006 bool LCursor::goUpDown(bool up)
1007 {
1008         // Be warned: The 'logic' implemented in this function is highly
1009         // fragile. A distance of one pixel or a '<' vs '<=' _really
1010         // matters. So fiddle around with it only if you think you know
1011         // what you are doing!
1012
1013   int xo = 0;
1014         int yo = 0;
1015         getPos(xo, yo);
1016
1017         // check if we had something else in mind, if not, this is the future goal
1018         if (x_target() == -1)
1019                 x_target() = xo;
1020         else
1021                 xo = x_target();
1022
1023         // try neigbouring script insets
1024         if (!selection()) {
1025                 // try left
1026                 if (pos() != 0) {
1027                         MathScriptInset const * p = prevAtom()->asScriptInset();
1028                         if (p && p->has(up)) {
1029                                 --pos();
1030                                 push(inset());
1031                                 idx() = up; // the superscript has index 1
1032                                 pos() = lastpos();
1033                                 //lyxerr << "updown: handled by scriptinset to the left" << endl;
1034                                 return true;
1035                         }
1036                 }
1037
1038                 // try right
1039                 if (pos() != lastpos()) {
1040                         MathScriptInset const * p = nextAtom()->asScriptInset();
1041                         if (p && p->has(up)) {
1042                                 push(inset());
1043                                 idx() = up;
1044                                 pos() = 0;
1045                                 //lyxerr << "updown: handled by scriptinset to the right" << endl;
1046                                 return true;
1047                         }
1048                 }
1049         }
1050
1051         // try current cell for e.g. text insets
1052         if (inset().idxUpDown2(*this, up))
1053                 return true;
1054
1055         //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1056         //if (up)
1057         //      yhigh = yo - 4;
1058         //else
1059         //      ylow = yo + 4;
1060         //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1061         //      lyxerr << "updown: handled by brute find in the same cell" << endl;
1062         //      return true;
1063         //}
1064
1065         // try to find an inset that knows better then we
1066         while (1) {
1067                 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1068                 // ask inset first
1069                 if (inset().idxUpDown(*this, up)) {
1070                         // try to find best position within this inset
1071                         if (!selection())
1072                                 bruteFind2(xo, yo);
1073                         return true;
1074                 }
1075
1076                 // no such inset found, just take something "above"
1077                 //lyxerr << "updown: handled by strange case" << endl;
1078                 if (!popLeft()) {
1079                         int ylow  = up ? 0 : yo + 1;
1080                         int yhigh = up ? yo - 1 : bv().workHeight();
1081                         return bruteFind(xo, yo, 0, bv().workWidth(), ylow, yhigh);
1082                 }
1083
1084                 // any improvement so far?
1085                 int xnew, ynew;
1086                 getPos(xnew, ynew);
1087                 if (up ? ynew < yo : ynew > yo)
1088                         return true;
1089         }
1090 }
1091
1092
1093 bool LCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1094 {
1095         BOOST_ASSERT(!empty());
1096         ParagraphList::iterator beg;
1097         ParagraphList::iterator end;
1098         CursorSlice bottom = operator[](0); 
1099         LyXText * text = bottom.text();
1100         BOOST_ASSERT(text);
1101         getParsInRange(text->paragraphs(), ylow, yhigh, beg, end);
1102
1103         DocumentIterator it = insetBegin(bv().buffer()->inset());
1104         DocumentIterator et;
1105         lyxerr << "x: " << x << " y: " << y << endl;
1106         lyxerr << "xlow: " << xlow << " ylow: " << ylow << endl;
1107         lyxerr << "xhigh: " << xhigh << " yhigh: " << yhigh << endl;
1108
1109         it.par() = text->parOffset(beg);
1110         //et.par() = text->parOffset(end);
1111
1112         double best_dist = 10e10;
1113         DocumentIterator best_cursor = it;
1114
1115         for ( ; it != et; it.forwardPos()) {
1116                 // avoid invalid nesting when selecting
1117                 if (!selection() || positionable(it, anchor_)) {
1118                         int xo = 0, yo = 0;
1119                         CursorSlice & cur = it.back();
1120                         cur.inset().getCursorPos(cur, xo, yo);
1121                         if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1122                                 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1123                                 lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
1124                                 // '<=' in order to take the last possible position
1125                                 // this is important for clicking behind \sum in e.g. '\sum_i a'
1126                                 if (d <= best_dist) {
1127                                         lyxerr << "*" << endl;
1128                                         best_dist   = d;
1129                                         best_cursor = it;
1130                                 }
1131                         }
1132                 }
1133         }
1134
1135         lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
1136         if (best_dist < 1e10)
1137                 setCursor(best_cursor, false);
1138         return best_dist < 1e10;
1139 }
1140
1141
1142 void LCursor::bruteFind2(int x, int y)
1143 {
1144         double best_dist = 1e10;
1145
1146         DocumentIterator it = *this;
1147         it.back().pos() = 0;
1148         DocumentIterator et = *this;
1149         et.back().pos() = et.back().asMathInset()->cell(et.back().idx_).size();
1150         for (int i = 0; ; ++i) {
1151                 int xo, yo;
1152                 CursorSlice & cur = it.back();
1153                 cur.inset().getCursorPos(cur, xo, yo);
1154                 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1155                 // '<=' in order to take the last possible position
1156                 // this is important for clicking behind \sum in e.g. '\sum_i a'
1157                 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
1158                 if (d <= best_dist) {
1159                         best_dist = d;
1160                         setCursor(it, false);
1161                 }
1162                 if (it == et)
1163                         break;
1164                 it.forwardPos();
1165         }
1166 }
1167
1168
1169 CursorSlice LCursor::normalAnchor()
1170 {
1171         if (anchor_.size() < depth()) {
1172                 resetAnchor();
1173                 lyxerr << "unusual Anchor size" << endl;
1174         }
1175         //lyx::BOOST_ASSERT(Anchor_.size() >= cursor.depth());
1176         // use Anchor on the same level as Cursor
1177         CursorSlice normal = anchor_[size() - 1];
1178 #if 0
1179         if (depth() < anchor_.size() && !(normal < xx())) {
1180                 // anchor is behind cursor -> move anchor behind the inset
1181                 ++normal.pos_;
1182         }
1183 #endif
1184         return normal;
1185 }
1186
1187
1188 void LCursor::handleFont(string const & font)
1189 {
1190         lyxerr << "LCursor::handleFont: " << font << endl;
1191         string safe;
1192         if (selection()) {
1193                 macroModeClose();
1194                 safe = grabAndEraseSelection();
1195         }
1196
1197         if (lastpos() != 0) {
1198                 // something left in the cell
1199                 if (pos() == 0) {
1200                         // cursor in first position
1201                         popLeft();
1202                 } else if (pos() == lastpos()) {
1203                         // cursor in last position
1204                         popRight();
1205                 } else {
1206                         // cursor in between. split cell
1207                         MathArray::iterator bt = cell().begin();
1208                         MathAtom at = createMathInset(font);
1209                         at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1210                         cell().erase(bt, bt + pos());
1211                         popLeft();
1212                         plainInsert(at);
1213                 }
1214         } else {
1215                 // nothing left in the cell
1216                 pullArg();
1217                 plainErase();
1218         }
1219         insert(safe);
1220 }
1221
1222
1223 void LCursor::message(string const & msg) const
1224 {
1225         bv().owner()->getLyXFunc().setMessage(msg);
1226 }
1227
1228
1229 void LCursor::errorMessage(string const & msg) const
1230 {
1231         bv().owner()->getLyXFunc().setErrorMessage(msg);
1232 }
1233
1234
1235 string LCursor::selectionAsString(bool label) const
1236 {
1237         if (!selection())
1238                 return string();
1239
1240         if (inTexted()) {
1241                 Buffer const & buffer = *bv().buffer();
1242
1243                 // should be const ...
1244                 ParagraphList::iterator startpit = text()->getPar(selBegin());
1245                 ParagraphList::iterator endpit = text()->getPar(selEnd());
1246                 size_t const startpos = selBegin().pos();
1247                 size_t const endpos = selEnd().pos();
1248
1249                 if (startpit == endpit)
1250                         return startpit->asString(buffer, startpos, endpos, label);
1251
1252                 // First paragraph in selection
1253                 string result =
1254                         startpit->asString(buffer, startpos, startpit->size(), label) + "\n\n";
1255
1256                 // The paragraphs in between (if any)
1257                 ParagraphList::iterator pit = startpit;
1258                 for (++pit; pit != endpit; ++pit)
1259                         result += pit->asString(buffer, 0, pit->size(), label) + "\n\n";
1260
1261                 // Last paragraph in selection
1262                 result += endpit->asString(buffer, 0, endpos, label);
1263
1264                 return result;
1265         }
1266
1267 #warning and mathed?
1268         return string();
1269 }
1270
1271
1272 string LCursor::currentState()
1273 {
1274         if (inMathed()) {
1275                 std::ostringstream os;
1276                 info(os);
1277                 return os.str();
1278         }
1279
1280         if (inTexted())
1281          return text()->currentState(*this);
1282
1283         return string();
1284 }
1285
1286
1287 // only used by the spellchecker
1288 void LCursor::replaceWord(string const & replacestring)
1289 {
1290         LyXText * t = text();
1291         BOOST_ASSERT(t);
1292
1293         t->replaceSelectionWithString(*this, replacestring);
1294         t->setSelectionRange(*this, replacestring.length());
1295
1296         // Go back so that replacement string is also spellchecked
1297         for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
1298                 t->cursorLeft(*this);
1299 }
1300
1301
1302 void LCursor::update()
1303 {
1304         bv().update();
1305 }
1306
1307
1308 string LCursor::getPossibleLabel()
1309 {
1310         return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1311 }
1312
1313
1314 Encoding const * LCursor::getEncoding() const
1315 {
1316         if (empty())
1317                 return 0;
1318         if (!bv().buffer())
1319                 return 0;
1320         int s = 0;
1321         // go up until first non-0 text is hit
1322         // (innermost text is 0 in mathed)
1323         for (s = size() - 1; s >= 0; --s)
1324                 if (operator[](s).text())
1325                         break;
1326         CursorSlice const & sl = operator[](s);
1327         LyXText & text = *sl.text();
1328         ParagraphList::iterator pit = text.getPar(sl.par());
1329         LyXFont font = pit->getFont(
1330                 bv().buffer()->params(), sl.pos(), outerFont(pit, text.paragraphs()));  
1331         return font.language()->encoding();
1332 }
1333
1334
1335 void LCursor::undispatched()
1336 {
1337         disp_.dispatched(false);
1338 }
1339
1340
1341 void LCursor::noUpdate()
1342 {
1343         disp_.update(false);
1344 }