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