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