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