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