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