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