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