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