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