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