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