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