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