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