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