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