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