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