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