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