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