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