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