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