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