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