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