]> git.lyx.org Git - features.git/blob - src/Text3.cpp
0d7aa48a01e11b29b0aaecf830f51bb56e61974a
[features.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         cur.setCurrentFont();
135 }
136
137
138 static void finishChange(Cursor & cur, bool selecting)
139 {
140         cur.finishUndo();
141         moveCursor(cur, selecting);
142 }
143
144
145 static void mathDispatch(Cursor & cur, FuncRequest const & cmd)
146 {
147         cur.recordUndo();
148         docstring sel = cur.selectionAsString(false);
149
150         // It may happen that sel is empty but there is a selection
151         replaceSelection(cur);
152
153         // Is this a valid formula?
154         bool valid = true;
155
156         if (sel.empty()) {
157 #ifdef ENABLE_ASSERTIONS
158                 const int old_pos = cur.pos();
159 #endif
160                 cur.insert(new InsetMathHull(cur.buffer(), hullSimple));
161 #ifdef ENABLE_ASSERTIONS
162                 LATTEST(old_pos == cur.pos());
163 #endif
164                 cur.nextInset()->edit(cur, true);
165                 if (cmd.action() != LFUN_MATH_MODE)
166                         // LFUN_MATH_MODE has a different meaning in math mode
167                         cur.dispatch(cmd);
168         } else {
169                 InsetMathHull * formula = new InsetMathHull(cur.buffer());
170                 string const selstr = to_utf8(sel);
171                 istringstream is(selstr);
172                 Lexer lex;
173                 lex.setStream(is);
174                 if (!formula->readQuiet(lex)) {
175                         // No valid formula, let's try with delims
176                         is.str("$" + selstr + "$");
177                         lex.setStream(is);
178                         if (!formula->readQuiet(lex)) {
179                                 // Still not valid, leave it as is
180                                 valid = false;
181                                 delete formula;
182                                 cur.insert(sel);
183                         }
184                 }
185                 if (valid) {
186                         cur.insert(formula);
187                         cur.nextInset()->edit(cur, true);
188                         LASSERT(cur.inMathed(), return);
189                         cur.pos() = 0;
190                         cur.resetAnchor();
191                         cur.selection(true);
192                         cur.pos() = cur.lastpos();
193                         if (cmd.action() != LFUN_MATH_MODE)
194                                 // LFUN_MATH_MODE has a different meaning in math mode
195                                 cur.dispatch(cmd);
196                         cur.clearSelection();
197                         cur.pos() = cur.lastpos();
198                 }
199         }
200         if (valid)
201                 cur.message(from_utf8(N_("Math editor mode")));
202         else
203                 cur.message(from_utf8(N_("No valid math formula")));
204 }
205
206
207 void regexpDispatch(Cursor & cur, FuncRequest const & cmd)
208 {
209         LASSERT(cmd.action() == LFUN_REGEXP_MODE, return);
210         if (cur.inRegexped()) {
211                 cur.message(_("Already in regular expression mode"));
212                 return;
213         }
214         cur.recordUndo();
215         docstring sel = cur.selectionAsString(false);
216
217         // It may happen that sel is empty but there is a selection
218         replaceSelection(cur);
219
220         cur.insert(new InsetMathHull(cur.buffer(), hullRegexp));
221         cur.nextInset()->edit(cur, true);
222         cur.niceInsert(sel);
223
224         cur.message(_("Regexp editor mode"));
225 }
226
227
228 static void specialChar(Cursor & cur, InsetSpecialChar::Kind kind)
229 {
230         cur.recordUndo();
231         cap::replaceSelection(cur);
232         cur.insert(new InsetSpecialChar(kind));
233         cur.posForward();
234 }
235
236
237 static void ipaChar(Cursor & cur, InsetIPAChar::Kind kind)
238 {
239         cur.recordUndo();
240         cap::replaceSelection(cur);
241         cur.insert(new InsetIPAChar(kind));
242         cur.posForward();
243 }
244
245
246 static bool doInsertInset(Cursor & cur, Text * text,
247         FuncRequest const & cmd, bool edit, bool pastesel)
248 {
249         Buffer & buffer = cur.bv().buffer();
250         BufferParams const & bparams = buffer.params();
251         Inset * inset = createInset(&buffer, cmd);
252         if (!inset)
253                 return false;
254
255         if (InsetCollapsible * ci = inset->asInsetCollapsible())
256                 ci->setButtonLabel();
257
258         cur.recordUndo();
259         if (cmd.action() == LFUN_ARGUMENT_INSERT) {
260                 bool cotextinsert = false;
261                 InsetArgument const * const ia = static_cast<InsetArgument const *>(inset);
262                 Layout const & lay = cur.paragraph().layout();
263                 Layout::LaTeXArgMap args = lay.args();
264                 Layout::LaTeXArgMap::const_iterator const lait = args.find(ia->name());
265                 if (lait != args.end())
266                         cotextinsert = (*lait).second.insertcotext;
267                 else {
268                         InsetLayout const & il = cur.inset().getLayout();
269                         args = il.args();
270                         Layout::LaTeXArgMap::const_iterator const ilait = args.find(ia->name());
271                         if (ilait != args.end())
272                                 cotextinsert = (*ilait).second.insertcotext;
273                 }
274                 // The argument requests to insert a copy of the co-text to the inset
275                 if (cotextinsert) {
276                         docstring ds;
277                         // If we have a selection within a paragraph, use this
278                         if (cur.selection() && cur.selBegin().pit() == cur.selEnd().pit())
279                                 ds = cur.selectionAsString(false);
280                         // else use the whole paragraph
281                         else
282                                 ds = cur.paragraph().asString();
283                         text->insertInset(cur, inset);
284                         if (edit)
285                                 inset->edit(cur, true);
286                         // Now put co-text into inset
287                         Font const f(inherit_font, cur.current_font.language());
288                         if (!ds.empty()) {
289                                 cur.text()->insertStringAsLines(cur, ds, f);
290                                 cur.leaveInset(*inset);
291                         }
292                         return true;
293                 }
294         }
295
296         bool gotsel = false;
297         bool move_layout = false;
298         if (cur.selection()) {
299                 if (cmd.action() == LFUN_INDEX_INSERT)
300                         copySelectionToTemp(cur);
301                 else {
302                         cutSelectionToTemp(cur, pastesel);
303                         /* Move layout information inside the inset if the whole
304                          * paragraph and the inset allows setting layout
305                          * FIXME: this does not work as expected when change tracking is on
306                          *   However, we do not really know what to do in this case.
307                          */
308                         if (cur.paragraph().empty() && !inset->forcePlainLayout()) {
309                                 cur.paragraph().setPlainOrDefaultLayout(bparams.documentClass());
310                                 move_layout = true;
311                         }
312                 }
313                 cur.clearSelection();
314                 gotsel = true;
315         } else if (cmd.action() == LFUN_INDEX_INSERT) {
316                 gotsel = text->selectWordWhenUnderCursor(cur, WHOLE_WORD);
317                 copySelectionToTemp(cur);
318                 cur.clearSelection();
319         }
320         text->insertInset(cur, inset);
321
322         if (edit)
323                 inset->edit(cur, true);
324
325         if (!gotsel || !pastesel)
326                 return true;
327
328         pasteFromTemp(cur, cur.buffer()->errorList("Paste"));
329         cur.buffer()->errors("Paste");
330         cur.clearSelection(); // bug 393
331         cur.finishUndo();
332         InsetText * inset_text = inset->asInsetText();
333         if (inset_text) {
334                 inset_text->fixParagraphsFont();
335                 cur.pos() = 0;
336                 cur.pit() = 0;
337                 /* If the containing paragraph has kept its layout, reset the
338                  * layout of the first paragraph of the inset.
339                  */
340                 if (!move_layout)
341                         cur.paragraph().setPlainOrDefaultLayout(bparams.documentClass());
342                 // FIXME: what does this do?
343                 if (cmd.action() == LFUN_FLEX_INSERT)
344                         return true;
345                 Cursor old = cur;
346                 cur.leaveInset(*inset);
347                 if (cmd.action() == LFUN_PREVIEW_INSERT
348                         || cmd.action() == LFUN_IPA_INSERT)
349                         // trigger preview
350                         notifyCursorLeavesOrEnters(old, cur);
351         } else {
352                 cur.leaveInset(*inset);
353                 // reset surrounding par to default
354                 DocumentClass const & dc = bparams.documentClass();
355                 docstring const layoutname = inset->usePlainLayout()
356                         ? dc.plainLayoutName()
357                         : dc.defaultLayoutName();
358                 text->setLayout(cur, layoutname);
359         }
360         return true;
361 }
362
363
364 /// the type of outline operation
365 enum OutlineOp {
366         OutlineUp, // Move this header with text down
367         OutlineDown,   // Move this header with text up
368         OutlineIn, // Make this header deeper
369         OutlineOut // Make this header shallower
370 };
371
372
373 static void insertSeparator(Cursor & cur, depth_type const depth)
374 {
375         Buffer & buf = *cur.buffer();
376         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK));
377         DocumentClass const & tc = buf.params().documentClass();
378         lyx::dispatch(FuncRequest(LFUN_LAYOUT, from_ascii("\"") + tc.plainLayout().name()
379                                   + from_ascii("\" ignoreautonests")));
380         // FIXME: Bibitem mess!
381         if (cur.prevInset() && cur.prevInset()->lyxCode() == BIBITEM_CODE)
382                 lyx::dispatch(FuncRequest(LFUN_CHAR_DELETE_BACKWARD));
383         lyx::dispatch(FuncRequest(LFUN_SEPARATOR_INSERT, "plain"));
384         while (cur.paragraph().params().depth() > depth)
385                 lyx::dispatch(FuncRequest(LFUN_DEPTH_DECREMENT));
386 }
387
388
389 static void outline(OutlineOp mode, Cursor & cur, Text * text)
390 {
391         Buffer & buf = *cur.buffer();
392         pit_type & pit = cur.pit();
393         ParagraphList & pars = buf.text().paragraphs();
394         ParagraphList::iterator const bgn = pars.begin();
395         // The first paragraph of the area to be copied:
396         ParagraphList::iterator start = pars.iterator_at(pit);
397         // The final paragraph of area to be copied:
398         ParagraphList::iterator finish = start;
399         ParagraphList::iterator const end = pars.end();
400         depth_type const current_depth = cur.paragraph().params().depth();
401
402         int const thistoclevel = buf.text().getTocLevel(distance(bgn, start));
403         int toclevel;
404
405         // Move out (down) from this section header
406         if (finish != end)
407                 ++finish;
408
409         // Seek the one (on same level) below
410         for (; finish != end; ++finish) {
411                 toclevel = buf.text().getTocLevel(distance(bgn, finish));
412                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
413                         break;
414         }
415
416         switch (mode) {
417                 case OutlineUp: {
418                         if (start == pars.begin())
419                                 // Nothing to move.
420                                 return;
421                         ParagraphList::iterator dest = start;
422                         // Move out (up) from this header
423                         if (dest == bgn)
424                                 return;
425                         // Search previous same-level header above
426                         do {
427                                 --dest;
428                                 toclevel = buf.text().getTocLevel(distance(bgn, dest));
429                         } while(dest != bgn
430                                 && (toclevel == Layout::NOT_IN_TOC
431                                     || toclevel > thistoclevel));
432                         // Not found; do nothing
433                         if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
434                                 return;
435                         pit_type newpit = distance(bgn, dest);
436                         pit_type const len = distance(start, finish);
437                         pit_type const deletepit = pit + len;
438                         buf.undo().recordUndo(cur, newpit, deletepit - 1);
439                         // If we move an environment upwards, make sure it is
440                         // separated from its new neighbour below:
441                         // If an environment of the same layout follows, and the moved
442                         // paragraph sequence does not end with a separator, insert one.
443                         ParagraphList::iterator lastmoved = finish;
444                         --lastmoved;
445                         if (start->layout().isEnvironment()
446                             && dest->layout() == start->layout()
447                             && !lastmoved->isEnvSeparator(lastmoved->beginOfBody())) {
448                                 cur.pit() = distance(bgn, lastmoved);
449                                 cur.pos() = cur.lastpos();
450                                 insertSeparator(cur, current_depth);
451                                 cur.pit() = pit;
452                         }
453                         // Likewise, if we moved an environment upwards, make sure it
454                         // is separated from its new neighbour above.
455                         // The paragraph before the target of movement
456                         if (dest != bgn) {
457                                 ParagraphList::iterator before = dest;
458                                 --before;
459                                 // Get the parent paragraph (outer in nested context)
460                                 pit_type const parent =
461                                         before->params().depth() > current_depth
462                                                 ? text->depthHook(distance(bgn, before), current_depth)
463                                                 : distance(bgn, before);
464                                 // If a environment with same layout preceeds the moved one in the new
465                                 // position, and there is no separator yet, insert one.
466                                 if (start->layout().isEnvironment()
467                                     && pars[parent].layout() == start->layout()
468                                     && !before->isEnvSeparator(before->beginOfBody())) {
469                                         cur.pit() = distance(bgn, before);
470                                         cur.pos() = cur.lastpos();
471                                         insertSeparator(cur, current_depth);
472                                         cur.pit() = pit;
473                                 }
474                         }
475                         newpit = distance(bgn, dest);
476                         pars.splice(dest, start, finish);
477                         cur.pit() = newpit;
478                         break;
479                 }
480                 case OutlineDown: {
481                         if (finish == end)
482                                 // Nothing to move.
483                                 return;
484                         // Go one down from *this* header:
485                         ParagraphList::iterator dest = next(finish, 1);
486                         // Go further down to find header to insert in front of:
487                         for (; dest != end; ++dest) {
488                                 toclevel = buf.text().getTocLevel(distance(bgn, dest));
489                                 if (toclevel != Layout::NOT_IN_TOC
490                                       && toclevel <= thistoclevel)
491                                         break;
492                         }
493                         // One such was found, so go on...
494                         // If we move an environment downwards, make sure it is
495                         // separated from its new neighbour above.
496                         pit_type newpit = distance(bgn, dest);
497                         buf.undo().recordUndo(cur, pit, newpit - 1);
498                         // The paragraph before the target of movement
499                         ParagraphList::iterator before = dest;
500                         --before;
501                         // Get the parent paragraph (outer in nested context)
502                         pit_type const parent =
503                                 before->params().depth() > current_depth
504                                         ? text->depthHook(distance(bgn, before), current_depth)
505                                         : distance(bgn, before);
506                         // If a environment with same layout preceeds the moved one in the new
507                         // position, and there is no separator yet, insert one.
508                         if (start->layout().isEnvironment()
509                             && pars[parent].layout() == start->layout()
510                             && !before->isEnvSeparator(before->beginOfBody())) {
511                                 cur.pit() = distance(bgn, before);
512                                 cur.pos() = cur.lastpos();
513                                 insertSeparator(cur, current_depth);
514                                 cur.pit() = pit;
515                         }
516                         // Likewise, make sure moved environments are separated
517                         // from their new neighbour below:
518                         // If an environment of the same layout follows, and the moved
519                         // paragraph sequence does not end with a separator, insert one.
520                         ParagraphList::iterator lastmoved = finish;
521                         --lastmoved;
522                         if (dest != end
523                             && start->layout().isEnvironment()
524                             && dest->layout() == start->layout()
525                             && !lastmoved->isEnvSeparator(lastmoved->beginOfBody())) {
526                                 cur.pit() = distance(bgn, lastmoved);
527                                 cur.pos() = cur.lastpos();
528                                 insertSeparator(cur, current_depth);
529                                 cur.pit() = pit;
530                         }
531                         newpit = distance(bgn, dest);
532                         pit_type const len = distance(start, finish);
533                         pars.splice(dest, start, finish);
534                         cur.pit() = newpit - len;
535                         break;
536                 }
537                 case OutlineIn:
538                 case OutlineOut: {
539                         pit_type const len = distance(start, finish);
540                         buf.undo().recordUndo(cur, pit, pit + len - 1);
541                         for (; start != finish; ++start) {
542                                 toclevel = buf.text().getTocLevel(distance(bgn, start));
543                                 if (toclevel == Layout::NOT_IN_TOC)
544                                         continue;
545
546                                 DocumentClass const & tc = buf.params().documentClass();
547                                 int const newtoclevel =
548                                         (mode == OutlineIn ? toclevel + 1 : toclevel - 1);
549                                 LabelType const oldlabeltype = start->layout().labeltype;
550
551                                 for (auto const & lay : tc) {
552                                         if (lay.toclevel ==  newtoclevel &&
553                                                  lay.labeltype == oldlabeltype) {
554                                                 start->setLayout(lay);
555                                                 break;
556                                         }
557                                 }
558                         }
559                         break;
560                 }
561         }
562 }
563
564
565 void Text::number(Cursor & cur)
566 {
567         FontInfo font = ignore_font;
568         font.setNumber(FONT_TOGGLE);
569         toggleAndShow(cur, this, Font(font, ignore_language));
570 }
571
572
573 bool Text::isRTL(pit_type const pit) const
574 {
575         Buffer const & buffer = owner_->buffer();
576         return pars_[pit].isRTL(buffer.params());
577 }
578
579
580 namespace {
581
582 Language const * getLanguage(Cursor const & cur, string const & lang)
583 {
584         return lang.empty() ? cur.getFont().language() : languages.getLanguage(lang);
585 }
586
587
588 docstring resolveLayout(docstring layout, DocIterator const & dit)
589 {
590         Paragraph const & par = dit.paragraph();
591         DocumentClass const & tclass = dit.buffer()->params().documentClass();
592
593         if (layout.empty())
594                 layout = tclass.defaultLayoutName();
595
596         if (dit.inset().forcePlainLayout(dit.idx()))
597                 // in this case only the empty layout is allowed
598                 layout = tclass.plainLayoutName();
599         else if (par.usePlainLayout()) {
600                 // in this case, default layout maps to empty layout
601                 if (layout == tclass.defaultLayoutName())
602                         layout = tclass.plainLayoutName();
603         } else {
604                 // otherwise, the empty layout maps to the default
605                 if (layout == tclass.plainLayoutName())
606                         layout = tclass.defaultLayoutName();
607         }
608
609         // If the entry is obsolete, use the new one instead.
610         if (tclass.hasLayout(layout)) {
611                 docstring const & obs = tclass[layout].obsoleted_by();
612                 if (!obs.empty())
613                         layout = obs;
614         }
615         if (!tclass.hasLayout(layout))
616                 layout.clear();
617         return layout;
618 }
619
620
621 bool isAlreadyLayout(docstring const & layout, CursorData const & cur)
622 {
623         ParagraphList const & pars = cur.text()->paragraphs();
624
625         pit_type pit = cur.selBegin().pit();
626         pit_type const epit = cur.selEnd().pit() + 1;
627         for ( ; pit != epit; ++pit)
628                 if (pars[pit].layout().name() != layout)
629                         return false;
630
631         return true;
632 }
633
634
635 } // namespace
636
637
638 void Text::dispatch(Cursor & cur, FuncRequest & cmd)
639 {
640         LYXERR(Debug::ACTION, "Text::dispatch: cmd: " << cmd);
641
642         // Dispatch if the cursor is inside the text. It is not the
643         // case for context menus (bug 5797).
644         if (cur.text() != this) {
645                 cur.undispatched();
646                 return;
647         }
648
649         BufferView * bv = &cur.bv();
650         TextMetrics * tm = &bv->textMetrics(this);
651         if (!tm->contains(cur.pit())) {
652                 lyx::dispatch(FuncRequest(LFUN_SCREEN_SHOW_CURSOR));
653                 tm = &bv->textMetrics(this);
654         }
655
656         // FIXME: We use the update flag to indicates wether a singlePar or a
657         // full screen update is needed. We reset it here but shall we restore it
658         // at the end?
659         cur.noScreenUpdate();
660
661         LBUFERR(this == cur.text());
662
663         // NOTE: This should NOT be a reference. See commit 94a5481a.
664         CursorSlice const oldTopSlice = cur.top();
665         bool const oldBoundary = cur.boundary();
666         bool const oldSelection = cur.selection();
667         // Signals that, even if needsUpdate == false, an update of the
668         // cursor paragraph is required
669         bool singleParUpdate = lyxaction.funcHasFlag(cmd.action(),
670                 LyXAction::SingleParUpdate);
671         // Signals that a full-screen update is required
672         bool needsUpdate = !(lyxaction.funcHasFlag(cmd.action(),
673                 LyXAction::NoUpdate) || singleParUpdate);
674         bool const last_misspelled = lyxrc.spellcheck_continuously
675                 && cur.paragraph().isMisspelled(cur.pos(), true);
676
677         FuncCode const act = cmd.action();
678         switch (act) {
679
680         case LFUN_PARAGRAPH_MOVE_DOWN: {
681                 pit_type const pit = cur.pit();
682                 cur.recordUndo(pit, pit + 1);
683                 pars_.swap(pit, pit + 1);
684                 needsUpdate = true;
685                 cur.forceBufferUpdate();
686                 ++cur.pit();
687                 break;
688         }
689
690         case LFUN_PARAGRAPH_MOVE_UP: {
691                 pit_type const pit = cur.pit();
692                 cur.recordUndo(pit - 1, pit);
693                 cur.finishUndo();
694                 pars_.swap(pit, pit - 1);
695                 --cur.pit();
696                 needsUpdate = true;
697                 cur.forceBufferUpdate();
698                 break;
699         }
700
701         case LFUN_APPENDIX: {
702                 Paragraph & par = cur.paragraph();
703                 bool start = !par.params().startOfAppendix();
704
705 // FIXME: The code below only makes sense at top level.
706 // Should LFUN_APPENDIX be restricted to top-level paragraphs?
707                 // ensure that we have only one start_of_appendix in this document
708                 // FIXME: this don't work for multipart document!
709                 for (pit_type tmp = 0, end = pars_.size(); tmp != end; ++tmp) {
710                         if (pars_[tmp].params().startOfAppendix()) {
711                                 cur.recordUndo(tmp, tmp);
712                                 pars_[tmp].params().startOfAppendix(false);
713                                 break;
714                         }
715                 }
716
717                 cur.recordUndo();
718                 par.params().startOfAppendix(start);
719
720                 // we can set the refreshing parameters now
721                 cur.forceBufferUpdate();
722                 break;
723         }
724
725         case LFUN_WORD_DELETE_FORWARD:
726                 if (cur.selection())
727                         cutSelection(cur, false);
728                 else
729                         deleteWordForward(cur, cmd.getArg(0) == "force");
730                 finishChange(cur, false);
731                 break;
732
733         case LFUN_WORD_DELETE_BACKWARD:
734                 if (cur.selection())
735                         cutSelection(cur, false);
736                 else
737                         deleteWordBackward(cur, cmd.getArg(0) == "force");
738                 finishChange(cur, false);
739                 break;
740
741         case LFUN_LINE_DELETE_FORWARD:
742                 if (cur.selection())
743                         cutSelection(cur, false);
744                 else
745                         tm->deleteLineForward(cur);
746                 finishChange(cur, false);
747                 break;
748
749         case LFUN_BUFFER_BEGIN:
750         case LFUN_BUFFER_BEGIN_SELECT:
751                 needsUpdate |= cur.selHandle(act == LFUN_BUFFER_BEGIN_SELECT);
752                 if (cur.depth() == 1)
753                         needsUpdate |= cursorTop(cur);
754                 else
755                         cur.undispatched();
756                 cur.screenUpdateFlags(Update::FitCursor);
757                 break;
758
759         case LFUN_BUFFER_END:
760         case LFUN_BUFFER_END_SELECT:
761                 needsUpdate |= cur.selHandle(act == LFUN_BUFFER_END_SELECT);
762                 if (cur.depth() == 1)
763                         needsUpdate |= cursorBottom(cur);
764                 else
765                         cur.undispatched();
766                 cur.screenUpdateFlags(Update::FitCursor);
767                 break;
768
769         case LFUN_INSET_BEGIN:
770         case LFUN_INSET_BEGIN_SELECT:
771                 needsUpdate |= cur.selHandle(act == LFUN_INSET_BEGIN_SELECT);
772                 if (cur.depth() == 1 || !cur.top().at_begin())
773                         needsUpdate |= cursorTop(cur);
774                 else
775                         cur.undispatched();
776                 cur.screenUpdateFlags(Update::FitCursor);
777                 break;
778
779         case LFUN_INSET_END:
780         case LFUN_INSET_END_SELECT:
781                 needsUpdate |= cur.selHandle(act == LFUN_INSET_END_SELECT);
782                 if (cur.depth() == 1 || !cur.top().at_end())
783                         needsUpdate |= cursorBottom(cur);
784                 else
785                         cur.undispatched();
786                 cur.screenUpdateFlags(Update::FitCursor);
787                 break;
788
789         case LFUN_CHAR_FORWARD:
790         case LFUN_CHAR_FORWARD_SELECT: {
791                 //LYXERR0(" LFUN_CHAR_FORWARD[SEL]:\n" << cur);
792                 needsUpdate |= cur.selHandle(act == LFUN_CHAR_FORWARD_SELECT);
793                 bool const cur_moved = cursorForward(cur);
794                 needsUpdate |= cur_moved;
795
796                 if (!cur_moved && oldTopSlice == cur.top()
797                                && cur.boundary() == oldBoundary) {
798                         cur.undispatched();
799                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
800
801                         // we will probably be moving out the inset, so we should execute
802                         // the depm-mechanism, but only when the cursor has a place to
803                         // go outside this inset, i.e. in a slice above.
804                         if (cur.depth() > 1 && cur.pos() == cur.lastpos()
805                                   && cur.pit() == cur.lastpit()) {
806                                 // The cursor hasn't changed yet. To give the
807                                 // DEPM the possibility of doing something we must
808                                 // provide it with two different cursors.
809                                 Cursor dummy = cur;
810                                 dummy.pos() = dummy.pit() = 0;
811                                 if (cur.bv().checkDepm(dummy, cur))
812                                         cur.forceBufferUpdate();
813                         }
814                 }
815                 break;
816         }
817
818         case LFUN_CHAR_BACKWARD:
819         case LFUN_CHAR_BACKWARD_SELECT: {
820                 //lyxerr << "handle LFUN_CHAR_BACKWARD[_SELECT]:\n" << cur << endl;
821                 needsUpdate |= cur.selHandle(act == LFUN_CHAR_BACKWARD_SELECT);
822                 bool const cur_moved = cursorBackward(cur);
823                 needsUpdate |= cur_moved;
824
825                 if (!cur_moved && oldTopSlice == cur.top()
826                                && cur.boundary() == oldBoundary) {
827                         cur.undispatched();
828                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
829
830                         // we will probably be moving out the inset, so we should execute
831                         // the depm-mechanism, but only when the cursor has a place to
832                         // go outside this inset, i.e. in a slice above.
833                         if (cur.depth() > 1 && cur.pos() == 0 && cur.pit() == 0) {
834                                 // The cursor hasn't changed yet. To give the
835                                 // DEPM the possibility of doing something we must
836                                 // provide it with two different cursors.
837                                 Cursor dummy = cur;
838                                 dummy.pos() = cur.lastpos();
839                                 dummy.pit() = cur.lastpit();
840                                 if (cur.bv().checkDepm(dummy, cur))
841                                         cur.forceBufferUpdate();
842                         }
843                 }
844                 break;
845         }
846
847         case LFUN_CHAR_LEFT:
848         case LFUN_CHAR_LEFT_SELECT:
849                 if (lyxrc.visual_cursor) {
850                         needsUpdate |= cur.selHandle(act == LFUN_CHAR_LEFT_SELECT);
851                         bool const cur_moved = cursorVisLeft(cur);
852                         needsUpdate |= cur_moved;
853                         if (!cur_moved && oldTopSlice == cur.top()
854                                        && cur.boundary() == oldBoundary) {
855                                 cur.undispatched();
856                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
857                         }
858                 } else {
859                         if (cur.reverseDirectionNeeded()) {
860                                 cmd.setAction(cmd.action() == LFUN_CHAR_LEFT_SELECT ?
861                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD);
862                         } else {
863                                 cmd.setAction(cmd.action() == LFUN_CHAR_LEFT_SELECT ?
864                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD);
865                         }
866                         dispatch(cur, cmd);
867                         return;
868                 }
869                 break;
870
871         case LFUN_CHAR_RIGHT:
872         case LFUN_CHAR_RIGHT_SELECT:
873                 if (lyxrc.visual_cursor) {
874                         needsUpdate |= cur.selHandle(cmd.action() == LFUN_CHAR_RIGHT_SELECT);
875                         bool const cur_moved = cursorVisRight(cur);
876                         needsUpdate |= cur_moved;
877                         if (!cur_moved && oldTopSlice == cur.top()
878                                        && cur.boundary() == oldBoundary) {
879                                 cur.undispatched();
880                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
881                         }
882                 } else {
883                         if (cur.reverseDirectionNeeded()) {
884                                 cmd.setAction(cmd.action() == LFUN_CHAR_RIGHT_SELECT ?
885                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD);
886                         } else {
887                                 cmd.setAction(cmd.action() == LFUN_CHAR_RIGHT_SELECT ?
888                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD);
889                         }
890                         dispatch(cur, cmd);
891                         return;
892                 }
893                 break;
894
895
896         case LFUN_UP_SELECT:
897         case LFUN_DOWN_SELECT:
898         case LFUN_UP:
899         case LFUN_DOWN: {
900                 // stop/start the selection
901                 bool select = cmd.action() == LFUN_DOWN_SELECT ||
902                         cmd.action() == LFUN_UP_SELECT;
903
904                 // move cursor up/down
905                 bool up = cmd.action() == LFUN_UP_SELECT || cmd.action() == LFUN_UP;
906                 bool const atFirstOrLastRow = cur.atFirstOrLastRow(up);
907
908                 if (!atFirstOrLastRow) {
909                         needsUpdate |= cur.selHandle(select);
910                         cur.upDownInText(up, needsUpdate);
911                         needsUpdate |= cur.beforeDispatchCursor().inMathed();
912                 } else {
913                         pos_type newpos = up ? 0 : cur.lastpos();
914                         if (lyxrc.mac_like_cursor_movement && cur.pos() != newpos) {
915                                 needsUpdate |= cur.selHandle(select);
916                                 // we do not reset the targetx of the cursor
917                                 cur.pos() = newpos;
918                                 needsUpdate |= bv->checkDepm(cur, bv->cursor());
919                                 cur.updateTextTargetOffset();
920                                 if (needsUpdate)
921                                         cur.forceBufferUpdate();
922                                 break;
923                         }
924
925                         // if the cursor cannot be moved up or down do not remove
926                         // the selection right now, but wait for the next dispatch.
927                         if (select)
928                                 needsUpdate |= cur.selHandle(select);
929                         cur.upDownInText(up, needsUpdate);
930                         cur.undispatched();
931                 }
932
933                 break;
934         }
935
936         case LFUN_PARAGRAPH_SELECT:
937                 if (cur.pos() > 0)
938                         needsUpdate |= setCursor(cur, cur.pit(), 0);
939                 needsUpdate |= cur.selHandle(true);
940                 if (cur.pos() < cur.lastpos())
941                         needsUpdate |= setCursor(cur, cur.pit(), cur.lastpos());
942                 break;
943
944         case LFUN_PARAGRAPH_UP:
945         case LFUN_PARAGRAPH_UP_SELECT:
946                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_PARAGRAPH_UP_SELECT);
947                 needsUpdate |= cursorUpParagraph(cur);
948                 break;
949
950         case LFUN_PARAGRAPH_DOWN:
951         case LFUN_PARAGRAPH_DOWN_SELECT:
952                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_PARAGRAPH_DOWN_SELECT);
953                 needsUpdate |= cursorDownParagraph(cur);
954                 break;
955
956         case LFUN_LINE_BEGIN:
957         case LFUN_LINE_BEGIN_SELECT:
958                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_LINE_BEGIN_SELECT);
959                 needsUpdate |= tm->cursorHome(cur);
960                 break;
961
962         case LFUN_LINE_END:
963         case LFUN_LINE_END_SELECT:
964                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_LINE_END_SELECT);
965                 needsUpdate |= tm->cursorEnd(cur);
966                 break;
967
968         case LFUN_SECTION_SELECT: {
969                 Buffer const & buf = *cur.buffer();
970                 pit_type const pit = cur.pit();
971                 ParagraphList & pars = buf.text().paragraphs();
972                 ParagraphList::iterator bgn = pars.begin();
973                 // The first paragraph of the area to be selected:
974                 ParagraphList::iterator start = pars.iterator_at(pit);
975                 // The final paragraph of area to be selected:
976                 ParagraphList::iterator finish = start;
977                 ParagraphList::iterator end = pars.end();
978
979                 int const thistoclevel = buf.text().getTocLevel(distance(bgn, start));
980                 if (thistoclevel == Layout::NOT_IN_TOC)
981                         break;
982
983                 cur.pos() = 0;
984                 Cursor const old_cur = cur;
985                 needsUpdate |= cur.selHandle(true);
986
987                 // Move out (down) from this section header
988                 if (finish != end)
989                         ++finish;
990
991                 // Seek the one (on same level) below
992                 for (; finish != end; ++finish, ++cur.pit()) {
993                         int const toclevel = buf.text().getTocLevel(distance(bgn, finish));
994                         if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
995                                 break;
996                 }
997                 cur.pos() = cur.lastpos();
998                 cur.boundary(false);
999                 cur.setCurrentFont();
1000
1001                 needsUpdate |= cur != old_cur;
1002                 break;
1003         }
1004
1005         case LFUN_WORD_RIGHT:
1006         case LFUN_WORD_RIGHT_SELECT:
1007                 if (lyxrc.visual_cursor) {
1008                         needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_RIGHT_SELECT);
1009                         bool const cur_moved = cursorVisRightOneWord(cur);
1010                         needsUpdate |= cur_moved;
1011                         if (!cur_moved && oldTopSlice == cur.top()
1012                                        && cur.boundary() == oldBoundary) {
1013                                 cur.undispatched();
1014                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
1015                         }
1016                 } else {
1017                         if (cur.reverseDirectionNeeded()) {
1018                                 cmd.setAction(cmd.action() == LFUN_WORD_RIGHT_SELECT ?
1019                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD);
1020                         } else {
1021                                 cmd.setAction(cmd.action() == LFUN_WORD_RIGHT_SELECT ?
1022                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD);
1023                         }
1024                         dispatch(cur, cmd);
1025                         return;
1026                 }
1027                 break;
1028
1029         case LFUN_WORD_FORWARD:
1030         case LFUN_WORD_FORWARD_SELECT: {
1031                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_FORWARD_SELECT);
1032                 bool const cur_moved = cursorForwardOneWord(cur);
1033                 needsUpdate |= cur_moved;
1034
1035                 if (!cur_moved && oldTopSlice == cur.top()
1036                                && cur.boundary() == oldBoundary) {
1037                         cur.undispatched();
1038                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
1039
1040                         // we will probably be moving out the inset, so we should execute
1041                         // the depm-mechanism, but only when the cursor has a place to
1042                         // go outside this inset, i.e. in a slice above.
1043                         if (cur.depth() > 1 && cur.pos() == cur.lastpos()
1044                                   && cur.pit() == cur.lastpit()) {
1045                                 // The cursor hasn't changed yet. To give the
1046                                 // DEPM the possibility of doing something we must
1047                                 // provide it with two different cursors.
1048                                 Cursor dummy = cur;
1049                                 dummy.pos() = dummy.pit() = 0;
1050                                 if (cur.bv().checkDepm(dummy, cur))
1051                                         cur.forceBufferUpdate();
1052                         }
1053                 }
1054                 break;
1055         }
1056
1057         case LFUN_WORD_LEFT:
1058         case LFUN_WORD_LEFT_SELECT:
1059                 if (lyxrc.visual_cursor) {
1060                         needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_LEFT_SELECT);
1061                         bool const cur_moved = cursorVisLeftOneWord(cur);
1062                         needsUpdate |= cur_moved;
1063                         if (!cur_moved && oldTopSlice == cur.top()
1064                                        && cur.boundary() == oldBoundary) {
1065                                 cur.undispatched();
1066                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
1067                         }
1068                 } else {
1069                         if (cur.reverseDirectionNeeded()) {
1070                                 cmd.setAction(cmd.action() == LFUN_WORD_LEFT_SELECT ?
1071                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD);
1072                         } else {
1073                                 cmd.setAction(cmd.action() == LFUN_WORD_LEFT_SELECT ?
1074                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD);
1075                         }
1076                         dispatch(cur, cmd);
1077                         return;
1078                 }
1079                 break;
1080
1081         case LFUN_WORD_BACKWARD:
1082         case LFUN_WORD_BACKWARD_SELECT: {
1083                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_BACKWARD_SELECT);
1084                 bool const cur_moved = cursorBackwardOneWord(cur);
1085                 needsUpdate |= cur_moved;
1086
1087                 if (!cur_moved && oldTopSlice == cur.top()
1088                                && cur.boundary() == oldBoundary) {
1089                         cur.undispatched();
1090                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
1091
1092                         // we will probably be moving out the inset, so we should execute
1093                         // the depm-mechanism, but only when the cursor has a place to
1094                         // go outside this inset, i.e. in a slice above.
1095                         if (cur.depth() > 1 && cur.pos() == 0
1096                                   && cur.pit() == 0) {
1097                                 // The cursor hasn't changed yet. To give the
1098                                 // DEPM the possibility of doing something we must
1099                                 // provide it with two different cursors.
1100                                 Cursor dummy = cur;
1101                                 dummy.pos() = cur.lastpos();
1102                                 dummy.pit() = cur.lastpit();
1103                                 if (cur.bv().checkDepm(dummy, cur))
1104                                         cur.forceBufferUpdate();
1105                         }
1106                 }
1107                 break;
1108         }
1109
1110         case LFUN_WORD_SELECT: {
1111                 selectWord(cur, WHOLE_WORD);
1112                 finishChange(cur, true);
1113                 break;
1114         }
1115
1116         case LFUN_NEWLINE_INSERT: {
1117                 InsetNewlineParams inp;
1118                 docstring arg = cmd.argument();
1119                 if (arg == "linebreak")
1120                         inp.kind = InsetNewlineParams::LINEBREAK;
1121                 else
1122                         inp.kind = InsetNewlineParams::NEWLINE;
1123                 cap::replaceSelection(cur);
1124                 cur.recordUndo();
1125                 cur.insert(new InsetNewline(inp));
1126                 cur.posForward();
1127                 moveCursor(cur, false);
1128                 break;
1129         }
1130
1131         case LFUN_TAB_INSERT: {
1132                 bool const multi_par_selection = cur.selection() &&
1133                         cur.selBegin().pit() != cur.selEnd().pit();
1134                 if (multi_par_selection) {
1135                         // If there is a multi-paragraph selection, a tab is inserted
1136                         // at the beginning of each paragraph.
1137                         cur.recordUndoSelection();
1138                         pit_type const pit_end = cur.selEnd().pit();
1139                         for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
1140                                 pars_[pit].insertChar(0, '\t',
1141                                                       bv->buffer().params().track_changes);
1142                                 // Update the selection pos to make sure the selection does not
1143                                 // change as the inserted tab will increase the logical pos.
1144                                 if (cur.realAnchor().pit() == pit)
1145                                         cur.realAnchor().forwardPos();
1146                                 if (cur.pit() == pit)
1147                                         cur.forwardPos();
1148                         }
1149                         cur.finishUndo();
1150                 } else {
1151                         // Maybe we shouldn't allow tabs within a line, because they
1152                         // are not (yet) aligned as one might do expect.
1153                         FuncRequest ncmd(LFUN_SELF_INSERT, from_ascii("\t"));
1154                         dispatch(cur, ncmd);
1155                 }
1156                 break;
1157         }
1158
1159         case LFUN_TAB_DELETE: {
1160                 bool const tc = bv->buffer().params().track_changes;
1161                 if (cur.selection()) {
1162                         // If there is a selection, a tab (if present) is removed from
1163                         // the beginning of each paragraph.
1164                         cur.recordUndoSelection();
1165                         pit_type const pit_end = cur.selEnd().pit();
1166                         for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
1167                                 Paragraph & par = paragraphs()[pit];
1168                                 if (par.empty())
1169                                         continue;
1170                                 char_type const c = par.getChar(0);
1171                                 if (c == '\t' || c == ' ') {
1172                                         // remove either 1 tab or 4 spaces.
1173                                         int const n = (c == ' ' ? 4 : 1);
1174                                         for (int i = 0; i < n
1175                                                   && !par.empty() && par.getChar(0) == c; ++i) {
1176                                                 if (cur.pit() == pit)
1177                                                         cur.posBackward();
1178                                                 if (cur.realAnchor().pit() == pit
1179                                                           && cur.realAnchor().pos() > 0 )
1180                                                         cur.realAnchor().backwardPos();
1181                                                 par.eraseChar(0, tc);
1182                                         }
1183                                 }
1184                         }
1185                         cur.finishUndo();
1186                 } else {
1187                         // If there is no selection, try to remove a tab or some spaces
1188                         // before the position of the cursor.
1189                         Paragraph & par = paragraphs()[cur.pit()];
1190                         pos_type const pos = cur.pos();
1191
1192                         if (pos == 0)
1193                                 break;
1194
1195                         char_type const c = par.getChar(pos - 1);
1196                         cur.recordUndo();
1197                         if (c == '\t') {
1198                                 cur.posBackward();
1199                                 par.eraseChar(cur.pos(), tc);
1200                         } else
1201                                 for (int n_spaces = 0;
1202                                      cur.pos() > 0
1203                                              && par.getChar(cur.pos() - 1) == ' '
1204                                              && n_spaces < 4;
1205                                      ++n_spaces) {
1206                                         cur.posBackward();
1207                                         par.eraseChar(cur.pos(), tc);
1208                                 }
1209                         cur.finishUndo();
1210                 }
1211                 break;
1212         }
1213
1214         case LFUN_CHAR_DELETE_FORWARD:
1215                 if (!cur.selection()) {
1216                         if (cur.pos() == cur.paragraph().size())
1217                                 // Par boundary, force full-screen update
1218                                 singleParUpdate = false;
1219                         else if (cmd.getArg(0) != "force" && cur.confirmDeletion()) {
1220                                 cur.resetAnchor();
1221                                 cur.selection(true);
1222                                 cur.posForward();
1223                                 cur.setSelection();
1224                                 break;
1225                         }
1226                         needsUpdate |= erase(cur);
1227                         cur.resetAnchor();
1228                 } else {
1229                         cutSelection(cur, false);
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.size() && !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.clearSelection();
1965
1966                 for (char_type c : cmd.argument())
1967                         bv->translateAndInsert(c, this, cur);
1968
1969                 cur.resetAnchor();
1970                 moveCursor(cur, false);
1971                 cur.markNewWordPosition();
1972                 bv->bookmarkEditPosition();
1973                 break;
1974         }
1975
1976         case LFUN_HREF_INSERT: {
1977                 docstring content = cmd.argument();
1978                 if (content.empty() && cur.selection())
1979                         content = cur.selectionAsString(false);
1980
1981                 InsetCommandParams p(HYPERLINK_CODE);
1982                 if (!content.empty()){
1983                         // if it looks like a link, we'll put it as target,
1984                         // otherwise as name (bug #8792).
1985
1986                         // We can't do:
1987                         //   regex_match(to_utf8(content), matches, link_re)
1988                         // because smatch stores pointers to the substrings rather
1989                         // than making copies of them. And those pointers become
1990                         // invalid after regex_match returns, since it is then
1991                         // being given a temporary object. (Thanks to Georg for
1992                         // figuring that out.)
1993                         regex const link_re("^([a-z]+):.*");
1994                         smatch matches;
1995                         string const c = to_utf8(lowercase(content));
1996
1997                         if (c.substr(0,7) == "mailto:") {
1998                                 p["target"] = content;
1999                                 p["type"] = from_ascii("mailto:");
2000                         } else if (regex_match(c, matches, link_re)) {
2001                                 p["target"] = content;
2002                                 string protocol = matches.str(1);
2003                                 if (protocol == "file")
2004                                         p["type"] = from_ascii("file:");
2005                         } else
2006                                 p["name"] = content;
2007                 }
2008                 string const data = InsetCommand::params2string(p);
2009
2010                 // we need to have a target. if we already have one, then
2011                 // that gets used at the default for the name, too, which
2012                 // is probably what is wanted.
2013                 if (p["target"].empty()) {
2014                         bv->showDialog("href", data);
2015                 } else {
2016                         FuncRequest fr(LFUN_INSET_INSERT, data);
2017                         dispatch(cur, fr);
2018                 }
2019                 break;
2020         }
2021
2022         case LFUN_LABEL_INSERT: {
2023                 InsetCommandParams p(LABEL_CODE);
2024                 // Try to generate a valid label
2025                 p["name"] = (cmd.argument().empty()) ?
2026                         cur.getPossibleLabel() :
2027                         cmd.argument();
2028                 string const data = InsetCommand::params2string(p);
2029
2030                 if (cmd.argument().empty()) {
2031                         bv->showDialog("label", data);
2032                 } else {
2033                         FuncRequest fr(LFUN_INSET_INSERT, data);
2034                         dispatch(cur, fr);
2035                 }
2036                 break;
2037         }
2038
2039         case LFUN_INFO_INSERT: {
2040                 if (cmd.argument().empty()) {
2041                         bv->showDialog("info", cur.current_font.language()->lang());
2042                 } else {
2043                         Inset * inset;
2044                         inset = createInset(cur.buffer(), cmd);
2045                         if (!inset)
2046                                 break;
2047                         cur.recordUndo();
2048                         insertInset(cur, inset);
2049                         cur.forceBufferUpdate();
2050                         cur.posForward();
2051                 }
2052                 break;
2053         }
2054         case LFUN_CAPTION_INSERT:
2055         case LFUN_FOOTNOTE_INSERT:
2056         case LFUN_NOTE_INSERT:
2057         case LFUN_BOX_INSERT:
2058         case LFUN_BRANCH_INSERT:
2059         case LFUN_PHANTOM_INSERT:
2060         case LFUN_ERT_INSERT:
2061         case LFUN_LISTING_INSERT:
2062         case LFUN_MARGINALNOTE_INSERT:
2063         case LFUN_ARGUMENT_INSERT:
2064         case LFUN_INDEX_INSERT:
2065         case LFUN_PREVIEW_INSERT:
2066         case LFUN_SCRIPT_INSERT:
2067         case LFUN_IPA_INSERT:
2068                 // Open the inset, and move the current selection
2069                 // inside it.
2070                 doInsertInset(cur, this, cmd, true, true);
2071                 cur.posForward();
2072                 if (act == LFUN_SCRIPT_INSERT) {
2073                         /* Script insets change the font style in metrics(), and
2074                          * this is used to compute the height of the caret
2075                          * (because the font is stored in TextMetrics::font_).
2076                          * When we insert, we have to make sure that metrics are
2077                          * computed so that the caret height is wrong. Arguably,
2078                          * this is hackish.*/
2079                         bv->processUpdateFlags(Update::SinglePar);
2080                 }
2081                 cur.setCurrentFont();
2082                 // Some insets are numbered, others are shown in the outline pane so
2083                 // let's update the labels and the toc backend.
2084                 cur.forceBufferUpdate();
2085                 break;
2086
2087         case LFUN_FLEX_INSERT: {
2088                 // Open the inset, and move the current selection
2089                 // inside it.
2090                 bool const sel = cur.selection();
2091                 doInsertInset(cur, this, cmd, true, true);
2092                 // Insert auto-insert arguments
2093                 bool autoargs = false, inautoarg = false;
2094                 Layout::LaTeXArgMap args = cur.inset().getLayout().args();
2095                 for (auto const & argt : args) {
2096                         Layout::latexarg arg = argt.second;
2097                         if (!inautoarg && arg.insertonnewline && cur.pos() > 0) {
2098                                 FuncRequest cmd2(LFUN_PARAGRAPH_BREAK);
2099                                 lyx::dispatch(cmd2);
2100                         }
2101                         if (arg.autoinsert) {
2102                                 // The cursor might have been invalidated by the replaceSelection.
2103                                 cur.buffer()->changed(true);
2104                                 // If we had already inserted an arg automatically,
2105                                 // leave this now in order to insert the next one.
2106                                 if (inautoarg) {
2107                                         cur.leaveInset(cur.inset());
2108                                         cur.posForward();
2109                                         if (arg.insertonnewline && cur.pos() > 0) {
2110                                                 FuncRequest cmd2(LFUN_PARAGRAPH_BREAK);
2111                                                 lyx::dispatch(cmd2);
2112                                         }
2113                                 }
2114                                 FuncRequest cmd2(LFUN_ARGUMENT_INSERT, argt.first);
2115                                 lyx::dispatch(cmd2);
2116                                 autoargs = true;
2117                                 inautoarg = true;
2118                         }
2119                 }
2120                 if (!autoargs) {
2121                         if (sel)
2122                                 cur.leaveInset(cur.inset());
2123                         cur.posForward();
2124                 }
2125                 // Some insets are numbered, others are shown in the outline pane so
2126                 // let's update the labels and the toc backend.
2127                 cur.forceBufferUpdate();
2128                 break;
2129         }
2130
2131         case LFUN_TABULAR_INSERT: {
2132                 // if there were no arguments, just open the dialog
2133                 if (cmd.argument().empty()) {
2134                         bv->showDialog("tabularcreate");
2135                         break;
2136                 } else if (cur.buffer()->masterParams().tablestyle != "default"
2137                            || bv->buffer().params().documentClass().tablestyle() != "default") {
2138                         string tabstyle = cur.buffer()->masterParams().tablestyle;
2139                         if (tabstyle == "default")
2140                                 tabstyle = bv->buffer().params().documentClass().tablestyle();
2141                         if (!libFileSearch("tabletemplates", tabstyle + ".lyx").empty()) {
2142                                 FuncRequest fr(LFUN_TABULAR_STYLE_INSERT,
2143                                                tabstyle + " " + to_ascii(cmd.argument()));
2144                                 lyx::dispatch(fr);
2145                                 break;
2146                         } else
2147                                 // Unknown style. Report and fall back to default.
2148                                 cur.errorMessage(from_utf8(N_("Table Style ")) + from_utf8(tabstyle) +
2149                                                      from_utf8(N_(" not known")));
2150                         
2151                 }
2152                 if (doInsertInset(cur, this, cmd, false, true))
2153                         cur.posForward();
2154                 break;
2155         }
2156
2157         case LFUN_TABULAR_STYLE_INSERT: {
2158                 string const style = cmd.getArg(0);
2159                 string const rows = cmd.getArg(1);
2160                 string const cols = cmd.getArg(2);
2161                 if (cols.empty() || !isStrInt(cols)
2162                     || rows.empty() || !isStrInt(rows))
2163                         break;
2164                 int const r = convert<int>(rows);
2165                 int const c = convert<int>(cols);
2166                         
2167                 string suffix;
2168                 if (r == 1)
2169                         suffix = "_1x1";
2170                 else if (r == 2)
2171                         suffix = "_1x2";
2172                 FileName const tabstyle = libFileSearch("tabletemplates",
2173                                                         style + suffix + ".lyx", "lyx");
2174                 if (tabstyle.empty())
2175                             break;
2176                 UndoGroupHelper ugh(cur.buffer());
2177                 cur.recordUndo();
2178                 FuncRequest cmd2(LFUN_FILE_INSERT, tabstyle.absFileName() + " ignorelang");
2179                 lyx::dispatch(cmd2);
2180                 // go into table
2181                 cur.backwardPos();
2182                 if (r > 2) {
2183                         // move one cell up to middle cell
2184                         cur.up();
2185                         // add the missing rows
2186                         int const addrows = r - 3;
2187                         for (int i = 0 ; i < addrows ; ++i) {
2188                                 FuncRequest fr(LFUN_TABULAR_FEATURE, "append-row");
2189                                 lyx::dispatch(fr);
2190                         }
2191                 }
2192                 // add the missing columns
2193                 int const addcols = c - 1;
2194                 for (int i = 0 ; i < addcols ; ++i) {
2195                         FuncRequest fr(LFUN_TABULAR_FEATURE, "append-column");
2196                         lyx::dispatch(fr);
2197                 }
2198                 if (r > 1)
2199                         // go to first cell
2200                         cur.up();
2201                 break;
2202         }
2203
2204         case LFUN_FLOAT_INSERT:
2205         case LFUN_FLOAT_WIDE_INSERT:
2206         case LFUN_WRAP_INSERT: {
2207                 // will some content be moved into the inset?
2208                 bool const content = cur.selection();
2209                 // does the content consist of multiple paragraphs?
2210                 bool const singlepar = (cur.selBegin().pit() == cur.selEnd().pit());
2211
2212                 doInsertInset(cur, this, cmd, true, true);
2213                 cur.posForward();
2214
2215                 // If some single-par content is moved into the inset,
2216                 // doInsertInset puts the cursor outside the inset.
2217                 // To insert the caption we put it back into the inset.
2218                 // FIXME cleanup doInsertInset to avoid such dances!
2219                 if (content && singlepar)
2220                         cur.backwardPos();
2221
2222                 ParagraphList & pars = cur.text()->paragraphs();
2223
2224                 DocumentClass const & tclass = bv->buffer().params().documentClass();
2225
2226                 // add a separate paragraph for the caption inset
2227                 pars.push_back(Paragraph());
2228                 pars.back().setInsetOwner(&cur.text()->inset());
2229                 pars.back().setPlainOrDefaultLayout(tclass);
2230                 int cap_pit = pars.size() - 1;
2231
2232                 // if an empty inset was created, we create an additional empty
2233                 // paragraph at the bottom so that the user can choose where to put
2234                 // the graphics (or table).
2235                 if (!content) {
2236                         pars.push_back(Paragraph());
2237                         pars.back().setInsetOwner(&cur.text()->inset());
2238                         pars.back().setPlainOrDefaultLayout(tclass);
2239                 }
2240
2241                 // reposition the cursor to the caption
2242                 cur.pit() = cap_pit;
2243                 cur.pos() = 0;
2244                 // FIXME: This Text/Cursor dispatch handling is a mess!
2245                 // We cannot use Cursor::dispatch here it needs access to up to
2246                 // date metrics.
2247                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
2248                 doInsertInset(cur, cur.text(), cmd_caption, true, false);
2249                 cur.forceBufferUpdate();
2250                 cur.screenUpdateFlags(Update::Force);
2251                 // FIXME: When leaving the Float (or Wrap) inset we should
2252                 // delete any empty paragraph left above or below the
2253                 // caption.
2254                 break;
2255         }
2256
2257         case LFUN_NOMENCL_INSERT: {
2258                 InsetCommandParams p(NOMENCL_CODE);
2259                 if (cmd.argument().empty()) {
2260                         p["symbol"] = 
2261                                 bv->cursor().innerText()->getStringForDialog(bv->cursor());
2262                         cur.clearSelection();
2263                 } else
2264                         p["symbol"] = cmd.argument();
2265                 string const data = InsetCommand::params2string(p);
2266                 bv->showDialog("nomenclature", data);
2267                 break;
2268         }
2269
2270         case LFUN_INDEX_PRINT: {
2271                 InsetCommandParams p(INDEX_PRINT_CODE);
2272                 if (cmd.argument().empty())
2273                         p["type"] = from_ascii("idx");
2274                 else
2275                         p["type"] = cmd.argument();
2276                 string const data = InsetCommand::params2string(p);
2277                 FuncRequest fr(LFUN_INSET_INSERT, data);
2278                 dispatch(cur, fr);
2279                 break;
2280         }
2281
2282         case LFUN_NOMENCL_PRINT:
2283         case LFUN_NEWPAGE_INSERT:
2284                 // do nothing fancy
2285                 doInsertInset(cur, this, cmd, false, false);
2286                 cur.posForward();
2287                 break;
2288
2289         case LFUN_SEPARATOR_INSERT: {
2290                 doInsertInset(cur, this, cmd, false, false);
2291                 cur.posForward();
2292                 // remove a following space
2293                 Paragraph & par = cur.paragraph();
2294                 if (cur.pos() != cur.lastpos() && par.isLineSeparator(cur.pos()))
2295                     par.eraseChar(cur.pos(), cur.buffer()->params().track_changes);
2296                 break;
2297         }
2298
2299         case LFUN_DEPTH_DECREMENT:
2300                 changeDepth(cur, DEC_DEPTH);
2301                 break;
2302
2303         case LFUN_DEPTH_INCREMENT:
2304                 changeDepth(cur, INC_DEPTH);
2305                 break;
2306
2307         case LFUN_REGEXP_MODE:
2308                 regexpDispatch(cur, cmd);
2309                 break;
2310
2311         case LFUN_MATH_MODE: {
2312                 if (cmd.argument() == "on" || cmd.argument() == "") {
2313                         // don't pass "on" as argument
2314                         // (it would appear literally in the first cell)
2315                         docstring sel = cur.selectionAsString(false);
2316                         InsetMathMacroTemplate * macro = new InsetMathMacroTemplate(cur.buffer());
2317                         // create a macro template if we see "\\newcommand" somewhere, and
2318                         // an ordinary formula otherwise
2319                         if (!sel.empty()
2320                                 && (sel.find(from_ascii("\\newcommand")) != string::npos
2321                                         || sel.find(from_ascii("\\newlyxcommand")) != string::npos
2322                                         || sel.find(from_ascii("\\def")) != string::npos)
2323                                 && macro->fromString(sel)) {
2324                                 cur.recordUndo();
2325                                 replaceSelection(cur);
2326                                 cur.insert(macro);
2327                         } else {
2328                                 // no meaningful macro template was found
2329                                 delete macro;
2330                                 mathDispatch(cur,FuncRequest(LFUN_MATH_MODE));
2331                         }
2332                 } else
2333                         // The argument is meaningful
2334                         // We replace cmd with LFUN_MATH_INSERT because LFUN_MATH_MODE
2335                         // has a different meaning in math mode
2336                         mathDispatch(cur, FuncRequest(LFUN_MATH_INSERT,cmd.argument()));
2337                 break;
2338         }
2339
2340         case LFUN_MATH_MACRO:
2341                 if (cmd.argument().empty())
2342                         cur.errorMessage(from_utf8(N_("Missing argument")));
2343                 else {
2344                         cur.recordUndo();
2345                         string s = to_utf8(cmd.argument());
2346                         string const s1 = token(s, ' ', 1);
2347                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
2348                         string const s2 = token(s, ' ', 2);
2349                         MacroType type = MacroTypeNewcommand;
2350                         if (s2 == "def")
2351                                 type = MacroTypeDef;
2352                         InsetMathMacroTemplate * inset = new InsetMathMacroTemplate(cur.buffer(),
2353                                 from_utf8(token(s, ' ', 0)), nargs, false, type);
2354                         inset->setBuffer(bv->buffer());
2355                         insertInset(cur, inset);
2356
2357                         // enter macro inset and select the name
2358                         cur.push(*inset);
2359                         cur.top().pos() = cur.top().lastpos();
2360                         cur.resetAnchor();
2361                         cur.selection(true);
2362                         cur.top().pos() = 0;
2363                 }
2364                 break;
2365
2366         case LFUN_MATH_DISPLAY:
2367         case LFUN_MATH_SUBSCRIPT:
2368         case LFUN_MATH_SUPERSCRIPT:
2369         case LFUN_MATH_INSERT:
2370         case LFUN_MATH_AMS_MATRIX:
2371         case LFUN_MATH_MATRIX:
2372         case LFUN_MATH_DELIM:
2373         case LFUN_MATH_BIGDELIM:
2374                 mathDispatch(cur, cmd);
2375                 break;
2376
2377         case LFUN_FONT_EMPH: {
2378                 Font font(ignore_font, ignore_language);
2379                 font.fontInfo().setEmph(FONT_TOGGLE);
2380                 toggleAndShow(cur, this, font);
2381                 break;
2382         }
2383
2384         case LFUN_FONT_ITAL: {
2385                 Font font(ignore_font, ignore_language);
2386                 font.fontInfo().setShape(ITALIC_SHAPE);
2387                 toggleAndShow(cur, this, font);
2388                 break;
2389         }
2390
2391         case LFUN_FONT_BOLD:
2392         case LFUN_FONT_BOLDSYMBOL: {
2393                 Font font(ignore_font, ignore_language);
2394                 font.fontInfo().setSeries(BOLD_SERIES);
2395                 toggleAndShow(cur, this, font);
2396                 break;
2397         }
2398
2399         case LFUN_FONT_NOUN: {
2400                 Font font(ignore_font, ignore_language);
2401                 font.fontInfo().setNoun(FONT_TOGGLE);
2402                 toggleAndShow(cur, this, font);
2403                 break;
2404         }
2405
2406         case LFUN_FONT_TYPEWRITER: {
2407                 Font font(ignore_font, ignore_language);
2408                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
2409                 toggleAndShow(cur, this, font);
2410                 break;
2411         }
2412
2413         case LFUN_FONT_SANS: {
2414                 Font font(ignore_font, ignore_language);
2415                 font.fontInfo().setFamily(SANS_FAMILY);
2416                 toggleAndShow(cur, this, font);
2417                 break;
2418         }
2419
2420         case LFUN_FONT_ROMAN: {
2421                 Font font(ignore_font, ignore_language);
2422                 font.fontInfo().setFamily(ROMAN_FAMILY);
2423                 toggleAndShow(cur, this, font);
2424                 break;
2425         }
2426
2427         case LFUN_FONT_DEFAULT: {
2428                 Font font(inherit_font, ignore_language);
2429                 toggleAndShow(cur, this, font);
2430                 break;
2431         }
2432
2433         case LFUN_FONT_STRIKEOUT: {
2434                 Font font(ignore_font, ignore_language);
2435                 font.fontInfo().setStrikeout(FONT_TOGGLE);
2436                 toggleAndShow(cur, this, font);
2437                 break;
2438         }
2439
2440         case LFUN_FONT_CROSSOUT: {
2441                 Font font(ignore_font, ignore_language);
2442                 font.fontInfo().setXout(FONT_TOGGLE);
2443                 toggleAndShow(cur, this, font);
2444                 break;
2445         }
2446
2447         case LFUN_FONT_UNDERUNDERLINE: {
2448                 Font font(ignore_font, ignore_language);
2449                 font.fontInfo().setUuline(FONT_TOGGLE);
2450                 toggleAndShow(cur, this, font);
2451                 break;
2452         }
2453
2454         case LFUN_FONT_UNDERWAVE: {
2455                 Font font(ignore_font, ignore_language);
2456                 font.fontInfo().setUwave(FONT_TOGGLE);
2457                 toggleAndShow(cur, this, font);
2458                 break;
2459         }
2460
2461         case LFUN_FONT_UNDERLINE: {
2462                 Font font(ignore_font, ignore_language);
2463                 font.fontInfo().setUnderbar(FONT_TOGGLE);
2464                 toggleAndShow(cur, this, font);
2465                 break;
2466         }
2467
2468         case LFUN_FONT_SIZE: {
2469                 Font font(ignore_font, ignore_language);
2470                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
2471                 toggleAndShow(cur, this, font);
2472                 break;
2473         }
2474
2475         case LFUN_LANGUAGE: {
2476                 string const lang_arg = cmd.getArg(0);
2477                 bool const reset = (lang_arg.empty() || lang_arg == "reset");
2478                 Language const * lang =
2479                         reset ? reset_language
2480                               : languages.getLanguage(lang_arg);
2481                 // we allow reset_language, which is 0, but only if it
2482                 // was requested via empty or "reset" arg.
2483                 if (!lang && !reset)
2484                         break;
2485                 bool const toggle = (cmd.getArg(1) != "set");
2486                 selectWordWhenUnderCursor(cur, WHOLE_WORD_STRICT);
2487                 Font font(ignore_font, lang);
2488                 toggleAndShow(cur, this, font, toggle);
2489                 // We need a buffer update if we change the language
2490                 // of an info inset
2491                 if (cur.insetInSelection(INFO_CODE))
2492                         cur.forceBufferUpdate();
2493                 break;
2494         }
2495
2496         case LFUN_TEXTSTYLE_APPLY: {
2497                 unsigned int num = 0;
2498                 string const arg = to_utf8(cmd.argument());
2499                 // Argument?
2500                 if (!arg.empty()) {
2501                         if (isStrUnsignedInt(arg)) {
2502                                 num = convert<uint>(arg);
2503                                 if (num >= freeFonts.size()) {
2504                                         cur.message(_("Invalid argument (number exceeds stack size)!"));
2505                                         break;
2506                                 }
2507                         } else {
2508                                 cur.message(_("Invalid argument (must be a non-negative number)!"));
2509                                 break;
2510                         }
2511                 }
2512                 toggleAndShow(cur, this, freeFonts[num].second, toggleall);
2513                 cur.message(bformat(_("Text properties applied: %1$s"), freeFonts[num].first));
2514                 break;
2515         }
2516
2517         // Set the freefont using the contents of \param data dispatched from
2518         // the frontends and apply it at the current cursor location.
2519         case LFUN_TEXTSTYLE_UPDATE: {
2520                 Font font(ignore_font, ignore_language);
2521                 bool toggle;
2522                 if (font.fromString(to_utf8(cmd.argument()), toggle)) {
2523                         docstring const props = font.stateText(&bv->buffer().params(), true);
2524                         freeFonts.push(make_pair(props, font));
2525                         toggleall = toggle;
2526                         toggleAndShow(cur, this, font, toggleall);
2527                         // We need a buffer update if we change the language
2528                         // of an info inset
2529                         if (cur.insetInSelection(INFO_CODE))
2530                                 cur.forceBufferUpdate();
2531                         cur.message(bformat(_("Text properties applied: %1$s"), props));
2532                 } else
2533                         LYXERR0("Invalid argument of textstyle-update");
2534                 break;
2535         }
2536
2537         case LFUN_FINISHED_LEFT:
2538                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
2539                 // We're leaving an inset, going left. If the inset is LTR, we're
2540                 // leaving from the front, so we should not move (remain at --- but
2541                 // not in --- the inset). If the inset is RTL, move left, without
2542                 // entering the inset itself; i.e., move to after the inset.
2543                 if (cur.paragraph().getFontSettings(
2544                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
2545                         cursorVisLeft(cur, true);
2546                 break;
2547
2548         case LFUN_FINISHED_RIGHT:
2549                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
2550                 // We're leaving an inset, going right. If the inset is RTL, we're
2551                 // leaving from the front, so we should not move (remain at --- but
2552                 // not in --- the inset). If the inset is LTR, move right, without
2553                 // entering the inset itself; i.e., move to after the inset.
2554                 if (!cur.paragraph().getFontSettings(
2555                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
2556                         cursorVisRight(cur, true);
2557                 break;
2558
2559         case LFUN_FINISHED_BACKWARD:
2560                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
2561                 cur.setCurrentFont();
2562                 break;
2563
2564         case LFUN_FINISHED_FORWARD:
2565                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
2566                 ++cur.pos();
2567                 cur.setCurrentFont();
2568                 break;
2569
2570         case LFUN_LAYOUT_PARAGRAPH: {
2571                 string data;
2572                 params2string(cur.paragraph(), data);
2573                 data = "show\n" + data;
2574                 bv->showDialog("paragraph", data);
2575                 break;
2576         }
2577
2578         case LFUN_PARAGRAPH_UPDATE: {
2579                 string data;
2580                 params2string(cur.paragraph(), data);
2581
2582                 // Will the paragraph accept changes from the dialog?
2583                 bool const accept =
2584                         cur.inset().allowParagraphCustomization(cur.idx());
2585
2586                 data = "update " + convert<string>(accept) + '\n' + data;
2587                 bv->updateDialog("paragraph", data);
2588                 break;
2589         }
2590
2591         case LFUN_ACCENT_UMLAUT:
2592         case LFUN_ACCENT_CIRCUMFLEX:
2593         case LFUN_ACCENT_GRAVE:
2594         case LFUN_ACCENT_ACUTE:
2595         case LFUN_ACCENT_TILDE:
2596         case LFUN_ACCENT_PERISPOMENI:
2597         case LFUN_ACCENT_CEDILLA:
2598         case LFUN_ACCENT_MACRON:
2599         case LFUN_ACCENT_DOT:
2600         case LFUN_ACCENT_UNDERDOT:
2601         case LFUN_ACCENT_UNDERBAR:
2602         case LFUN_ACCENT_CARON:
2603         case LFUN_ACCENT_BREVE:
2604         case LFUN_ACCENT_TIE:
2605         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2606         case LFUN_ACCENT_CIRCLE:
2607         case LFUN_ACCENT_OGONEK:
2608                 theApp()->handleKeyFunc(cmd.action());
2609                 if (!cmd.argument().empty())
2610                         // FIXME: Are all these characters encoded in one byte in utf8?
2611                         bv->translateAndInsert(cmd.argument()[0], this, cur);
2612                 cur.screenUpdateFlags(Update::FitCursor);
2613                 break;
2614
2615         case LFUN_FLOAT_LIST_INSERT: {
2616                 DocumentClass const & tclass = bv->buffer().params().documentClass();
2617                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
2618                         cur.recordUndo();
2619                         if (cur.selection())
2620                                 cutSelection(cur, false);
2621                         breakParagraph(cur);
2622
2623                         if (cur.lastpos() != 0) {
2624                                 cursorBackward(cur);
2625                                 breakParagraph(cur);
2626                         }
2627
2628                         docstring const laystr = cur.inset().usePlainLayout() ?
2629                                 tclass.plainLayoutName() :
2630                                 tclass.defaultLayoutName();
2631                         setLayout(cur, laystr);
2632                         ParagraphParameters p;
2633                         // FIXME If this call were replaced with one to clearParagraphParams(),
2634                         // then we could get rid of this method altogether.
2635                         setParagraphs(cur, p);
2636                         // FIXME This should be simplified when InsetFloatList takes a
2637                         // Buffer in its constructor.
2638                         InsetFloatList * ifl = new InsetFloatList(cur.buffer(), to_utf8(cmd.argument()));
2639                         ifl->setBuffer(bv->buffer());
2640                         insertInset(cur, ifl);
2641                         cur.posForward();
2642                 } else {
2643                         lyxerr << "Non-existent float type: "
2644                                << to_utf8(cmd.argument()) << endl;
2645                 }
2646                 break;
2647         }
2648
2649         case LFUN_CHANGE_ACCEPT: {
2650                 acceptOrRejectChanges(cur, ACCEPT);
2651                 break;
2652         }
2653
2654         case LFUN_CHANGE_REJECT: {
2655                 acceptOrRejectChanges(cur, REJECT);
2656                 break;
2657         }
2658
2659         case LFUN_THESAURUS_ENTRY: {
2660                 Language const * language = cur.getFont().language();
2661                 docstring arg = cmd.argument();
2662                 if (arg.empty()) {
2663                         arg = cur.selectionAsString(false);
2664                         // FIXME
2665                         if (arg.size() > 100 || arg.empty()) {
2666                                 // Get word or selection
2667                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2668                                 arg = cur.selectionAsString(false);
2669                                 arg += " lang=" + from_ascii(language->lang());
2670                         }
2671                 } else {
2672                         string lang = cmd.getArg(1);
2673                         // This duplicates the code in GuiThesaurus::initialiseParams
2674                         if (prefixIs(lang, "lang=")) {
2675                                 language = languages.getLanguage(lang.substr(5));
2676                                 if (!language)
2677                                         language = cur.getFont().language();
2678                         }
2679                 }
2680                 string lang = language->code();
2681                 if (lyxrc.thesaurusdir_path.empty() && !thesaurus.thesaurusInstalled(from_ascii(lang))) {
2682                         LYXERR(Debug::ACTION, "Command " << cmd << ". Thesaurus not found for language " << lang);
2683                         frontend::Alert::warning(_("Path to thesaurus directory not set!"),
2684                                         _("The path to the thesaurus directory has not been specified.\n"
2685                                           "The thesaurus is not functional.\n"
2686                                           "Please refer to sec. 6.15.1 of the User's Guide for setup\n"
2687                                           "instructions."));
2688                 }
2689                 bv->showDialog("thesaurus", to_utf8(arg));
2690                 break;
2691         }
2692
2693         case LFUN_SPELLING_ADD: {
2694                 Language const * language = getLanguage(cur, cmd.getArg(1));
2695                 docstring word = from_utf8(cmd.getArg(0));
2696                 if (word.empty()) {
2697                         word = cur.selectionAsString(false);
2698                         // FIXME
2699                         if (word.size() > 100 || word.empty()) {
2700                                 // Get word or selection
2701                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2702                                 word = cur.selectionAsString(false);
2703                         }
2704                 }
2705                 WordLangTuple wl(word, language);
2706                 theSpellChecker()->insert(wl);
2707                 break;
2708         }
2709
2710         case LFUN_SPELLING_IGNORE: {
2711                 Language const * language = getLanguage(cur, cmd.getArg(1));
2712                 docstring word = from_utf8(cmd.getArg(0));
2713                 if (word.empty()) {
2714                         word = cur.selectionAsString(false);
2715                         // FIXME
2716                         if (word.size() > 100 || word.empty()) {
2717                                 // Get word or selection
2718                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2719                                 word = cur.selectionAsString(false);
2720                         }
2721                 }
2722                 WordLangTuple wl(word, language);
2723                 theSpellChecker()->accept(wl);
2724                 break;
2725         }
2726
2727         case LFUN_SPELLING_REMOVE: {
2728                 Language const * language = getLanguage(cur, cmd.getArg(1));
2729                 docstring word = from_utf8(cmd.getArg(0));
2730                 if (word.empty()) {
2731                         word = cur.selectionAsString(false);
2732                         // FIXME
2733                         if (word.size() > 100 || word.empty()) {
2734                                 // Get word or selection
2735                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2736                                 word = cur.selectionAsString(false);
2737                         }
2738                 }
2739                 WordLangTuple wl(word, language);
2740                 theSpellChecker()->remove(wl);
2741                 break;
2742         }
2743
2744         case LFUN_PARAGRAPH_PARAMS_APPLY: {
2745                 // Given data, an encoding of the ParagraphParameters
2746                 // generated in the Paragraph dialog, this function sets
2747                 // the current paragraph, or currently selected paragraphs,
2748                 // appropriately.
2749                 // NOTE: This function overrides all existing settings.
2750                 setParagraphs(cur, cmd.argument());
2751                 cur.message(_("Paragraph layout set"));
2752                 break;
2753         }
2754
2755         case LFUN_PARAGRAPH_PARAMS: {
2756                 // Given data, an encoding of the ParagraphParameters as we'd
2757                 // find them in a LyX file, this function modifies the current paragraph,
2758                 // or currently selected paragraphs.
2759                 // NOTE: This function only modifies, and does not override, existing
2760                 // settings.
2761                 setParagraphs(cur, cmd.argument(), true);
2762                 cur.message(_("Paragraph layout set"));
2763                 break;
2764         }
2765
2766         case LFUN_ESCAPE:
2767                 if (cur.selection()) {
2768                         cur.selection(false);
2769                 } else {
2770                         cur.undispatched();
2771                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
2772                         // correct, but I'm not 100% sure -- dov, 071019
2773                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
2774                 }
2775                 break;
2776
2777         case LFUN_OUTLINE_UP: {
2778                 pos_type const opos = cur.pos();
2779                 outline(OutlineUp, cur, this);
2780                 setCursor(cur, cur.pit(), opos);
2781                 cur.forceBufferUpdate();
2782                 needsUpdate = true;
2783                 break;
2784         }
2785
2786         case LFUN_OUTLINE_DOWN: {
2787                 pos_type const opos = cur.pos();
2788                 outline(OutlineDown, cur, this);
2789                 setCursor(cur, cur.pit(), opos);
2790                 cur.forceBufferUpdate();
2791                 needsUpdate = true;
2792                 break;
2793         }
2794
2795         case LFUN_OUTLINE_IN:
2796                 outline(OutlineIn, cur, this);
2797                 cur.forceBufferUpdate();
2798                 needsUpdate = true;
2799                 break;
2800
2801         case LFUN_OUTLINE_OUT:
2802                 outline(OutlineOut, cur, this);
2803                 cur.forceBufferUpdate();
2804                 needsUpdate = true;
2805                 break;
2806
2807         case LFUN_SERVER_GET_STATISTICS:
2808                 {
2809                         DocIterator from, to;
2810                         if (cur.selection()) {
2811                                 from = cur.selectionBegin();
2812                                 to = cur.selectionEnd();
2813                         } else {
2814                                 from = doc_iterator_begin(cur.buffer());
2815                                 to = doc_iterator_end(cur.buffer());
2816                         }
2817
2818                         cur.buffer()->updateStatistics(from, to);
2819                         string const arg0 = cmd.getArg(0);
2820                         if (arg0 == "words") {
2821                                 cur.message(convert<docstring>(cur.buffer()->wordCount()));
2822                         } else if (arg0 == "chars") {
2823                                 cur.message(convert<docstring>(cur.buffer()->charCount(false)));
2824                         } else if (arg0 == "chars-space") {
2825                                 cur.message(convert<docstring>(cur.buffer()->charCount(true)));
2826                         } else {
2827                                 cur.message(convert<docstring>(cur.buffer()->wordCount()) + " "
2828                                 + convert<docstring>(cur.buffer()->charCount(false)) + " "
2829                                 + convert<docstring>(cur.buffer()->charCount(true)));
2830                         }
2831                 }
2832                 break;
2833
2834         default:
2835                 LYXERR(Debug::ACTION, "Command " << cmd << " not DISPATCHED by Text");
2836                 cur.undispatched();
2837                 break;
2838         }
2839
2840         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
2841
2842         if (lyxrc.spellcheck_continuously && !needsUpdate) {
2843                 // Check for misspelled text
2844                 // The redraw is useful because of the painting of
2845                 // misspelled markers depends on the cursor position.
2846                 // Trigger a redraw for cursor moves inside misspelled text.
2847                 if (!cur.inTexted()) {
2848                         // move from regular text to math
2849                         needsUpdate = last_misspelled;
2850                 } else if (oldTopSlice != cur.top() || oldBoundary != cur.boundary()) {
2851                         // move inside regular text
2852                         needsUpdate = last_misspelled
2853                                 || cur.paragraph().isMisspelled(cur.pos(), true);
2854                 }
2855         }
2856
2857         // FIXME: The cursor flag is reset two lines below
2858         // so we need to check here if some of the LFUN did touch that.
2859         // for now only Text::erase() and Text::backspace() do that.
2860         // The plan is to verify all the LFUNs and then to remove this
2861         // singleParUpdate boolean altogether.
2862         if (cur.result().screenUpdate() & Update::Force) {
2863                 singleParUpdate = false;
2864                 needsUpdate = true;
2865         }
2866
2867         // FIXME: the following code should go in favor of fine grained
2868         // update flag treatment.
2869         if (singleParUpdate) {
2870                 // Inserting characters does not change par height in general. So, try
2871                 // to update _only_ this paragraph. BufferView will detect if a full
2872                 // metrics update is needed anyway.
2873                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
2874                 return;
2875         }
2876         if (!needsUpdate
2877             && &oldTopSlice.inset() == &cur.inset()
2878             && oldTopSlice.idx() == cur.idx()
2879             && !oldSelection // oldSelection is a backup of cur.selection() at the beginning of the function.
2880             && !cur.selection())
2881                 // FIXME: it would be better if we could just do this
2882                 //
2883                 //if (cur.result().update() != Update::FitCursor)
2884                 //      cur.noScreenUpdate();
2885                 //
2886                 // But some LFUNs do not set Update::FitCursor when needed, so we
2887                 // do it for all. This is not very harmfull as FitCursor will provoke
2888                 // a full redraw only if needed but still, a proper review of all LFUN
2889                 // should be done and this needsUpdate boolean can then be removed.
2890                 cur.screenUpdateFlags(Update::FitCursor);
2891         else
2892                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
2893 }
2894
2895
2896 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
2897                         FuncStatus & flag) const
2898 {
2899         LBUFERR(this == cur.text());
2900
2901         FontInfo const & fontinfo = cur.real_current_font.fontInfo();
2902         bool enable = true;
2903         bool allow_in_passthru = false;
2904         InsetCode code = NO_CODE;
2905         
2906         switch (cmd.action()) {
2907
2908         case LFUN_DEPTH_DECREMENT:
2909                 enable = changeDepthAllowed(cur, DEC_DEPTH);
2910                 break;
2911
2912         case LFUN_DEPTH_INCREMENT:
2913                 enable = changeDepthAllowed(cur, INC_DEPTH);
2914                 break;
2915
2916         case LFUN_APPENDIX:
2917                 // FIXME We really should not allow this to be put, e.g.,
2918                 // in a footnote, or in ERT. But it would make sense in a
2919                 // branch, so I'm not sure what to do.
2920                 flag.setOnOff(cur.paragraph().params().startOfAppendix());
2921                 break;
2922
2923         case LFUN_DIALOG_SHOW_NEW_INSET:
2924                 if (cmd.argument() == "bibitem")
2925                         code = BIBITEM_CODE;
2926                 else if (cmd.argument() == "bibtex") {
2927                         code = BIBTEX_CODE;
2928                         // not allowed in description items
2929                         enable = !inDescriptionItem(cur);
2930                 }
2931                 else if (cmd.argument() == "box")
2932                         code = BOX_CODE;
2933                 else if (cmd.argument() == "branch")
2934                         code = BRANCH_CODE;
2935                 else if (cmd.argument() == "citation")
2936                         code = CITE_CODE;
2937                 else if (cmd.argument() == "ert")
2938                         code = ERT_CODE;
2939                 else if (cmd.argument() == "external")
2940                         code = EXTERNAL_CODE;
2941                 else if (cmd.argument() == "float")
2942                         code = FLOAT_CODE;
2943                 else if (cmd.argument() == "graphics")
2944                         code = GRAPHICS_CODE;
2945                 else if (cmd.argument() == "href")
2946                         code = HYPERLINK_CODE;
2947                 else if (cmd.argument() == "include")
2948                         code = INCLUDE_CODE;
2949                 else if (cmd.argument() == "index")
2950                         code = INDEX_CODE;
2951                 else if (cmd.argument() == "index_print")
2952                         code = INDEX_PRINT_CODE;
2953                 else if (cmd.argument() == "listings")
2954                         code = LISTINGS_CODE;
2955                 else if (cmd.argument() == "mathspace")
2956                         code = MATH_HULL_CODE;
2957                 else if (cmd.argument() == "nomenclature")
2958                         code = NOMENCL_CODE;
2959                 else if (cmd.argument() == "nomencl_print")
2960                         code = NOMENCL_PRINT_CODE;
2961                 else if (cmd.argument() == "label")
2962                         code = LABEL_CODE;
2963                 else if (cmd.argument() == "line")
2964                         code = LINE_CODE;
2965                 else if (cmd.argument() == "note")
2966                         code = NOTE_CODE;
2967                 else if (cmd.argument() == "phantom")
2968                         code = PHANTOM_CODE;
2969                 else if (cmd.argument() == "ref")
2970                         code = REF_CODE;
2971                 else if (cmd.argument() == "space")
2972                         code = SPACE_CODE;
2973                 else if (cmd.argument() == "toc")
2974                         code = TOC_CODE;
2975                 else if (cmd.argument() == "vspace")
2976                         code = VSPACE_CODE;
2977                 else if (cmd.argument() == "wrap")
2978                         code = WRAP_CODE;
2979                 break;
2980
2981         case LFUN_ERT_INSERT:
2982                 code = ERT_CODE;
2983                 break;
2984         case LFUN_LISTING_INSERT:
2985                 code = LISTINGS_CODE;
2986                 // not allowed in description items
2987                 enable = !inDescriptionItem(cur);
2988                 break;
2989         case LFUN_FOOTNOTE_INSERT:
2990                 code = FOOT_CODE;
2991                 break;
2992         case LFUN_TABULAR_INSERT:
2993                 code = TABULAR_CODE;
2994                 break;
2995         case LFUN_TABULAR_STYLE_INSERT:
2996                 code = TABULAR_CODE;
2997                 break;
2998         case LFUN_MARGINALNOTE_INSERT:
2999                 code = MARGIN_CODE;
3000                 break;
3001         case LFUN_FLOAT_INSERT:
3002         case LFUN_FLOAT_WIDE_INSERT:
3003                 // FIXME: If there is a selection, we should check whether there
3004                 // are floats in the selection, but this has performance issues, see
3005                 // LFUN_CHANGE_ACCEPT/REJECT.
3006                 code = FLOAT_CODE;
3007                 if (inDescriptionItem(cur))
3008                         // not allowed in description items
3009                         enable = false;
3010                 else {
3011                         InsetCode const inset_code = cur.inset().lyxCode();
3012
3013                         // algorithm floats cannot be put in another float
3014                         if (to_utf8(cmd.argument()) == "algorithm") {
3015                                 enable = inset_code != WRAP_CODE && inset_code != FLOAT_CODE;
3016                                 break;
3017                         }
3018
3019                         // for figures and tables: only allow in another
3020                         // float or wrap if it is of the same type and
3021                         // not a subfloat already
3022                         if(cur.inset().lyxCode() == code) {
3023                                 InsetFloat const & ins =
3024                                         static_cast<InsetFloat const &>(cur.inset());
3025                                 enable = ins.params().type == to_utf8(cmd.argument())
3026                                         && !ins.params().subfloat;
3027                         } else if(cur.inset().lyxCode() == WRAP_CODE) {
3028                                 InsetWrap const & ins =
3029                                         static_cast<InsetWrap const &>(cur.inset());
3030                                 enable = ins.params().type == to_utf8(cmd.argument());
3031                         }
3032                 }
3033                 break;
3034         case LFUN_WRAP_INSERT:
3035                 code = WRAP_CODE;
3036                 // not allowed in description items
3037                 enable = !inDescriptionItem(cur);
3038                 break;
3039         case LFUN_FLOAT_LIST_INSERT: {
3040                 code = FLOAT_LIST_CODE;
3041                 // not allowed in description items
3042                 enable = !inDescriptionItem(cur);
3043                 if (enable) {
3044                         FloatList const & floats = cur.buffer()->params().documentClass().floats();
3045                         FloatList::const_iterator cit = floats[to_ascii(cmd.argument())];
3046                         // make sure we know about such floats
3047                         if (cit == floats.end() ||
3048                                         // and that we know how to generate a list of them
3049                             (!cit->second.usesFloatPkg() && cit->second.listCommand().empty())) {
3050                                 flag.setUnknown(true);
3051                                 // probably not necessary, but...
3052                                 enable = false;
3053                         }
3054                 }
3055                 break;
3056         }
3057         case LFUN_CAPTION_INSERT: {
3058                 code = CAPTION_CODE;
3059                 string arg = cmd.getArg(0);
3060                 bool varia = arg != "Unnumbered"
3061                         && cur.inset().allowsCaptionVariation(arg);
3062                 // not allowed in description items,
3063                 // and in specific insets
3064                 enable = !inDescriptionItem(cur)
3065                         && (varia || arg.empty() || arg == "Standard");
3066                 break;
3067         }
3068         case LFUN_NOTE_INSERT:
3069                 code = NOTE_CODE;
3070                 break;
3071         case LFUN_FLEX_INSERT: {
3072                 code = FLEX_CODE;
3073                 string s = cmd.getArg(0);
3074                 InsetLayout il =
3075                         cur.buffer()->params().documentClass().insetLayout(from_utf8(s));
3076                 if (il.lyxtype() != InsetLayout::CHARSTYLE &&
3077                     il.lyxtype() != InsetLayout::CUSTOM &&
3078                     il.lyxtype ()!= InsetLayout::STANDARD)
3079                         enable = false;
3080                 break;
3081                 }
3082         case LFUN_BOX_INSERT:
3083                 code = BOX_CODE;
3084                 break;
3085         case LFUN_BRANCH_INSERT:
3086                 code = BRANCH_CODE;
3087                 if (cur.buffer()->masterBuffer()->params().branchlist().empty()
3088                     && cur.buffer()->params().branchlist().empty())
3089                         enable = false;
3090                 break;
3091         case LFUN_IPA_INSERT:
3092                 code = IPA_CODE;
3093                 break;
3094         case LFUN_PHANTOM_INSERT:
3095                 code = PHANTOM_CODE;
3096                 break;
3097         case LFUN_LABEL_INSERT:
3098                 code = LABEL_CODE;
3099                 break;
3100         case LFUN_INFO_INSERT:
3101                 code = INFO_CODE;
3102                 enable = cmd.argument().empty()
3103                         || infoparams.validateArgument(cur.buffer(), cmd.argument(), true);
3104                 break;
3105         case LFUN_ARGUMENT_INSERT: {
3106                 code = ARG_CODE;
3107                 allow_in_passthru = true;
3108                 string const arg = cmd.getArg(0);
3109                 if (arg.empty()) {
3110                         enable = false;
3111                         break;
3112                 }
3113                 Layout const & lay = cur.paragraph().layout();
3114                 Layout::LaTeXArgMap args = lay.args();
3115                 Layout::LaTeXArgMap::const_iterator const lait =
3116                                 args.find(arg);
3117                 if (lait != args.end()) {
3118                         enable = true;
3119                         pit_type pit = cur.pit();
3120                         pit_type lastpit = cur.pit();
3121                         if (lay.isEnvironment() && !prefixIs(arg, "item:")) {
3122                                 // In a sequence of "merged" environment layouts, we only allow
3123                                 // non-item arguments once.
3124                                 lastpit = cur.lastpit();
3125                                 // get the first paragraph in sequence with this layout
3126                                 depth_type const current_depth = cur.paragraph().params().depth();
3127                                 while (true) {
3128                                         if (pit == 0)
3129                                                 break;
3130                                         Paragraph cpar = pars_[pit - 1];
3131                                         if (cpar.layout() == lay && cpar.params().depth() == current_depth)
3132                                                 --pit;
3133                                         else
3134                                                 break;
3135                                 }
3136                         }
3137                         for (; pit <= lastpit; ++pit) {
3138                                 if (pars_[pit].layout() != lay)
3139                                         break;
3140                                 for (auto const & table : pars_[pit].insetList())
3141                                         if (InsetArgument const * ins = table.inset->asInsetArgument())
3142                                                 if (ins->name() == arg) {
3143                                                         // we have this already
3144                                                         enable = false;
3145                                                         break;
3146                                                 }
3147                         }
3148                 } else
3149                         enable = false;
3150                 break;
3151         }
3152         case LFUN_INDEX_INSERT:
3153                 code = INDEX_CODE;
3154                 break;
3155         case LFUN_INDEX_PRINT:
3156                 code = INDEX_PRINT_CODE;
3157                 // not allowed in description items
3158                 enable = !inDescriptionItem(cur);
3159                 break;
3160         case LFUN_NOMENCL_INSERT:
3161                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
3162                         enable = false;
3163                         break;
3164                 }
3165                 code = NOMENCL_CODE;
3166                 break;
3167         case LFUN_NOMENCL_PRINT:
3168                 code = NOMENCL_PRINT_CODE;
3169                 // not allowed in description items
3170                 enable = !inDescriptionItem(cur);
3171                 break;
3172         case LFUN_HREF_INSERT:
3173                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
3174                         enable = false;
3175                         break;
3176                 }
3177                 code = HYPERLINK_CODE;
3178                 break;
3179         case LFUN_IPAMACRO_INSERT: {
3180                 string const arg = cmd.getArg(0);
3181                 if (arg == "deco")
3182                         code = IPADECO_CODE;
3183                 else
3184                         code = IPACHAR_CODE;
3185                 break;
3186         }
3187         case LFUN_QUOTE_INSERT:
3188                 // always allow this, since we will inset a raw quote
3189                 // if an inset is not allowed.
3190                 allow_in_passthru = true;
3191                 break;
3192         case LFUN_SPECIALCHAR_INSERT:
3193                 code = SPECIALCHAR_CODE;
3194                 break;
3195         case LFUN_SPACE_INSERT:
3196                 // slight hack: we know this is allowed in math mode
3197                 if (cur.inTexted())
3198                         code = SPACE_CODE;
3199                 break;
3200         case LFUN_PREVIEW_INSERT:
3201                 code = PREVIEW_CODE;
3202                 break;
3203         case LFUN_SCRIPT_INSERT:
3204                 code = SCRIPT_CODE;
3205                 break;
3206
3207         case LFUN_MATH_INSERT:
3208         case LFUN_MATH_AMS_MATRIX:
3209         case LFUN_MATH_MATRIX:
3210         case LFUN_MATH_DELIM:
3211         case LFUN_MATH_BIGDELIM:
3212         case LFUN_MATH_DISPLAY:
3213         case LFUN_MATH_MODE:
3214         case LFUN_MATH_MACRO:
3215         case LFUN_MATH_SUBSCRIPT:
3216         case LFUN_MATH_SUPERSCRIPT:
3217                 code = MATH_HULL_CODE;
3218                 break;
3219
3220         case LFUN_REGEXP_MODE:
3221                 code = MATH_HULL_CODE;
3222                 enable = cur.buffer()->isInternal() && !cur.inRegexped();
3223                 break;
3224
3225         case LFUN_INSET_MODIFY:
3226                 // We need to disable this, because we may get called for a
3227                 // tabular cell via
3228                 // InsetTabular::getStatus() -> InsetText::getStatus()
3229                 // and we don't handle LFUN_INSET_MODIFY.
3230                 enable = false;
3231                 break;
3232
3233         case LFUN_FONT_EMPH:
3234                 flag.setOnOff(fontinfo.emph() == FONT_ON);
3235                 enable = !cur.paragraph().isPassThru();
3236                 break;
3237
3238         case LFUN_FONT_ITAL:
3239                 flag.setOnOff(fontinfo.shape() == ITALIC_SHAPE);
3240                 enable = !cur.paragraph().isPassThru();
3241                 break;
3242
3243         case LFUN_FONT_NOUN:
3244                 flag.setOnOff(fontinfo.noun() == FONT_ON);
3245                 enable = !cur.paragraph().isPassThru();
3246                 break;
3247
3248         case LFUN_FONT_BOLD:
3249         case LFUN_FONT_BOLDSYMBOL:
3250                 flag.setOnOff(fontinfo.series() == BOLD_SERIES);
3251                 enable = !cur.paragraph().isPassThru();
3252                 break;
3253
3254         case LFUN_FONT_SANS:
3255                 flag.setOnOff(fontinfo.family() == SANS_FAMILY);
3256                 enable = !cur.paragraph().isPassThru();
3257                 break;
3258
3259         case LFUN_FONT_ROMAN:
3260                 flag.setOnOff(fontinfo.family() == ROMAN_FAMILY);
3261                 enable = !cur.paragraph().isPassThru();
3262                 break;
3263
3264         case LFUN_FONT_TYPEWRITER:
3265                 flag.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
3266                 enable = !cur.paragraph().isPassThru();
3267                 break;
3268
3269         case LFUN_CUT:
3270         case LFUN_COPY:
3271                 enable = cur.selection();
3272                 break;
3273
3274         case LFUN_PASTE: {
3275                 if (cmd.argument().empty()) {
3276                         if (theClipboard().isInternal())
3277                                 enable = cap::numberOfSelections() > 0;
3278                         else
3279                                 enable = !theClipboard().empty();
3280                         break;
3281                 }
3282
3283                 // we have an argument
3284                 string const arg = to_utf8(cmd.argument());
3285                 if (isStrUnsignedInt(arg)) {
3286                         // it's a number and therefore means the internal stack
3287                         unsigned int n = convert<unsigned int>(arg);
3288                         enable = cap::numberOfSelections() > n;
3289                         break;
3290                 }
3291
3292                 // explicit text type?
3293                 if (arg == "html") {
3294                         // Do not enable for PlainTextType, since some tidying in the
3295                         // frontend is needed for HTML, which is too unsafe for plain text.
3296                         enable = theClipboard().hasTextContents(Clipboard::HtmlTextType);
3297                         break;
3298                 } else if (arg == "latex") {
3299                         // LaTeX is usually not available on the clipboard with
3300                         // the correct MIME type, but in plain text.
3301                         enable = theClipboard().hasTextContents(Clipboard::PlainTextType) ||
3302                                  theClipboard().hasTextContents(Clipboard::LaTeXTextType);
3303                         break;
3304                 }
3305
3306                 Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
3307                 if (arg == "pdf")
3308                         type = Clipboard::PdfGraphicsType;
3309                 else if (arg == "png")
3310                         type = Clipboard::PngGraphicsType;
3311                 else if (arg == "jpeg")
3312                         type = Clipboard::JpegGraphicsType;
3313                 else if (arg == "linkback")
3314                         type = Clipboard::LinkBackGraphicsType;
3315                 else if (arg == "emf")
3316                         type = Clipboard::EmfGraphicsType;
3317                 else if (arg == "wmf")
3318                         type = Clipboard::WmfGraphicsType;
3319                 else {
3320                         // unknown argument
3321                         LYXERR0("Unrecognized graphics type: " << arg);
3322                         // we don't want to assert if the user just mistyped the LFUN
3323                         LATTEST(cmd.origin() != FuncRequest::INTERNAL);
3324                         enable = false;
3325                         break;
3326                 }
3327                 enable = theClipboard().hasGraphicsContents(type);
3328                 break;
3329         }
3330
3331         case LFUN_CLIPBOARD_PASTE:
3332         case LFUN_CLIPBOARD_PASTE_SIMPLE:
3333                 enable = !theClipboard().empty();
3334                 break;
3335
3336         case LFUN_PRIMARY_SELECTION_PASTE:
3337                 enable = cur.selection() || !theSelection().empty();
3338                 break;
3339
3340         case LFUN_SELECTION_PASTE:
3341                 enable = cap::selection();
3342                 break;
3343
3344         case LFUN_PARAGRAPH_MOVE_UP:
3345                 enable = cur.pit() > 0 && !cur.selection();
3346                 break;
3347
3348         case LFUN_PARAGRAPH_MOVE_DOWN:
3349                 enable = cur.pit() < cur.lastpit() && !cur.selection();
3350                 break;
3351
3352         case LFUN_CHANGE_ACCEPT:
3353         case LFUN_CHANGE_REJECT:
3354                 if (!cur.selection())
3355                         enable = cur.paragraph().isChanged(cur.pos());
3356                 else {
3357                         // will enable if there is a change in the selection
3358                         enable = false;
3359
3360                         // cheap improvement for efficiency: using cached
3361                         // buffer variable, if there is no change in the
3362                         // document, no need to check further.
3363                         if (!cur.buffer()->areChangesPresent())
3364                                 break;
3365
3366                         for (DocIterator it = cur.selectionBegin(); ; it.forwardPar()) {
3367                                 pos_type const beg = it.pos();
3368                                 pos_type end;
3369                                 bool const in_last_par = (it.pit() == cur.selectionEnd().pit() &&
3370                                                           it.idx() == cur.selectionEnd().idx());
3371                                 if (in_last_par)
3372                                         end = cur.selectionEnd().pos();
3373                                 else
3374                                         // the +1 is needed for cases, e.g., where there is a
3375                                         // paragraph break. See #11629.
3376                                         end = it.lastpos() + 1;
3377                                 if (beg != end && it.paragraph().isChanged(beg, end)) {
3378                                         enable = true;
3379                                         break;
3380                                 }
3381                                 if (beg != end && it.paragraph().hasChangedInsets(beg, end)) {
3382                                         enable = true;
3383                                         break;
3384                                 }
3385                                 if (in_last_par)
3386                                         break;
3387                         }
3388                 }
3389                 break;
3390
3391         case LFUN_OUTLINE_UP:
3392         case LFUN_OUTLINE_DOWN:
3393         case LFUN_OUTLINE_IN:
3394         case LFUN_OUTLINE_OUT:
3395                 // FIXME: LyX is not ready for outlining within inset.
3396                 enable = isMainText()
3397                         && cur.buffer()->text().getTocLevel(cur.pit()) != Layout::NOT_IN_TOC;
3398                 break;
3399
3400         case LFUN_NEWLINE_INSERT:
3401                 // LaTeX restrictions (labels or empty par)
3402                 enable = !cur.paragraph().isPassThru()
3403                         && cur.pos() > cur.paragraph().beginOfBody();
3404                 break;
3405
3406         case LFUN_SEPARATOR_INSERT:
3407                 // Always enabled for now
3408                 enable = true;
3409                 break;
3410
3411         case LFUN_TAB_INSERT:
3412         case LFUN_TAB_DELETE:
3413                 enable = cur.paragraph().isPassThru();
3414                 break;
3415
3416         case LFUN_GRAPHICS_SET_GROUP: {
3417                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
3418                 if (!ins)
3419                         enable = false;
3420                 else
3421                         flag.setOnOff(to_utf8(cmd.argument()) == ins->getParams().groupId);
3422                 break;
3423         }
3424
3425         case LFUN_NEWPAGE_INSERT:
3426                 // not allowed in description items
3427                 code = NEWPAGE_CODE;
3428                 enable = !inDescriptionItem(cur);
3429                 break;
3430
3431         case LFUN_LANGUAGE:
3432                 enable = !cur.paragraph().isPassThru();
3433                 flag.setOnOff(cmd.getArg(0) == cur.real_current_font.language()->lang());
3434                 break;
3435
3436         case LFUN_PARAGRAPH_BREAK:
3437                 enable = inset().allowMultiPar();
3438                 break;
3439
3440         case LFUN_SPELLING_ADD:
3441         case LFUN_SPELLING_IGNORE:
3442         case LFUN_SPELLING_REMOVE:
3443                 enable = theSpellChecker() != nullptr;
3444                 if (enable && !cmd.getArg(1).empty()) {
3445                         // validate explicitly given language
3446                         Language const * const lang = const_cast<Language *>(languages.getLanguage(cmd.getArg(1)));
3447                         enable &= lang != nullptr;
3448                 }
3449                 break;
3450
3451         case LFUN_LAYOUT:
3452         case LFUN_LAYOUT_TOGGLE: {
3453                 bool const ignoreautonests = cmd.getArg(1) == "ignoreautonests";
3454                 docstring const req_layout = ignoreautonests ? from_utf8(cmd.getArg(0)) : cmd.argument();
3455                 docstring const layout = resolveLayout(req_layout, cur);
3456
3457                 enable = !owner_->forcePlainLayout() && !layout.empty();
3458                 flag.setOnOff(isAlreadyLayout(layout, cur));
3459                 break;
3460         }
3461
3462         case LFUN_ENVIRONMENT_SPLIT: {
3463                 if (cmd.argument() == "outer") {
3464                         // check if we have an environment in our nesting hierarchy
3465                         bool res = false;
3466                         depth_type const current_depth = cur.paragraph().params().depth();
3467                         pit_type pit = cur.pit();
3468                         Paragraph cpar = pars_[pit];
3469                         while (true) {
3470                                 if (pit == 0 || cpar.params().depth() == 0)
3471                                         break;
3472                                 --pit;
3473                                 cpar = pars_[pit];
3474                                 if (cpar.params().depth() < current_depth)
3475                                         res = cpar.layout().isEnvironment();
3476                         }
3477                         enable = res;
3478                         break;
3479                 }
3480                 else if (cmd.argument() == "previous") {
3481                         // look if we have an environment in the previous par
3482                         pit_type pit = cur.pit();
3483                         Paragraph cpar = pars_[pit];
3484                         if (pit > 0) {
3485                                 --pit;
3486                                 cpar = pars_[pit];
3487                                 enable = cpar.layout().isEnvironment();
3488                                 break;
3489                         }
3490                         enable = false;
3491                         break;
3492                 }
3493                 else if (cur.paragraph().layout().isEnvironment()) {
3494                         enable = cmd.argument() == "before"
3495                                 || cur.pos() > 0 || !isFirstInSequence(cur.pit());
3496                         break;
3497                 }
3498                 enable = false;
3499                 break;
3500         }
3501
3502         case LFUN_LAYOUT_PARAGRAPH:
3503         case LFUN_PARAGRAPH_PARAMS:
3504         case LFUN_PARAGRAPH_PARAMS_APPLY:
3505         case LFUN_PARAGRAPH_UPDATE:
3506                 enable = owner_->allowParagraphCustomization();
3507                 break;
3508
3509         // FIXME: why are accent lfuns forbidden with pass_thru layouts?
3510         //  Because they insert COMBINING DIACRITICAL Unicode characters,
3511         //  that cannot be handled by LaTeX but must be converted according
3512         //  to the definition in lib/unicodesymbols?
3513         case LFUN_ACCENT_ACUTE:
3514         case LFUN_ACCENT_BREVE:
3515         case LFUN_ACCENT_CARON:
3516         case LFUN_ACCENT_CEDILLA:
3517         case LFUN_ACCENT_CIRCLE:
3518         case LFUN_ACCENT_CIRCUMFLEX:
3519         case LFUN_ACCENT_DOT:
3520         case LFUN_ACCENT_GRAVE:
3521         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
3522         case LFUN_ACCENT_MACRON:
3523         case LFUN_ACCENT_OGONEK:
3524         case LFUN_ACCENT_TIE:
3525         case LFUN_ACCENT_TILDE:
3526         case LFUN_ACCENT_PERISPOMENI:
3527         case LFUN_ACCENT_UMLAUT:
3528         case LFUN_ACCENT_UNDERBAR:
3529         case LFUN_ACCENT_UNDERDOT:
3530         case LFUN_FONT_FRAK:
3531         case LFUN_FONT_SIZE:
3532         case LFUN_FONT_STATE:
3533         case LFUN_FONT_UNDERLINE:
3534         case LFUN_FONT_STRIKEOUT:
3535         case LFUN_FONT_CROSSOUT:
3536         case LFUN_FONT_UNDERUNDERLINE:
3537         case LFUN_FONT_UNDERWAVE:
3538         case LFUN_TEXTSTYLE_UPDATE:
3539                 enable = !cur.paragraph().isPassThru();
3540                 break;
3541
3542         case LFUN_FONT_DEFAULT: {
3543                 Font font(inherit_font, ignore_language);
3544                 BufferParams const & bp = cur.buffer()->masterParams();
3545                 if (cur.selection()) {
3546                         enable = false;
3547                         // Check if we have a non-default font attribute
3548                         // in the selection range.
3549                         DocIterator const from = cur.selectionBegin();
3550                         DocIterator const to = cur.selectionEnd();
3551                         for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
3552                                 if (!dit.inTexted()) {
3553                                         dit.forwardPos();
3554                                         continue;
3555                                 }
3556                                 Paragraph const & par = dit.paragraph();
3557                                 pos_type const pos = dit.pos();
3558                                 Font tmp = par.getFontSettings(bp, pos);
3559                                 if (tmp.fontInfo() != font.fontInfo()
3560                                     || tmp.language() != bp.language) {
3561                                         enable = true;
3562                                         break;
3563                                 }
3564                                 dit.forwardPos();
3565                         }
3566                         break;
3567                 }
3568                 // Disable if all is default already.
3569                 enable = (cur.current_font.fontInfo() != font.fontInfo()
3570                           || cur.current_font.language() != bp.language);
3571                 break;
3572         }
3573
3574         case LFUN_TEXTSTYLE_APPLY:
3575                 enable = !freeFonts.empty();
3576                 break;
3577
3578         case LFUN_WORD_DELETE_FORWARD:
3579         case LFUN_WORD_DELETE_BACKWARD:
3580         case LFUN_LINE_DELETE_FORWARD:
3581         case LFUN_WORD_FORWARD:
3582         case LFUN_WORD_BACKWARD:
3583         case LFUN_WORD_RIGHT:
3584         case LFUN_WORD_LEFT:
3585         case LFUN_CHAR_FORWARD:
3586         case LFUN_CHAR_FORWARD_SELECT:
3587         case LFUN_CHAR_BACKWARD:
3588         case LFUN_CHAR_BACKWARD_SELECT:
3589         case LFUN_CHAR_LEFT:
3590         case LFUN_CHAR_LEFT_SELECT:
3591         case LFUN_CHAR_RIGHT:
3592         case LFUN_CHAR_RIGHT_SELECT:
3593         case LFUN_UP:
3594         case LFUN_UP_SELECT:
3595         case LFUN_DOWN:
3596         case LFUN_DOWN_SELECT:
3597         case LFUN_PARAGRAPH_SELECT:
3598         case LFUN_PARAGRAPH_UP_SELECT:
3599         case LFUN_PARAGRAPH_DOWN_SELECT:
3600         case LFUN_LINE_BEGIN_SELECT:
3601         case LFUN_LINE_END_SELECT:
3602         case LFUN_WORD_FORWARD_SELECT:
3603         case LFUN_WORD_BACKWARD_SELECT:
3604         case LFUN_WORD_RIGHT_SELECT:
3605         case LFUN_WORD_LEFT_SELECT:
3606         case LFUN_WORD_SELECT:
3607         case LFUN_SECTION_SELECT:
3608         case LFUN_BUFFER_BEGIN:
3609         case LFUN_BUFFER_END:
3610         case LFUN_BUFFER_BEGIN_SELECT:
3611         case LFUN_BUFFER_END_SELECT:
3612         case LFUN_INSET_BEGIN:
3613         case LFUN_INSET_END:
3614         case LFUN_INSET_BEGIN_SELECT:
3615         case LFUN_INSET_END_SELECT:
3616         case LFUN_PARAGRAPH_UP:
3617         case LFUN_PARAGRAPH_DOWN:
3618         case LFUN_LINE_BEGIN:
3619         case LFUN_LINE_END:
3620         case LFUN_CHAR_DELETE_FORWARD:
3621         case LFUN_CHAR_DELETE_BACKWARD:
3622         case LFUN_WORD_UPCASE:
3623         case LFUN_WORD_LOWCASE:
3624         case LFUN_WORD_CAPITALIZE:
3625         case LFUN_CHARS_TRANSPOSE:
3626         case LFUN_SERVER_GET_XY:
3627         case LFUN_SERVER_SET_XY:
3628         case LFUN_SERVER_GET_LAYOUT:
3629         case LFUN_SELF_INSERT:
3630         case LFUN_UNICODE_INSERT:
3631         case LFUN_THESAURUS_ENTRY:
3632         case LFUN_ESCAPE:
3633         case LFUN_SERVER_GET_STATISTICS:
3634                 // these are handled in our dispatch()
3635                 enable = true;
3636                 break;
3637
3638         case LFUN_INSET_INSERT: {
3639                 string const type = cmd.getArg(0);
3640                 if (type == "toc") {
3641                         code = TOC_CODE;
3642                         // not allowed in description items
3643                         //FIXME: couldn't this be merged in Inset::insetAllowed()?
3644                         enable = !inDescriptionItem(cur);
3645                 } else {
3646                         enable = true;
3647                 }
3648                 break;
3649         }
3650
3651         case LFUN_SEARCH_IGNORE: {
3652                 bool const value = cmd.getArg(1) == "true";
3653                 setIgnoreFormat(cmd.getArg(0), value);
3654                 break;
3655         }
3656
3657         default:
3658                 return false;
3659         }
3660
3661         if (code != NO_CODE
3662             && (cur.empty()
3663                 || !cur.inset().insetAllowed(code)
3664                 || (cur.paragraph().layout().pass_thru && !allow_in_passthru)))
3665                 enable = false;
3666
3667         flag.setEnabled(enable);
3668         return true;
3669 }
3670
3671
3672 void Text::pasteString(Cursor & cur, docstring const & clip,
3673                 bool asParagraphs)
3674 {
3675         if (!clip.empty()) {
3676                 cur.recordUndo();
3677                 if (asParagraphs)
3678                         insertStringAsParagraphs(cur, clip, cur.current_font);
3679                 else
3680                         insertStringAsLines(cur, clip, cur.current_font);
3681         }
3682 }
3683
3684
3685 // FIXME: an item inset would make things much easier.
3686 bool Text::inDescriptionItem(Cursor & cur) const
3687 {
3688         Paragraph & par = cur.paragraph();
3689         pos_type const pos = cur.pos();
3690         pos_type const body_pos = par.beginOfBody();
3691
3692         if (par.layout().latextype != LATEX_LIST_ENVIRONMENT
3693             && (par.layout().latextype != LATEX_ITEM_ENVIRONMENT
3694                 || par.layout().margintype != MARGIN_FIRST_DYNAMIC))
3695                 return false;
3696
3697         return (pos < body_pos
3698                 || (pos == body_pos
3699                     && (pos == 0 || par.getChar(pos - 1) != ' ')));
3700 }
3701
3702
3703 std::vector<docstring> Text::getFreeFonts() const
3704 {
3705         vector<docstring> ffList;
3706
3707         for (auto const & f : freeFonts)
3708                 ffList.push_back(f.first);
3709
3710         return ffList;
3711 }
3712
3713 } // namespace lyx