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