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