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