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