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