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