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