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