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