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