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