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