]> git.lyx.org Git - lyx.git/blob - src/cursor.C
d8cc1ba53a760d2670e17386c4d9cb9a5a3aabda
[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(*this, 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         niceInsert(createMathInset(name));      
874 }
875
876
877 string LCursor::macroName()
878 {
879         return inMacroMode() ? activeMacro()->name() : string();
880 }
881
882
883 void LCursor::handleNest(MathAtom const & a, int c)
884 {
885         //lyxerr << "LCursor::handleNest: " << c << endl;
886         MathAtom t = a;
887         asArray(grabAndEraseSelection(), t.nucleus()->cell(c));
888         insert(t);
889         posLeft();
890         pushLeft(*nextInset());
891 }
892
893
894 int LCursor::targetX() const
895 {
896         if (x_target() != -1)
897                 return x_target();
898         int x = 0;
899         int y = 0;
900         getPos(x, y);
901         return x;
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 void LCursor::pullArg()
921 {
922 #ifdef WITH_WARNINGS
923 #warning Look here
924 #endif
925         MathArray ar = cell();
926         if (popLeft() && inMathed()) {
927                 plainErase();
928                 cell().insert(pos(), ar);
929                 resetAnchor();
930         } else {
931                 //formula()->mutateToText();
932         }
933 }
934
935
936 void LCursor::touch()
937 {
938 #ifdef WITH_WARNINGS
939 #warning look here
940 #endif
941 #if 0
942         DocIterator::const_iterator it = begin();
943         DocIterator::const_iterator et = end();
944         for ( ; it != et; ++it)
945                 it->cell().touch();
946 #endif
947 }
948
949
950 void LCursor::normalize()
951 {
952         if (idx() >= nargs()) {
953                 lyxerr << "this should not really happen - 1: "
954                        << idx() << ' ' << nargs()
955                        << " in: " << &inset() << endl;
956         }
957         idx() = min(idx(), lastidx());
958
959         if (pos() > lastpos()) {
960                 lyxerr << "this should not really happen - 2: "
961                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
962                        << " in atom: '";
963                 WriteStream wi(lyxerr, false, true);
964                 inset().asMathInset()->write(wi);
965                 lyxerr << endl;
966         }
967         pos() = min(pos(), lastpos());
968 }
969
970
971 bool LCursor::goUpDown(bool up)
972 {
973         // Be warned: The 'logic' implemented in this function is highly
974         // fragile. A distance of one pixel or a '<' vs '<=' _really
975         // matters. So fiddle around with it only if you think you know
976         // what you are doing!
977
978   int xo = 0;
979         int yo = 0;
980         getPos(xo, yo);
981
982         // check if we had something else in mind, if not, this is the future goal
983         if (x_target() == -1)
984                 x_target() = xo;
985         else
986                 xo = x_target();
987
988         // try neigbouring script insets
989         if (!selection()) {
990                 // try left
991                 if (pos() != 0) {
992                         MathScriptInset const * p = prevAtom()->asScriptInset();
993                         if (p && p->has(up)) {
994                                 --pos();
995                                 push(inset());
996                                 idx() = up; // the superscript has index 1
997                                 pos() = lastpos();
998                                 //lyxerr << "updown: handled by scriptinset to the left" << endl;
999                                 return true;
1000                         }
1001                 }
1002
1003                 // try right
1004                 if (pos() != lastpos()) {
1005                         MathScriptInset const * p = nextAtom()->asScriptInset();
1006                         if (p && p->has(up)) {
1007                                 push(inset());
1008                                 idx() = up;
1009                                 pos() = 0;
1010                                 //lyxerr << "updown: handled by scriptinset to the right" << endl;
1011                                 return true;
1012                         }
1013                 }
1014         }
1015
1016         // try current cell for e.g. text insets
1017         if (inset().idxUpDown2(*this, up))
1018                 return true;
1019
1020         //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1021         //if (up)
1022         //      yhigh = yo - 4;
1023         //else
1024         //      ylow = yo + 4;
1025         //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1026         //      lyxerr << "updown: handled by brute find in the same cell" << endl;
1027         //      return true;
1028         //}
1029
1030         // try to find an inset that knows better then we
1031         while (1) {
1032                 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1033                 // ask inset first
1034                 if (inset().idxUpDown(*this, up)) {
1035                         // try to find best position within this inset
1036                         if (!selection())
1037                                 bruteFind2(xo, yo);
1038                         return true;
1039                 }
1040
1041                 // no such inset found, just take something "above"
1042                 //lyxerr << "updown: handled by strange case" << endl;
1043                 if (!popLeft()) {
1044                         int ylow  = up ? 0 : yo + 1;
1045                         int yhigh = up ? yo - 1 : bv().workHeight();
1046                         return bruteFind(xo, yo, 0, bv().workWidth(), ylow, yhigh);
1047                 }
1048
1049                 // any improvement so far?
1050                 int xnew, ynew;
1051                 getPos(xnew, ynew);
1052                 if (up ? ynew < yo : ynew > yo)
1053                         return true;
1054         }
1055 }
1056
1057
1058 bool LCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1059 {
1060         BOOST_ASSERT(!empty());
1061         par_type beg, end;
1062         CursorSlice bottom = operator[](0);
1063         LyXText * text = bottom.text();
1064         BOOST_ASSERT(text);
1065         getParsInRange(text->paragraphs(), ylow, yhigh, beg, end);
1066
1067         DocIterator it = doc_iterator_begin(bv().buffer()->inset());
1068         DocIterator et = doc_iterator_end(bv().buffer()->inset());
1069         //lyxerr << "x: " << x << " y: " << y << endl;
1070         //lyxerr << "xlow: " << xlow << " ylow: " << ylow << endl;
1071         //lyxerr << "xhigh: " << xhigh << " yhigh: " << yhigh << endl;
1072
1073         it.par() = beg;
1074         //et.par() = text->parOffset(end);
1075
1076         double best_dist = 10e10;
1077         DocIterator best_cursor = it;
1078
1079         for ( ; it != et; it.forwardPos()) {
1080                 // avoid invalid nesting when selecting
1081                 if (!selection() || positionable(it, anchor_)) {
1082                         int xo = 0, yo = 0;
1083                         LCursor cur = *this;
1084                         cur.setCursor(it, false);
1085                         cur.inset().getCursorPos(cur, xo, yo);
1086                         if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1087                                 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1088                                 //lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
1089                                 // '<=' in order to take the last possible position
1090                                 // this is important for clicking behind \sum in e.g. '\sum_i a'
1091                                 if (d <= best_dist) {
1092                                         //lyxerr << "*" << endl;
1093                                         best_dist   = d;
1094                                         best_cursor = it;
1095                                 }
1096                         }
1097                 }
1098         }
1099
1100         //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
1101         if (best_dist < 1e10)
1102                 setCursor(best_cursor, false);
1103         return best_dist < 1e10;
1104 }
1105
1106
1107 void LCursor::bruteFind2(int x, int y)
1108 {
1109         double best_dist = 1e10;
1110
1111         DocIterator it = *this;
1112         it.back().pos() = 0;
1113         DocIterator et = *this;
1114         et.back().pos() = et.back().asMathInset()->cell(et.back().idx()).size();
1115         for (int i = 0; ; ++i) {
1116                 int xo, yo;
1117                 LCursor cur = *this;
1118                 cur.setCursor(it, false);
1119                 cur.inset().getCursorPos(cur, xo, yo);
1120                 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1121                 // '<=' in order to take the last possible position
1122                 // this is important for clicking behind \sum in e.g. '\sum_i a'
1123                 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
1124                 if (d <= best_dist) {
1125                         best_dist = d;
1126                         setCursor(it, false);
1127                 }
1128                 if (it == et)
1129                         break;
1130                 it.forwardPos();
1131         }
1132 }
1133
1134
1135 void LCursor::handleFont(string const & font)
1136 {
1137         lyxerr << "LCursor::handleFont: " << font << endl;
1138         string safe;
1139         if (selection()) {
1140                 macroModeClose();
1141                 safe = grabAndEraseSelection();
1142         }
1143
1144         if (lastpos() != 0) {
1145                 // something left in the cell
1146                 if (pos() == 0) {
1147                         // cursor in first position
1148                         popLeft();
1149                 } else if (pos() == lastpos()) {
1150                         // cursor in last position
1151                         popRight();
1152                 } else {
1153                         // cursor in between. split cell
1154                         MathArray::iterator bt = cell().begin();
1155                         MathAtom at = createMathInset(font);
1156                         at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1157                         cell().erase(bt, bt + pos());
1158                         popLeft();
1159                         plainInsert(at);
1160                 }
1161         } else {
1162                 // nothing left in the cell
1163                 pullArg();
1164                 plainErase();
1165         }
1166         insert(safe);
1167 }
1168
1169
1170 void LCursor::message(string const & msg) const
1171 {
1172         bv().owner()->getLyXFunc().setMessage(msg);
1173 }
1174
1175
1176 void LCursor::errorMessage(string const & msg) const
1177 {
1178         bv().owner()->getLyXFunc().setErrorMessage(msg);
1179 }
1180
1181
1182 string LCursor::selectionAsString(bool label) const
1183 {
1184         if (!selection())
1185                 return string();
1186
1187         if (inTexted()) {
1188                 Buffer const & buffer = *bv().buffer();
1189                 ParagraphList & pars = text()->paragraphs();
1190
1191                 // should be const ...
1192                 par_type startpit = selBegin().par();
1193                 par_type endpit = selEnd().par();
1194                 size_t const startpos = selBegin().pos();
1195                 size_t const endpos = selEnd().pos();
1196
1197                 if (startpit == endpit)
1198                         return pars[startpit].asString(buffer, startpos, endpos, label);
1199
1200                 // First paragraph in selection
1201                 string result = pars[startpit].
1202                         asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1203
1204                 // The paragraphs in between (if any)
1205                 for (par_type pit = startpit + 1; pit != endpit; ++pit) {
1206                         Paragraph & par = pars[pit];
1207                         result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1208                 }
1209
1210                 // Last paragraph in selection
1211                 result += pars[endpit].asString(buffer, 0, endpos, label);
1212
1213                 return result;
1214         }
1215
1216 #ifdef WITH_WARNINGS
1217 #warning and mathed?
1218 #endif
1219         return string();
1220 }
1221
1222
1223 string LCursor::currentState()
1224 {
1225         if (inMathed()) {
1226                 std::ostringstream os;
1227                 info(os);
1228                 return os.str();
1229         }
1230
1231         if (inTexted())
1232          return text()->currentState(*this);
1233
1234         return string();
1235 }
1236
1237
1238 string LCursor::getPossibleLabel()
1239 {
1240         return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1241 }
1242
1243
1244 Encoding const * LCursor::getEncoding() const
1245 {
1246         if (empty())
1247                 return 0;
1248         if (!bv().buffer())
1249                 return 0;
1250         int s = 0;
1251         // go up until first non-0 text is hit
1252         // (innermost text is 0 in mathed)
1253         for (s = size() - 1; s >= 0; --s)
1254                 if (operator[](s).text())
1255                         break;
1256         CursorSlice const & sl = operator[](s);
1257         LyXText & text = *sl.text();
1258         LyXFont font = text.getPar(sl.par()).getFont(
1259                 bv().buffer()->params(), sl.pos(), outerFont(sl.par(), text.paragraphs()));
1260         return font.language()->encoding();
1261 }
1262
1263
1264 void LCursor::undispatched()
1265 {
1266         disp_.dispatched(false);
1267 }
1268
1269
1270 void LCursor::dispatched()
1271 {
1272         disp_.dispatched(true);
1273 }
1274
1275
1276 void LCursor::noUpdate()
1277 {
1278         disp_.update(false);
1279 }