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