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