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