]> git.lyx.org Git - lyx.git/blob - src/Text3.cpp
1d3e44d3eb1813171ca8b2caa4bd1c509b65e2b8
[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 const & 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                         cur.setCurrentFont();
1230                         singleParUpdate = false;
1231                 }
1232                 moveCursor(cur, false);
1233                 break;
1234
1235         case LFUN_CHAR_DELETE_BACKWARD:
1236                 if (!cur.selection()) {
1237                         if (bv->getIntl().getTransManager().backspace()) {
1238                                 bool par_boundary = cur.pos() == 0;
1239                                 bool first_par = cur.pit() == 0;
1240                                 // Par boundary, full-screen update
1241                                 if (par_boundary)
1242                                         singleParUpdate = false;
1243                                 else if (cmd.getArg(0) != "force" && cur.confirmDeletion(true)) {
1244                                         cur.resetAnchor();
1245                                         cur.selection(true);
1246                                         cur.posBackward();
1247                                         cur.setSelection();
1248                                         break;
1249                                 }
1250                                 needsUpdate |= backspace(cur);
1251                                 cur.resetAnchor();
1252                                 if (par_boundary && !first_par && cur.pos() > 0
1253                                     && cur.paragraph().isEnvSeparator(cur.pos() - 1)) {
1254                                         needsUpdate |= backspace(cur);
1255                                         cur.resetAnchor();
1256                                 }
1257                         }
1258                 } else {
1259                         DocIterator const dit = cur.selectionBegin();
1260                         cutSelection(cur, false);
1261                         if (cur.buffer()->params().track_changes)
1262                                 // since we're doing backwards deletion,
1263                                 // and the selection is not really cut,
1264                                 // move cursor before selection (#11630)
1265                                 cur.setCursor(dit);
1266                         cur.setCurrentFont();
1267                         singleParUpdate = false;
1268                 }
1269                 break;
1270
1271         case LFUN_PARAGRAPH_BREAK: {
1272                 cap::replaceSelection(cur);
1273                 pit_type pit = cur.pit();
1274                 Paragraph const & par = pars_[pit];
1275                 bool lastpar = (pit == pit_type(pars_.size() - 1));
1276                 Paragraph const & nextpar = lastpar ? par : pars_[pit + 1];
1277                 pit_type prev = pit > 0 ? depthHook(pit, par.getDepth()) : pit;
1278                 if (prev < pit && cur.pos() == par.beginOfBody()
1279                     && par.empty() && !par.isEnvSeparator(cur.pos())
1280                     && !par.layout().keepempty
1281                     && !par.layout().isCommand()
1282                     && pars_[prev].layout() != par.layout()
1283                     && pars_[prev].layout().isEnvironment()
1284                     && !nextpar.isEnvSeparator(nextpar.beginOfBody())) {
1285                         if (par.layout().isEnvironment()
1286                             && pars_[prev].getDepth() == par.getDepth()) {
1287                                 docstring const layout = par.layout().name();
1288                                 DocumentClass const & tc = bv->buffer().params().documentClass();
1289                                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, tc.plainLayout().name()));
1290                                 lyx::dispatch(FuncRequest(LFUN_SEPARATOR_INSERT, "plain"));
1291                                 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK, "inverse"));
1292                                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, layout));
1293                         } else {
1294                                 lyx::dispatch(FuncRequest(LFUN_SEPARATOR_INSERT, "plain"));
1295                                 breakParagraph(cur);
1296                         }
1297                         Font const f(inherit_font, cur.current_font.language());
1298                         pars_[cur.pit() - 1].resetFonts(f);
1299                 } else {
1300                         if (par.isEnvSeparator(cur.pos()) && cmd.getArg(1) != "ignoresep")
1301                                 cur.posForward();
1302                         breakParagraph(cur, cmd.getArg(0) == "inverse");
1303                 }
1304                 cur.resetAnchor();
1305                 // If we have a list and autoinsert item insets,
1306                 // insert them now.
1307                 Layout::LaTeXArgMap args = par.layout().args();
1308                 for (auto const & thearg : args) {
1309                         Layout::latexarg arg = thearg.second;
1310                         if (arg.autoinsert && prefixIs(thearg.first, "item:")) {
1311                                 FuncRequest cmd2(LFUN_ARGUMENT_INSERT, thearg.first);
1312                                 lyx::dispatch(cmd2);
1313                         }
1314                 }
1315                 break;
1316         }
1317
1318         case LFUN_INSET_INSERT: {
1319                 cur.recordUndo();
1320
1321                 // We have to avoid triggering InstantPreview loading
1322                 // before inserting into the document. See bug #5626.
1323                 bool loaded = bv->buffer().isFullyLoaded();
1324                 bv->buffer().setFullyLoaded(false);
1325                 Inset * inset = createInset(&bv->buffer(), cmd);
1326                 bv->buffer().setFullyLoaded(loaded);
1327
1328                 if (inset) {
1329                         // FIXME (Abdel 01/02/2006):
1330                         // What follows would be a partial fix for bug 2154:
1331                         //   http://www.lyx.org/trac/ticket/2154
1332                         // This automatically put the label inset _after_ a
1333                         // numbered section. It should be possible to extend the mechanism
1334                         // to any kind of LateX environement.
1335                         // The correct way to fix that bug would be at LateX generation.
1336                         // I'll let the code here for reference as it could be used for some
1337                         // other feature like "automatic labelling".
1338                         /*
1339                         Paragraph & par = pars_[cur.pit()];
1340                         if (inset->lyxCode() == LABEL_CODE
1341                                 && !par.layout().counter.empty()) {
1342                                 // Go to the end of the paragraph
1343                                 // Warning: Because of Change-Tracking, the last
1344                                 // position is 'size()' and not 'size()-1':
1345                                 cur.pos() = par.size();
1346                                 // Insert a new paragraph
1347                                 FuncRequest fr(LFUN_PARAGRAPH_BREAK);
1348                                 dispatch(cur, fr);
1349                         }
1350                         */
1351                         if (cur.selection())
1352                                 cutSelection(cur, false);
1353                         cur.insert(inset);
1354                         cur.forceBufferUpdate();
1355                         if (inset->editable() && inset->asInsetText())
1356                                 inset->edit(cur, true);
1357                         else
1358                                 cur.posForward();
1359
1360                         // trigger InstantPreview now
1361                         if (inset->lyxCode() == EXTERNAL_CODE) {
1362                                 InsetExternal & ins =
1363                                         static_cast<InsetExternal &>(*inset);
1364                                 ins.updatePreview();
1365                         }
1366                 }
1367
1368                 break;
1369         }
1370
1371         case LFUN_INSET_DISSOLVE: {
1372                 if (dissolveInset(cur)) {
1373                         needsUpdate = true;
1374                         cur.forceBufferUpdate();
1375                 }
1376                 break;
1377         }
1378
1379         case LFUN_GRAPHICS_SET_GROUP: {
1380                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
1381                 if (!ins)
1382                         break;
1383
1384                 cur.recordUndo();
1385
1386                 string id = to_utf8(cmd.argument());
1387                 string grp = graphics::getGroupParams(bv->buffer(), id);
1388                 InsetGraphicsParams tmp, inspar = ins->getParams();
1389
1390                 if (id.empty())
1391                         inspar.groupId = to_utf8(cmd.argument());
1392                 else {
1393                         InsetGraphics::string2params(grp, bv->buffer(), tmp);
1394                         tmp.filename = inspar.filename;
1395                         inspar = tmp;
1396                 }
1397
1398                 ins->setParams(inspar);
1399                 break;
1400         }
1401
1402         case LFUN_SPACE_INSERT:
1403                 if (cur.paragraph().layout().free_spacing)
1404                         insertChar(cur, ' ');
1405                 else {
1406                         doInsertInset(cur, this, cmd, false, false);
1407                         cur.posForward();
1408                 }
1409                 moveCursor(cur, false);
1410                 break;
1411
1412         case LFUN_SPECIALCHAR_INSERT: {
1413                 string const name = to_utf8(cmd.argument());
1414                 if (name == "hyphenation")
1415                         specialChar(cur, InsetSpecialChar::HYPHENATION);
1416                 else if (name == "allowbreak")
1417                         specialChar(cur, InsetSpecialChar::ALLOWBREAK);
1418                 else if (name == "ligature-break")
1419                         specialChar(cur, InsetSpecialChar::LIGATURE_BREAK);
1420                 else if (name == "slash")
1421                         specialChar(cur, InsetSpecialChar::SLASH);
1422                 else if (name == "nobreakdash")
1423                         specialChar(cur, InsetSpecialChar::NOBREAKDASH);
1424                 else if (name == "dots")
1425                         specialChar(cur, InsetSpecialChar::LDOTS);
1426                 else if (name == "end-of-sentence")
1427                         specialChar(cur, InsetSpecialChar::END_OF_SENTENCE);
1428                 else if (name == "menu-separator")
1429                         specialChar(cur, InsetSpecialChar::MENU_SEPARATOR);
1430                 else if (name == "lyx")
1431                         specialChar(cur, InsetSpecialChar::PHRASE_LYX);
1432                 else if (name == "tex")
1433                         specialChar(cur, InsetSpecialChar::PHRASE_TEX);
1434                 else if (name == "latex")
1435                         specialChar(cur, InsetSpecialChar::PHRASE_LATEX);
1436                 else if (name == "latex2e")
1437                         specialChar(cur, InsetSpecialChar::PHRASE_LATEX2E);
1438                 else if (name.empty())
1439                         lyxerr << "LyX function 'specialchar-insert' needs an argument." << endl;
1440                 else
1441                         lyxerr << "Wrong argument for LyX function 'specialchar-insert'." << endl;
1442                 break;
1443         }
1444
1445         case LFUN_IPAMACRO_INSERT: {
1446                 string const arg = cmd.getArg(0);
1447                 if (arg == "deco") {
1448                         // Open the inset, and move the current selection
1449                         // inside it.
1450                         doInsertInset(cur, this, cmd, true, true);
1451                         cur.posForward();
1452                         // Some insets are numbered, others are shown in the outline pane so
1453                         // let's update the labels and the toc backend.
1454                         cur.forceBufferUpdate();
1455                         break;
1456                 }
1457                 if (arg == "tone-falling")
1458                         ipaChar(cur, InsetIPAChar::TONE_FALLING);
1459                 else if (arg == "tone-rising")
1460                         ipaChar(cur, InsetIPAChar::TONE_RISING);
1461                 else if (arg == "tone-high-rising")
1462                         ipaChar(cur, InsetIPAChar::TONE_HIGH_RISING);
1463                 else if (arg == "tone-low-rising")
1464                         ipaChar(cur, InsetIPAChar::TONE_LOW_RISING);
1465                 else if (arg == "tone-high-rising-falling")
1466                         ipaChar(cur, InsetIPAChar::TONE_HIGH_RISING_FALLING);
1467                 else if (arg.empty())
1468                         lyxerr << "LyX function 'ipamacro-insert' needs an argument." << endl;
1469                 else
1470                         lyxerr << "Wrong argument for LyX function 'ipamacro-insert'." << endl;
1471                 break;
1472         }
1473
1474         case LFUN_WORD_UPCASE:
1475                 changeCase(cur, text_uppercase, cmd.getArg(0) == "partial");
1476                 break;
1477
1478         case LFUN_WORD_LOWCASE:
1479                 changeCase(cur, text_lowercase, cmd.getArg(0) == "partial");
1480                 break;
1481
1482         case LFUN_WORD_CAPITALIZE:
1483                 changeCase(cur, text_capitalization, cmd.getArg(0) == "partial");
1484                 break;
1485
1486         case LFUN_CHARS_TRANSPOSE:
1487                 charsTranspose(cur);
1488                 break;
1489
1490         case LFUN_PASTE: {
1491                 cur.message(_("Paste"));
1492                 LASSERT(cur.selBegin().idx() == cur.selEnd().idx(), break);
1493                 cap::replaceSelection(cur);
1494
1495                 // without argument?
1496                 string const arg = to_utf8(cmd.argument());
1497                 if (arg.empty()) {
1498                         bool tryGraphics = true;
1499                         if (theClipboard().isInternal())
1500                                 pasteFromStack(cur, bv->buffer().errorList("Paste"), 0);
1501                         else if (theClipboard().hasTextContents()) {
1502                                 if (pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1503                                                        true, Clipboard::AnyTextType))
1504                                         tryGraphics = false;
1505                         }
1506                         if (tryGraphics && theClipboard().hasGraphicsContents())
1507                                 pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"));
1508                 } else if (isStrUnsignedInt(arg)) {
1509                         // we have a numerical argument
1510                         pasteFromStack(cur, bv->buffer().errorList("Paste"),
1511                                        convert<unsigned int>(arg));
1512                 } else if (arg == "html" || arg == "latex") {
1513                         Clipboard::TextType type = (arg == "html") ?
1514                                 Clipboard::HtmlTextType : Clipboard::LaTeXTextType;
1515                         pasteClipboardText(cur, bv->buffer().errorList("Paste"), true, type);
1516                 } else {
1517                         Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
1518                         if (arg == "pdf")
1519                                 type = Clipboard::PdfGraphicsType;
1520                         else if (arg == "png")
1521                                 type = Clipboard::PngGraphicsType;
1522                         else if (arg == "jpeg")
1523                                 type = Clipboard::JpegGraphicsType;
1524                         else if (arg == "linkback")
1525                                 type = Clipboard::LinkBackGraphicsType;
1526                         else if (arg == "emf")
1527                                 type = Clipboard::EmfGraphicsType;
1528                         else if (arg == "wmf")
1529                                 type = Clipboard::WmfGraphicsType;
1530                         else
1531                                 // we also check in getStatus()
1532                                 LYXERR0("Unrecognized graphics type: " << arg);
1533
1534                         pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"), type);
1535                 }
1536
1537                 bv->buffer().errors("Paste");
1538                 bv->buffer().updatePreviews(); // bug 11619
1539                 cur.clearSelection(); // bug 393
1540                 cur.finishUndo();
1541                 break;
1542         }
1543
1544         case LFUN_CUT:
1545                 cutSelection(cur, true);
1546                 cur.message(_("Cut"));
1547                 break;
1548
1549         case LFUN_COPY:
1550                 copySelection(cur);
1551                 cur.message(_("Copy"));
1552                 break;
1553
1554         case LFUN_SERVER_GET_XY:
1555                 cur.message(from_utf8(
1556                         convert<string>(tm->cursorX(cur.top(), cur.boundary()))
1557                         + ' ' + convert<string>(tm->cursorY(cur.top(), cur.boundary()))));
1558                 break;
1559
1560         case LFUN_SERVER_SET_XY: {
1561                 int x = 0;
1562                 int y = 0;
1563                 istringstream is(to_utf8(cmd.argument()));
1564                 is >> x >> y;
1565                 if (!is)
1566                         lyxerr << "SETXY: Could not parse coordinates in '"
1567                                << to_utf8(cmd.argument()) << endl;
1568                 else
1569                         tm->setCursorFromCoordinates(cur, x, y);
1570                 break;
1571         }
1572
1573         case LFUN_SERVER_GET_LAYOUT:
1574                 cur.message(cur.paragraph().layout().name());
1575                 break;
1576
1577         case LFUN_LAYOUT:
1578         case LFUN_LAYOUT_TOGGLE: {
1579                 bool const ignoreautonests = cmd.getArg(1) == "ignoreautonests";
1580                 docstring req_layout = ignoreautonests ? from_utf8(cmd.getArg(0)) : cmd.argument();
1581                 LYXERR(Debug::INFO, "LFUN_LAYOUT: (arg) " << to_utf8(req_layout));
1582
1583                 docstring layout = resolveLayout(req_layout, cur);
1584                 if (layout.empty()) {
1585                         cur.errorMessage(from_utf8(N_("Layout ")) + req_layout +
1586                                 from_utf8(N_(" not known")));
1587                         break;
1588                 }
1589
1590                 docstring const old_layout = cur.paragraph().layout().name();
1591                 bool change_layout = !isAlreadyLayout(layout, cur);
1592
1593                 if (cmd.action() == LFUN_LAYOUT_TOGGLE && !change_layout) {
1594                         change_layout = true;
1595                         layout = resolveLayout(docstring(), cur);
1596                 }
1597
1598                 if (change_layout) {
1599                         setLayout(cur, layout);
1600                         if (cur.pit() > 0 && !ignoreautonests) {
1601                                 pit_type prev_pit = cur.pit() - 1;
1602                                 depth_type const cur_depth = pars_[cur.pit()].getDepth();
1603                                 // Scan for the previous par on same nesting level
1604                                 while (prev_pit > 0 && pars_[prev_pit].getDepth() > cur_depth)
1605                                         --prev_pit;
1606                                 set<docstring> const & autonests =
1607                                                 pars_[prev_pit].layout().autonests();
1608                                 set<docstring> const & autonested =
1609                                                 pars_[cur.pit()].layout().isAutonestedBy();
1610                                 if (autonests.find(layout) != autonests.end()
1611                                                 || autonested.find(old_layout) != autonested.end())
1612                                         lyx::dispatch(FuncRequest(LFUN_DEPTH_INCREMENT));
1613                         }
1614                 }
1615
1616                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1617                 bool inautoarg = false;
1618                 for (auto const & la_pair : tclass[layout].args()) {
1619                         Layout::latexarg const & arg = la_pair.second;
1620                         if (arg.autoinsert) {
1621                                 // If we had already inserted an arg automatically,
1622                                 // leave this now in order to insert the next one.
1623                                 if (inautoarg) {
1624                                         cur.leaveInset(cur.inset());
1625                                         cur.posForward();
1626                                 }
1627                                 FuncRequest const cmd2(LFUN_ARGUMENT_INSERT, la_pair.first);
1628                                 lyx::dispatch(cmd2);
1629                                 inautoarg = true;
1630                         }
1631                 }
1632
1633                 break;
1634         }
1635
1636         case LFUN_ENVIRONMENT_SPLIT: {
1637                 bool const outer = cmd.argument() == "outer";
1638                 bool const previous = cmd.argument() == "previous";
1639                 bool const before = cmd.argument() == "before";
1640                 bool const normal = cmd.argument().empty();
1641                 Paragraph const & para = cur.paragraph();
1642                 docstring layout;
1643                 if (para.layout().isEnvironment())
1644                         layout = para.layout().name();
1645                 depth_type split_depth = cur.paragraph().params().depth();
1646                 depth_type nextpar_depth = 0;
1647                 if (outer || previous) {
1648                         // check if we have an environment in our scope
1649                         pit_type pit = cur.pit();
1650                         Paragraph cpar = pars_[pit];
1651                         while (true) {
1652                                 if (pit == 0)
1653                                         break;
1654                                 --pit;
1655                                 cpar = pars_[pit];
1656                                 if (layout.empty() && previous
1657                                     && cpar.layout().isEnvironment()
1658                                     && cpar.params().depth() <= split_depth)
1659                                         layout = cpar.layout().name();
1660                                 if (cpar.params().depth() < split_depth
1661                                     && cpar.layout().isEnvironment()) {
1662                                                 if (!previous)
1663                                                         layout = cpar.layout().name();
1664                                                 split_depth = cpar.params().depth();
1665                                 }
1666                                 if (cpar.params().depth() == 0)
1667                                         break;
1668                         }
1669                 }
1670                 if ((outer || normal) && cur.pit() < cur.lastpit()) {
1671                         // save nesting of following paragraph
1672                         Paragraph cpar = pars_[cur.pit() + 1];
1673                         nextpar_depth = cpar.params().depth();
1674                 }
1675                 if (before)
1676                         cur.top().setPitPos(cur.pit(), 0);
1677                 if (before || cur.pos() > 0)
1678                         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK));
1679                 else if (previous && cur.nextInset() && cur.nextInset()->lyxCode() == SEPARATOR_CODE)
1680                         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK, "inverse ignoresep"));
1681                 if (outer) {
1682                         while (cur.paragraph().params().depth() > split_depth)
1683                                 lyx::dispatch(FuncRequest(LFUN_DEPTH_DECREMENT));
1684                 }
1685                 DocumentClass const & tc = bv->buffer().params().documentClass();
1686                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, from_ascii("\"") + tc.plainLayout().name()
1687                                           + from_ascii("\" ignoreautonests")));
1688                 // FIXME: Bibitem mess!
1689                 if (cur.prevInset() && cur.prevInset()->lyxCode() == BIBITEM_CODE)
1690                         lyx::dispatch(FuncRequest(LFUN_CHAR_DELETE_BACKWARD));
1691                 lyx::dispatch(FuncRequest(LFUN_SEPARATOR_INSERT, "plain"));
1692                 if (before) {
1693                         cur.backwardPos();
1694                         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK, "inverse ignoresep"));
1695                         while (cur.paragraph().params().depth() < split_depth)
1696                                 lyx::dispatch(FuncRequest(LFUN_DEPTH_INCREMENT));
1697                 }
1698                 else
1699                         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK, "inverse"));
1700                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, layout));
1701                 if ((outer || normal) && nextpar_depth > 0) {
1702                         // restore nesting of following paragraph
1703                         DocIterator scur = cur;
1704                         depth_type const max_depth = cur.paragraph().params().depth() + 1;
1705                         cur.forwardPar();
1706                         while (cur.paragraph().params().depth() < min(nextpar_depth, max_depth)) {
1707                                 depth_type const olddepth = cur.paragraph().params().depth();
1708                                 lyx::dispatch(FuncRequest(LFUN_DEPTH_INCREMENT));
1709                                 if (olddepth == cur.paragraph().params().depth())
1710                                         // leave loop if no incrementation happens
1711                                         break;
1712                         }
1713                         cur.setCursor(scur);
1714                 }
1715
1716                 break;
1717         }
1718
1719         case LFUN_CLIPBOARD_PASTE:
1720                 cap::replaceSelection(cur);
1721                 pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1722                                cmd.argument() == "paragraph");
1723                 bv->buffer().errors("Paste");
1724                 break;
1725
1726         case LFUN_CLIPBOARD_PASTE_SIMPLE:
1727                 cap::replaceSelection(cur);
1728                 pasteSimpleText(cur, cmd.argument() == "paragraph");
1729                 break;
1730
1731         case LFUN_PRIMARY_SELECTION_PASTE:
1732                 cap::replaceSelection(cur);
1733                 pasteString(cur, theSelection().get(),
1734                             cmd.argument() == "paragraph");
1735                 break;
1736
1737         case LFUN_SELECTION_PASTE:
1738                 // Copy the selection buffer to the clipboard stack,
1739                 // because we want it to appear in the "Edit->Paste
1740                 // recent" menu.
1741                 cap::replaceSelection(cur);
1742                 cap::copySelectionToStack();
1743                 cap::pasteSelection(bv->cursor(), bv->buffer().errorList("Paste"));
1744                 bv->buffer().errors("Paste");
1745                 break;
1746
1747         case LFUN_QUOTE_INSERT: {
1748                 cap::replaceSelection(cur);
1749                 cur.recordUndo();
1750
1751                 Paragraph const & par = cur.paragraph();
1752                 pos_type pos = cur.pos();
1753                 // Ignore deleted text before cursor
1754                 while (pos > 0 && par.isDeleted(pos - 1))
1755                         --pos;
1756
1757                 bool const inner = (cmd.getArg(0) == "single" || cmd.getArg(0) == "inner");
1758
1759                 // Guess quote side.
1760                 // A space triggers an opening quote. This is passed if the preceding
1761                 // char/inset is a space or at paragraph start.
1762                 char_type c = ' ';
1763                 if (pos > 0 && !par.isSpace(pos - 1)) {
1764                         if (cur.prevInset() && cur.prevInset()->lyxCode() == QUOTE_CODE) {
1765                                 // If an opening double quotation mark precedes, and this
1766                                 // is a single quote, make it opening as well
1767                                 InsetQuotes & ins =
1768                                         static_cast<InsetQuotes &>(*cur.prevInset());
1769                                 string const type = ins.getType();
1770                                 if (!suffixIs(type, "ld") || !inner)
1771                                         c = par.getChar(pos - 1);
1772                         }
1773                         else if (!cur.prevInset()
1774                             || (cur.prevInset() && cur.prevInset()->isChar()))
1775                                 // If a char precedes, pass that and let InsetQuote decide
1776                                 c = par.getChar(pos - 1);
1777                         else {
1778                                 while (pos > 0) {
1779                                         if (par.getInset(pos - 1)
1780                                             && !par.getInset(pos - 1)->isPartOfTextSequence()) {
1781                                                 // skip "invisible" insets
1782                                                 --pos;
1783                                                 continue;
1784                                         }
1785                                         c = par.getChar(pos - 1);
1786                                         break;
1787                                 }
1788                         }
1789                 }
1790                 InsetQuotesParams::QuoteLevel const quote_level = inner
1791                                 ? InsetQuotesParams::SecondaryQuotes : InsetQuotesParams::PrimaryQuotes;
1792                 cur.insert(new InsetQuotes(cur.buffer(), c, quote_level, cmd.getArg(1), cmd.getArg(2)));
1793                 cur.buffer()->updateBuffer();
1794                 cur.posForward();
1795                 break;
1796         }
1797
1798         case LFUN_MOUSE_TRIPLE:
1799                 if (cmd.button() == mouse_button::button1) {
1800                         if (cur.pos() > 0)
1801                                 setCursor(cur, cur.pit(), 0);
1802                         bv->cursor() = cur;
1803                         cur.resetAnchor();
1804                         if (cur.pos() < cur.lastpos())
1805                                 setCursor(cur, cur.pit(), cur.lastpos());
1806                         cur.setSelection();
1807                         bv->cursor() = cur;
1808                 }
1809                 break;
1810
1811         case LFUN_MOUSE_DOUBLE:
1812                 if (cmd.button() == mouse_button::button1) {
1813                         selectWord(cur, WHOLE_WORD);
1814                         bv->cursor() = cur;
1815                 }
1816                 break;
1817
1818         // Single-click on work area
1819         case LFUN_MOUSE_PRESS: {
1820                 // We are not marking a selection with the keyboard in any case.
1821                 Cursor & bvcur = cur.bv().cursor();
1822                 bvcur.setMark(false);
1823                 switch (cmd.button()) {
1824                 case mouse_button::button1:
1825                         if (!bvcur.selection())
1826                                 // Set the cursor
1827                                 bvcur.resetAnchor();
1828                         if (!bv->mouseSetCursor(cur, cmd.modifier() == ShiftModifier))
1829                                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1830                         if (bvcur.wordSelection())
1831                                 selectWord(bvcur, WHOLE_WORD);
1832                         break;
1833
1834                 case mouse_button::button2:
1835                         if (lyxrc.mouse_middlebutton_paste) {
1836                                 // Middle mouse pasting.
1837                                 bv->mouseSetCursor(cur);
1838                                 lyx::dispatch(
1839                                         FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1840                                                     "selection-paste ; primary-selection-paste paragraph"));
1841                         }
1842                         cur.noScreenUpdate();
1843                         break;
1844
1845                 case mouse_button::button3: {
1846                         // Don't do anything if we right-click a
1847                         // selection, a context menu will popup.
1848                         if (bvcur.selection() && cur >= bvcur.selectionBegin()
1849                             && cur < bvcur.selectionEnd()) {
1850                                 cur.noScreenUpdate();
1851                                 return;
1852                         }
1853                         if (!bv->mouseSetCursor(cur, false))
1854                                 cur.screenUpdateFlags(Update::FitCursor);
1855                         break;
1856                 }
1857
1858                 default:
1859                         break;
1860                 } // switch (cmd.button())
1861                 break;
1862         }
1863         case LFUN_MOUSE_MOTION: {
1864                 // Mouse motion with right or middle mouse do nothing for now.
1865                 if (cmd.button() != mouse_button::button1) {
1866                         cur.noScreenUpdate();
1867                         return;
1868                 }
1869                 // ignore motions deeper nested than the real anchor
1870                 Cursor & bvcur = cur.bv().cursor();
1871                 if (!bvcur.realAnchor().hasPart(cur)) {
1872                         cur.undispatched();
1873                         break;
1874                 }
1875                 CursorSlice old = bvcur.top();
1876
1877                 int const wh = bv->workHeight();
1878                 int const y = max(0, min(wh - 1, cmd.y()));
1879
1880                 tm->setCursorFromCoordinates(cur, cmd.x(), y);
1881                 cur.setTargetX(cmd.x());
1882                 // Don't allow selecting a separator inset
1883                 if (cur.pos() && cur.paragraph().isEnvSeparator(cur.pos() - 1))
1884                         cur.posBackward();
1885                 if (cmd.y() >= wh)
1886                         lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1887                 else if (cmd.y() < 0)
1888                         lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1889                 // This is to allow jumping over large insets
1890                 if (cur.top() == old) {
1891                         if (cmd.y() >= wh)
1892                                 lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1893                         else if (cmd.y() < 0)
1894                                 lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1895                 }
1896                 // We continue with our existing selection or start a new one, so don't
1897                 // reset the anchor.
1898                 bvcur.setCursor(cur);
1899                 bvcur.selection(true);
1900                 bvcur.setCurrentFont();
1901                 if (cur.top() == old) {
1902                         // We didn't move one iota, so no need to update the screen.
1903                         cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1904                         //cur.noScreenUpdate();
1905                         return;
1906                 }
1907                 break;
1908         }
1909
1910         case LFUN_MOUSE_RELEASE:
1911                 switch (cmd.button()) {
1912                 case mouse_button::button1:
1913                         // Cursor was set at LFUN_MOUSE_PRESS or LFUN_MOUSE_MOTION time.
1914                         // If there is a new selection, update persistent selection;
1915                         // otherwise, single click does not clear persistent selection
1916                         // buffer.
1917                         if (cur.selection()) {
1918                                 // Finish selection. If double click,
1919                                 // cur is moved to the end of word by
1920                                 // selectWord but bvcur is current
1921                                 // mouse position.
1922                                 cur.bv().cursor().setSelection();
1923                                 // We might have removed an empty but drawn selection
1924                                 // (probably a margin)
1925                                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1926                         } else
1927                                 cur.noScreenUpdate();
1928                         // FIXME: We could try to handle drag and drop of selection here.
1929                         return;
1930
1931                 case mouse_button::button2:
1932                         // Middle mouse pasting is handled at mouse press time,
1933                         // see LFUN_MOUSE_PRESS.
1934                         cur.noScreenUpdate();
1935                         return;
1936
1937                 case mouse_button::button3:
1938                         // Cursor was set at LFUN_MOUSE_PRESS time.
1939                         // FIXME: If there is a selection we could try to handle a special
1940                         // drag & drop context menu.
1941                         cur.noScreenUpdate();
1942                         return;
1943
1944                 case mouse_button::none:
1945                 case mouse_button::button4:
1946                 case mouse_button::button5:
1947                         break;
1948                 } // switch (cmd.button())
1949
1950                 break;
1951
1952         case LFUN_SELF_INSERT: {
1953                 if (cmd.argument().empty())
1954                         break;
1955
1956                 // Automatically delete the currently selected
1957                 // text and replace it with what is being
1958                 // typed in now. Depends on lyxrc settings
1959                 // "auto_region_delete", which defaults to
1960                 // true (on).
1961
1962                 if (lyxrc.auto_region_delete && cur.selection()) {
1963                         cutSelection(cur, false);
1964                         cur.setCurrentFont();
1965                 }
1966                 cur.clearSelection();
1967
1968                 for (char_type c : cmd.argument())
1969                         bv->translateAndInsert(c, this, cur);
1970
1971                 cur.resetAnchor();
1972                 moveCursor(cur, false);
1973                 cur.markNewWordPosition();
1974                 bv->bookmarkEditPosition();
1975                 break;
1976         }
1977
1978         case LFUN_HREF_INSERT: {
1979                 docstring content = cmd.argument();
1980                 if (content.empty() && cur.selection())
1981                         content = cur.selectionAsString(false);
1982
1983                 InsetCommandParams p(HYPERLINK_CODE);
1984                 if (!content.empty()){
1985                         // if it looks like a link, we'll put it as target,
1986                         // otherwise as name (bug #8792).
1987
1988                         // We can't do:
1989                         //   regex_match(to_utf8(content), matches, link_re)
1990                         // because smatch stores pointers to the substrings rather
1991                         // than making copies of them. And those pointers become
1992                         // invalid after regex_match returns, since it is then
1993                         // being given a temporary object. (Thanks to Georg for
1994                         // figuring that out.)
1995                         regex const link_re("^([a-z]+):.*");
1996                         smatch matches;
1997                         string const c = to_utf8(lowercase(content));
1998
1999                         if (c.substr(0,7) == "mailto:") {
2000                                 p["target"] = content;
2001                                 p["type"] = from_ascii("mailto:");
2002                         } else if (regex_match(c, matches, link_re)) {
2003                                 p["target"] = content;
2004                                 string protocol = matches.str(1);
2005                                 if (protocol == "file")
2006                                         p["type"] = from_ascii("file:");
2007                         } else
2008                                 p["name"] = content;
2009                 }
2010                 string const data = InsetCommand::params2string(p);
2011
2012                 // we need to have a target. if we already have one, then
2013                 // that gets used at the default for the name, too, which
2014                 // is probably what is wanted.
2015                 if (p["target"].empty()) {
2016                         bv->showDialog("href", data);
2017                 } else {
2018                         FuncRequest fr(LFUN_INSET_INSERT, data);
2019                         dispatch(cur, fr);
2020                 }
2021                 break;
2022         }
2023
2024         case LFUN_LABEL_INSERT: {
2025                 InsetCommandParams p(LABEL_CODE);
2026                 // Try to generate a valid label
2027                 p["name"] = (cmd.argument().empty()) ?
2028                         cur.getPossibleLabel() :
2029                         cmd.argument();
2030                 string const data = InsetCommand::params2string(p);
2031
2032                 if (cmd.argument().empty()) {
2033                         bv->showDialog("label", data);
2034                 } else {
2035                         FuncRequest fr(LFUN_INSET_INSERT, data);
2036                         dispatch(cur, fr);
2037                 }
2038                 break;
2039         }
2040
2041         case LFUN_INFO_INSERT: {
2042                 if (cmd.argument().empty()) {
2043                         bv->showDialog("info", cur.current_font.language()->lang());
2044                 } else {
2045                         Inset * inset;
2046                         inset = createInset(cur.buffer(), cmd);
2047                         if (!inset)
2048                                 break;
2049                         cur.recordUndo();
2050                         insertInset(cur, inset);
2051                         cur.forceBufferUpdate();
2052                         cur.posForward();
2053                 }
2054                 break;
2055         }
2056         case LFUN_CAPTION_INSERT:
2057         case LFUN_FOOTNOTE_INSERT:
2058         case LFUN_NOTE_INSERT:
2059         case LFUN_BOX_INSERT:
2060         case LFUN_BRANCH_INSERT:
2061         case LFUN_PHANTOM_INSERT:
2062         case LFUN_ERT_INSERT:
2063         case LFUN_LISTING_INSERT:
2064         case LFUN_MARGINALNOTE_INSERT:
2065         case LFUN_ARGUMENT_INSERT:
2066         case LFUN_INDEX_INSERT:
2067         case LFUN_PREVIEW_INSERT:
2068         case LFUN_SCRIPT_INSERT:
2069         case LFUN_IPA_INSERT:
2070                 // Open the inset, and move the current selection
2071                 // inside it.
2072                 doInsertInset(cur, this, cmd, true, true);
2073                 cur.posForward();
2074                 if (act == LFUN_SCRIPT_INSERT) {
2075                         /* Script insets change the font style in metrics(), and
2076                          * this is used to compute the height of the caret
2077                          * (because the font is stored in TextMetrics::font_).
2078                          * When we insert, we have to make sure that metrics are
2079                          * computed so that the caret height is wrong. Arguably,
2080                          * this is hackish.*/
2081                         bv->processUpdateFlags(Update::SinglePar);
2082                 }
2083                 cur.setCurrentFont();
2084                 // Some insets are numbered, others are shown in the outline pane so
2085                 // let's update the labels and the toc backend.
2086                 cur.forceBufferUpdate();
2087                 break;
2088
2089         case LFUN_FLEX_INSERT: {
2090                 // Open the inset, and move the current selection
2091                 // inside it.
2092                 bool const sel = cur.selection();
2093                 doInsertInset(cur, this, cmd, true, true);
2094                 // Insert auto-insert arguments
2095                 bool autoargs = false, inautoarg = false;
2096                 Layout::LaTeXArgMap args = cur.inset().getLayout().args();
2097                 for (auto const & argt : args) {
2098                         Layout::latexarg arg = argt.second;
2099                         if (!inautoarg && arg.insertonnewline && cur.pos() > 0) {
2100                                 FuncRequest cmd2(LFUN_PARAGRAPH_BREAK);
2101                                 lyx::dispatch(cmd2);
2102                         }
2103                         if (arg.autoinsert) {
2104                                 // The cursor might have been invalidated by the replaceSelection.
2105                                 cur.buffer()->changed(true);
2106                                 // If we had already inserted an arg automatically,
2107                                 // leave this now in order to insert the next one.
2108                                 if (inautoarg) {
2109                                         cur.leaveInset(cur.inset());
2110                                         cur.posForward();
2111                                         if (arg.insertonnewline && cur.pos() > 0) {
2112                                                 FuncRequest cmd2(LFUN_PARAGRAPH_BREAK);
2113                                                 lyx::dispatch(cmd2);
2114                                         }
2115                                 }
2116                                 FuncRequest cmd2(LFUN_ARGUMENT_INSERT, argt.first);
2117                                 lyx::dispatch(cmd2);
2118                                 autoargs = true;
2119                                 inautoarg = true;
2120                         }
2121                 }
2122                 if (!autoargs) {
2123                         if (sel)
2124                                 cur.leaveInset(cur.inset());
2125                         cur.posForward();
2126                 }
2127                 // Some insets are numbered, others are shown in the outline pane so
2128                 // let's update the labels and the toc backend.
2129                 cur.forceBufferUpdate();
2130                 break;
2131         }
2132
2133         case LFUN_TABULAR_INSERT: {
2134                 // if there were no arguments, just open the dialog
2135                 if (cmd.argument().empty()) {
2136                         bv->showDialog("tabularcreate");
2137                         break;
2138                 } else if (cur.buffer()->masterParams().tablestyle != "default"
2139                            || bv->buffer().params().documentClass().tablestyle() != "default") {
2140                         string tabstyle = cur.buffer()->masterParams().tablestyle;
2141                         if (tabstyle == "default")
2142                                 tabstyle = bv->buffer().params().documentClass().tablestyle();
2143                         if (!libFileSearch("tabletemplates", tabstyle + ".lyx").empty()) {
2144                                 FuncRequest fr(LFUN_TABULAR_STYLE_INSERT,
2145                                                tabstyle + " " + to_ascii(cmd.argument()));
2146                                 lyx::dispatch(fr);
2147                                 break;
2148                         } else
2149                                 // Unknown style. Report and fall back to default.
2150                                 cur.errorMessage(from_utf8(N_("Table Style ")) + from_utf8(tabstyle) +
2151                                                      from_utf8(N_(" not known")));
2152                         
2153                 }
2154                 if (doInsertInset(cur, this, cmd, false, true))
2155                         cur.posForward();
2156                 break;
2157         }
2158
2159         case LFUN_TABULAR_STYLE_INSERT: {
2160                 string const style = cmd.getArg(0);
2161                 string const rows = cmd.getArg(1);
2162                 string const cols = cmd.getArg(2);
2163                 if (cols.empty() || !isStrInt(cols)
2164                     || rows.empty() || !isStrInt(rows))
2165                         break;
2166                 int const r = convert<int>(rows);
2167                 int const c = convert<int>(cols);
2168                         
2169                 string suffix;
2170                 if (r == 1)
2171                         suffix = "_1x1";
2172                 else if (r == 2)
2173                         suffix = "_1x2";
2174                 FileName const tabstyle = libFileSearch("tabletemplates",
2175                                                         style + suffix + ".lyx", "lyx");
2176                 if (tabstyle.empty())
2177                             break;
2178                 UndoGroupHelper ugh(cur.buffer());
2179                 cur.recordUndo();
2180                 FuncRequest cmd2(LFUN_FILE_INSERT, tabstyle.absFileName() + " ignorelang");
2181                 lyx::dispatch(cmd2);
2182                 // go into table
2183                 cur.backwardPos();
2184                 if (r > 2) {
2185                         // move one cell up to middle cell
2186                         cur.up();
2187                         // add the missing rows
2188                         int const addrows = r - 3;
2189                         for (int i = 0 ; i < addrows ; ++i) {
2190                                 FuncRequest fr(LFUN_TABULAR_FEATURE, "append-row");
2191                                 lyx::dispatch(fr);
2192                         }
2193                 }
2194                 // add the missing columns
2195                 int const addcols = c - 1;
2196                 for (int i = 0 ; i < addcols ; ++i) {
2197                         FuncRequest fr(LFUN_TABULAR_FEATURE, "append-column");
2198                         lyx::dispatch(fr);
2199                 }
2200                 if (r > 1)
2201                         // go to first cell
2202                         cur.up();
2203                 break;
2204         }
2205
2206         case LFUN_FLOAT_INSERT:
2207         case LFUN_FLOAT_WIDE_INSERT:
2208         case LFUN_WRAP_INSERT: {
2209                 // will some content be moved into the inset?
2210                 bool const content = cur.selection();
2211                 // does the content consist of multiple paragraphs?
2212                 bool const singlepar = (cur.selBegin().pit() == cur.selEnd().pit());
2213
2214                 doInsertInset(cur, this, cmd, true, true);
2215                 cur.posForward();
2216
2217                 // If some single-par content is moved into the inset,
2218                 // doInsertInset puts the cursor outside the inset.
2219                 // To insert the caption we put it back into the inset.
2220                 // FIXME cleanup doInsertInset to avoid such dances!
2221                 if (content && singlepar)
2222                         cur.backwardPos();
2223
2224                 ParagraphList & pars = cur.text()->paragraphs();
2225
2226                 DocumentClass const & tclass = bv->buffer().params().documentClass();
2227
2228                 // add a separate paragraph for the caption inset
2229                 pars.push_back(Paragraph());
2230                 pars.back().setInsetOwner(&cur.text()->inset());
2231                 pars.back().setPlainOrDefaultLayout(tclass);
2232                 int cap_pit = pars.size() - 1;
2233
2234                 // if an empty inset was created, we create an additional empty
2235                 // paragraph at the bottom so that the user can choose where to put
2236                 // the graphics (or table).
2237                 if (!content) {
2238                         pars.push_back(Paragraph());
2239                         pars.back().setInsetOwner(&cur.text()->inset());
2240                         pars.back().setPlainOrDefaultLayout(tclass);
2241                 }
2242
2243                 // reposition the cursor to the caption
2244                 cur.pit() = cap_pit;
2245                 cur.pos() = 0;
2246                 // FIXME: This Text/Cursor dispatch handling is a mess!
2247                 // We cannot use Cursor::dispatch here it needs access to up to
2248                 // date metrics.
2249                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
2250                 doInsertInset(cur, cur.text(), cmd_caption, true, false);
2251                 cur.forceBufferUpdate();
2252                 cur.screenUpdateFlags(Update::Force);
2253                 // FIXME: When leaving the Float (or Wrap) inset we should
2254                 // delete any empty paragraph left above or below the
2255                 // caption.
2256                 break;
2257         }
2258
2259         case LFUN_NOMENCL_INSERT: {
2260                 InsetCommandParams p(NOMENCL_CODE);
2261                 if (cmd.argument().empty()) {
2262                         p["symbol"] = 
2263                                 bv->cursor().innerText()->getStringForDialog(bv->cursor());
2264                         cur.clearSelection();
2265                 } else
2266                         p["symbol"] = cmd.argument();
2267                 string const data = InsetCommand::params2string(p);
2268                 bv->showDialog("nomenclature", data);
2269                 break;
2270         }
2271
2272         case LFUN_INDEX_PRINT: {
2273                 InsetCommandParams p(INDEX_PRINT_CODE);
2274                 if (cmd.argument().empty())
2275                         p["type"] = from_ascii("idx");
2276                 else
2277                         p["type"] = cmd.argument();
2278                 string const data = InsetCommand::params2string(p);
2279                 FuncRequest fr(LFUN_INSET_INSERT, data);
2280                 dispatch(cur, fr);
2281                 break;
2282         }
2283
2284         case LFUN_NOMENCL_PRINT:
2285         case LFUN_NEWPAGE_INSERT:
2286                 // do nothing fancy
2287                 doInsertInset(cur, this, cmd, false, false);
2288                 cur.posForward();
2289                 break;
2290
2291         case LFUN_SEPARATOR_INSERT: {
2292                 doInsertInset(cur, this, cmd, false, false);
2293                 cur.posForward();
2294                 // remove a following space
2295                 Paragraph & par = cur.paragraph();
2296                 if (cur.pos() != cur.lastpos() && par.isLineSeparator(cur.pos()))
2297                     par.eraseChar(cur.pos(), cur.buffer()->params().track_changes);
2298                 break;
2299         }
2300
2301         case LFUN_DEPTH_DECREMENT:
2302                 changeDepth(cur, DEC_DEPTH);
2303                 break;
2304
2305         case LFUN_DEPTH_INCREMENT:
2306                 changeDepth(cur, INC_DEPTH);
2307                 break;
2308
2309         case LFUN_REGEXP_MODE:
2310                 regexpDispatch(cur, cmd);
2311                 break;
2312
2313         case LFUN_MATH_MODE: {
2314                 if (cmd.argument() == "on" || cmd.argument() == "") {
2315                         // don't pass "on" as argument
2316                         // (it would appear literally in the first cell)
2317                         docstring sel = cur.selectionAsString(false);
2318                         InsetMathMacroTemplate * macro = new InsetMathMacroTemplate(cur.buffer());
2319                         // create a macro template if we see "\\newcommand" somewhere, and
2320                         // an ordinary formula otherwise
2321                         if (!sel.empty()
2322                                 && (sel.find(from_ascii("\\newcommand")) != string::npos
2323                                         || sel.find(from_ascii("\\newlyxcommand")) != string::npos
2324                                         || sel.find(from_ascii("\\def")) != string::npos)
2325                                 && macro->fromString(sel)) {
2326                                 cur.recordUndo();
2327                                 replaceSelection(cur);
2328                                 cur.insert(macro);
2329                         } else {
2330                                 // no meaningful macro template was found
2331                                 delete macro;
2332                                 mathDispatch(cur,FuncRequest(LFUN_MATH_MODE));
2333                         }
2334                 } else
2335                         // The argument is meaningful
2336                         // We replace cmd with LFUN_MATH_INSERT because LFUN_MATH_MODE
2337                         // has a different meaning in math mode
2338                         mathDispatch(cur, FuncRequest(LFUN_MATH_INSERT,cmd.argument()));
2339                 break;
2340         }
2341
2342         case LFUN_MATH_MACRO:
2343                 if (cmd.argument().empty())
2344                         cur.errorMessage(from_utf8(N_("Missing argument")));
2345                 else {
2346                         cur.recordUndo();
2347                         string s = to_utf8(cmd.argument());
2348                         string const s1 = token(s, ' ', 1);
2349                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
2350                         string const s2 = token(s, ' ', 2);
2351                         MacroType type = MacroTypeNewcommand;
2352                         if (s2 == "def")
2353                                 type = MacroTypeDef;
2354                         InsetMathMacroTemplate * inset = new InsetMathMacroTemplate(cur.buffer(),
2355                                 from_utf8(token(s, ' ', 0)), nargs, false, type);
2356                         inset->setBuffer(bv->buffer());
2357                         insertInset(cur, inset);
2358
2359                         // enter macro inset and select the name
2360                         cur.push(*inset);
2361                         cur.top().pos() = cur.top().lastpos();
2362                         cur.resetAnchor();
2363                         cur.selection(true);
2364                         cur.top().pos() = 0;
2365                 }
2366                 break;
2367
2368         case LFUN_MATH_DISPLAY:
2369         case LFUN_MATH_SUBSCRIPT:
2370         case LFUN_MATH_SUPERSCRIPT:
2371         case LFUN_MATH_INSERT:
2372         case LFUN_MATH_AMS_MATRIX:
2373         case LFUN_MATH_MATRIX:
2374         case LFUN_MATH_DELIM:
2375         case LFUN_MATH_BIGDELIM:
2376                 mathDispatch(cur, cmd);
2377                 break;
2378
2379         case LFUN_FONT_EMPH: {
2380                 Font font(ignore_font, ignore_language);
2381                 font.fontInfo().setEmph(FONT_TOGGLE);
2382                 toggleAndShow(cur, this, font);
2383                 break;
2384         }
2385
2386         case LFUN_FONT_ITAL: {
2387                 Font font(ignore_font, ignore_language);
2388                 font.fontInfo().setShape(ITALIC_SHAPE);
2389                 toggleAndShow(cur, this, font);
2390                 break;
2391         }
2392
2393         case LFUN_FONT_BOLD:
2394         case LFUN_FONT_BOLDSYMBOL: {
2395                 Font font(ignore_font, ignore_language);
2396                 font.fontInfo().setSeries(BOLD_SERIES);
2397                 toggleAndShow(cur, this, font);
2398                 break;
2399         }
2400
2401         case LFUN_FONT_NOUN: {
2402                 Font font(ignore_font, ignore_language);
2403                 font.fontInfo().setNoun(FONT_TOGGLE);
2404                 toggleAndShow(cur, this, font);
2405                 break;
2406         }
2407
2408         case LFUN_FONT_TYPEWRITER: {
2409                 Font font(ignore_font, ignore_language);
2410                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
2411                 toggleAndShow(cur, this, font);
2412                 break;
2413         }
2414
2415         case LFUN_FONT_SANS: {
2416                 Font font(ignore_font, ignore_language);
2417                 font.fontInfo().setFamily(SANS_FAMILY);
2418                 toggleAndShow(cur, this, font);
2419                 break;
2420         }
2421
2422         case LFUN_FONT_ROMAN: {
2423                 Font font(ignore_font, ignore_language);
2424                 font.fontInfo().setFamily(ROMAN_FAMILY);
2425                 toggleAndShow(cur, this, font);
2426                 break;
2427         }
2428
2429         case LFUN_FONT_DEFAULT: {
2430                 Font font(inherit_font, ignore_language);
2431                 toggleAndShow(cur, this, font);
2432                 break;
2433         }
2434
2435         case LFUN_FONT_STRIKEOUT: {
2436                 Font font(ignore_font, ignore_language);
2437                 font.fontInfo().setStrikeout(FONT_TOGGLE);
2438                 toggleAndShow(cur, this, font);
2439                 break;
2440         }
2441
2442         case LFUN_FONT_CROSSOUT: {
2443                 Font font(ignore_font, ignore_language);
2444                 font.fontInfo().setXout(FONT_TOGGLE);
2445                 toggleAndShow(cur, this, font);
2446                 break;
2447         }
2448
2449         case LFUN_FONT_UNDERUNDERLINE: {
2450                 Font font(ignore_font, ignore_language);
2451                 font.fontInfo().setUuline(FONT_TOGGLE);
2452                 toggleAndShow(cur, this, font);
2453                 break;
2454         }
2455
2456         case LFUN_FONT_UNDERWAVE: {
2457                 Font font(ignore_font, ignore_language);
2458                 font.fontInfo().setUwave(FONT_TOGGLE);
2459                 toggleAndShow(cur, this, font);
2460                 break;
2461         }
2462
2463         case LFUN_FONT_UNDERLINE: {
2464                 Font font(ignore_font, ignore_language);
2465                 font.fontInfo().setUnderbar(FONT_TOGGLE);
2466                 toggleAndShow(cur, this, font);
2467                 break;
2468         }
2469
2470         case LFUN_FONT_SIZE: {
2471                 Font font(ignore_font, ignore_language);
2472                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
2473                 toggleAndShow(cur, this, font);
2474                 break;
2475         }
2476
2477         case LFUN_LANGUAGE: {
2478                 string const lang_arg = cmd.getArg(0);
2479                 bool const reset = (lang_arg.empty() || lang_arg == "reset");
2480                 Language const * lang =
2481                         reset ? reset_language
2482                               : languages.getLanguage(lang_arg);
2483                 // we allow reset_language, which is 0, but only if it
2484                 // was requested via empty or "reset" arg.
2485                 if (!lang && !reset)
2486                         break;
2487                 bool const toggle = (cmd.getArg(1) != "set");
2488                 selectWordWhenUnderCursor(cur, WHOLE_WORD_STRICT);
2489                 Font font(ignore_font, lang);
2490                 toggleAndShow(cur, this, font, toggle);
2491                 // We need a buffer update if we change the language
2492                 // of an info inset
2493                 if (cur.insetInSelection(INFO_CODE))
2494                         cur.forceBufferUpdate();
2495                 break;
2496         }
2497
2498         case LFUN_TEXTSTYLE_APPLY: {
2499                 unsigned int num = 0;
2500                 string const arg = to_utf8(cmd.argument());
2501                 // Argument?
2502                 if (!arg.empty()) {
2503                         if (isStrUnsignedInt(arg)) {
2504                                 num = convert<uint>(arg);
2505                                 if (num >= freeFonts.size()) {
2506                                         cur.message(_("Invalid argument (number exceeds stack size)!"));
2507                                         break;
2508                                 }
2509                         } else {
2510                                 cur.message(_("Invalid argument (must be a non-negative number)!"));
2511                                 break;
2512                         }
2513                 }
2514                 toggleAndShow(cur, this, freeFonts[num].second, toggleall);
2515                 cur.message(bformat(_("Text properties applied: %1$s"), freeFonts[num].first));
2516                 break;
2517         }
2518
2519         // Set the freefont using the contents of \param data dispatched from
2520         // the frontends and apply it at the current cursor location.
2521         case LFUN_TEXTSTYLE_UPDATE: {
2522                 Font font(ignore_font, ignore_language);
2523                 bool toggle;
2524                 if (font.fromString(to_utf8(cmd.argument()), toggle)) {
2525                         docstring const props = font.stateText(&bv->buffer().params(), true);
2526                         freeFonts.push(make_pair(props, font));
2527                         toggleall = toggle;
2528                         toggleAndShow(cur, this, font, toggleall);
2529                         // We need a buffer update if we change the language
2530                         // of an info inset
2531                         if (cur.insetInSelection(INFO_CODE))
2532                                 cur.forceBufferUpdate();
2533                         cur.message(bformat(_("Text properties applied: %1$s"), props));
2534                 } else
2535                         LYXERR0("Invalid argument of textstyle-update");
2536                 break;
2537         }
2538
2539         case LFUN_FINISHED_LEFT:
2540                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
2541                 // We're leaving an inset, going left. If the inset is LTR, we're
2542                 // leaving from the front, so we should not move (remain at --- but
2543                 // not in --- the inset). If the inset is RTL, move left, without
2544                 // entering the inset itself; i.e., move to after the inset.
2545                 if (cur.paragraph().getFontSettings(
2546                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
2547                         cursorVisLeft(cur, true);
2548                 break;
2549
2550         case LFUN_FINISHED_RIGHT:
2551                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
2552                 // We're leaving an inset, going right. If the inset is RTL, we're
2553                 // leaving from the front, so we should not move (remain at --- but
2554                 // not in --- the inset). If the inset is LTR, move right, without
2555                 // entering the inset itself; i.e., move to after the inset.
2556                 if (!cur.paragraph().getFontSettings(
2557                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
2558                         cursorVisRight(cur, true);
2559                 break;
2560
2561         case LFUN_FINISHED_BACKWARD:
2562                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
2563                 cur.setCurrentFont();
2564                 break;
2565
2566         case LFUN_FINISHED_FORWARD:
2567                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
2568                 ++cur.pos();
2569                 cur.setCurrentFont();
2570                 break;
2571
2572         case LFUN_LAYOUT_PARAGRAPH: {
2573                 string data;
2574                 params2string(cur.paragraph(), data);
2575                 data = "show\n" + data;
2576                 bv->showDialog("paragraph", data);
2577                 break;
2578         }
2579
2580         case LFUN_PARAGRAPH_UPDATE: {
2581                 string data;
2582                 params2string(cur.paragraph(), data);
2583
2584                 // Will the paragraph accept changes from the dialog?
2585                 bool const accept =
2586                         cur.inset().allowParagraphCustomization(cur.idx());
2587
2588                 data = "update " + convert<string>(accept) + '\n' + data;
2589                 bv->updateDialog("paragraph", data);
2590                 break;
2591         }
2592
2593         case LFUN_ACCENT_UMLAUT:
2594         case LFUN_ACCENT_CIRCUMFLEX:
2595         case LFUN_ACCENT_GRAVE:
2596         case LFUN_ACCENT_ACUTE:
2597         case LFUN_ACCENT_TILDE:
2598         case LFUN_ACCENT_PERISPOMENI:
2599         case LFUN_ACCENT_CEDILLA:
2600         case LFUN_ACCENT_MACRON:
2601         case LFUN_ACCENT_DOT:
2602         case LFUN_ACCENT_UNDERDOT:
2603         case LFUN_ACCENT_UNDERBAR:
2604         case LFUN_ACCENT_CARON:
2605         case LFUN_ACCENT_BREVE:
2606         case LFUN_ACCENT_TIE:
2607         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2608         case LFUN_ACCENT_CIRCLE:
2609         case LFUN_ACCENT_OGONEK:
2610                 theApp()->handleKeyFunc(cmd.action());
2611                 if (!cmd.argument().empty())
2612                         // FIXME: Are all these characters encoded in one byte in utf8?
2613                         bv->translateAndInsert(cmd.argument()[0], this, cur);
2614                 cur.screenUpdateFlags(Update::FitCursor);
2615                 break;
2616
2617         case LFUN_FLOAT_LIST_INSERT: {
2618                 DocumentClass const & tclass = bv->buffer().params().documentClass();
2619                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
2620                         cur.recordUndo();
2621                         if (cur.selection())
2622                                 cutSelection(cur, false);
2623                         breakParagraph(cur);
2624
2625                         if (cur.lastpos() != 0) {
2626                                 cursorBackward(cur);
2627                                 breakParagraph(cur);
2628                         }
2629
2630                         docstring const laystr = cur.inset().usePlainLayout() ?
2631                                 tclass.plainLayoutName() :
2632                                 tclass.defaultLayoutName();
2633                         setLayout(cur, laystr);
2634                         ParagraphParameters p;
2635                         // FIXME If this call were replaced with one to clearParagraphParams(),
2636                         // then we could get rid of this method altogether.
2637                         setParagraphs(cur, p);
2638                         // FIXME This should be simplified when InsetFloatList takes a
2639                         // Buffer in its constructor.
2640                         InsetFloatList * ifl = new InsetFloatList(cur.buffer(), to_utf8(cmd.argument()));
2641                         ifl->setBuffer(bv->buffer());
2642                         insertInset(cur, ifl);
2643                         cur.posForward();
2644                 } else {
2645                         lyxerr << "Non-existent float type: "
2646                                << to_utf8(cmd.argument()) << endl;
2647                 }
2648                 break;
2649         }
2650
2651         case LFUN_CHANGE_ACCEPT: {
2652                 acceptOrRejectChanges(cur, ACCEPT);
2653                 break;
2654         }
2655
2656         case LFUN_CHANGE_REJECT: {
2657                 acceptOrRejectChanges(cur, REJECT);
2658                 break;
2659         }
2660
2661         case LFUN_THESAURUS_ENTRY: {
2662                 Language const * language = cur.getFont().language();
2663                 docstring arg = cmd.argument();
2664                 if (arg.empty()) {
2665                         arg = cur.selectionAsString(false);
2666                         // FIXME
2667                         if (arg.size() > 100 || arg.empty()) {
2668                                 // Get word or selection
2669                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2670                                 arg = cur.selectionAsString(false);
2671                                 arg += " lang=" + from_ascii(language->lang());
2672                         }
2673                 } else {
2674                         string lang = cmd.getArg(1);
2675                         // This duplicates the code in GuiThesaurus::initialiseParams
2676                         if (prefixIs(lang, "lang=")) {
2677                                 language = languages.getLanguage(lang.substr(5));
2678                                 if (!language)
2679                                         language = cur.getFont().language();
2680                         }
2681                 }
2682                 string lang = language->code();
2683                 if (lyxrc.thesaurusdir_path.empty() && !thesaurus.thesaurusInstalled(from_ascii(lang))) {
2684                         LYXERR(Debug::ACTION, "Command " << cmd << ". Thesaurus not found for language " << lang);
2685                         frontend::Alert::warning(_("Path to thesaurus directory not set!"),
2686                                         _("The path to the thesaurus directory has not been specified.\n"
2687                                           "The thesaurus is not functional.\n"
2688                                           "Please refer to sec. 6.15.1 of the User's Guide for setup\n"
2689                                           "instructions."));
2690                 }
2691                 bv->showDialog("thesaurus", to_utf8(arg));
2692                 break;
2693         }
2694
2695         case LFUN_SPELLING_ADD: {
2696                 Language const * language = getLanguage(cur, cmd.getArg(1));
2697                 docstring word = from_utf8(cmd.getArg(0));
2698                 if (word.empty()) {
2699                         word = cur.selectionAsString(false);
2700                         // FIXME
2701                         if (word.size() > 100 || word.empty()) {
2702                                 // Get word or selection
2703                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2704                                 word = cur.selectionAsString(false);
2705                         }
2706                 }
2707                 WordLangTuple wl(word, language);
2708                 theSpellChecker()->insert(wl);
2709                 break;
2710         }
2711
2712         case LFUN_SPELLING_IGNORE: {
2713                 Language const * language = getLanguage(cur, cmd.getArg(1));
2714                 docstring word = from_utf8(cmd.getArg(0));
2715                 if (word.empty()) {
2716                         word = cur.selectionAsString(false);
2717                         // FIXME
2718                         if (word.size() > 100 || word.empty()) {
2719                                 // Get word or selection
2720                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2721                                 word = cur.selectionAsString(false);
2722                         }
2723                 }
2724                 WordLangTuple wl(word, language);
2725                 theSpellChecker()->accept(wl);
2726                 break;
2727         }
2728
2729         case LFUN_SPELLING_REMOVE: {
2730                 Language const * language = getLanguage(cur, cmd.getArg(1));
2731                 docstring word = from_utf8(cmd.getArg(0));
2732                 if (word.empty()) {
2733                         word = cur.selectionAsString(false);
2734                         // FIXME
2735                         if (word.size() > 100 || word.empty()) {
2736                                 // Get word or selection
2737                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2738                                 word = cur.selectionAsString(false);
2739                         }
2740                 }
2741                 WordLangTuple wl(word, language);
2742                 theSpellChecker()->remove(wl);
2743                 break;
2744         }
2745
2746         case LFUN_PARAGRAPH_PARAMS_APPLY: {
2747                 // Given data, an encoding of the ParagraphParameters
2748                 // generated in the Paragraph dialog, this function sets
2749                 // the current paragraph, or currently selected paragraphs,
2750                 // appropriately.
2751                 // NOTE: This function overrides all existing settings.
2752                 setParagraphs(cur, cmd.argument());
2753                 cur.message(_("Paragraph layout set"));
2754                 break;
2755         }
2756
2757         case LFUN_PARAGRAPH_PARAMS: {
2758                 // Given data, an encoding of the ParagraphParameters as we'd
2759                 // find them in a LyX file, this function modifies the current paragraph,
2760                 // or currently selected paragraphs.
2761                 // NOTE: This function only modifies, and does not override, existing
2762                 // settings.
2763                 setParagraphs(cur, cmd.argument(), true);
2764                 cur.message(_("Paragraph layout set"));
2765                 break;
2766         }
2767
2768         case LFUN_ESCAPE:
2769                 if (cur.selection()) {
2770                         cur.selection(false);
2771                 } else {
2772                         cur.undispatched();
2773                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
2774                         // correct, but I'm not 100% sure -- dov, 071019
2775                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
2776                 }
2777                 break;
2778
2779         case LFUN_OUTLINE_UP: {
2780                 pos_type const opos = cur.pos();
2781                 outline(OutlineUp, cur, this);
2782                 setCursor(cur, cur.pit(), opos);
2783                 cur.forceBufferUpdate();
2784                 needsUpdate = true;
2785                 break;
2786         }
2787
2788         case LFUN_OUTLINE_DOWN: {
2789                 pos_type const opos = cur.pos();
2790                 outline(OutlineDown, cur, this);
2791                 setCursor(cur, cur.pit(), opos);
2792                 cur.forceBufferUpdate();
2793                 needsUpdate = true;
2794                 break;
2795         }
2796
2797         case LFUN_OUTLINE_IN:
2798                 outline(OutlineIn, cur, this);
2799                 cur.forceBufferUpdate();
2800                 needsUpdate = true;
2801                 break;
2802
2803         case LFUN_OUTLINE_OUT:
2804                 outline(OutlineOut, cur, this);
2805                 cur.forceBufferUpdate();
2806                 needsUpdate = true;
2807                 break;
2808
2809         case LFUN_SERVER_GET_STATISTICS:
2810                 {
2811                         DocIterator from, to;
2812                         if (cur.selection()) {
2813                                 from = cur.selectionBegin();
2814                                 to = cur.selectionEnd();
2815                         } else {
2816                                 from = doc_iterator_begin(cur.buffer());
2817                                 to = doc_iterator_end(cur.buffer());
2818                         }
2819
2820                         cur.buffer()->updateStatistics(from, to);
2821                         string const arg0 = cmd.getArg(0);
2822                         if (arg0 == "words") {
2823                                 cur.message(convert<docstring>(cur.buffer()->wordCount()));
2824                         } else if (arg0 == "chars") {
2825                                 cur.message(convert<docstring>(cur.buffer()->charCount(false)));
2826                         } else if (arg0 == "chars-space") {
2827                                 cur.message(convert<docstring>(cur.buffer()->charCount(true)));
2828                         } else {
2829                                 cur.message(convert<docstring>(cur.buffer()->wordCount()) + " "
2830                                 + convert<docstring>(cur.buffer()->charCount(false)) + " "
2831                                 + convert<docstring>(cur.buffer()->charCount(true)));
2832                         }
2833                 }
2834                 break;
2835
2836         default:
2837                 LYXERR(Debug::ACTION, "Command " << cmd << " not DISPATCHED by Text");
2838                 cur.undispatched();
2839                 break;
2840         }
2841
2842         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
2843
2844         if (lyxrc.spellcheck_continuously && !needsUpdate) {
2845                 // Check for misspelled text
2846                 // The redraw is useful because of the painting of
2847                 // misspelled markers depends on the cursor position.
2848                 // Trigger a redraw for cursor moves inside misspelled text.
2849                 if (!cur.inTexted()) {
2850                         // move from regular text to math
2851                         needsUpdate = last_misspelled;
2852                 } else if (oldTopSlice != cur.top() || oldBoundary != cur.boundary()) {
2853                         // move inside regular text
2854                         needsUpdate = last_misspelled
2855                                 || cur.paragraph().isMisspelled(cur.pos(), true);
2856                 }
2857         }
2858
2859         // FIXME: The cursor flag is reset two lines below
2860         // so we need to check here if some of the LFUN did touch that.
2861         // for now only Text::erase() and Text::backspace() do that.
2862         // The plan is to verify all the LFUNs and then to remove this
2863         // singleParUpdate boolean altogether.
2864         if (cur.result().screenUpdate() & Update::Force) {
2865                 singleParUpdate = false;
2866                 needsUpdate = true;
2867         }
2868
2869         // FIXME: the following code should go in favor of fine grained
2870         // update flag treatment.
2871         if (singleParUpdate) {
2872                 // Inserting characters does not change par height in general. So, try
2873                 // to update _only_ this paragraph. BufferView will detect if a full
2874                 // metrics update is needed anyway.
2875                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
2876                 return;
2877         }
2878         if (!needsUpdate
2879             && &oldTopSlice.inset() == &cur.inset()
2880             && oldTopSlice.idx() == cur.idx()
2881             && !oldSelection // oldSelection is a backup of cur.selection() at the beginning of the function.
2882             && !cur.selection())
2883                 // FIXME: it would be better if we could just do this
2884                 //
2885                 //if (cur.result().update() != Update::FitCursor)
2886                 //      cur.noScreenUpdate();
2887                 //
2888                 // But some LFUNs do not set Update::FitCursor when needed, so we
2889                 // do it for all. This is not very harmfull as FitCursor will provoke
2890                 // a full redraw only if needed but still, a proper review of all LFUN
2891                 // should be done and this needsUpdate boolean can then be removed.
2892                 cur.screenUpdateFlags(Update::FitCursor);
2893         else
2894                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
2895 }
2896
2897
2898 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
2899                         FuncStatus & flag) const
2900 {
2901         LBUFERR(this == cur.text());
2902
2903         FontInfo const & fontinfo = cur.real_current_font.fontInfo();
2904         bool enable = true;
2905         bool allow_in_passthru = false;
2906         InsetCode code = NO_CODE;
2907         
2908         switch (cmd.action()) {
2909
2910         case LFUN_DEPTH_DECREMENT:
2911                 enable = changeDepthAllowed(cur, DEC_DEPTH);
2912                 break;
2913
2914         case LFUN_DEPTH_INCREMENT:
2915                 enable = changeDepthAllowed(cur, INC_DEPTH);
2916                 break;
2917
2918         case LFUN_APPENDIX:
2919                 // FIXME We really should not allow this to be put, e.g.,
2920                 // in a footnote, or in ERT. But it would make sense in a
2921                 // branch, so I'm not sure what to do.
2922                 flag.setOnOff(cur.paragraph().params().startOfAppendix());
2923                 break;
2924
2925         case LFUN_DIALOG_SHOW_NEW_INSET:
2926                 if (cmd.argument() == "bibitem")
2927                         code = BIBITEM_CODE;
2928                 else if (cmd.argument() == "bibtex") {
2929                         code = BIBTEX_CODE;
2930                         // not allowed in description items
2931                         enable = !inDescriptionItem(cur);
2932                 }
2933                 else if (cmd.argument() == "box")
2934                         code = BOX_CODE;
2935                 else if (cmd.argument() == "branch")
2936                         code = BRANCH_CODE;
2937                 else if (cmd.argument() == "citation")
2938                         code = CITE_CODE;
2939                 else if (cmd.argument() == "ert")
2940                         code = ERT_CODE;
2941                 else if (cmd.argument() == "external")
2942                         code = EXTERNAL_CODE;
2943                 else if (cmd.argument() == "float")
2944                         code = FLOAT_CODE;
2945                 else if (cmd.argument() == "graphics")
2946                         code = GRAPHICS_CODE;
2947                 else if (cmd.argument() == "href")
2948                         code = HYPERLINK_CODE;
2949                 else if (cmd.argument() == "include")
2950                         code = INCLUDE_CODE;
2951                 else if (cmd.argument() == "index")
2952                         code = INDEX_CODE;
2953                 else if (cmd.argument() == "index_print")
2954                         code = INDEX_PRINT_CODE;
2955                 else if (cmd.argument() == "listings")
2956                         code = LISTINGS_CODE;
2957                 else if (cmd.argument() == "mathspace")
2958                         code = MATH_HULL_CODE;
2959                 else if (cmd.argument() == "nomenclature")
2960                         code = NOMENCL_CODE;
2961                 else if (cmd.argument() == "nomencl_print")
2962                         code = NOMENCL_PRINT_CODE;
2963                 else if (cmd.argument() == "label")
2964                         code = LABEL_CODE;
2965                 else if (cmd.argument() == "line")
2966                         code = LINE_CODE;
2967                 else if (cmd.argument() == "note")
2968                         code = NOTE_CODE;
2969                 else if (cmd.argument() == "phantom")
2970                         code = PHANTOM_CODE;
2971                 else if (cmd.argument() == "ref")
2972                         code = REF_CODE;
2973                 else if (cmd.argument() == "space")
2974                         code = SPACE_CODE;
2975                 else if (cmd.argument() == "toc")
2976                         code = TOC_CODE;
2977                 else if (cmd.argument() == "vspace")
2978                         code = VSPACE_CODE;
2979                 else if (cmd.argument() == "wrap")
2980                         code = WRAP_CODE;
2981                 break;
2982
2983         case LFUN_ERT_INSERT:
2984                 code = ERT_CODE;
2985                 break;
2986         case LFUN_LISTING_INSERT:
2987                 code = LISTINGS_CODE;
2988                 // not allowed in description items
2989                 enable = !inDescriptionItem(cur);
2990                 break;
2991         case LFUN_FOOTNOTE_INSERT:
2992                 code = FOOT_CODE;
2993                 break;
2994         case LFUN_TABULAR_INSERT:
2995                 code = TABULAR_CODE;
2996                 break;
2997         case LFUN_TABULAR_STYLE_INSERT:
2998                 code = TABULAR_CODE;
2999                 break;
3000         case LFUN_MARGINALNOTE_INSERT:
3001                 code = MARGIN_CODE;
3002                 break;
3003         case LFUN_FLOAT_INSERT:
3004         case LFUN_FLOAT_WIDE_INSERT:
3005                 // FIXME: If there is a selection, we should check whether there
3006                 // are floats in the selection, but this has performance issues, see
3007                 // LFUN_CHANGE_ACCEPT/REJECT.
3008                 code = FLOAT_CODE;
3009                 if (inDescriptionItem(cur))
3010                         // not allowed in description items
3011                         enable = false;
3012                 else {
3013                         InsetCode const inset_code = cur.inset().lyxCode();
3014
3015                         // algorithm floats cannot be put in another float
3016                         if (to_utf8(cmd.argument()) == "algorithm") {
3017                                 enable = inset_code != WRAP_CODE && inset_code != FLOAT_CODE;
3018                                 break;
3019                         }
3020
3021                         // for figures and tables: only allow in another
3022                         // float or wrap if it is of the same type and
3023                         // not a subfloat already
3024                         if(cur.inset().lyxCode() == code) {
3025                                 InsetFloat const & ins =
3026                                         static_cast<InsetFloat const &>(cur.inset());
3027                                 enable = ins.params().type == to_utf8(cmd.argument())
3028                                         && !ins.params().subfloat;
3029                         } else if(cur.inset().lyxCode() == WRAP_CODE) {
3030                                 InsetWrap const & ins =
3031                                         static_cast<InsetWrap const &>(cur.inset());
3032                                 enable = ins.params().type == to_utf8(cmd.argument());
3033                         }
3034                 }
3035                 break;
3036         case LFUN_WRAP_INSERT:
3037                 code = WRAP_CODE;
3038                 // not allowed in description items
3039                 enable = !inDescriptionItem(cur);
3040                 break;
3041         case LFUN_FLOAT_LIST_INSERT: {
3042                 code = FLOAT_LIST_CODE;
3043                 // not allowed in description items
3044                 enable = !inDescriptionItem(cur);
3045                 if (enable) {
3046                         FloatList const & floats = cur.buffer()->params().documentClass().floats();
3047                         FloatList::const_iterator cit = floats[to_ascii(cmd.argument())];
3048                         // make sure we know about such floats
3049                         if (cit == floats.end() ||
3050                                         // and that we know how to generate a list of them
3051                             (!cit->second.usesFloatPkg() && cit->second.listCommand().empty())) {
3052                                 flag.setUnknown(true);
3053                                 // probably not necessary, but...
3054                                 enable = false;
3055                         }
3056                 }
3057                 break;
3058         }
3059         case LFUN_CAPTION_INSERT: {
3060                 code = CAPTION_CODE;
3061                 string arg = cmd.getArg(0);
3062                 bool varia = arg != "Unnumbered"
3063                         && cur.inset().allowsCaptionVariation(arg);
3064                 // not allowed in description items,
3065                 // and in specific insets
3066                 enable = !inDescriptionItem(cur)
3067                         && (varia || arg.empty() || arg == "Standard");
3068                 break;
3069         }
3070         case LFUN_NOTE_INSERT:
3071                 code = NOTE_CODE;
3072                 break;
3073         case LFUN_FLEX_INSERT: {
3074                 code = FLEX_CODE;
3075                 string s = cmd.getArg(0);
3076                 InsetLayout il =
3077                         cur.buffer()->params().documentClass().insetLayout(from_utf8(s));
3078                 if (il.lyxtype() != InsetLayout::CHARSTYLE &&
3079                     il.lyxtype() != InsetLayout::CUSTOM &&
3080                     il.lyxtype ()!= InsetLayout::STANDARD)
3081                         enable = false;
3082                 break;
3083                 }
3084         case LFUN_BOX_INSERT:
3085                 code = BOX_CODE;
3086                 break;
3087         case LFUN_BRANCH_INSERT:
3088                 code = BRANCH_CODE;
3089                 if (cur.buffer()->masterBuffer()->params().branchlist().empty()
3090                     && cur.buffer()->params().branchlist().empty())
3091                         enable = false;
3092                 break;
3093         case LFUN_IPA_INSERT:
3094                 code = IPA_CODE;
3095                 break;
3096         case LFUN_PHANTOM_INSERT:
3097                 code = PHANTOM_CODE;
3098                 break;
3099         case LFUN_LABEL_INSERT:
3100                 code = LABEL_CODE;
3101                 break;
3102         case LFUN_INFO_INSERT:
3103                 code = INFO_CODE;
3104                 enable = cmd.argument().empty()
3105                         || infoparams.validateArgument(cur.buffer(), cmd.argument(), true);
3106                 break;
3107         case LFUN_ARGUMENT_INSERT: {
3108                 code = ARG_CODE;
3109                 allow_in_passthru = true;
3110                 string const arg = cmd.getArg(0);
3111                 if (arg.empty()) {
3112                         enable = false;
3113                         break;
3114                 }
3115                 Layout const & lay = cur.paragraph().layout();
3116                 Layout::LaTeXArgMap args = lay.args();
3117                 Layout::LaTeXArgMap::const_iterator const lait =
3118                                 args.find(arg);
3119                 if (lait != args.end()) {
3120                         enable = true;
3121                         pit_type pit = cur.pit();
3122                         pit_type lastpit = cur.pit();
3123                         if (lay.isEnvironment() && !prefixIs(arg, "item:")) {
3124                                 // In a sequence of "merged" environment layouts, we only allow
3125                                 // non-item arguments once.
3126                                 lastpit = cur.lastpit();
3127                                 // get the first paragraph in sequence with this layout
3128                                 depth_type const current_depth = cur.paragraph().params().depth();
3129                                 while (true) {
3130                                         if (pit == 0)
3131                                                 break;
3132                                         Paragraph cpar = pars_[pit - 1];
3133                                         if (cpar.layout() == lay && cpar.params().depth() == current_depth)
3134                                                 --pit;
3135                                         else
3136                                                 break;
3137                                 }
3138                         }
3139                         for (; pit <= lastpit; ++pit) {
3140                                 if (pars_[pit].layout() != lay)
3141                                         break;
3142                                 for (auto const & table : pars_[pit].insetList())
3143                                         if (InsetArgument const * ins = table.inset->asInsetArgument())
3144                                                 if (ins->name() == arg) {
3145                                                         // we have this already
3146                                                         enable = false;
3147                                                         break;
3148                                                 }
3149                         }
3150                 } else
3151                         enable = false;
3152                 break;
3153         }
3154         case LFUN_INDEX_INSERT:
3155                 code = INDEX_CODE;
3156                 break;
3157         case LFUN_INDEX_PRINT:
3158                 code = INDEX_PRINT_CODE;
3159                 // not allowed in description items
3160                 enable = !inDescriptionItem(cur);
3161                 break;
3162         case LFUN_NOMENCL_INSERT:
3163                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
3164                         enable = false;
3165                         break;
3166                 }
3167                 code = NOMENCL_CODE;
3168                 break;
3169         case LFUN_NOMENCL_PRINT:
3170                 code = NOMENCL_PRINT_CODE;
3171                 // not allowed in description items
3172                 enable = !inDescriptionItem(cur);
3173                 break;
3174         case LFUN_HREF_INSERT:
3175                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
3176                         enable = false;
3177                         break;
3178                 }
3179                 code = HYPERLINK_CODE;
3180                 break;
3181         case LFUN_IPAMACRO_INSERT: {
3182                 string const arg = cmd.getArg(0);
3183                 if (arg == "deco")
3184                         code = IPADECO_CODE;
3185                 else
3186                         code = IPACHAR_CODE;
3187                 break;
3188         }
3189         case LFUN_QUOTE_INSERT:
3190                 // always allow this, since we will inset a raw quote
3191                 // if an inset is not allowed.
3192                 allow_in_passthru = true;
3193                 break;
3194         case LFUN_SPECIALCHAR_INSERT:
3195                 code = SPECIALCHAR_CODE;
3196                 break;
3197         case LFUN_SPACE_INSERT:
3198                 // slight hack: we know this is allowed in math mode
3199                 if (cur.inTexted())
3200                         code = SPACE_CODE;
3201                 break;
3202         case LFUN_PREVIEW_INSERT:
3203                 code = PREVIEW_CODE;
3204                 break;
3205         case LFUN_SCRIPT_INSERT:
3206                 code = SCRIPT_CODE;
3207                 break;
3208
3209         case LFUN_MATH_INSERT:
3210         case LFUN_MATH_AMS_MATRIX:
3211         case LFUN_MATH_MATRIX:
3212         case LFUN_MATH_DELIM:
3213         case LFUN_MATH_BIGDELIM:
3214         case LFUN_MATH_DISPLAY:
3215         case LFUN_MATH_MODE:
3216         case LFUN_MATH_MACRO:
3217         case LFUN_MATH_SUBSCRIPT:
3218         case LFUN_MATH_SUPERSCRIPT:
3219                 code = MATH_HULL_CODE;
3220                 break;
3221
3222         case LFUN_REGEXP_MODE:
3223                 code = MATH_HULL_CODE;
3224                 enable = cur.buffer()->isInternal() && !cur.inRegexped();
3225                 break;
3226
3227         case LFUN_INSET_MODIFY:
3228                 // We need to disable this, because we may get called for a
3229                 // tabular cell via
3230                 // InsetTabular::getStatus() -> InsetText::getStatus()
3231                 // and we don't handle LFUN_INSET_MODIFY.
3232                 enable = false;
3233                 break;
3234
3235         case LFUN_FONT_EMPH:
3236                 flag.setOnOff(fontinfo.emph() == FONT_ON);
3237                 enable = !cur.paragraph().isPassThru();
3238                 break;
3239
3240         case LFUN_FONT_ITAL:
3241                 flag.setOnOff(fontinfo.shape() == ITALIC_SHAPE);
3242                 enable = !cur.paragraph().isPassThru();
3243                 break;
3244
3245         case LFUN_FONT_NOUN:
3246                 flag.setOnOff(fontinfo.noun() == FONT_ON);
3247                 enable = !cur.paragraph().isPassThru();
3248                 break;
3249
3250         case LFUN_FONT_BOLD:
3251         case LFUN_FONT_BOLDSYMBOL:
3252                 flag.setOnOff(fontinfo.series() == BOLD_SERIES);
3253                 enable = !cur.paragraph().isPassThru();
3254                 break;
3255
3256         case LFUN_FONT_SANS:
3257                 flag.setOnOff(fontinfo.family() == SANS_FAMILY);
3258                 enable = !cur.paragraph().isPassThru();
3259                 break;
3260
3261         case LFUN_FONT_ROMAN:
3262                 flag.setOnOff(fontinfo.family() == ROMAN_FAMILY);
3263                 enable = !cur.paragraph().isPassThru();
3264                 break;
3265
3266         case LFUN_FONT_TYPEWRITER:
3267                 flag.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
3268                 enable = !cur.paragraph().isPassThru();
3269                 break;
3270
3271         case LFUN_CUT:
3272         case LFUN_COPY:
3273                 enable = cur.selection();
3274                 break;
3275
3276         case LFUN_PASTE: {
3277                 if (cmd.argument().empty()) {
3278                         if (theClipboard().isInternal())
3279                                 enable = cap::numberOfSelections() > 0;
3280                         else
3281                                 enable = !theClipboard().empty();
3282                         break;
3283                 }
3284
3285                 // we have an argument
3286                 string const arg = to_utf8(cmd.argument());
3287                 if (isStrUnsignedInt(arg)) {
3288                         // it's a number and therefore means the internal stack
3289                         unsigned int n = convert<unsigned int>(arg);
3290                         enable = cap::numberOfSelections() > n;
3291                         break;
3292                 }
3293
3294                 // explicit text type?
3295                 if (arg == "html") {
3296                         // Do not enable for PlainTextType, since some tidying in the
3297                         // frontend is needed for HTML, which is too unsafe for plain text.
3298                         enable = theClipboard().hasTextContents(Clipboard::HtmlTextType);
3299                         break;
3300                 } else if (arg == "latex") {
3301                         // LaTeX is usually not available on the clipboard with
3302                         // the correct MIME type, but in plain text.
3303                         enable = theClipboard().hasTextContents(Clipboard::PlainTextType) ||
3304                                  theClipboard().hasTextContents(Clipboard::LaTeXTextType);
3305                         break;
3306                 }
3307
3308                 Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
3309                 if (arg == "pdf")
3310                         type = Clipboard::PdfGraphicsType;
3311                 else if (arg == "png")
3312                         type = Clipboard::PngGraphicsType;
3313                 else if (arg == "jpeg")
3314                         type = Clipboard::JpegGraphicsType;
3315                 else if (arg == "linkback")
3316                         type = Clipboard::LinkBackGraphicsType;
3317                 else if (arg == "emf")
3318                         type = Clipboard::EmfGraphicsType;
3319                 else if (arg == "wmf")
3320                         type = Clipboard::WmfGraphicsType;
3321                 else {
3322                         // unknown argument
3323                         LYXERR0("Unrecognized graphics type: " << arg);
3324                         // we don't want to assert if the user just mistyped the LFUN
3325                         LATTEST(cmd.origin() != FuncRequest::INTERNAL);
3326                         enable = false;
3327                         break;
3328                 }
3329                 enable = theClipboard().hasGraphicsContents(type);
3330                 break;
3331         }
3332
3333         case LFUN_CLIPBOARD_PASTE:
3334         case LFUN_CLIPBOARD_PASTE_SIMPLE:
3335                 enable = !theClipboard().empty();
3336                 break;
3337
3338         case LFUN_PRIMARY_SELECTION_PASTE:
3339                 enable = cur.selection() || !theSelection().empty();
3340                 break;
3341
3342         case LFUN_SELECTION_PASTE:
3343                 enable = cap::selection();
3344                 break;
3345
3346         case LFUN_PARAGRAPH_MOVE_UP:
3347                 enable = cur.pit() > 0 && !cur.selection();
3348                 break;
3349
3350         case LFUN_PARAGRAPH_MOVE_DOWN:
3351                 enable = cur.pit() < cur.lastpit() && !cur.selection();
3352                 break;
3353
3354         case LFUN_CHANGE_ACCEPT:
3355         case LFUN_CHANGE_REJECT:
3356                 if (!cur.selection())
3357                         enable = cur.paragraph().isChanged(cur.pos());
3358                 else {
3359                         // will enable if there is a change in the selection
3360                         enable = false;
3361
3362                         // cheap improvement for efficiency: using cached
3363                         // buffer variable, if there is no change in the
3364                         // document, no need to check further.
3365                         if (!cur.buffer()->areChangesPresent())
3366                                 break;
3367
3368                         for (DocIterator it = cur.selectionBegin(); ; it.forwardPar()) {
3369                                 pos_type const beg = it.pos();
3370                                 pos_type end;
3371                                 bool const in_last_par = (it.pit() == cur.selectionEnd().pit() &&
3372                                                           it.idx() == cur.selectionEnd().idx());
3373                                 if (in_last_par)
3374                                         end = cur.selectionEnd().pos();
3375                                 else
3376                                         // the +1 is needed for cases, e.g., where there is a
3377                                         // paragraph break. See #11629.
3378                                         end = it.lastpos() + 1;
3379                                 if (beg != end && it.paragraph().isChanged(beg, end)) {
3380                                         enable = true;
3381                                         break;
3382                                 }
3383                                 if (beg != end && it.paragraph().hasChangedInsets(beg, end)) {
3384                                         enable = true;
3385                                         break;
3386                                 }
3387                                 if (in_last_par)
3388                                         break;
3389                         }
3390                 }
3391                 break;
3392
3393         case LFUN_OUTLINE_UP:
3394         case LFUN_OUTLINE_DOWN:
3395         case LFUN_OUTLINE_IN:
3396         case LFUN_OUTLINE_OUT:
3397                 // FIXME: LyX is not ready for outlining within inset.
3398                 enable = isMainText()
3399                         && cur.buffer()->text().getTocLevel(cur.pit()) != Layout::NOT_IN_TOC;
3400                 break;
3401
3402         case LFUN_NEWLINE_INSERT:
3403                 // LaTeX restrictions (labels or empty par)
3404                 enable = !cur.paragraph().isPassThru()
3405                         && cur.pos() > cur.paragraph().beginOfBody();
3406                 break;
3407
3408         case LFUN_SEPARATOR_INSERT:
3409                 // Always enabled for now
3410                 enable = true;
3411                 break;
3412
3413         case LFUN_TAB_INSERT:
3414         case LFUN_TAB_DELETE:
3415                 enable = cur.paragraph().isPassThru();
3416                 break;
3417
3418         case LFUN_GRAPHICS_SET_GROUP: {
3419                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
3420                 if (!ins)
3421                         enable = false;
3422                 else
3423                         flag.setOnOff(to_utf8(cmd.argument()) == ins->getParams().groupId);
3424                 break;
3425         }
3426
3427         case LFUN_NEWPAGE_INSERT:
3428                 // not allowed in description items
3429                 code = NEWPAGE_CODE;
3430                 enable = !inDescriptionItem(cur);
3431                 break;
3432
3433         case LFUN_LANGUAGE:
3434                 enable = !cur.paragraph().isPassThru();
3435                 flag.setOnOff(cmd.getArg(0) == cur.real_current_font.language()->lang());
3436                 break;
3437
3438         case LFUN_PARAGRAPH_BREAK:
3439                 enable = inset().allowMultiPar();
3440                 break;
3441
3442         case LFUN_SPELLING_ADD:
3443         case LFUN_SPELLING_IGNORE:
3444         case LFUN_SPELLING_REMOVE:
3445                 enable = theSpellChecker() != nullptr;
3446                 if (enable && !cmd.getArg(1).empty()) {
3447                         // validate explicitly given language
3448                         Language const * const lang = const_cast<Language *>(languages.getLanguage(cmd.getArg(1)));
3449                         enable &= lang != nullptr;
3450                 }
3451                 break;
3452
3453         case LFUN_LAYOUT:
3454         case LFUN_LAYOUT_TOGGLE: {
3455                 bool const ignoreautonests = cmd.getArg(1) == "ignoreautonests";
3456                 docstring const req_layout = ignoreautonests ? from_utf8(cmd.getArg(0)) : cmd.argument();
3457                 docstring const layout = resolveLayout(req_layout, cur);
3458
3459                 enable = !owner_->forcePlainLayout() && !layout.empty();
3460                 flag.setOnOff(isAlreadyLayout(layout, cur));
3461                 break;
3462         }
3463
3464         case LFUN_ENVIRONMENT_SPLIT: {
3465                 if (cmd.argument() == "outer") {
3466                         // check if we have an environment in our nesting hierarchy
3467                         bool res = false;
3468                         depth_type const current_depth = cur.paragraph().params().depth();
3469                         pit_type pit = cur.pit();
3470                         Paragraph cpar = pars_[pit];
3471                         while (true) {
3472                                 if (pit == 0 || cpar.params().depth() == 0)
3473                                         break;
3474                                 --pit;
3475                                 cpar = pars_[pit];
3476                                 if (cpar.params().depth() < current_depth)
3477                                         res = cpar.layout().isEnvironment();
3478                         }
3479                         enable = res;
3480                         break;
3481                 }
3482                 else if (cmd.argument() == "previous") {
3483                         // look if we have an environment in the previous par
3484                         pit_type pit = cur.pit();
3485                         Paragraph cpar = pars_[pit];
3486                         if (pit > 0) {
3487                                 --pit;
3488                                 cpar = pars_[pit];
3489                                 enable = cpar.layout().isEnvironment();
3490                                 break;
3491                         }
3492                         enable = false;
3493                         break;
3494                 }
3495                 else if (cur.paragraph().layout().isEnvironment()) {
3496                         enable = cmd.argument() == "before"
3497                                 || cur.pos() > 0 || !isFirstInSequence(cur.pit());
3498                         break;
3499                 }
3500                 enable = false;
3501                 break;
3502         }
3503
3504         case LFUN_LAYOUT_PARAGRAPH:
3505         case LFUN_PARAGRAPH_PARAMS:
3506         case LFUN_PARAGRAPH_PARAMS_APPLY:
3507         case LFUN_PARAGRAPH_UPDATE:
3508                 enable = owner_->allowParagraphCustomization();
3509                 break;
3510
3511         // FIXME: why are accent lfuns forbidden with pass_thru layouts?
3512         //  Because they insert COMBINING DIACRITICAL Unicode characters,
3513         //  that cannot be handled by LaTeX but must be converted according
3514         //  to the definition in lib/unicodesymbols?
3515         case LFUN_ACCENT_ACUTE:
3516         case LFUN_ACCENT_BREVE:
3517         case LFUN_ACCENT_CARON:
3518         case LFUN_ACCENT_CEDILLA:
3519         case LFUN_ACCENT_CIRCLE:
3520         case LFUN_ACCENT_CIRCUMFLEX:
3521         case LFUN_ACCENT_DOT:
3522         case LFUN_ACCENT_GRAVE:
3523         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
3524         case LFUN_ACCENT_MACRON:
3525         case LFUN_ACCENT_OGONEK:
3526         case LFUN_ACCENT_TIE:
3527         case LFUN_ACCENT_TILDE:
3528         case LFUN_ACCENT_PERISPOMENI:
3529         case LFUN_ACCENT_UMLAUT:
3530         case LFUN_ACCENT_UNDERBAR:
3531         case LFUN_ACCENT_UNDERDOT:
3532         case LFUN_FONT_FRAK:
3533         case LFUN_FONT_SIZE:
3534         case LFUN_FONT_STATE:
3535         case LFUN_FONT_UNDERLINE:
3536         case LFUN_FONT_STRIKEOUT:
3537         case LFUN_FONT_CROSSOUT:
3538         case LFUN_FONT_UNDERUNDERLINE:
3539         case LFUN_FONT_UNDERWAVE:
3540         case LFUN_TEXTSTYLE_UPDATE:
3541                 enable = !cur.paragraph().isPassThru();
3542                 break;
3543
3544         case LFUN_FONT_DEFAULT: {
3545                 Font font(inherit_font, ignore_language);
3546                 BufferParams const & bp = cur.buffer()->masterParams();
3547                 if (cur.selection()) {
3548                         enable = false;
3549                         // Check if we have a non-default font attribute
3550                         // in the selection range.
3551                         DocIterator const from = cur.selectionBegin();
3552                         DocIterator const to = cur.selectionEnd();
3553                         for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
3554                                 if (!dit.inTexted()) {
3555                                         dit.forwardPos();
3556                                         continue;
3557                                 }
3558                                 Paragraph const & par = dit.paragraph();
3559                                 pos_type const pos = dit.pos();
3560                                 Font tmp = par.getFontSettings(bp, pos);
3561                                 if (tmp.fontInfo() != font.fontInfo()
3562                                     || tmp.language() != bp.language) {
3563                                         enable = true;
3564                                         break;
3565                                 }
3566                                 dit.forwardPos();
3567                         }
3568                         break;
3569                 }
3570                 // Disable if all is default already.
3571                 enable = (cur.current_font.fontInfo() != font.fontInfo()
3572                           || cur.current_font.language() != bp.language);
3573                 break;
3574         }
3575
3576         case LFUN_TEXTSTYLE_APPLY:
3577                 enable = !freeFonts.empty();
3578                 break;
3579
3580         case LFUN_WORD_DELETE_FORWARD:
3581         case LFUN_WORD_DELETE_BACKWARD:
3582         case LFUN_LINE_DELETE_FORWARD:
3583         case LFUN_WORD_FORWARD:
3584         case LFUN_WORD_BACKWARD:
3585         case LFUN_WORD_RIGHT:
3586         case LFUN_WORD_LEFT:
3587         case LFUN_CHAR_FORWARD:
3588         case LFUN_CHAR_FORWARD_SELECT:
3589         case LFUN_CHAR_BACKWARD:
3590         case LFUN_CHAR_BACKWARD_SELECT:
3591         case LFUN_CHAR_LEFT:
3592         case LFUN_CHAR_LEFT_SELECT:
3593         case LFUN_CHAR_RIGHT:
3594         case LFUN_CHAR_RIGHT_SELECT:
3595         case LFUN_UP:
3596         case LFUN_UP_SELECT:
3597         case LFUN_DOWN:
3598         case LFUN_DOWN_SELECT:
3599         case LFUN_PARAGRAPH_SELECT:
3600         case LFUN_PARAGRAPH_UP_SELECT:
3601         case LFUN_PARAGRAPH_DOWN_SELECT:
3602         case LFUN_LINE_BEGIN_SELECT:
3603         case LFUN_LINE_END_SELECT:
3604         case LFUN_WORD_FORWARD_SELECT:
3605         case LFUN_WORD_BACKWARD_SELECT:
3606         case LFUN_WORD_RIGHT_SELECT:
3607         case LFUN_WORD_LEFT_SELECT:
3608         case LFUN_WORD_SELECT:
3609         case LFUN_SECTION_SELECT:
3610         case LFUN_BUFFER_BEGIN:
3611         case LFUN_BUFFER_END:
3612         case LFUN_BUFFER_BEGIN_SELECT:
3613         case LFUN_BUFFER_END_SELECT:
3614         case LFUN_INSET_BEGIN:
3615         case LFUN_INSET_END:
3616         case LFUN_INSET_BEGIN_SELECT:
3617         case LFUN_INSET_END_SELECT:
3618         case LFUN_PARAGRAPH_UP:
3619         case LFUN_PARAGRAPH_DOWN:
3620         case LFUN_LINE_BEGIN:
3621         case LFUN_LINE_END:
3622         case LFUN_CHAR_DELETE_FORWARD:
3623         case LFUN_CHAR_DELETE_BACKWARD:
3624         case LFUN_WORD_UPCASE:
3625         case LFUN_WORD_LOWCASE:
3626         case LFUN_WORD_CAPITALIZE:
3627         case LFUN_CHARS_TRANSPOSE:
3628         case LFUN_SERVER_GET_XY:
3629         case LFUN_SERVER_SET_XY:
3630         case LFUN_SERVER_GET_LAYOUT:
3631         case LFUN_SELF_INSERT:
3632         case LFUN_UNICODE_INSERT:
3633         case LFUN_THESAURUS_ENTRY:
3634         case LFUN_ESCAPE:
3635         case LFUN_SERVER_GET_STATISTICS:
3636                 // these are handled in our dispatch()
3637                 enable = true;
3638                 break;
3639
3640         case LFUN_INSET_INSERT: {
3641                 string const type = cmd.getArg(0);
3642                 if (type == "toc") {
3643                         code = TOC_CODE;
3644                         // not allowed in description items
3645                         //FIXME: couldn't this be merged in Inset::insetAllowed()?
3646                         enable = !inDescriptionItem(cur);
3647                 } else {
3648                         enable = true;
3649                 }
3650                 break;
3651         }
3652
3653         case LFUN_SEARCH_IGNORE: {
3654                 bool const value = cmd.getArg(1) == "true";
3655                 setIgnoreFormat(cmd.getArg(0), value);
3656                 break;
3657         }
3658
3659         default:
3660                 return false;
3661         }
3662
3663         if (code != NO_CODE
3664             && (cur.empty()
3665                 || !cur.inset().insetAllowed(code)
3666                 || (cur.paragraph().layout().pass_thru && !allow_in_passthru)))
3667                 enable = false;
3668
3669         flag.setEnabled(enable);
3670         return true;
3671 }
3672
3673
3674 void Text::pasteString(Cursor & cur, docstring const & clip,
3675                 bool asParagraphs)
3676 {
3677         if (!clip.empty()) {
3678                 cur.recordUndo();
3679                 if (asParagraphs)
3680                         insertStringAsParagraphs(cur, clip, cur.current_font);
3681                 else
3682                         insertStringAsLines(cur, clip, cur.current_font);
3683         }
3684 }
3685
3686
3687 // FIXME: an item inset would make things much easier.
3688 bool Text::inDescriptionItem(Cursor const & cur) const
3689 {
3690         Paragraph const & par = cur.paragraph();
3691         pos_type const pos = cur.pos();
3692         pos_type const body_pos = par.beginOfBody();
3693
3694         if (par.layout().latextype != LATEX_LIST_ENVIRONMENT
3695             && (par.layout().latextype != LATEX_ITEM_ENVIRONMENT
3696                 || par.layout().margintype != MARGIN_FIRST_DYNAMIC))
3697                 return false;
3698
3699         return (pos < body_pos
3700                 || (pos == body_pos
3701                     && (pos == 0 || par.getChar(pos - 1) != ' ')));
3702 }
3703
3704
3705 std::vector<docstring> Text::getFreeFonts() const
3706 {
3707         vector<docstring> ffList;
3708
3709         for (auto const & f : freeFonts)
3710                 ffList.push_back(f.first);
3711
3712         return ffList;
3713 }
3714
3715 } // namespace lyx