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