]> git.lyx.org Git - features.git/blob - src/mathed/InsetMathNest.cpp
14ec77cfd005027bae184ba56c065c7baeee7d88
[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(Buffer const &, odocstream & os,
359                         OutputParams const & runparams) const
360 {
361         WriteStream wi(os, runparams.moving_arg, true);
362         write(wi);
363         return wi.line();
364 }
365
366
367 bool InsetMathNest::setMouseHover(bool mouse_hover)
368 {
369         mouse_hover_ = mouse_hover;
370         return true;
371 }
372
373
374 bool InsetMathNest::notifyCursorLeaves(Cursor & /*cur*/)
375 {
376         // FIXME: look here
377 #if 0
378         MathData & ar = cur.cell();
379         // remove base-only "scripts"
380         for (pos_type i = 0; i + 1 < ar.size(); ++i) {
381                 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
382                 if (p && p->nargs() == 1) {
383                         MathData ar = p->nuc();
384                         erase(i);
385                         insert(i, ar);
386                         cur.adjust(i, ar.size() - 1);
387                 }
388         }
389
390         // glue adjacent font insets of the same kind
391         for (pos_type i = 0; i + 1 < size(); ++i) {
392                 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
393                 InsetMathFont const * q = operator[](i + 1)->asFontInset();
394                 if (p && q && p->name() == q->name()) {
395                         p->cell(0).append(q->cell(0));
396                         erase(i + 1);
397                         cur.adjust(i, -1);
398                 }
399         }
400 #endif
401         return false;
402 }
403
404
405 void InsetMathNest::handleFont
406         (Cursor & cur, docstring const & arg, char const * const font)
407 {
408         handleFont(cur, arg, from_ascii(font));
409 }
410
411
412 void InsetMathNest::handleFont
413         (Cursor & cur, docstring const & arg, docstring const & font)
414 {
415         // this whole function is a hack and won't work for incremental font
416         // changes...
417
418         if (cur.inset().asInsetMath()->name() == font) {
419                 cur.recordUndoInset();
420                 cur.handleFont(to_utf8(font));
421         } else {
422                 cur.recordUndo();
423                 cur.handleNest(createInsetMath(font));
424                 cur.insert(arg);
425         }
426 }
427
428
429 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
430 {
431         cur.recordUndo();
432         Font font;
433         bool b;
434         font.fromString(to_utf8(arg), b);
435         if (font.fontInfo().color() != Color_inherit) {
436                 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
437                 cur.handleNest(at, 0);
438         }
439 }
440
441
442 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
443 {
444         //lyxerr << "InsetMathNest: request: " << cmd << endl;
445         //CursorSlice sl = cur.current();
446
447         switch (cmd.action) {
448
449         case LFUN_PASTE: {
450                 cur.recordUndo();
451                 cur.message(_("Paste"));
452                 replaceSelection(cur);
453                 docstring topaste;
454                 if (cmd.argument().empty() && !theClipboard().isInternal())
455                         topaste = theClipboard().getAsText();
456                 else {
457                         size_t n = 0;
458                         idocstringstream is(cmd.argument());
459                         is >> n;
460                         topaste = cap::getSelection(cur.buffer(), n);
461                 }
462                 cur.niceInsert(topaste);
463                 cur.clearSelection(); // bug 393
464                 cur.finishUndo();
465                 break;
466         }
467
468         case LFUN_CUT:
469                 cur.recordUndo();
470                 cutSelection(cur, true, true);
471                 cur.message(_("Cut"));
472                 // Prevent stale position >= size crash
473                 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
474                 cur.normalize();
475                 break;
476
477         case LFUN_COPY:
478                 copySelection(cur);
479                 cur.message(_("Copy"));
480                 break;
481
482         case LFUN_MOUSE_PRESS:
483                 lfunMousePress(cur, cmd);
484                 break;
485
486         case LFUN_MOUSE_MOTION:
487                 lfunMouseMotion(cur, cmd);
488                 break;
489
490         case LFUN_MOUSE_RELEASE:
491                 lfunMouseRelease(cur, cmd);
492                 break;
493
494         case LFUN_FINISHED_LEFT: // in math, left is backwards
495         case LFUN_FINISHED_BACKWARD:
496                 cur.bv().cursor() = cur;
497                 break;
498
499         case LFUN_FINISHED_RIGHT: // in math, right is forward
500         case LFUN_FINISHED_FORWARD:
501                 ++cur.pos();
502                 cur.bv().cursor() = cur;
503                 break;
504
505         case LFUN_CHAR_RIGHT:
506         case LFUN_CHAR_LEFT:
507         case LFUN_CHAR_BACKWARD:
508         case LFUN_CHAR_FORWARD:
509                 cur.updateFlags(Update::Decoration | Update::FitCursor);
510         case LFUN_CHAR_RIGHT_SELECT:
511         case LFUN_CHAR_LEFT_SELECT:
512         case LFUN_CHAR_BACKWARD_SELECT:
513         case LFUN_CHAR_FORWARD_SELECT: {
514                 // are we in a selection?
515                 bool select = (cmd.action == LFUN_CHAR_RIGHT_SELECT 
516                                            || cmd.action == LFUN_CHAR_LEFT_SELECT
517                                            || cmd.action == LFUN_CHAR_BACKWARD_SELECT
518                                            || cmd.action == LFUN_CHAR_FORWARD_SELECT);
519                 // are we moving forward or backwards? 
520                 // If the command was RIGHT or LEFT, then whether we're moving forward
521                 // or backwards depends on the cursor movement mode (logical or visual):
522                 //  * in visual mode, since math is always LTR, right -> forward, 
523                 //    left -> backwards
524                 //  * in logical mode, the mapping is determined by the
525                 //    reverseDirectionNeeded() function
526                 
527                 bool forward;
528                 kb_action finish_lfun;
529
530                 if (cmd.action == LFUN_CHAR_FORWARD 
531                                 || cmd.action == LFUN_CHAR_FORWARD_SELECT) {
532                         forward = true;
533                         finish_lfun = LFUN_FINISHED_FORWARD;
534                 }
535                 else if (cmd.action == LFUN_CHAR_BACKWARD
536                                 || cmd.action == LFUN_CHAR_BACKWARD_SELECT) {
537                         forward = false;
538                         finish_lfun = LFUN_FINISHED_BACKWARD;
539                 }
540                 else {
541                         bool right = (cmd.action == LFUN_CHAR_RIGHT_SELECT
542                                                   || cmd.action == LFUN_CHAR_RIGHT);
543                         if (lyxrc.visual_cursor || !reverseDirectionNeeded(cur))
544                                 forward = right;
545                         else 
546                                 forward = !right;
547
548                         if (right)
549                                 finish_lfun = LFUN_FINISHED_RIGHT;
550                         else
551                                 finish_lfun = LFUN_FINISHED_LEFT;
552                 }
553                 // Now that we know exactly what we want to do, let's do it!
554                 cur.selHandle(select);
555                 cur.autocorrect() = false;
556                 cur.clearTargetX();
557                 cur.macroModeClose();
558                 // try moving forward or backwards as necessary...
559                 if (!(forward ? cursorMathForward(cur) : cursorMathBackward(cur))) {
560                         // ... and if movement failed, then finish forward or backwards
561                         // as necessary
562                         cmd = FuncRequest(finish_lfun);
563                         cur.undispatched();
564                 }
565                 break;
566         }
567
568         case LFUN_DOWN:
569         case LFUN_UP:
570                 cur.updateFlags(Update::Decoration | Update::FitCursor);
571         case LFUN_DOWN_SELECT:
572         case LFUN_UP_SELECT: {
573                 // close active macro
574                 if (cur.inMacroMode()) {
575                         cur.macroModeClose();
576                         break;
577                 }
578                 
579                 // stop/start the selection
580                 bool select = cmd.action == LFUN_DOWN_SELECT ||
581                         cmd.action == LFUN_UP_SELECT;
582                 cur.selHandle(select);
583                 
584                 // go up/down
585                 bool up = cmd.action == LFUN_UP || cmd.action == LFUN_UP_SELECT;
586                 bool successful = cur.upDownInMath(up);
587                 if (successful) {
588                         // notify left insets and give them chance to set update flags
589                         lyx::notifyCursorLeaves(cur.beforeDispatchCursor(), cur);
590                         cur.fixIfBroken();
591                         break;
592                 }
593                 
594                 if (cur.fixIfBroken())
595                         // FIXME: Something bad happened. We pass the corrected Cursor
596                         // instead of letting things go worse.
597                         break;
598
599                 // We did not manage to move the cursor.
600                 cur.undispatched();
601                 break;
602         }
603
604         case LFUN_MOUSE_DOUBLE:
605         case LFUN_MOUSE_TRIPLE:
606         case LFUN_WORD_SELECT:
607                 cur.pos() = 0;
608                 cur.idx() = 0;
609                 cur.resetAnchor();
610                 cur.selection() = true;
611                 cur.pos() = cur.lastpos();
612                 cur.idx() = cur.lastidx();
613                 break;
614
615         case LFUN_PARAGRAPH_UP:
616         case LFUN_PARAGRAPH_DOWN:
617                 cur.updateFlags(Update::Decoration | Update::FitCursor);
618         case LFUN_PARAGRAPH_UP_SELECT:
619         case LFUN_PARAGRAPH_DOWN_SELECT:
620                 break;
621
622         case LFUN_LINE_BEGIN:
623         case LFUN_WORD_BACKWARD:
624         case LFUN_WORD_LEFT:
625                 cur.updateFlags(Update::Decoration | Update::FitCursor);
626         case LFUN_LINE_BEGIN_SELECT:
627         case LFUN_WORD_BACKWARD_SELECT:
628         case LFUN_WORD_LEFT_SELECT:
629                 cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT ||
630                                 cmd.action == LFUN_WORD_LEFT_SELECT || 
631                                 cmd.action == LFUN_LINE_BEGIN_SELECT);
632                 cur.macroModeClose();
633                 if (cur.pos() != 0) {
634                         cur.pos() = 0;
635                 } else if (cur.col() != 0) {
636                         cur.idx() -= cur.col();
637                         cur.pos() = 0;
638                 } else if (cur.idx() != 0) {
639                         cur.idx() = 0;
640                         cur.pos() = 0;
641                 } else {
642                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
643                         cur.undispatched();
644                 }
645                 break;
646
647         case LFUN_WORD_FORWARD:
648         case LFUN_WORD_RIGHT:
649         case LFUN_LINE_END:
650                 cur.updateFlags(Update::Decoration | Update::FitCursor);
651         case LFUN_WORD_FORWARD_SELECT:
652         case LFUN_WORD_RIGHT_SELECT:
653         case LFUN_LINE_END_SELECT:
654                 cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT ||
655                                 cmd.action == LFUN_WORD_RIGHT_SELECT ||
656                                 cmd.action == LFUN_LINE_END_SELECT);
657                 cur.macroModeClose();
658                 cur.clearTargetX();
659                 if (cur.pos() != cur.lastpos()) {
660                         cur.pos() = cur.lastpos();
661                 } else if (ncols() && (cur.col() != cur.lastcol())) {
662                         cur.idx() = cur.idx() - cur.col() + cur.lastcol();
663                         cur.pos() = cur.lastpos();
664                 } else if (cur.idx() != cur.lastidx()) {
665                         cur.idx() = cur.lastidx();
666                         cur.pos() = cur.lastpos();
667                 } else {
668                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
669                         cur.undispatched();
670                 }
671                 break;
672
673         case LFUN_SCREEN_UP_SELECT:
674                 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
675                 cur.undispatched();
676                 break;
677
678         case LFUN_SCREEN_DOWN_SELECT:
679                 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
680                 cur.undispatched();
681                 break;
682
683         case LFUN_CELL_FORWARD:
684                 cur.updateFlags(Update::Decoration | Update::FitCursor);
685                 cur.inset().idxNext(cur);
686                 break;
687
688         case LFUN_CELL_BACKWARD:
689                 cur.updateFlags(Update::Decoration | Update::FitCursor);
690                 cur.inset().idxPrev(cur);
691                 break;
692
693         case LFUN_WORD_DELETE_BACKWARD:
694         case LFUN_CHAR_DELETE_BACKWARD:
695                 if (cur.pos() == 0)
696                         // May affect external cell:
697                         cur.recordUndoInset();
698                 else
699                         cur.recordUndo();
700                 // if the inset can not be removed from within, delete it
701                 if (!cur.backspace()) {
702                         FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
703                         cur.innerText()->dispatch(cur, cmd);
704                 }
705                 break;
706
707         case LFUN_WORD_DELETE_FORWARD:
708         case LFUN_CHAR_DELETE_FORWARD:
709                 if (cur.pos() == cur.lastpos())
710                         // May affect external cell:
711                         cur.recordUndoInset();
712                 else
713                         cur.recordUndo();
714                 // if the inset can not be removed from within, delete it
715                 if (!cur.erase()) {
716                         FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
717                         cur.innerText()->dispatch(cur, cmd);
718                 }
719                 break;
720
721         case LFUN_ESCAPE:
722                 if (cur.selection())
723                         cur.clearSelection();
724                 else  {
725                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
726                         cur.undispatched();
727                 }
728                 break;
729
730         // 'Locks' the math inset. A 'locked' math inset behaves as a unit
731         // that is traversed by a single <CursorLeft>/<CursorRight>.
732         case LFUN_INSET_TOGGLE:
733                 cur.recordUndo();
734                 lock(!lock());
735                 cur.popForward();
736                 break;
737
738         case LFUN_SELF_INSERT:
739                 if (cmd.argument().size() != 1) {
740                         cur.recordUndo();
741                         docstring const arg = cmd.argument();
742                         if (!interpretString(cur, arg))
743                                 cur.insert(arg);
744                         break;
745                 }
746                 // Don't record undo steps if we are in macro mode and
747                 // cmd.argument is the next character of the macro name.
748                 // Otherwise we'll get an invalid cursor if we undo after
749                 // the macro was finished and the macro is a known command,
750                 // e.g. sqrt. Cursor::macroModeClose replaces in this case
751                 // the InsetMathUnknown with name "frac" by an empty
752                 // InsetMathFrac -> a pos value > 0 is invalid.
753                 // A side effect is that an undo before the macro is finished
754                 // undoes the complete macro, not only the last character.
755                 if (!cur.inMacroMode())
756                         cur.recordUndo();
757
758                 // spacial handling of space. If we insert an inset
759                 // via macro mode, we want to put the cursor inside it
760                 // if relevant. Think typing "\frac<space>".
761                 if (cmd.argument()[0] == ' '
762                     && cur.inMacroMode() && cur.macroName() != "\\"
763                     && cur.macroModeClose()) {
764                         MathAtom const atom = cur.prevAtom();
765                         if (atom->asNestInset() && atom->isActive()) {
766                                 cur.posBackward();
767                                 cur.pushBackward(*cur.nextInset());
768                         }
769                 } else if (!interpretChar(cur, cmd.argument()[0])) {
770                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
771                         cur.undispatched();
772                 }
773                 break;
774
775         //case LFUN_SERVER_GET_XY:
776         //      sprintf(dispatch_buffer, "%d %d",);
777         //      break;
778
779         case LFUN_SERVER_SET_XY: {
780                 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
781                 int x = 0;
782                 int y = 0;
783                 istringstream is(to_utf8(cmd.argument()));
784                 is >> x >> y;
785                 cur.setScreenPos(x, y);
786                 break;
787         }
788
789         // Special casing for superscript in case of LyX handling
790         // dead-keys:
791         case LFUN_ACCENT_CIRCUMFLEX:
792                 if (cmd.argument().empty()) {
793                         // do superscript if LyX handles
794                         // deadkeys
795                         cur.recordUndo();
796                         script(cur, true, grabAndEraseSelection(cur));
797                 }
798                 break;
799
800         case LFUN_ACCENT_UMLAUT:
801         case LFUN_ACCENT_ACUTE:
802         case LFUN_ACCENT_GRAVE:
803         case LFUN_ACCENT_BREVE:
804         case LFUN_ACCENT_DOT:
805         case LFUN_ACCENT_MACRON:
806         case LFUN_ACCENT_CARON:
807         case LFUN_ACCENT_TILDE:
808         case LFUN_ACCENT_CEDILLA:
809         case LFUN_ACCENT_CIRCLE:
810         case LFUN_ACCENT_UNDERDOT:
811         case LFUN_ACCENT_TIE:
812         case LFUN_ACCENT_OGONEK:
813         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
814                 break;
815
816         //  Math fonts
817         case LFUN_FONT_FREE_APPLY:
818         case LFUN_FONT_FREE_UPDATE:
819                 handleFont2(cur, cmd.argument());
820                 break;
821
822         case LFUN_FONT_BOLD:
823                 if (currentMode() == TEXT_MODE)
824                         handleFont(cur, cmd.argument(), "textbf");
825                 else
826                         handleFont(cur, cmd.argument(), "mathbf");
827                 break;
828         case LFUN_FONT_SANS:
829                 if (currentMode() == TEXT_MODE)
830                         handleFont(cur, cmd.argument(), "textsf");
831                 else
832                         handleFont(cur, cmd.argument(), "mathsf");
833                 break;
834         case LFUN_FONT_EMPH:
835                 if (currentMode() == TEXT_MODE)
836                         handleFont(cur, cmd.argument(), "emph");
837                 else
838                         handleFont(cur, cmd.argument(), "mathcal");
839                 break;
840         case LFUN_FONT_ROMAN:
841                 if (currentMode() == TEXT_MODE)
842                         handleFont(cur, cmd.argument(), "textrm");
843                 else
844                         handleFont(cur, cmd.argument(), "mathrm");
845                 break;
846         case LFUN_FONT_TYPEWRITER:
847                 if (currentMode() == TEXT_MODE)
848                         handleFont(cur, cmd.argument(), "texttt");
849                 else
850                         handleFont(cur, cmd.argument(), "mathtt");
851                 break;
852         case LFUN_FONT_FRAK:
853                 handleFont(cur, cmd.argument(), "mathfrak");
854                 break;
855         case LFUN_FONT_ITAL:
856                 if (currentMode() == TEXT_MODE)
857                         handleFont(cur, cmd.argument(), "textit");
858                 else
859                         handleFont(cur, cmd.argument(), "mathit");
860                 break;
861         case LFUN_FONT_NOUN:
862                 if (currentMode() == TEXT_MODE)
863                         // FIXME: should be "noun"
864                         handleFont(cur, cmd.argument(), "textsc");
865                 else
866                         handleFont(cur, cmd.argument(), "mathbb");
867                 break;
868         /*
869         case LFUN_FONT_FREE_APPLY:
870                 handleFont(cur, cmd.argument(), "textrm");
871                 break;
872         */
873         case LFUN_FONT_DEFAULT:
874                 handleFont(cur, cmd.argument(), "textnormal");
875                 break;
876
877         case LFUN_MATH_MODE: {
878 #if 1
879                 // ignore math-mode on when already in math mode
880                 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
881                         break;
882                 cur.macroModeClose();
883                 docstring const save_selection = grabAndEraseSelection(cur);
884                 selClearOrDel(cur);
885                 //cur.plainInsert(MathAtom(new InsetMathMBox(cur.bv())));
886                 cur.plainInsert(MathAtom(new InsetMathBox(from_ascii("mbox"))));
887                 cur.posBackward();
888                 cur.pushBackward(*cur.nextInset());
889                 cur.niceInsert(save_selection);
890 #else
891                 if (currentMode() == Inset::TEXT_MODE) {
892                         cur.niceInsert(MathAtom(new InsetMathHull("simple")));
893                         cur.message(_("create new math text environment ($...$)"));
894                 } else {
895                         handleFont(cur, cmd.argument(), "textrm");
896                         cur.message(_("entered math text mode (textrm)"));
897                 }
898 #endif
899                 break;
900         }
901
902         case LFUN_MATH_SIZE:
903 #if 0
904                 cur.recordUndo();
905                 cur.setSize(arg);
906 #endif
907                 break;
908
909         case LFUN_MATH_MATRIX: {
910                 cur.recordUndo();
911                 unsigned int m = 1;
912                 unsigned int n = 1;
913                 docstring v_align;
914                 docstring h_align;
915                 idocstringstream is(cmd.argument());
916                 is >> m >> n >> v_align >> h_align;
917                 if (m < 1)
918                         m = 1;
919                 if (n < 1)
920                         n = 1;
921                 v_align += 'c';
922                 cur.niceInsert(
923                         MathAtom(new InsetMathArray(from_ascii("array"), m, n, (char)v_align[0], h_align)));
924                 break;
925         }
926
927         case LFUN_MATH_DELIM: {
928                 docstring ls;
929                 docstring rs = split(cmd.argument(), ls, ' ');
930                 // Reasonable default values
931                 if (ls.empty())
932                         ls = '(';
933                 if (rs.empty())
934                         rs = ')';
935                 cur.recordUndo();
936                 cur.handleNest(MathAtom(new InsetMathDelim(ls, rs)));
937                 break;
938         }
939
940         case LFUN_MATH_BIGDELIM: {
941                 docstring const lname  = from_utf8(cmd.getArg(0));
942                 docstring const ldelim = from_utf8(cmd.getArg(1));
943                 docstring const rname  = from_utf8(cmd.getArg(2));
944                 docstring const rdelim = from_utf8(cmd.getArg(3));
945                 latexkeys const * l = in_word_set(lname);
946                 bool const have_l = l && l->inset == "big" &&
947                                     InsetMathBig::isBigInsetDelim(ldelim);
948                 l = in_word_set(rname);
949                 bool const have_r = l && l->inset == "big" &&
950                                     InsetMathBig::isBigInsetDelim(rdelim);
951                 // We mimic LFUN_MATH_DELIM in case we have an empty left
952                 // or right delimiter.
953                 if (have_l || have_r) {
954                         cur.recordUndo();
955                         docstring const selection = grabAndEraseSelection(cur);
956                         selClearOrDel(cur);
957                         if (have_l)
958                                 cur.insert(MathAtom(new InsetMathBig(lname,
959                                                                 ldelim)));
960                         cur.niceInsert(selection);
961                         if (have_r)
962                                 cur.insert(MathAtom(new InsetMathBig(rname,
963                                                                 rdelim)));
964                 }
965                 // Don't call cur.undispatched() if we did nothing, this would
966                 // lead to infinite recursion via Text::dispatch().
967                 break;
968         }
969
970         case LFUN_SPACE_INSERT:
971         case LFUN_MATH_SPACE:
972                 cur.recordUndo();
973                 cur.insert(MathAtom(new InsetMathSpace(from_ascii(","))));
974                 break;
975
976         case LFUN_ERT_INSERT:
977                 // interpret this as if a backslash was typed
978                 cur.recordUndo();
979                 interpretChar(cur, '\\');
980                 break;
981
982         case LFUN_MATH_SUBSCRIPT:
983                 // interpret this as if a _ was typed
984                 cur.recordUndo();
985                 interpretChar(cur, '_');
986                 break;
987
988         case LFUN_MATH_SUPERSCRIPT:
989                 // interpret this as if a ^ was typed
990                 cur.recordUndo();
991                 interpretChar(cur, '^');
992                 break;
993                 
994         case LFUN_MATH_MACRO_FOLD:
995         case LFUN_MATH_MACRO_UNFOLD: {
996                 Cursor it = cur;
997                 bool fold = cmd.action == LFUN_MATH_MACRO_FOLD;
998                 bool found = findMacroToFoldUnfold(it, fold);
999                 if (found) {
1000                         MathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1001                         cur.recordUndoInset();
1002                         if (fold)
1003                                 macro->fold(cur);
1004                         else
1005                                 macro->unfold(cur);
1006                 }
1007                 break;
1008         }
1009
1010         case LFUN_QUOTE_INSERT:
1011                 // interpret this as if a straight " was typed
1012                 cur.recordUndo();
1013                 interpretChar(cur, '\"');
1014                 break;
1015
1016 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1017 // handling such that "self-insert" works on "arbitrary stuff" too, and
1018 // math-insert only handles special math things like "matrix".
1019         case LFUN_MATH_INSERT: {
1020                 cur.recordUndo();
1021                 if (cmd.argument() == "^" || cmd.argument() == "_") {
1022                         interpretChar(cur, cmd.argument()[0]);
1023                 } else
1024                         cur.niceInsert(cmd.argument());
1025                 break;
1026                 }
1027
1028         case LFUN_DIALOG_SHOW_NEW_INSET: {
1029                 docstring const & name = cmd.argument();
1030                 string data;
1031                 if (name == "ref") {
1032                         InsetMathRef tmp(name);
1033                         data = tmp.createDialogStr(to_utf8(name));
1034                 }
1035                 cur.bv().showDialog(to_utf8(name), data);
1036                 break;
1037         }
1038
1039         case LFUN_INSET_INSERT: {
1040                 MathData ar;
1041                 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1042                         cur.recordUndo();
1043                         cur.insert(ar);
1044                 } else
1045                         cur.undispatched();
1046                 break;
1047         }
1048         case LFUN_INSET_DISSOLVE:
1049                 if (!asHullInset()) {
1050                         cur.recordUndoInset();
1051                         cur.pullArg();
1052                 }
1053                 break;
1054
1055         default:
1056                 InsetMath::doDispatch(cur, cmd);
1057                 break;
1058         }
1059 }
1060
1061
1062 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1063         // look for macro to open/close, but stay in mathed
1064         for (; !it.empty(); it.pop_back()) {
1065                         
1066                 // go backward through the current cell
1067                 Inset * inset = it.nextInset();
1068                 while (inset && inset->asInsetMath()) {
1069                         MathMacro * macro = inset->asInsetMath()->asMacro();
1070                         if (macro) {
1071                                 // found the an macro to open/close?
1072                                 if (macro->folded() != fold)
1073                                         return true;
1074                                 
1075                                 // Wrong folding state.
1076                                 // If this was the first we see in this slice, look further left,
1077                                 // otherwise go up.
1078                                 if (inset != it.nextInset())
1079                                         break;
1080                         }
1081                         
1082                         // go up if this was the left most position
1083                         if (it.pos() == 0)
1084                                 break;
1085                         
1086                         // go left
1087                         it.pos()--;
1088                         inset = it.nextInset();
1089                 }
1090         }
1091         
1092         return false;
1093 }
1094
1095
1096 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1097                 FuncStatus & flag) const
1098 {
1099         // the font related toggles
1100         //string tc = "mathnormal";
1101         bool ret = true;
1102         string const arg = to_utf8(cmd.argument());
1103         switch (cmd.action) {
1104         case LFUN_TABULAR_FEATURE:
1105                 flag.enabled(false);
1106                 break;
1107 #if 0
1108         case LFUN_TABULAR_FEATURE:
1109                 // FIXME: check temporarily disabled
1110                 // valign code
1111                 char align = mathcursor::valign();
1112                 if (align == '\0') {
1113                         enable = false;
1114                         break;
1115                 }
1116                 if (cmd.argument().empty()) {
1117                         flag.clear();
1118                         break;
1119                 }
1120                 if (!contains("tcb", cmd.argument()[0])) {
1121                         enable = false;
1122                         break;
1123                 }
1124                 flag.setOnOff(cmd.argument()[0] == align);
1125                 break;
1126 #endif
1127         /// We have to handle them since 1.4 blocks all unhandled actions
1128         case LFUN_FONT_ITAL:
1129         case LFUN_FONT_BOLD:
1130         case LFUN_FONT_SANS:
1131         case LFUN_FONT_EMPH:
1132         case LFUN_FONT_TYPEWRITER:
1133         case LFUN_FONT_NOUN:
1134         case LFUN_FONT_ROMAN:
1135         case LFUN_FONT_DEFAULT:
1136                 flag.enabled(true);
1137                 break;
1138         case LFUN_MATH_MUTATE:
1139                 //flag.setOnOff(mathcursor::formula()->hullType() == to_utf8(cmd.argument()));
1140                 flag.setOnOff(false);
1141                 break;
1142
1143         // we just need to be in math mode to enable that
1144         case LFUN_MATH_SIZE:
1145         case LFUN_MATH_SPACE:
1146         case LFUN_MATH_LIMITS:
1147         case LFUN_MATH_EXTERN:
1148                 flag.enabled(true);
1149                 break;
1150
1151         case LFUN_FONT_FRAK:
1152                 flag.enabled(currentMode() != TEXT_MODE);
1153                 break;
1154
1155         case LFUN_MATH_INSERT: {
1156                 bool const textarg =
1157                         arg == "\\textbf"   || arg == "\\textsf" ||
1158                         arg == "\\textrm"   || arg == "\\textmd" ||
1159                         arg == "\\textit"   || arg == "\\textsc" ||
1160                         arg == "\\textsl"   || arg == "\\textup" ||
1161                         arg == "\\texttt"   || arg == "\\textbb" ||
1162                         arg == "\\textnormal";
1163                 flag.enabled(currentMode() != TEXT_MODE || textarg);
1164                 break;
1165         }
1166
1167         case LFUN_MATH_MATRIX:
1168                 flag.enabled(currentMode() == MATH_MODE);
1169                 break;
1170
1171         case LFUN_INSET_INSERT: {
1172                 // Don't test createMathInset_fromDialogStr(), since
1173                 // getStatus is not called with a valid reference and the
1174                 // dialog would not be applyable.
1175                 string const name = cmd.getArg(0);
1176                 flag.enabled(name == "ref");
1177                 break;
1178         }
1179
1180         case LFUN_MATH_DELIM:
1181         case LFUN_MATH_BIGDELIM:
1182                 // Don't do this with multi-cell selections
1183                 flag.enabled(cur.selBegin().idx() == cur.selEnd().idx());
1184                 break;
1185                 
1186         case LFUN_MATH_MACRO_FOLD:
1187         case LFUN_MATH_MACRO_UNFOLD: {
1188                 Cursor it = cur;
1189                 bool found = findMacroToFoldUnfold(it, cmd.action == LFUN_MATH_MACRO_FOLD);
1190                 flag.enabled(found);
1191                 break;
1192         }
1193                 
1194         case LFUN_SPECIALCHAR_INSERT:
1195                 // FIXME: These would probably make sense in math-text mode
1196                 flag.enabled(false);
1197                 break;
1198
1199         case LFUN_INSET_DISSOLVE:
1200                 flag.enabled(!asHullInset());
1201                 break;
1202
1203         default:
1204                 ret = false;
1205                 break;
1206         }
1207         return ret;
1208 }
1209
1210
1211 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1212 {
1213         cur.push(*this);
1214         bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_RIGHT || 
1215                 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1216         cur.idx() = enter_front ? 0 : cur.lastidx();
1217         cur.pos() = enter_front ? 0 : cur.lastpos();
1218         cur.resetAnchor();
1219         //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1220 }
1221
1222
1223 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1224 {
1225         int idx_min = 0;
1226         int dist_min = 1000000;
1227         for (idx_type i = 0, n = nargs(); i != n; ++i) {
1228                 int const d = cell(i).dist(cur.bv(), x, y);
1229                 if (d < dist_min) {
1230                         dist_min = d;
1231                         idx_min = i;
1232                 }
1233         }
1234         MathData & ar = cell(idx_min);
1235         cur.push(*this);
1236         cur.idx() = idx_min;
1237         cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1238
1239         //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1240         if (dist_min == 0) {
1241                 // hit inside cell
1242                 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1243                         if (ar[i]->covers(cur.bv(), x, y))
1244                                 return ar[i].nucleus()->editXY(cur, x, y);
1245         }
1246         return this;
1247 }
1248
1249
1250 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1251 {
1252         //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1253         BufferView & bv = cur.bv();
1254         bool do_selection = cmd.button() == mouse_button::button1
1255                 && cmd.argument() == "region-select";
1256         bv.mouseSetCursor(cur, do_selection);
1257         if (cmd.button() == mouse_button::button1) {
1258                 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1259                 // Update the cursor update flags as needed:
1260                 //
1261                 // Update::Decoration: tells to update the decoration
1262                 //                     (visual box corners that define
1263                 //                     the inset)/
1264                 // Update::FitCursor: adjust the screen to the cursor
1265                 //                    position if needed
1266                 // cur.result().update(): don't overwrite previously set flags.
1267                 cur.updateFlags(Update::Decoration | Update::FitCursor 
1268                                 | cur.result().update());
1269         } else if (cmd.button() == mouse_button::button2) {
1270                 if (cap::selection()) {
1271                         // See comment in Text::dispatch why we do this
1272                         cap::copySelectionToStack();
1273                         cmd = FuncRequest(LFUN_PASTE, "0");
1274                         doDispatch(bv.cursor(), cmd);
1275                 } else {
1276                         MathData ar;
1277                         asArray(theSelection().get(), ar);
1278                         bv.cursor().insert(ar);
1279                 }
1280         }
1281 }
1282
1283
1284 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1285 {
1286         // only select with button 1
1287         if (cmd.button() == mouse_button::button1) {
1288                 Cursor & bvcur = cur.bv().cursor();
1289                 if (bvcur.anchor_.hasPart(cur)) {
1290                         //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
1291                         bvcur.setCursor(cur);
1292                         bvcur.selection() = true;
1293                         //lyxerr << "MOTION " << bvcur << endl;
1294                 } else
1295                         cur.undispatched();
1296         }
1297 }
1298
1299
1300 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1301 {
1302         //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1303
1304         if (cmd.button() == mouse_button::button1) {
1305                 if (!cur.selection())
1306                         cur.noUpdate();
1307                 else {
1308                         Cursor & bvcur = cur.bv().cursor();
1309                         bvcur.selection() = true;
1310                 }
1311                 return;
1312         }
1313
1314         cur.undispatched();
1315 }
1316
1317
1318 bool InsetMathNest::interpretChar(Cursor & cur, char_type c)
1319 {
1320         //lyxerr << "interpret 2: '" << c << "'" << endl;
1321         docstring save_selection;
1322         if (c == '^' || c == '_')
1323                 save_selection = grabAndEraseSelection(cur);
1324
1325         cur.clearTargetX();
1326
1327         // handle macroMode
1328         if (cur.inMacroMode()) {
1329                 docstring name = cur.macroName();
1330
1331                 /// are we currently typing '#1' or '#2' or...?
1332                 if (name == "\\#") {
1333                         cur.backspace();
1334                         int n = c - '0';
1335                         if (n >= 1 && n <= 9)
1336                                 cur.insert(new MathMacroArgument(n));
1337                         return true;
1338                 }
1339
1340                 if (isAlphaASCII(c)) {
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         selClearOrDel(cur);
1427
1428         if (c == '\\') {
1429                 //lyxerr << "starting with macro" << endl;
1430                 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), false)));
1431                 return true;
1432         }
1433
1434         if (c == '\n') {
1435                 if (currentMode() == InsetMath::TEXT_MODE)
1436                         cur.insert(c);
1437                 return true;
1438         }
1439
1440         if (c == ' ') {
1441                 if (currentMode() == InsetMath::TEXT_MODE) {
1442                         // insert spaces in text mode,
1443                         // but suppress direct insertion of two spaces in a row
1444                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1445                         // it is better than nothing...
1446                         if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ') {
1447                                 cur.insert(c);
1448                                 // FIXME: we have to enable full redraw here because of the
1449                                 // visual box corners that define the inset. If we know for
1450                                 // sure that we stay within the same cell we can optimize for
1451                                 // that using:
1452                                 //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1453                         }
1454                         return true;
1455                 }
1456                 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1457                         cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
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::SinglePar | Update::FitCursor);
1463                         return true;
1464                 }
1465
1466                 if (cur.popForward()) {
1467                         // FIXME: we have to enable full redraw here because of the
1468                         // visual box corners that define the inset. If we know for
1469                         // sure that we stay within the same cell we can optimize for
1470                         // that using:
1471                         //cur.updateFlags(Update::FitCursor);
1472                         return true;
1473                 }
1474
1475                 // if we are at the very end, leave the formula
1476                 return cur.pos() != cur.lastpos();
1477         }
1478
1479         // These shouldn't work in text mode:
1480         if (currentMode() != InsetMath::TEXT_MODE) {
1481                 if (c == '_') {
1482                         script(cur, false, save_selection);
1483                         return true;
1484                 }
1485                 if (c == '^') {
1486                         script(cur, true, save_selection);
1487                         return true;
1488                 }
1489                 if (c == '~') {
1490                         cur.niceInsert(createInsetMath("sim"));
1491                         return true;
1492                 }
1493         }
1494
1495         if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1496             c == '%' || c == '_' || c == '^') {
1497                 cur.niceInsert(createInsetMath(docstring(1, c)));
1498                 return true;
1499         }
1500
1501
1502         // try auto-correction
1503         //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1504         //      return true;
1505
1506         // no special circumstances, so insert the character without any fuss
1507         cur.insert(c);
1508         cur.autocorrect() = true;
1509         return true;
1510 }
1511
1512
1513 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1514 {
1515         // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1516         // possible
1517         if (!cur.empty() && cur.pos() > 0 &&
1518             cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1519                 if (InsetMathBig::isBigInsetDelim(str)) {
1520                         docstring prev = asString(cur.cell()[cur.pos() - 1]);
1521                         if (prev[0] == '\\') {
1522                                 prev = prev.substr(1);
1523                                 latexkeys const * l = in_word_set(prev);
1524                                 if (l && l->inset == "big") {
1525                                         cur.cell()[cur.pos() - 1] =
1526                                                 MathAtom(new InsetMathBig(prev, str));
1527                                         return true;
1528                                 }
1529                         }
1530                 }
1531         }
1532         return false;
1533 }
1534
1535
1536 bool InsetMathNest::script(Cursor & cur, bool up,
1537                 docstring const & save_selection)
1538 {
1539         // Hack to get \^ and \_ working
1540         //lyxerr << "handling script: up: " << up << endl;
1541         if (cur.inMacroMode() && cur.macroName() == "\\") {
1542                 if (up)
1543                         cur.niceInsert(createInsetMath("mathcircumflex"));
1544                 else
1545                         interpretChar(cur, '_');
1546                 return true;
1547         }
1548
1549         cur.macroModeClose();
1550         if (asScriptInset() && cur.idx() == 0) {
1551                 // we are in a nucleus of a script inset, move to _our_ script
1552                 InsetMathScript * inset = asScriptInset();
1553                 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1554                 inset->ensure(up);
1555                 cur.idx() = inset->idxOfScript(up);
1556                 cur.pos() = 0;
1557         } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1558                 --cur.pos();
1559                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1560                 cur.push(*inset);
1561                 inset->ensure(up);
1562                 cur.idx() = inset->idxOfScript(up);
1563                 cur.pos() = cur.lastpos();
1564         } else {
1565                 // convert the thing to our left to a scriptinset or create a new
1566                 // one if in the very first position of the array
1567                 if (cur.pos() == 0) {
1568                         //lyxerr << "new scriptinset" << endl;
1569                         cur.insert(new InsetMathScript(up));
1570                 } else {
1571                         //lyxerr << "converting prev atom " << endl;
1572                         cur.prevAtom() = MathAtom(new InsetMathScript(cur.prevAtom(), up));
1573                 }
1574                 --cur.pos();
1575                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1576                 // See comment in MathParser.cpp for special handling of {}-bases
1577
1578                 cur.push(*inset);
1579                 cur.idx() = 1;
1580                 cur.pos() = 0;
1581         }
1582         //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1583         cur.niceInsert(save_selection);
1584         cur.resetAnchor();
1585         //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1586         return true;
1587 }
1588
1589
1590 bool InsetMathNest::completionSupported(Cursor const & cur) const
1591 {
1592         return cur.inMacroMode();
1593 }
1594
1595
1596 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
1597 {
1598         return cur.inMacroMode();
1599 }
1600
1601
1602 bool InsetMathNest::automaticInlineCompletion() const
1603 {
1604         return lyxrc.completion_inline_math;
1605 }
1606
1607
1608 bool InsetMathNest::automaticPopupCompletion() const
1609 {
1610         return lyxrc.completion_popup_math;
1611 }
1612
1613
1614 Inset::CompletionList const * InsetMathNest::completionList(Cursor const & cur) const
1615 {
1616         if (!cur.inMacroMode())
1617                 return 0;
1618         
1619         return new MathCompletionList(cur);
1620 }
1621
1622
1623 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
1624 {
1625         if (!cur.inMacroMode())
1626                 return docstring();
1627         
1628         return cur.activeMacro()->name();
1629 }
1630
1631
1632 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
1633                                      bool finished)
1634 {
1635         if (!cur.inMacroMode())
1636                 return false;
1637
1638         // append completion to active macro
1639         InsetMathUnknown * inset = cur.activeMacro();
1640         inset->setName(inset->name() + s);
1641
1642         // finish macro
1643         if (finished) {
1644 #if 0
1645                 // FIXME: this creates duplicates in the completion popup
1646                 // which looks ugly. Moreover the changes the list lengths
1647                 // which seems to
1648                 confuse the popup as well.
1649                 MathCompletionList::addToFavorites(inset->name());
1650 #endif
1651                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
1652         }
1653
1654         return true;
1655 }
1656
1657
1658 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y, 
1659                                         Dimension & dim) const
1660 {
1661         Inset const * inset = cur.activeMacro();
1662         if (!inset)
1663                 return;
1664
1665         // get inset dimensions
1666         dim = cur.bv().coordCache().insets().dim(inset);
1667         // FIXME: these 3 are no accurate, but should depend on the font.
1668         // Now the popup jumps down if you enter a char with descent > 0.
1669         dim.des += 3;
1670         dim.asc += 3;
1671
1672         // and position
1673         Point xy
1674         = cur.bv().coordCache().insets().xy(inset);
1675         x = xy.x_;
1676         y = xy.y_;
1677 }
1678
1679
1680 bool InsetMathNest::cursorMathForward(Cursor & cur)
1681 {
1682         if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
1683                 cur.pushBackward(*cur.nextAtom().nucleus());
1684                 cur.inset().idxFirst(cur);
1685                 return true;
1686         } 
1687         if (cur.posForward() || idxForward(cur) || cur.selection())
1688                 return true;
1689         // try to pop forwards --- but don't pop out of math! leave that to
1690         // the FINISH lfuns
1691         int s = cur.depth() - 2;
1692         if (s >= 0 && cur[s].inset().asInsetMath())
1693                 return cur.popForward();
1694         return false;
1695 }
1696
1697
1698 bool InsetMathNest::cursorMathBackward(Cursor & cur)
1699 {
1700         if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
1701                 cur.posBackward();
1702                 cur.push(*cur.nextAtom().nucleus());
1703                 cur.inset().idxLast(cur);
1704                 return true;
1705         } 
1706         if (cur.posBackward() || idxBackward(cur) || cur.selection())
1707                 return true;
1708         // try to pop backwards --- but don't pop out of math! leave that to 
1709         // the FINISH lfuns
1710         int s = cur.depth() - 2;
1711         if (s >= 0 && cur[s].inset().asInsetMath())
1712                 return cur.popBackward();
1713         return false;
1714 }
1715
1716
1717 ////////////////////////////////////////////////////////////////////
1718
1719 MathCompletionList::MathCompletionList(Cursor const & cur)
1720 {
1721         // fill it with macros from the buffer
1722         Buffer::MacroNameSet macros;
1723         cur.buffer().listMacroNames(macros);
1724         Buffer::MacroNameSet::const_iterator it;
1725         for (it = macros.begin(); it != macros.end(); ++it) {
1726                 if (cur.buffer().getMacro(*it, cur, false))
1727                         locals.push_back("\\" + *it);
1728         }
1729         sort(locals.begin(), locals.end());
1730
1731         if (globals.size() > 0)
1732                 return;
1733
1734         // fill in global macros
1735         macros.clear();
1736         MacroTable::globalMacros().getMacroNames(macros);
1737         lyxerr << "Globals completion macros: ";
1738         for (it = macros.begin(); it != macros.end(); ++it) {
1739                 lyxerr << "\\" + *it << " ";
1740                 globals.push_back("\\" + *it);
1741         }
1742         lyxerr << std::endl;
1743
1744         // fill in global commands
1745         globals.push_back(from_ascii("\\boxed"));
1746         globals.push_back(from_ascii("\\fbox"));
1747         globals.push_back(from_ascii("\\framebox"));
1748         globals.push_back(from_ascii("\\makebox"));
1749         globals.push_back(from_ascii("\\kern"));
1750         globals.push_back(from_ascii("\\xrightarrow"));
1751         globals.push_back(from_ascii("\\xleftarrow"));
1752         globals.push_back(from_ascii("\\split"));
1753         globals.push_back(from_ascii("\\gathered"));
1754         globals.push_back(from_ascii("\\aligned"));
1755         globals.push_back(from_ascii("\\alignedat"));
1756         globals.push_back(from_ascii("\\cases"));
1757         globals.push_back(from_ascii("\\substack"));
1758         globals.push_back(from_ascii("\\subarray"));
1759         globals.push_back(from_ascii("\\array"));
1760         globals.push_back(from_ascii("\\sqrt"));
1761         globals.push_back(from_ascii("\\root"));
1762         globals.push_back(from_ascii("\\tabular"));
1763         globals.push_back(from_ascii("\\stackrel"));
1764         globals.push_back(from_ascii("\\binom"));
1765         globals.push_back(from_ascii("\\choose"));
1766         globals.push_back(from_ascii("\\choose"));
1767         globals.push_back(from_ascii("\\frac"));
1768         globals.push_back(from_ascii("\\over"));
1769         globals.push_back(from_ascii("\\nicefrac"));
1770         globals.push_back(from_ascii("\\unitfrac"));
1771         globals.push_back(from_ascii("\\unitfracthree"));
1772         globals.push_back(from_ascii("\\unitone"));
1773         globals.push_back(from_ascii("\\unittwo"));
1774         globals.push_back(from_ascii("\\infer"));
1775         globals.push_back(from_ascii("\\atop"));
1776         globals.push_back(from_ascii("\\lefteqn"));
1777         globals.push_back(from_ascii("\\boldsymbol"));
1778         globals.push_back(from_ascii("\\color"));
1779         globals.push_back(from_ascii("\\normalcolor"));
1780         globals.push_back(from_ascii("\\textcolor"));
1781         globals.push_back(from_ascii("\\dfrac"));
1782         globals.push_back(from_ascii("\\tfrac"));
1783         globals.push_back(from_ascii("\\dbinom"));
1784         globals.push_back(from_ascii("\\tbinom"));
1785         globals.push_back(from_ascii("\\hphantom"));
1786         globals.push_back(from_ascii("\\phantom"));
1787         globals.push_back(from_ascii("\\vphantom"));
1788         WordList const & words = mathedWordList();
1789         WordList::const_iterator it2;
1790         lyxerr << "Globals completion commands: ";
1791         for (it2 = words.begin(); it2 != words.end(); ++it2) {
1792                 globals.push_back("\\" + (*it2).first);
1793                 lyxerr << "\\" + (*it2).first << " ";
1794         }
1795         lyxerr << std::endl;
1796         sort(globals.begin(), globals.end());
1797 }
1798
1799
1800 MathCompletionList::~MathCompletionList()
1801 {
1802 }
1803
1804
1805 size_type MathCompletionList::size() const
1806 {
1807         return locals.size() + globals.size();
1808 }
1809
1810
1811 docstring MathCompletionList::data(size_t idx) const
1812 {
1813         size_t lsize = locals.size();
1814         if (idx >= lsize)
1815                 return globals[idx - lsize];
1816         else
1817                 return locals[idx];
1818 }
1819
1820
1821 std::string MathCompletionList::icon(size_t idx) const 
1822 {
1823         // get the latex command
1824         docstring cmd;
1825         size_t lsize = locals.size();
1826         if (idx >= lsize)
1827                 cmd = globals[idx - lsize];
1828         else
1829                 cmd = locals[idx];
1830         
1831         // get the icon resource name by stripping the backslash
1832         return "images/math/" + to_utf8(cmd.substr(1)) + ".png";
1833 }
1834
1835 std::vector<docstring> MathCompletionList::globals;
1836
1837 } // namespace lyx