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