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