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