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