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