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