]> git.lyx.org Git - lyx.git/blob - src/cursor.C
Glade tweakage: make OK button default in citation dialog
[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 #include "mathed/math_parser.h"
43
44 #include "support/limited_stack.h"
45
46 #include "frontends/LyXView.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::pit_type;
58
59 using std::string;
60 using std::vector;
61 using std::endl;
62 #ifndef CXX_GLOBAL_CSTD
63 using std::isalpha;
64 #endif
65 using std::min;
66 using std::swap;
67
68 namespace {
69
70         bool
71         positionable(DocIterator const & cursor, DocIterator const & anchor)
72         {
73                 // avoid deeper nested insets when selecting
74                 if (cursor.depth() > anchor.depth())
75                         return false;
76
77                 // anchor might be deeper, should have same path then
78                 for (size_t i = 0; i < cursor.depth(); ++i)
79                         if (&cursor[i].inset() != &anchor[i].inset())
80                                 return false;
81
82                 // position should be ok.
83                 return true;
84         }
85
86
87         // Find position closest to (x, y) in cell given by iter.
88         // Used only in mathed
89         DocIterator bruteFind2(LCursor const & c, int x, int y)
90         {
91                 double best_dist = std::numeric_limits<double>::max();
92
93                 DocIterator result;
94
95                 DocIterator it = c;
96                 it.top().pos() = 0;
97                 DocIterator et = c;
98                 et.top().pos() = et.top().asMathInset()->cell(et.top().idx()).size();
99                 for (size_t i = 0; ; ++i) {
100                         int xo;
101                         int yo;
102                         InsetBase const * inset = &it.inset();
103                         Point o = theCoords.getInsets().xy(inset);
104                         inset->cursorPos(it.top(), c.boundary(), xo, yo);
105                         // Convert to absolute
106                         xo += o.x_;
107                         yo += o.y_;
108                         double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
109                         // '<=' in order to take the last possible position
110                         // this is important for clicking behind \sum in e.g. '\sum_i a'
111                         lyxerr[Debug::DEBUG] << "i: " << i << " d: " << d
112                                 << " best: " << best_dist << endl;
113                         if (d <= best_dist) {
114                                 best_dist = d;
115                                 result = it;
116                         }
117                         if (it == et)
118                                 break;
119                         it.forwardPos();
120                 }
121                 return result;
122         }
123
124
125         /// moves position closest to (x, y) in given box
126         bool bruteFind(LCursor & cursor,
127                 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
128         {
129                 BOOST_ASSERT(!cursor.empty());
130                 InsetBase & inset = cursor[0].inset();
131
132                 CoordCache::InnerParPosCache const & cache = theCoords.getParPos().find(cursor.bottom().text())->second;
133                 // Get an iterator on the first paragraph in the cache
134                 DocIterator it(inset);
135                 it.push_back(CursorSlice(inset));
136                 it.pit() = cache.begin()->first;
137                 // Get an iterator after the last paragraph in the cache
138                 DocIterator et(inset);
139                 et.push_back(CursorSlice(inset));
140                 et.pit() = boost::prior(cache.end())->first;
141                 if (et.pit() >= et.lastpit())
142                         et = doc_iterator_end(inset);
143                 else
144                         ++et.pit();
145
146                 double best_dist = std::numeric_limits<double>::max();;
147                 DocIterator best_cursor = et;
148
149                 for ( ; it != et; it.forwardPos(true)) {
150                         // avoid invalid nesting when selecting
151                         if (!cursor.selection() || positionable(it, cursor.anchor_)) {
152                                 Point p = bv_funcs::getPos(it, false);
153                                 int xo = p.x_;
154                                 int yo = p.y_;
155                                 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
156                                         double const dx = xo - x;
157                                         double const dy = yo - y;
158                                         double const d = dx * dx + dy * dy;
159                                         // '<=' in order to take the last possible position
160                                         // this is important for clicking behind \sum in e.g. '\sum_i a'
161                                         if (d <= best_dist) {
162                                                 //      lyxerr << "*" << endl;
163                                                 best_dist   = d;
164                                                 best_cursor = it;
165                                         }
166                                 }
167                         }
168                 }
169
170                 if (best_cursor != et) {
171                         cursor.setCursor(best_cursor);
172                         return true;
173                 }
174
175                 return false;
176         }
177
178
179         /// moves position closest to (x, y) in given box
180         bool bruteFind3(LCursor & cur, int x, int y, bool up)
181         {
182                 BufferView & bv = cur.bv();
183                 int ylow  = up ? 0 : y + 1;
184                 int yhigh = up ? y - 1 : bv.workHeight();
185                 int xlow = 0;
186                 int xhigh = bv.workWidth();
187
188 // FIXME: bit more work needed to get 'from' and 'to' right.
189                 pit_type from = cur.bottom().pit();
190                 //pit_type to = cur.bottom().pit();
191                 //lyxerr << "Pit start: " << from << endl;
192
193                 //lyxerr << "bruteFind3: x: " << x << " y: " << y
194                 //      << " xlow: " << xlow << " xhigh: " << xhigh
195                 //      << " ylow: " << ylow << " yhigh: " << yhigh
196                 //      << endl;
197                 InsetBase & inset = bv.buffer()->inset();
198                 DocIterator it = doc_iterator_begin(inset);
199                 it.pit() = from;
200                 DocIterator et = doc_iterator_end(inset);
201
202                 double best_dist = std::numeric_limits<double>::max();
203                 DocIterator best_cursor = et;
204
205                 for ( ; it != et; it.forwardPos()) {
206                         // avoid invalid nesting when selecting
207                         if (bv_funcs::status(&bv, it) == bv_funcs::CUR_INSIDE
208                             && (!cur.selection() || positionable(it, cur.anchor_))) {
209                                 Point p = bv_funcs::getPos(it, false);
210                                 int xo = p.x_;
211                                 int yo = p.y_;
212                                 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
213                                         double const dx = xo - x;
214                                         double const dy = yo - y;
215                                         double const d = dx * dx + dy * dy;
216                                         //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
217                                         //      << " dx: " << dx << " dy: " << dy
218                                         //      << " idx: " << it.idx() << " pos: " << it.pos()
219                                         //      << " it:\n" << it
220                                         //      << endl;
221                                         // '<=' in order to take the last possible position
222                                         // this is important for clicking behind \sum in e.g. '\sum_i a'
223                                         if (d <= best_dist) {
224                                                 //lyxerr << "*" << endl;
225                                                 best_dist   = d;
226                                                 best_cursor = it;
227                                         }
228                                 }
229                         }
230                 }
231
232                 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
233                 if (best_cursor == et)
234                         return false;
235                 cur.setCursor(best_cursor);
236                 return true;
237         }
238
239 } // namespace anon
240
241
242 // be careful: this is called from the bv's constructor, too, so
243 // bv functions are not yet available!
244 LCursor::LCursor(BufferView & bv)
245         : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
246           selection_(false), mark_(false), logicalpos_(false)
247 {}
248
249
250 void LCursor::reset(InsetBase & inset)
251 {
252         clear();
253         push_back(CursorSlice(inset));
254         anchor_ = DocIterator(inset);
255         clearTargetX();
256         selection_ = false;
257         mark_ = false;
258 }
259
260
261 // this (intentionally) does neither touch anchor nor selection status
262 void LCursor::setCursor(DocIterator const & cur)
263 {
264         DocIterator::operator=(cur);
265 }
266
267
268 void LCursor::dispatch(FuncRequest const & cmd0)
269 {
270         lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
271                              << " cmd: " << cmd0 << '\n'
272                              << *this << endl;
273         if (empty())
274                 return;
275
276         fixIfBroken();
277         FuncRequest cmd = cmd0;
278         LCursor safe = *this;
279
280         for (; depth(); pop()) {
281                 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: "
282                         << cmd0 << endl << *this << endl;
283                 BOOST_ASSERT(pos() <= lastpos());
284                 BOOST_ASSERT(idx() <= lastidx());
285                 BOOST_ASSERT(pit() <= lastpit());
286
287                 // The common case is 'LFUN handled, need update', so make the
288                 // LFUN handler's life easier by assuming this as default value.
289                 // The handler can reset the update and val flags if necessary.
290                 disp_.update(true);
291                 disp_.dispatched(true);
292                 inset().dispatch(*this, cmd);
293                 if (disp_.dispatched())
294                         break;
295         }
296         // it completely to get a 'bomb early' behaviour in case this
297         // object will be used again.
298         if (!disp_.dispatched()) {
299                 lyxerr[Debug::DEBUG] << "RESTORING OLD CURSOR!" << endl;
300                 operator=(safe);
301                 disp_.dispatched(false);
302         }
303 }
304
305
306 DispatchResult LCursor::result() const
307 {
308         return disp_;
309 }
310
311
312 BufferView & LCursor::bv() const
313 {
314         BOOST_ASSERT(bv_);
315         return *bv_;
316 }
317
318
319 Buffer & LCursor::buffer() const
320 {
321         BOOST_ASSERT(bv_);
322         BOOST_ASSERT(bv_->buffer());
323         return *bv_->buffer();
324 }
325
326
327 void LCursor::pop()
328 {
329         BOOST_ASSERT(depth() >= 1);
330         pop_back();
331 }
332
333
334 void LCursor::push(InsetBase & p)
335 {
336         push_back(CursorSlice(p));
337 }
338
339
340 void LCursor::pushLeft(InsetBase & p)
341 {
342         BOOST_ASSERT(!empty());
343         //lyxerr << "Entering inset " << t << " left" << endl;
344         push(p);
345         p.idxFirst(*this);
346 }
347
348
349 bool LCursor::popLeft()
350 {
351         BOOST_ASSERT(!empty());
352         //lyxerr << "Leaving inset to the left" << endl;
353         inset().notifyCursorLeaves(*this);
354         if (depth() == 1)
355                 return false;
356         pop();
357         return true;
358 }
359
360
361 bool LCursor::popRight()
362 {
363         BOOST_ASSERT(!empty());
364         //lyxerr << "Leaving inset to the right" << endl;
365         inset().notifyCursorLeaves(*this);
366         if (depth() == 1)
367                 return false;
368         pop();
369         ++pos();
370         return true;
371 }
372
373
374 int LCursor::currentMode()
375 {
376         BOOST_ASSERT(!empty());
377         for (int i = depth() - 1; i >= 0; --i) {
378                 int res = operator[](i).inset().currentMode();
379                 if (res != InsetBase::UNDECIDED_MODE)
380                         return res;
381         }
382         return InsetBase::TEXT_MODE;
383 }
384
385
386 void LCursor::getPos(int & x, int & y) const
387 {
388         Point p = bv_funcs::getPos(*this, boundary());
389         x = p.x_;
390         y = p.y_;
391 }
392
393
394 void LCursor::resetAnchor()
395 {
396         anchor_ = *this;
397 }
398
399
400
401 bool LCursor::posLeft()
402 {
403         if (pos() == 0)
404                 return false;
405         --pos();
406         return true;
407 }
408
409
410 bool LCursor::posRight()
411 {
412         if (pos() == lastpos())
413                 return false;
414         ++pos();
415         return true;
416 }
417
418
419 CursorSlice LCursor::anchor() const
420 {
421         BOOST_ASSERT(anchor_.depth() >= depth());
422         CursorSlice normal = anchor_[depth() - 1];
423         if (depth() < anchor_.depth() && top() <= normal) {
424                 // anchor is behind cursor -> move anchor behind the inset
425                 ++normal.pos();
426         }
427         return normal;
428 }
429
430
431 CursorSlice LCursor::selBegin() const
432 {
433         if (!selection())
434                 return top();
435         return anchor() < top() ? anchor() : top();
436 }
437
438
439 CursorSlice LCursor::selEnd() const
440 {
441         if (!selection())
442                 return top();
443         return anchor() > top() ? anchor() : top();
444 }
445
446
447 DocIterator LCursor::selectionBegin() const
448 {
449         if (!selection())
450                 return *this;
451         DocIterator di = (anchor() < top() ? anchor_ : *this);
452         di.resize(depth());
453         return di;
454 }
455
456
457 DocIterator LCursor::selectionEnd() const
458 {
459         if (!selection())
460                 return *this;
461         DocIterator di = (anchor() > top() ? anchor_ : *this);
462         if (di.depth() > depth()) {
463                 di.resize(depth());
464                 ++di.pos();
465         }
466         return di;
467 }
468
469
470 void LCursor::setSelection()
471 {
472         selection() = true;
473         // A selection with no contents is not a selection
474 #ifdef WITH_WARNINGS
475 #warning doesnt look ok
476 #endif
477         if (pit() == anchor().pit() && pos() == anchor().pos())
478                 selection() = false;
479 }
480
481
482 void LCursor::setSelection(DocIterator const & where, size_t n)
483 {
484         setCursor(where);
485         selection() = true;
486         anchor_ = where;
487         pos() += n;
488 }
489
490
491 void LCursor::clearSelection()
492 {
493         selection() = false;
494         mark() = false;
495         resetAnchor();
496         bv().unsetXSel();
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 MathNestInset).
570 //
571 ///////////////////////////////////////////////////////////////////
572
573 #include "mathed/math_charinset.h"
574 #include "mathed/math_factory.h"
575 #include "mathed/math_gridinset.h"
576 #include "mathed/math_macroarg.h"
577 #include "mathed/math_mathmlstream.h"
578 #include "mathed/math_scriptinset.h"
579 #include "mathed/math_support.h"
580 #include "mathed/math_unknowninset.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 MathCharInset(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                 MathUnknownInset * 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         MathUnknownInset * 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         MathNestInset * const in = inset().asMathInset()->asNestInset();
864         if (in && in->interpret(*this, s))
865                 return true;
866         plainInsert(createMathInset(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         MathUnknownInset const * p = prevAtom()->asUnknownInset();
916         return p && !p->final();
917 }
918
919
920 MathUnknownInset * 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().asMathInset()->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 goal
989         if (x_target() == -1)
990                 x_target() = xo;
991         else
992                 xo = x_target();
993
994         // try neigbouring script insets
995         if (!selection()) {
996                 // try left
997                 if (pos() != 0) {
998                         MathScriptInset const * p = prevAtom()->asScriptInset();
999                         if (p && p->has(up)) {
1000                                 --pos();
1001                                 push(*const_cast<MathScriptInset*>(p));
1002                                 idx() = p->idxOfScript(up);
1003                                 pos() = lastpos();
1004                                 return true;
1005                         }
1006                 }
1007
1008                 // try right
1009                 if (pos() != lastpos()) {
1010                         MathScriptInset const * p = nextAtom()->asScriptInset();
1011                         if (p && p->has(up)) {
1012                                 push(*const_cast<MathScriptInset*>(p));
1013                                 idx() = p->idxOfScript(up);
1014                                 pos() = 0;
1015                                 return true;
1016                         }
1017                 }
1018         }
1019
1020 // FIXME: Switch this on for more robust movement
1021 #if 0
1022
1023         return bruteFind3(*this, xo, yo, up);
1024
1025 #else
1026         //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1027         //if (up)
1028         //      yhigh = yo - 4;
1029         //else
1030         //      ylow = yo + 4;
1031         //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
1032         //      lyxerr << "updown: handled by brute find in the same cell" << endl;
1033         //      return true;
1034         //}
1035
1036         // try to find an inset that knows better then we
1037         while (true) {
1038                 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1039                 // ask inset first
1040                 if (inset().idxUpDown(*this, up)) {
1041                         //lyxerr << "idxUpDown triggered" << endl;
1042                         // try to find best position within this inset
1043                         if (!selection())
1044                                 setCursor(bruteFind2(*this, xo, yo));
1045                         return true;
1046                 }
1047
1048                 // no such inset found, just take something "above"
1049                 if (!popLeft()) {
1050                         //lyxerr << "updown: popleft failed (strange case)" << endl;
1051                         int ylow  = up ? 0 : yo + 1;
1052                         int yhigh = up ? yo - 1 : bv().workHeight();
1053                         return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
1054                 }
1055
1056                 // any improvement so far?
1057                 //lyxerr << "updown: popLeft succeeded" << endl;
1058                 int xnew;
1059                 int ynew;
1060                 getPos(xnew, ynew);
1061                 if (up ? ynew < yo : ynew > yo)
1062                         return true;
1063         }
1064
1065         // we should not come here.
1066         BOOST_ASSERT(false);
1067 #endif
1068 }
1069
1070
1071 void LCursor::handleFont(string const & font)
1072 {
1073         lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << ": " << font << endl;
1074         string safe;
1075         if (selection()) {
1076                 macroModeClose();
1077                 safe = lyx::cap::grabAndEraseSelection(*this);
1078         }
1079
1080         if (lastpos() != 0) {
1081                 // something left in the cell
1082                 if (pos() == 0) {
1083                         // cursor in first position
1084                         popLeft();
1085                 } else if (pos() == lastpos()) {
1086                         // cursor in last position
1087                         popRight();
1088                 } else {
1089                         // cursor in between. split cell
1090                         MathArray::iterator bt = cell().begin();
1091                         MathAtom at = createMathInset(font);
1092                         at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1093                         cell().erase(bt, bt + pos());
1094                         popLeft();
1095                         plainInsert(at);
1096                 }
1097         } else {
1098                 // nothing left in the cell
1099                 pullArg();
1100                 plainErase();
1101         }
1102         insert(safe);
1103 }
1104
1105
1106 void LCursor::message(string const & msg) const
1107 {
1108         bv().owner()->getLyXFunc().setMessage(msg);
1109 }
1110
1111
1112 void LCursor::errorMessage(string const & msg) const
1113 {
1114         bv().owner()->getLyXFunc().setErrorMessage(msg);
1115 }
1116
1117
1118 string LCursor::selectionAsString(bool label) const
1119 {
1120         if (!selection())
1121                 return string();
1122
1123         if (inTexted()) {
1124                 Buffer const & buffer = *bv().buffer();
1125                 ParagraphList const & pars = text()->paragraphs();
1126
1127                 // should be const ...
1128                 pit_type startpit = selBegin().pit();
1129                 pit_type endpit = selEnd().pit();
1130                 size_t const startpos = selBegin().pos();
1131                 size_t const endpos = selEnd().pos();
1132
1133                 if (startpit == endpit)
1134                         return pars[startpit].asString(buffer, startpos, endpos, label);
1135
1136                 // First paragraph in selection
1137                 string result = pars[startpit].
1138                         asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1139
1140                 // The paragraphs in between (if any)
1141                 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1142                         Paragraph const & par = pars[pit];
1143                         result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1144                 }
1145
1146                 // Last paragraph in selection
1147                 result += pars[endpit].asString(buffer, 0, endpos, label);
1148
1149                 return result;
1150         }
1151
1152         if (inMathed())
1153                 return lyx::cap::grabSelection(*this);
1154
1155         return string();
1156 }
1157
1158
1159 string LCursor::currentState()
1160 {
1161         if (inMathed()) {
1162                 std::ostringstream os;
1163                 info(os);
1164                 return os.str();
1165         }
1166
1167         if (inTexted())
1168                 return text()->currentState(*this);
1169
1170         return string();
1171 }
1172
1173
1174 string LCursor::getPossibleLabel()
1175 {
1176         return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1177 }
1178
1179
1180 Encoding const * LCursor::getEncoding() const
1181 {
1182         if (empty())
1183                 return 0;
1184         if (!bv().buffer())
1185                 return 0;
1186         int s = 0;
1187         // go up until first non-0 text is hit
1188         // (innermost text is 0 in mathed)
1189         for (s = depth() - 1; s >= 0; --s)
1190                 if (operator[](s).text())
1191                         break;
1192         CursorSlice const & sl = operator[](s);
1193         LyXText const & text = *sl.text();
1194         LyXFont font = text.getPar(sl.pit()).getFont(
1195                 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1196         return font.language()->encoding();
1197 }
1198
1199
1200 void LCursor::undispatched()
1201 {
1202         disp_.dispatched(false);
1203 }
1204
1205
1206 void LCursor::dispatched()
1207 {
1208         disp_.dispatched(true);
1209 }
1210
1211
1212 void LCursor::needsUpdate()
1213 {
1214         disp_.update(true);
1215 }
1216
1217
1218 void LCursor::noUpdate()
1219 {
1220         disp_.update(false);
1221 }
1222
1223
1224 LyXFont LCursor::getFont() const
1225 {
1226         // HACK. far from being perfect...
1227         int s = 0;
1228         // go up until first non-0 text is hit
1229         // (innermost text is 0 in mathed)
1230         for (s = depth() - 1; s >= 0; --s)
1231                 if (operator[](s).text())
1232                         break;
1233         CursorSlice const & sl = operator[](s);
1234         LyXText const & text = *sl.text();
1235         LyXFont font = text.getPar(sl.pit()).getFont(
1236                 bv().buffer()->params(),
1237                 sl.pos(),
1238                 outerFont(sl.pit(), text.paragraphs()));
1239
1240         return font;
1241 }
1242
1243
1244 void LCursor::fixIfBroken()
1245 {
1246         // find out last good level
1247         LCursor copy = *this;
1248         size_t newdepth = depth();
1249         while (!copy.empty()) {
1250                 if (copy.idx() > copy.lastidx()) {
1251                         lyxerr << "wrong idx " << copy.idx()
1252                                << ", max is " << copy.lastidx()
1253                                << " at level " << copy.depth()
1254                                << ". Trying to correct this."  << endl;
1255                         newdepth = copy.depth() - 1;
1256                 }
1257                 else if (copy.pit() > copy.lastpit()) {
1258                         lyxerr << "wrong pit " << copy.pit()
1259                                << ", max is " << copy.lastpit()
1260                                << " at level " << copy.depth()
1261                                << ". Trying to correct this."  << endl;
1262                         newdepth = copy.depth() - 1;
1263                 }
1264                 else if (copy.pos() > copy.lastpos()) {
1265                         lyxerr << "wrong pos " << copy.pos()
1266                                << ", max is " << copy.lastpos()
1267                                << " at level " << copy.depth()
1268                                << ". Trying to correct this."  << endl;
1269                         newdepth = copy.depth() - 1;
1270                 }
1271                 copy.pop();
1272         }
1273         // shrink cursor to a size where everything is valid, possibly
1274         // leaving insets
1275         while (depth() > newdepth) {
1276                 pop();
1277                 lyxerr << "correcting cursor to level " << depth() << endl;
1278         }
1279 }