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