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