]> git.lyx.org Git - features.git/blob - src/mathed/InsetMathNest.cpp
* store the selection in the InsetMathUnknown and insert it into the
[features.git] / src / mathed / InsetMathNest.cpp
1 /**
2  * \file InsetMathNest.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetMathNest.h"
14
15 #include "InsetMathArray.h"
16 #include "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_SCREEN_UP_SELECT:
669                 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
670                 cur.undispatched();
671                 break;
672
673         case LFUN_SCREEN_DOWN_SELECT:
674                 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
675                 cur.undispatched();
676                 break;
677
678         case LFUN_CELL_FORWARD:
679                 cur.updateFlags(Update::Decoration | Update::FitCursor);
680                 cur.inset().idxNext(cur);
681                 break;
682
683         case LFUN_CELL_BACKWARD:
684                 cur.updateFlags(Update::Decoration | Update::FitCursor);
685                 cur.inset().idxPrev(cur);
686                 break;
687
688         case LFUN_WORD_DELETE_BACKWARD:
689         case LFUN_CHAR_DELETE_BACKWARD:
690                 if (cur.pos() == 0)
691                         // May affect external cell:
692                         cur.recordUndoInset();
693                 else
694                         cur.recordUndo();
695                 // if the inset can not be removed from within, delete it
696                 if (!cur.backspace()) {
697                         FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
698                         cur.innerText()->dispatch(cur, cmd);
699                 }
700                 break;
701
702         case LFUN_WORD_DELETE_FORWARD:
703         case LFUN_CHAR_DELETE_FORWARD:
704                 if (cur.pos() == cur.lastpos())
705                         // May affect external cell:
706                         cur.recordUndoInset();
707                 else
708                         cur.recordUndo();
709                 // if the inset can not be removed from within, delete it
710                 if (!cur.erase()) {
711                         FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
712                         cur.innerText()->dispatch(cur, cmd);
713                 }
714                 break;
715
716         case LFUN_ESCAPE:
717                 if (cur.selection())
718                         cur.clearSelection();
719                 else  {
720                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
721                         cur.undispatched();
722                 }
723                 break;
724
725         // 'Locks' the math inset. A 'locked' math inset behaves as a unit
726         // that is traversed by a single <CursorLeft>/<CursorRight>.
727         case LFUN_INSET_TOGGLE:
728                 cur.recordUndo();
729                 lock(!lock());
730                 cur.popForward();
731                 break;
732
733         case LFUN_SELF_INSERT:
734                 if (cmd.argument().size() != 1) {
735                         cur.recordUndo();
736                         docstring const arg = cmd.argument();
737                         if (!interpretString(cur, arg))
738                                 cur.insert(arg);
739                         break;
740                 }
741                 // Don't record undo steps if we are in macro mode and
742                 // cmd.argument is the next character of the macro name.
743                 // Otherwise we'll get an invalid cursor if we undo after
744                 // the macro was finished and the macro is a known command,
745                 // e.g. sqrt. Cursor::macroModeClose replaces in this case
746                 // the InsetMathUnknown with name "frac" by an empty
747                 // InsetMathFrac -> a pos value > 0 is invalid.
748                 // A side effect is that an undo before the macro is finished
749                 // undoes the complete macro, not only the last character.
750                 if (!cur.inMacroMode())
751                         cur.recordUndo();
752
753                 // spacial handling of space. If we insert an inset
754                 // via macro mode, we want to put the cursor inside it
755                 // if relevant. Think typing "\frac<space>".
756                 if (cmd.argument()[0] == ' '
757                     && cur.inMacroMode() && cur.macroName() != "\\"
758                     && cur.macroModeClose()) {
759                         MathAtom const atom = cur.prevAtom();
760                         if (atom->asNestInset() && atom->isActive()) {
761                                 cur.posBackward();
762                                 cur.pushBackward(*cur.nextInset());
763                         }
764                 } else if (!interpretChar(cur, cmd.argument()[0])) {
765                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
766                         cur.undispatched();
767                 }
768                 break;
769
770         //case LFUN_SERVER_GET_XY:
771         //      sprintf(dispatch_buffer, "%d %d",);
772         //      break;
773
774         case LFUN_SERVER_SET_XY: {
775                 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
776                 int x = 0;
777                 int y = 0;
778                 istringstream is(to_utf8(cmd.argument()));
779                 is >> x >> y;
780                 cur.setScreenPos(x, y);
781                 break;
782         }
783
784         // Special casing for superscript in case of LyX handling
785         // dead-keys:
786         case LFUN_ACCENT_CIRCUMFLEX:
787                 if (cmd.argument().empty()) {
788                         // do superscript if LyX handles
789                         // deadkeys
790                         cur.recordUndo();
791                         script(cur, true, grabAndEraseSelection(cur));
792                 }
793                 break;
794
795         case LFUN_ACCENT_UMLAUT:
796         case LFUN_ACCENT_ACUTE:
797         case LFUN_ACCENT_GRAVE:
798         case LFUN_ACCENT_BREVE:
799         case LFUN_ACCENT_DOT:
800         case LFUN_ACCENT_MACRON:
801         case LFUN_ACCENT_CARON:
802         case LFUN_ACCENT_TILDE:
803         case LFUN_ACCENT_CEDILLA:
804         case LFUN_ACCENT_CIRCLE:
805         case LFUN_ACCENT_UNDERDOT:
806         case LFUN_ACCENT_TIE:
807         case LFUN_ACCENT_OGONEK:
808         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
809                 break;
810
811         //  Math fonts
812         case LFUN_FONT_FREE_APPLY:
813         case LFUN_FONT_FREE_UPDATE:
814                 handleFont2(cur, cmd.argument());
815                 break;
816
817         case LFUN_FONT_BOLD:
818                 if (currentMode() == TEXT_MODE)
819                         handleFont(cur, cmd.argument(), "textbf");
820                 else
821                         handleFont(cur, cmd.argument(), "mathbf");
822                 break;
823         case LFUN_FONT_SANS:
824                 if (currentMode() == TEXT_MODE)
825                         handleFont(cur, cmd.argument(), "textsf");
826                 else
827                         handleFont(cur, cmd.argument(), "mathsf");
828                 break;
829         case LFUN_FONT_EMPH:
830                 if (currentMode() == TEXT_MODE)
831                         handleFont(cur, cmd.argument(), "emph");
832                 else
833                         handleFont(cur, cmd.argument(), "mathcal");
834                 break;
835         case LFUN_FONT_ROMAN:
836                 if (currentMode() == TEXT_MODE)
837                         handleFont(cur, cmd.argument(), "textrm");
838                 else
839                         handleFont(cur, cmd.argument(), "mathrm");
840                 break;
841         case LFUN_FONT_TYPEWRITER:
842                 if (currentMode() == TEXT_MODE)
843                         handleFont(cur, cmd.argument(), "texttt");
844                 else
845                         handleFont(cur, cmd.argument(), "mathtt");
846                 break;
847         case LFUN_FONT_FRAK:
848                 handleFont(cur, cmd.argument(), "mathfrak");
849                 break;
850         case LFUN_FONT_ITAL:
851                 if (currentMode() == TEXT_MODE)
852                         handleFont(cur, cmd.argument(), "textit");
853                 else
854                         handleFont(cur, cmd.argument(), "mathit");
855                 break;
856         case LFUN_FONT_NOUN:
857                 if (currentMode() == TEXT_MODE)
858                         // FIXME: should be "noun"
859                         handleFont(cur, cmd.argument(), "textsc");
860                 else
861                         handleFont(cur, cmd.argument(), "mathbb");
862                 break;
863         /*
864         case LFUN_FONT_FREE_APPLY:
865                 handleFont(cur, cmd.argument(), "textrm");
866                 break;
867         */
868         case LFUN_FONT_DEFAULT:
869                 handleFont(cur, cmd.argument(), "textnormal");
870                 break;
871
872         case LFUN_MATH_MODE: {
873 #if 1
874                 // ignore math-mode on when already in math mode
875                 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
876                         break;
877                 cur.macroModeClose();
878                 docstring const save_selection = grabAndEraseSelection(cur);
879                 selClearOrDel(cur);
880                 //cur.plainInsert(MathAtom(new InsetMathMBox(cur.bv())));
881                 cur.plainInsert(MathAtom(new InsetMathBox(from_ascii("mbox"))));
882                 cur.posBackward();
883                 cur.pushBackward(*cur.nextInset());
884                 cur.niceInsert(save_selection);
885 #else
886                 if (currentMode() == Inset::TEXT_MODE) {
887                         cur.niceInsert(MathAtom(new InsetMathHull("simple")));
888                         cur.message(_("create new math text environment ($...$)"));
889                 } else {
890                         handleFont(cur, cmd.argument(), "textrm");
891                         cur.message(_("entered math text mode (textrm)"));
892                 }
893 #endif
894                 break;
895         }
896
897         case LFUN_MATH_SIZE:
898 #if 0
899                 cur.recordUndo();
900                 cur.setSize(arg);
901 #endif
902                 break;
903
904         case LFUN_MATH_MATRIX: {
905                 cur.recordUndo();
906                 unsigned int m = 1;
907                 unsigned int n = 1;
908                 docstring v_align;
909                 docstring h_align;
910                 idocstringstream is(cmd.argument());
911                 is >> m >> n >> v_align >> h_align;
912                 if (m < 1)
913                         m = 1;
914                 if (n < 1)
915                         n = 1;
916                 v_align += 'c';
917                 cur.niceInsert(
918                         MathAtom(new InsetMathArray(from_ascii("array"), m, n, (char)v_align[0], h_align)));
919                 break;
920         }
921
922         case LFUN_MATH_DELIM: {
923                 docstring ls;
924                 docstring rs = split(cmd.argument(), ls, ' ');
925                 // Reasonable default values
926                 if (ls.empty())
927                         ls = '(';
928                 if (rs.empty())
929                         rs = ')';
930                 cur.recordUndo();
931                 cur.handleNest(MathAtom(new InsetMathDelim(ls, rs)));
932                 break;
933         }
934
935         case LFUN_MATH_BIGDELIM: {
936                 docstring const lname  = from_utf8(cmd.getArg(0));
937                 docstring const ldelim = from_utf8(cmd.getArg(1));
938                 docstring const rname  = from_utf8(cmd.getArg(2));
939                 docstring const rdelim = from_utf8(cmd.getArg(3));
940                 latexkeys const * l = in_word_set(lname);
941                 bool const have_l = l && l->inset == "big" &&
942                                     InsetMathBig::isBigInsetDelim(ldelim);
943                 l = in_word_set(rname);
944                 bool const have_r = l && l->inset == "big" &&
945                                     InsetMathBig::isBigInsetDelim(rdelim);
946                 // We mimic LFUN_MATH_DELIM in case we have an empty left
947                 // or right delimiter.
948                 if (have_l || have_r) {
949                         cur.recordUndo();
950                         docstring const selection = grabAndEraseSelection(cur);
951                         selClearOrDel(cur);
952                         if (have_l)
953                                 cur.insert(MathAtom(new InsetMathBig(lname,
954                                                                 ldelim)));
955                         cur.niceInsert(selection);
956                         if (have_r)
957                                 cur.insert(MathAtom(new InsetMathBig(rname,
958                                                                 rdelim)));
959                 }
960                 // Don't call cur.undispatched() if we did nothing, this would
961                 // lead to infinite recursion via Text::dispatch().
962                 break;
963         }
964
965         case LFUN_SPACE_INSERT:
966         case LFUN_MATH_SPACE:
967                 cur.recordUndo();
968                 cur.insert(MathAtom(new InsetMathSpace(from_ascii(","))));
969                 break;
970
971         case LFUN_ERT_INSERT:
972                 // interpret this as if a backslash was typed
973                 cur.recordUndo();
974                 interpretChar(cur, '\\');
975                 break;
976
977         case LFUN_MATH_SUBSCRIPT:
978                 // interpret this as if a _ was typed
979                 cur.recordUndo();
980                 interpretChar(cur, '_');
981                 break;
982
983         case LFUN_MATH_SUPERSCRIPT:
984                 // interpret this as if a ^ was typed
985                 cur.recordUndo();
986                 interpretChar(cur, '^');
987                 break;
988                 
989         case LFUN_MATH_MACRO_FOLD:
990         case LFUN_MATH_MACRO_UNFOLD: {
991                 Cursor it = cur;
992                 bool fold = cmd.action == LFUN_MATH_MACRO_FOLD;
993                 bool found = findMacroToFoldUnfold(it, fold);
994                 if (found) {
995                         MathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
996                         cur.recordUndoInset();
997                         if (fold)
998                                 macro->fold(cur);
999                         else
1000                                 macro->unfold(cur);
1001                 }
1002                 break;
1003         }
1004
1005         case LFUN_QUOTE_INSERT:
1006                 // interpret this as if a straight " was typed
1007                 cur.recordUndo();
1008                 interpretChar(cur, '\"');
1009                 break;
1010
1011 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1012 // handling such that "self-insert" works on "arbitrary stuff" too, and
1013 // math-insert only handles special math things like "matrix".
1014         case LFUN_MATH_INSERT: {
1015                 cur.recordUndo();
1016                 if (cmd.argument() == "^" || cmd.argument() == "_") {
1017                         interpretChar(cur, cmd.argument()[0]);
1018                 } else
1019                         cur.niceInsert(cmd.argument());
1020                 break;
1021                 }
1022
1023         case LFUN_DIALOG_SHOW_NEW_INSET: {
1024                 docstring const & name = cmd.argument();
1025                 string data;
1026                 if (name == "ref") {
1027                         InsetMathRef tmp(name);
1028                         data = tmp.createDialogStr(to_utf8(name));
1029                 }
1030                 cur.bv().showDialog(to_utf8(name), data);
1031                 break;
1032         }
1033
1034         case LFUN_INSET_INSERT: {
1035                 MathData ar;
1036                 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1037                         cur.recordUndo();
1038                         cur.insert(ar);
1039                 } else
1040                         cur.undispatched();
1041                 break;
1042         }
1043         case LFUN_INSET_DISSOLVE:
1044                 if (!asHullInset()) {
1045                         cur.recordUndoInset();
1046                         cur.pullArg();
1047                 }
1048                 break;
1049
1050         default:
1051                 InsetMath::doDispatch(cur, cmd);
1052                 break;
1053         }
1054 }
1055
1056
1057 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1058         // look for macro to open/close, but stay in mathed
1059         for (; !it.empty(); it.pop_back()) {
1060                         
1061                 // go backward through the current cell
1062                 Inset * inset = it.nextInset();
1063                 while (inset && inset->asInsetMath()) {
1064                         MathMacro * macro = inset->asInsetMath()->asMacro();
1065                         if (macro) {
1066                                 // found the an macro to open/close?
1067                                 if (macro->folded() != fold)
1068                                         return true;
1069                                 
1070                                 // Wrong folding state.
1071                                 // If this was the first we see in this slice, look further left,
1072                                 // otherwise go up.
1073                                 if (inset != it.nextInset())
1074                                         break;
1075                         }
1076                         
1077                         // go up if this was the left most position
1078                         if (it.pos() == 0)
1079                                 break;
1080                         
1081                         // go left
1082                         it.pos()--;
1083                         inset = it.nextInset();
1084                 }
1085         }
1086         
1087         return false;
1088 }
1089
1090
1091 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1092                 FuncStatus & flag) const
1093 {
1094         // the font related toggles
1095         //string tc = "mathnormal";
1096         bool ret = true;
1097         string const arg = to_utf8(cmd.argument());
1098         switch (cmd.action) {
1099         case LFUN_TABULAR_FEATURE:
1100                 flag.enabled(false);
1101                 break;
1102 #if 0
1103         case LFUN_TABULAR_FEATURE:
1104                 // FIXME: check temporarily disabled
1105                 // valign code
1106                 char align = mathcursor::valign();
1107                 if (align == '\0') {
1108                         enable = false;
1109                         break;
1110                 }
1111                 if (cmd.argument().empty()) {
1112                         flag.clear();
1113                         break;
1114                 }
1115                 if (!contains("tcb", cmd.argument()[0])) {
1116                         enable = false;
1117                         break;
1118                 }
1119                 flag.setOnOff(cmd.argument()[0] == align);
1120                 break;
1121 #endif
1122         /// We have to handle them since 1.4 blocks all unhandled actions
1123         case LFUN_FONT_ITAL:
1124         case LFUN_FONT_BOLD:
1125         case LFUN_FONT_SANS:
1126         case LFUN_FONT_EMPH:
1127         case LFUN_FONT_TYPEWRITER:
1128         case LFUN_FONT_NOUN:
1129         case LFUN_FONT_ROMAN:
1130         case LFUN_FONT_DEFAULT:
1131                 flag.enabled(true);
1132                 break;
1133         case LFUN_MATH_MUTATE:
1134                 //flag.setOnOff(mathcursor::formula()->hullType() == to_utf8(cmd.argument()));
1135                 flag.setOnOff(false);
1136                 break;
1137
1138         // we just need to be in math mode to enable that
1139         case LFUN_MATH_SIZE:
1140         case LFUN_MATH_SPACE:
1141         case LFUN_MATH_LIMITS:
1142         case LFUN_MATH_EXTERN:
1143                 flag.enabled(true);
1144                 break;
1145
1146         case LFUN_FONT_FRAK:
1147                 flag.enabled(currentMode() != TEXT_MODE);
1148                 break;
1149
1150         case LFUN_MATH_INSERT: {
1151                 bool const textarg =
1152                         arg == "\\textbf"   || arg == "\\textsf" ||
1153                         arg == "\\textrm"   || arg == "\\textmd" ||
1154                         arg == "\\textit"   || arg == "\\textsc" ||
1155                         arg == "\\textsl"   || arg == "\\textup" ||
1156                         arg == "\\texttt"   || arg == "\\textbb" ||
1157                         arg == "\\textnormal";
1158                 flag.enabled(currentMode() != TEXT_MODE || textarg);
1159                 break;
1160         }
1161
1162         case LFUN_MATH_MATRIX:
1163                 flag.enabled(currentMode() == MATH_MODE);
1164                 break;
1165
1166         case LFUN_INSET_INSERT: {
1167                 // Don't test createMathInset_fromDialogStr(), since
1168                 // getStatus is not called with a valid reference and the
1169                 // dialog would not be applyable.
1170                 string const name = cmd.getArg(0);
1171                 flag.enabled(name == "ref");
1172                 break;
1173         }
1174
1175         case LFUN_MATH_DELIM:
1176         case LFUN_MATH_BIGDELIM:
1177                 // Don't do this with multi-cell selections
1178                 flag.enabled(cur.selBegin().idx() == cur.selEnd().idx());
1179                 break;
1180                 
1181         case LFUN_MATH_MACRO_FOLD:
1182         case LFUN_MATH_MACRO_UNFOLD: {
1183                 Cursor it = cur;
1184                 bool found = findMacroToFoldUnfold(it, cmd.action == LFUN_MATH_MACRO_FOLD);
1185                 flag.enabled(found);
1186                 break;
1187         }
1188                 
1189         case LFUN_SPECIALCHAR_INSERT:
1190                 // FIXME: These would probably make sense in math-text mode
1191                 flag.enabled(false);
1192                 break;
1193
1194         case LFUN_INSET_DISSOLVE:
1195                 flag.enabled(!asHullInset());
1196                 break;
1197
1198         default:
1199                 ret = false;
1200                 break;
1201         }
1202         return ret;
1203 }
1204
1205
1206 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1207 {
1208         cur.push(*this);
1209         bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_RIGHT || 
1210                 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1211         cur.idx() = enter_front ? 0 : cur.lastidx();
1212         cur.pos() = enter_front ? 0 : cur.lastpos();
1213         cur.resetAnchor();
1214         //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1215 }
1216
1217
1218 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1219 {
1220         int idx_min = 0;
1221         int dist_min = 1000000;
1222         for (idx_type i = 0, n = nargs(); i != n; ++i) {
1223                 int const d = cell(i).dist(cur.bv(), x, y);
1224                 if (d < dist_min) {
1225                         dist_min = d;
1226                         idx_min = i;
1227                 }
1228         }
1229         MathData & ar = cell(idx_min);
1230         cur.push(*this);
1231         cur.idx() = idx_min;
1232         cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1233
1234         //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1235         if (dist_min == 0) {
1236                 // hit inside cell
1237                 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1238                         if (ar[i]->covers(cur.bv(), x, y))
1239                                 return ar[i].nucleus()->editXY(cur, x, y);
1240         }
1241         return this;
1242 }
1243
1244
1245 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1246 {
1247         //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1248         BufferView & bv = cur.bv();
1249         bool do_selection = cmd.button() == mouse_button::button1
1250                 && cmd.argument() == "region-select";
1251         bv.mouseSetCursor(cur, do_selection);
1252         if (cmd.button() == mouse_button::button1) {
1253                 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1254                 // Update the cursor update flags as needed:
1255                 //
1256                 // Update::Decoration: tells to update the decoration
1257                 //                     (visual box corners that define
1258                 //                     the inset)/
1259                 // Update::FitCursor: adjust the screen to the cursor
1260                 //                    position if needed
1261                 // cur.result().update(): don't overwrite previously set flags.
1262                 cur.updateFlags(Update::Decoration | Update::FitCursor 
1263                                 | cur.result().update());
1264         } else if (cmd.button() == mouse_button::button2) {
1265                 if (cap::selection()) {
1266                         // See comment in Text::dispatch why we do this
1267                         cap::copySelectionToStack();
1268                         cmd = FuncRequest(LFUN_PASTE, "0");
1269                         doDispatch(bv.cursor(), cmd);
1270                 } else {
1271                         MathData ar;
1272                         asArray(theSelection().get(), ar);
1273                         bv.cursor().insert(ar);
1274                 }
1275         }
1276 }
1277
1278
1279 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1280 {
1281         // only select with button 1
1282         if (cmd.button() == mouse_button::button1) {
1283                 Cursor & bvcur = cur.bv().cursor();
1284                 if (bvcur.anchor_.hasPart(cur)) {
1285                         //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
1286                         bvcur.setCursor(cur);
1287                         bvcur.selection() = true;
1288                         //lyxerr << "MOTION " << bvcur << endl;
1289                 } else
1290                         cur.undispatched();
1291         }
1292 }
1293
1294
1295 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1296 {
1297         //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1298
1299         if (cmd.button() == mouse_button::button1) {
1300                 if (!cur.selection())
1301                         cur.noUpdate();
1302                 else {
1303                         Cursor & bvcur = cur.bv().cursor();
1304                         bvcur.selection() = true;
1305                 }
1306                 return;
1307         }
1308
1309         cur.undispatched();
1310 }
1311
1312
1313 bool InsetMathNest::interpretChar(Cursor & cur, char_type c)
1314 {
1315         //lyxerr << "interpret 2: '" << c << "'" << endl;
1316         docstring save_selection;
1317         if (c == '^' || c == '_')
1318                 save_selection = grabAndEraseSelection(cur);
1319
1320         cur.clearTargetX();
1321
1322         // handle macroMode
1323         if (cur.inMacroMode()) {
1324                 docstring name = cur.macroName();
1325
1326                 /// are we currently typing '#1' or '#2' or...?
1327                 if (name == "\\#") {
1328                         cur.backspace();
1329                         int n = c - '0';
1330                         if (n >= 1 && n <= 9)
1331                                 cur.insert(new MathMacroArgument(n));
1332                         return true;
1333                 }
1334
1335                 // do not finish macro for known * commands
1336                 MathWordList const & mwl = mathedWordList();
1337                 bool star_macro = c == '*'
1338                         && (mwl.find(name.substr(1) + "*") != mwl.end()
1339                             || cur.buffer().getMacro(name.substr(1) + "*", cur, true));
1340                 if (isAlphaASCII(c) || star_macro) {
1341                         cur.activeMacro()->setName(name + docstring(1, c));
1342                         return true;
1343                 }
1344
1345                 // handle 'special char' macros
1346                 if (name == "\\") {
1347                         // remove the '\\'
1348                         if (c == '\\') {
1349                                 cur.backspace();
1350                                 if (currentMode() == InsetMath::TEXT_MODE)
1351                                         cur.niceInsert(createInsetMath("textbackslash"));
1352                                 else
1353                                         cur.niceInsert(createInsetMath("backslash"));
1354                         } else if (c == '{') {
1355                                 cur.backspace();
1356                                 cur.niceInsert(MathAtom(new InsetMathBrace));
1357                         } else if (c == '%') {
1358                                 cur.backspace();
1359                                 cur.niceInsert(MathAtom(new InsetMathComment));
1360                         } else if (c == '#') {
1361                                 BOOST_ASSERT(cur.activeMacro());
1362                                 cur.activeMacro()->setName(name + docstring(1, c));
1363                         } else {
1364                                 cur.backspace();
1365                                 cur.niceInsert(createInsetMath(docstring(1, c)));
1366                         }
1367                         return true;
1368                 }
1369
1370                 // One character big delimiters. The others are handled in
1371                 // interpretString().
1372                 latexkeys const * l = in_word_set(name.substr(1));
1373                 if (name[0] == '\\' && l && l->inset == "big") {
1374                         docstring delim;
1375                         switch (c) {
1376                         case '{':
1377                                 delim = from_ascii("\\{");
1378                                 break;
1379                         case '}':
1380                                 delim = from_ascii("\\}");
1381                                 break;
1382                         default:
1383                                 delim = docstring(1, c);
1384                                 break;
1385                         }
1386                         if (InsetMathBig::isBigInsetDelim(delim)) {
1387                                 // name + delim ared a valid InsetMathBig.
1388                                 // We can't use cur.macroModeClose() because
1389                                 // it does not handle delim.
1390                                 InsetMathUnknown * p = cur.activeMacro();
1391                                 p->finalize();
1392                                 --cur.pos();
1393                                 cur.cell().erase(cur.pos());
1394                                 cur.plainInsert(MathAtom(
1395                                         new InsetMathBig(name.substr(1), delim)));
1396                                 return true;
1397                         }
1398                 }
1399
1400                 // leave macro mode and try again if necessary
1401                 cur.macroModeClose();
1402                 if (c == '{')
1403                         cur.niceInsert(MathAtom(new InsetMathBrace));
1404                 else if (c != ' ')
1405                         interpretChar(cur, c);
1406                 return true;
1407         }
1408
1409         // This is annoying as one has to press <space> far too often.
1410         // Disable it.
1411
1412 #if 0
1413                 // leave autocorrect mode if necessary
1414                 if (autocorrect() && c == ' ') {
1415                         autocorrect() = false;
1416                         return true;
1417                 }
1418 #endif
1419
1420         // just clear selection on pressing the space bar
1421         if (cur.selection() && c == ' ') {
1422                 cur.selection() = false;
1423                 return true;
1424         }
1425
1426         if (c == '\\') {
1427                 //lyxerr << "starting with macro" << endl;
1428                 docstring const safe = cap::grabAndEraseSelection(cur);
1429                 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1430                 return true;
1431         }
1432
1433         selClearOrDel(cur);
1434
1435         if (c == '\n') {
1436                 if (currentMode() == InsetMath::TEXT_MODE)
1437                         cur.insert(c);
1438                 return true;
1439         }
1440
1441         if (c == ' ') {
1442                 if (currentMode() == InsetMath::TEXT_MODE) {
1443                         // insert spaces in text mode,
1444                         // but suppress direct insertion of two spaces in a row
1445                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1446                         // it is better than nothing...
1447                         if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ') {
1448                                 cur.insert(c);
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                         }
1455                         return true;
1456                 }
1457                 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1458                         cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1459                         // FIXME: we have to enable full redraw here because of the
1460                         // visual box corners that define the inset. If we know for
1461                         // sure that we stay within the same cell we can optimize for
1462                         // that using:
1463                         //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1464                         return true;
1465                 }
1466
1467                 if (cur.popForward()) {
1468                         // FIXME: we have to enable full redraw here because of the
1469                         // visual box corners that define the inset. If we know for
1470                         // sure that we stay within the same cell we can optimize for
1471                         // that using:
1472                         //cur.updateFlags(Update::FitCursor);
1473                         return true;
1474                 }
1475
1476                 // if we are at the very end, leave the formula
1477                 return cur.pos() != cur.lastpos();
1478         }
1479
1480         // These shouldn't work in text mode:
1481         if (currentMode() != InsetMath::TEXT_MODE) {
1482                 if (c == '_') {
1483                         script(cur, false, save_selection);
1484                         return true;
1485                 }
1486                 if (c == '^') {
1487                         script(cur, true, save_selection);
1488                         return true;
1489                 }
1490                 if (c == '~') {
1491                         cur.niceInsert(createInsetMath("sim"));
1492                         return true;
1493                 }
1494         }
1495
1496         if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1497             c == '%' || c == '_' || c == '^') {
1498                 cur.niceInsert(createInsetMath(docstring(1, c)));
1499                 return true;
1500         }
1501
1502
1503         // try auto-correction
1504         //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1505         //      return true;
1506
1507         // no special circumstances, so insert the character without any fuss
1508         cur.insert(c);
1509         cur.autocorrect() = true;
1510         return true;
1511 }
1512
1513
1514 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1515 {
1516         // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1517         // possible
1518         if (!cur.empty() && cur.pos() > 0 &&
1519             cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1520                 if (InsetMathBig::isBigInsetDelim(str)) {
1521                         docstring prev = asString(cur.cell()[cur.pos() - 1]);
1522                         if (prev[0] == '\\') {
1523                                 prev = prev.substr(1);
1524                                 latexkeys const * l = in_word_set(prev);
1525                                 if (l && l->inset == "big") {
1526                                         cur.cell()[cur.pos() - 1] =
1527                                                 MathAtom(new InsetMathBig(prev, str));
1528                                         return true;
1529                                 }
1530                         }
1531                 }
1532         }
1533         return false;
1534 }
1535
1536
1537 bool InsetMathNest::script(Cursor & cur, bool up,
1538                 docstring const & save_selection)
1539 {
1540         // Hack to get \^ and \_ working
1541         //lyxerr << "handling script: up: " << up << endl;
1542         if (cur.inMacroMode() && cur.macroName() == "\\") {
1543                 if (up)
1544                         cur.niceInsert(createInsetMath("mathcircumflex"));
1545                 else
1546                         interpretChar(cur, '_');
1547                 return true;
1548         }
1549
1550         cur.macroModeClose();
1551         if (asScriptInset() && cur.idx() == 0) {
1552                 // we are in a nucleus of a script inset, move to _our_ script
1553                 InsetMathScript * inset = asScriptInset();
1554                 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1555                 inset->ensure(up);
1556                 cur.idx() = inset->idxOfScript(up);
1557                 cur.pos() = 0;
1558         } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1559                 --cur.pos();
1560                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1561                 cur.push(*inset);
1562                 inset->ensure(up);
1563                 cur.idx() = inset->idxOfScript(up);
1564                 cur.pos() = cur.lastpos();
1565         } else {
1566                 // convert the thing to our left to a scriptinset or create a new
1567                 // one if in the very first position of the array
1568                 if (cur.pos() == 0) {
1569                         //lyxerr << "new scriptinset" << endl;
1570                         cur.insert(new InsetMathScript(up));
1571                 } else {
1572                         //lyxerr << "converting prev atom " << endl;
1573                         cur.prevAtom() = MathAtom(new InsetMathScript(cur.prevAtom(), up));
1574                 }
1575                 --cur.pos();
1576                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1577                 // See comment in MathParser.cpp for special handling of {}-bases
1578
1579                 cur.push(*inset);
1580                 cur.idx() = 1;
1581                 cur.pos() = 0;
1582         }
1583         //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1584         cur.niceInsert(save_selection);
1585         cur.resetAnchor();
1586         //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1587         return true;
1588 }
1589
1590
1591 bool InsetMathNest::completionSupported(Cursor const & cur) const
1592 {
1593         return cur.inMacroMode();
1594 }
1595
1596
1597 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
1598 {
1599         return cur.inMacroMode();
1600 }
1601
1602
1603 bool InsetMathNest::automaticInlineCompletion() const
1604 {
1605         return lyxrc.completion_inline_math;
1606 }
1607
1608
1609 bool InsetMathNest::automaticPopupCompletion() const
1610 {
1611         return lyxrc.completion_popup_math;
1612 }
1613
1614
1615 Inset::CompletionList const *
1616 InsetMathNest::createCompletionList(Cursor const & cur) const
1617 {
1618         if (!cur.inMacroMode())
1619                 return 0;
1620         
1621         return new MathCompletionList(cur);
1622 }
1623
1624
1625 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
1626 {
1627         if (!cur.inMacroMode())
1628                 return docstring();
1629         
1630         return cur.activeMacro()->name();
1631 }
1632
1633
1634 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
1635                                      bool finished)
1636 {
1637         if (!cur.inMacroMode())
1638                 return false;
1639
1640         // append completion to active macro
1641         InsetMathUnknown * inset = cur.activeMacro();
1642         inset->setName(inset->name() + s);
1643
1644         // finish macro
1645         if (finished) {
1646 #if 0
1647                 // FIXME: this creates duplicates in the completion popup
1648                 // which looks ugly. Moreover the changes the list lengths
1649                 // which seems to
1650                 confuse the popup as well.
1651                 MathCompletionList::addToFavorites(inset->name());
1652 #endif
1653                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
1654         }
1655
1656         return true;
1657 }
1658
1659
1660 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y, 
1661                                         Dimension & dim) const
1662 {
1663         Inset const * inset = cur.activeMacro();
1664         if (!inset)
1665                 return;
1666
1667         // get inset dimensions
1668         dim = cur.bv().coordCache().insets().dim(inset);
1669         // FIXME: these 3 are no accurate, but should depend on the font.
1670         // Now the popup jumps down if you enter a char with descent > 0.
1671         dim.des += 3;
1672         dim.asc += 3;
1673
1674         // and position
1675         Point xy
1676         = cur.bv().coordCache().insets().xy(inset);
1677         x = xy.x_;
1678         y = xy.y_;
1679 }
1680
1681
1682 bool InsetMathNest::cursorMathForward(Cursor & cur)
1683 {
1684         if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
1685                 cur.pushBackward(*cur.nextAtom().nucleus());
1686                 cur.inset().idxFirst(cur);
1687                 return true;
1688         } 
1689         if (cur.posForward() || idxForward(cur) || cur.selection())
1690                 return true;
1691         // try to pop forwards --- but don't pop out of math! leave that to
1692         // the FINISH lfuns
1693         int s = cur.depth() - 2;
1694         if (s >= 0 && cur[s].inset().asInsetMath())
1695                 return cur.popForward();
1696         return false;
1697 }
1698
1699
1700 bool InsetMathNest::cursorMathBackward(Cursor & cur)
1701 {
1702         if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
1703                 cur.posBackward();
1704                 cur.push(*cur.nextAtom().nucleus());
1705                 cur.inset().idxLast(cur);
1706                 return true;
1707         } 
1708         if (cur.posBackward() || idxBackward(cur) || cur.selection())
1709                 return true;
1710         // try to pop backwards --- but don't pop out of math! leave that to 
1711         // the FINISH lfuns
1712         int s = cur.depth() - 2;
1713         if (s >= 0 && cur[s].inset().asInsetMath())
1714                 return cur.popBackward();
1715         return false;
1716 }
1717
1718
1719 ////////////////////////////////////////////////////////////////////
1720
1721 MathCompletionList::MathCompletionList(Cursor const & cur)
1722 {
1723         // fill it with macros from the buffer
1724         MacroNameSet macros;
1725         cur.buffer().listMacroNames(macros);
1726         MacroNameSet::const_iterator it;
1727         for (it = macros.begin(); it != macros.end(); ++it) {
1728                 if (cur.buffer().getMacro(*it, cur, false))
1729                         locals.push_back("\\" + *it);
1730         }
1731         sort(locals.begin(), locals.end());
1732
1733         if (globals.size() > 0)
1734                 return;
1735
1736         // fill in global macros
1737         macros.clear();
1738         MacroTable::globalMacros().getMacroNames(macros);
1739         lyxerr << "Globals completion macros: ";
1740         for (it = macros.begin(); it != macros.end(); ++it) {
1741                 lyxerr << "\\" + *it << " ";
1742                 globals.push_back("\\" + *it);
1743         }
1744         lyxerr << std::endl;
1745
1746         // fill in global commands
1747         globals.push_back(from_ascii("\\boxed"));
1748         globals.push_back(from_ascii("\\fbox"));
1749         globals.push_back(from_ascii("\\framebox"));
1750         globals.push_back(from_ascii("\\makebox"));
1751         globals.push_back(from_ascii("\\kern"));
1752         globals.push_back(from_ascii("\\xrightarrow"));
1753         globals.push_back(from_ascii("\\xleftarrow"));
1754         globals.push_back(from_ascii("\\split"));
1755         globals.push_back(from_ascii("\\gathered"));
1756         globals.push_back(from_ascii("\\aligned"));
1757         globals.push_back(from_ascii("\\alignedat"));
1758         globals.push_back(from_ascii("\\cases"));
1759         globals.push_back(from_ascii("\\substack"));
1760         globals.push_back(from_ascii("\\subarray"));
1761         globals.push_back(from_ascii("\\array"));
1762         globals.push_back(from_ascii("\\sqrt"));
1763         globals.push_back(from_ascii("\\root"));
1764         globals.push_back(from_ascii("\\tabular"));
1765         globals.push_back(from_ascii("\\stackrel"));
1766         globals.push_back(from_ascii("\\binom"));
1767         globals.push_back(from_ascii("\\choose"));
1768         globals.push_back(from_ascii("\\choose"));
1769         globals.push_back(from_ascii("\\frac"));
1770         globals.push_back(from_ascii("\\over"));
1771         globals.push_back(from_ascii("\\nicefrac"));
1772         globals.push_back(from_ascii("\\unitfrac"));
1773         globals.push_back(from_ascii("\\unitfracthree"));
1774         globals.push_back(from_ascii("\\unitone"));
1775         globals.push_back(from_ascii("\\unittwo"));
1776         globals.push_back(from_ascii("\\infer"));
1777         globals.push_back(from_ascii("\\atop"));
1778         globals.push_back(from_ascii("\\lefteqn"));
1779         globals.push_back(from_ascii("\\boldsymbol"));
1780         globals.push_back(from_ascii("\\color"));
1781         globals.push_back(from_ascii("\\normalcolor"));
1782         globals.push_back(from_ascii("\\textcolor"));
1783         globals.push_back(from_ascii("\\dfrac"));
1784         globals.push_back(from_ascii("\\tfrac"));
1785         globals.push_back(from_ascii("\\dbinom"));
1786         globals.push_back(from_ascii("\\tbinom"));
1787         globals.push_back(from_ascii("\\hphantom"));
1788         globals.push_back(from_ascii("\\phantom"));
1789         globals.push_back(from_ascii("\\vphantom"));
1790         MathWordList const & words = mathedWordList();
1791         MathWordList::const_iterator it2;
1792         lyxerr << "Globals completion commands: ";
1793         for (it2 = words.begin(); it2 != words.end(); ++it2) {
1794                 globals.push_back("\\" + (*it2).first);
1795                 lyxerr << "\\" + (*it2).first << " ";
1796         }
1797         lyxerr << std::endl;
1798         sort(globals.begin(), globals.end());
1799 }
1800
1801
1802 MathCompletionList::~MathCompletionList()
1803 {
1804 }
1805
1806
1807 size_type MathCompletionList::size() const
1808 {
1809         return locals.size() + globals.size();
1810 }
1811
1812
1813 docstring const & MathCompletionList::data(size_t idx) const
1814 {
1815         size_t lsize = locals.size();
1816         if (idx >= lsize)
1817                 return globals[idx - lsize];
1818         else
1819                 return locals[idx];
1820 }
1821
1822
1823 std::string MathCompletionList::icon(size_t idx) const 
1824 {
1825         // get the latex command
1826         docstring cmd;
1827         size_t lsize = locals.size();
1828         if (idx >= lsize)
1829                 cmd = globals[idx - lsize];
1830         else
1831                 cmd = locals[idx];
1832         
1833         // get the icon resource name by stripping the backslash
1834         return "images/math/" + to_utf8(cmd.substr(1)) + ".png";
1835 }
1836
1837 std::vector<docstring> MathCompletionList::globals;
1838
1839 } // namespace lyx