]> git.lyx.org Git - lyx.git/blob - src/Text3.cpp
Remove references to Counter LabelType from source code. The
[lyx.git] / src / Text3.cpp
1 /**
2  * \file Text3.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Alfredo Braunstein
9  * \author Angus Leeming
10  * \author John Levon
11  * \author André Pönitz
12  *
13  * Full author contact details are available in file CREDITS.
14  */
15
16 #include <config.h>
17
18 #include "Text.h"
19
20 #include "Bidi.h"
21 #include "BranchList.h"
22 #include "FloatList.h"
23 #include "FuncStatus.h"
24 #include "Buffer.h"
25 #include "buffer_funcs.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
28 #include "Changes.h"
29 #include "Cursor.h"
30 #include "CutAndPaste.h"
31 #include "DispatchResult.h"
32 #include "ErrorList.h"
33 #include "factory.h"
34 #include "FuncRequest.h"
35 #include "InsetList.h"
36 #include "Intl.h"
37 #include "Language.h"
38 #include "Layout.h"
39 #include "LyXAction.h"
40 #include "LyX.h"
41 #include "Lexer.h"
42 #include "LyXRC.h"
43 #include "Paragraph.h"
44 #include "ParagraphParameters.h"
45 #include "SpellChecker.h"
46 #include "TextClass.h"
47 #include "TextMetrics.h"
48 #include "WordLangTuple.h"
49
50 #include "frontends/Application.h"
51 #include "frontends/Clipboard.h"
52 #include "frontends/Selection.h"
53
54 #include "insets/InsetArgument.h"
55 #include "insets/InsetCollapsable.h"
56 #include "insets/InsetCommand.h"
57 #include "insets/InsetExternal.h"
58 #include "insets/InsetFloat.h"
59 #include "insets/InsetFloatList.h"
60 #include "insets/InsetGraphics.h"
61 #include "insets/InsetGraphicsParams.h"
62 #include "insets/InsetIPAMacro.h"
63 #include "insets/InsetNewline.h"
64 #include "insets/InsetQuotes.h"
65 #include "insets/InsetSpecialChar.h"
66 #include "insets/InsetText.h"
67 #include "insets/InsetWrap.h"
68
69 #include "support/convert.h"
70 #include "support/debug.h"
71 #include "support/gettext.h"
72 #include "support/lassert.h"
73 #include "support/lstrings.h"
74 #include "support/lyxtime.h"
75 #include "support/os.h"
76
77 #include "mathed/InsetMathHull.h"
78 #include "mathed/MathMacroTemplate.h"
79
80 #include <boost/next_prior.hpp>
81
82 #include <clocale>
83 #include <sstream>
84
85 using namespace std;
86 using namespace lyx::support;
87
88 namespace lyx {
89
90 using cap::copySelection;
91 using cap::cutSelection;
92 using cap::pasteFromStack;
93 using cap::pasteClipboardText;
94 using cap::pasteClipboardGraphics;
95 using cap::replaceSelection;
96 using cap::grabAndEraseSelection;
97 using cap::selClearOrDel;
98 using cap::pasteSimpleText;
99
100 // globals...
101 static Font freefont(ignore_font, ignore_language);
102 static bool toggleall = false;
103
104 static void toggleAndShow(Cursor & cur, Text * text,
105         Font const & font, bool toggleall = true)
106 {
107         text->toggleFree(cur, font, toggleall);
108
109         if (font.language() != ignore_language ||
110             font.fontInfo().number() != FONT_IGNORE) {
111                 TextMetrics const & tm = cur.bv().textMetrics(text);
112                 if (cur.boundary() != tm.isRTLBoundary(cur.pit(), cur.pos(),
113                                                        cur.real_current_font))
114                         text->setCursor(cur, cur.pit(), cur.pos(),
115                                         false, !cur.boundary());
116         }
117 }
118
119
120 static void moveCursor(Cursor & cur, bool selecting)
121 {
122         if (selecting || cur.mark())
123                 cur.setSelection();
124 }
125
126
127 static void finishChange(Cursor & cur, bool selecting)
128 {
129         cur.finishUndo();
130         moveCursor(cur, selecting);
131 }
132
133
134 static void mathDispatch(Cursor & cur, FuncRequest const & cmd, bool display)
135 {
136         cur.recordUndo();
137         docstring sel = cur.selectionAsString(false);
138
139         // It may happen that sel is empty but there is a selection
140         replaceSelection(cur);
141
142         // Is this a valid formula?
143         bool valid = true;
144
145         if (sel.empty()) {
146 #ifdef ENABLE_ASSERTIONS
147                 const int old_pos = cur.pos();
148 #endif
149                 cur.insert(new InsetMathHull(cur.buffer(), hullSimple));
150 #ifdef ENABLE_ASSERTIONS
151                 LASSERT(old_pos == cur.pos(), /**/);
152 #endif
153                 cur.nextInset()->edit(cur, true);
154                 // don't do that also for LFUN_MATH_MODE
155                 // unless you want end up with always changing
156                 // to mathrm when opening an inlined inset --
157                 // I really hate "LyXfunc overloading"...
158                 if (display)
159                         cur.dispatch(FuncRequest(LFUN_MATH_DISPLAY));
160                 // Avoid an unnecessary undo step if cmd.argument
161                 // is empty
162                 if (!cmd.argument().empty())
163                         cur.dispatch(FuncRequest(LFUN_MATH_INSERT,
164                                                  cmd.argument()));
165         } else {
166                 // create a macro if we see "\\newcommand"
167                 // somewhere, and an ordinary formula
168                 // otherwise
169                 if (sel.find(from_ascii("\\newcommand")) == string::npos
170                                 && sel.find(from_ascii("\\newlyxcommand")) == string::npos
171                                 && sel.find(from_ascii("\\def")) == string::npos)
172                 {
173                         InsetMathHull * formula = new InsetMathHull(cur.buffer());
174                         string const selstr = to_utf8(sel);
175                         istringstream is(selstr);
176                         Lexer lex;
177                         lex.setStream(is);
178                         if (!formula->readQuiet(lex)) {
179                                 // No valid formula, let's try with delims
180                                 is.str("$" + selstr + "$");
181                                 lex.setStream(is);
182                                 if (!formula->readQuiet(lex)) {
183                                         // Still not valid, leave it as is
184                                         valid = false;
185                                         delete formula;
186                                         cur.insert(sel);
187                                 } else
188                                         cur.insert(formula);
189                         } else
190                                 cur.insert(formula);
191                 } else {
192                         cur.insert(new MathMacroTemplate(cur.buffer(), sel));
193                 }
194         }
195         if (valid)
196                 cur.message(from_utf8(N_("Math editor mode")));
197         else
198                 cur.message(from_utf8(N_("No valid math formula")));
199 }
200
201
202 void regexpDispatch(Cursor & cur, FuncRequest const & cmd)
203 {
204         LASSERT(cmd.action() == LFUN_REGEXP_MODE, return);
205         if (cur.inRegexped()) {
206                 cur.message(_("Already in regular expression mode"));
207                 return;
208         }
209         cur.recordUndo();
210         docstring sel = cur.selectionAsString(false);
211
212         // It may happen that sel is empty but there is a selection
213         replaceSelection(cur);
214
215         cur.insert(new InsetMathHull(cur.buffer(), hullRegexp));
216         cur.nextInset()->edit(cur, true);
217         cur.niceInsert(sel);
218
219         cur.message(_("Regexp editor mode"));
220 }
221
222
223 static void specialChar(Cursor & cur, InsetSpecialChar::Kind kind)
224 {
225         cur.recordUndo();
226         cap::replaceSelection(cur);
227         cur.insert(new InsetSpecialChar(kind));
228         cur.posForward();
229 }
230
231
232 static void ipaChar(Cursor & cur, InsetIPAChar::Kind kind)
233 {
234         cur.recordUndo();
235         cap::replaceSelection(cur);
236         cur.insert(new InsetIPAChar(kind));
237         cur.posForward();
238 }
239
240
241 static bool doInsertInset(Cursor & cur, Text * text,
242         FuncRequest const & cmd, bool edit, bool pastesel)
243 {
244         Buffer & buffer = cur.bv().buffer();
245         BufferParams const & bparams = buffer.params();
246         Inset * inset = createInset(&buffer, cmd);
247         if (!inset)
248                 return false;
249
250         if (InsetCollapsable * ci = inset->asInsetCollapsable())
251                 ci->setButtonLabel();
252
253         cur.recordUndo();
254         if (cmd.action() == LFUN_INDEX_INSERT) {
255                 docstring ds = subst(text->getStringToIndex(cur), '\n', ' ');
256                 text->insertInset(cur, inset);
257                 if (edit)
258                         inset->edit(cur, true);
259                 // Now put this into inset
260                 Font const f(inherit_font, cur.current_font.language());
261                 if (!ds.empty()) {
262                         cur.text()->insertStringAsLines(cur, ds, f);
263                         cur.leaveInset(*inset);
264                 }
265                 return true;
266         }
267
268         bool gotsel = false;
269         if (cur.selection()) {
270                 cutSelection(cur, false, pastesel);
271                 cur.clearSelection();
272                 gotsel = true;
273         }
274         text->insertInset(cur, inset);
275
276         if (edit)
277                 inset->edit(cur, true);
278
279         if (!gotsel || !pastesel)
280                 return true;
281
282         pasteFromStack(cur, cur.buffer()->errorList("Paste"), 0);
283         cur.buffer()->errors("Paste");
284         cur.clearSelection(); // bug 393
285         cur.finishUndo();
286         InsetText * inset_text = inset->asInsetText();
287         if (inset_text) {
288                 inset_text->fixParagraphsFont();
289                 if (!inset_text->allowMultiPar() || cur.lastpit() == 0) {
290                         // reset first par to default
291                         cur.text()->paragraphs().begin()
292                                 ->setPlainOrDefaultLayout(bparams.documentClass());
293                         cur.pos() = 0;
294                         cur.pit() = 0;
295                         // Merge multiple paragraphs -- hack
296                         while (cur.lastpit() > 0)
297                                 mergeParagraph(bparams, cur.text()->paragraphs(), 0);
298                         if (cmd.action() == LFUN_FLEX_INSERT)
299                                 return true;
300                         Cursor old = cur;
301                         cur.leaveInset(*inset);
302                         if (cmd.action() == LFUN_PREVIEW_INSERT
303                             || cmd.action() == LFUN_IPA_INSERT)
304                                 // trigger preview
305                                 notifyCursorLeavesOrEnters(old, cur);
306                 }
307         } else {
308                 cur.leaveInset(*inset);
309                 // reset surrounding par to default
310                 DocumentClass const & dc = bparams.documentClass();
311                 docstring const layoutname = inset->usePlainLayout()
312                         ? dc.plainLayoutName()
313                         : dc.defaultLayoutName();
314                 text->setLayout(cur, layoutname);
315         }
316         return true;
317 }
318
319
320 string const freefont2string()
321 {
322         return freefont.toString(toggleall);
323 }
324
325
326 /// the type of outline operation
327 enum OutlineOp {
328         OutlineUp, // Move this header with text down
329         OutlineDown,   // Move this header with text up
330         OutlineIn, // Make this header deeper
331         OutlineOut // Make this header shallower
332 };
333
334
335 static void outline(OutlineOp mode, Cursor & cur)
336 {
337         Buffer & buf = *cur.buffer();
338         pit_type & pit = cur.pit();
339         ParagraphList & pars = buf.text().paragraphs();
340         ParagraphList::iterator const bgn = pars.begin();
341         // The first paragraph of the area to be copied:
342         ParagraphList::iterator start = boost::next(bgn, pit);
343         // The final paragraph of area to be copied:
344         ParagraphList::iterator finish = start;
345         ParagraphList::iterator const end = pars.end();
346
347         DocumentClass const & tc = buf.params().documentClass();
348
349         int const thistoclevel = buf.text().getTocLevel(distance(bgn, start));
350         int toclevel;
351
352         // Move out (down) from this section header
353         if (finish != end)
354                 ++finish;
355
356         // Seek the one (on same level) below
357         for (; finish != end; ++finish) {
358                 toclevel = buf.text().getTocLevel(distance(bgn, finish));
359                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
360                         break;
361         }
362
363         switch (mode) {
364                 case OutlineUp: {
365                         if (start == pars.begin())
366                                 // Nothing to move.
367                                 return;
368                         ParagraphList::iterator dest = start;
369                         // Move out (up) from this header
370                         if (dest == bgn)
371                                 return;
372                         // Search previous same-level header above
373                         do {
374                                 --dest;
375                                 toclevel = buf.text().getTocLevel(distance(bgn, dest));
376                         } while(dest != bgn
377                                 && (toclevel == Layout::NOT_IN_TOC
378                                     || toclevel > thistoclevel));
379                         // Not found; do nothing
380                         if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
381                                 return;
382                         pit_type const newpit = distance(bgn, dest);
383                         pit_type const len = distance(start, finish);
384                         pit_type const deletepit = pit + len;
385                         buf.undo().recordUndo(cur, ATOMIC_UNDO, newpit, deletepit - 1);
386                         pars.splice(dest, start, finish);
387                         cur.pit() = newpit;
388                         break;
389                 }
390                 case OutlineDown: {
391                         if (finish == end)
392                                 // Nothing to move.
393                                 return;
394                         // Go one down from *this* header:
395                         ParagraphList::iterator dest = boost::next(finish, 1);
396                         // Go further down to find header to insert in front of:
397                         for (; dest != end; ++dest) {
398                                 toclevel = buf.text().getTocLevel(distance(bgn, dest));
399                                 if (toclevel != Layout::NOT_IN_TOC
400                                       && toclevel <= thistoclevel)
401                                         break;
402                         }
403                         // One such was found:
404                         pit_type newpit = distance(bgn, dest);
405                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, newpit - 1);
406                         pit_type const len = distance(start, finish);
407                         pars.splice(dest, start, finish);
408                         cur.pit() = newpit - len;
409                         break;
410                 }
411                 case OutlineIn: {
412                         pit_type const len = distance(start, finish);
413                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, pit + len - 1);
414                         for (; start != finish; ++start) {
415                                 toclevel = buf.text().getTocLevel(distance(bgn, start));
416                                 if (toclevel == Layout::NOT_IN_TOC)
417                                         continue;
418                                 DocumentClass::const_iterator lit = tc.begin();
419                                 DocumentClass::const_iterator len = tc.end();
420                                 for (; lit != len; ++lit) {
421                                         if (lit->toclevel == toclevel + 1 &&
422                                             start->layout().labeltype == lit->labeltype) {
423                                                 start->setLayout(*lit);
424                                                 break;
425                                         }
426                                 }
427                         }
428                         break;
429                 }
430                 case OutlineOut: {
431                         pit_type const len = distance(start, finish);
432                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, pit + len - 1);
433                         for (; start != finish; ++start) {
434                                 toclevel = buf.text().getTocLevel(distance(bgn, start));
435                                 if (toclevel == Layout::NOT_IN_TOC)
436                                         continue;
437                                 DocumentClass::const_iterator lit = tc.begin();
438                                 DocumentClass::const_iterator len = tc.end();
439                                 for (; lit != len; ++lit) {
440                                         if (lit->toclevel == toclevel - 1 &&
441                                                 start->layout().labeltype == lit->labeltype) {
442                                                         start->setLayout(*lit);
443                                                         break;
444                                         }
445                                 }
446                         }
447                         break;
448                 }
449         }
450 }
451
452
453 void Text::number(Cursor & cur)
454 {
455         FontInfo font = ignore_font;
456         font.setNumber(FONT_TOGGLE);
457         toggleAndShow(cur, this, Font(font, ignore_language));
458 }
459
460
461 bool Text::isRTL(Paragraph const & par) const
462 {
463         Buffer const & buffer = owner_->buffer();
464         return par.isRTL(buffer.params());
465 }
466
467
468 void Text::dispatch(Cursor & cur, FuncRequest & cmd)
469 {
470         LYXERR(Debug::ACTION, "Text::dispatch: cmd: " << cmd);
471
472         // Dispatch if the cursor is inside the text. It is not the
473         // case for context menus (bug 5797).
474         if (cur.text() != this) {
475                 cur.undispatched();
476                 return;
477         }
478
479         BufferView * bv = &cur.bv();
480         TextMetrics * tm = &bv->textMetrics(this);
481         if (!tm->contains(cur.pit())) {
482                 lyx::dispatch(FuncRequest(LFUN_SCREEN_SHOW_CURSOR));
483                 tm = &bv->textMetrics(this);
484         }
485
486         // FIXME: We use the update flag to indicates wether a singlePar or a
487         // full screen update is needed. We reset it here but shall we restore it
488         // at the end?
489         cur.noScreenUpdate();
490
491         LASSERT(cur.text() == this, /**/);
492         CursorSlice const oldTopSlice = cur.top();
493         bool const oldBoundary = cur.boundary();
494         bool const oldSelection = cur.selection();
495         // Signals that, even if needsUpdate == false, an update of the
496         // cursor paragraph is required
497         bool singleParUpdate = lyxaction.funcHasFlag(cmd.action(),
498                 LyXAction::SingleParUpdate);
499         // Signals that a full-screen update is required
500         bool needsUpdate = !(lyxaction.funcHasFlag(cmd.action(),
501                 LyXAction::NoUpdate) || singleParUpdate);
502         bool const last_misspelled = lyxrc.spellcheck_continuously
503                 && cur.paragraph().isMisspelled(cur.pos(), true);
504         
505         FuncCode const act = cmd.action();
506         switch (act) {
507
508         case LFUN_PARAGRAPH_MOVE_DOWN: {
509                 pit_type const pit = cur.pit();
510                 recUndo(cur, pit, pit + 1);
511                 cur.finishUndo();
512                 pars_.swap(pit, pit + 1);
513                 needsUpdate = true;
514                 cur.forceBufferUpdate();
515                 ++cur.pit();
516                 break;
517         }
518
519         case LFUN_PARAGRAPH_MOVE_UP: {
520                 pit_type const pit = cur.pit();
521                 recUndo(cur, pit - 1, pit);
522                 cur.finishUndo();
523                 pars_.swap(pit, pit - 1);
524                 --cur.pit();
525                 needsUpdate = true;
526                 cur.forceBufferUpdate();
527                 break;
528         }
529
530         case LFUN_APPENDIX: {
531                 Paragraph & par = cur.paragraph();
532                 bool start = !par.params().startOfAppendix();
533
534 // FIXME: The code below only makes sense at top level.
535 // Should LFUN_APPENDIX be restricted to top-level paragraphs?
536                 // ensure that we have only one start_of_appendix in this document
537                 // FIXME: this don't work for multipart document!
538                 for (pit_type tmp = 0, end = pars_.size(); tmp != end; ++tmp) {
539                         if (pars_[tmp].params().startOfAppendix()) {
540                                 recUndo(cur, tmp);
541                                 pars_[tmp].params().startOfAppendix(false);
542                                 break;
543                         }
544                 }
545
546                 cur.recordUndo();
547                 par.params().startOfAppendix(start);
548
549                 // we can set the refreshing parameters now
550                 cur.forceBufferUpdate();
551                 break;
552         }
553
554         case LFUN_WORD_DELETE_FORWARD:
555                 if (cur.selection())
556                         cutSelection(cur, true, false);
557                 else
558                         deleteWordForward(cur);
559                 finishChange(cur, false);
560                 break;
561
562         case LFUN_WORD_DELETE_BACKWARD:
563                 if (cur.selection())
564                         cutSelection(cur, true, false);
565                 else
566                         deleteWordBackward(cur);
567                 finishChange(cur, false);
568                 break;
569
570         case LFUN_LINE_DELETE:
571                 if (cur.selection())
572                         cutSelection(cur, true, false);
573                 else
574                         tm->deleteLineForward(cur);
575                 finishChange(cur, false);
576                 break;
577
578         case LFUN_BUFFER_BEGIN:
579         case LFUN_BUFFER_BEGIN_SELECT:
580                 needsUpdate |= cur.selHandle(act == LFUN_BUFFER_BEGIN_SELECT);
581                 if (cur.depth() == 1)
582                         needsUpdate |= cursorTop(cur);
583                 else
584                         cur.undispatched();
585                 cur.screenUpdateFlags(Update::FitCursor);
586                 break;
587
588         case LFUN_BUFFER_END:
589         case LFUN_BUFFER_END_SELECT:
590                 needsUpdate |= cur.selHandle(act == LFUN_BUFFER_END_SELECT);
591                 if (cur.depth() == 1)
592                         needsUpdate |= cursorBottom(cur);
593                 else
594                         cur.undispatched();
595                 cur.screenUpdateFlags(Update::FitCursor);
596                 break;
597
598         case LFUN_INSET_BEGIN:
599         case LFUN_INSET_BEGIN_SELECT:
600                 needsUpdate |= cur.selHandle(act == LFUN_INSET_BEGIN_SELECT);
601                 if (cur.depth() == 1 || !cur.top().at_begin())
602                         needsUpdate |= cursorTop(cur);
603                 else
604                         cur.undispatched();
605                 cur.screenUpdateFlags(Update::FitCursor);
606                 break;
607
608         case LFUN_INSET_END:
609         case LFUN_INSET_END_SELECT:
610                 needsUpdate |= cur.selHandle(act == LFUN_INSET_END_SELECT);
611                 if (cur.depth() == 1 || !cur.top().at_end())
612                         needsUpdate |= cursorBottom(cur);
613                 else
614                         cur.undispatched();
615                 cur.screenUpdateFlags(Update::FitCursor);
616                 break;
617
618         case LFUN_INSET_SELECT_ALL:
619                 if (cur.depth() == 1 || !cur.selection() || !cur.selBegin().at_begin()
620                           || !cur.selEnd().at_end()) {
621                         needsUpdate |= cur.selHandle(false);
622                         needsUpdate |= cursorTop(cur);
623                         needsUpdate |= cur.selHandle(true);
624                         needsUpdate |= cursorBottom(cur);
625                 } else 
626                         cur.undispatched();
627                 cur.screenUpdateFlags(Update::FitCursor);
628                 break;
629
630         case LFUN_CHAR_FORWARD:
631         case LFUN_CHAR_FORWARD_SELECT:
632                 //LYXERR0(" LFUN_CHAR_FORWARD[SEL]:\n" << cur);
633                 needsUpdate |= cur.selHandle(act == LFUN_CHAR_FORWARD_SELECT);
634                 needsUpdate |= cursorForward(cur);
635
636                 if (!needsUpdate && oldTopSlice == cur.top()
637                                 && cur.boundary() == oldBoundary) {
638                         cur.undispatched();
639                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
640                 
641                         // we will probably be moving out the inset, so we should execute
642                         // the depm-mechanism, but only when the cursor has a place to 
643                         // go outside this inset, i.e. in a slice above.
644                         if (cur.depth() > 1 && cur.pos() == cur.lastpos() 
645                                   && cur.pit() == cur.lastpit()) {
646                                 // The cursor hasn't changed yet. To give the 
647                                 // DEPM the possibility of doing something we must
648                                 // provide it with two different cursors.
649                                 Cursor dummy = cur;
650                                 dummy.pos() = dummy.pit() = 0;
651                                 if (cur.bv().checkDepm(dummy, cur)) {
652                                         cur.forceBufferUpdate();
653                                         // DEPM may have requested a screen update
654                                         cur.screenUpdateFlags(
655                                                 cur.screenUpdate() | dummy.screenUpdate());
656                                 }
657                         }
658                 }
659                 break;
660
661         case LFUN_CHAR_BACKWARD:
662         case LFUN_CHAR_BACKWARD_SELECT:
663                 //lyxerr << "handle LFUN_CHAR_BACKWARD[_SELECT]:\n" << cur << endl;
664                 needsUpdate |= cur.selHandle(act == LFUN_CHAR_BACKWARD_SELECT);
665                 needsUpdate |= cursorBackward(cur);
666
667                 if (!needsUpdate && oldTopSlice == cur.top()
668                         && cur.boundary() == oldBoundary) {
669                         cur.undispatched();
670                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
671
672                         // we will probably be moving out the inset, so we should execute
673                         // the depm-mechanism, but only when the cursor has a place to 
674                         // go outside this inset, i.e. in a slice above.
675                         if (cur.depth() > 1 && cur.pos() == 0 && cur.pit() == 0) {
676                                 // The cursor hasn't changed yet. To give the 
677                                 // DEPM the possibility of doing something we must
678                                 // provide it with two different cursors.
679                                 Cursor dummy = cur;
680                                 dummy.pos() = cur.lastpos();
681                                 dummy.pit() = cur.lastpit();
682                                 if (cur.bv().checkDepm(dummy, cur)) {
683                                         cur.forceBufferUpdate();
684                                         // DEPM may have requested a screen update
685                                         cur.screenUpdateFlags(
686                                                 cur.screenUpdate() | dummy.screenUpdate());
687                                 }
688                         }
689                 }
690                 break;
691
692         case LFUN_CHAR_LEFT:
693         case LFUN_CHAR_LEFT_SELECT:
694                 if (lyxrc.visual_cursor) {
695                         needsUpdate |= cur.selHandle(act == LFUN_CHAR_LEFT_SELECT);
696                         needsUpdate |= cursorVisLeft(cur);
697                         if (!needsUpdate && oldTopSlice == cur.top()
698                                         && cur.boundary() == oldBoundary) {
699                                 cur.undispatched();
700                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
701                         }
702                 } else {
703                         if (reverseDirectionNeeded(cur)) {
704                                 cmd.setAction(cmd.action() == LFUN_CHAR_LEFT_SELECT ?
705                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD);
706                         } else {
707                                 cmd.setAction(cmd.action() == LFUN_CHAR_LEFT_SELECT ?
708                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD);
709                         }
710                         dispatch(cur, cmd);
711                         return;
712                 }
713                 break;
714
715         case LFUN_CHAR_RIGHT:
716         case LFUN_CHAR_RIGHT_SELECT:
717                 if (lyxrc.visual_cursor) {
718                         needsUpdate |= cur.selHandle(cmd.action() == LFUN_CHAR_RIGHT_SELECT);
719                         needsUpdate |= cursorVisRight(cur);
720                         if (!needsUpdate && oldTopSlice == cur.top()
721                                         && cur.boundary() == oldBoundary) {
722                                 cur.undispatched();
723                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
724                         }
725                 } else {
726                         if (reverseDirectionNeeded(cur)) {
727                                 cmd.setAction(cmd.action() == LFUN_CHAR_RIGHT_SELECT ?
728                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD);
729                         } else {
730                                 cmd.setAction(cmd.action() == LFUN_CHAR_RIGHT_SELECT ?
731                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD);
732                         }
733                         dispatch(cur, cmd);
734                         return;
735                 }
736                 break;
737
738
739         case LFUN_UP_SELECT:
740         case LFUN_DOWN_SELECT:
741         case LFUN_UP:
742         case LFUN_DOWN: {
743                 // stop/start the selection
744                 bool select = cmd.action() == LFUN_DOWN_SELECT ||
745                         cmd.action() == LFUN_UP_SELECT;
746
747                 // move cursor up/down
748                 bool up = cmd.action() == LFUN_UP_SELECT || cmd.action() == LFUN_UP;
749                 bool const atFirstOrLastRow = cur.atFirstOrLastRow(up);
750
751                 if (!atFirstOrLastRow) {
752                         needsUpdate |= cur.selHandle(select);   
753                         cur.selHandle(select);
754                         cur.upDownInText(up, needsUpdate);
755                         needsUpdate |= cur.beforeDispatchCursor().inMathed();
756                 } else {
757                         // if the cursor cannot be moved up or down do not remove
758                         // the selection right now, but wait for the next dispatch.
759                         if (select)
760                                 needsUpdate |= cur.selHandle(select);   
761                         cur.upDownInText(up, needsUpdate);
762                         cur.undispatched();
763                 }
764
765                 break;
766         }
767
768         case LFUN_PARAGRAPH_UP:
769         case LFUN_PARAGRAPH_UP_SELECT:
770                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_PARAGRAPH_UP_SELECT);
771                 needsUpdate |= cursorUpParagraph(cur);
772                 break;
773
774         case LFUN_PARAGRAPH_DOWN:
775         case LFUN_PARAGRAPH_DOWN_SELECT:
776                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_PARAGRAPH_DOWN_SELECT);
777                 needsUpdate |= cursorDownParagraph(cur);
778                 break;
779
780         case LFUN_LINE_BEGIN:
781         case LFUN_LINE_BEGIN_SELECT:
782                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_LINE_BEGIN_SELECT);
783                 needsUpdate |= tm->cursorHome(cur);
784                 break;
785
786         case LFUN_LINE_END:
787         case LFUN_LINE_END_SELECT:
788                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_LINE_END_SELECT);
789                 needsUpdate |= tm->cursorEnd(cur);
790                 break;
791
792         case LFUN_SECTION_SELECT: {
793                 Buffer const & buf = *cur.buffer();
794                 pit_type const pit = cur.pit();
795                 ParagraphList & pars = buf.text().paragraphs();
796                 ParagraphList::iterator bgn = pars.begin();
797                 // The first paragraph of the area to be selected:
798                 ParagraphList::iterator start = boost::next(bgn, pit);
799                 // The final paragraph of area to be selected:
800                 ParagraphList::iterator finish = start;
801                 ParagraphList::iterator end = pars.end();
802
803                 int const thistoclevel = buf.text().getTocLevel(distance(bgn, start));
804                 if (thistoclevel == Layout::NOT_IN_TOC)
805                         break;
806
807                 cur.pos() = 0;
808                 Cursor const old_cur = cur;
809                 needsUpdate |= cur.selHandle(true);
810
811                 // Move out (down) from this section header
812                 if (finish != end)
813                         ++finish;
814
815                 // Seek the one (on same level) below
816                 for (; finish != end; ++finish, ++cur.pit()) {
817                         int const toclevel = buf.text().getTocLevel(distance(bgn, finish));
818                         if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
819                                 break;
820                 }
821                 cur.pos() = cur.lastpos();
822                 
823                 needsUpdate |= cur != old_cur;
824                 break;
825         }
826
827         case LFUN_WORD_RIGHT:
828         case LFUN_WORD_RIGHT_SELECT:
829                 if (lyxrc.visual_cursor) {
830                         needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_RIGHT_SELECT);
831                         needsUpdate |= cursorVisRightOneWord(cur);
832                         if (!needsUpdate && oldTopSlice == cur.top()
833                                         && cur.boundary() == oldBoundary) {
834                                 cur.undispatched();
835                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
836                         }
837                 } else {
838                         if (reverseDirectionNeeded(cur)) {
839                                 cmd.setAction(cmd.action() == LFUN_WORD_RIGHT_SELECT ?
840                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD);
841                         } else {
842                                 cmd.setAction(cmd.action() == LFUN_WORD_RIGHT_SELECT ?
843                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD);
844                         }
845                         dispatch(cur, cmd);
846                         return;
847                 }
848                 break;
849
850         case LFUN_WORD_FORWARD:
851         case LFUN_WORD_FORWARD_SELECT:
852                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_FORWARD_SELECT);
853                 needsUpdate |= cursorForwardOneWord(cur);
854
855                 if (!needsUpdate && oldTopSlice == cur.top()
856                                 && cur.boundary() == oldBoundary) {
857                         cur.undispatched();
858                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
859                 
860                         // we will probably be moving out the inset, so we should execute
861                         // the depm-mechanism, but only when the cursor has a place to 
862                         // go outside this inset, i.e. in a slice above.
863                         if (cur.depth() > 1 && cur.pos() == cur.lastpos() 
864                                   && cur.pit() == cur.lastpit()) {
865                                 // The cursor hasn't changed yet. To give the 
866                                 // DEPM the possibility of doing something we must
867                                 // provide it with two different cursors.
868                                 Cursor dummy = cur;
869                                 dummy.pos() = dummy.pit() = 0;
870                                 if (cur.bv().checkDepm(dummy, cur)) {
871                                         cur.forceBufferUpdate();
872                                         // DEPM may have requested a screen update
873                                         cur.screenUpdateFlags(
874                                                 cur.screenUpdate() | dummy.screenUpdate());
875                                 }
876                         }
877                 }
878                 break;
879
880         case LFUN_WORD_LEFT:
881         case LFUN_WORD_LEFT_SELECT:
882                 if (lyxrc.visual_cursor) {
883                         needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_LEFT_SELECT);
884                         needsUpdate |= cursorVisLeftOneWord(cur);
885                         if (!needsUpdate && oldTopSlice == cur.top()
886                                         && cur.boundary() == oldBoundary) {
887                                 cur.undispatched();
888                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
889                         }
890                 } else {
891                         if (reverseDirectionNeeded(cur)) {
892                                 cmd.setAction(cmd.action() == LFUN_WORD_LEFT_SELECT ?
893                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD);
894                         } else {
895                                 cmd.setAction(cmd.action() == LFUN_WORD_LEFT_SELECT ?
896                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD);
897                         }
898                         dispatch(cur, cmd);
899                         return;
900                 }
901                 break;
902
903         case LFUN_WORD_BACKWARD:
904         case LFUN_WORD_BACKWARD_SELECT:
905                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_BACKWARD_SELECT);
906                 needsUpdate |= cursorBackwardOneWord(cur);
907         
908                 if (!needsUpdate && oldTopSlice == cur.top()
909                                 && cur.boundary() == oldBoundary) {
910                         cur.undispatched();
911                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
912                 
913                         // we will probably be moving out the inset, so we should execute
914                         // the depm-mechanism, but only when the cursor has a place to 
915                         // go outside this inset, i.e. in a slice above.
916                         if (cur.depth() > 1 && cur.pos() == 0 
917                                   && cur.pit() == 0) {
918                                 // The cursor hasn't changed yet. To give the 
919                                 // DEPM the possibility of doing something we must
920                                 // provide it with two different cursors.
921                                 Cursor dummy = cur;
922                                 dummy.pos() = cur.lastpos();
923                                 dummy.pit() = cur.lastpit();
924                                 if (cur.bv().checkDepm(dummy, cur)) {
925                                         cur.forceBufferUpdate();
926                                         // DEPM may have requested a screen update
927                                         cur.screenUpdateFlags(
928                                                 cur.screenUpdate() | dummy.screenUpdate());
929                                 }
930                         }
931                 }
932                 break;
933
934         case LFUN_WORD_SELECT: {
935                 selectWord(cur, WHOLE_WORD);
936                 finishChange(cur, true);
937                 break;
938         }
939
940         case LFUN_NEWLINE_INSERT: {
941                 InsetNewlineParams inp;
942                 docstring arg = cmd.argument();
943                 if (arg == "linebreak")
944                         inp.kind = InsetNewlineParams::LINEBREAK;
945                 else
946                         inp.kind = InsetNewlineParams::NEWLINE;
947                 cap::replaceSelection(cur);
948                 cur.recordUndo();
949                 cur.insert(new InsetNewline(inp));
950                 cur.posForward();
951                 moveCursor(cur, false);
952                 break;
953         }
954
955         case LFUN_TAB_INSERT: {
956                 bool const multi_par_selection = cur.selection() &&
957                         cur.selBegin().pit() != cur.selEnd().pit();
958                 if (multi_par_selection) {
959                         // If there is a multi-paragraph selection, a tab is inserted
960                         // at the beginning of each paragraph.
961                         cur.recordUndoSelection();
962                         pit_type const pit_end = cur.selEnd().pit();
963                         for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
964                                 pars_[pit].insertChar(0, '\t', 
965                                                       bv->buffer().params().trackChanges);
966                                 // Update the selection pos to make sure the selection does not
967                                 // change as the inserted tab will increase the logical pos.
968                                 if (cur.realAnchor().pit() == pit)
969                                         cur.realAnchor().forwardPos();
970                                 if (cur.pit() == pit)
971                                         cur.forwardPos();
972                         }
973                         cur.finishUndo();
974                 } else {
975                         // Maybe we shouldn't allow tabs within a line, because they
976                         // are not (yet) aligned as one might do expect.
977                         FuncRequest cmd(LFUN_SELF_INSERT, from_ascii("\t"));
978                         dispatch(cur, cmd);     
979                 }
980                 break;
981         }
982
983         case LFUN_TAB_DELETE: {
984                 bool const tc = bv->buffer().params().trackChanges;
985                 if (cur.selection()) {
986                         // If there is a selection, a tab (if present) is removed from
987                         // the beginning of each paragraph.
988                         cur.recordUndoSelection();
989                         pit_type const pit_end = cur.selEnd().pit();
990                         for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
991                                 Paragraph & par = paragraphs()[pit];
992                                 if (par.empty())
993                                         continue;
994                                 char_type const c = par.getChar(0);
995                                 if (c == '\t' || c == ' ') {
996                                         // remove either 1 tab or 4 spaces.
997                                         int const n = (c == ' ' ? 4 : 1);
998                                         for (int i = 0; i < n 
999                                                   && !par.empty() && par.getChar(0) == c; ++i) {
1000                                                 if (cur.pit() == pit)
1001                                                         cur.posBackward();
1002                                                 if (cur.realAnchor().pit() == pit 
1003                                                           && cur.realAnchor().pos() > 0 )
1004                                                         cur.realAnchor().backwardPos();
1005                                                 par.eraseChar(0, tc);
1006                                         }
1007                                 }
1008                         }
1009                         cur.finishUndo();
1010                 } else {
1011                         // If there is no selection, try to remove a tab or some spaces 
1012                         // before the position of the cursor.
1013                         Paragraph & par = paragraphs()[cur.pit()];
1014                         pos_type const pos = cur.pos();
1015                         
1016                         if (pos == 0)
1017                                 break;
1018                         
1019                         char_type const c = par.getChar(pos - 1);
1020                         cur.recordUndo();
1021                         if (c == '\t') {
1022                                 cur.posBackward();
1023                                 par.eraseChar(cur.pos(), tc);
1024                         } else
1025                                 for (int n_spaces = 0; 
1026                                      cur.pos() > 0
1027                                              && par.getChar(cur.pos() - 1) == ' ' 
1028                                              && n_spaces < 4;
1029                                      ++n_spaces) {
1030                                         cur.posBackward();
1031                                         par.eraseChar(cur.pos(), tc);
1032                                 }
1033                         cur.finishUndo();
1034                 }
1035                 break;
1036         }
1037
1038         case LFUN_CHAR_DELETE_FORWARD:
1039                 if (!cur.selection()) {
1040                         if (cur.pos() == cur.paragraph().size())
1041                                 // Par boundary, force full-screen update
1042                                 singleParUpdate = false;
1043                         needsUpdate |= erase(cur);
1044                         cur.resetAnchor();
1045                         // It is possible to make it a lot faster still
1046                         // just comment out the line below...
1047                 } else {
1048                         cutSelection(cur, true, false);
1049                         singleParUpdate = false;
1050                 }
1051                 moveCursor(cur, false);
1052                 break;
1053
1054         case LFUN_CHAR_DELETE_BACKWARD:
1055                 if (!cur.selection()) {
1056                         if (bv->getIntl().getTransManager().backspace()) {
1057                                 // Par boundary, full-screen update
1058                                 if (cur.pos() == 0)
1059                                         singleParUpdate = false;
1060                                 needsUpdate |= backspace(cur);
1061                                 cur.resetAnchor();
1062                                 // It is possible to make it a lot faster still
1063                                 // just comment out the line below...
1064                         }
1065                 } else {
1066                         cutSelection(cur, true, false);
1067                         singleParUpdate = false;
1068                 }
1069                 break;
1070
1071         case LFUN_PARAGRAPH_BREAK:
1072                 cap::replaceSelection(cur);
1073                 breakParagraph(cur, cmd.argument() == "inverse");
1074                 cur.resetAnchor();
1075                 break;
1076
1077         case LFUN_INSET_INSERT: {
1078                 cur.recordUndo();
1079
1080                 // We have to avoid triggering InstantPreview loading
1081                 // before inserting into the document. See bug #5626.
1082                 bool loaded = bv->buffer().isFullyLoaded();
1083                 bv->buffer().setFullyLoaded(false);
1084                 Inset * inset = createInset(&bv->buffer(), cmd);
1085                 bv->buffer().setFullyLoaded(loaded);
1086
1087                 if (inset) {
1088                         // FIXME (Abdel 01/02/2006):
1089                         // What follows would be a partial fix for bug 2154:
1090                         //   http://www.lyx.org/trac/ticket/2154
1091                         // This automatically put the label inset _after_ a
1092                         // numbered section. It should be possible to extend the mechanism
1093                         // to any kind of LateX environement.
1094                         // The correct way to fix that bug would be at LateX generation.
1095                         // I'll let the code here for reference as it could be used for some
1096                         // other feature like "automatic labelling".
1097                         /*
1098                         Paragraph & par = pars_[cur.pit()];
1099                         if (inset->lyxCode() == LABEL_CODE
1100                                 && !par.layout().counter.empty() {
1101                                 // Go to the end of the paragraph
1102                                 // Warning: Because of Change-Tracking, the last
1103                                 // position is 'size()' and not 'size()-1':
1104                                 cur.pos() = par.size();
1105                                 // Insert a new paragraph
1106                                 FuncRequest fr(LFUN_BREAK_PARAGRAPH);
1107                                 dispatch(cur, fr);
1108                         }
1109                         */
1110                         if (cur.selection())
1111                                 cutSelection(cur, true, false);
1112                         cur.insert(inset);
1113                         if (inset->editable() && inset->asInsetText())
1114                                 inset->edit(cur, true);
1115                         else
1116                                 cur.posForward();
1117
1118                         // trigger InstantPreview now
1119                         if (inset->lyxCode() == EXTERNAL_CODE) {
1120                                 InsetExternal & ins =
1121                                         static_cast<InsetExternal &>(*inset);
1122                                 ins.updatePreview();
1123                         }
1124                 }
1125
1126                 break;
1127         }
1128
1129         case LFUN_INSET_DISSOLVE: {
1130                 if (dissolveInset(cur)) {
1131                         needsUpdate = true;
1132                         cur.forceBufferUpdate();
1133                 }
1134                 break;
1135         }
1136
1137         case LFUN_SET_GRAPHICS_GROUP: {
1138                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
1139                 if (!ins)
1140                         break;
1141
1142                 cur.recordUndo();
1143
1144                 string id = to_utf8(cmd.argument());
1145                 string grp = graphics::getGroupParams(bv->buffer(), id);
1146                 InsetGraphicsParams tmp, inspar = ins->getParams();
1147
1148                 if (id.empty())
1149                         inspar.groupId = to_utf8(cmd.argument());
1150                 else {
1151                         InsetGraphics::string2params(grp, bv->buffer(), tmp);
1152                         tmp.filename = inspar.filename;
1153                         inspar = tmp;
1154                 }
1155
1156                 ins->setParams(inspar);
1157         }
1158
1159         case LFUN_SPACE_INSERT:
1160                 if (cur.paragraph().layout().free_spacing)
1161                         insertChar(cur, ' ');
1162                 else {
1163                         doInsertInset(cur, this, cmd, false, false);
1164                         cur.posForward();
1165                 }
1166                 moveCursor(cur, false);
1167                 break;
1168
1169         case LFUN_SPECIALCHAR_INSERT: {
1170                 string const name = to_utf8(cmd.argument());
1171                 if (name == "hyphenation")
1172                         specialChar(cur, InsetSpecialChar::HYPHENATION);
1173                 else if (name == "ligature-break")
1174                         specialChar(cur, InsetSpecialChar::LIGATURE_BREAK);
1175                 else if (name == "slash")
1176                         specialChar(cur, InsetSpecialChar::SLASH);
1177                 else if (name == "nobreakdash")
1178                         specialChar(cur, InsetSpecialChar::NOBREAKDASH);
1179                 else if (name == "dots")
1180                         specialChar(cur, InsetSpecialChar::LDOTS);
1181                 else if (name == "end-of-sentence")
1182                         specialChar(cur, InsetSpecialChar::END_OF_SENTENCE);
1183                 else if (name == "menu-separator")
1184                         specialChar(cur, InsetSpecialChar::MENU_SEPARATOR);
1185                 else if (name.empty())
1186                         lyxerr << "LyX function 'specialchar-insert' needs an argument." << endl;
1187                 else
1188                         lyxerr << "Wrong argument for LyX function 'specialchar-insert'." << endl;
1189                 break;
1190         }
1191
1192         case LFUN_IPAMACRO_INSERT: {
1193                 string const arg = cmd.getArg(0);
1194                 if (arg == "deco") {
1195                         // Open the inset, and move the current selection
1196                         // inside it.
1197                         doInsertInset(cur, this, cmd, true, true);
1198                         cur.posForward();
1199                         // Some insets are numbered, others are shown in the outline pane so
1200                         // let's update the labels and the toc backend.
1201                         cur.forceBufferUpdate();
1202                         break;
1203                 }
1204                 if (arg == "tone-falling")
1205                         ipaChar(cur, InsetIPAChar::TONE_FALLING);
1206                 else if (arg == "tone-rising")
1207                         ipaChar(cur, InsetIPAChar::TONE_RISING);
1208                 else if (arg == "tone-high-rising")
1209                         ipaChar(cur, InsetIPAChar::TONE_HIGH_RISING);
1210                 else if (arg == "tone-low-rising")
1211                         ipaChar(cur, InsetIPAChar::TONE_LOW_RISING);
1212                 else if (arg == "tone-high-rising-falling")
1213                         ipaChar(cur, InsetIPAChar::TONE_HIGH_RISING_FALLING);
1214                 else if (arg.empty())
1215                         lyxerr << "LyX function 'ipamacro-insert' needs an argument." << endl;
1216                 else
1217                         lyxerr << "Wrong argument for LyX function 'ipamacro-insert'." << endl;
1218                 break;
1219         }
1220
1221         case LFUN_WORD_UPCASE:
1222                 changeCase(cur, text_uppercase);
1223                 break;
1224
1225         case LFUN_WORD_LOWCASE:
1226                 changeCase(cur, text_lowercase);
1227                 break;
1228
1229         case LFUN_WORD_CAPITALIZE:
1230                 changeCase(cur, text_capitalization);
1231                 break;
1232
1233         case LFUN_CHARS_TRANSPOSE:
1234                 charsTranspose(cur);
1235                 break;
1236
1237         case LFUN_PASTE: {
1238                 cur.message(_("Paste"));
1239                 LASSERT(cur.selBegin().idx() == cur.selEnd().idx(), /**/);
1240                 cap::replaceSelection(cur);
1241
1242                 // without argument?
1243                 string const arg = to_utf8(cmd.argument());
1244                 if (arg.empty()) {
1245                         if (theClipboard().isInternal())
1246                                 pasteFromStack(cur, bv->buffer().errorList("Paste"), 0);
1247                         else if (theClipboard().hasGraphicsContents() 
1248                                      && !theClipboard().hasTextContents())
1249                                 pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"));
1250                         else
1251                                 pasteClipboardText(cur, bv->buffer().errorList("Paste"));
1252                 } else if (isStrUnsignedInt(arg)) {
1253                         // we have a numerical argument
1254                         pasteFromStack(cur, bv->buffer().errorList("Paste"),
1255                                        convert<unsigned int>(arg));
1256                 } else {
1257                         Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
1258                         if (arg == "pdf")
1259                                 type = Clipboard::PdfGraphicsType;
1260                         else if (arg == "png")
1261                                 type = Clipboard::PngGraphicsType;
1262                         else if (arg == "jpeg")
1263                                 type = Clipboard::JpegGraphicsType;
1264                         else if (arg == "linkback")
1265                                 type = Clipboard::LinkBackGraphicsType;
1266                         else if (arg == "emf")
1267                                 type = Clipboard::EmfGraphicsType;
1268                         else if (arg == "wmf")
1269                                 type = Clipboard::WmfGraphicsType;
1270
1271                         else
1272                                 LASSERT(false, /**/);
1273
1274                         pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"), type);
1275                 }
1276
1277                 bv->buffer().errors("Paste");
1278                 cur.clearSelection(); // bug 393
1279                 cur.finishUndo();
1280                 break;
1281         }
1282
1283         case LFUN_CUT:
1284                 cutSelection(cur, true, true);
1285                 cur.message(_("Cut"));
1286                 break;
1287
1288         case LFUN_COPY:
1289                 copySelection(cur);
1290                 cur.message(_("Copy"));
1291                 break;
1292
1293         case LFUN_SERVER_GET_XY:
1294                 cur.message(from_utf8(
1295                         convert<string>(tm->cursorX(cur.top(), cur.boundary()))
1296                         + ' ' + convert<string>(tm->cursorY(cur.top(), cur.boundary()))));
1297                 break;
1298
1299         case LFUN_SERVER_SET_XY: {
1300                 int x = 0;
1301                 int y = 0;
1302                 istringstream is(to_utf8(cmd.argument()));
1303                 is >> x >> y;
1304                 if (!is)
1305                         lyxerr << "SETXY: Could not parse coordinates in '"
1306                                << to_utf8(cmd.argument()) << endl;
1307                 else
1308                         tm->setCursorFromCoordinates(cur, x, y);
1309                 break;
1310         }
1311
1312         case LFUN_SERVER_GET_LAYOUT:
1313                 cur.message(cur.paragraph().layout().name());
1314                 break;
1315
1316         case LFUN_LAYOUT: {
1317                 docstring layout = cmd.argument();
1318                 LYXERR(Debug::INFO, "LFUN_LAYOUT: (arg) " << to_utf8(layout));
1319
1320                 Paragraph const & para = cur.paragraph();
1321                 docstring const old_layout = para.layout().name();
1322                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1323
1324                 if (layout.empty())
1325                         layout = tclass.defaultLayoutName();
1326
1327                 if (owner_->forcePlainLayout())
1328                         // in this case only the empty layout is allowed
1329                         layout = tclass.plainLayoutName();
1330                 else if (para.usePlainLayout()) {
1331                         // in this case, default layout maps to empty layout
1332                         if (layout == tclass.defaultLayoutName())
1333                                 layout = tclass.plainLayoutName();
1334                 } else {
1335                         // otherwise, the empty layout maps to the default
1336                         if (layout == tclass.plainLayoutName())
1337                                 layout = tclass.defaultLayoutName();
1338                 }
1339
1340                 bool hasLayout = tclass.hasLayout(layout);
1341
1342                 // If the entry is obsolete, use the new one instead.
1343                 if (hasLayout) {
1344                         docstring const & obs = tclass[layout].obsoleted_by();
1345                         if (!obs.empty())
1346                                 layout = obs;
1347                 }
1348
1349                 if (!hasLayout) {
1350                         cur.errorMessage(from_utf8(N_("Layout ")) + cmd.argument() +
1351                                 from_utf8(N_(" not known")));
1352                         break;
1353                 }
1354
1355                 bool change_layout = (old_layout != layout);
1356
1357                 if (!change_layout && cur.selection() &&
1358                         cur.selBegin().pit() != cur.selEnd().pit())
1359                 {
1360                         pit_type spit = cur.selBegin().pit();
1361                         pit_type epit = cur.selEnd().pit() + 1;
1362                         while (spit != epit) {
1363                                 if (pars_[spit].layout().name() != old_layout) {
1364                                         change_layout = true;
1365                                         break;
1366                                 }
1367                                 ++spit;
1368                         }
1369                 }
1370
1371                 if (change_layout)
1372                         setLayout(cur, layout);
1373
1374                 Layout::LaTeXArgMap args = tclass[layout].args();
1375                 Layout::LaTeXArgMap::const_iterator lait = args.begin();
1376                 Layout::LaTeXArgMap::const_iterator const laend = args.end();
1377                 for (; lait != laend; ++lait) {
1378                         Layout::latexarg arg = (*lait).second;
1379                         if (arg.autoinsert) {
1380                                 FuncRequest cmd(LFUN_ARGUMENT_INSERT, (*lait).first);
1381                                 lyx::dispatch(cmd);
1382                         }
1383                 }
1384
1385                 break;
1386         }
1387
1388         case LFUN_ENVIRONMENT_SPLIT: {
1389                 Paragraph const & para = cur.paragraph();
1390                 docstring const layout = para.layout().name();
1391                 if (cur.pos() > 0)
1392                         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK));
1393                 bool const morecont = cur.lastpos() > cur.pos();
1394                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, "Separator"));
1395                 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK, "inverse"));
1396                 if (morecont) 
1397                         lyx::dispatch(FuncRequest(LFUN_DOWN));
1398                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, layout));
1399
1400                 break;
1401         }
1402
1403         case LFUN_CLIPBOARD_PASTE:
1404                 cap::replaceSelection(cur);
1405                 pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1406                                cmd.argument() == "paragraph");
1407                 bv->buffer().errors("Paste");
1408                 break;
1409
1410         case LFUN_CLIPBOARD_PASTE_SIMPLE:
1411                 cap::replaceSelection(cur);
1412                 pasteSimpleText(cur, cmd.argument() == "paragraph");
1413                 break;
1414
1415         case LFUN_PRIMARY_SELECTION_PASTE:
1416                 cap::replaceSelection(cur);
1417                 pasteString(cur, theSelection().get(),
1418                             cmd.argument() == "paragraph");
1419                 break;
1420
1421         case LFUN_SELECTION_PASTE:
1422                 // Copy the selection buffer to the clipboard stack,
1423                 // because we want it to appear in the "Edit->Paste
1424                 // recent" menu.
1425                 cap::replaceSelection(cur);
1426                 cap::copySelectionToStack();
1427                 cap::pasteSelection(bv->cursor(), bv->buffer().errorList("Paste"));
1428                 bv->buffer().errors("Paste");
1429                 break;
1430
1431         case LFUN_UNICODE_INSERT: {
1432                 if (cmd.argument().empty())
1433                         break;
1434                 docstring hexstring = cmd.argument();
1435                 if (isHex(hexstring)) {
1436                         char_type c = hexToInt(hexstring);
1437                         if (c >= 32 && c < 0x10ffff) {
1438                                 lyxerr << "Inserting c: " << c << endl;
1439                                 docstring s = docstring(1, c);
1440                                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, s));
1441                         }
1442                 }
1443                 break;
1444         }
1445
1446         case LFUN_QUOTE_INSERT: {
1447                 cap::replaceSelection(cur);
1448                 cur.recordUndo();
1449
1450                 Paragraph const & par = cur.paragraph();
1451                 pos_type pos = cur.pos();
1452                 // Ignore deleted text before cursor
1453                 while (pos > 0 && par.isDeleted(pos - 1))
1454                         --pos;
1455
1456                 BufferParams const & bufparams = bv->buffer().params();
1457                 bool const hebrew = 
1458                         par.getFontSettings(bufparams, pos).language()->lang() == "hebrew";
1459                 bool const allow_inset_quote = !(par.isPassThru() || hebrew);
1460                 
1461                 if (allow_inset_quote) {
1462                         char_type c = ' ';
1463                         if (pos > 0 && (!cur.prevInset() || !cur.prevInset()->isSpace()))
1464                                 c = par.getChar(pos - 1);
1465                         string const arg = to_utf8(cmd.argument());
1466                         InsetQuotes::QuoteTimes const quote_type = (arg == "single")
1467                                 ? InsetQuotes::SingleQuotes : InsetQuotes::DoubleQuotes;
1468                         cur.insert(new InsetQuotes(cur.buffer(), c, quote_type));
1469                         cur.posForward();
1470                 } else {
1471                         // The cursor might have been invalidated by the replaceSelection.
1472                         cur.buffer()->changed(true);
1473                         lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, "\""));
1474                 }                       
1475                 break;
1476         }
1477
1478         case LFUN_DATE_INSERT: {
1479                 string const format = cmd.argument().empty()
1480                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
1481                 string const time = formatted_time(current_time(), format);
1482                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, time));
1483                 break;
1484         }
1485
1486         case LFUN_MOUSE_TRIPLE:
1487                 if (cmd.button() == mouse_button::button1) {
1488                         tm->cursorHome(cur);
1489                         cur.resetAnchor();
1490                         tm->cursorEnd(cur);
1491                         cur.setSelection();
1492                         bv->cursor() = cur;
1493                 }
1494                 break;
1495
1496         case LFUN_MOUSE_DOUBLE:
1497                 if (cmd.button() == mouse_button::button1) {
1498                         selectWord(cur, WHOLE_WORD_STRICT);
1499                         bv->cursor() = cur;
1500                 }
1501                 break;
1502
1503         // Single-click on work area
1504         case LFUN_MOUSE_PRESS: {
1505                 // We are not marking a selection with the keyboard in any case.
1506                 Cursor & bvcur = cur.bv().cursor();
1507                 bvcur.setMark(false);
1508                 switch (cmd.button()) {
1509                 case mouse_button::button1:
1510                         // Set the cursor
1511                         if (!bv->mouseSetCursor(cur, cmd.argument() == "region-select"))
1512                                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1513                         if (bvcur.wordSelection())
1514                                 selectWord(bvcur, WHOLE_WORD);
1515                         break;
1516
1517                 case mouse_button::button2:
1518                         // Middle mouse pasting.
1519                         bv->mouseSetCursor(cur);
1520                         lyx::dispatch(
1521                                 FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1522                                             "selection-paste ; primary-selection-paste paragraph"));
1523                         cur.noScreenUpdate();
1524                         break;
1525
1526                 case mouse_button::button3: {
1527                         // Don't do anything if we right-click a
1528                         // selection, a context menu will popup.
1529                         if (bvcur.selection() && cur >= bvcur.selectionBegin()
1530                             && cur < bvcur.selectionEnd()) {
1531                                 cur.noScreenUpdate();
1532                                 return;
1533                         }
1534                         if (!bv->mouseSetCursor(cur, false))
1535                                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1536                         break;
1537                 }
1538
1539                 default:
1540                         break;
1541                 } // switch (cmd.button())
1542                 break;
1543         }
1544         case LFUN_MOUSE_MOTION: {
1545                 // Mouse motion with right or middle mouse do nothing for now.
1546                 if (cmd.button() != mouse_button::button1) {
1547                         cur.noScreenUpdate();
1548                         return;
1549                 }
1550                 // ignore motions deeper nested than the real anchor
1551                 Cursor & bvcur = cur.bv().cursor();
1552                 if (!bvcur.realAnchor().hasPart(cur)) {
1553                         cur.undispatched();
1554                         break;
1555                 }
1556                 CursorSlice old = bvcur.top();
1557
1558                 int const wh = bv->workHeight();
1559                 int const y = max(0, min(wh - 1, cmd.y()));
1560
1561                 tm->setCursorFromCoordinates(cur, cmd.x(), y);
1562                 cur.setTargetX(cmd.x());
1563                 if (cmd.y() >= wh)
1564                         lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1565                 else if (cmd.y() < 0)
1566                         lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1567                 // This is to allow jumping over large insets
1568                 if (cur.top() == old) {
1569                         if (cmd.y() >= wh)
1570                                 lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1571                         else if (cmd.y() < 0)
1572                                 lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1573                 }
1574                 // We continue with our existing selection or start a new one, so don't
1575                 // reset the anchor.
1576                 bvcur.setCursor(cur);
1577                 bvcur.setSelection(true);
1578                 if (cur.top() == old) {
1579                         // We didn't move one iota, so no need to update the screen.
1580                         cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1581                         //cur.noScreenUpdate();
1582                         return;
1583                 }
1584                 break;
1585         }
1586
1587         case LFUN_MOUSE_RELEASE:
1588                 switch (cmd.button()) {
1589                 case mouse_button::button1:
1590                         // Cursor was set at LFUN_MOUSE_PRESS or LFUN_MOUSE_MOTION time.
1591                         // If there is a new selection, update persistent selection;
1592                         // otherwise, single click does not clear persistent selection
1593                         // buffer.
1594                         if (cur.selection()) {
1595                                 // Finish selection. If double click,
1596                                 // cur is moved to the end of word by
1597                                 // selectWord but bvcur is current
1598                                 // mouse position.
1599                                 cur.bv().cursor().setSelection();
1600                                 // We might have removed an empty but drawn selection
1601                                 // (probably a margin)
1602                                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1603                         } else
1604                                 cur.noScreenUpdate();
1605                         // FIXME: We could try to handle drag and drop of selection here.
1606                         return;
1607
1608                 case mouse_button::button2:
1609                         // Middle mouse pasting is handled at mouse press time,
1610                         // see LFUN_MOUSE_PRESS.
1611                         cur.noScreenUpdate();
1612                         return;
1613
1614                 case mouse_button::button3:
1615                         // Cursor was set at LFUN_MOUSE_PRESS time.
1616                         // FIXME: If there is a selection we could try to handle a special
1617                         // drag & drop context menu.
1618                         cur.noScreenUpdate();
1619                         return;
1620
1621                 case mouse_button::none:
1622                 case mouse_button::button4:
1623                 case mouse_button::button5:
1624                         break;
1625                 } // switch (cmd.button())
1626
1627                 break;
1628
1629         case LFUN_SELF_INSERT: {
1630                 if (cmd.argument().empty())
1631                         break;
1632
1633                 // Automatically delete the currently selected
1634                 // text and replace it with what is being
1635                 // typed in now. Depends on lyxrc settings
1636                 // "auto_region_delete", which defaults to
1637                 // true (on).
1638
1639                 if (lyxrc.auto_region_delete && cur.selection())
1640                         cutSelection(cur, false, false);
1641
1642                 cur.clearSelection();
1643
1644                 docstring::const_iterator cit = cmd.argument().begin();
1645                 docstring::const_iterator const end = cmd.argument().end();
1646                 for (; cit != end; ++cit)
1647                         bv->translateAndInsert(*cit, this, cur);
1648
1649                 cur.resetAnchor();
1650                 moveCursor(cur, false);
1651                 cur.markNewWordPosition();
1652                 bv->bookmarkEditPosition();
1653                 break;
1654         }
1655
1656         case LFUN_HYPERLINK_INSERT: {
1657                 InsetCommandParams p(HYPERLINK_CODE);
1658                 docstring content;
1659                 if (cur.selection()) {
1660                         content = cur.selectionAsString(false);
1661                         cutSelection(cur, true, false);
1662                 }
1663                 p["target"] = (cmd.argument().empty()) ?
1664                         content : cmd.argument();
1665                 string const data = InsetCommand::params2string(p);
1666                 if (p["target"].empty()) {
1667                         bv->showDialog("href", data);
1668                 } else {
1669                         FuncRequest fr(LFUN_INSET_INSERT, data);
1670                         dispatch(cur, fr);
1671                 }
1672                 break;
1673         }
1674
1675         case LFUN_LABEL_INSERT: {
1676                 InsetCommandParams p(LABEL_CODE);
1677                 // Try to generate a valid label
1678                 p["name"] = (cmd.argument().empty()) ?
1679                         cur.getPossibleLabel() :
1680                         cmd.argument();
1681                 string const data = InsetCommand::params2string(p);
1682
1683                 if (cmd.argument().empty()) {
1684                         bv->showDialog("label", data);
1685                 } else {
1686                         FuncRequest fr(LFUN_INSET_INSERT, data);
1687                         dispatch(cur, fr);
1688                 }
1689                 break;
1690         }
1691
1692         case LFUN_INFO_INSERT: {
1693                 Inset * inset;
1694                 if (cmd.argument().empty() && cur.selection()) {
1695                         // if command argument is empty use current selection as parameter.
1696                         docstring ds = cur.selectionAsString(false);
1697                         cutSelection(cur, true, false);
1698                         FuncRequest cmd0(cmd, ds);
1699                         inset = createInset(cur.buffer(), cmd0);
1700                 } else {
1701                         inset = createInset(cur.buffer(), cmd);
1702                 }
1703                 if (!inset)
1704                         break;
1705                 cur.recordUndo();
1706                 insertInset(cur, inset);
1707                 cur.posForward();
1708                 break;
1709         }
1710         case LFUN_CAPTION_INSERT:
1711         case LFUN_FOOTNOTE_INSERT:
1712         case LFUN_NOTE_INSERT:
1713         case LFUN_BOX_INSERT:
1714         case LFUN_BRANCH_INSERT:
1715         case LFUN_PHANTOM_INSERT:
1716         case LFUN_ERT_INSERT:
1717         case LFUN_LISTING_INSERT:
1718         case LFUN_MARGINALNOTE_INSERT:
1719         case LFUN_ARGUMENT_INSERT:
1720         case LFUN_INDEX_INSERT:
1721         case LFUN_PREVIEW_INSERT:
1722         case LFUN_SCRIPT_INSERT:
1723         case LFUN_IPA_INSERT:
1724                 // Open the inset, and move the current selection
1725                 // inside it.
1726                 doInsertInset(cur, this, cmd, true, true);
1727                 cur.posForward();
1728                 // Some insets are numbered, others are shown in the outline pane so
1729                 // let's update the labels and the toc backend.
1730                 cur.forceBufferUpdate();
1731                 break;
1732
1733         case LFUN_FLEX_INSERT: {
1734                 // Open the inset, and move the current selection
1735                 // inside it.
1736                 bool const sel = cur.selection();
1737                 doInsertInset(cur, this, cmd, true, true);
1738                 // Insert auto-insert arguments
1739                 bool autoargs = false;
1740                 Layout::LaTeXArgMap args = cur.inset().getLayout().latexargs();
1741                 Layout::LaTeXArgMap::const_iterator lait = args.begin();
1742                 Layout::LaTeXArgMap::const_iterator const laend = args.end();
1743                 for (; lait != laend; ++lait) {
1744                         Layout::latexarg arg = (*lait).second;
1745                         if (arg.autoinsert) {
1746                                 // The cursor might have been invalidated by the replaceSelection.
1747                                 cur.buffer()->changed(true);
1748                                 FuncRequest cmd(LFUN_ARGUMENT_INSERT, (*lait).first);
1749                                 lyx::dispatch(cmd);
1750                                 autoargs = true;
1751                         }
1752                 }
1753                 if (!autoargs) {
1754                         if (sel)
1755                                 cur.leaveInset(cur.inset());
1756                         cur.posForward();
1757                 }
1758                 // Some insets are numbered, others are shown in the outline pane so
1759                 // let's update the labels and the toc backend.
1760                 cur.forceBufferUpdate();
1761                 break;
1762         }
1763
1764         case LFUN_TABULAR_INSERT:
1765                 // if there were no arguments, just open the dialog
1766                 if (doInsertInset(cur, this, cmd, false, true))
1767                         cur.posForward();
1768                 else
1769                         bv->showDialog("tabularcreate");
1770
1771                 break;
1772
1773         case LFUN_FLOAT_INSERT:
1774         case LFUN_FLOAT_WIDE_INSERT:
1775         case LFUN_WRAP_INSERT: {
1776                 // will some content be moved into the inset?
1777                 bool const content = cur.selection();
1778                 // does the content consist of multiple paragraphs?
1779                 bool const singlepar = (cur.selBegin().pit() == cur.selEnd().pit());
1780
1781                 doInsertInset(cur, this, cmd, true, true);
1782                 cur.posForward();
1783
1784                 // If some single-par content is moved into the inset,
1785                 // doInsertInset puts the cursor outside the inset.
1786                 // To insert the caption we put it back into the inset.
1787                 // FIXME cleanup doInsertInset to avoid such dances!
1788                 if (content && singlepar)
1789                         cur.backwardPos();
1790
1791                 ParagraphList & pars = cur.text()->paragraphs();
1792
1793                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1794
1795                 // add a separate paragraph for the caption inset
1796                 pars.push_back(Paragraph());
1797                 pars.back().setInsetOwner(&cur.text()->inset());
1798                 pars.back().setPlainOrDefaultLayout(tclass);
1799                 int cap_pit = pars.size() - 1;
1800
1801                 // if an empty inset was created, we create an additional empty
1802                 // paragraph at the bottom so that the user can choose where to put
1803                 // the graphics (or table).
1804                 if (!content) {
1805                         pars.push_back(Paragraph());
1806                         pars.back().setInsetOwner(&cur.text()->inset());
1807                         pars.back().setPlainOrDefaultLayout(tclass);
1808                 }
1809
1810                 // reposition the cursor to the caption
1811                 cur.pit() = cap_pit;
1812                 cur.pos() = 0;
1813                 // FIXME: This Text/Cursor dispatch handling is a mess!
1814                 // We cannot use Cursor::dispatch here it needs access to up to
1815                 // date metrics.
1816                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
1817                 doInsertInset(cur, cur.text(), cmd_caption, true, false);
1818                 cur.forceBufferUpdate();
1819                 cur.screenUpdateFlags(Update::Force);
1820                 // FIXME: When leaving the Float (or Wrap) inset we should
1821                 // delete any empty paragraph left above or below the
1822                 // caption.
1823                 break;
1824         }
1825
1826         case LFUN_NOMENCL_INSERT: {
1827                 InsetCommandParams p(NOMENCL_CODE);
1828                 if (cmd.argument().empty())
1829                         p["symbol"] = bv->cursor().innerText()->getStringToIndex(bv->cursor());
1830                 else
1831                         p["symbol"] = cmd.argument();
1832                 string const data = InsetCommand::params2string(p);
1833                 bv->showDialog("nomenclature", data);
1834                 break;
1835         }
1836
1837         case LFUN_INDEX_PRINT: {
1838                 InsetCommandParams p(INDEX_PRINT_CODE);
1839                 if (cmd.argument().empty())
1840                         p["type"] = from_ascii("idx");
1841                 else
1842                         p["type"] = cmd.argument();
1843                 string const data = InsetCommand::params2string(p);
1844                 FuncRequest fr(LFUN_INSET_INSERT, data);
1845                 dispatch(cur, fr);
1846                 break;
1847         }
1848         
1849         case LFUN_NOMENCL_PRINT:
1850         case LFUN_NEWPAGE_INSERT:
1851                 // do nothing fancy
1852                 doInsertInset(cur, this, cmd, false, false);
1853                 cur.posForward();
1854                 break;
1855
1856         case LFUN_DEPTH_DECREMENT:
1857                 changeDepth(cur, DEC_DEPTH);
1858                 break;
1859
1860         case LFUN_DEPTH_INCREMENT:
1861                 changeDepth(cur, INC_DEPTH);
1862                 break;
1863
1864         case LFUN_MATH_DISPLAY:
1865                 mathDispatch(cur, cmd, true);
1866                 break;
1867
1868         case LFUN_REGEXP_MODE:
1869                 regexpDispatch(cur, cmd);
1870                 break;
1871
1872         case LFUN_MATH_MODE:
1873                 if (cmd.argument() == "on")
1874                         // don't pass "on" as argument
1875                         // (it would appear literally in the first cell)
1876                         mathDispatch(cur, FuncRequest(LFUN_MATH_MODE), false);
1877                 else
1878                         mathDispatch(cur, cmd, false);
1879                 break;
1880
1881         case LFUN_MATH_MACRO:
1882                 if (cmd.argument().empty())
1883                         cur.errorMessage(from_utf8(N_("Missing argument")));
1884                 else {
1885                         cur.recordUndo();
1886                         string s = to_utf8(cmd.argument());
1887                         string const s1 = token(s, ' ', 1);
1888                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
1889                         string const s2 = token(s, ' ', 2);
1890                         MacroType type = MacroTypeNewcommand;
1891                         if (s2 == "def")
1892                                 type = MacroTypeDef;
1893                         MathMacroTemplate * inset = new MathMacroTemplate(cur.buffer(),
1894                                 from_utf8(token(s, ' ', 0)), nargs, false, type);
1895                         inset->setBuffer(bv->buffer());
1896                         insertInset(cur, inset);
1897
1898                         // enter macro inset and select the name
1899                         cur.push(*inset);
1900                         cur.top().pos() = cur.top().lastpos();
1901                         cur.resetAnchor();
1902                         cur.setSelection(true);
1903                         cur.top().pos() = 0;
1904                 }
1905                 break;
1906
1907         // passthrough hat and underscore outside mathed:
1908         case LFUN_MATH_SUBSCRIPT:
1909                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "_"), false);
1910                 break;
1911         case LFUN_MATH_SUPERSCRIPT:
1912                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "^"), false);
1913                 break;
1914
1915         case LFUN_MATH_INSERT:
1916         case LFUN_MATH_AMS_MATRIX:
1917         case LFUN_MATH_MATRIX:
1918         case LFUN_MATH_DELIM:
1919         case LFUN_MATH_BIGDELIM: {
1920                 cur.recordUndo();
1921                 cap::replaceSelection(cur);
1922                 cur.insert(new InsetMathHull(cur.buffer(), hullSimple));
1923                 checkAndActivateInset(cur, true);
1924                 LASSERT(cur.inMathed(), /**/);
1925                 cur.dispatch(cmd);
1926                 break;
1927         }
1928
1929         case LFUN_FONT_EMPH: {
1930                 Font font(ignore_font, ignore_language);
1931                 font.fontInfo().setEmph(FONT_TOGGLE);
1932                 toggleAndShow(cur, this, font);
1933                 break;
1934         }
1935
1936         case LFUN_FONT_ITAL: {
1937                 Font font(ignore_font, ignore_language);
1938                 font.fontInfo().setShape(ITALIC_SHAPE);
1939                 toggleAndShow(cur, this, font);
1940                 break;
1941         }
1942
1943         case LFUN_FONT_BOLD:
1944         case LFUN_FONT_BOLDSYMBOL: {
1945                 Font font(ignore_font, ignore_language);
1946                 font.fontInfo().setSeries(BOLD_SERIES);
1947                 toggleAndShow(cur, this, font);
1948                 break;
1949         }
1950
1951         case LFUN_FONT_NOUN: {
1952                 Font font(ignore_font, ignore_language);
1953                 font.fontInfo().setNoun(FONT_TOGGLE);
1954                 toggleAndShow(cur, this, font);
1955                 break;
1956         }
1957
1958         case LFUN_FONT_TYPEWRITER: {
1959                 Font font(ignore_font, ignore_language);
1960                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
1961                 toggleAndShow(cur, this, font);
1962                 break;
1963         }
1964
1965         case LFUN_FONT_SANS: {
1966                 Font font(ignore_font, ignore_language);
1967                 font.fontInfo().setFamily(SANS_FAMILY);
1968                 toggleAndShow(cur, this, font);
1969                 break;
1970         }
1971
1972         case LFUN_FONT_ROMAN: {
1973                 Font font(ignore_font, ignore_language);
1974                 font.fontInfo().setFamily(ROMAN_FAMILY);
1975                 toggleAndShow(cur, this, font);
1976                 break;
1977         }
1978
1979         case LFUN_FONT_DEFAULT: {
1980                 Font font(inherit_font, ignore_language);
1981                 toggleAndShow(cur, this, font);
1982                 break;
1983         }
1984
1985         case LFUN_FONT_STRIKEOUT: {
1986                 Font font(ignore_font, ignore_language);
1987                 font.fontInfo().setStrikeout(FONT_TOGGLE);
1988                 toggleAndShow(cur, this, font);
1989                 break;
1990         }
1991
1992         case LFUN_FONT_UULINE: {
1993                 Font font(ignore_font, ignore_language);
1994                 font.fontInfo().setUuline(FONT_TOGGLE);
1995                 toggleAndShow(cur, this, font);
1996                 break;
1997         }
1998
1999         case LFUN_FONT_UWAVE: {
2000                 Font font(ignore_font, ignore_language);
2001                 font.fontInfo().setUwave(FONT_TOGGLE);
2002                 toggleAndShow(cur, this, font);
2003                 break;
2004         }
2005
2006         case LFUN_FONT_UNDERLINE: {
2007                 Font font(ignore_font, ignore_language);
2008                 font.fontInfo().setUnderbar(FONT_TOGGLE);
2009                 toggleAndShow(cur, this, font);
2010                 break;
2011         }
2012
2013         case LFUN_FONT_SIZE: {
2014                 Font font(ignore_font, ignore_language);
2015                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
2016                 toggleAndShow(cur, this, font);
2017                 break;
2018         }
2019
2020         case LFUN_LANGUAGE: {
2021                 string const lang_arg = cmd.getArg(0);
2022                 bool const reset = (lang_arg.empty() || lang_arg == "reset");
2023                 Language const * lang =
2024                         reset ? reset_language
2025                               : languages.getLanguage(lang_arg);
2026                 // we allow reset_language, which is 0, but only if it
2027                 // was requested via empty or "reset" arg.
2028                 if (!lang && !reset)
2029                         break;
2030                 bool const toggle = (cmd.getArg(1) != "set");
2031                 selectWordWhenUnderCursor(cur, WHOLE_WORD_STRICT);
2032                 Font font(ignore_font, lang);
2033                 toggleAndShow(cur, this, font, toggle);
2034                 break;
2035         }
2036
2037         case LFUN_TEXTSTYLE_APPLY:
2038                 toggleAndShow(cur, this, freefont, toggleall);
2039                 cur.message(_("Character set"));
2040                 break;
2041
2042         // Set the freefont using the contents of \param data dispatched from
2043         // the frontends and apply it at the current cursor location.
2044         case LFUN_TEXTSTYLE_UPDATE: {
2045                 Font font;
2046                 bool toggle;
2047                 if (font.fromString(to_utf8(cmd.argument()), toggle)) {
2048                         freefont = font;
2049                         toggleall = toggle;
2050                         toggleAndShow(cur, this, freefont, toggleall);
2051                         cur.message(_("Character set"));
2052                 } else {
2053                         lyxerr << "Argument not ok";
2054                 }
2055                 break;
2056         }
2057
2058         case LFUN_FINISHED_LEFT:
2059                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
2060                 // We're leaving an inset, going left. If the inset is LTR, we're
2061                 // leaving from the front, so we should not move (remain at --- but
2062                 // not in --- the inset). If the inset is RTL, move left, without
2063                 // entering the inset itself; i.e., move to after the inset.
2064                 if (cur.paragraph().getFontSettings(
2065                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
2066                         cursorVisLeft(cur, true);
2067                 break;
2068
2069         case LFUN_FINISHED_RIGHT:
2070                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
2071                 // We're leaving an inset, going right. If the inset is RTL, we're
2072                 // leaving from the front, so we should not move (remain at --- but
2073                 // not in --- the inset). If the inset is LTR, move right, without
2074                 // entering the inset itself; i.e., move to after the inset.
2075                 if (!cur.paragraph().getFontSettings(
2076                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
2077                         cursorVisRight(cur, true);
2078                 break;
2079
2080         case LFUN_FINISHED_BACKWARD:
2081                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
2082                 break;
2083
2084         case LFUN_FINISHED_FORWARD:
2085                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
2086                 ++cur.pos();
2087                 cur.setCurrentFont();
2088                 break;
2089
2090         case LFUN_LAYOUT_PARAGRAPH: {
2091                 string data;
2092                 params2string(cur.paragraph(), data);
2093                 data = "show\n" + data;
2094                 bv->showDialog("paragraph", data);
2095                 break;
2096         }
2097
2098         case LFUN_PARAGRAPH_UPDATE: {
2099                 string data;
2100                 params2string(cur.paragraph(), data);
2101
2102                 // Will the paragraph accept changes from the dialog?
2103                 bool const accept =
2104                         cur.inset().allowParagraphCustomization(cur.idx());
2105
2106                 data = "update " + convert<string>(accept) + '\n' + data;
2107                 bv->updateDialog("paragraph", data);
2108                 break;
2109         }
2110
2111         case LFUN_ACCENT_UMLAUT:
2112         case LFUN_ACCENT_CIRCUMFLEX:
2113         case LFUN_ACCENT_GRAVE:
2114         case LFUN_ACCENT_ACUTE:
2115         case LFUN_ACCENT_TILDE:
2116         case LFUN_ACCENT_CEDILLA:
2117         case LFUN_ACCENT_MACRON:
2118         case LFUN_ACCENT_DOT:
2119         case LFUN_ACCENT_UNDERDOT:
2120         case LFUN_ACCENT_UNDERBAR:
2121         case LFUN_ACCENT_CARON:
2122         case LFUN_ACCENT_BREVE:
2123         case LFUN_ACCENT_TIE:
2124         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2125         case LFUN_ACCENT_CIRCLE:
2126         case LFUN_ACCENT_OGONEK:
2127                 theApp()->handleKeyFunc(cmd.action());
2128                 if (!cmd.argument().empty())
2129                         // FIXME: Are all these characters encoded in one byte in utf8?
2130                         bv->translateAndInsert(cmd.argument()[0], this, cur);
2131                 cur.screenUpdateFlags(Update::FitCursor);
2132                 break;
2133
2134         case LFUN_FLOAT_LIST_INSERT: {
2135                 DocumentClass const & tclass = bv->buffer().params().documentClass();
2136                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
2137                         cur.recordUndo();
2138                         if (cur.selection())
2139                                 cutSelection(cur, true, false);
2140                         breakParagraph(cur);
2141
2142                         if (cur.lastpos() != 0) {
2143                                 cursorBackward(cur);
2144                                 breakParagraph(cur);
2145                         }
2146
2147                         docstring const laystr = cur.inset().usePlainLayout() ?
2148                                 tclass.plainLayoutName() :
2149                                 tclass.defaultLayoutName();
2150                         setLayout(cur, laystr);
2151                         ParagraphParameters p;
2152                         // FIXME If this call were replaced with one to clearParagraphParams(),
2153                         // then we could get rid of this method altogether.
2154                         setParagraphs(cur, p);
2155                         // FIXME This should be simplified when InsetFloatList takes a
2156                         // Buffer in its constructor.
2157                         InsetFloatList * ifl = new InsetFloatList(cur.buffer(), to_utf8(cmd.argument()));
2158                         ifl->setBuffer(bv->buffer());
2159                         insertInset(cur, ifl);
2160                         cur.posForward();
2161                 } else {
2162                         lyxerr << "Non-existent float type: "
2163                                << to_utf8(cmd.argument()) << endl;
2164                 }
2165                 break;
2166         }
2167
2168         case LFUN_CHANGE_ACCEPT: {
2169                 acceptOrRejectChanges(cur, ACCEPT);
2170                 break;
2171         }
2172
2173         case LFUN_CHANGE_REJECT: {
2174                 acceptOrRejectChanges(cur, REJECT);
2175                 break;
2176         }
2177
2178         case LFUN_THESAURUS_ENTRY: {
2179                 docstring arg = cmd.argument();
2180                 if (arg.empty()) {
2181                         arg = cur.selectionAsString(false);
2182                         // FIXME
2183                         if (arg.size() > 100 || arg.empty()) {
2184                                 // Get word or selection
2185                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2186                                 arg = cur.selectionAsString(false);
2187                                 arg += " lang=" + from_ascii(cur.getFont().language()->lang());
2188                         }
2189                 }
2190                 bv->showDialog("thesaurus", to_utf8(arg));
2191                 break;
2192         }
2193
2194         case LFUN_SPELLING_ADD: {
2195                 docstring word = from_utf8(cmd.getArg(0));
2196                 Language * lang;
2197                 if (word.empty()) {
2198                         word = cur.selectionAsString(false);
2199                         // FIXME
2200                         if (word.size() > 100 || word.empty()) {
2201                                 // Get word or selection
2202                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2203                                 word = cur.selectionAsString(false);
2204                         }
2205                         lang = const_cast<Language *>(cur.getFont().language());
2206                 } else
2207                         lang = const_cast<Language *>(languages.getLanguage(cmd.getArg(1)));
2208                 WordLangTuple wl(word, lang);
2209                 theSpellChecker()->insert(wl);
2210                 break;
2211         }
2212
2213         case LFUN_SPELLING_IGNORE: {
2214                 docstring word = from_utf8(cmd.getArg(0));
2215                 Language * lang;
2216                 if (word.empty()) {
2217                         word = cur.selectionAsString(false);
2218                         // FIXME
2219                         if (word.size() > 100 || word.empty()) {
2220                                 // Get word or selection
2221                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2222                                 word = cur.selectionAsString(false);
2223                         }
2224                         lang = const_cast<Language *>(cur.getFont().language());
2225                 } else
2226                         lang = const_cast<Language *>(languages.getLanguage(cmd.getArg(1)));
2227                 WordLangTuple wl(word, lang);
2228                 theSpellChecker()->accept(wl);
2229                 break;
2230         }
2231
2232         case LFUN_SPELLING_REMOVE: {
2233                 docstring word = from_utf8(cmd.getArg(0));
2234                 Language * lang;
2235                 if (word.empty()) {
2236                         word = cur.selectionAsString(false);
2237                         // FIXME
2238                         if (word.size() > 100 || word.empty()) {
2239                                 // Get word or selection
2240                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2241                                 word = cur.selectionAsString(false);
2242                         }
2243                         lang = const_cast<Language *>(cur.getFont().language());
2244                 } else
2245                         lang = const_cast<Language *>(languages.getLanguage(cmd.getArg(1)));
2246                 WordLangTuple wl(word, lang);
2247                 theSpellChecker()->remove(wl);
2248                 break;
2249         }
2250
2251         case LFUN_PARAGRAPH_PARAMS_APPLY: {
2252                 // Given data, an encoding of the ParagraphParameters
2253                 // generated in the Paragraph dialog, this function sets
2254                 // the current paragraph, or currently selected paragraphs,
2255                 // appropriately.
2256                 // NOTE: This function overrides all existing settings.
2257                 setParagraphs(cur, cmd.argument());
2258                 cur.message(_("Paragraph layout set"));
2259                 break;
2260         }
2261
2262         case LFUN_PARAGRAPH_PARAMS: {
2263                 // Given data, an encoding of the ParagraphParameters as we'd
2264                 // find them in a LyX file, this function modifies the current paragraph,
2265                 // or currently selected paragraphs.
2266                 // NOTE: This function only modifies, and does not override, existing
2267                 // settings.
2268                 setParagraphs(cur, cmd.argument(), true);
2269                 cur.message(_("Paragraph layout set"));
2270                 break;
2271         }
2272
2273         case LFUN_ESCAPE:
2274                 if (cur.selection()) {
2275                         cur.setSelection(false);
2276                 } else {
2277                         cur.undispatched();
2278                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
2279                         // correct, but I'm not 100% sure -- dov, 071019
2280                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
2281                 }
2282                 break;
2283
2284         case LFUN_OUTLINE_UP:
2285                 outline(OutlineUp, cur);
2286                 setCursor(cur, cur.pit(), 0);
2287                 cur.forceBufferUpdate();
2288                 needsUpdate = true;
2289                 break;
2290
2291         case LFUN_OUTLINE_DOWN:
2292                 outline(OutlineDown, cur);
2293                 setCursor(cur, cur.pit(), 0);
2294                 cur.forceBufferUpdate();
2295                 needsUpdate = true;
2296                 break;
2297
2298         case LFUN_OUTLINE_IN:
2299                 outline(OutlineIn, cur);
2300                 cur.forceBufferUpdate();
2301                 needsUpdate = true;
2302                 break;
2303
2304         case LFUN_OUTLINE_OUT:
2305                 outline(OutlineOut, cur);
2306                 cur.forceBufferUpdate();
2307                 needsUpdate = true;
2308                 break;
2309
2310         default:
2311                 LYXERR(Debug::ACTION, "Command " << cmd << " not DISPATCHED by Text");
2312                 cur.undispatched();
2313                 break;
2314         }
2315
2316         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
2317
2318         if (lyxrc.spellcheck_continuously && !needsUpdate) {
2319                 // Check for misspelled text
2320                 // The redraw is useful because of the painting of
2321                 // misspelled markers depends on the cursor position.
2322                 // Trigger a redraw for cursor moves inside misspelled text.
2323                 if (!cur.inTexted()) {
2324                         // move from regular text to math
2325                         needsUpdate = last_misspelled;
2326                 } else if (oldTopSlice != cur.top() || oldBoundary != cur.boundary()) {
2327                         // move inside regular text
2328                         needsUpdate = last_misspelled
2329                                 || cur.paragraph().isMisspelled(cur.pos(), true);
2330                 }
2331         }
2332
2333         // FIXME: The cursor flag is reset two lines below
2334         // so we need to check here if some of the LFUN did touch that.
2335         // for now only Text::erase() and Text::backspace() do that.
2336         // The plan is to verify all the LFUNs and then to remove this
2337         // singleParUpdate boolean altogether.
2338         if (cur.result().screenUpdate() & Update::Force) {
2339                 singleParUpdate = false;
2340                 needsUpdate = true;
2341         }
2342
2343         // FIXME: the following code should go in favor of fine grained
2344         // update flag treatment.
2345         if (singleParUpdate) {
2346                 // Inserting characters does not change par height in general. So, try
2347                 // to update _only_ this paragraph. BufferView will detect if a full
2348                 // metrics update is needed anyway.
2349                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
2350                 return;
2351         }
2352         if (!needsUpdate
2353             && &oldTopSlice.inset() == &cur.inset()
2354             && oldTopSlice.idx() == cur.idx()
2355             && !oldSelection // oldSelection is a backup of cur.selection() at the beginning of the function.
2356             && !cur.selection())
2357                 // FIXME: it would be better if we could just do this
2358                 //
2359                 //if (cur.result().update() != Update::FitCursor)
2360                 //      cur.noScreenUpdate();
2361                 //
2362                 // But some LFUNs do not set Update::FitCursor when needed, so we
2363                 // do it for all. This is not very harmfull as FitCursor will provoke
2364                 // a full redraw only if needed but still, a proper review of all LFUN
2365                 // should be done and this needsUpdate boolean can then be removed.
2366                 cur.screenUpdateFlags(Update::FitCursor);
2367         else
2368                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
2369 }
2370
2371
2372 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
2373                         FuncStatus & flag) const
2374 {
2375         LASSERT(cur.text() == this, /**/);
2376
2377         FontInfo const & fontinfo = cur.real_current_font.fontInfo();
2378         bool enable = true;
2379         bool allow_in_passthru = false;
2380         InsetCode code = NO_CODE;
2381
2382         switch (cmd.action()) {
2383
2384         case LFUN_DEPTH_DECREMENT:
2385                 enable = changeDepthAllowed(cur, DEC_DEPTH);
2386                 break;
2387
2388         case LFUN_DEPTH_INCREMENT:
2389                 enable = changeDepthAllowed(cur, INC_DEPTH);
2390                 break;
2391
2392         case LFUN_APPENDIX:
2393                 // FIXME We really should not allow this to be put, e.g.,
2394                 // in a footnote, or in ERT. But it would make sense in a 
2395                 // branch, so I'm not sure what to do.
2396                 flag.setOnOff(cur.paragraph().params().startOfAppendix());
2397                 break;
2398
2399         case LFUN_DIALOG_SHOW_NEW_INSET:
2400                 if (cmd.argument() == "bibitem")
2401                         code = BIBITEM_CODE;
2402                 else if (cmd.argument() == "bibtex") {
2403                         code = BIBTEX_CODE;
2404                         // not allowed in description items
2405                         enable = !inDescriptionItem(cur);
2406                 }
2407                 else if (cmd.argument() == "box")
2408                         code = BOX_CODE;
2409                 else if (cmd.argument() == "branch")
2410                         code = BRANCH_CODE;
2411                 else if (cmd.argument() == "citation")
2412                         code = CITE_CODE;
2413                 else if (cmd.argument() == "ert")
2414                         code = ERT_CODE;
2415                 else if (cmd.argument() == "external")
2416                         code = EXTERNAL_CODE;
2417                 else if (cmd.argument() == "float")
2418                         code = FLOAT_CODE;
2419                 else if (cmd.argument() == "graphics")
2420                         code = GRAPHICS_CODE;
2421                 else if (cmd.argument() == "href")
2422                         code = HYPERLINK_CODE;
2423                 else if (cmd.argument() == "include")
2424                         code = INCLUDE_CODE;
2425                 else if (cmd.argument() == "index")
2426                         code = INDEX_CODE;
2427                 else if (cmd.argument() == "index_print")
2428                         code = INDEX_PRINT_CODE;
2429                 else if (cmd.argument() == "nomenclature")
2430                         code = NOMENCL_CODE;
2431                 else if (cmd.argument() == "nomencl_print")
2432                         code = NOMENCL_PRINT_CODE;
2433                 else if (cmd.argument() == "label")
2434                         code = LABEL_CODE;
2435                 else if (cmd.argument() == "line")
2436                         code = LINE_CODE;
2437                 else if (cmd.argument() == "note")
2438                         code = NOTE_CODE;
2439                 else if (cmd.argument() == "phantom")
2440                         code = PHANTOM_CODE;
2441                 else if (cmd.argument() == "ref")
2442                         code = REF_CODE;
2443                 else if (cmd.argument() == "space")
2444                         code = SPACE_CODE;
2445                 else if (cmd.argument() == "toc")
2446                         code = TOC_CODE;
2447                 else if (cmd.argument() == "vspace")
2448                         code = VSPACE_CODE;
2449                 else if (cmd.argument() == "wrap")
2450                         code = WRAP_CODE;
2451                 else if (cmd.argument() == "listings")
2452                         code = LISTINGS_CODE;
2453                 break;
2454
2455         case LFUN_ERT_INSERT:
2456                 code = ERT_CODE;
2457                 break;
2458         case LFUN_LISTING_INSERT:
2459                 code = LISTINGS_CODE;
2460                 // not allowed in description items
2461                 enable = !inDescriptionItem(cur);
2462                 break;
2463         case LFUN_FOOTNOTE_INSERT:
2464                 code = FOOT_CODE;
2465                 break;
2466         case LFUN_TABULAR_INSERT:
2467                 code = TABULAR_CODE;
2468                 break;
2469         case LFUN_MARGINALNOTE_INSERT:
2470                 code = MARGIN_CODE;
2471                 break;
2472         case LFUN_FLOAT_INSERT:
2473         case LFUN_FLOAT_WIDE_INSERT:
2474                 // FIXME: If there is a selection, we should check whether there
2475                 // are floats in the selection, but this has performance issues, see
2476                 // LFUN_CHANGE_ACCEPT/REJECT.
2477                 code = FLOAT_CODE;
2478                 if (inDescriptionItem(cur))
2479                         // not allowed in description items
2480                         enable = false;
2481                 else {
2482                         InsetCode const inset_code = cur.inset().lyxCode();
2483
2484                         // algorithm floats cannot be put in another float
2485                         if (to_utf8(cmd.argument()) == "algorithm") {
2486                                 enable = inset_code != WRAP_CODE && inset_code != FLOAT_CODE;
2487                                 break;
2488                         }
2489
2490                         // for figures and tables: only allow in another
2491                         // float or wrap if it is of the same type and
2492                         // not a subfloat already
2493                         if(cur.inset().lyxCode() == code) {
2494                                 InsetFloat const & ins =
2495                                         static_cast<InsetFloat const &>(cur.inset());
2496                                 enable = ins.params().type == to_utf8(cmd.argument())
2497                                         && !ins.params().subfloat;
2498                         } else if(cur.inset().lyxCode() == WRAP_CODE) {
2499                                 InsetWrap const & ins =
2500                                         static_cast<InsetWrap const &>(cur.inset());
2501                                 enable = ins.params().type == to_utf8(cmd.argument());
2502                         }
2503                 }
2504                 break;
2505         case LFUN_WRAP_INSERT:
2506                 code = WRAP_CODE;
2507                 // not allowed in description items
2508                 enable = !inDescriptionItem(cur);
2509                 break;
2510         case LFUN_FLOAT_LIST_INSERT: {
2511                 code = FLOAT_LIST_CODE;
2512                 // not allowed in description items
2513                 enable = !inDescriptionItem(cur);
2514                 if (enable) {
2515                         FloatList const & floats = cur.buffer()->params().documentClass().floats();
2516                         FloatList::const_iterator cit = floats[to_ascii(cmd.argument())];
2517                         // make sure we know about such floats
2518                         if (cit == floats.end() ||
2519                                         // and that we know how to generate a list of them
2520                             (!cit->second.usesFloatPkg() && cit->second.listCommand().empty())) {
2521                                 flag.setUnknown(true);
2522                                 // probably not necessary, but...
2523                                 enable = false;
2524                         }
2525                 }
2526                 break;
2527         }
2528         case LFUN_CAPTION_INSERT: {
2529                 code = CAPTION_CODE;
2530                 bool varia = true;
2531                 if (cur.depth() > 0) {
2532                         if (&cur[cur.depth() - 1].inset()
2533                             && !cur[cur.depth() - 1].inset().allowsCaptionVariation())
2534                                 varia = false;
2535                 }
2536                 string arg = cmd.getArg(0);
2537                 // not allowed in description items,
2538                 // and in specific insets
2539                 enable = !inDescriptionItem(cur)
2540                         && (varia || arg.empty() || arg == "Standard");
2541                 break;
2542         }
2543         case LFUN_NOTE_INSERT:
2544                 code = NOTE_CODE;
2545                 // in commands (sections etc.) and description items,
2546                 // only Notes are allowed
2547                 enable = (cmd.argument().empty() || cmd.getArg(0) == "Note" ||
2548                           (!cur.paragraph().layout().isCommand()
2549                            && !inDescriptionItem(cur)));
2550                 break;
2551         case LFUN_FLEX_INSERT: {
2552                 code = FLEX_CODE;
2553                 string s = cmd.getArg(0);
2554                 InsetLayout il =
2555                         cur.buffer()->params().documentClass().insetLayout(from_utf8(s));
2556                 if (il.lyxtype() != InsetLayout::CHARSTYLE &&
2557                     il.lyxtype() != InsetLayout::CUSTOM &&
2558                     il.lyxtype() != InsetLayout::ELEMENT &&
2559                     il.lyxtype ()!= InsetLayout::STANDARD)
2560                         enable = false;
2561                 break;
2562                 }
2563         case LFUN_BOX_INSERT:
2564                 code = BOX_CODE;
2565                 break;
2566         case LFUN_BRANCH_INSERT:
2567                 code = BRANCH_CODE;
2568                 if (cur.buffer()->masterBuffer()->params().branchlist().empty()
2569                     && cur.buffer()->params().branchlist().empty())
2570                         enable = false;
2571                 break;
2572         case LFUN_IPA_INSERT:
2573                 code = IPA_CODE;
2574                 break;
2575         case LFUN_PHANTOM_INSERT:
2576                 code = PHANTOM_CODE;
2577                 break;
2578         case LFUN_LABEL_INSERT:
2579                 code = LABEL_CODE;
2580                 break;
2581         case LFUN_INFO_INSERT:
2582                 code = INFO_CODE;
2583                 break;
2584         case LFUN_ARGUMENT_INSERT: {
2585                 code = ARG_CODE;
2586                 allow_in_passthru = true;
2587                 string const arg = cmd.getArg(0);
2588                 if (arg.empty()) {
2589                         enable = false;
2590                         break;
2591                 }
2592                 Layout const & lay = cur.paragraph().layout();
2593                 Layout::LaTeXArgMap args = lay.args();
2594                 Layout::LaTeXArgMap::const_iterator const lait =
2595                                 args.find(arg);
2596                 if (lait != args.end()) {
2597                         enable = true;
2598                         pit_type pit = cur.pit();
2599                         pit_type lastpit = cur.pit();
2600                         if (lay.isEnvironment() && !prefixIs(arg, "item:")) {
2601                                 // In a sequence of "merged" environment layouts, we only allow
2602                                 // non-item arguments once.
2603                                 lastpit = cur.lastpit();
2604                                 // get the first paragraph in sequence with this layout
2605                                 depth_type const current_depth = cur.paragraph().params().depth();
2606                                 while (true) {
2607                                         if (pit == 0)
2608                                                 break;
2609                                         Paragraph cpar = pars_[pit - 1];
2610                                         if (cpar.layout() == lay && cpar.params().depth() == current_depth)
2611                                                 --pit;
2612                                         else
2613                                                 break;
2614                                 }
2615                         }
2616                         for (; pit <= lastpit; ++pit) {
2617                                 if (pars_[pit].layout() != lay)
2618                                         break;
2619                                 InsetList::const_iterator it = pars_[pit].insetList().begin();
2620                                 InsetList::const_iterator end = pars_[pit].insetList().end();
2621                                 for (; it != end; ++it) {
2622                                         if (it->inset->lyxCode() == ARG_CODE) {
2623                                                 InsetArgument const * ins =
2624                                                         static_cast<InsetArgument const *>(it->inset);
2625                                                 if (ins->name() == arg) {
2626                                                         // we have this already
2627                                                         enable = false;
2628                                                         break;
2629                                                 }
2630                                         }
2631                                 }
2632                         }
2633                 } else
2634                         enable = false;
2635                 break;
2636         }
2637         case LFUN_INDEX_INSERT:
2638                 code = INDEX_CODE;
2639                 break;
2640         case LFUN_INDEX_PRINT:
2641                 code = INDEX_PRINT_CODE;
2642                 // not allowed in description items
2643                 enable = !inDescriptionItem(cur);
2644                 break;
2645         case LFUN_NOMENCL_INSERT:
2646                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
2647                         enable = false;
2648                         break;
2649                 }
2650                 code = NOMENCL_CODE;
2651                 break;
2652         case LFUN_NOMENCL_PRINT:
2653                 code = NOMENCL_PRINT_CODE;
2654                 // not allowed in description items
2655                 enable = !inDescriptionItem(cur);
2656                 break;
2657         case LFUN_HYPERLINK_INSERT:
2658                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
2659                         enable = false;
2660                         break;
2661                 }
2662                 code = HYPERLINK_CODE;
2663                 break;
2664         case LFUN_IPAMACRO_INSERT: {
2665                 string const arg = cmd.getArg(0);
2666                 if (arg == "deco")
2667                         code = IPADECO_CODE;
2668                 else
2669                         code = IPACHAR_CODE;
2670                 break;
2671         }
2672         case LFUN_QUOTE_INSERT:
2673                 // always allow this, since we will inset a raw quote
2674                 // if an inset is not allowed.
2675                 break;
2676         case LFUN_SPECIALCHAR_INSERT:
2677                 code = SPECIALCHAR_CODE;
2678                 break;
2679         case LFUN_SPACE_INSERT:
2680                 // slight hack: we know this is allowed in math mode
2681                 if (cur.inTexted())
2682                         code = SPACE_CODE;
2683                 break;
2684         case LFUN_PREVIEW_INSERT:
2685                 code = PREVIEW_CODE;
2686                 break;
2687         case LFUN_SCRIPT_INSERT:
2688                 code = SCRIPT_CODE;
2689                 break;
2690
2691         case LFUN_MATH_INSERT:
2692         case LFUN_MATH_AMS_MATRIX:
2693         case LFUN_MATH_MATRIX:
2694         case LFUN_MATH_DELIM:
2695         case LFUN_MATH_BIGDELIM:
2696         case LFUN_MATH_DISPLAY:
2697         case LFUN_MATH_MODE:
2698         case LFUN_MATH_MACRO:
2699         case LFUN_MATH_SUBSCRIPT:
2700         case LFUN_MATH_SUPERSCRIPT:
2701                 code = MATH_HULL_CODE;
2702                 break;
2703
2704         case LFUN_REGEXP_MODE:
2705                 code = MATH_HULL_CODE;
2706                 enable = cur.buffer()->isInternal() && !cur.inRegexped();
2707                 break;
2708
2709         case LFUN_INSET_MODIFY:
2710                 // We need to disable this, because we may get called for a
2711                 // tabular cell via
2712                 // InsetTabular::getStatus() -> InsetText::getStatus()
2713                 // and we don't handle LFUN_INSET_MODIFY.
2714                 enable = false;
2715                 break;
2716
2717         case LFUN_FONT_EMPH:
2718                 flag.setOnOff(fontinfo.emph() == FONT_ON);
2719                 enable = !cur.paragraph().isPassThru();
2720                 break;
2721
2722         case LFUN_FONT_ITAL:
2723                 flag.setOnOff(fontinfo.shape() == ITALIC_SHAPE);
2724                 enable = !cur.paragraph().isPassThru();
2725                 break;
2726
2727         case LFUN_FONT_NOUN:
2728                 flag.setOnOff(fontinfo.noun() == FONT_ON);
2729                 enable = !cur.paragraph().isPassThru();
2730                 break;
2731
2732         case LFUN_FONT_BOLD:
2733         case LFUN_FONT_BOLDSYMBOL:
2734                 flag.setOnOff(fontinfo.series() == BOLD_SERIES);
2735                 enable = !cur.paragraph().isPassThru();
2736                 break;
2737
2738         case LFUN_FONT_SANS:
2739                 flag.setOnOff(fontinfo.family() == SANS_FAMILY);
2740                 enable = !cur.paragraph().isPassThru();
2741                 break;
2742
2743         case LFUN_FONT_ROMAN:
2744                 flag.setOnOff(fontinfo.family() == ROMAN_FAMILY);
2745                 enable = !cur.paragraph().isPassThru();
2746                 break;
2747
2748         case LFUN_FONT_TYPEWRITER:
2749                 flag.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
2750                 enable = !cur.paragraph().isPassThru();
2751                 break;
2752
2753         case LFUN_CUT:
2754         case LFUN_COPY:
2755                 enable = cur.selection();
2756                 break;
2757
2758         case LFUN_PASTE: {
2759                 if (cmd.argument().empty()) {
2760                         if (theClipboard().isInternal())
2761                                 enable = cap::numberOfSelections() > 0;
2762                         else
2763                                 enable = !theClipboard().empty();
2764                         break;
2765                 }
2766
2767                 // we have an argument
2768                 string const arg = to_utf8(cmd.argument());
2769                 if (isStrUnsignedInt(arg)) {
2770                         // it's a number and therefore means the internal stack
2771                         unsigned int n = convert<unsigned int>(arg);
2772                         enable = cap::numberOfSelections() > n;
2773                         break;
2774                 }
2775
2776                 // explicit graphics type?
2777                 Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
2778                 if ((arg == "pdf" && (type = Clipboard::PdfGraphicsType))
2779                           || (arg == "png" && (type = Clipboard::PngGraphicsType))
2780                           || (arg == "jpeg" && (type = Clipboard::JpegGraphicsType))
2781                           || (arg == "linkback" &&  (type = Clipboard::LinkBackGraphicsType))
2782                           || (arg == "emf" &&  (type = Clipboard::EmfGraphicsType))
2783                           || (arg == "wmf" &&  (type = Clipboard::WmfGraphicsType))) {
2784                         enable = theClipboard().hasGraphicsContents(type);
2785                         break;
2786                 }
2787
2788                 // unknown argument
2789                 enable = false;
2790                 break;
2791          }
2792
2793         case LFUN_CLIPBOARD_PASTE:
2794         case LFUN_CLIPBOARD_PASTE_SIMPLE:
2795                 enable = !theClipboard().empty();
2796                 break;
2797
2798         case LFUN_PRIMARY_SELECTION_PASTE:
2799                 enable = cur.selection() || !theSelection().empty();
2800                 break;
2801
2802         case LFUN_SELECTION_PASTE:
2803                 enable = cap::selection();
2804                 break;
2805
2806         case LFUN_PARAGRAPH_MOVE_UP:
2807                 enable = cur.pit() > 0 && !cur.selection();
2808                 break;
2809
2810         case LFUN_PARAGRAPH_MOVE_DOWN:
2811                 enable = cur.pit() < cur.lastpit() && !cur.selection();
2812                 break;
2813
2814         case LFUN_CHANGE_ACCEPT:
2815         case LFUN_CHANGE_REJECT:
2816                 // In principle, these LFUNs should only be enabled if there
2817                 // is a change at the current position/in the current selection.
2818                 // However, without proper optimizations, this will inevitably
2819                 // result in unacceptable performance - just imagine a user who
2820                 // wants to select the complete content of a long document.
2821                 if (!cur.selection())
2822                         enable = cur.paragraph().isChanged(cur.pos());
2823                 else
2824                         // TODO: context-sensitive enabling of LFUN_CHANGE_ACCEPT/REJECT
2825                         // for selections.
2826                         enable = true;
2827                 break;
2828
2829         case LFUN_OUTLINE_UP:
2830         case LFUN_OUTLINE_DOWN:
2831         case LFUN_OUTLINE_IN:
2832         case LFUN_OUTLINE_OUT:
2833                 // FIXME: LyX is not ready for outlining within inset.
2834                 enable = isMainText()
2835                         && cur.buffer()->text().getTocLevel(cur.pit()) != Layout::NOT_IN_TOC;
2836                 break;
2837
2838         case LFUN_NEWLINE_INSERT:
2839                 // LaTeX restrictions (labels or empty par)
2840                 enable = (cur.pos() > cur.paragraph().beginOfBody());
2841                 break;
2842
2843         case LFUN_TAB_INSERT:
2844         case LFUN_TAB_DELETE:
2845                 enable = cur.paragraph().isPassThru();
2846                 break;
2847
2848         case LFUN_SET_GRAPHICS_GROUP: {
2849                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
2850                 if (!ins)
2851                         enable = false;
2852                 else
2853                         flag.setOnOff(to_utf8(cmd.argument()) == ins->getParams().groupId);
2854                 break;
2855         }
2856
2857         case LFUN_NEWPAGE_INSERT:
2858                 // not allowed in description items
2859                 code = NEWPAGE_CODE;
2860                 enable = !inDescriptionItem(cur);
2861                 break;
2862
2863         case LFUN_DATE_INSERT: {
2864                 string const format = cmd.argument().empty()
2865                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
2866                 enable = support::os::is_valid_strftime(format);
2867                 break;
2868         }
2869
2870         case LFUN_LANGUAGE:
2871                 enable = !cur.paragraph().isPassThru();
2872                 flag.setOnOff(cmd.getArg(0) == cur.real_current_font.language()->lang());
2873                 break;
2874
2875         case LFUN_PARAGRAPH_BREAK:
2876                 enable = cur.inset().getLayout().isMultiPar();
2877                 break;
2878         
2879         case LFUN_SPELLING_ADD:
2880         case LFUN_SPELLING_IGNORE:
2881         case LFUN_SPELLING_REMOVE:
2882                 enable = theSpellChecker();
2883                 break;
2884
2885         case LFUN_LAYOUT:
2886                 enable = !cur.inset().forcePlainLayout();
2887                 break;
2888         
2889         case LFUN_ENVIRONMENT_SPLIT: {
2890                 if (cur.paragraph().layout().isEnvironment()
2891                     && cur.buffer()->params().documentClass().hasLayout(from_ascii("Separator"))) {
2892                         enable = true;
2893                         break;
2894                 }
2895                 enable = false;
2896                 break;
2897         }
2898
2899         case LFUN_LAYOUT_PARAGRAPH:
2900         case LFUN_PARAGRAPH_PARAMS:
2901         case LFUN_PARAGRAPH_PARAMS_APPLY:
2902         case LFUN_PARAGRAPH_UPDATE:
2903                 enable = cur.inset().allowParagraphCustomization();
2904                 break;
2905
2906         // FIXME: why are accent lfuns forbidden with pass_thru layouts?
2907         case LFUN_ACCENT_ACUTE:
2908         case LFUN_ACCENT_BREVE:
2909         case LFUN_ACCENT_CARON:
2910         case LFUN_ACCENT_CEDILLA:
2911         case LFUN_ACCENT_CIRCLE:
2912         case LFUN_ACCENT_CIRCUMFLEX:
2913         case LFUN_ACCENT_DOT:
2914         case LFUN_ACCENT_GRAVE:
2915         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2916         case LFUN_ACCENT_MACRON:
2917         case LFUN_ACCENT_OGONEK:
2918         case LFUN_ACCENT_TIE:
2919         case LFUN_ACCENT_TILDE:
2920         case LFUN_ACCENT_UMLAUT:
2921         case LFUN_ACCENT_UNDERBAR:
2922         case LFUN_ACCENT_UNDERDOT:
2923         case LFUN_FONT_DEFAULT:
2924         case LFUN_FONT_FRAK:
2925         case LFUN_FONT_SIZE:
2926         case LFUN_FONT_STATE:
2927         case LFUN_FONT_UNDERLINE:
2928         case LFUN_FONT_STRIKEOUT:
2929         case LFUN_FONT_UULINE:
2930         case LFUN_FONT_UWAVE:
2931         case LFUN_TEXTSTYLE_APPLY:
2932         case LFUN_TEXTSTYLE_UPDATE:
2933                 enable = !cur.paragraph().isPassThru();
2934                 break;
2935
2936         case LFUN_WORD_DELETE_FORWARD:
2937         case LFUN_WORD_DELETE_BACKWARD:
2938         case LFUN_LINE_DELETE:
2939         case LFUN_WORD_FORWARD:
2940         case LFUN_WORD_BACKWARD:
2941         case LFUN_WORD_RIGHT:
2942         case LFUN_WORD_LEFT:
2943         case LFUN_CHAR_FORWARD:
2944         case LFUN_CHAR_FORWARD_SELECT:
2945         case LFUN_CHAR_BACKWARD:
2946         case LFUN_CHAR_BACKWARD_SELECT:
2947         case LFUN_CHAR_LEFT:
2948         case LFUN_CHAR_LEFT_SELECT:
2949         case LFUN_CHAR_RIGHT:
2950         case LFUN_CHAR_RIGHT_SELECT:
2951         case LFUN_UP:
2952         case LFUN_UP_SELECT:
2953         case LFUN_DOWN:
2954         case LFUN_DOWN_SELECT:
2955         case LFUN_PARAGRAPH_UP_SELECT:
2956         case LFUN_PARAGRAPH_DOWN_SELECT:
2957         case LFUN_LINE_BEGIN_SELECT:
2958         case LFUN_LINE_END_SELECT:
2959         case LFUN_WORD_FORWARD_SELECT:
2960         case LFUN_WORD_BACKWARD_SELECT:
2961         case LFUN_WORD_RIGHT_SELECT:
2962         case LFUN_WORD_LEFT_SELECT:
2963         case LFUN_WORD_SELECT:
2964         case LFUN_SECTION_SELECT:
2965         case LFUN_BUFFER_BEGIN:
2966         case LFUN_BUFFER_END:
2967         case LFUN_BUFFER_BEGIN_SELECT:
2968         case LFUN_BUFFER_END_SELECT:
2969         case LFUN_INSET_BEGIN:
2970         case LFUN_INSET_END:
2971         case LFUN_INSET_BEGIN_SELECT:
2972         case LFUN_INSET_END_SELECT:
2973         case LFUN_INSET_SELECT_ALL:
2974         case LFUN_PARAGRAPH_UP:
2975         case LFUN_PARAGRAPH_DOWN:
2976         case LFUN_LINE_BEGIN:
2977         case LFUN_LINE_END:
2978         case LFUN_CHAR_DELETE_FORWARD:
2979         case LFUN_CHAR_DELETE_BACKWARD:
2980         case LFUN_WORD_UPCASE:
2981         case LFUN_WORD_LOWCASE:
2982         case LFUN_WORD_CAPITALIZE:
2983         case LFUN_CHARS_TRANSPOSE:
2984         case LFUN_SERVER_GET_XY:
2985         case LFUN_SERVER_SET_XY:
2986         case LFUN_SERVER_GET_LAYOUT:
2987         case LFUN_SELF_INSERT:
2988         case LFUN_UNICODE_INSERT:
2989         case LFUN_THESAURUS_ENTRY:
2990         case LFUN_ESCAPE:
2991                 // these are handled in our dispatch()
2992                 enable = true;
2993                 break;
2994
2995         case LFUN_INSET_INSERT: {
2996                 string const type = cmd.getArg(0);
2997                 if (type == "toc") {
2998                         code = TOC_CODE;
2999                         // not allowed in description items
3000                         //FIXME: couldn't this be merged in Inset::insetAllowed()?
3001                         enable = !inDescriptionItem(cur);
3002                 } else {
3003                         enable = true;
3004                 }
3005                 break;
3006         }
3007
3008         default:
3009                 return false;
3010         }
3011
3012         if (code != NO_CODE
3013             && (cur.empty() 
3014                 || !cur.inset().insetAllowed(code)
3015                 || (cur.paragraph().layout().pass_thru && !allow_in_passthru)))
3016                 enable = false;
3017
3018         flag.setEnabled(enable);
3019         return true;
3020 }
3021
3022
3023 void Text::pasteString(Cursor & cur, docstring const & clip,
3024                 bool asParagraphs)
3025 {
3026         if (!clip.empty()) {
3027                 cur.recordUndo();
3028                 if (asParagraphs)
3029                         insertStringAsParagraphs(cur, clip, cur.current_font);
3030                 else
3031                         insertStringAsLines(cur, clip, cur.current_font);
3032         }
3033 }
3034
3035
3036 // FIXME: an item inset would make things much easier.
3037 bool Text::inDescriptionItem(Cursor & cur) const
3038 {
3039         Paragraph & par = cur.paragraph();
3040         pos_type const pos = cur.pos();
3041         pos_type const body_pos = par.beginOfBody();
3042
3043         if (par.layout().latextype != LATEX_LIST_ENVIRONMENT
3044             && (par.layout().latextype != LATEX_ITEM_ENVIRONMENT
3045                 || par.layout().margintype != MARGIN_FIRST_DYNAMIC))
3046                 return false;
3047
3048         return (pos < body_pos
3049                 || (pos == body_pos
3050                     && (pos == 0 || par.getChar(pos - 1) != ' ')));
3051 }
3052
3053 } // namespace lyx