]> git.lyx.org Git - lyx.git/blob - src/Text3.cpp
Amend 9f04eeae032d
[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                 cur.clearSelection();
302                 gotsel = true;
303         } else if (cmd.action() == LFUN_INDEX_INSERT) {
304                 gotsel = text->selectWordWhenUnderCursor(cur, WHOLE_WORD);
305                 copySelectionToTemp(cur);
306                 cur.clearSelection();
307         }
308         text->insertInset(cur, inset);
309
310         if (edit)
311                 inset->edit(cur, true);
312
313         if (!gotsel || !pastesel)
314                 return true;
315
316         pasteFromTemp(cur, cur.buffer()->errorList("Paste"));
317         cur.buffer()->errors("Paste");
318         cur.clearSelection(); // bug 393
319         cur.finishUndo();
320         InsetText * inset_text = inset->asInsetText();
321         if (inset_text) {
322                 inset_text->fixParagraphsFont();
323                 if (!inset_text->allowMultiPar() || cur.lastpit() == 0) {
324                         // reset first par to default
325                         cur.text()->paragraphs().begin()
326                                 ->setPlainOrDefaultLayout(bparams.documentClass());
327                         cur.pos() = 0;
328                         cur.pit() = 0;
329                         // Merge multiple paragraphs -- hack
330                         while (cur.lastpit() > 0)
331                                 mergeParagraph(bparams, cur.text()->paragraphs(), 0);
332                         if (cmd.action() == LFUN_FLEX_INSERT)
333                                 return true;
334                         Cursor old = cur;
335                         cur.leaveInset(*inset);
336                         if (cmd.action() == LFUN_PREVIEW_INSERT
337                             || cmd.action() == LFUN_IPA_INSERT)
338                                 // trigger preview
339                                 notifyCursorLeavesOrEnters(old, cur);
340                 }
341         } else {
342                 cur.leaveInset(*inset);
343                 // reset surrounding par to default
344                 DocumentClass const & dc = bparams.documentClass();
345                 docstring const layoutname = inset->usePlainLayout()
346                         ? dc.plainLayoutName()
347                         : dc.defaultLayoutName();
348                 text->setLayout(cur, layoutname);
349         }
350         return true;
351 }
352
353
354 /// the type of outline operation
355 enum OutlineOp {
356         OutlineUp, // Move this header with text down
357         OutlineDown,   // Move this header with text up
358         OutlineIn, // Make this header deeper
359         OutlineOut // Make this header shallower
360 };
361
362
363 static void insertSeparator(Cursor & cur, depth_type const depth)
364 {
365         Buffer & buf = *cur.buffer();
366         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK));
367         DocumentClass const & tc = buf.params().documentClass();
368         lyx::dispatch(FuncRequest(LFUN_LAYOUT, from_ascii("\"") + tc.plainLayout().name()
369                                   + from_ascii("\" ignoreautonests")));
370         // FIXME: Bibitem mess!
371         if (cur.prevInset() && cur.prevInset()->lyxCode() == BIBITEM_CODE)
372                 lyx::dispatch(FuncRequest(LFUN_CHAR_DELETE_BACKWARD));
373         lyx::dispatch(FuncRequest(LFUN_SEPARATOR_INSERT, "plain"));
374         while (cur.paragraph().params().depth() > depth)
375                 lyx::dispatch(FuncRequest(LFUN_DEPTH_DECREMENT));
376 }
377
378
379 static void outline(OutlineOp mode, Cursor & cur, Text * text)
380 {
381         Buffer & buf = *cur.buffer();
382         pit_type & pit = cur.pit();
383         ParagraphList & pars = buf.text().paragraphs();
384         ParagraphList::iterator const bgn = pars.begin();
385         // The first paragraph of the area to be copied:
386         ParagraphList::iterator start = lyx::next(bgn, pit);
387         // The final paragraph of area to be copied:
388         ParagraphList::iterator finish = start;
389         ParagraphList::iterator const end = pars.end();
390         depth_type const current_depth = cur.paragraph().params().depth();
391
392         int const thistoclevel = buf.text().getTocLevel(distance(bgn, start));
393         int toclevel;
394
395         // Move out (down) from this section header
396         if (finish != end)
397                 ++finish;
398
399         // Seek the one (on same level) below
400         for (; finish != end; ++finish) {
401                 toclevel = buf.text().getTocLevel(distance(bgn, finish));
402                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
403                         break;
404         }
405
406         switch (mode) {
407                 case OutlineUp: {
408                         if (start == pars.begin())
409                                 // Nothing to move.
410                                 return;
411                         ParagraphList::iterator dest = start;
412                         // Move out (up) from this header
413                         if (dest == bgn)
414                                 return;
415                         // Search previous same-level header above
416                         do {
417                                 --dest;
418                                 toclevel = buf.text().getTocLevel(distance(bgn, dest));
419                         } while(dest != bgn
420                                 && (toclevel == Layout::NOT_IN_TOC
421                                     || toclevel > thistoclevel));
422                         // Not found; do nothing
423                         if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
424                                 return;
425                         pit_type newpit = distance(bgn, dest);
426                         pit_type const len = distance(start, finish);
427                         pit_type const deletepit = pit + len;
428                         buf.undo().recordUndo(cur, newpit, deletepit - 1);
429                         // If we move an environment upwards, make sure it is
430                         // separated from its new neighbour below:
431                         // If an environment of the same layout follows, and the moved
432                         // paragraph sequence does not end with a separator, insert one.
433                         ParagraphList::iterator lastmoved = finish;
434                         --lastmoved;
435                         if (start->layout().isEnvironment()
436                             && dest->layout() == start->layout()
437                             && !lastmoved->isEnvSeparator(lastmoved->beginOfBody())) {
438                                 cur.pit() = distance(bgn, lastmoved);
439                                 cur.pos() = cur.lastpos();
440                                 insertSeparator(cur, current_depth);
441                                 cur.pit() = pit;
442                         }
443                         // Likewise, if we moved an environment upwards, make sure it
444                         // is separated from its new neighbour above.
445                         // The paragraph before the target of movement
446                         if (dest != bgn) {
447                                 ParagraphList::iterator before = dest;
448                                 --before;
449                                 // Get the parent paragraph (outer in nested context)
450                                 pit_type const parent =
451                                         before->params().depth() > current_depth
452                                                 ? text->depthHook(distance(bgn, before), current_depth)
453                                                 : distance(bgn, before);
454                                 // If a environment with same layout preceeds the moved one in the new
455                                 // position, and there is no separator yet, insert one.
456                                 if (start->layout().isEnvironment()
457                                     && pars[parent].layout() == start->layout()
458                                     && !before->isEnvSeparator(before->beginOfBody())) {
459                                         cur.pit() = distance(bgn, before);
460                                         cur.pos() = cur.lastpos();
461                                         insertSeparator(cur, current_depth);
462                                         cur.pit() = pit;
463                                 }
464                         }
465                         newpit = distance(bgn, dest);
466                         pars.splice(dest, start, finish);
467                         cur.pit() = newpit;
468                         break;
469                 }
470                 case OutlineDown: {
471                         if (finish == end)
472                                 // Nothing to move.
473                                 return;
474                         // Go one down from *this* header:
475                         ParagraphList::iterator dest = next(finish, 1);
476                         // Go further down to find header to insert in front of:
477                         for (; dest != end; ++dest) {
478                                 toclevel = buf.text().getTocLevel(distance(bgn, dest));
479                                 if (toclevel != Layout::NOT_IN_TOC
480                                       && toclevel <= thistoclevel)
481                                         break;
482                         }
483                         // One such was found, so go on...
484                         // If we move an environment downwards, make sure it is
485                         // separated from its new neighbour above.
486                         pit_type newpit = distance(bgn, dest);
487                         buf.undo().recordUndo(cur, pit, newpit - 1);
488                         // The paragraph before the target of movement
489                         ParagraphList::iterator before = dest;
490                         --before;
491                         // Get the parent paragraph (outer in nested context)
492                         pit_type const parent =
493                                 before->params().depth() > current_depth
494                                         ? text->depthHook(distance(bgn, before), current_depth)
495                                         : distance(bgn, before);
496                         // If a environment with same layout preceeds the moved one in the new
497                         // position, and there is no separator yet, insert one.
498                         if (start->layout().isEnvironment()
499                             && pars[parent].layout() == start->layout()
500                             && !before->isEnvSeparator(before->beginOfBody())) {
501                                 cur.pit() = distance(bgn, before);
502                                 cur.pos() = cur.lastpos();
503                                 insertSeparator(cur, current_depth);
504                                 cur.pit() = pit;
505                         }
506                         // Likewise, make sure moved environments are separated
507                         // from their new neighbour below:
508                         // If an environment of the same layout follows, and the moved
509                         // paragraph sequence does not end with a separator, insert one.
510                         ParagraphList::iterator lastmoved = finish;
511                         --lastmoved;
512                         if (dest != end
513                             && start->layout().isEnvironment()
514                             && dest->layout() == start->layout()
515                             && !lastmoved->isEnvSeparator(lastmoved->beginOfBody())) {
516                                 cur.pit() = distance(bgn, lastmoved);
517                                 cur.pos() = cur.lastpos();
518                                 insertSeparator(cur, current_depth);
519                                 cur.pit() = pit;
520                         }
521                         newpit = distance(bgn, dest);
522                         pit_type const len = distance(start, finish);
523                         pars.splice(dest, start, finish);
524                         cur.pit() = newpit - len;
525                         break;
526                 }
527                 case OutlineIn:
528                 case OutlineOut: {
529                         pit_type const len = distance(start, finish);
530                         buf.undo().recordUndo(cur, pit, pit + len - 1);
531                         for (; start != finish; ++start) {
532                                 toclevel = buf.text().getTocLevel(distance(bgn, start));
533                                 if (toclevel == Layout::NOT_IN_TOC)
534                                         continue;
535
536                                 DocumentClass const & tc = buf.params().documentClass();
537                                 DocumentClass::const_iterator lit = tc.begin();
538                                 DocumentClass::const_iterator len = tc.end();
539                                 int const newtoclevel =
540                                         (mode == OutlineIn ? toclevel + 1 : toclevel - 1);
541                                 LabelType const oldlabeltype = start->layout().labeltype;
542
543                                 for (; lit != len; ++lit) {
544                                         if (lit->toclevel ==  newtoclevel &&
545                                              lit->labeltype == oldlabeltype) {
546                                                 start->setLayout(*lit);
547                                                 break;
548                                         }
549                                 }
550                         }
551                         break;
552                 }
553         }
554 }
555
556
557 void Text::number(Cursor & cur)
558 {
559         FontInfo font = ignore_font;
560         font.setNumber(FONT_TOGGLE);
561         toggleAndShow(cur, this, Font(font, ignore_language));
562 }
563
564
565 bool Text::isRTL(pit_type const pit) const
566 {
567         Buffer const & buffer = owner_->buffer();
568         return pars_[pit].isRTL(buffer.params());
569 }
570
571
572 namespace {
573
574 Language const * getLanguage(Cursor const & cur, string const & lang)
575 {
576         return lang.empty() ? cur.getFont().language() : languages.getLanguage(lang);
577 }
578
579
580 docstring resolveLayout(docstring layout, DocIterator const & dit)
581 {
582         Paragraph const & par = dit.paragraph();
583         docstring const old_layout = par.layout().name();
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                         cutSelection(cur, false);
1254                         singleParUpdate = false;
1255                 }
1256                 break;
1257
1258         case LFUN_PARAGRAPH_BREAK: {
1259                 cap::replaceSelection(cur);
1260                 pit_type pit = cur.pit();
1261                 Paragraph const & par = pars_[pit];
1262                 bool lastpar = (pit == pit_type(pars_.size() - 1));
1263                 Paragraph const & nextpar = lastpar ? par : pars_[pit + 1];
1264                 pit_type prev = pit > 0 ? depthHook(pit, par.getDepth()) : pit;
1265                 if (prev < pit && cur.pos() == par.beginOfBody()
1266                     && !par.size() && !par.isEnvSeparator(cur.pos())
1267                     && !par.layout().keepempty
1268                     && !par.layout().isCommand()
1269                     && pars_[prev].layout() != par.layout()
1270                     && pars_[prev].layout().isEnvironment()
1271                     && !nextpar.isEnvSeparator(nextpar.beginOfBody())) {
1272                         if (par.layout().isEnvironment()
1273                             && pars_[prev].getDepth() == par.getDepth()) {
1274                                 docstring const layout = par.layout().name();
1275                                 DocumentClass const & tc = bv->buffer().params().documentClass();
1276                                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, tc.plainLayout().name()));
1277                                 lyx::dispatch(FuncRequest(LFUN_SEPARATOR_INSERT, "plain"));
1278                                 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK, "inverse"));
1279                                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, layout));
1280                         } else {
1281                                 lyx::dispatch(FuncRequest(LFUN_SEPARATOR_INSERT, "plain"));
1282                                 breakParagraph(cur);
1283                         }
1284                         Font const f(inherit_font, cur.current_font.language());
1285                         pars_[cur.pit() - 1].resetFonts(f);
1286                 } else {
1287                         if (par.isEnvSeparator(cur.pos()) && cmd.getArg(1) != "ignoresep")
1288                                 cur.posForward();
1289                         breakParagraph(cur, cmd.getArg(0) == "inverse");
1290                 }
1291                 cur.resetAnchor();
1292                 // If we have a list and autoinsert item insets,
1293                 // insert them now.
1294                 Layout::LaTeXArgMap args = par.layout().args();
1295                 for (auto const & thearg : args) {
1296                         Layout::latexarg arg = thearg.second;
1297                         if (arg.autoinsert && prefixIs(thearg.first, "item:")) {
1298                                 FuncRequest cmd2(LFUN_ARGUMENT_INSERT, thearg.first);
1299                                 lyx::dispatch(cmd2);
1300                         }
1301                 }
1302                 break;
1303         }
1304
1305         case LFUN_INSET_INSERT: {
1306                 cur.recordUndo();
1307
1308                 // We have to avoid triggering InstantPreview loading
1309                 // before inserting into the document. See bug #5626.
1310                 bool loaded = bv->buffer().isFullyLoaded();
1311                 bv->buffer().setFullyLoaded(false);
1312                 Inset * inset = createInset(&bv->buffer(), cmd);
1313                 bv->buffer().setFullyLoaded(loaded);
1314
1315                 if (inset) {
1316                         // FIXME (Abdel 01/02/2006):
1317                         // What follows would be a partial fix for bug 2154:
1318                         //   http://www.lyx.org/trac/ticket/2154
1319                         // This automatically put the label inset _after_ a
1320                         // numbered section. It should be possible to extend the mechanism
1321                         // to any kind of LateX environement.
1322                         // The correct way to fix that bug would be at LateX generation.
1323                         // I'll let the code here for reference as it could be used for some
1324                         // other feature like "automatic labelling".
1325                         /*
1326                         Paragraph & par = pars_[cur.pit()];
1327                         if (inset->lyxCode() == LABEL_CODE
1328                                 && !par.layout().counter.empty()) {
1329                                 // Go to the end of the paragraph
1330                                 // Warning: Because of Change-Tracking, the last
1331                                 // position is 'size()' and not 'size()-1':
1332                                 cur.pos() = par.size();
1333                                 // Insert a new paragraph
1334                                 FuncRequest fr(LFUN_PARAGRAPH_BREAK);
1335                                 dispatch(cur, fr);
1336                         }
1337                         */
1338                         if (cur.selection())
1339                                 cutSelection(cur, false);
1340                         cur.insert(inset);
1341                         cur.forceBufferUpdate();
1342                         if (inset->editable() && inset->asInsetText())
1343                                 inset->edit(cur, true);
1344                         else
1345                                 cur.posForward();
1346
1347                         // trigger InstantPreview now
1348                         if (inset->lyxCode() == EXTERNAL_CODE) {
1349                                 InsetExternal & ins =
1350                                         static_cast<InsetExternal &>(*inset);
1351                                 ins.updatePreview();
1352                         }
1353                 }
1354
1355                 break;
1356         }
1357
1358         case LFUN_INSET_DISSOLVE: {
1359                 if (dissolveInset(cur)) {
1360                         needsUpdate = true;
1361                         cur.forceBufferUpdate();
1362                 }
1363                 break;
1364         }
1365
1366         case LFUN_GRAPHICS_SET_GROUP: {
1367                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
1368                 if (!ins)
1369                         break;
1370
1371                 cur.recordUndo();
1372
1373                 string id = to_utf8(cmd.argument());
1374                 string grp = graphics::getGroupParams(bv->buffer(), id);
1375                 InsetGraphicsParams tmp, inspar = ins->getParams();
1376
1377                 if (id.empty())
1378                         inspar.groupId = to_utf8(cmd.argument());
1379                 else {
1380                         InsetGraphics::string2params(grp, bv->buffer(), tmp);
1381                         tmp.filename = inspar.filename;
1382                         inspar = tmp;
1383                 }
1384
1385                 ins->setParams(inspar);
1386                 break;
1387         }
1388
1389         case LFUN_SPACE_INSERT:
1390                 if (cur.paragraph().layout().free_spacing)
1391                         insertChar(cur, ' ');
1392                 else {
1393                         doInsertInset(cur, this, cmd, false, false);
1394                         cur.posForward();
1395                 }
1396                 moveCursor(cur, false);
1397                 break;
1398
1399         case LFUN_SPECIALCHAR_INSERT: {
1400                 string const name = to_utf8(cmd.argument());
1401                 if (name == "hyphenation")
1402                         specialChar(cur, InsetSpecialChar::HYPHENATION);
1403                 else if (name == "allowbreak")
1404                         specialChar(cur, InsetSpecialChar::ALLOWBREAK);
1405                 else if (name == "ligature-break")
1406                         specialChar(cur, InsetSpecialChar::LIGATURE_BREAK);
1407                 else if (name == "slash")
1408                         specialChar(cur, InsetSpecialChar::SLASH);
1409                 else if (name == "nobreakdash")
1410                         specialChar(cur, InsetSpecialChar::NOBREAKDASH);
1411                 else if (name == "dots")
1412                         specialChar(cur, InsetSpecialChar::LDOTS);
1413                 else if (name == "end-of-sentence")
1414                         specialChar(cur, InsetSpecialChar::END_OF_SENTENCE);
1415                 else if (name == "menu-separator")
1416                         specialChar(cur, InsetSpecialChar::MENU_SEPARATOR);
1417                 else if (name == "lyx")
1418                         specialChar(cur, InsetSpecialChar::PHRASE_LYX);
1419                 else if (name == "tex")
1420                         specialChar(cur, InsetSpecialChar::PHRASE_TEX);
1421                 else if (name == "latex")
1422                         specialChar(cur, InsetSpecialChar::PHRASE_LATEX);
1423                 else if (name == "latex2e")
1424                         specialChar(cur, InsetSpecialChar::PHRASE_LATEX2E);
1425                 else if (name.empty())
1426                         lyxerr << "LyX function 'specialchar-insert' needs an argument." << endl;
1427                 else
1428                         lyxerr << "Wrong argument for LyX function 'specialchar-insert'." << endl;
1429                 break;
1430         }
1431
1432         case LFUN_IPAMACRO_INSERT: {
1433                 string const arg = cmd.getArg(0);
1434                 if (arg == "deco") {
1435                         // Open the inset, and move the current selection
1436                         // inside it.
1437                         doInsertInset(cur, this, cmd, true, true);
1438                         cur.posForward();
1439                         // Some insets are numbered, others are shown in the outline pane so
1440                         // let's update the labels and the toc backend.
1441                         cur.forceBufferUpdate();
1442                         break;
1443                 }
1444                 if (arg == "tone-falling")
1445                         ipaChar(cur, InsetIPAChar::TONE_FALLING);
1446                 else if (arg == "tone-rising")
1447                         ipaChar(cur, InsetIPAChar::TONE_RISING);
1448                 else if (arg == "tone-high-rising")
1449                         ipaChar(cur, InsetIPAChar::TONE_HIGH_RISING);
1450                 else if (arg == "tone-low-rising")
1451                         ipaChar(cur, InsetIPAChar::TONE_LOW_RISING);
1452                 else if (arg == "tone-high-rising-falling")
1453                         ipaChar(cur, InsetIPAChar::TONE_HIGH_RISING_FALLING);
1454                 else if (arg.empty())
1455                         lyxerr << "LyX function 'ipamacro-insert' needs an argument." << endl;
1456                 else
1457                         lyxerr << "Wrong argument for LyX function 'ipamacro-insert'." << endl;
1458                 break;
1459         }
1460
1461         case LFUN_WORD_UPCASE:
1462                 changeCase(cur, text_uppercase, cmd.getArg(0) == "partial");
1463                 break;
1464
1465         case LFUN_WORD_LOWCASE:
1466                 changeCase(cur, text_lowercase, cmd.getArg(0) == "partial");
1467                 break;
1468
1469         case LFUN_WORD_CAPITALIZE:
1470                 changeCase(cur, text_capitalization, cmd.getArg(0) == "partial");
1471                 break;
1472
1473         case LFUN_CHARS_TRANSPOSE:
1474                 charsTranspose(cur);
1475                 break;
1476
1477         case LFUN_PASTE: {
1478                 cur.message(_("Paste"));
1479                 LASSERT(cur.selBegin().idx() == cur.selEnd().idx(), break);
1480                 cap::replaceSelection(cur);
1481
1482                 // without argument?
1483                 string const arg = to_utf8(cmd.argument());
1484                 if (arg.empty()) {
1485                         bool tryGraphics = true;
1486                         if (theClipboard().isInternal())
1487                                 pasteFromStack(cur, bv->buffer().errorList("Paste"), 0);
1488                         else if (theClipboard().hasTextContents()) {
1489                                 if (pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1490                                                        true, Clipboard::AnyTextType))
1491                                         tryGraphics = false;
1492                         }
1493                         if (tryGraphics && theClipboard().hasGraphicsContents())
1494                                 pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"));
1495                 } else if (isStrUnsignedInt(arg)) {
1496                         // we have a numerical argument
1497                         pasteFromStack(cur, bv->buffer().errorList("Paste"),
1498                                        convert<unsigned int>(arg));
1499                 } else if (arg == "html" || arg == "latex") {
1500                         Clipboard::TextType type = (arg == "html") ?
1501                                 Clipboard::HtmlTextType : Clipboard::LaTeXTextType;
1502                         pasteClipboardText(cur, bv->buffer().errorList("Paste"), true, type);
1503                 } else {
1504                         Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
1505                         if (arg == "pdf")
1506                                 type = Clipboard::PdfGraphicsType;
1507                         else if (arg == "png")
1508                                 type = Clipboard::PngGraphicsType;
1509                         else if (arg == "jpeg")
1510                                 type = Clipboard::JpegGraphicsType;
1511                         else if (arg == "linkback")
1512                                 type = Clipboard::LinkBackGraphicsType;
1513                         else if (arg == "emf")
1514                                 type = Clipboard::EmfGraphicsType;
1515                         else if (arg == "wmf")
1516                                 type = Clipboard::WmfGraphicsType;
1517                         else
1518                                 // we also check in getStatus()
1519                                 LYXERR0("Unrecognized graphics type: " << arg);
1520
1521                         pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"), type);
1522                 }
1523
1524                 bv->buffer().errors("Paste");
1525                 cur.clearSelection(); // bug 393
1526                 cur.finishUndo();
1527                 break;
1528         }
1529
1530         case LFUN_CUT:
1531                 cutSelection(cur, true);
1532                 cur.message(_("Cut"));
1533                 break;
1534
1535         case LFUN_COPY:
1536                 copySelection(cur);
1537                 cur.message(_("Copy"));
1538                 break;
1539
1540         case LFUN_SERVER_GET_XY:
1541                 cur.message(from_utf8(
1542                         convert<string>(tm->cursorX(cur.top(), cur.boundary()))
1543                         + ' ' + convert<string>(tm->cursorY(cur.top(), cur.boundary()))));
1544                 break;
1545
1546         case LFUN_SERVER_SET_XY: {
1547                 int x = 0;
1548                 int y = 0;
1549                 istringstream is(to_utf8(cmd.argument()));
1550                 is >> x >> y;
1551                 if (!is)
1552                         lyxerr << "SETXY: Could not parse coordinates in '"
1553                                << to_utf8(cmd.argument()) << endl;
1554                 else
1555                         tm->setCursorFromCoordinates(cur, x, y);
1556                 break;
1557         }
1558
1559         case LFUN_SERVER_GET_LAYOUT:
1560                 cur.message(cur.paragraph().layout().name());
1561                 break;
1562
1563         case LFUN_LAYOUT:
1564         case LFUN_LAYOUT_TOGGLE: {
1565                 bool const ignoreautonests = cmd.getArg(1) == "ignoreautonests";
1566                 docstring req_layout = ignoreautonests ? from_utf8(cmd.getArg(0)) : cmd.argument();
1567                 LYXERR(Debug::INFO, "LFUN_LAYOUT: (arg) " << to_utf8(req_layout));
1568
1569                 docstring layout = resolveLayout(req_layout, cur);
1570                 if (layout.empty()) {
1571                         cur.errorMessage(from_utf8(N_("Layout ")) + req_layout +
1572                                 from_utf8(N_(" not known")));
1573                         break;
1574                 }
1575
1576                 docstring const old_layout = cur.paragraph().layout().name();
1577                 bool change_layout = !isAlreadyLayout(layout, cur);
1578
1579                 if (cmd.action() == LFUN_LAYOUT_TOGGLE && !change_layout) {
1580                         change_layout = true;
1581                         layout = resolveLayout(docstring(), cur);
1582                 }
1583
1584                 if (change_layout) {
1585                         setLayout(cur, layout);
1586                         if (cur.pit() > 0 && !ignoreautonests) {
1587                                 set<docstring> const & autonests =
1588                                                 pars_[cur.pit() - 1].layout().autonests();
1589                                 set<docstring> const & autonested =
1590                                                 pars_[cur.pit()].layout().isAutonestedBy();
1591                                 if (autonests.find(layout) != autonests.end()
1592                                                 || autonested.find(old_layout) != autonested.end())
1593                                         lyx::dispatch(FuncRequest(LFUN_DEPTH_INCREMENT));
1594                         }
1595                 }
1596
1597                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1598                 bool inautoarg = false;
1599                 for (auto const & la_pair : tclass[layout].args()) {
1600                         Layout::latexarg const & arg = la_pair.second;
1601                         if (arg.autoinsert) {
1602                                 // If we had already inserted an arg automatically,
1603                                 // leave this now in order to insert the next one.
1604                                 if (inautoarg) {
1605                                         cur.leaveInset(cur.inset());
1606                                         cur.posForward();
1607                                         inautoarg = false;
1608                                 }
1609                                 FuncRequest const cmd2(LFUN_ARGUMENT_INSERT, la_pair.first);
1610                                 lyx::dispatch(cmd2);
1611                                 inautoarg = true;
1612                         }
1613                 }
1614
1615                 break;
1616         }
1617
1618         case LFUN_ENVIRONMENT_SPLIT: {
1619                 bool const outer = cmd.argument() == "outer";
1620                 bool const previous = cmd.argument() == "previous";
1621                 bool const before = cmd.argument() == "before";
1622                 bool const normal = cmd.argument().empty();
1623                 Paragraph const & para = cur.paragraph();
1624                 docstring layout;
1625                 if (para.layout().isEnvironment())
1626                         layout = para.layout().name();
1627                 depth_type split_depth = cur.paragraph().params().depth();
1628                 depth_type nextpar_depth = 0;
1629                 if (outer || previous) {
1630                         // check if we have an environment in our scope
1631                         pit_type pit = cur.pit();
1632                         Paragraph cpar = pars_[pit];
1633                         while (true) {
1634                                 if (pit == 0)
1635                                         break;
1636                                 --pit;
1637                                 cpar = pars_[pit];
1638                                 if (layout.empty() && previous
1639                                     && cpar.layout().isEnvironment()
1640                                     && cpar.params().depth() <= split_depth)
1641                                         layout = cpar.layout().name();
1642                                 if (cpar.params().depth() < split_depth
1643                                     && cpar.layout().isEnvironment()) {
1644                                                 if (!previous)
1645                                                         layout = cpar.layout().name();
1646                                                 split_depth = cpar.params().depth();
1647                                 }
1648                                 if (cpar.params().depth() == 0)
1649                                         break;
1650                         }
1651                 }
1652                 if ((outer || normal) && cur.pit() < cur.lastpit()) {
1653                         // save nesting of following paragraph
1654                         Paragraph cpar = pars_[cur.pit() + 1];
1655                         nextpar_depth = cpar.params().depth();
1656                 }
1657                 if (before)
1658                         cur.top().setPitPos(cur.pit(), 0);
1659                 if (before || cur.pos() > 0)
1660                         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK));
1661                 else if (previous && cur.nextInset() && cur.nextInset()->lyxCode() == SEPARATOR_CODE)
1662                         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK, "inverse ignoresep"));
1663                 if (outer) {
1664                         while (cur.paragraph().params().depth() > split_depth)
1665                                 lyx::dispatch(FuncRequest(LFUN_DEPTH_DECREMENT));
1666                 }
1667                 DocumentClass const & tc = bv->buffer().params().documentClass();
1668                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, from_ascii("\"") + tc.plainLayout().name()
1669                                           + from_ascii("\" ignoreautonests")));
1670                 // FIXME: Bibitem mess!
1671                 if (cur.prevInset() && cur.prevInset()->lyxCode() == BIBITEM_CODE)
1672                         lyx::dispatch(FuncRequest(LFUN_CHAR_DELETE_BACKWARD));
1673                 lyx::dispatch(FuncRequest(LFUN_SEPARATOR_INSERT, "plain"));
1674                 if (before) {
1675                         cur.backwardPos();
1676                         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK, "inverse ignoresep"));
1677                         while (cur.paragraph().params().depth() < split_depth)
1678                                 lyx::dispatch(FuncRequest(LFUN_DEPTH_INCREMENT));
1679                 }
1680                 else
1681                         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK, "inverse"));
1682                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, layout));
1683                 if ((outer || normal) && nextpar_depth > 0) {
1684                         // restore nesting of following paragraph
1685                         DocIterator scur = cur;
1686                         depth_type const max_depth = cur.paragraph().params().depth() + 1;
1687                         cur.forwardPar();
1688                         while (cur.paragraph().params().depth() < min(nextpar_depth, max_depth)) {
1689                                 depth_type const olddepth = cur.paragraph().params().depth();
1690                                 lyx::dispatch(FuncRequest(LFUN_DEPTH_INCREMENT));
1691                                 if (olddepth == cur.paragraph().params().depth())
1692                                         // leave loop if no incrementation happens
1693                                         break;
1694                         }
1695                         cur.setCursor(scur);
1696                 }
1697
1698                 break;
1699         }
1700
1701         case LFUN_CLIPBOARD_PASTE:
1702                 cap::replaceSelection(cur);
1703                 pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1704                                cmd.argument() == "paragraph");
1705                 bv->buffer().errors("Paste");
1706                 break;
1707
1708         case LFUN_CLIPBOARD_PASTE_SIMPLE:
1709                 cap::replaceSelection(cur);
1710                 pasteSimpleText(cur, cmd.argument() == "paragraph");
1711                 break;
1712
1713         case LFUN_PRIMARY_SELECTION_PASTE:
1714                 cap::replaceSelection(cur);
1715                 pasteString(cur, theSelection().get(),
1716                             cmd.argument() == "paragraph");
1717                 break;
1718
1719         case LFUN_SELECTION_PASTE:
1720                 // Copy the selection buffer to the clipboard stack,
1721                 // because we want it to appear in the "Edit->Paste
1722                 // recent" menu.
1723                 cap::replaceSelection(cur);
1724                 cap::copySelectionToStack();
1725                 cap::pasteSelection(bv->cursor(), bv->buffer().errorList("Paste"));
1726                 bv->buffer().errors("Paste");
1727                 break;
1728
1729         case LFUN_QUOTE_INSERT: {
1730                 cap::replaceSelection(cur);
1731                 cur.recordUndo();
1732
1733                 Paragraph const & par = cur.paragraph();
1734                 pos_type pos = cur.pos();
1735                 // Ignore deleted text before cursor
1736                 while (pos > 0 && par.isDeleted(pos - 1))
1737                         --pos;
1738
1739                 bool const inner = (cmd.getArg(0) == "single" || cmd.getArg(0) == "inner");
1740
1741                 // Guess quote side.
1742                 // A space triggers an opening quote. This is passed if the preceding
1743                 // char/inset is a space or at paragraph start.
1744                 char_type c = ' ';
1745                 if (pos > 0 && !par.isSpace(pos - 1)) {
1746                         if (cur.prevInset() && cur.prevInset()->lyxCode() == QUOTE_CODE) {
1747                                 // If an opening double quotation mark precedes, and this
1748                                 // is a single quote, make it opening as well
1749                                 InsetQuotes & ins =
1750                                         static_cast<InsetQuotes &>(*cur.prevInset());
1751                                 string const type = ins.getType();
1752                                 if (!suffixIs(type, "ld") || !inner)
1753                                         c = par.getChar(pos - 1);
1754                         }
1755                         else if (!cur.prevInset()
1756                             || (cur.prevInset() && cur.prevInset()->isChar()))
1757                                 // If a char precedes, pass that and let InsetQuote decide
1758                                 c = par.getChar(pos - 1);
1759                         else {
1760                                 while (pos > 0) {
1761                                         if (par.getInset(pos - 1)
1762                                             && !par.getInset(pos - 1)->isPartOfTextSequence()) {
1763                                                 // skip "invisible" insets
1764                                                 --pos;
1765                                                 continue;
1766                                         }
1767                                         c = par.getChar(pos - 1);
1768                                         break;
1769                                 }
1770                         }
1771                 }
1772                 InsetQuotesParams::QuoteLevel const quote_level = inner
1773                                 ? InsetQuotesParams::SecondaryQuotes : InsetQuotesParams::PrimaryQuotes;
1774                 cur.insert(new InsetQuotes(cur.buffer(), c, quote_level, cmd.getArg(1), cmd.getArg(2)));
1775                 cur.buffer()->updateBuffer();
1776                 cur.posForward();
1777                 break;
1778         }
1779
1780         case LFUN_MOUSE_TRIPLE:
1781                 if (cmd.button() == mouse_button::button1) {
1782                         if (cur.pos() > 0)
1783                                 setCursor(cur, cur.pit(), 0);
1784                         bv->cursor() = cur;
1785                         cur.resetAnchor();
1786                         if (cur.pos() < cur.lastpos())
1787                                 setCursor(cur, cur.pit(), cur.lastpos());
1788                         cur.setSelection();
1789                         bv->cursor() = cur;
1790                 }
1791                 break;
1792
1793         case LFUN_MOUSE_DOUBLE:
1794                 if (cmd.button() == mouse_button::button1) {
1795                         selectWord(cur, WHOLE_WORD);
1796                         bv->cursor() = cur;
1797                 }
1798                 break;
1799
1800         // Single-click on work area
1801         case LFUN_MOUSE_PRESS: {
1802                 // We are not marking a selection with the keyboard in any case.
1803                 Cursor & bvcur = cur.bv().cursor();
1804                 bvcur.setMark(false);
1805                 switch (cmd.button()) {
1806                 case mouse_button::button1:
1807                         if (!bvcur.selection())
1808                                 // Set the cursor
1809                                 bvcur.resetAnchor();
1810                         if (!bv->mouseSetCursor(cur, cmd.modifier() == ShiftModifier))
1811                                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1812                         if (bvcur.wordSelection())
1813                                 selectWord(bvcur, WHOLE_WORD);
1814                         break;
1815
1816                 case mouse_button::button2:
1817                         if (lyxrc.mouse_middlebutton_paste) {
1818                                 // Middle mouse pasting.
1819                                 bv->mouseSetCursor(cur);
1820                                 lyx::dispatch(
1821                                         FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1822                                                     "selection-paste ; primary-selection-paste paragraph"));
1823                         }
1824                         cur.noScreenUpdate();
1825                         break;
1826
1827                 case mouse_button::button3: {
1828                         // Don't do anything if we right-click a
1829                         // selection, a context menu will popup.
1830                         if (bvcur.selection() && cur >= bvcur.selectionBegin()
1831                             && cur < bvcur.selectionEnd()) {
1832                                 cur.noScreenUpdate();
1833                                 return;
1834                         }
1835                         if (!bv->mouseSetCursor(cur, false))
1836                                 cur.screenUpdateFlags(Update::FitCursor);
1837                         break;
1838                 }
1839
1840                 default:
1841                         break;
1842                 } // switch (cmd.button())
1843                 break;
1844         }
1845         case LFUN_MOUSE_MOTION: {
1846                 // Mouse motion with right or middle mouse do nothing for now.
1847                 if (cmd.button() != mouse_button::button1) {
1848                         cur.noScreenUpdate();
1849                         return;
1850                 }
1851                 // ignore motions deeper nested than the real anchor
1852                 Cursor & bvcur = cur.bv().cursor();
1853                 if (!bvcur.realAnchor().hasPart(cur)) {
1854                         cur.undispatched();
1855                         break;
1856                 }
1857                 CursorSlice old = bvcur.top();
1858
1859                 int const wh = bv->workHeight();
1860                 int const y = max(0, min(wh - 1, cmd.y()));
1861
1862                 tm->setCursorFromCoordinates(cur, cmd.x(), y);
1863                 cur.setTargetX(cmd.x());
1864                 // Don't allow selecting a separator inset
1865                 if (cur.pos() && cur.paragraph().isEnvSeparator(cur.pos() - 1))
1866                         cur.posBackward();
1867                 if (cmd.y() >= wh)
1868                         lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1869                 else if (cmd.y() < 0)
1870                         lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1871                 // This is to allow jumping over large insets
1872                 if (cur.top() == old) {
1873                         if (cmd.y() >= wh)
1874                                 lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1875                         else if (cmd.y() < 0)
1876                                 lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1877                 }
1878                 // We continue with our existing selection or start a new one, so don't
1879                 // reset the anchor.
1880                 bvcur.setCursor(cur);
1881                 bvcur.selection(true);
1882                 bvcur.setCurrentFont();
1883                 if (cur.top() == old) {
1884                         // We didn't move one iota, so no need to update the screen.
1885                         cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1886                         //cur.noScreenUpdate();
1887                         return;
1888                 }
1889                 break;
1890         }
1891
1892         case LFUN_MOUSE_RELEASE:
1893                 switch (cmd.button()) {
1894                 case mouse_button::button1:
1895                         // Cursor was set at LFUN_MOUSE_PRESS or LFUN_MOUSE_MOTION time.
1896                         // If there is a new selection, update persistent selection;
1897                         // otherwise, single click does not clear persistent selection
1898                         // buffer.
1899                         if (cur.selection()) {
1900                                 // Finish selection. If double click,
1901                                 // cur is moved to the end of word by
1902                                 // selectWord but bvcur is current
1903                                 // mouse position.
1904                                 cur.bv().cursor().setSelection();
1905                                 // We might have removed an empty but drawn selection
1906                                 // (probably a margin)
1907                                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1908                         } else
1909                                 cur.noScreenUpdate();
1910                         // FIXME: We could try to handle drag and drop of selection here.
1911                         return;
1912
1913                 case mouse_button::button2:
1914                         // Middle mouse pasting is handled at mouse press time,
1915                         // see LFUN_MOUSE_PRESS.
1916                         cur.noScreenUpdate();
1917                         return;
1918
1919                 case mouse_button::button3:
1920                         // Cursor was set at LFUN_MOUSE_PRESS time.
1921                         // FIXME: If there is a selection we could try to handle a special
1922                         // drag & drop context menu.
1923                         cur.noScreenUpdate();
1924                         return;
1925
1926                 case mouse_button::none:
1927                 case mouse_button::button4:
1928                 case mouse_button::button5:
1929                         break;
1930                 } // switch (cmd.button())
1931
1932                 break;
1933
1934         case LFUN_SELF_INSERT: {
1935                 if (cmd.argument().empty())
1936                         break;
1937
1938                 // Automatically delete the currently selected
1939                 // text and replace it with what is being
1940                 // typed in now. Depends on lyxrc settings
1941                 // "auto_region_delete", which defaults to
1942                 // true (on).
1943
1944                 if (lyxrc.auto_region_delete && cur.selection())
1945                         cutSelection(cur, false);
1946                 cur.clearSelection();
1947
1948                 for (char_type c : cmd.argument())
1949                         bv->translateAndInsert(c, this, cur);
1950
1951                 cur.resetAnchor();
1952                 moveCursor(cur, false);
1953                 cur.markNewWordPosition();
1954                 bv->bookmarkEditPosition();
1955                 break;
1956         }
1957
1958         case LFUN_HREF_INSERT: {
1959                 docstring content = cmd.argument();
1960                 if (content.empty() && cur.selection())
1961                         content = cur.selectionAsString(false);
1962
1963                 InsetCommandParams p(HYPERLINK_CODE);
1964                 if (!content.empty()){
1965                         // if it looks like a link, we'll put it as target,
1966                         // otherwise as name (bug #8792).
1967
1968                         // We can't do:
1969                         //   regex_match(to_utf8(content), matches, link_re)
1970                         // because smatch stores pointers to the substrings rather
1971                         // than making copies of them. And those pointers become
1972                         // invalid after regex_match returns, since it is then
1973                         // being given a temporary object. (Thanks to Georg for
1974                         // figuring that out.)
1975                         regex const link_re("^([a-z]+):.*");
1976                         smatch matches;
1977                         string const c = to_utf8(lowercase(content));
1978
1979                         if (c.substr(0,7) == "mailto:") {
1980                                 p["target"] = content;
1981                                 p["type"] = from_ascii("mailto:");
1982                         } else if (regex_match(c, matches, link_re)) {
1983                                 p["target"] = content;
1984                                 string protocol = matches.str(1);
1985                                 if (protocol == "file")
1986                                         p["type"] = from_ascii("file:");
1987                         } else
1988                                 p["name"] = content;
1989                 }
1990                 string const data = InsetCommand::params2string(p);
1991
1992                 // we need to have a target. if we already have one, then
1993                 // that gets used at the default for the name, too, which
1994                 // is probably what is wanted.
1995                 if (p["target"].empty()) {
1996                         bv->showDialog("href", data);
1997                 } else {
1998                         FuncRequest fr(LFUN_INSET_INSERT, data);
1999                         dispatch(cur, fr);
2000                 }
2001                 break;
2002         }
2003
2004         case LFUN_LABEL_INSERT: {
2005                 InsetCommandParams p(LABEL_CODE);
2006                 // Try to generate a valid label
2007                 p["name"] = (cmd.argument().empty()) ?
2008                         cur.getPossibleLabel() :
2009                         cmd.argument();
2010                 string const data = InsetCommand::params2string(p);
2011
2012                 if (cmd.argument().empty()) {
2013                         bv->showDialog("label", data);
2014                 } else {
2015                         FuncRequest fr(LFUN_INSET_INSERT, data);
2016                         dispatch(cur, fr);
2017                 }
2018                 break;
2019         }
2020
2021         case LFUN_INFO_INSERT: {
2022                 if (cmd.argument().empty()) {
2023                         bv->showDialog("info", cur.current_font.language()->lang());
2024                 } else {
2025                         Inset * inset;
2026                         inset = createInset(cur.buffer(), cmd);
2027                         if (!inset)
2028                                 break;
2029                         cur.recordUndo();
2030                         insertInset(cur, inset);
2031                         cur.forceBufferUpdate();
2032                         cur.posForward();
2033                 }
2034                 break;
2035         }
2036         case LFUN_CAPTION_INSERT:
2037         case LFUN_FOOTNOTE_INSERT:
2038         case LFUN_NOTE_INSERT:
2039         case LFUN_BOX_INSERT:
2040         case LFUN_BRANCH_INSERT:
2041         case LFUN_PHANTOM_INSERT:
2042         case LFUN_ERT_INSERT:
2043         case LFUN_LISTING_INSERT:
2044         case LFUN_MARGINALNOTE_INSERT:
2045         case LFUN_ARGUMENT_INSERT:
2046         case LFUN_INDEX_INSERT:
2047         case LFUN_PREVIEW_INSERT:
2048         case LFUN_SCRIPT_INSERT:
2049         case LFUN_IPA_INSERT:
2050                 // Open the inset, and move the current selection
2051                 // inside it.
2052                 doInsertInset(cur, this, cmd, true, true);
2053                 cur.posForward();
2054                 if (act == LFUN_SCRIPT_INSERT) {
2055                         /* Script insets change the font style in metrics(), and
2056                          * this is used to compute the height of the caret
2057                          * (because the font is stored in TextMetrics::font_).
2058                          * When we insert, we have to make sure that metrics are
2059                          * computed so that the caret height is wrong. Arguably,
2060                          * this is hackish.*/
2061                         bv->processUpdateFlags(Update::SinglePar);
2062                 }
2063                 cur.setCurrentFont();
2064                 // Some insets are numbered, others are shown in the outline pane so
2065                 // let's update the labels and the toc backend.
2066                 cur.forceBufferUpdate();
2067                 break;
2068
2069         case LFUN_FLEX_INSERT: {
2070                 // Open the inset, and move the current selection
2071                 // inside it.
2072                 bool const sel = cur.selection();
2073                 doInsertInset(cur, this, cmd, true, true);
2074                 // Insert auto-insert arguments
2075                 bool autoargs, inautoarg = false;
2076                 Layout::LaTeXArgMap args = cur.inset().getLayout().args();
2077                 Layout::LaTeXArgMap::const_iterator lait = args.begin();
2078                 Layout::LaTeXArgMap::const_iterator const laend = args.end();
2079                 for (; lait != laend; ++lait) {
2080                         Layout::latexarg arg = (*lait).second;
2081                         if (arg.autoinsert) {
2082                                 // The cursor might have been invalidated by the replaceSelection.
2083                                 cur.buffer()->changed(true);
2084                                 // If we had already inserted an arg automatically,
2085                                 // leave this now in order to insert the next one.
2086                                 if (inautoarg) {
2087                                         cur.leaveInset(cur.inset());
2088                                         cur.posForward();
2089                                         inautoarg = false;
2090                                 }
2091                                 FuncRequest cmd2(LFUN_ARGUMENT_INSERT, (*lait).first);
2092                                 lyx::dispatch(cmd2);
2093                                 autoargs = true;
2094                                 inautoarg = true;
2095                         }
2096                 }
2097                 if (!autoargs) {
2098                         if (sel)
2099                                 cur.leaveInset(cur.inset());
2100                         cur.posForward();
2101                 }
2102                 // Some insets are numbered, others are shown in the outline pane so
2103                 // let's update the labels and the toc backend.
2104                 cur.forceBufferUpdate();
2105                 break;
2106         }
2107
2108         case LFUN_TABULAR_INSERT: {
2109                 // if there were no arguments, just open the dialog
2110                 if (cmd.argument().empty()) {
2111                         bv->showDialog("tabularcreate");
2112                         break;
2113                 } else if (cur.buffer()->masterParams().tablestyle != "default"
2114                            || bv->buffer().params().documentClass().tablestyle() != "default") {
2115                         string tabstyle = cur.buffer()->masterParams().tablestyle;
2116                         if (tabstyle == "default")
2117                                 tabstyle = bv->buffer().params().documentClass().tablestyle();
2118                         if (!libFileSearch("tabletemplates", tabstyle + ".lyx").empty()) {
2119                                 FuncRequest fr(LFUN_TABULAR_STYLE_INSERT,
2120                                                tabstyle + " " + to_ascii(cmd.argument()));
2121                                 lyx::dispatch(fr);
2122                                 break;
2123                         } else
2124                                 // Unknown style. Report and fall back to default.
2125                                 cur.errorMessage(from_utf8(N_("Table Style ")) + from_utf8(tabstyle) +
2126                                                      from_utf8(N_(" not known")));
2127                         
2128                 }
2129                 if (doInsertInset(cur, this, cmd, false, true))
2130                         cur.posForward();
2131                 break;
2132         }
2133
2134         case LFUN_TABULAR_STYLE_INSERT: {
2135                 string const style = cmd.getArg(0);
2136                 string const rows = cmd.getArg(1);
2137                 string const cols = cmd.getArg(2);
2138                 if (cols.empty() || !isStrInt(cols)
2139                     || rows.empty() || !isStrInt(rows))
2140                         break;
2141                 int const r = convert<int>(rows);
2142                 int const c = convert<int>(cols);
2143                         
2144                 string suffix;
2145                 if (r == 1)
2146                         suffix = "_1x1";
2147                 else if (r == 2)
2148                         suffix = "_1x2";
2149                 FileName const tabstyle = libFileSearch("tabletemplates",
2150                                                         style + suffix + ".lyx", "lyx");
2151                 if (tabstyle.empty())
2152                             break;
2153                 UndoGroupHelper ugh(cur.buffer());
2154                 cur.recordUndo();
2155                 FuncRequest cmd2(LFUN_FILE_INSERT, tabstyle.absFileName() + " ignorelang");
2156                 lyx::dispatch(cmd2);
2157                 // go into table
2158                 cur.backwardPos();
2159                 if (r > 2) {
2160                         // move one cell up to middle cell
2161                         cur.up();
2162                         // add the missing rows
2163                         int const addrows = r - 3;
2164                         for (int i = 0 ; i < addrows ; ++i) {
2165                                 FuncRequest fr(LFUN_TABULAR_FEATURE, "append-row");
2166                                 lyx::dispatch(fr);
2167                         }
2168                 }
2169                 // add the missing columns
2170                 int const addcols = c - 1;
2171                 for (int i = 0 ; i < addcols ; ++i) {
2172                         FuncRequest fr(LFUN_TABULAR_FEATURE, "append-column");
2173                         lyx::dispatch(fr);
2174                 }
2175                 if (r > 1)
2176                         // go to first cell
2177                         cur.up();
2178                 break;
2179         }
2180
2181         case LFUN_FLOAT_INSERT:
2182         case LFUN_FLOAT_WIDE_INSERT:
2183         case LFUN_WRAP_INSERT: {
2184                 // will some content be moved into the inset?
2185                 bool const content = cur.selection();
2186                 // does the content consist of multiple paragraphs?
2187                 bool const singlepar = (cur.selBegin().pit() == cur.selEnd().pit());
2188
2189                 doInsertInset(cur, this, cmd, true, true);
2190                 cur.posForward();
2191
2192                 // If some single-par content is moved into the inset,
2193                 // doInsertInset puts the cursor outside the inset.
2194                 // To insert the caption we put it back into the inset.
2195                 // FIXME cleanup doInsertInset to avoid such dances!
2196                 if (content && singlepar)
2197                         cur.backwardPos();
2198
2199                 ParagraphList & pars = cur.text()->paragraphs();
2200
2201                 DocumentClass const & tclass = bv->buffer().params().documentClass();
2202
2203                 // add a separate paragraph for the caption inset
2204                 pars.push_back(Paragraph());
2205                 pars.back().setInsetOwner(&cur.text()->inset());
2206                 pars.back().setPlainOrDefaultLayout(tclass);
2207                 int cap_pit = pars.size() - 1;
2208
2209                 // if an empty inset was created, we create an additional empty
2210                 // paragraph at the bottom so that the user can choose where to put
2211                 // the graphics (or table).
2212                 if (!content) {
2213                         pars.push_back(Paragraph());
2214                         pars.back().setInsetOwner(&cur.text()->inset());
2215                         pars.back().setPlainOrDefaultLayout(tclass);
2216                 }
2217
2218                 // reposition the cursor to the caption
2219                 cur.pit() = cap_pit;
2220                 cur.pos() = 0;
2221                 // FIXME: This Text/Cursor dispatch handling is a mess!
2222                 // We cannot use Cursor::dispatch here it needs access to up to
2223                 // date metrics.
2224                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
2225                 doInsertInset(cur, cur.text(), cmd_caption, true, false);
2226                 cur.forceBufferUpdate();
2227                 cur.screenUpdateFlags(Update::Force);
2228                 // FIXME: When leaving the Float (or Wrap) inset we should
2229                 // delete any empty paragraph left above or below the
2230                 // caption.
2231                 break;
2232         }
2233
2234         case LFUN_NOMENCL_INSERT: {
2235                 InsetCommandParams p(NOMENCL_CODE);
2236                 if (cmd.argument().empty()) {
2237                         p["symbol"] = 
2238                                 bv->cursor().innerText()->getStringForDialog(bv->cursor());
2239                         cur.clearSelection();
2240                 } else
2241                         p["symbol"] = cmd.argument();
2242                 string const data = InsetCommand::params2string(p);
2243                 bv->showDialog("nomenclature", data);
2244                 break;
2245         }
2246
2247         case LFUN_INDEX_PRINT: {
2248                 InsetCommandParams p(INDEX_PRINT_CODE);
2249                 if (cmd.argument().empty())
2250                         p["type"] = from_ascii("idx");
2251                 else
2252                         p["type"] = cmd.argument();
2253                 string const data = InsetCommand::params2string(p);
2254                 FuncRequest fr(LFUN_INSET_INSERT, data);
2255                 dispatch(cur, fr);
2256                 break;
2257         }
2258
2259         case LFUN_NOMENCL_PRINT:
2260         case LFUN_NEWPAGE_INSERT:
2261                 // do nothing fancy
2262                 doInsertInset(cur, this, cmd, false, false);
2263                 cur.posForward();
2264                 break;
2265
2266         case LFUN_SEPARATOR_INSERT: {
2267                 doInsertInset(cur, this, cmd, false, false);
2268                 cur.posForward();
2269                 // remove a following space
2270                 Paragraph & par = cur.paragraph();
2271                 if (cur.pos() != cur.lastpos() && par.isLineSeparator(cur.pos()))
2272                     par.eraseChar(cur.pos(), cur.buffer()->params().track_changes);
2273                 break;
2274         }
2275
2276         case LFUN_DEPTH_DECREMENT:
2277                 changeDepth(cur, DEC_DEPTH);
2278                 break;
2279
2280         case LFUN_DEPTH_INCREMENT:
2281                 changeDepth(cur, INC_DEPTH);
2282                 break;
2283
2284         case LFUN_REGEXP_MODE:
2285                 regexpDispatch(cur, cmd);
2286                 break;
2287
2288         case LFUN_MATH_MODE: {
2289                 if (cmd.argument() == "on" || cmd.argument() == "") {
2290                         // don't pass "on" as argument
2291                         // (it would appear literally in the first cell)
2292                         docstring sel = cur.selectionAsString(false);
2293                         InsetMathMacroTemplate * macro = new InsetMathMacroTemplate(cur.buffer());
2294                         // create a macro template if we see "\\newcommand" somewhere, and
2295                         // an ordinary formula otherwise
2296                         if (!sel.empty()
2297                                 && (sel.find(from_ascii("\\newcommand")) != string::npos
2298                                         || sel.find(from_ascii("\\newlyxcommand")) != string::npos
2299                                         || sel.find(from_ascii("\\def")) != string::npos)
2300                                 && macro->fromString(sel)) {
2301                                 cur.recordUndo();
2302                                 replaceSelection(cur);
2303                                 cur.insert(macro);
2304                         } else {
2305                                 // no meaningful macro template was found
2306                                 delete macro;
2307                                 mathDispatch(cur,FuncRequest(LFUN_MATH_MODE));
2308                         }
2309                 } else
2310                         // The argument is meaningful
2311                         // We replace cmd with LFUN_MATH_INSERT because LFUN_MATH_MODE
2312                         // has a different meaning in math mode
2313                         mathDispatch(cur, FuncRequest(LFUN_MATH_INSERT,cmd.argument()));
2314                 break;
2315         }
2316
2317         case LFUN_MATH_MACRO:
2318                 if (cmd.argument().empty())
2319                         cur.errorMessage(from_utf8(N_("Missing argument")));
2320                 else {
2321                         cur.recordUndo();
2322                         string s = to_utf8(cmd.argument());
2323                         string const s1 = token(s, ' ', 1);
2324                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
2325                         string const s2 = token(s, ' ', 2);
2326                         MacroType type = MacroTypeNewcommand;
2327                         if (s2 == "def")
2328                                 type = MacroTypeDef;
2329                         InsetMathMacroTemplate * inset = new InsetMathMacroTemplate(cur.buffer(),
2330                                 from_utf8(token(s, ' ', 0)), nargs, false, type);
2331                         inset->setBuffer(bv->buffer());
2332                         insertInset(cur, inset);
2333
2334                         // enter macro inset and select the name
2335                         cur.push(*inset);
2336                         cur.top().pos() = cur.top().lastpos();
2337                         cur.resetAnchor();
2338                         cur.selection(true);
2339                         cur.top().pos() = 0;
2340                 }
2341                 break;
2342
2343         case LFUN_MATH_DISPLAY:
2344         case LFUN_MATH_SUBSCRIPT:
2345         case LFUN_MATH_SUPERSCRIPT:
2346         case LFUN_MATH_INSERT:
2347         case LFUN_MATH_AMS_MATRIX:
2348         case LFUN_MATH_MATRIX:
2349         case LFUN_MATH_DELIM:
2350         case LFUN_MATH_BIGDELIM:
2351                 mathDispatch(cur, cmd);
2352                 break;
2353
2354         case LFUN_FONT_EMPH: {
2355                 Font font(ignore_font, ignore_language);
2356                 font.fontInfo().setEmph(FONT_TOGGLE);
2357                 toggleAndShow(cur, this, font);
2358                 break;
2359         }
2360
2361         case LFUN_FONT_ITAL: {
2362                 Font font(ignore_font, ignore_language);
2363                 font.fontInfo().setShape(ITALIC_SHAPE);
2364                 toggleAndShow(cur, this, font);
2365                 break;
2366         }
2367
2368         case LFUN_FONT_BOLD:
2369         case LFUN_FONT_BOLDSYMBOL: {
2370                 Font font(ignore_font, ignore_language);
2371                 font.fontInfo().setSeries(BOLD_SERIES);
2372                 toggleAndShow(cur, this, font);
2373                 break;
2374         }
2375
2376         case LFUN_FONT_NOUN: {
2377                 Font font(ignore_font, ignore_language);
2378                 font.fontInfo().setNoun(FONT_TOGGLE);
2379                 toggleAndShow(cur, this, font);
2380                 break;
2381         }
2382
2383         case LFUN_FONT_TYPEWRITER: {
2384                 Font font(ignore_font, ignore_language);
2385                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
2386                 toggleAndShow(cur, this, font);
2387                 break;
2388         }
2389
2390         case LFUN_FONT_SANS: {
2391                 Font font(ignore_font, ignore_language);
2392                 font.fontInfo().setFamily(SANS_FAMILY);
2393                 toggleAndShow(cur, this, font);
2394                 break;
2395         }
2396
2397         case LFUN_FONT_ROMAN: {
2398                 Font font(ignore_font, ignore_language);
2399                 font.fontInfo().setFamily(ROMAN_FAMILY);
2400                 toggleAndShow(cur, this, font);
2401                 break;
2402         }
2403
2404         case LFUN_FONT_DEFAULT: {
2405                 Font font(inherit_font, ignore_language);
2406                 toggleAndShow(cur, this, font);
2407                 break;
2408         }
2409
2410         case LFUN_FONT_STRIKEOUT: {
2411                 Font font(ignore_font, ignore_language);
2412                 font.fontInfo().setStrikeout(FONT_TOGGLE);
2413                 toggleAndShow(cur, this, font);
2414                 break;
2415         }
2416
2417         case LFUN_FONT_CROSSOUT: {
2418                 Font font(ignore_font, ignore_language);
2419                 font.fontInfo().setXout(FONT_TOGGLE);
2420                 toggleAndShow(cur, this, font);
2421                 break;
2422         }
2423
2424         case LFUN_FONT_UNDERUNDERLINE: {
2425                 Font font(ignore_font, ignore_language);
2426                 font.fontInfo().setUuline(FONT_TOGGLE);
2427                 toggleAndShow(cur, this, font);
2428                 break;
2429         }
2430
2431         case LFUN_FONT_UNDERWAVE: {
2432                 Font font(ignore_font, ignore_language);
2433                 font.fontInfo().setUwave(FONT_TOGGLE);
2434                 toggleAndShow(cur, this, font);
2435                 break;
2436         }
2437
2438         case LFUN_FONT_UNDERLINE: {
2439                 Font font(ignore_font, ignore_language);
2440                 font.fontInfo().setUnderbar(FONT_TOGGLE);
2441                 toggleAndShow(cur, this, font);
2442                 break;
2443         }
2444
2445         case LFUN_FONT_SIZE: {
2446                 Font font(ignore_font, ignore_language);
2447                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
2448                 toggleAndShow(cur, this, font);
2449                 break;
2450         }
2451
2452         case LFUN_LANGUAGE: {
2453                 string const lang_arg = cmd.getArg(0);
2454                 bool const reset = (lang_arg.empty() || lang_arg == "reset");
2455                 Language const * lang =
2456                         reset ? reset_language
2457                               : languages.getLanguage(lang_arg);
2458                 // we allow reset_language, which is 0, but only if it
2459                 // was requested via empty or "reset" arg.
2460                 if (!lang && !reset)
2461                         break;
2462                 bool const toggle = (cmd.getArg(1) != "set");
2463                 selectWordWhenUnderCursor(cur, WHOLE_WORD_STRICT);
2464                 Font font(ignore_font, lang);
2465                 toggleAndShow(cur, this, font, toggle);
2466                 // We need a buffer update if we change the language
2467                 // of an info inset
2468                 if (cur.insetInSelection(INFO_CODE))
2469                         cur.forceBufferUpdate();
2470                 break;
2471         }
2472
2473         case LFUN_TEXTSTYLE_APPLY: {
2474                 unsigned int num = 0;
2475                 string const arg = to_utf8(cmd.argument());
2476                 // Argument?
2477                 if (!arg.empty()) {
2478                         if (isStrUnsignedInt(arg)) {
2479                                 num = convert<uint>(arg);
2480                                 if (num >= freeFonts.size()) {
2481                                         cur.message(_("Invalid argument (number exceeds stack size)!"));
2482                                         break;
2483                                 }
2484                         } else {
2485                                 cur.message(_("Invalid argument (must be a non-negative number)!"));
2486                                 break;
2487                         }
2488                 }
2489                 toggleAndShow(cur, this, freeFonts[num].second, toggleall);
2490                 cur.message(bformat(_("Text properties applied: %1$s"), freeFonts[num].first));
2491                 break;
2492         }
2493
2494         // Set the freefont using the contents of \param data dispatched from
2495         // the frontends and apply it at the current cursor location.
2496         case LFUN_TEXTSTYLE_UPDATE: {
2497                 Font font(ignore_font, ignore_language);
2498                 bool toggle;
2499                 if (font.fromString(to_utf8(cmd.argument()), toggle)) {
2500                         docstring const props = font.stateText(&bv->buffer().params(), true);
2501                         freeFonts.push(make_pair(props, font));
2502                         toggleall = toggle;
2503                         toggleAndShow(cur, this, font, toggleall);
2504                         // We need a buffer update if we change the language
2505                         // of an info inset
2506                         if (cur.insetInSelection(INFO_CODE))
2507                                 cur.forceBufferUpdate();
2508                         cur.message(bformat(_("Text properties applied: %1$s"), props));
2509                 } else
2510                         LYXERR0("Invalid argument of textstyle-update");
2511                 break;
2512         }
2513
2514         case LFUN_FINISHED_LEFT:
2515                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
2516                 // We're leaving an inset, going left. If the inset is LTR, we're
2517                 // leaving from the front, so we should not move (remain at --- but
2518                 // not in --- the inset). If the inset is RTL, move left, without
2519                 // entering the inset itself; i.e., move to after the inset.
2520                 if (cur.paragraph().getFontSettings(
2521                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
2522                         cursorVisLeft(cur, true);
2523                 break;
2524
2525         case LFUN_FINISHED_RIGHT:
2526                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
2527                 // We're leaving an inset, going right. If the inset is RTL, we're
2528                 // leaving from the front, so we should not move (remain at --- but
2529                 // not in --- the inset). If the inset is LTR, move right, without
2530                 // entering the inset itself; i.e., move to after the inset.
2531                 if (!cur.paragraph().getFontSettings(
2532                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
2533                         cursorVisRight(cur, true);
2534                 break;
2535
2536         case LFUN_FINISHED_BACKWARD:
2537                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
2538                 cur.setCurrentFont();
2539                 break;
2540
2541         case LFUN_FINISHED_FORWARD:
2542                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
2543                 ++cur.pos();
2544                 cur.setCurrentFont();
2545                 break;
2546
2547         case LFUN_LAYOUT_PARAGRAPH: {
2548                 string data;
2549                 params2string(cur.paragraph(), data);
2550                 data = "show\n" + data;
2551                 bv->showDialog("paragraph", data);
2552                 break;
2553         }
2554
2555         case LFUN_PARAGRAPH_UPDATE: {
2556                 string data;
2557                 params2string(cur.paragraph(), data);
2558
2559                 // Will the paragraph accept changes from the dialog?
2560                 bool const accept =
2561                         cur.inset().allowParagraphCustomization(cur.idx());
2562
2563                 data = "update " + convert<string>(accept) + '\n' + data;
2564                 bv->updateDialog("paragraph", data);
2565                 break;
2566         }
2567
2568         case LFUN_ACCENT_UMLAUT:
2569         case LFUN_ACCENT_CIRCUMFLEX:
2570         case LFUN_ACCENT_GRAVE:
2571         case LFUN_ACCENT_ACUTE:
2572         case LFUN_ACCENT_TILDE:
2573         case LFUN_ACCENT_PERISPOMENI:
2574         case LFUN_ACCENT_CEDILLA:
2575         case LFUN_ACCENT_MACRON:
2576         case LFUN_ACCENT_DOT:
2577         case LFUN_ACCENT_UNDERDOT:
2578         case LFUN_ACCENT_UNDERBAR:
2579         case LFUN_ACCENT_CARON:
2580         case LFUN_ACCENT_BREVE:
2581         case LFUN_ACCENT_TIE:
2582         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2583         case LFUN_ACCENT_CIRCLE:
2584         case LFUN_ACCENT_OGONEK:
2585                 theApp()->handleKeyFunc(cmd.action());
2586                 if (!cmd.argument().empty())
2587                         // FIXME: Are all these characters encoded in one byte in utf8?
2588                         bv->translateAndInsert(cmd.argument()[0], this, cur);
2589                 cur.screenUpdateFlags(Update::FitCursor);
2590                 break;
2591
2592         case LFUN_FLOAT_LIST_INSERT: {
2593                 DocumentClass const & tclass = bv->buffer().params().documentClass();
2594                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
2595                         cur.recordUndo();
2596                         if (cur.selection())
2597                                 cutSelection(cur, false);
2598                         breakParagraph(cur);
2599
2600                         if (cur.lastpos() != 0) {
2601                                 cursorBackward(cur);
2602                                 breakParagraph(cur);
2603                         }
2604
2605                         docstring const laystr = cur.inset().usePlainLayout() ?
2606                                 tclass.plainLayoutName() :
2607                                 tclass.defaultLayoutName();
2608                         setLayout(cur, laystr);
2609                         ParagraphParameters p;
2610                         // FIXME If this call were replaced with one to clearParagraphParams(),
2611                         // then we could get rid of this method altogether.
2612                         setParagraphs(cur, p);
2613                         // FIXME This should be simplified when InsetFloatList takes a
2614                         // Buffer in its constructor.
2615                         InsetFloatList * ifl = new InsetFloatList(cur.buffer(), to_utf8(cmd.argument()));
2616                         ifl->setBuffer(bv->buffer());
2617                         insertInset(cur, ifl);
2618                         cur.posForward();
2619                 } else {
2620                         lyxerr << "Non-existent float type: "
2621                                << to_utf8(cmd.argument()) << endl;
2622                 }
2623                 break;
2624         }
2625
2626         case LFUN_CHANGE_ACCEPT: {
2627                 acceptOrRejectChanges(cur, ACCEPT);
2628                 break;
2629         }
2630
2631         case LFUN_CHANGE_REJECT: {
2632                 acceptOrRejectChanges(cur, REJECT);
2633                 break;
2634         }
2635
2636         case LFUN_THESAURUS_ENTRY: {
2637                 Language const * language = cur.getFont().language();
2638                 docstring arg = cmd.argument();
2639                 if (arg.empty()) {
2640                         arg = cur.selectionAsString(false);
2641                         // FIXME
2642                         if (arg.size() > 100 || arg.empty()) {
2643                                 // Get word or selection
2644                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2645                                 arg = cur.selectionAsString(false);
2646                                 arg += " lang=" + from_ascii(language->lang());
2647                         }
2648                 } else {
2649                         string lang = cmd.getArg(1);
2650                         // This duplicates the code in GuiThesaurus::initialiseParams
2651                         if (prefixIs(lang, "lang=")) {
2652                                 language = languages.getLanguage(lang.substr(5));
2653                                 if (!language)
2654                                         language = cur.getFont().language();
2655                         }
2656                 }
2657                 string lang = language->code();
2658                 if (lyxrc.thesaurusdir_path.empty() && !thesaurus.thesaurusInstalled(from_ascii(lang))) {
2659                         LYXERR(Debug::ACTION, "Command " << cmd << ". Thesaurus not found for language " << lang);
2660                         frontend::Alert::warning(_("Path to thesaurus directory not set!"),
2661                                         _("The path to the thesaurus directory has not been specified.\n"
2662                                           "The thesaurus is not functional.\n"
2663                                           "Please refer to sec. 6.15.1 of the User's Guide for setup\n"
2664                                           "instructions."));
2665                 }
2666                 bv->showDialog("thesaurus", to_utf8(arg));
2667                 break;
2668         }
2669
2670         case LFUN_SPELLING_ADD: {
2671                 Language const * language = getLanguage(cur, cmd.getArg(1));
2672                 docstring word = from_utf8(cmd.getArg(0));
2673                 if (word.empty()) {
2674                         word = cur.selectionAsString(false);
2675                         // FIXME
2676                         if (word.size() > 100 || word.empty()) {
2677                                 // Get word or selection
2678                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2679                                 word = cur.selectionAsString(false);
2680                         }
2681                 }
2682                 WordLangTuple wl(word, language);
2683                 theSpellChecker()->insert(wl);
2684                 break;
2685         }
2686
2687         case LFUN_SPELLING_IGNORE: {
2688                 Language const * language = getLanguage(cur, cmd.getArg(1));
2689                 docstring word = from_utf8(cmd.getArg(0));
2690                 if (word.empty()) {
2691                         word = cur.selectionAsString(false);
2692                         // FIXME
2693                         if (word.size() > 100 || word.empty()) {
2694                                 // Get word or selection
2695                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2696                                 word = cur.selectionAsString(false);
2697                         }
2698                 }
2699                 WordLangTuple wl(word, language);
2700                 theSpellChecker()->accept(wl);
2701                 break;
2702         }
2703
2704         case LFUN_SPELLING_REMOVE: {
2705                 Language const * language = getLanguage(cur, cmd.getArg(1));
2706                 docstring word = from_utf8(cmd.getArg(0));
2707                 if (word.empty()) {
2708                         word = cur.selectionAsString(false);
2709                         // FIXME
2710                         if (word.size() > 100 || word.empty()) {
2711                                 // Get word or selection
2712                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2713                                 word = cur.selectionAsString(false);
2714                         }
2715                 }
2716                 WordLangTuple wl(word, language);
2717                 theSpellChecker()->remove(wl);
2718                 break;
2719         }
2720
2721         case LFUN_PARAGRAPH_PARAMS_APPLY: {
2722                 // Given data, an encoding of the ParagraphParameters
2723                 // generated in the Paragraph dialog, this function sets
2724                 // the current paragraph, or currently selected paragraphs,
2725                 // appropriately.
2726                 // NOTE: This function overrides all existing settings.
2727                 setParagraphs(cur, cmd.argument());
2728                 cur.message(_("Paragraph layout set"));
2729                 break;
2730         }
2731
2732         case LFUN_PARAGRAPH_PARAMS: {
2733                 // Given data, an encoding of the ParagraphParameters as we'd
2734                 // find them in a LyX file, this function modifies the current paragraph,
2735                 // or currently selected paragraphs.
2736                 // NOTE: This function only modifies, and does not override, existing
2737                 // settings.
2738                 setParagraphs(cur, cmd.argument(), true);
2739                 cur.message(_("Paragraph layout set"));
2740                 break;
2741         }
2742
2743         case LFUN_ESCAPE:
2744                 if (cur.selection()) {
2745                         cur.selection(false);
2746                 } else {
2747                         cur.undispatched();
2748                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
2749                         // correct, but I'm not 100% sure -- dov, 071019
2750                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
2751                 }
2752                 break;
2753
2754         case LFUN_OUTLINE_UP:
2755                 outline(OutlineUp, cur, this);
2756                 setCursor(cur, cur.pit(), 0);
2757                 cur.forceBufferUpdate();
2758                 needsUpdate = true;
2759                 break;
2760
2761         case LFUN_OUTLINE_DOWN:
2762                 outline(OutlineDown, cur, this);
2763                 setCursor(cur, cur.pit(), 0);
2764                 cur.forceBufferUpdate();
2765                 needsUpdate = true;
2766                 break;
2767
2768         case LFUN_OUTLINE_IN:
2769                 outline(OutlineIn, cur, this);
2770                 cur.forceBufferUpdate();
2771                 needsUpdate = true;
2772                 break;
2773
2774         case LFUN_OUTLINE_OUT:
2775                 outline(OutlineOut, cur, this);
2776                 cur.forceBufferUpdate();
2777                 needsUpdate = true;
2778                 break;
2779
2780         case LFUN_SERVER_GET_STATISTICS:
2781                 {
2782                         DocIterator from, to;
2783                         if (cur.selection()) {
2784                                 from = cur.selectionBegin();
2785                                 to = cur.selectionEnd();
2786                         } else {
2787                                 from = doc_iterator_begin(cur.buffer());
2788                                 to = doc_iterator_end(cur.buffer());
2789                         }
2790
2791                         cur.buffer()->updateStatistics(from, to);
2792                         string const arg0 = cmd.getArg(0);
2793                         if (arg0 == "words") {
2794                                 cur.message(convert<docstring>(cur.buffer()->wordCount()));
2795                         } else if (arg0 == "chars") {
2796                                 cur.message(convert<docstring>(cur.buffer()->charCount(false)));
2797                         } else if (arg0 == "chars-space") {
2798                                 cur.message(convert<docstring>(cur.buffer()->charCount(true)));
2799                         } else {
2800                                 cur.message(convert<docstring>(cur.buffer()->wordCount()) + " "
2801                                 + convert<docstring>(cur.buffer()->charCount(false)) + " "
2802                                 + convert<docstring>(cur.buffer()->charCount(true)));
2803                         }
2804                 }
2805                 break;
2806
2807         default:
2808                 LYXERR(Debug::ACTION, "Command " << cmd << " not DISPATCHED by Text");
2809                 cur.undispatched();
2810                 break;
2811         }
2812
2813         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
2814
2815         if (lyxrc.spellcheck_continuously && !needsUpdate) {
2816                 // Check for misspelled text
2817                 // The redraw is useful because of the painting of
2818                 // misspelled markers depends on the cursor position.
2819                 // Trigger a redraw for cursor moves inside misspelled text.
2820                 if (!cur.inTexted()) {
2821                         // move from regular text to math
2822                         needsUpdate = last_misspelled;
2823                 } else if (oldTopSlice != cur.top() || oldBoundary != cur.boundary()) {
2824                         // move inside regular text
2825                         needsUpdate = last_misspelled
2826                                 || cur.paragraph().isMisspelled(cur.pos(), true);
2827                 }
2828         }
2829
2830         // FIXME: The cursor flag is reset two lines below
2831         // so we need to check here if some of the LFUN did touch that.
2832         // for now only Text::erase() and Text::backspace() do that.
2833         // The plan is to verify all the LFUNs and then to remove this
2834         // singleParUpdate boolean altogether.
2835         if (cur.result().screenUpdate() & Update::Force) {
2836                 singleParUpdate = false;
2837                 needsUpdate = true;
2838         }
2839
2840         // FIXME: the following code should go in favor of fine grained
2841         // update flag treatment.
2842         if (singleParUpdate) {
2843                 // Inserting characters does not change par height in general. So, try
2844                 // to update _only_ this paragraph. BufferView will detect if a full
2845                 // metrics update is needed anyway.
2846                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
2847                 return;
2848         }
2849         if (!needsUpdate
2850             && &oldTopSlice.inset() == &cur.inset()
2851             && oldTopSlice.idx() == cur.idx()
2852             && !oldSelection // oldSelection is a backup of cur.selection() at the beginning of the function.
2853             && !cur.selection())
2854                 // FIXME: it would be better if we could just do this
2855                 //
2856                 //if (cur.result().update() != Update::FitCursor)
2857                 //      cur.noScreenUpdate();
2858                 //
2859                 // But some LFUNs do not set Update::FitCursor when needed, so we
2860                 // do it for all. This is not very harmfull as FitCursor will provoke
2861                 // a full redraw only if needed but still, a proper review of all LFUN
2862                 // should be done and this needsUpdate boolean can then be removed.
2863                 cur.screenUpdateFlags(Update::FitCursor);
2864         else
2865                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
2866 }
2867
2868
2869 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
2870                         FuncStatus & flag) const
2871 {
2872         LBUFERR(this == cur.text());
2873
2874         FontInfo const & fontinfo = cur.real_current_font.fontInfo();
2875         bool enable = true;
2876         bool allow_in_passthru = false;
2877         InsetCode code = NO_CODE;
2878         
2879         switch (cmd.action()) {
2880
2881         case LFUN_DEPTH_DECREMENT:
2882                 enable = changeDepthAllowed(cur, DEC_DEPTH);
2883                 break;
2884
2885         case LFUN_DEPTH_INCREMENT:
2886                 enable = changeDepthAllowed(cur, INC_DEPTH);
2887                 break;
2888
2889         case LFUN_APPENDIX:
2890                 // FIXME We really should not allow this to be put, e.g.,
2891                 // in a footnote, or in ERT. But it would make sense in a
2892                 // branch, so I'm not sure what to do.
2893                 flag.setOnOff(cur.paragraph().params().startOfAppendix());
2894                 break;
2895
2896         case LFUN_DIALOG_SHOW_NEW_INSET:
2897                 if (cmd.argument() == "bibitem")
2898                         code = BIBITEM_CODE;
2899                 else if (cmd.argument() == "bibtex") {
2900                         code = BIBTEX_CODE;
2901                         // not allowed in description items
2902                         enable = !inDescriptionItem(cur);
2903                 }
2904                 else if (cmd.argument() == "box")
2905                         code = BOX_CODE;
2906                 else if (cmd.argument() == "branch")
2907                         code = BRANCH_CODE;
2908                 else if (cmd.argument() == "citation")
2909                         code = CITE_CODE;
2910                 else if (cmd.argument() == "ert")
2911                         code = ERT_CODE;
2912                 else if (cmd.argument() == "external")
2913                         code = EXTERNAL_CODE;
2914                 else if (cmd.argument() == "float")
2915                         code = FLOAT_CODE;
2916                 else if (cmd.argument() == "graphics")
2917                         code = GRAPHICS_CODE;
2918                 else if (cmd.argument() == "href")
2919                         code = HYPERLINK_CODE;
2920                 else if (cmd.argument() == "include")
2921                         code = INCLUDE_CODE;
2922                 else if (cmd.argument() == "index")
2923                         code = INDEX_CODE;
2924                 else if (cmd.argument() == "index_print")
2925                         code = INDEX_PRINT_CODE;
2926                 else if (cmd.argument() == "listings")
2927                         code = LISTINGS_CODE;
2928                 else if (cmd.argument() == "mathspace")
2929                         code = MATH_HULL_CODE;
2930                 else if (cmd.argument() == "nomenclature")
2931                         code = NOMENCL_CODE;
2932                 else if (cmd.argument() == "nomencl_print")
2933                         code = NOMENCL_PRINT_CODE;
2934                 else if (cmd.argument() == "label")
2935                         code = LABEL_CODE;
2936                 else if (cmd.argument() == "line")
2937                         code = LINE_CODE;
2938                 else if (cmd.argument() == "note")
2939                         code = NOTE_CODE;
2940                 else if (cmd.argument() == "phantom")
2941                         code = PHANTOM_CODE;
2942                 else if (cmd.argument() == "ref")
2943                         code = REF_CODE;
2944                 else if (cmd.argument() == "space")
2945                         code = SPACE_CODE;
2946                 else if (cmd.argument() == "toc")
2947                         code = TOC_CODE;
2948                 else if (cmd.argument() == "vspace")
2949                         code = VSPACE_CODE;
2950                 else if (cmd.argument() == "wrap")
2951                         code = WRAP_CODE;
2952                 break;
2953
2954         case LFUN_ERT_INSERT:
2955                 code = ERT_CODE;
2956                 break;
2957         case LFUN_LISTING_INSERT:
2958                 code = LISTINGS_CODE;
2959                 // not allowed in description items
2960                 enable = !inDescriptionItem(cur);
2961                 break;
2962         case LFUN_FOOTNOTE_INSERT:
2963                 code = FOOT_CODE;
2964                 break;
2965         case LFUN_TABULAR_INSERT:
2966                 code = TABULAR_CODE;
2967                 break;
2968         case LFUN_TABULAR_STYLE_INSERT:
2969                 code = TABULAR_CODE;
2970                 break;
2971         case LFUN_MARGINALNOTE_INSERT:
2972                 code = MARGIN_CODE;
2973                 break;
2974         case LFUN_FLOAT_INSERT:
2975         case LFUN_FLOAT_WIDE_INSERT:
2976                 // FIXME: If there is a selection, we should check whether there
2977                 // are floats in the selection, but this has performance issues, see
2978                 // LFUN_CHANGE_ACCEPT/REJECT.
2979                 code = FLOAT_CODE;
2980                 if (inDescriptionItem(cur))
2981                         // not allowed in description items
2982                         enable = false;
2983                 else {
2984                         InsetCode const inset_code = cur.inset().lyxCode();
2985
2986                         // algorithm floats cannot be put in another float
2987                         if (to_utf8(cmd.argument()) == "algorithm") {
2988                                 enable = inset_code != WRAP_CODE && inset_code != FLOAT_CODE;
2989                                 break;
2990                         }
2991
2992                         // for figures and tables: only allow in another
2993                         // float or wrap if it is of the same type and
2994                         // not a subfloat already
2995                         if(cur.inset().lyxCode() == code) {
2996                                 InsetFloat const & ins =
2997                                         static_cast<InsetFloat const &>(cur.inset());
2998                                 enable = ins.params().type == to_utf8(cmd.argument())
2999                                         && !ins.params().subfloat;
3000                         } else if(cur.inset().lyxCode() == WRAP_CODE) {
3001                                 InsetWrap const & ins =
3002                                         static_cast<InsetWrap const &>(cur.inset());
3003                                 enable = ins.params().type == to_utf8(cmd.argument());
3004                         }
3005                 }
3006                 break;
3007         case LFUN_WRAP_INSERT:
3008                 code = WRAP_CODE;
3009                 // not allowed in description items
3010                 enable = !inDescriptionItem(cur);
3011                 break;
3012         case LFUN_FLOAT_LIST_INSERT: {
3013                 code = FLOAT_LIST_CODE;
3014                 // not allowed in description items
3015                 enable = !inDescriptionItem(cur);
3016                 if (enable) {
3017                         FloatList const & floats = cur.buffer()->params().documentClass().floats();
3018                         FloatList::const_iterator cit = floats[to_ascii(cmd.argument())];
3019                         // make sure we know about such floats
3020                         if (cit == floats.end() ||
3021                                         // and that we know how to generate a list of them
3022                             (!cit->second.usesFloatPkg() && cit->second.listCommand().empty())) {
3023                                 flag.setUnknown(true);
3024                                 // probably not necessary, but...
3025                                 enable = false;
3026                         }
3027                 }
3028                 break;
3029         }
3030         case LFUN_CAPTION_INSERT: {
3031                 code = CAPTION_CODE;
3032                 string arg = cmd.getArg(0);
3033                 bool varia = arg != "Unnumbered"
3034                         && cur.inset().allowsCaptionVariation(arg);
3035                 // not allowed in description items,
3036                 // and in specific insets
3037                 enable = !inDescriptionItem(cur)
3038                         && (varia || arg.empty() || arg == "Standard");
3039                 break;
3040         }
3041         case LFUN_NOTE_INSERT:
3042                 code = NOTE_CODE;
3043                 break;
3044         case LFUN_FLEX_INSERT: {
3045                 code = FLEX_CODE;
3046                 string s = cmd.getArg(0);
3047                 InsetLayout il =
3048                         cur.buffer()->params().documentClass().insetLayout(from_utf8(s));
3049                 if (il.lyxtype() != InsetLayout::CHARSTYLE &&
3050                     il.lyxtype() != InsetLayout::CUSTOM &&
3051                     il.lyxtype() != InsetLayout::ELEMENT &&
3052                     il.lyxtype ()!= InsetLayout::STANDARD)
3053                         enable = false;
3054                 break;
3055                 }
3056         case LFUN_BOX_INSERT:
3057                 code = BOX_CODE;
3058                 break;
3059         case LFUN_BRANCH_INSERT:
3060                 code = BRANCH_CODE;
3061                 if (cur.buffer()->masterBuffer()->params().branchlist().empty()
3062                     && cur.buffer()->params().branchlist().empty())
3063                         enable = false;
3064                 break;
3065         case LFUN_IPA_INSERT:
3066                 code = IPA_CODE;
3067                 break;
3068         case LFUN_PHANTOM_INSERT:
3069                 code = PHANTOM_CODE;
3070                 break;
3071         case LFUN_LABEL_INSERT:
3072                 code = LABEL_CODE;
3073                 break;
3074         case LFUN_INFO_INSERT:
3075                 code = INFO_CODE;
3076                 enable = cmd.argument().empty()
3077                         || infoparams.validateArgument(cur.buffer(), cmd.argument(), true);
3078                 break;
3079         case LFUN_ARGUMENT_INSERT: {
3080                 code = ARG_CODE;
3081                 allow_in_passthru = true;
3082                 string const arg = cmd.getArg(0);
3083                 if (arg.empty()) {
3084                         enable = false;
3085                         break;
3086                 }
3087                 Layout const & lay = cur.paragraph().layout();
3088                 Layout::LaTeXArgMap args = lay.args();
3089                 Layout::LaTeXArgMap::const_iterator const lait =
3090                                 args.find(arg);
3091                 if (lait != args.end()) {
3092                         enable = true;
3093                         pit_type pit = cur.pit();
3094                         pit_type lastpit = cur.pit();
3095                         if (lay.isEnvironment() && !prefixIs(arg, "item:")) {
3096                                 // In a sequence of "merged" environment layouts, we only allow
3097                                 // non-item arguments once.
3098                                 lastpit = cur.lastpit();
3099                                 // get the first paragraph in sequence with this layout
3100                                 depth_type const current_depth = cur.paragraph().params().depth();
3101                                 while (true) {
3102                                         if (pit == 0)
3103                                                 break;
3104                                         Paragraph cpar = pars_[pit - 1];
3105                                         if (cpar.layout() == lay && cpar.params().depth() == current_depth)
3106                                                 --pit;
3107                                         else
3108                                                 break;
3109                                 }
3110                         }
3111                         for (; pit <= lastpit; ++pit) {
3112                                 if (pars_[pit].layout() != lay)
3113                                         break;
3114                                 for (auto const & table : pars_[pit].insetList())
3115                                         if (InsetArgument const * ins = table.inset->asInsetArgument())
3116                                                 if (ins->name() == arg) {
3117                                                         // we have this already
3118                                                         enable = false;
3119                                                         break;
3120                                                 }
3121                         }
3122                 } else
3123                         enable = false;
3124                 break;
3125         }
3126         case LFUN_INDEX_INSERT:
3127                 code = INDEX_CODE;
3128                 break;
3129         case LFUN_INDEX_PRINT:
3130                 code = INDEX_PRINT_CODE;
3131                 // not allowed in description items
3132                 enable = !inDescriptionItem(cur);
3133                 break;
3134         case LFUN_NOMENCL_INSERT:
3135                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
3136                         enable = false;
3137                         break;
3138                 }
3139                 code = NOMENCL_CODE;
3140                 break;
3141         case LFUN_NOMENCL_PRINT:
3142                 code = NOMENCL_PRINT_CODE;
3143                 // not allowed in description items
3144                 enable = !inDescriptionItem(cur);
3145                 break;
3146         case LFUN_HREF_INSERT:
3147                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
3148                         enable = false;
3149                         break;
3150                 }
3151                 code = HYPERLINK_CODE;
3152                 break;
3153         case LFUN_IPAMACRO_INSERT: {
3154                 string const arg = cmd.getArg(0);
3155                 if (arg == "deco")
3156                         code = IPADECO_CODE;
3157                 else
3158                         code = IPACHAR_CODE;
3159                 break;
3160         }
3161         case LFUN_QUOTE_INSERT:
3162                 // always allow this, since we will inset a raw quote
3163                 // if an inset is not allowed.
3164                 allow_in_passthru = true;
3165                 break;
3166         case LFUN_SPECIALCHAR_INSERT:
3167                 code = SPECIALCHAR_CODE;
3168                 break;
3169         case LFUN_SPACE_INSERT:
3170                 // slight hack: we know this is allowed in math mode
3171                 if (cur.inTexted())
3172                         code = SPACE_CODE;
3173                 break;
3174         case LFUN_PREVIEW_INSERT:
3175                 code = PREVIEW_CODE;
3176                 break;
3177         case LFUN_SCRIPT_INSERT:
3178                 code = SCRIPT_CODE;
3179                 break;
3180
3181         case LFUN_MATH_INSERT:
3182         case LFUN_MATH_AMS_MATRIX:
3183         case LFUN_MATH_MATRIX:
3184         case LFUN_MATH_DELIM:
3185         case LFUN_MATH_BIGDELIM:
3186         case LFUN_MATH_DISPLAY:
3187         case LFUN_MATH_MODE:
3188         case LFUN_MATH_MACRO:
3189         case LFUN_MATH_SUBSCRIPT:
3190         case LFUN_MATH_SUPERSCRIPT:
3191                 code = MATH_HULL_CODE;
3192                 break;
3193
3194         case LFUN_REGEXP_MODE:
3195                 code = MATH_HULL_CODE;
3196                 enable = cur.buffer()->isInternal() && !cur.inRegexped();
3197                 break;
3198
3199         case LFUN_INSET_MODIFY:
3200                 // We need to disable this, because we may get called for a
3201                 // tabular cell via
3202                 // InsetTabular::getStatus() -> InsetText::getStatus()
3203                 // and we don't handle LFUN_INSET_MODIFY.
3204                 enable = false;
3205                 break;
3206
3207         case LFUN_FONT_EMPH:
3208                 flag.setOnOff(fontinfo.emph() == FONT_ON);
3209                 enable = !cur.paragraph().isPassThru();
3210                 break;
3211
3212         case LFUN_FONT_ITAL:
3213                 flag.setOnOff(fontinfo.shape() == ITALIC_SHAPE);
3214                 enable = !cur.paragraph().isPassThru();
3215                 break;
3216
3217         case LFUN_FONT_NOUN:
3218                 flag.setOnOff(fontinfo.noun() == FONT_ON);
3219                 enable = !cur.paragraph().isPassThru();
3220                 break;
3221
3222         case LFUN_FONT_BOLD:
3223         case LFUN_FONT_BOLDSYMBOL:
3224                 flag.setOnOff(fontinfo.series() == BOLD_SERIES);
3225                 enable = !cur.paragraph().isPassThru();
3226                 break;
3227
3228         case LFUN_FONT_SANS:
3229                 flag.setOnOff(fontinfo.family() == SANS_FAMILY);
3230                 enable = !cur.paragraph().isPassThru();
3231                 break;
3232
3233         case LFUN_FONT_ROMAN:
3234                 flag.setOnOff(fontinfo.family() == ROMAN_FAMILY);
3235                 enable = !cur.paragraph().isPassThru();
3236                 break;
3237
3238         case LFUN_FONT_TYPEWRITER:
3239                 flag.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
3240                 enable = !cur.paragraph().isPassThru();
3241                 break;
3242
3243         case LFUN_CUT:
3244         case LFUN_COPY:
3245                 enable = cur.selection();
3246                 break;
3247
3248         case LFUN_PASTE: {
3249                 if (cmd.argument().empty()) {
3250                         if (theClipboard().isInternal())
3251                                 enable = cap::numberOfSelections() > 0;
3252                         else
3253                                 enable = !theClipboard().empty();
3254                         break;
3255                 }
3256
3257                 // we have an argument
3258                 string const arg = to_utf8(cmd.argument());
3259                 if (isStrUnsignedInt(arg)) {
3260                         // it's a number and therefore means the internal stack
3261                         unsigned int n = convert<unsigned int>(arg);
3262                         enable = cap::numberOfSelections() > n;
3263                         break;
3264                 }
3265
3266                 // explicit text type?
3267                 if (arg == "html") {
3268                         // Do not enable for PlainTextType, since some tidying in the
3269                         // frontend is needed for HTML, which is too unsafe for plain text.
3270                         enable = theClipboard().hasTextContents(Clipboard::HtmlTextType);
3271                         break;
3272                 } else if (arg == "latex") {
3273                         // LaTeX is usually not available on the clipboard with
3274                         // the correct MIME type, but in plain text.
3275                         enable = theClipboard().hasTextContents(Clipboard::PlainTextType) ||
3276                                  theClipboard().hasTextContents(Clipboard::LaTeXTextType);
3277                         break;
3278                 }
3279
3280                 Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
3281                 if (arg == "pdf")
3282                         type = Clipboard::PdfGraphicsType;
3283                 else if (arg == "png")
3284                         type = Clipboard::PngGraphicsType;
3285                 else if (arg == "jpeg")
3286                         type = Clipboard::JpegGraphicsType;
3287                 else if (arg == "linkback")
3288                         type = Clipboard::LinkBackGraphicsType;
3289                 else if (arg == "emf")
3290                         type = Clipboard::EmfGraphicsType;
3291                 else if (arg == "wmf")
3292                         type = Clipboard::WmfGraphicsType;
3293                 else {
3294                         // unknown argument
3295                         LYXERR0("Unrecognized graphics type: " << arg);
3296                         // we don't want to assert if the user just mistyped the LFUN
3297                         LATTEST(cmd.origin() != FuncRequest::INTERNAL);
3298                         enable = false;
3299                         break;
3300                 }
3301                 enable = theClipboard().hasGraphicsContents(type);
3302                 break;
3303         }
3304
3305         case LFUN_CLIPBOARD_PASTE:
3306         case LFUN_CLIPBOARD_PASTE_SIMPLE:
3307                 enable = !theClipboard().empty();
3308                 break;
3309
3310         case LFUN_PRIMARY_SELECTION_PASTE:
3311                 enable = cur.selection() || !theSelection().empty();
3312                 break;
3313
3314         case LFUN_SELECTION_PASTE:
3315                 enable = cap::selection();
3316                 break;
3317
3318         case LFUN_PARAGRAPH_MOVE_UP:
3319                 enable = cur.pit() > 0 && !cur.selection();
3320                 break;
3321
3322         case LFUN_PARAGRAPH_MOVE_DOWN:
3323                 enable = cur.pit() < cur.lastpit() && !cur.selection();
3324                 break;
3325
3326         case LFUN_CHANGE_ACCEPT:
3327         case LFUN_CHANGE_REJECT:
3328                 if (!cur.selection())
3329                         enable = cur.paragraph().isChanged(cur.pos());
3330                 else {
3331                         // will enable if there is a change in the selection
3332                         enable = false;
3333
3334                         // cheap improvement for efficiency: using cached
3335                         // buffer variable, if there is no change in the
3336                         // document, no need to check further.
3337                         if (!cur.buffer()->areChangesPresent())
3338                                 break;
3339
3340                         for (DocIterator it = cur.selectionBegin(); ; it.forwardPar()) {
3341                                 pos_type const beg = it.pos();
3342                                 pos_type end;
3343                                 bool const in_last_par = (it.pit() == cur.selectionEnd().pit() &&
3344                                                           it.idx() == cur.selectionEnd().idx());
3345                                 if (in_last_par)
3346                                         end = cur.selectionEnd().pos();
3347                                 else
3348                                         end = it.lastpos();
3349                                 if (beg != end && it.paragraph().isChanged(beg, end)) {
3350                                         enable = true;
3351                                         break;
3352                                 }
3353                                 if (in_last_par)
3354                                         break;
3355                         }
3356                 }
3357                 break;
3358
3359         case LFUN_OUTLINE_UP:
3360         case LFUN_OUTLINE_DOWN:
3361         case LFUN_OUTLINE_IN:
3362         case LFUN_OUTLINE_OUT:
3363                 // FIXME: LyX is not ready for outlining within inset.
3364                 enable = isMainText()
3365                         && cur.buffer()->text().getTocLevel(cur.pit()) != Layout::NOT_IN_TOC;
3366                 break;
3367
3368         case LFUN_NEWLINE_INSERT:
3369                 // LaTeX restrictions (labels or empty par)
3370                 enable = !cur.paragraph().isPassThru()
3371                         && cur.pos() > cur.paragraph().beginOfBody();
3372                 break;
3373
3374         case LFUN_SEPARATOR_INSERT:
3375                 // Always enabled for now
3376                 enable = true;
3377                 break;
3378
3379         case LFUN_TAB_INSERT:
3380         case LFUN_TAB_DELETE:
3381                 enable = cur.paragraph().isPassThru();
3382                 break;
3383
3384         case LFUN_GRAPHICS_SET_GROUP: {
3385                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
3386                 if (!ins)
3387                         enable = false;
3388                 else
3389                         flag.setOnOff(to_utf8(cmd.argument()) == ins->getParams().groupId);
3390                 break;
3391         }
3392
3393         case LFUN_NEWPAGE_INSERT:
3394                 // not allowed in description items
3395                 code = NEWPAGE_CODE;
3396                 enable = !inDescriptionItem(cur);
3397                 break;
3398
3399         case LFUN_LANGUAGE:
3400                 enable = !cur.paragraph().isPassThru();
3401                 flag.setOnOff(cmd.getArg(0) == cur.real_current_font.language()->lang());
3402                 break;
3403
3404         case LFUN_PARAGRAPH_BREAK:
3405                 enable = inset().allowMultiPar();
3406                 break;
3407
3408         case LFUN_SPELLING_ADD:
3409         case LFUN_SPELLING_IGNORE:
3410         case LFUN_SPELLING_REMOVE:
3411                 enable = theSpellChecker() != NULL;
3412                 if (enable && !cmd.getArg(1).empty()) {
3413                         // validate explicitly given language
3414                         Language const * const lang = const_cast<Language *>(languages.getLanguage(cmd.getArg(1)));
3415                         enable &= lang != NULL;
3416                 }
3417                 break;
3418
3419         case LFUN_LAYOUT:
3420         case LFUN_LAYOUT_TOGGLE: {
3421                 bool const ignoreautonests = cmd.getArg(1) == "ignoreautonests";
3422                 docstring const req_layout = ignoreautonests ? from_utf8(cmd.getArg(0)) : cmd.argument();
3423                 docstring const layout = resolveLayout(req_layout, cur);
3424
3425                 enable = !owner_->forcePlainLayout() && !layout.empty();
3426                 flag.setOnOff(isAlreadyLayout(layout, cur));
3427                 break;
3428         }
3429
3430         case LFUN_ENVIRONMENT_SPLIT: {
3431                 if (cmd.argument() == "outer") {
3432                         // check if we have an environment in our nesting hierarchy
3433                         bool res = false;
3434                         depth_type const current_depth = cur.paragraph().params().depth();
3435                         pit_type pit = cur.pit();
3436                         Paragraph cpar = pars_[pit];
3437                         while (true) {
3438                                 if (pit == 0 || cpar.params().depth() == 0)
3439                                         break;
3440                                 --pit;
3441                                 cpar = pars_[pit];
3442                                 if (cpar.params().depth() < current_depth)
3443                                         res = cpar.layout().isEnvironment();
3444                         }
3445                         enable = res;
3446                         break;
3447                 }
3448                 else if (cmd.argument() == "previous") {
3449                         // look if we have an environment in the previous par
3450                         pit_type pit = cur.pit();
3451                         Paragraph cpar = pars_[pit];
3452                         if (pit > 0) {
3453                                 --pit;
3454                                 cpar = pars_[pit];
3455                                 enable = cpar.layout().isEnvironment();
3456                                 break;
3457                         }
3458                         enable = false;
3459                         break;
3460                 }
3461                 else if (cur.paragraph().layout().isEnvironment()) {
3462                         enable = cmd.argument() == "before"
3463                                 || cur.pos() > 0 || !isFirstInSequence(cur.pit());
3464                         break;
3465                 }
3466                 enable = false;
3467                 break;
3468         }
3469
3470         case LFUN_LAYOUT_PARAGRAPH:
3471         case LFUN_PARAGRAPH_PARAMS:
3472         case LFUN_PARAGRAPH_PARAMS_APPLY:
3473         case LFUN_PARAGRAPH_UPDATE:
3474                 enable = owner_->allowParagraphCustomization();
3475                 break;
3476
3477         // FIXME: why are accent lfuns forbidden with pass_thru layouts?
3478         //  Because they insert COMBINING DIACRITICAL Unicode characters,
3479         //  that cannot be handled by LaTeX but must be converted according
3480         //  to the definition in lib/unicodesymbols?
3481         case LFUN_ACCENT_ACUTE:
3482         case LFUN_ACCENT_BREVE:
3483         case LFUN_ACCENT_CARON:
3484         case LFUN_ACCENT_CEDILLA:
3485         case LFUN_ACCENT_CIRCLE:
3486         case LFUN_ACCENT_CIRCUMFLEX:
3487         case LFUN_ACCENT_DOT:
3488         case LFUN_ACCENT_GRAVE:
3489         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
3490         case LFUN_ACCENT_MACRON:
3491         case LFUN_ACCENT_OGONEK:
3492         case LFUN_ACCENT_TIE:
3493         case LFUN_ACCENT_TILDE:
3494         case LFUN_ACCENT_PERISPOMENI:
3495         case LFUN_ACCENT_UMLAUT:
3496         case LFUN_ACCENT_UNDERBAR:
3497         case LFUN_ACCENT_UNDERDOT:
3498         case LFUN_FONT_FRAK:
3499         case LFUN_FONT_SIZE:
3500         case LFUN_FONT_STATE:
3501         case LFUN_FONT_UNDERLINE:
3502         case LFUN_FONT_STRIKEOUT:
3503         case LFUN_FONT_CROSSOUT:
3504         case LFUN_FONT_UNDERUNDERLINE:
3505         case LFUN_FONT_UNDERWAVE:
3506         case LFUN_TEXTSTYLE_UPDATE:
3507                 enable = !cur.paragraph().isPassThru();
3508                 break;
3509
3510         case LFUN_FONT_DEFAULT: {
3511                 Font font(inherit_font, ignore_language);
3512                 BufferParams const & bp = cur.buffer()->masterParams();
3513                 if (cur.selection()) {
3514                         enable = false;
3515                         // Check if we have a non-default font attribute
3516                         // in the selection range.
3517                         DocIterator const from = cur.selectionBegin();
3518                         DocIterator const to = cur.selectionEnd();
3519                         for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
3520                                 if (!dit.inTexted()) {
3521                                         dit.forwardPos();
3522                                         continue;
3523                                 }
3524                                 Paragraph const & par = dit.paragraph();
3525                                 pos_type const pos = dit.pos();
3526                                 Font tmp = par.getFontSettings(bp, pos);
3527                                 if (tmp.fontInfo() != font.fontInfo()
3528                                     || tmp.language() != bp.language) {
3529                                         enable = true;
3530                                         break;
3531                                 }
3532                                 dit.forwardPos();
3533                         }
3534                         break;
3535                 }
3536                 // Disable if all is default already.
3537                 enable = (cur.current_font.fontInfo() != font.fontInfo()
3538                           || cur.current_font.language() != bp.language);
3539                 break;
3540         }
3541
3542         case LFUN_TEXTSTYLE_APPLY:
3543                 enable = !freeFonts.empty();
3544                 break;
3545
3546         case LFUN_WORD_DELETE_FORWARD:
3547         case LFUN_WORD_DELETE_BACKWARD:
3548         case LFUN_LINE_DELETE_FORWARD:
3549         case LFUN_WORD_FORWARD:
3550         case LFUN_WORD_BACKWARD:
3551         case LFUN_WORD_RIGHT:
3552         case LFUN_WORD_LEFT:
3553         case LFUN_CHAR_FORWARD:
3554         case LFUN_CHAR_FORWARD_SELECT:
3555         case LFUN_CHAR_BACKWARD:
3556         case LFUN_CHAR_BACKWARD_SELECT:
3557         case LFUN_CHAR_LEFT:
3558         case LFUN_CHAR_LEFT_SELECT:
3559         case LFUN_CHAR_RIGHT:
3560         case LFUN_CHAR_RIGHT_SELECT:
3561         case LFUN_UP:
3562         case LFUN_UP_SELECT:
3563         case LFUN_DOWN:
3564         case LFUN_DOWN_SELECT:
3565         case LFUN_PARAGRAPH_SELECT:
3566         case LFUN_PARAGRAPH_UP_SELECT:
3567         case LFUN_PARAGRAPH_DOWN_SELECT:
3568         case LFUN_LINE_BEGIN_SELECT:
3569         case LFUN_LINE_END_SELECT:
3570         case LFUN_WORD_FORWARD_SELECT:
3571         case LFUN_WORD_BACKWARD_SELECT:
3572         case LFUN_WORD_RIGHT_SELECT:
3573         case LFUN_WORD_LEFT_SELECT:
3574         case LFUN_WORD_SELECT:
3575         case LFUN_SECTION_SELECT:
3576         case LFUN_BUFFER_BEGIN:
3577         case LFUN_BUFFER_END:
3578         case LFUN_BUFFER_BEGIN_SELECT:
3579         case LFUN_BUFFER_END_SELECT:
3580         case LFUN_INSET_BEGIN:
3581         case LFUN_INSET_END:
3582         case LFUN_INSET_BEGIN_SELECT:
3583         case LFUN_INSET_END_SELECT:
3584         case LFUN_PARAGRAPH_UP:
3585         case LFUN_PARAGRAPH_DOWN:
3586         case LFUN_LINE_BEGIN:
3587         case LFUN_LINE_END:
3588         case LFUN_CHAR_DELETE_FORWARD:
3589         case LFUN_CHAR_DELETE_BACKWARD:
3590         case LFUN_WORD_UPCASE:
3591         case LFUN_WORD_LOWCASE:
3592         case LFUN_WORD_CAPITALIZE:
3593         case LFUN_CHARS_TRANSPOSE:
3594         case LFUN_SERVER_GET_XY:
3595         case LFUN_SERVER_SET_XY:
3596         case LFUN_SERVER_GET_LAYOUT:
3597         case LFUN_SELF_INSERT:
3598         case LFUN_UNICODE_INSERT:
3599         case LFUN_THESAURUS_ENTRY:
3600         case LFUN_ESCAPE:
3601         case LFUN_SERVER_GET_STATISTICS:
3602                 // these are handled in our dispatch()
3603                 enable = true;
3604                 break;
3605
3606         case LFUN_INSET_INSERT: {
3607                 string const type = cmd.getArg(0);
3608                 if (type == "toc") {
3609                         code = TOC_CODE;
3610                         // not allowed in description items
3611                         //FIXME: couldn't this be merged in Inset::insetAllowed()?
3612                         enable = !inDescriptionItem(cur);
3613                 } else {
3614                         enable = true;
3615                 }
3616                 break;
3617         }
3618
3619         case LFUN_SEARCH_IGNORE: {
3620                 bool const value = cmd.getArg(1) == "true";
3621                 setIgnoreFormat(cmd.getArg(0), value);
3622                 break;
3623         }
3624
3625         default:
3626                 return false;
3627         }
3628
3629         if (code != NO_CODE
3630             && (cur.empty()
3631                 || !cur.inset().insetAllowed(code)
3632                 || (cur.paragraph().layout().pass_thru && !allow_in_passthru)))
3633                 enable = false;
3634
3635         flag.setEnabled(enable);
3636         return true;
3637 }
3638
3639
3640 void Text::pasteString(Cursor & cur, docstring const & clip,
3641                 bool asParagraphs)
3642 {
3643         if (!clip.empty()) {
3644                 cur.recordUndo();
3645                 if (asParagraphs)
3646                         insertStringAsParagraphs(cur, clip, cur.current_font);
3647                 else
3648                         insertStringAsLines(cur, clip, cur.current_font);
3649         }
3650 }
3651
3652
3653 // FIXME: an item inset would make things much easier.
3654 bool Text::inDescriptionItem(Cursor & cur) const
3655 {
3656         Paragraph & par = cur.paragraph();
3657         pos_type const pos = cur.pos();
3658         pos_type const body_pos = par.beginOfBody();
3659
3660         if (par.layout().latextype != LATEX_LIST_ENVIRONMENT
3661             && (par.layout().latextype != LATEX_ITEM_ENVIRONMENT
3662                 || par.layout().margintype != MARGIN_FIRST_DYNAMIC))
3663                 return false;
3664
3665         return (pos < body_pos
3666                 || (pos == body_pos
3667                     && (pos == 0 || par.getChar(pos - 1) != ' ')));
3668 }
3669
3670
3671 std::vector<docstring> Text::getFreeFonts() const
3672 {
3673         vector<docstring> ffList;
3674
3675         FontStack::const_iterator cit = freeFonts.begin();
3676         FontStack::const_iterator end = freeFonts.end();
3677         for (; cit != end; ++cit)
3678                 // we do not use cit-> here because gcc 2.9x does not
3679                 // like it (JMarc)
3680                 ffList.push_back((*cit).first);
3681
3682         return ffList;
3683 }
3684
3685 } // namespace lyx