]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathNest.cpp
fix off-by-two drawing error
[lyx.git] / src / mathed / InsetMathNest.cpp
1 /**
2  * \file InsetMathNest.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetMathNest.h"
14
15 #include "InsetMathArray.h"
16 #include "InsetMathBig.h"
17 #include "InsetMathBox.h"
18 #include "InsetMathBrace.h"
19 #include "InsetMathColor.h"
20 #include "InsetMathComment.h"
21 #include "InsetMathDelim.h"
22 #include "InsetMathHull.h"
23 #include "InsetMathRef.h"
24 #include "InsetMathScript.h"
25 #include "InsetMathSpace.h"
26 #include "InsetMathSymbol.h"
27 #include "InsetMathUnknown.h"
28 #include "MathCompletionList.h"
29 #include "MathData.h"
30 #include "MathFactory.h"
31 #include "MathMacro.h"
32 #include "MathMacroArgument.h"
33 #include "MathParser.h"
34 #include "MathStream.h"
35 #include "MathSupport.h"
36
37 #include "Bidi.h"
38 #include "Buffer.h"
39 #include "BufferView.h"
40 #include "CoordCache.h"
41 #include "Cursor.h"
42 #include "CutAndPaste.h"
43 #include "DispatchResult.h"
44 #include "FuncRequest.h"
45 #include "FuncStatus.h"
46 #include "LyXFunc.h"
47 #include "LyXRC.h"
48 #include "OutputParams.h"
49 #include "Text.h"
50
51 #include "frontends/Clipboard.h"
52 #include "frontends/Painter.h"
53 #include "frontends/Selection.h"
54
55 #include "support/lassert.h"
56 #include "support/debug.h"
57 #include "support/gettext.h"
58 #include "support/lstrings.h"
59 #include "support/textutils.h"
60 #include "support/docstream.h"
61
62 #include <algorithm>
63 #include <sstream>
64
65 using namespace std;
66 using namespace lyx::support;
67
68 namespace lyx {
69
70 using cap::copySelection;
71 using cap::grabAndEraseSelection;
72 using cap::cutSelection;
73 using cap::replaceSelection;
74 using cap::selClearOrDel;
75
76
77 InsetMathNest::InsetMathNest(idx_type nargs)
78         : cells_(nargs), lock_(false), mouse_hover_(false)
79 {}
80
81
82 InsetMathNest::InsetMathNest(InsetMathNest const & inset)
83         : InsetMath(inset), cells_(inset.cells_), lock_(inset.lock_),
84           mouse_hover_(false)
85 {}
86
87
88 InsetMathNest & InsetMathNest::operator=(InsetMathNest const & inset)
89 {
90         cells_ = inset.cells_;
91         lock_ = inset.lock_;
92         mouse_hover_ = false;
93         InsetMath::operator=(inset);
94         return *this;
95 }
96
97
98 InsetMath::idx_type InsetMathNest::nargs() const
99 {
100         return cells_.size();
101 }
102
103
104 void InsetMathNest::cursorPos(BufferView const & bv,
105                 CursorSlice const & sl, bool /*boundary*/,
106                 int & x, int & y) const
107 {
108 // FIXME: This is a hack. Ideally, the coord cache should not store
109 // absolute positions, but relative ones. This would mean to call
110 // setXY() not in MathData::draw(), but in the parent insets' draw()
111 // with the correctly adjusted x,y values. But this means that we'd have
112 // to touch all (math)inset's draw() methods. Right now, we'll store
113 // absolute value, and make them here relative, only to make them
114 // absolute again when actually drawing the cursor. What a mess.
115         LASSERT(&sl.inset() == this, /**/);
116         MathData const & ar = sl.cell();
117         CoordCache const & coord_cache = bv.coordCache();
118         if (!coord_cache.getArrays().has(&ar)) {
119                 // this can (semi-)legally happen if we just created this cell
120                 // and it never has been drawn before. So don't ASSERT.
121                 //lyxerr << "no cached data for array " << &ar << endl;
122                 x = 0;
123                 y = 0;
124                 return;
125         }
126         Point const pt = coord_cache.getArrays().xy(&ar);
127         if (!coord_cache.getInsets().has(this)) {
128                 // same as above
129                 //lyxerr << "no cached data for inset " << this << endl;
130                 x = 0;
131                 y = 0;
132                 return;
133         }
134         Point const pt2 = coord_cache.getInsets().xy(this);
135         //lyxerr << "retrieving position cache for MathData "
136         //      << pt.x_ << ' ' << pt.y_ << endl;
137         x = pt.x_ - pt2.x_ + ar.pos2x(&bv, sl.pos());
138         y = pt.y_ - pt2.y_;
139 //      lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
140 //              << " asc: " << ascent() << "  des: " << descent()
141 //              << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
142         // move cursor visually into empty cells ("blue rectangles");
143         if (ar.empty())
144                 x += 2;
145 }
146
147
148 void InsetMathNest::metrics(MetricsInfo const & mi) const
149 {
150         MetricsInfo m = mi;
151         for (idx_type i = 0, n = nargs(); i != n; ++i) {
152                 Dimension dim;
153                 cell(i).metrics(m, dim);
154         }
155 }
156
157
158 bool InsetMathNest::idxNext(Cursor & cur) const
159 {
160         LASSERT(&cur.inset() == this, /**/);
161         if (cur.idx() == cur.lastidx())
162                 return false;
163         ++cur.idx();
164         cur.pos() = 0;
165         return true;
166 }
167
168
169 bool InsetMathNest::idxForward(Cursor & cur) const
170 {
171         return idxNext(cur);
172 }
173
174
175 bool InsetMathNest::idxPrev(Cursor & cur) const
176 {
177         LASSERT(&cur.inset() == this, /**/);
178         if (cur.idx() == 0)
179                 return false;
180         --cur.idx();
181         cur.pos() = cur.lastpos();
182         return true;
183 }
184
185
186 bool InsetMathNest::idxBackward(Cursor & cur) const
187 {
188         return idxPrev(cur);
189 }
190
191
192 bool InsetMathNest::idxFirst(Cursor & cur) const
193 {
194         LASSERT(&cur.inset() == this, /**/);
195         if (nargs() == 0)
196                 return false;
197         cur.idx() = 0;
198         cur.pos() = 0;
199         return true;
200 }
201
202
203 bool InsetMathNest::idxLast(Cursor & cur) const
204 {
205         LASSERT(&cur.inset() == this, /**/);
206         if (nargs() == 0)
207                 return false;
208         cur.idx() = cur.lastidx();
209         cur.pos() = cur.lastpos();
210         return true;
211 }
212
213
214 void InsetMathNest::dump() const
215 {
216         odocstringstream oss;
217         WriteStream os(oss);
218         os << "---------------------------------------------\n";
219         write(os);
220         os << "\n";
221         for (idx_type i = 0, n = nargs(); i != n; ++i)
222                 os << cell(i) << "\n";
223         os << "---------------------------------------------\n";
224         lyxerr << to_utf8(oss.str());
225 }
226
227
228 void InsetMathNest::draw(PainterInfo & pi, int x, int y) const
229 {
230 #if 0
231         if (lock_)
232                 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
233                                         Color_mathlockbg);
234 #endif
235         setPosCache(pi, x, y);
236 }
237
238
239 void InsetMathNest::drawSelection(PainterInfo & pi, int x, int y) const
240 {
241         BufferView & bv = *pi.base.bv;
242         // this should use the x/y values given, not the cached values
243         Cursor & cur = bv.cursor();
244         if (!cur.selection())
245                 return;
246         if (&cur.inset() != this)
247                 return;
248
249         // FIXME: hack to get position cache warm
250         bool const original_drawing_state = pi.pain.isDrawingEnabled();
251         pi.pain.setDrawingEnabled(false);
252         draw(pi, x, y);
253         pi.pain.setDrawingEnabled(original_drawing_state);
254
255         CursorSlice s1 = cur.selBegin();
256         CursorSlice s2 = cur.selEnd();
257
258         //lyxerr << "InsetMathNest::drawing selection: "
259         //      << " s1: " << s1 << " s2: " << s2 << endl;
260         if (s1.idx() == s2.idx()) {
261                 MathData const & c = cell(s1.idx());
262                 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
263                 int x1 = g.pos.x_ + c.pos2x(pi.base.bv, s1.pos());
264                 int y1 = g.pos.y_ - g.dim.ascent();
265                 int x2 = g.pos.x_ + c.pos2x(pi.base.bv, s2.pos());
266                 int y2 = g.pos.y_ + g.dim.descent();
267                 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
268         //lyxerr << "InsetMathNest::drawing selection 3: "
269         //      << " x1: " << x1 << " x2: " << x2
270         //      << " y1: " << y1 << " y2: " << y2 << endl;
271         } else {
272                 for (idx_type i = 0; i < nargs(); ++i) {
273                         if (idxBetween(i, s1.idx(), s2.idx())) {
274                                 MathData const & c = cell(i);
275                                 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
276                                 int x1 = g.pos.x_;
277                                 int y1 = g.pos.y_ - g.dim.ascent();
278                                 int x2 = g.pos.x_ + g.dim.width();
279                                 int y2 = g.pos.y_ + g.dim.descent();
280                                 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
281                         }
282                 }
283         }
284 }
285
286
287 void InsetMathNest::validate(LaTeXFeatures & features) const
288 {
289         for (idx_type i = 0; i < nargs(); ++i)
290                 cell(i).validate(features);
291 }
292
293
294 void InsetMathNest::replace(ReplaceData & rep)
295 {
296         for (idx_type i = 0; i < nargs(); ++i)
297                 cell(i).replace(rep);
298 }
299
300
301 bool InsetMathNest::contains(MathData const & ar) const
302 {
303         for (idx_type i = 0; i < nargs(); ++i)
304                 if (cell(i).contains(ar))
305                         return true;
306         return false;
307 }
308
309
310 bool InsetMathNest::lock() const
311 {
312         return lock_;
313 }
314
315
316 void InsetMathNest::lock(bool l)
317 {
318         lock_ = l;
319 }
320
321
322 bool InsetMathNest::isActive() const
323 {
324         return nargs() > 0;
325 }
326
327
328 MathData InsetMathNest::glue() const
329 {
330         MathData ar;
331         for (size_t i = 0; i < nargs(); ++i)
332                 ar.append(cell(i));
333         return ar;
334 }
335
336
337 void InsetMathNest::write(WriteStream & os) const
338 {
339         ModeSpecifier specifier(os, currentMode());
340         docstring const latex_name = name();
341         os << '\\' << latex_name;
342         for (size_t i = 0; i < nargs(); ++i)
343                 os << '{' << cell(i) << '}';
344         if (nargs() == 0)
345                 os.pendingSpace(true);
346         if (lock_ && !os.latex()) {
347                 os << "\\lyxlock";
348                 os.pendingSpace(true);
349         }
350 }
351
352
353 void InsetMathNest::normalize(NormalStream & os) const
354 {
355         os << '[' << name();
356         for (size_t i = 0; i < nargs(); ++i)
357                 os << ' ' << cell(i);
358         os << ']';
359 }
360
361
362 int InsetMathNest::latex(odocstream & os, OutputParams const & runparams) const
363 {
364         WriteStream wi(os, runparams.moving_arg, true, runparams.dryrun,
365                         runparams.encoding);
366         write(wi);
367         return wi.line();
368 }
369
370
371 bool InsetMathNest::setMouseHover(bool mouse_hover)
372 {
373         mouse_hover_ = mouse_hover;
374         return true;
375 }
376
377
378 bool InsetMathNest::notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
379 {
380         // FIXME: look here
381 #if 0
382         MathData & ar = cur.cell();
383         // remove base-only "scripts"
384         for (pos_type i = 0; i + 1 < ar.size(); ++i) {
385                 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
386                 if (p && p->nargs() == 1) {
387                         MathData ar = p->nuc();
388                         erase(i);
389                         insert(i, ar);
390                         cur.adjust(i, ar.size() - 1);
391                 }
392         }
393
394         // glue adjacent font insets of the same kind
395         for (pos_type i = 0; i + 1 < size(); ++i) {
396                 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
397                 InsetMathFont const * q = operator[](i + 1)->asFontInset();
398                 if (p && q && p->name() == q->name()) {
399                         p->cell(0).append(q->cell(0));
400                         erase(i + 1);
401                         cur.adjust(i, -1);
402                 }
403         }
404 #endif
405         return false;
406 }
407
408
409 void InsetMathNest::handleFont
410         (Cursor & cur, docstring const & arg, char const * const font)
411 {
412         handleFont(cur, arg, from_ascii(font));
413 }
414
415
416 void InsetMathNest::handleFont(Cursor & cur, docstring const & arg,
417         docstring const & font)
418 {
419         cur.recordUndoSelection();
420
421         // this whole function is a hack and won't work for incremental font
422         // changes...
423         if (cur.inset().asInsetMath()->name() == font)
424                 cur.handleFont(to_utf8(font));
425         else
426                 handleNest(cur, createInsetMath(font), arg);
427 }
428
429
430 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest)
431 {
432         handleNest(cur, nest, docstring());
433 }
434
435
436 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest,
437         docstring const & arg)
438 {
439         CursorSlice i1 = cur.selBegin();
440         CursorSlice i2 = cur.selEnd();
441         if (!i1.inset().asInsetMath())
442                 return;
443         if (i1.idx() == i2.idx()) {
444                 // the easy case where only one cell is selected
445                 cur.handleNest(nest);
446                 cur.insert(arg);
447                 return;
448         }
449         
450         // multiple selected cells in a simple non-grid inset
451         if (i1.asInsetMath()->nrows() == 0 || i1.asInsetMath()->ncols() == 0) {
452                 for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
453                         // select cell
454                         cur.idx() = i;
455                         cur.pos() = 0;
456                         cur.resetAnchor();
457                         cur.pos() = cur.lastpos();
458                         cur.setSelection();
459                         
460                         // change font of cell
461                         cur.handleNest(nest);
462                         cur.insert(arg);
463                         
464                         // cur is in the font inset now. If the loop continues,
465                         // we need to get outside again for the next cell
466                         if (i + 1 <= i2.idx())
467                                 cur.pop_back();
468                 }
469                 return;
470         }
471         
472         // the complicated case with multiple selected cells in a grid
473         row_type r1, r2;
474         col_type c1, c2;
475         cap::region(i1, i2, r1, r2, c1, c2);
476         for (row_type row = r1; row <= r2; ++row) {
477                 for (col_type col = c1; col <= c2; ++col) {
478                         // select cell
479                         cur.idx() = i1.asInsetMath()->index(row, col);
480                         cur.pos() = 0;
481                         cur.resetAnchor();
482                         cur.pos() = cur.lastpos();
483                         cur.setSelection();
484                         
485                         // 
486                         cur.handleNest(nest);
487                         cur.insert(arg);
488                 
489                         // cur is in the font inset now. If the loop continues,
490                         // we need to get outside again for the next cell
491                         if (col + 1 <= c2 || row + 1 <= r2)
492                                 cur.pop_back();
493                 }
494         }
495 }
496
497
498 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
499 {
500         cur.recordUndoSelection();
501         Font font;
502         bool b;
503         font.fromString(to_utf8(arg), b);
504         if (font.fontInfo().color() != Color_inherit &&
505             font.fontInfo().color() != Color_ignore)
506                 handleNest(cur, MathAtom(new InsetMathColor(true, font.fontInfo().color())));
507         
508         // FIXME: support other font changes here as well?
509 }
510
511
512 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
513 {
514         //lyxerr << "InsetMathNest: request: " << cmd << endl;
515
516         switch (cmd.action) {
517
518         case LFUN_PASTE: {
519                 cur.recordUndoSelection();
520                 cur.message(_("Paste"));
521                 replaceSelection(cur);
522                 docstring topaste;
523                 if (cmd.argument().empty() && !theClipboard().isInternal())
524                         topaste = theClipboard().getAsText();
525                 else {
526                         size_t n = 0;
527                         idocstringstream is(cmd.argument());
528                         is >> n;
529                         topaste = cap::selection(n);
530                 }
531                 cur.niceInsert(topaste);
532                 cur.clearSelection(); // bug 393
533                 cur.finishUndo();
534                 break;
535         }
536
537         case LFUN_CUT:
538                 cur.recordUndo();
539                 cutSelection(cur, true, true);
540                 cur.message(_("Cut"));
541                 // Prevent stale position >= size crash
542                 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
543                 cur.normalize();
544                 break;
545
546         case LFUN_COPY:
547                 copySelection(cur);
548                 cur.message(_("Copy"));
549                 break;
550
551         case LFUN_MOUSE_PRESS:
552                 lfunMousePress(cur, cmd);
553                 break;
554
555         case LFUN_MOUSE_MOTION:
556                 lfunMouseMotion(cur, cmd);
557                 break;
558
559         case LFUN_MOUSE_RELEASE:
560                 lfunMouseRelease(cur, cmd);
561                 break;
562
563         case LFUN_FINISHED_LEFT: // in math, left is backwards
564         case LFUN_FINISHED_BACKWARD:
565                 cur.bv().cursor() = cur;
566                 break;
567
568         case LFUN_FINISHED_RIGHT: // in math, right is forward
569         case LFUN_FINISHED_FORWARD:
570                 ++cur.pos();
571                 cur.bv().cursor() = cur;
572                 break;
573
574         case LFUN_CHAR_RIGHT:
575         case LFUN_CHAR_LEFT:
576         case LFUN_CHAR_BACKWARD:
577         case LFUN_CHAR_FORWARD:
578                 cur.updateFlags(Update::Decoration | Update::FitCursor);
579         case LFUN_CHAR_RIGHT_SELECT:
580         case LFUN_CHAR_LEFT_SELECT:
581         case LFUN_CHAR_BACKWARD_SELECT:
582         case LFUN_CHAR_FORWARD_SELECT: {
583                 // are we in a selection?
584                 bool select = (cmd.action == LFUN_CHAR_RIGHT_SELECT 
585                                            || cmd.action == LFUN_CHAR_LEFT_SELECT
586                                            || cmd.action == LFUN_CHAR_BACKWARD_SELECT
587                                            || cmd.action == LFUN_CHAR_FORWARD_SELECT);
588                 // are we moving forward or backwards? 
589                 // If the command was RIGHT or LEFT, then whether we're moving forward
590                 // or backwards depends on the cursor movement mode (logical or visual):
591                 //  * in visual mode, since math is always LTR, right -> forward, 
592                 //    left -> backwards
593                 //  * in logical mode, the mapping is determined by the
594                 //    reverseDirectionNeeded() function
595                 
596                 bool forward;
597                 FuncCode finish_lfun;
598
599                 if (cmd.action == LFUN_CHAR_FORWARD 
600                                 || cmd.action == LFUN_CHAR_FORWARD_SELECT) {
601                         forward = true;
602                         finish_lfun = LFUN_FINISHED_FORWARD;
603                 }
604                 else if (cmd.action == LFUN_CHAR_BACKWARD
605                                 || cmd.action == LFUN_CHAR_BACKWARD_SELECT) {
606                         forward = false;
607                         finish_lfun = LFUN_FINISHED_BACKWARD;
608                 }
609                 else {
610                         bool right = (cmd.action == LFUN_CHAR_RIGHT_SELECT
611                                                   || cmd.action == LFUN_CHAR_RIGHT);
612                         if (lyxrc.visual_cursor || !reverseDirectionNeeded(cur))
613                                 forward = right;
614                         else 
615                                 forward = !right;
616
617                         if (right)
618                                 finish_lfun = LFUN_FINISHED_RIGHT;
619                         else
620                                 finish_lfun = LFUN_FINISHED_LEFT;
621                 }
622                 // Now that we know exactly what we want to do, let's do it!
623                 cur.selHandle(select);
624                 cur.autocorrect() = false;
625                 cur.clearTargetX();
626                 cur.macroModeClose();
627                 // try moving forward or backwards as necessary...
628                 if (!(forward ? cursorMathForward(cur) : cursorMathBackward(cur))) {
629                         // ... and if movement failed, then finish forward or backwards
630                         // as necessary
631                         cmd = FuncRequest(finish_lfun);
632                         cur.undispatched();
633                 }
634                 break;
635         }
636
637         case LFUN_DOWN:
638         case LFUN_UP:
639                 cur.updateFlags(Update::Decoration | Update::FitCursor);
640         case LFUN_DOWN_SELECT:
641         case LFUN_UP_SELECT: {
642                 // close active macro
643                 if (cur.inMacroMode()) {
644                         cur.macroModeClose();
645                         break;
646                 }
647                 
648                 // stop/start the selection
649                 bool select = cmd.action == LFUN_DOWN_SELECT ||
650                         cmd.action == LFUN_UP_SELECT;
651                 cur.selHandle(select);
652                 
653                 // go up/down
654                 bool up = cmd.action == LFUN_UP || cmd.action == LFUN_UP_SELECT;
655                 bool successful = cur.upDownInMath(up);
656                 if (successful)
657                         break;
658                 
659                 if (cur.fixIfBroken())
660                         // FIXME: Something bad happened. We pass the corrected Cursor
661                         // instead of letting things go worse.
662                         break;
663
664                 // We did not manage to move the cursor.
665                 cur.undispatched();
666                 break;
667         }
668
669         case LFUN_MOUSE_DOUBLE:
670         case LFUN_MOUSE_TRIPLE:
671         case LFUN_WORD_SELECT:
672                 cur.pos() = 0;
673                 cur.idx() = 0;
674                 cur.resetAnchor();
675                 cur.selection() = true;
676                 cur.pos() = cur.lastpos();
677                 cur.idx() = cur.lastidx();
678                 break;
679
680         case LFUN_PARAGRAPH_UP:
681         case LFUN_PARAGRAPH_DOWN:
682                 cur.updateFlags(Update::Decoration | Update::FitCursor);
683         case LFUN_PARAGRAPH_UP_SELECT:
684         case LFUN_PARAGRAPH_DOWN_SELECT:
685                 break;
686
687         case LFUN_LINE_BEGIN:
688         case LFUN_WORD_BACKWARD:
689         case LFUN_WORD_LEFT:
690                 cur.updateFlags(Update::Decoration | Update::FitCursor);
691         case LFUN_LINE_BEGIN_SELECT:
692         case LFUN_WORD_BACKWARD_SELECT:
693         case LFUN_WORD_LEFT_SELECT:
694                 cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT ||
695                                 cmd.action == LFUN_WORD_LEFT_SELECT || 
696                                 cmd.action == LFUN_LINE_BEGIN_SELECT);
697                 cur.macroModeClose();
698                 if (cur.pos() != 0) {
699                         cur.pos() = 0;
700                 } else if (cur.col() != 0) {
701                         cur.idx() -= cur.col();
702                         cur.pos() = 0;
703                 } else if (cur.idx() != 0) {
704                         cur.idx() = 0;
705                         cur.pos() = 0;
706                 } else {
707                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
708                         cur.undispatched();
709                 }
710                 break;
711
712         case LFUN_WORD_FORWARD:
713         case LFUN_WORD_RIGHT:
714         case LFUN_LINE_END:
715                 cur.updateFlags(Update::Decoration | Update::FitCursor);
716         case LFUN_WORD_FORWARD_SELECT:
717         case LFUN_WORD_RIGHT_SELECT:
718         case LFUN_LINE_END_SELECT:
719                 cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT ||
720                                 cmd.action == LFUN_WORD_RIGHT_SELECT ||
721                                 cmd.action == LFUN_LINE_END_SELECT);
722                 cur.macroModeClose();
723                 cur.clearTargetX();
724                 if (cur.pos() != cur.lastpos()) {
725                         cur.pos() = cur.lastpos();
726                 } else if (ncols() && (cur.col() != cur.lastcol())) {
727                         cur.idx() = cur.idx() - cur.col() + cur.lastcol();
728                         cur.pos() = cur.lastpos();
729                 } else if (cur.idx() != cur.lastidx()) {
730                         cur.idx() = cur.lastidx();
731                         cur.pos() = cur.lastpos();
732                 } else {
733                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
734                         cur.undispatched();
735                 }
736                 break;
737
738         case LFUN_CELL_FORWARD:
739                 cur.updateFlags(Update::Decoration | Update::FitCursor);
740                 cur.inset().idxNext(cur);
741                 break;
742
743         case LFUN_CELL_BACKWARD:
744                 cur.updateFlags(Update::Decoration | Update::FitCursor);
745                 cur.inset().idxPrev(cur);
746                 break;
747
748         case LFUN_WORD_DELETE_BACKWARD:
749         case LFUN_CHAR_DELETE_BACKWARD:
750                 if (cur.pos() == 0)
751                         // May affect external cell:
752                         cur.recordUndoInset();
753                 else
754                         cur.recordUndoSelection();
755                 // if the inset can not be removed from within, delete it
756                 if (!cur.backspace()) {
757                         FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
758                         cur.innerText()->dispatch(cur, cmd);
759                 }
760                 break;
761
762         case LFUN_WORD_DELETE_FORWARD:
763         case LFUN_CHAR_DELETE_FORWARD:
764                 if (cur.pos() == cur.lastpos())
765                         // May affect external cell:
766                         cur.recordUndoInset();
767                 else
768                         cur.recordUndoSelection();
769                 // if the inset can not be removed from within, delete it
770                 if (!cur.erase()) {
771                         FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
772                         cur.innerText()->dispatch(cur, cmd);
773                 }
774                 break;
775
776         case LFUN_ESCAPE:
777                 if (cur.selection())
778                         cur.clearSelection();
779                 else  {
780                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
781                         cur.undispatched();
782                 }
783                 break;
784
785         // 'Locks' the math inset. A 'locked' math inset behaves as a unit
786         // that is traversed by a single <CursorLeft>/<CursorRight>.
787         case LFUN_INSET_TOGGLE:
788                 cur.recordUndo();
789                 lock(!lock());
790                 cur.popForward();
791                 break;
792
793         case LFUN_SELF_INSERT:
794                 if (cmd.argument().size() != 1) {
795                         cur.recordUndoSelection();
796                         docstring const arg = cmd.argument();
797                         if (!interpretString(cur, arg))
798                                 cur.insert(arg);
799                         break;
800                 }
801                 // Don't record undo steps if we are in macro mode and
802                 // cmd.argument is the next character of the macro name.
803                 // Otherwise we'll get an invalid cursor if we undo after
804                 // the macro was finished and the macro is a known command,
805                 // e.g. sqrt. Cursor::macroModeClose replaces in this case
806                 // the InsetMathUnknown with name "frac" by an empty
807                 // InsetMathFrac -> a pos value > 0 is invalid.
808                 // A side effect is that an undo before the macro is finished
809                 // undoes the complete macro, not only the last character.
810                 if (!cur.inMacroMode())
811                         cur.recordUndoSelection();
812
813                 // spacial handling of space. If we insert an inset
814                 // via macro mode, we want to put the cursor inside it
815                 // if relevant. Think typing "\frac<space>".
816                 if (cmd.argument()[0] == ' '
817                     && cur.inMacroMode() && cur.macroName() != "\\"
818                     && cur.macroModeClose()) {
819                         MathAtom const atom = cur.prevAtom();
820                         if (atom->asNestInset() && atom->isActive()) {
821                                 cur.posBackward();
822                                 cur.pushBackward(*cur.nextInset());
823                         }
824                 } else if (!interpretChar(cur, cmd.argument()[0])) {
825                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
826                         cur.undispatched();
827                 }
828                 break;
829
830         //case LFUN_SERVER_GET_XY:
831         //      sprintf(dispatch_buffer, "%d %d",);
832         //      break;
833
834         case LFUN_SERVER_SET_XY: {
835                 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
836                 int x = 0;
837                 int y = 0;
838                 istringstream is(to_utf8(cmd.argument()));
839                 is >> x >> y;
840                 cur.setScreenPos(x, y);
841                 break;
842         }
843
844         // Special casing for superscript in case of LyX handling
845         // dead-keys:
846         case LFUN_ACCENT_CIRCUMFLEX:
847                 if (cmd.argument().empty()) {
848                         // do superscript if LyX handles
849                         // deadkeys
850                         cur.recordUndoSelection();
851                         script(cur, true, grabAndEraseSelection(cur));
852                 }
853                 break;
854
855         case LFUN_ACCENT_UMLAUT:
856         case LFUN_ACCENT_ACUTE:
857         case LFUN_ACCENT_GRAVE:
858         case LFUN_ACCENT_BREVE:
859         case LFUN_ACCENT_DOT:
860         case LFUN_ACCENT_MACRON:
861         case LFUN_ACCENT_CARON:
862         case LFUN_ACCENT_TILDE:
863         case LFUN_ACCENT_CEDILLA:
864         case LFUN_ACCENT_CIRCLE:
865         case LFUN_ACCENT_UNDERDOT:
866         case LFUN_ACCENT_TIE:
867         case LFUN_ACCENT_OGONEK:
868         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
869                 break;
870
871         //  Math fonts
872         case LFUN_TEXTSTYLE_APPLY:
873         case LFUN_TEXTSTYLE_UPDATE:
874                 handleFont2(cur, cmd.argument());
875                 break;
876
877         case LFUN_FONT_BOLD:
878                 if (currentMode() == TEXT_MODE)
879                         handleFont(cur, cmd.argument(), "textbf");
880                 else
881                         handleFont(cur, cmd.argument(), "boldsymbol");
882                 break;
883         case LFUN_FONT_SANS:
884                 if (currentMode() == TEXT_MODE)
885                         handleFont(cur, cmd.argument(), "textsf");
886                 else
887                         handleFont(cur, cmd.argument(), "mathsf");
888                 break;
889         case LFUN_FONT_EMPH:
890                 if (currentMode() == TEXT_MODE)
891                         handleFont(cur, cmd.argument(), "emph");
892                 else
893                         handleFont(cur, cmd.argument(), "mathcal");
894                 break;
895         case LFUN_FONT_ROMAN:
896                 if (currentMode() == TEXT_MODE)
897                         handleFont(cur, cmd.argument(), "textrm");
898                 else
899                         handleFont(cur, cmd.argument(), "mathrm");
900                 break;
901         case LFUN_FONT_TYPEWRITER:
902                 if (currentMode() == TEXT_MODE)
903                         handleFont(cur, cmd.argument(), "texttt");
904                 else
905                         handleFont(cur, cmd.argument(), "mathtt");
906                 break;
907         case LFUN_FONT_FRAK:
908                 handleFont(cur, cmd.argument(), "mathfrak");
909                 break;
910         case LFUN_FONT_ITAL:
911                 if (currentMode() == TEXT_MODE)
912                         handleFont(cur, cmd.argument(), "textit");
913                 else
914                         handleFont(cur, cmd.argument(), "mathit");
915                 break;
916         case LFUN_FONT_NOUN:
917                 if (currentMode() == TEXT_MODE)
918                         // FIXME: should be "noun"
919                         handleFont(cur, cmd.argument(), "textsc");
920                 else
921                         handleFont(cur, cmd.argument(), "mathbb");
922                 break;
923         case LFUN_FONT_DEFAULT:
924                 handleFont(cur, cmd.argument(), "textnormal");
925                 break;
926
927         case LFUN_MATH_MODE: {
928 #if 1
929                 // ignore math-mode on when already in math mode
930                 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
931                         break;
932                 cur.recordUndoSelection();
933                 cur.macroModeClose();
934                 docstring const save_selection = grabAndEraseSelection(cur);
935                 selClearOrDel(cur);
936                 //cur.plainInsert(MathAtom(new InsetMathMBox(cur.bv())));
937                 cur.plainInsert(MathAtom(new InsetMathBox(from_ascii("mbox"))));
938                 cur.posBackward();
939                 cur.pushBackward(*cur.nextInset());
940                 cur.niceInsert(save_selection);
941 #else
942                 if (currentMode() == Inset::TEXT_MODE) {
943                         cur.recordUndoSelection();
944                         cur.niceInsert(MathAtom(new InsetMathHull("simple")));
945                         cur.message(_("create new math text environment ($...$)"));
946                 } else {
947                         handleFont(cur, cmd.argument(), "textrm");
948                         cur.message(_("entered math text mode (textrm)"));
949                 }
950 #endif
951                 break;
952         }
953
954         case LFUN_MATH_SIZE: {
955                 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
956                 doDispatch(cur, fr);
957                 break;
958         }
959
960         case LFUN_MATH_MATRIX: {
961                 cur.recordUndo();
962                 unsigned int m = 1;
963                 unsigned int n = 1;
964                 docstring v_align;
965                 docstring h_align;
966                 idocstringstream is(cmd.argument());
967                 is >> m >> n >> v_align >> h_align;
968                 if (m < 1)
969                         m = 1;
970                 if (n < 1)
971                         n = 1;
972                 v_align += 'c';
973                 cur.niceInsert(
974                         MathAtom(new InsetMathArray(from_ascii("array"), m, n, (char)v_align[0], h_align)));
975                 break;
976         }
977
978         case LFUN_MATH_DELIM: {
979                 docstring ls;
980                 docstring rs = split(cmd.argument(), ls, ' ');
981                 // Reasonable default values
982                 if (ls.empty())
983                         ls = '(';
984                 if (rs.empty())
985                         rs = ')';
986                 cur.recordUndo();
987                 cur.handleNest(MathAtom(new InsetMathDelim(ls, rs)));
988                 break;
989         }
990
991         case LFUN_MATH_BIGDELIM: {
992                 docstring const lname  = from_utf8(cmd.getArg(0));
993                 docstring const ldelim = from_utf8(cmd.getArg(1));
994                 docstring const rname  = from_utf8(cmd.getArg(2));
995                 docstring const rdelim = from_utf8(cmd.getArg(3));
996                 latexkeys const * l = in_word_set(lname);
997                 bool const have_l = l && l->inset == "big" &&
998                                     InsetMathBig::isBigInsetDelim(ldelim);
999                 l = in_word_set(rname);
1000                 bool const have_r = l && l->inset == "big" &&
1001                                     InsetMathBig::isBigInsetDelim(rdelim);
1002                 // We mimic LFUN_MATH_DELIM in case we have an empty left
1003                 // or right delimiter.
1004                 if (have_l || have_r) {
1005                         cur.recordUndo();
1006                         docstring const selection = grabAndEraseSelection(cur);
1007                         selClearOrDel(cur);
1008                         if (have_l)
1009                                 cur.insert(MathAtom(new InsetMathBig(lname,
1010                                                                 ldelim)));
1011                         cur.niceInsert(selection);
1012                         if (have_r)
1013                                 cur.insert(MathAtom(new InsetMathBig(rname,
1014                                                                 rdelim)));
1015                 }
1016                 // Don't call cur.undispatched() if we did nothing, this would
1017                 // lead to infinite recursion via Text::dispatch().
1018                 break;
1019         }
1020
1021         case LFUN_SPACE_INSERT:
1022                 cur.recordUndoSelection();
1023                 cur.insert(MathAtom(new InsetMathSpace(from_ascii(","))));
1024                 break;
1025
1026         case LFUN_MATH_SPACE:
1027                 cur.recordUndoSelection();
1028                 if (cmd.argument().empty())
1029                         cur.insert(MathAtom(new InsetMathSpace(from_ascii(","))));
1030                 else
1031                         cur.insert(MathAtom(new InsetMathSpace(cmd.argument())));
1032                 break;
1033
1034         case LFUN_ERT_INSERT:
1035                 // interpret this as if a backslash was typed
1036                 cur.recordUndo();
1037                 interpretChar(cur, '\\');
1038                 break;
1039
1040         case LFUN_MATH_SUBSCRIPT:
1041                 // interpret this as if a _ was typed
1042                 cur.recordUndoSelection();
1043                 interpretChar(cur, '_');
1044                 break;
1045
1046         case LFUN_MATH_SUPERSCRIPT:
1047                 // interpret this as if a ^ was typed
1048                 cur.recordUndoSelection();
1049                 interpretChar(cur, '^');
1050                 break;
1051                 
1052         case LFUN_MATH_MACRO_FOLD:
1053         case LFUN_MATH_MACRO_UNFOLD: {
1054                 Cursor it = cur;
1055                 bool fold = cmd.action == LFUN_MATH_MACRO_FOLD;
1056                 bool found = findMacroToFoldUnfold(it, fold);
1057                 if (found) {
1058                         MathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1059                         cur.recordUndoInset();
1060                         if (fold)
1061                                 macro->fold(cur);
1062                         else
1063                                 macro->unfold(cur);
1064                 }
1065                 break;
1066         }
1067
1068         case LFUN_QUOTE_INSERT:
1069                 // interpret this as if a straight " was typed
1070                 cur.recordUndoSelection();
1071                 interpretChar(cur, '\"');
1072                 break;
1073
1074 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1075 // handling such that "self-insert" works on "arbitrary stuff" too, and
1076 // math-insert only handles special math things like "matrix".
1077         case LFUN_MATH_INSERT: {
1078                 cur.recordUndoSelection();
1079                 if (cmd.argument() == "^" || cmd.argument() == "_")
1080                         interpretChar(cur, cmd.argument()[0]);
1081                 else {
1082                         MathData ar;
1083                         asArray(cmd.argument(), ar);
1084                         if (ar.size() == 1 && ar[0]->asNestInset()
1085                                         && ar[0]->asNestInset()->nargs() > 1)
1086                                 handleNest(cur, ar[0]);
1087                         else
1088                                 cur.niceInsert(cmd.argument());
1089                 }
1090                 break;
1091                 }
1092
1093         case LFUN_DIALOG_SHOW_NEW_INSET: {
1094                 docstring const & name = cmd.argument();
1095                 string data;
1096                 if (name == "ref") {
1097                         InsetMathRef tmp(name);
1098                         data = tmp.createDialogStr(to_utf8(name));
1099                 }
1100                 cur.bv().showDialog(to_utf8(name), data);
1101                 break;
1102         }
1103
1104         case LFUN_INSET_INSERT: {
1105                 MathData ar;
1106                 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1107                         cur.recordUndoSelection();
1108                         cur.insert(ar);
1109                 } else
1110                         cur.undispatched();
1111                 break;
1112         }
1113         case LFUN_INSET_DISSOLVE:
1114                 if (!asHullInset()) {
1115                         cur.recordUndoInset();
1116                         cur.pullArg();
1117                 }
1118                 break;
1119
1120         default:
1121                 InsetMath::doDispatch(cur, cmd);
1122                 break;
1123         }
1124 }
1125
1126
1127 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1128         // look for macro to open/close, but stay in mathed
1129         for (; !it.empty(); it.pop_back()) {
1130                         
1131                 // go backward through the current cell
1132                 Inset * inset = it.nextInset();
1133                 while (inset && inset->asInsetMath()) {
1134                         MathMacro * macro = inset->asInsetMath()->asMacro();
1135                         if (macro) {
1136                                 // found the an macro to open/close?
1137                                 if (macro->folded() != fold)
1138                                         return true;
1139                                 
1140                                 // Wrong folding state.
1141                                 // If this was the first we see in this slice, look further left,
1142                                 // otherwise go up.
1143                                 if (inset != it.nextInset())
1144                                         break;
1145                         }
1146                         
1147                         // go up if this was the left most position
1148                         if (it.pos() == 0)
1149                                 break;
1150                         
1151                         // go left
1152                         it.pos()--;
1153                         inset = it.nextInset();
1154                 }
1155         }
1156         
1157         return false;
1158 }
1159
1160
1161 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1162                 FuncStatus & flag) const
1163 {
1164         // the font related toggles
1165         //string tc = "mathnormal";
1166         bool ret = true;
1167         string const arg = to_utf8(cmd.argument());
1168         switch (cmd.action) {
1169         case LFUN_TABULAR_FEATURE:
1170                 flag.setEnabled(false);
1171                 break;
1172 #if 0
1173         case LFUN_TABULAR_FEATURE:
1174                 // FIXME: check temporarily disabled
1175                 // valign code
1176                 char align = mathcursor::valign();
1177                 if (align == '\0') {
1178                         enable = false;
1179                         break;
1180                 }
1181                 if (cmd.argument().empty()) {
1182                         flag.clear();
1183                         break;
1184                 }
1185                 if (!contains("tcb", cmd.argument()[0])) {
1186                         enable = false;
1187                         break;
1188                 }
1189                 flag.setOnOff(cmd.argument()[0] == align);
1190                 break;
1191 #endif
1192         /// We have to handle them since 1.4 blocks all unhandled actions
1193         case LFUN_FONT_ITAL:
1194         case LFUN_FONT_BOLD:
1195         case LFUN_FONT_SANS:
1196         case LFUN_FONT_EMPH:
1197         case LFUN_FONT_TYPEWRITER:
1198         case LFUN_FONT_NOUN:
1199         case LFUN_FONT_ROMAN:
1200         case LFUN_FONT_DEFAULT:
1201                 flag.setEnabled(true);
1202                 break;
1203         case LFUN_MATH_MUTATE:
1204                 //flag.setOnOff(mathcursor::formula()->hullType() == to_utf8(cmd.argument()));
1205                 flag.setOnOff(false);
1206                 break;
1207
1208         // we just need to be in math mode to enable that
1209         case LFUN_MATH_SIZE:
1210         case LFUN_MATH_SPACE:
1211         case LFUN_MATH_LIMITS:
1212         case LFUN_MATH_EXTERN:
1213                 flag.setEnabled(true);
1214                 break;
1215
1216         case LFUN_FONT_FRAK:
1217                 flag.setEnabled(currentMode() != TEXT_MODE);
1218                 break;
1219
1220         case LFUN_MATH_INSERT: {
1221                 bool const textarg =
1222                         arg == "\\textbf"   || arg == "\\textsf" ||
1223                         arg == "\\textrm"   || arg == "\\textmd" ||
1224                         arg == "\\textit"   || arg == "\\textsc" ||
1225                         arg == "\\textsl"   || arg == "\\textup" ||
1226                         arg == "\\texttt"   || arg == "\\textbb" ||
1227                         arg == "\\textnormal";
1228                 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1229                 break;
1230         }
1231
1232         case LFUN_MATH_MATRIX:
1233                 flag.setEnabled(currentMode() == MATH_MODE);
1234                 break;
1235
1236         case LFUN_INSET_INSERT: {
1237                 // Don't test createMathInset_fromDialogStr(), since
1238                 // getStatus is not called with a valid reference and the
1239                 // dialog would not be applyable.
1240                 string const name = cmd.getArg(0);
1241                 flag.setEnabled(name == "ref");
1242                 break;
1243         }
1244
1245         case LFUN_MATH_DELIM:
1246         case LFUN_MATH_BIGDELIM:
1247                 // Don't do this with multi-cell selections
1248                 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1249                 break;
1250                 
1251         case LFUN_MATH_MACRO_FOLD:
1252         case LFUN_MATH_MACRO_UNFOLD: {
1253                 Cursor it = cur;
1254                 bool found = findMacroToFoldUnfold(it, cmd.action == LFUN_MATH_MACRO_FOLD);
1255                 flag.setEnabled(found);
1256                 break;
1257         }
1258                 
1259         case LFUN_SPECIALCHAR_INSERT:
1260                 // FIXME: These would probably make sense in math-text mode
1261                 flag.setEnabled(false);
1262                 break;
1263
1264         case LFUN_INSET_DISSOLVE:
1265                 flag.setEnabled(!asHullInset());
1266                 break;
1267
1268         default:
1269                 ret = false;
1270                 break;
1271         }
1272         return ret;
1273 }
1274
1275
1276 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1277 {
1278         cur.push(*this);
1279         bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_RIGHT || 
1280                 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1281         cur.idx() = enter_front ? 0 : cur.lastidx();
1282         cur.pos() = enter_front ? 0 : cur.lastpos();
1283         cur.resetAnchor();
1284         //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1285 }
1286
1287
1288 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1289 {
1290         int idx_min = 0;
1291         int dist_min = 1000000;
1292         for (idx_type i = 0, n = nargs(); i != n; ++i) {
1293                 int const d = cell(i).dist(cur.bv(), x, y);
1294                 if (d < dist_min) {
1295                         dist_min = d;
1296                         idx_min = i;
1297                 }
1298         }
1299         MathData & ar = cell(idx_min);
1300         cur.push(*this);
1301         cur.idx() = idx_min;
1302         cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1303
1304         //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1305         if (dist_min == 0) {
1306                 // hit inside cell
1307                 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1308                         if (ar[i]->covers(cur.bv(), x, y))
1309                                 return ar[i].nucleus()->editXY(cur, x, y);
1310         }
1311         return this;
1312 }
1313
1314
1315 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1316 {
1317         //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1318         BufferView & bv = cur.bv();
1319         bool do_selection = cmd.button() == mouse_button::button1
1320                 && cmd.argument() == "region-select";
1321         bv.mouseSetCursor(cur, do_selection);
1322         if (cmd.button() == mouse_button::button1) {
1323                 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1324                 // Update the cursor update flags as needed:
1325                 //
1326                 // Update::Decoration: tells to update the decoration
1327                 //                     (visual box corners that define
1328                 //                     the inset)/
1329                 // Update::FitCursor: adjust the screen to the cursor
1330                 //                    position if needed
1331                 // cur.result().update(): don't overwrite previously set flags.
1332                 cur.updateFlags(Update::Decoration | Update::FitCursor 
1333                                 | cur.result().update());
1334         } else if (cmd.button() == mouse_button::button2) {
1335                 if (cap::selection()) {
1336                         // See comment in Text::dispatch why we do this
1337                         cap::copySelectionToStack();
1338                         cmd = FuncRequest(LFUN_PASTE, "0");
1339                         doDispatch(bv.cursor(), cmd);
1340                 } else {
1341                         MathData ar;
1342                         asArray(theSelection().get(), ar);
1343                         bv.cursor().insert(ar);
1344                 }
1345         }
1346 }
1347
1348
1349 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1350 {
1351         // only select with button 1
1352         if (cmd.button() == mouse_button::button1) {
1353                 Cursor & bvcur = cur.bv().cursor();
1354                 if (bvcur.anchor_.hasPart(cur)) {
1355                         //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
1356                         bvcur.setCursor(cur);
1357                         bvcur.selection() = true;
1358                         //lyxerr << "MOTION " << bvcur << endl;
1359                 } else
1360                         cur.undispatched();
1361         }
1362 }
1363
1364
1365 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1366 {
1367         //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1368
1369         if (cmd.button() == mouse_button::button1) {
1370                 if (!cur.selection())
1371                         cur.noUpdate();
1372                 else {
1373                         Cursor & bvcur = cur.bv().cursor();
1374                         bvcur.selection() = true;
1375                 }
1376                 return;
1377         }
1378
1379         cur.undispatched();
1380 }
1381
1382
1383 bool InsetMathNest::interpretChar(Cursor & cur, char_type c)
1384 {
1385         //lyxerr << "interpret 2: '" << c << "'" << endl;
1386         docstring save_selection;
1387         if (c == '^' || c == '_')
1388                 save_selection = grabAndEraseSelection(cur);
1389
1390         cur.clearTargetX();
1391
1392         // handle macroMode
1393         if (cur.inMacroMode()) {
1394                 docstring name = cur.macroName();
1395
1396                 /// are we currently typing '#1' or '#2' or...?
1397                 if (name == "\\#") {
1398                         cur.backspace();
1399                         int n = c - '0';
1400                         if (n >= 1 && n <= 9)
1401                                 cur.insert(new MathMacroArgument(n));
1402                         return true;
1403                 }
1404
1405                 // do not finish macro for known * commands
1406                 MathWordList const & mwl = mathedWordList();
1407                 bool star_macro = c == '*'
1408                         && (mwl.find(name.substr(1) + "*") != mwl.end()
1409                             || cur.buffer().getMacro(name.substr(1) + "*", cur, true));
1410                 if (isAlphaASCII(c) || star_macro) {
1411                         cur.activeMacro()->setName(name + docstring(1, c));
1412                         return true;
1413                 }
1414
1415                 // handle 'special char' macros
1416                 if (name == "\\") {
1417                         // remove the '\\'
1418                         if (c == '\\') {
1419                                 cur.backspace();
1420                                 if (currentMode() == InsetMath::TEXT_MODE)
1421                                         cur.niceInsert(createInsetMath("textbackslash"));
1422                                 else
1423                                         cur.niceInsert(createInsetMath("backslash"));
1424                         } else if (c == '{') {
1425                                 cur.backspace();
1426                                 cur.niceInsert(MathAtom(new InsetMathBrace));
1427                         } else if (c == '%') {
1428                                 cur.backspace();
1429                                 cur.niceInsert(MathAtom(new InsetMathComment));
1430                         } else if (c == '#') {
1431                                 LASSERT(cur.activeMacro(), /**/);
1432                                 cur.activeMacro()->setName(name + docstring(1, c));
1433                         } else {
1434                                 cur.backspace();
1435                                 cur.niceInsert(createInsetMath(docstring(1, c)));
1436                         }
1437                         return true;
1438                 }
1439
1440                 // One character big delimiters. The others are handled in
1441                 // interpretString().
1442                 latexkeys const * l = in_word_set(name.substr(1));
1443                 if (name[0] == '\\' && l && l->inset == "big") {
1444                         docstring delim;
1445                         switch (c) {
1446                         case '{':
1447                                 delim = from_ascii("\\{");
1448                                 break;
1449                         case '}':
1450                                 delim = from_ascii("\\}");
1451                                 break;
1452                         default:
1453                                 delim = docstring(1, c);
1454                                 break;
1455                         }
1456                         if (InsetMathBig::isBigInsetDelim(delim)) {
1457                                 // name + delim ared a valid InsetMathBig.
1458                                 // We can't use cur.macroModeClose() because
1459                                 // it does not handle delim.
1460                                 InsetMathUnknown * p = cur.activeMacro();
1461                                 p->finalize();
1462                                 --cur.pos();
1463                                 cur.cell().erase(cur.pos());
1464                                 cur.plainInsert(MathAtom(
1465                                         new InsetMathBig(name.substr(1), delim)));
1466                                 return true;
1467                         }
1468                 }
1469
1470                 // leave macro mode and try again if necessary
1471                 cur.macroModeClose();
1472                 if (c == '{')
1473                         cur.niceInsert(MathAtom(new InsetMathBrace));
1474                 else if (c != ' ')
1475                         interpretChar(cur, c);
1476                 return true;
1477         }
1478
1479         // This is annoying as one has to press <space> far too often.
1480         // Disable it.
1481
1482 #if 0
1483                 // leave autocorrect mode if necessary
1484                 if (autocorrect() && c == ' ') {
1485                         autocorrect() = false;
1486                         return true;
1487                 }
1488 #endif
1489
1490         // just clear selection on pressing the space bar
1491         if (cur.selection() && c == ' ') {
1492                 cur.selection() = false;
1493                 return true;
1494         }
1495
1496         if (c == '\\') {
1497                 //lyxerr << "starting with macro" << endl;
1498                 bool reduced = cap::reduceSelectionToOneCell(cur);
1499                 if (reduced || !cur.selection()) {
1500                         docstring const safe = cap::grabAndEraseSelection(cur);
1501                         cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1502                 }
1503                 return true;
1504         }
1505
1506         selClearOrDel(cur);
1507
1508         if (c == '\n') {
1509                 if (currentMode() == InsetMath::TEXT_MODE)
1510                         cur.insert(c);
1511                 return true;
1512         }
1513
1514         if (c == ' ') {
1515                 if (currentMode() == InsetMath::TEXT_MODE) {
1516                         // insert spaces in text mode,
1517                         // but suppress direct insertion of two spaces in a row
1518                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1519                         // it is better than nothing...
1520                         if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ') {
1521                                 cur.insert(c);
1522                                 // FIXME: we have to enable full redraw here because of the
1523                                 // visual box corners that define the inset. If we know for
1524                                 // sure that we stay within the same cell we can optimize for
1525                                 // that using:
1526                                 //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1527                         }
1528                         return true;
1529                 }
1530                 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1531                         cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1532                         // FIXME: we have to enable full redraw here because of the
1533                         // visual box corners that define the inset. If we know for
1534                         // sure that we stay within the same cell we can optimize for
1535                         // that using:
1536                         //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1537                         return true;
1538                 }
1539
1540                 if (cur.popForward()) {
1541                         // FIXME: we have to enable full redraw here because of the
1542                         // visual box corners that define the inset. If we know for
1543                         // sure that we stay within the same cell we can optimize for
1544                         // that using:
1545                         //cur.updateFlags(Update::FitCursor);
1546                         return true;
1547                 }
1548
1549                 // if we are at the very end, leave the formula
1550                 return cur.pos() != cur.lastpos();
1551         }
1552
1553         // These shouldn't work in text mode:
1554         if (currentMode() != InsetMath::TEXT_MODE) {
1555                 if (c == '_') {
1556                         script(cur, false, save_selection);
1557                         return true;
1558                 }
1559                 if (c == '^') {
1560                         script(cur, true, save_selection);
1561                         return true;
1562                 }
1563                 if (c == '~') {
1564                         cur.niceInsert(createInsetMath("sim"));
1565                         return true;
1566                 }
1567         }
1568
1569         if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1570             c == '%' || c == '_' || c == '^') {
1571                 cur.niceInsert(createInsetMath(docstring(1, c)));
1572                 return true;
1573         }
1574
1575
1576         // try auto-correction
1577         //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1578         //      return true;
1579
1580         // no special circumstances, so insert the character without any fuss
1581         cur.insert(c);
1582         cur.autocorrect() = true;
1583         return true;
1584 }
1585
1586
1587 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1588 {
1589         // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1590         // possible
1591         if (!cur.empty() && cur.pos() > 0 &&
1592             cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1593                 if (InsetMathBig::isBigInsetDelim(str)) {
1594                         docstring prev = asString(cur.cell()[cur.pos() - 1]);
1595                         if (prev[0] == '\\') {
1596                                 prev = prev.substr(1);
1597                                 latexkeys const * l = in_word_set(prev);
1598                                 if (l && l->inset == "big") {
1599                                         cur.cell()[cur.pos() - 1] =
1600                                                 MathAtom(new InsetMathBig(prev, str));
1601                                         return true;
1602                                 }
1603                         }
1604                 }
1605         }
1606         return false;
1607 }
1608
1609
1610 bool InsetMathNest::script(Cursor & cur, bool up)
1611 {
1612         return script(cur, up, docstring());
1613 }
1614
1615
1616 bool InsetMathNest::script(Cursor & cur, bool up,
1617                 docstring const & save_selection)
1618 {
1619         // Hack to get \^ and \_ working
1620         //lyxerr << "handling script: up: " << up << endl;
1621         if (cur.inMacroMode() && cur.macroName() == "\\") {
1622                 if (up)
1623                         cur.niceInsert(createInsetMath("mathcircumflex"));
1624                 else
1625                         interpretChar(cur, '_');
1626                 return true;
1627         }
1628
1629         cur.macroModeClose();
1630         if (asScriptInset() && cur.idx() == 0) {
1631                 // we are in a nucleus of a script inset, move to _our_ script
1632                 InsetMathScript * inset = asScriptInset();
1633                 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1634                 inset->ensure(up);
1635                 cur.idx() = inset->idxOfScript(up);
1636                 cur.pos() = 0;
1637         } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1638                 --cur.pos();
1639                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1640                 cur.push(*inset);
1641                 inset->ensure(up);
1642                 cur.idx() = inset->idxOfScript(up);
1643                 cur.pos() = cur.lastpos();
1644         } else {
1645                 // convert the thing to our left to a scriptinset or create a new
1646                 // one if in the very first position of the array
1647                 if (cur.pos() == 0) {
1648                         //lyxerr << "new scriptinset" << endl;
1649                         cur.insert(new InsetMathScript(up));
1650                 } else {
1651                         //lyxerr << "converting prev atom " << endl;
1652                         cur.prevAtom() = MathAtom(new InsetMathScript(cur.prevAtom(), up));
1653                 }
1654                 --cur.pos();
1655                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1656                 // See comment in MathParser.cpp for special handling of {}-bases
1657
1658                 cur.push(*inset);
1659                 cur.idx() = 1;
1660                 cur.pos() = 0;
1661         }
1662         //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1663         cur.niceInsert(save_selection);
1664         cur.resetAnchor();
1665         //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1666         return true;
1667 }
1668
1669
1670 bool InsetMathNest::completionSupported(Cursor const & cur) const
1671 {
1672         return cur.inMacroMode();
1673 }
1674
1675
1676 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
1677 {
1678         return cur.inMacroMode();
1679 }
1680
1681
1682 bool InsetMathNest::automaticInlineCompletion() const
1683 {
1684         return lyxrc.completion_inline_math;
1685 }
1686
1687
1688 bool InsetMathNest::automaticPopupCompletion() const
1689 {
1690         return lyxrc.completion_popup_math;
1691 }
1692
1693
1694 CompletionList const *
1695 InsetMathNest::createCompletionList(Cursor const & cur) const
1696 {
1697         if (!cur.inMacroMode())
1698                 return 0;
1699         
1700         return new MathCompletionList(cur);
1701 }
1702
1703
1704 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
1705 {
1706         if (!cur.inMacroMode())
1707                 return docstring();
1708         
1709         return cur.activeMacro()->name();
1710 }
1711
1712
1713 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
1714                                      bool finished)
1715 {
1716         if (!cur.inMacroMode())
1717                 return false;
1718
1719         // append completion to active macro
1720         InsetMathUnknown * inset = cur.activeMacro();
1721         inset->setName(inset->name() + s);
1722
1723         // finish macro
1724         if (finished) {
1725 #if 0
1726                 // FIXME: this creates duplicates in the completion popup
1727                 // which looks ugly. Moreover the changes the list lengths
1728                 // which seems to
1729                 confuse the popup as well.
1730                 MathCompletionList::addToFavorites(inset->name());
1731 #endif
1732                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
1733         }
1734
1735         return true;
1736 }
1737
1738
1739 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y, 
1740                                         Dimension & dim) const
1741 {
1742         Inset const * inset = cur.activeMacro();
1743         if (!inset)
1744                 return;
1745
1746         // get inset dimensions
1747         dim = cur.bv().coordCache().insets().dim(inset);
1748         // FIXME: these 3 are no accurate, but should depend on the font.
1749         // Now the popup jumps down if you enter a char with descent > 0.
1750         dim.des += 3;
1751         dim.asc += 3;
1752
1753         // and position
1754         Point xy
1755         = cur.bv().coordCache().insets().xy(inset);
1756         x = xy.x_;
1757         y = xy.y_;
1758 }
1759
1760
1761 bool InsetMathNest::cursorMathForward(Cursor & cur)
1762 {
1763         if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
1764                 cur.pushBackward(*cur.nextAtom().nucleus());
1765                 cur.inset().idxFirst(cur);
1766                 return true;
1767         } 
1768         if (cur.posForward() || idxForward(cur))
1769                 return true;
1770         // try to pop forwards --- but don't pop out of math! leave that to
1771         // the FINISH lfuns
1772         int s = cur.depth() - 2;
1773         if (s >= 0 && cur[s].inset().asInsetMath())
1774                 return cur.popForward();
1775         return false;
1776 }
1777
1778
1779 bool InsetMathNest::cursorMathBackward(Cursor & cur)
1780 {
1781         if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
1782                 cur.posBackward();
1783                 cur.push(*cur.nextAtom().nucleus());
1784                 cur.inset().idxLast(cur);
1785                 return true;
1786         } 
1787         if (cur.posBackward() || idxBackward(cur))
1788                 return true;
1789         // try to pop backwards --- but don't pop out of math! leave that to 
1790         // the FINISH lfuns
1791         int s = cur.depth() - 2;
1792         if (s >= 0 && cur[s].inset().asInsetMath())
1793                 return cur.popBackward();
1794         return false;
1795 }
1796
1797
1798 ////////////////////////////////////////////////////////////////////
1799
1800 MathCompletionList::MathCompletionList(Cursor const & cur)
1801 {
1802         // fill it with macros from the buffer
1803         MacroNameSet macros;
1804         cur.buffer().listMacroNames(macros);
1805         MacroNameSet::const_iterator it;
1806         for (it = macros.begin(); it != macros.end(); ++it) {
1807                 if (cur.buffer().getMacro(*it, cur, false))
1808                         locals.push_back("\\" + *it);
1809         }
1810         sort(locals.begin(), locals.end());
1811
1812         if (globals.size() > 0)
1813                 return;
1814
1815         // fill in global macros
1816         macros.clear();
1817         MacroTable::globalMacros().getMacroNames(macros);
1818         //lyxerr << "Globals completion macros: ";
1819         for (it = macros.begin(); it != macros.end(); ++it) {
1820                 //lyxerr << "\\" + *it << " ";
1821                 globals.push_back("\\" + *it);
1822         }
1823         //lyxerr << std::endl;
1824
1825         // fill in global commands
1826         globals.push_back(from_ascii("\\boxed"));
1827         globals.push_back(from_ascii("\\fbox"));
1828         globals.push_back(from_ascii("\\framebox"));
1829         globals.push_back(from_ascii("\\makebox"));
1830         globals.push_back(from_ascii("\\kern"));
1831         globals.push_back(from_ascii("\\xrightarrow"));
1832         globals.push_back(from_ascii("\\xleftarrow"));
1833         globals.push_back(from_ascii("\\split"));
1834         globals.push_back(from_ascii("\\gathered"));
1835         globals.push_back(from_ascii("\\aligned"));
1836         globals.push_back(from_ascii("\\alignedat"));
1837         globals.push_back(from_ascii("\\cases"));
1838         globals.push_back(from_ascii("\\substack"));
1839         globals.push_back(from_ascii("\\xymatrix"));
1840         globals.push_back(from_ascii("\\subarray"));
1841         globals.push_back(from_ascii("\\array"));
1842         globals.push_back(from_ascii("\\sqrt"));
1843         globals.push_back(from_ascii("\\root"));
1844         globals.push_back(from_ascii("\\tabular"));
1845         globals.push_back(from_ascii("\\stackrel"));
1846         globals.push_back(from_ascii("\\binom"));
1847         globals.push_back(from_ascii("\\choose"));
1848         globals.push_back(from_ascii("\\brace"));
1849         globals.push_back(from_ascii("\\brack"));
1850         globals.push_back(from_ascii("\\frac"));
1851         globals.push_back(from_ascii("\\over"));
1852         globals.push_back(from_ascii("\\nicefrac"));
1853         globals.push_back(from_ascii("\\unitfrac"));
1854         globals.push_back(from_ascii("\\unitfracthree"));
1855         globals.push_back(from_ascii("\\unitone"));
1856         globals.push_back(from_ascii("\\unittwo"));
1857         globals.push_back(from_ascii("\\infer"));
1858         globals.push_back(from_ascii("\\atop"));
1859         globals.push_back(from_ascii("\\lefteqn"));
1860         globals.push_back(from_ascii("\\boldsymbol"));
1861         globals.push_back(from_ascii("\\bm"));
1862         globals.push_back(from_ascii("\\color"));
1863         globals.push_back(from_ascii("\\normalcolor"));
1864         globals.push_back(from_ascii("\\textcolor"));
1865         globals.push_back(from_ascii("\\dfrac"));
1866         globals.push_back(from_ascii("\\tfrac"));
1867         globals.push_back(from_ascii("\\dbinom"));
1868         globals.push_back(from_ascii("\\tbinom"));
1869         globals.push_back(from_ascii("\\hphantom"));
1870         globals.push_back(from_ascii("\\phantom"));
1871         globals.push_back(from_ascii("\\vphantom"));
1872         MathWordList const & words = mathedWordList();
1873         MathWordList::const_iterator it2;
1874         //lyxerr << "Globals completion commands: ";
1875         for (it2 = words.begin(); it2 != words.end(); ++it2) {
1876                 globals.push_back("\\" + (*it2).first);
1877                 //lyxerr << "\\" + (*it2).first << " ";
1878         }
1879         //lyxerr << std::endl;
1880         sort(globals.begin(), globals.end());
1881 }
1882
1883
1884 MathCompletionList::~MathCompletionList()
1885 {
1886 }
1887
1888
1889 size_type MathCompletionList::size() const
1890 {
1891         return locals.size() + globals.size();
1892 }
1893
1894
1895 docstring const & MathCompletionList::data(size_t idx) const
1896 {
1897         size_t lsize = locals.size();
1898         if (idx >= lsize)
1899                 return globals[idx - lsize];
1900         else
1901                 return locals[idx];
1902 }
1903
1904
1905 std::string MathCompletionList::icon(size_t idx) const 
1906 {
1907         // get the latex command
1908         docstring cmd;
1909         size_t lsize = locals.size();
1910         if (idx >= lsize)
1911                 cmd = globals[idx - lsize];
1912         else
1913                 cmd = locals[idx];
1914         
1915         // get the icon resource name by stripping the backslash
1916         return "images/math/" + to_utf8(cmd.substr(1)) + ".png";
1917 }
1918
1919 std::vector<docstring> MathCompletionList::globals;
1920
1921 } // namespace lyx