]> git.lyx.org Git - lyx.git/blob - src/Text3.cpp
d434eb5aaf25f5029e3e24f53085b7a2013653ba
[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 "Cursor.h"
29 #include "CutAndPaste.h"
30 #include "DispatchResult.h"
31 #include "ErrorList.h"
32 #include "factory.h"
33 #include "FuncRequest.h"
34 #include "InsetList.h"
35 #include "Intl.h"
36 #include "Language.h"
37 #include "Layout.h"
38 #include "LyXAction.h"
39 #include "LyXFunc.h"
40 #include "Lexer.h"
41 #include "LyXRC.h"
42 #include "Paragraph.h"
43 #include "paragraph_funcs.h"
44 #include "ParagraphParameters.h"
45 #include "TextClass.h"
46 #include "TextMetrics.h"
47 #include "VSpace.h"
48
49 #include "frontends/Clipboard.h"
50 #include "frontends/Selection.h"
51
52 #include "insets/InsetCollapsable.h"
53 #include "insets/InsetCommand.h"
54 #include "insets/InsetFloatList.h"
55 #include "insets/InsetNewline.h"
56 #include "insets/InsetQuotes.h"
57 #include "insets/InsetSpecialChar.h"
58 #include "insets/InsetText.h"
59 #include "insets/InsetInfo.h"
60
61 #include "support/convert.h"
62 #include "support/debug.h"
63 #include "support/gettext.h"
64 #include "support/lstrings.h"
65 #include "support/lyxtime.h"
66
67 #include "mathed/InsetMathHull.h"
68 #include "mathed/MathMacroTemplate.h"
69
70 #include <boost/next_prior.hpp>
71
72 #include <clocale>
73 #include <sstream>
74
75 using namespace std;
76 using namespace lyx::support;
77
78 namespace lyx {
79
80 using cap::copySelection;
81 using cap::cutSelection;
82 using cap::pasteFromStack;
83 using cap::pasteClipboardText;
84 using cap::pasteClipboardGraphics;
85 using cap::replaceSelection;
86
87 // globals...
88 static Font freefont(ignore_font, ignore_language);
89 static bool toggleall = false;
90
91 static void toggleAndShow(Cursor & cur, Text * text,
92         Font const & font, bool toggleall = true)
93 {
94         text->toggleFree(cur, font, toggleall);
95
96         if (font.language() != ignore_language ||
97             font.fontInfo().number() != FONT_IGNORE) {
98                 TextMetrics const & tm = cur.bv().textMetrics(text);
99                 if (cur.boundary() != tm.isRTLBoundary(cur.pit(), cur.pos(),
100                                                        cur.real_current_font))
101                         text->setCursor(cur, cur.pit(), cur.pos(),
102                                         false, !cur.boundary());
103         }
104 }
105
106
107 static void moveCursor(Cursor & cur, bool selecting)
108 {
109         if (selecting || cur.mark())
110                 cur.setSelection();
111 }
112
113
114 static void finishChange(Cursor & cur, bool selecting)
115 {
116         cur.finishUndo();
117         moveCursor(cur, selecting);
118 }
119
120
121 static void mathDispatch(Cursor & cur, FuncRequest const & cmd, bool display)
122 {
123         cur.recordUndo();
124         docstring sel = cur.selectionAsString(false);
125
126         // It may happen that sel is empty but there is a selection
127         replaceSelection(cur);
128
129         if (sel.empty()) {
130 #ifdef ENABLE_ASSERTIONS
131                 const int old_pos = cur.pos();
132 #endif
133                 cur.insert(new InsetMathHull(hullSimple));
134                 BOOST_ASSERT(old_pos == cur.pos());
135                 cur.nextInset()->edit(cur, true);
136                 // don't do that also for LFUN_MATH_MODE
137                 // unless you want end up with always changing
138                 // to mathrm when opening an inlined inset --
139                 // I really hate "LyXfunc overloading"...
140                 if (display)
141                         cur.dispatch(FuncRequest(LFUN_MATH_DISPLAY));
142                 // Avoid an unnecessary undo step if cmd.argument
143                 // is empty
144                 if (!cmd.argument().empty())
145                         cur.dispatch(FuncRequest(LFUN_MATH_INSERT,
146                                                  cmd.argument()));
147         } else {
148                 // create a macro if we see "\\newcommand"
149                 // somewhere, and an ordinary formula
150                 // otherwise
151                 if (sel.find(from_ascii("\\newcommand")) == string::npos
152                                 && sel.find(from_ascii("\\newlyxcommand")) == string::npos
153                                 && sel.find(from_ascii("\\def")) == string::npos)
154                 {
155                         InsetMathHull * formula = new InsetMathHull;
156                         istringstream is(to_utf8(sel));
157                         Lexer lex(0, 0);
158                         lex.setStream(is);
159                         formula->read(lex);
160                         if (formula->getType() == hullNone)
161                                 // Don't create pseudo formulas if
162                                 // delimiters are left out
163                                 formula->mutate(hullSimple);
164                         cur.insert(formula);
165                 } else {
166                         cur.insert(new MathMacroTemplate(sel));
167                 }
168         }
169         cur.message(from_utf8(N_("Math editor mode")));
170 }
171
172
173 static void specialChar(Cursor & cur, InsetSpecialChar::Kind kind)
174 {
175         cur.recordUndo();
176         cap::replaceSelection(cur);
177         cur.insert(new InsetSpecialChar(kind));
178         cur.posForward();
179 }
180
181
182 static bool doInsertInset(Cursor & cur, Text * text,
183         FuncRequest const & cmd, bool edit, bool pastesel)
184 {
185         Buffer & buffer = cur.bv().buffer();
186         BufferParams const & bparams = buffer.params();
187         Inset * inset = createInset(buffer, cmd);
188         if (!inset)
189                 return false;
190
191         if (InsetCollapsable * ci = inset->asInsetCollapsable())
192                 ci->setLayout(bparams);
193
194         cur.recordUndo();
195         if (cmd.action == LFUN_INDEX_INSERT) {
196                 docstring ds = subst(text->getStringToIndex(cur), '\n', ' ');
197                 text->insertInset(cur, inset);
198                 if (edit)
199                         inset->edit(cur, true);
200                 // Now put this into inset
201                 static_cast<InsetCollapsable *>(inset)->text_.insertStringAsParagraphs(cur, ds);
202                 return true;
203         }
204
205         bool gotsel = false;
206         if (cur.selection()) {
207                 lyx::dispatch(FuncRequest(LFUN_CUT));
208                 gotsel = true;
209         }
210         text->insertInset(cur, inset);
211
212         if (edit)
213                 inset->edit(cur, true);
214
215         if (!gotsel || !pastesel)
216                 return true;
217
218         lyx::dispatch(FuncRequest(LFUN_PASTE, "0"));
219         InsetText * insetText = dynamic_cast<InsetText *>(inset);
220         if (insetText && !insetText->allowMultiPar() || cur.lastpit() == 0) {
221                 // reset first par to default
222                 cur.text()->paragraphs().begin()
223                         ->setEmptyOrDefaultLayout(bparams.documentClass());
224                 cur.pos() = 0;
225                 cur.pit() = 0;
226                 // Merge multiple paragraphs -- hack
227                 while (cur.lastpit() > 0)
228                         mergeParagraph(bparams, cur.text()->paragraphs(), 0);
229         } else {
230                 // reset surrounding par to default
231                 docstring const layoutname = insetText->useEmptyLayout()
232                         ? bparams.documentClass().emptyLayoutName()
233                         : bparams.documentClass().defaultLayoutName();
234                 cur.leaveInset(*inset);
235                 text->setLayout(cur, layoutname);
236         }
237
238         return true;
239 }
240
241
242 string const freefont2string()
243 {
244         return freefont.toString(toggleall);
245 }
246
247
248 /// the type of outline operation
249 enum OutlineOp {
250         OutlineUp, // Move this header with text down
251         OutlineDown,   // Move this header with text up
252         OutlineIn, // Make this header deeper
253         OutlineOut // Make this header shallower
254 };
255
256
257 static void outline(OutlineOp mode, Cursor & cur)
258 {
259         Buffer & buf = cur.buffer();
260         pit_type & pit = cur.pit();
261         ParagraphList & pars = buf.text().paragraphs();
262         ParagraphList::iterator bgn = pars.begin();
263         // The first paragraph of the area to be copied:
264         ParagraphList::iterator start = boost::next(bgn, pit);
265         // The final paragraph of area to be copied:
266         ParagraphList::iterator finish = start;
267         ParagraphList::iterator end = pars.end();
268
269         DocumentClass const & tc = buf.params().documentClass();
270
271         int const thistoclevel = start->layout()->toclevel;
272         int toclevel;
273
274         // Move out (down) from this section header
275         if (finish != end)
276                 ++finish;
277         // Seek the one (on same level) below
278         for (; finish != end; ++finish) {
279                 toclevel = finish->layout()->toclevel;
280                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel) {
281                         break;
282                 }
283         }
284
285         switch (mode) {
286                 case OutlineUp: {
287                         ParagraphList::iterator dest = start;
288                         // Move out (up) from this header
289                         if (dest == bgn)
290                                 return;
291                         // Search previous same-level header above
292                         do {
293                                 --dest;
294                                 toclevel = dest->layout()->toclevel;
295                         } while(dest != bgn
296                                 && (toclevel == Layout::NOT_IN_TOC
297                                     || toclevel > thistoclevel));
298                         // Not found; do nothing
299                         if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
300                                 return;
301                         pit_type const newpit = distance(bgn, dest);
302                         pit_type const len = distance(start, finish);
303                         pit_type const deletepit = pit + len;
304                         buf.undo().recordUndo(cur, ATOMIC_UNDO, newpit, deletepit - 1);
305                         pars.insert(dest, start, finish);
306                         start = boost::next(pars.begin(), deletepit);
307                         pit = newpit;
308                         pars.erase(start, finish);
309                         return;
310                 }
311                 case OutlineDown: {
312                         ParagraphList::iterator dest = finish;
313                         // One such was found:
314                         pit_type newpit = distance(bgn, dest);
315                         pit_type const len = distance(start, finish);
316                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, newpit - 1);
317                         pars.insert(dest, start, finish);
318                         start = boost::next(bgn, pit);
319                         pit = newpit - len;
320                         pars.erase(start, finish);
321                         return;
322                 }
323                 case OutlineIn: {
324                         pit_type const len = distance(start, finish);
325                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, pit + len - 1);
326                         for (; start != finish; ++start) {
327                                 toclevel = start->layout()->toclevel;
328                                 if (toclevel == Layout::NOT_IN_TOC)
329                                         continue;
330                                 DocumentClass::const_iterator lit = tc.begin();
331                                 DocumentClass::const_iterator len = tc.end();
332                                 for (; lit != len; ++lit) {
333                                         LayoutPtr const & lt = *lit;
334                                         if (lt->toclevel == toclevel + 1 &&
335                                             start->layout()->labeltype == lt->labeltype) {
336                                                 start->setLayout(lt);
337                                                 break;
338                                         }
339                                 }
340                         }
341                         return;
342                 }
343                 case OutlineOut: {
344                         pit_type const len = distance(start, finish);
345                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, pit + len - 1);
346                         for (; start != finish; ++start) {
347                                 toclevel = start->layout()->toclevel;
348                                 if (toclevel == Layout::NOT_IN_TOC)
349                                         continue;
350                                 DocumentClass::const_iterator lit = tc.begin();
351                                 DocumentClass::const_iterator len = tc.end();
352                                 for (; lit != len; ++lit) {
353                                         LayoutPtr const & lt = *lit;
354                                         if (lt->toclevel == toclevel - 1 &&
355                                                 start->layout()->labeltype == lt->labeltype) {
356                                                         start->setLayout(lt);
357                                                         break;
358                                         }
359                                 }
360                         }
361                         return;
362                 }
363         }
364 }
365
366
367 void Text::number(Cursor & cur)
368 {
369         FontInfo font = ignore_font;
370         font.setNumber(FONT_TOGGLE);
371         toggleAndShow(cur, this, Font(font, ignore_language));
372 }
373
374
375 bool Text::isRTL(Buffer const & buffer, Paragraph const & par) const
376 {
377         return par.isRTL(buffer.params());
378 }
379
380
381 void Text::dispatch(Cursor & cur, FuncRequest & cmd)
382 {
383         LYXERR(Debug::ACTION, "Text::dispatch: cmd: " << cmd);
384
385         BufferView * bv = &cur.bv();
386         TextMetrics & tm = bv->textMetrics(this);
387         if (!tm.contains(cur.pit()))
388                 lyx::dispatch(FuncRequest(LFUN_SCREEN_RECENTER));
389
390         // FIXME: We use the update flag to indicates wether a singlePar or a
391         // full screen update is needed. We reset it here but shall we restore it
392         // at the end?
393         cur.noUpdate();
394
395         BOOST_ASSERT(cur.text() == this);
396         CursorSlice oldTopSlice = cur.top();
397         bool oldBoundary = cur.boundary();
398         bool sel = cur.selection();
399         // Signals that, even if needsUpdate == false, an update of the
400         // cursor paragraph is required
401         bool singleParUpdate = lyxaction.funcHasFlag(cmd.action,
402                 LyXAction::SingleParUpdate);
403         // Signals that a full-screen update is required
404         bool needsUpdate = !(lyxaction.funcHasFlag(cmd.action,
405                 LyXAction::NoUpdate) || singleParUpdate);
406
407         switch (cmd.action) {
408
409         case LFUN_PARAGRAPH_MOVE_DOWN: {
410                 pit_type const pit = cur.pit();
411                 recUndo(cur, pit, pit + 1);
412                 cur.finishUndo();
413                 swap(pars_[pit], pars_[pit + 1]);
414                 updateLabels(cur.buffer());
415                 needsUpdate = true;
416                 ++cur.pit();
417                 break;
418         }
419
420         case LFUN_PARAGRAPH_MOVE_UP: {
421                 pit_type const pit = cur.pit();
422                 recUndo(cur, pit - 1, pit);
423                 cur.finishUndo();
424                 swap(pars_[pit], pars_[pit - 1]);
425                 updateLabels(cur.buffer());
426                 --cur.pit();
427                 needsUpdate = true;
428                 break;
429         }
430
431         case LFUN_APPENDIX: {
432                 Paragraph & par = cur.paragraph();
433                 bool start = !par.params().startOfAppendix();
434
435 // FIXME: The code below only makes sense at top level.
436 // Should LFUN_APPENDIX be restricted to top-level paragraphs?
437                 // ensure that we have only one start_of_appendix in this document
438                 // FIXME: this don't work for multipart document!
439                 for (pit_type tmp = 0, end = pars_.size(); tmp != end; ++tmp) {
440                         if (pars_[tmp].params().startOfAppendix()) {
441                                 recUndo(cur, tmp);
442                                 pars_[tmp].params().startOfAppendix(false);
443                                 break;
444                         }
445                 }
446
447                 cur.recordUndo();
448                 par.params().startOfAppendix(start);
449
450                 // we can set the refreshing parameters now
451                 updateLabels(cur.buffer());
452                 break;
453         }
454
455         case LFUN_WORD_DELETE_FORWARD:
456                 if (cur.selection()) {
457                         cutSelection(cur, true, false);
458                 } else
459                         deleteWordForward(cur);
460                 finishChange(cur, false);
461                 break;
462
463         case LFUN_WORD_DELETE_BACKWARD:
464                 if (cur.selection()) {
465                         cutSelection(cur, true, false);
466                 } else
467                         deleteWordBackward(cur);
468                 finishChange(cur, false);
469                 break;
470
471         case LFUN_LINE_DELETE:
472                 if (cur.selection()) {
473                         cutSelection(cur, true, false);
474                 } else
475                         tm.deleteLineForward(cur);
476                 finishChange(cur, false);
477                 break;
478
479         case LFUN_BUFFER_BEGIN:
480         case LFUN_BUFFER_BEGIN_SELECT:
481                 needsUpdate |= cur.selHandle(cmd.action == LFUN_BUFFER_BEGIN_SELECT);
482                 if (cur.depth() == 1) {
483                         needsUpdate |= cursorTop(cur);
484                 } else {
485                         cur.undispatched();
486                 }
487                 cur.updateFlags(Update::FitCursor);
488                 break;
489
490         case LFUN_BUFFER_END:
491         case LFUN_BUFFER_END_SELECT:
492                 needsUpdate |= cur.selHandle(cmd.action == LFUN_BUFFER_END_SELECT);
493                 if (cur.depth() == 1) {
494                         needsUpdate |= cursorBottom(cur);
495                 } else {
496                         cur.undispatched();
497                 }
498                 cur.updateFlags(Update::FitCursor);
499                 break;
500
501         case LFUN_CHAR_FORWARD:
502         case LFUN_CHAR_FORWARD_SELECT:
503                 //LYXERR0(" LFUN_CHAR_FORWARD[SEL]:\n" << cur);
504                 needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_FORWARD_SELECT);
505                 needsUpdate |= cursorForward(cur);
506
507                 if (!needsUpdate && oldTopSlice == cur.top()
508                                 && cur.boundary() == oldBoundary) {
509                         cur.undispatched();
510                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
511                 }
512                 break;
513
514         case LFUN_CHAR_BACKWARD:
515         case LFUN_CHAR_BACKWARD_SELECT:
516                 //lyxerr << "handle LFUN_CHAR_BACKWARD[_SELECT]:\n" << cur << endl;
517                 needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_BACKWARD_SELECT);
518                 needsUpdate |= cursorBackward(cur);
519
520                 if (!needsUpdate && oldTopSlice == cur.top()
521                         && cur.boundary() == oldBoundary) {
522                         cur.undispatched();
523                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
524                 }
525                 break;
526
527         case LFUN_CHAR_LEFT:
528         case LFUN_CHAR_LEFT_SELECT:
529                 if (lyxrc.visual_cursor) {
530                         needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_LEFT_SELECT);
531                         needsUpdate |= cursorVisLeft(cur);
532                         if (!needsUpdate && oldTopSlice == cur.top()
533                                         && cur.boundary() == oldBoundary) {
534                                 cur.undispatched();
535                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
536                         }
537                 } else {
538                         if (reverseDirectionNeeded(cur)) {
539                                 cmd.action = cmd.action == LFUN_CHAR_LEFT_SELECT ? 
540                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD;
541                         } else {
542                                 cmd.action = cmd.action == LFUN_CHAR_LEFT_SELECT ? 
543                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD;
544                         }
545                         dispatch(cur, cmd);
546                         return;
547                 }
548                 break;
549
550         case LFUN_CHAR_RIGHT:
551         case LFUN_CHAR_RIGHT_SELECT:
552                 if (lyxrc.visual_cursor) {
553                         needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_RIGHT_SELECT);
554                         needsUpdate |= cursorVisRight(cur);
555                         if (!needsUpdate && oldTopSlice == cur.top()
556                                         && cur.boundary() == oldBoundary) {
557                                 cur.undispatched();
558                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
559                         }
560                 } else {
561                         if (reverseDirectionNeeded(cur)) {
562                                 cmd.action = cmd.action == LFUN_CHAR_RIGHT_SELECT ? 
563                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD;
564                         } else {
565                                 cmd.action = cmd.action == LFUN_CHAR_RIGHT_SELECT ? 
566                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD;
567                         }
568                         dispatch(cur, cmd);
569                         return;
570                 }
571                 break;
572                 
573
574         case LFUN_UP_SELECT:
575         case LFUN_DOWN_SELECT:
576         case LFUN_UP:
577         case LFUN_DOWN: {
578                 // stop/start the selection
579                 bool select = cmd.action == LFUN_DOWN_SELECT ||
580                         cmd.action == LFUN_UP_SELECT;
581                 cur.selHandle(select);
582                 
583                 // move cursor up/down
584                 bool up = cmd.action == LFUN_UP_SELECT || cmd.action == LFUN_UP;
585                 bool const successful = cur.upDownInText(up, needsUpdate);
586                 if (successful) {
587                         // redraw if you leave mathed (for the decorations)
588                         needsUpdate |= cur.beforeDispatchCursor().inMathed();
589                 } else
590                         cur.undispatched();
591                 
592                 break;
593         }
594
595         case LFUN_PARAGRAPH_UP:
596         case LFUN_PARAGRAPH_UP_SELECT:
597                 needsUpdate |= cur.selHandle(cmd.action == LFUN_PARAGRAPH_UP_SELECT);
598                 needsUpdate |= cursorUpParagraph(cur);
599                 break;
600
601         case LFUN_PARAGRAPH_DOWN:
602         case LFUN_PARAGRAPH_DOWN_SELECT:
603                 needsUpdate |= cur.selHandle(cmd.action == LFUN_PARAGRAPH_DOWN_SELECT);
604                 needsUpdate |= cursorDownParagraph(cur);
605                 break;
606
607         case LFUN_SCREEN_UP_SELECT:
608                 needsUpdate |= cur.selHandle(true);
609                 if (cur.pit() == 0 && cur.textRow().pos() == 0)
610                         cur.undispatched();
611                 else {
612                         tm.cursorPrevious(cur);
613                 }
614                 break;
615
616         case LFUN_SCREEN_DOWN_SELECT:
617                 needsUpdate |= cur.selHandle(true);
618                 if (cur.pit() == cur.lastpit()
619                           && cur.textRow().endpos() == cur.lastpos())
620                         cur.undispatched();
621                 else {
622                         tm.cursorNext(cur);
623                 }
624                 break;
625
626         case LFUN_LINE_BEGIN:
627         case LFUN_LINE_BEGIN_SELECT:
628                 needsUpdate |= cur.selHandle(cmd.action == LFUN_LINE_BEGIN_SELECT);
629                 needsUpdate |= tm.cursorHome(cur);
630                 break;
631
632         case LFUN_LINE_END:
633         case LFUN_LINE_END_SELECT:
634                 needsUpdate |= cur.selHandle(cmd.action == LFUN_LINE_END_SELECT);
635                 needsUpdate |= tm.cursorEnd(cur);
636                 break;
637
638         case LFUN_WORD_RIGHT:
639         case LFUN_WORD_RIGHT_SELECT:
640                 //FIXME: for visual cursor mode, really move right
641                 if (reverseDirectionNeeded(cur)) {
642                         cmd.action = cmd.action == LFUN_WORD_RIGHT_SELECT ?
643                                         LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD;
644                 } else {
645                         cmd.action = cmd.action == LFUN_WORD_RIGHT_SELECT ?
646                                         LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD;
647                 }
648                 dispatch(cur, cmd);
649                 return;
650
651         case LFUN_WORD_FORWARD:
652         case LFUN_WORD_FORWARD_SELECT:
653                 needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT);
654                 needsUpdate |= cursorForwardOneWord(cur);
655                 break;
656
657         case LFUN_WORD_LEFT:
658         case LFUN_WORD_LEFT_SELECT:
659                 //FIXME: for visual cursor mode, really move left
660                 if (reverseDirectionNeeded(cur)) {
661                         cmd.action = cmd.action == LFUN_WORD_LEFT_SELECT ?
662                                         LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD;
663                 } else {
664                         cmd.action = cmd.action == LFUN_WORD_LEFT_SELECT ?
665                                         LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD;
666                 }
667                 dispatch(cur, cmd);
668                 return;
669
670         case LFUN_WORD_BACKWARD:
671         case LFUN_WORD_BACKWARD_SELECT:
672                 needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT);
673                 needsUpdate |= cursorBackwardOneWord(cur);
674                 break;
675
676         case LFUN_WORD_SELECT: {
677                 selectWord(cur, WHOLE_WORD);
678                 finishChange(cur, true);
679                 break;
680         }
681
682         case LFUN_NEW_LINE: {
683                 // Not allowed by LaTeX (labels or empty par)
684                 if (cur.pos() > cur.paragraph().beginOfBody()) {
685                         // this avoids a double undo
686                         // FIXME: should not be needed, ideally
687                         if (!cur.selection())
688                                 cur.recordUndo();
689                         cap::replaceSelection(cur);
690                         cur.insert(new InsetNewline);
691                         cur.posForward();
692                         moveCursor(cur, false);
693                 }
694                 break;
695         }
696         
697         case LFUN_LINE_BREAK: {
698                 // Not allowed by LaTeX (labels or empty par)
699                 if (cur.pos() > cur.paragraph().beginOfBody()) {
700                         // this avoids a double undo
701                         // FIXME: should not be needed, ideally
702                         if (!cur.selection())
703                                 cur.recordUndo();
704                         cap::replaceSelection(cur);
705                         cur.insert(new InsetLinebreak);
706                         cur.posForward();
707                         moveCursor(cur, false);
708                 }
709                 break;
710         }
711
712         case LFUN_CHAR_DELETE_FORWARD:
713                 if (!cur.selection()) {
714                         if (cur.pos() == cur.paragraph().size())
715                                 // Par boundary, force full-screen update
716                                 singleParUpdate = false;
717                         needsUpdate |= erase(cur);
718                         cur.resetAnchor();
719                         // It is possible to make it a lot faster still
720                         // just comment out the line below...
721                 } else {
722                         cutSelection(cur, true, false);
723                         singleParUpdate = false;
724                 }
725                 moveCursor(cur, false);
726                 break;
727
728         case LFUN_DELETE_FORWARD_SKIP:
729                 // Reverse the effect of LFUN_BREAK_PARAGRAPH_SKIP.
730                 if (!cur.selection()) {
731                         if (cur.pos() == cur.lastpos()) {
732                                 cursorForward(cur);
733                                 cursorBackward(cur);
734                         }
735                         erase(cur);
736                         cur.resetAnchor();
737                 } else {
738                         cutSelection(cur, true, false);
739                 }
740                 break;
741
742
743         case LFUN_CHAR_DELETE_BACKWARD:
744                 if (!cur.selection()) {
745                         if (bv->getIntl().getTransManager().backspace()) {
746                                 // Par boundary, full-screen update
747                                 if (cur.pos() == 0)
748                                         singleParUpdate = false;
749                                 needsUpdate |= backspace(cur);
750                                 cur.resetAnchor();
751                                 // It is possible to make it a lot faster still
752                                 // just comment out the line below...
753                         }
754                 } else {
755                         cutSelection(cur, true, false);
756                         singleParUpdate = false;
757                 }
758                 break;
759
760         case LFUN_DELETE_BACKWARD_SKIP:
761                 // Reverse the effect of LFUN_BREAK_PARAGRAPH_SKIP.
762                 if (!cur.selection()) {
763                         // FIXME: look here
764                         //CursorSlice cur = cursor();
765                         backspace(cur);
766                         //anchor() = cur;
767                 } else {
768                         cutSelection(cur, true, false);
769                 }
770                 break;
771
772         case LFUN_BREAK_PARAGRAPH:
773                 cap::replaceSelection(cur);
774                 breakParagraph(cur, cmd.argument() == "inverse");
775                 cur.resetAnchor();
776                 break;
777
778         case LFUN_BREAK_PARAGRAPH_SKIP: {
779                 // When at the beginning of a paragraph, remove
780                 // indentation.  Otherwise, do the same as LFUN_BREAK_PARAGRAPH.
781                 cap::replaceSelection(cur);
782                 if (cur.pos() == 0)
783                         cur.paragraph().params().labelWidthString(docstring());
784                 else
785                         breakParagraph(cur, false);
786                 cur.resetAnchor();
787                 break;
788         }
789
790         // TODO
791         // With the creation of LFUN_PARAGRAPH_PARAMS, this is now redundant,
792         // as its duties can be performed there. Should it be removed??
793         // FIXME For now, it can just dispatch LFUN_PARAGRAPH_PARAMS...
794         case LFUN_PARAGRAPH_SPACING: {
795                 Paragraph & par = cur.paragraph();
796                 Spacing::Space cur_spacing = par.params().spacing().getSpace();
797                 string cur_value = "1.0";
798                 if (cur_spacing == Spacing::Other)
799                         cur_value = par.params().spacing().getValueAsString();
800
801                 istringstream is(to_utf8(cmd.argument()));
802                 string tmp;
803                 is >> tmp;
804                 Spacing::Space new_spacing = cur_spacing;
805                 string new_value = cur_value;
806                 if (tmp.empty()) {
807                         lyxerr << "Missing argument to `paragraph-spacing'"
808                                << endl;
809                 } else if (tmp == "single") {
810                         new_spacing = Spacing::Single;
811                 } else if (tmp == "onehalf") {
812                         new_spacing = Spacing::Onehalf;
813                 } else if (tmp == "double") {
814                         new_spacing = Spacing::Double;
815                 } else if (tmp == "other") {
816                         new_spacing = Spacing::Other;
817                         string tmpval = "0.0";
818                         is >> tmpval;
819                         lyxerr << "new_value = " << tmpval << endl;
820                         if (tmpval != "0.0")
821                                 new_value = tmpval;
822                 } else if (tmp == "default") {
823                         new_spacing = Spacing::Default;
824                 } else {
825                         lyxerr << to_utf8(_("Unknown spacing argument: "))
826                                << to_utf8(cmd.argument()) << endl;
827                 }
828                 if (cur_spacing != new_spacing || cur_value != new_value)
829                         par.params().spacing(Spacing(new_spacing, new_value));
830                 break;
831         }
832
833         case LFUN_INSET_INSERT: {
834                 cur.recordUndo();
835                 Inset * inset = createInset(bv->buffer(), cmd);
836                 if (inset) {
837                         // FIXME (Abdel 01/02/2006):
838                         // What follows would be a partial fix for bug 2154:
839                         //   http://bugzilla.lyx.org/show_bug.cgi?id=2154
840                         // This automatically put the label inset _after_ a
841                         // numbered section. It should be possible to extend the mechanism
842                         // to any kind of LateX environement.
843                         // The correct way to fix that bug would be at LateX generation.
844                         // I'll let the code here for reference as it could be used for some
845                         // other feature like "automatic labelling".
846                         /*
847                         Paragraph & par = pars_[cur.pit()];
848                         if (inset->lyxCode() == LABEL_CODE
849                                 && par.layout()->labeltype == LABEL_COUNTER) {
850                                 // Go to the end of the paragraph
851                                 // Warning: Because of Change-Tracking, the last
852                                 // position is 'size()' and not 'size()-1':
853                                 cur.pos() = par.size();
854                                 // Insert a new paragraph
855                                 FuncRequest fr(LFUN_BREAK_PARAGRAPH);
856                                 dispatch(cur, fr);
857                         }
858                         */
859                         if (cur.selection())
860                                 cutSelection(cur, true, false);
861                         cur.insert(inset);
862                         cur.posForward();
863                 }
864                 break;
865         }
866
867         case LFUN_INSET_DISSOLVE:
868                 needsUpdate |= dissolveInset(cur);
869                 break;
870
871         case LFUN_INSET_SETTINGS:
872                 cur.inset().showInsetDialog(bv);
873                 break;
874
875         case LFUN_SPACE_INSERT:
876                 if (cur.paragraph().layout()->free_spacing)
877                         insertChar(cur, ' ');
878                 else {
879                         doInsertInset(cur, this, cmd, false, false);
880                         cur.posForward();
881                 }
882                 moveCursor(cur, false);
883                 break;
884
885         case LFUN_SPECIALCHAR_INSERT: {
886                 string const name = to_utf8(cmd.argument());
887                 if (name == "hyphenation")
888                         specialChar(cur, InsetSpecialChar::HYPHENATION);
889                 else if (name == "ligature-break")
890                         specialChar(cur, InsetSpecialChar::LIGATURE_BREAK);
891                 else if (name == "slash")
892                         specialChar(cur, InsetSpecialChar::SLASH);
893                 else if (name == "nobreakdash")
894                         specialChar(cur, InsetSpecialChar::NOBREAKDASH);
895                 else if (name == "dots")
896                         specialChar(cur, InsetSpecialChar::LDOTS);
897                 else if (name == "end-of-sentence")
898                         specialChar(cur, InsetSpecialChar::END_OF_SENTENCE);
899                 else if (name == "menu-separator")
900                         specialChar(cur, InsetSpecialChar::MENU_SEPARATOR);
901                 else if (name.empty())
902                         lyxerr << "LyX function 'specialchar-insert' needs an argument." << endl;
903                 else
904                         lyxerr << "Wrong argument for LyX function 'specialchar-insert'." << endl;
905                 break;
906         }
907
908         case LFUN_WORD_UPCASE:
909                 changeCase(cur, text_uppercase);
910                 break;
911
912         case LFUN_WORD_LOWCASE:
913                 changeCase(cur, text_lowercase);
914                 break;
915
916         case LFUN_WORD_CAPITALIZE:
917                 changeCase(cur, text_capitalization);
918                 break;
919
920         case LFUN_CHARS_TRANSPOSE:
921                 charsTranspose(cur);
922                 break;
923
924         case LFUN_PASTE: {
925                 cur.message(_("Paste"));
926                 cap::replaceSelection(cur);
927
928                 // without argument?
929                 string const arg = to_utf8(cmd.argument());
930                 if (arg.empty()) {
931                         if (theClipboard().isInternal())
932                                 pasteFromStack(cur, bv->buffer().errorList("Paste"), 0);
933                         else if (theClipboard().hasGraphicsContents())
934                                 pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"));
935                         else
936                                 pasteClipboardText(cur, bv->buffer().errorList("Paste"));
937                 } else if (isStrUnsignedInt(arg)) {
938                         // we have a numerical argument
939                         pasteFromStack(cur, bv->buffer().errorList("Paste"),
940                                        convert<unsigned int>(arg));
941                 } else {
942                         Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
943                         if (arg == "pdf")
944                                 type = Clipboard::PdfGraphicsType;
945                         else if (arg == "png")
946                                 type = Clipboard::PngGraphicsType;
947                         else if (arg == "jpeg")
948                                 type = Clipboard::JpegGraphicsType;
949                         else if (arg == "linkback")
950                                 type = Clipboard::LinkBackGraphicsType;
951                         else
952                                 BOOST_ASSERT(false);
953
954                         pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"), type);
955                 }
956
957                 bv->buffer().errors("Paste");
958                 cur.clearSelection(); // bug 393
959                 cur.finishUndo();
960                 break;
961         }
962
963         case LFUN_CUT:
964                 cutSelection(cur, true, true);
965                 cur.message(_("Cut"));
966                 break;
967
968         case LFUN_COPY:
969                 copySelection(cur);
970                 cur.message(_("Copy"));
971                 break;
972
973         case LFUN_SERVER_GET_XY:
974                 cur.message(from_utf8(
975                         convert<string>(tm.cursorX(cur.top(), cur.boundary()))
976                         + ' ' + convert<string>(tm.cursorY(cur.top(), cur.boundary()))));
977                 break;
978
979         case LFUN_SERVER_SET_XY: {
980                 int x = 0;
981                 int y = 0;
982                 istringstream is(to_utf8(cmd.argument()));
983                 is >> x >> y;
984                 if (!is)
985                         lyxerr << "SETXY: Could not parse coordinates in '"
986                                << to_utf8(cmd.argument()) << endl;
987                 else
988                         tm.setCursorFromCoordinates(cur, x, y);
989                 break;
990         }
991
992         case LFUN_SERVER_GET_FONT:
993                 if (cur.current_font.fontInfo().shape() == ITALIC_SHAPE)
994                         cur.message(from_ascii("E"));
995                 else if (cur.current_font.fontInfo().shape() == SMALLCAPS_SHAPE)
996                         cur.message(from_ascii("N"));
997                 else
998                         cur.message(from_ascii("0"));
999                 break;
1000
1001         case LFUN_SERVER_GET_LAYOUT:
1002                 cur.message(cur.paragraph().layout()->name());
1003                 break;
1004
1005         case LFUN_LAYOUT: {
1006                 docstring layout = cmd.argument();
1007                 LYXERR(Debug::INFO, "LFUN_LAYOUT: (arg) " << to_utf8(layout));
1008
1009                 Paragraph const & para = cur.paragraph();
1010                 docstring const old_layout = para.layout()->name();
1011                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1012
1013                 if (layout.empty())
1014                         layout = tclass.defaultLayoutName();
1015
1016                 if (para.forceEmptyLayout()) 
1017                         // in this case only the empty layout is allowed
1018                         layout = tclass.emptyLayoutName();
1019                 else if (para.useEmptyLayout()) {
1020                         // in this case, default layout maps to empty layout 
1021                         if (layout == tclass.defaultLayoutName())
1022                                 layout = tclass.emptyLayoutName();
1023                 } else { 
1024                         // otherwise, the empty layout maps to the default
1025                         if (layout == tclass.emptyLayoutName())
1026                                 layout = tclass.defaultLayoutName();
1027                 }
1028
1029                 bool hasLayout = tclass.hasLayout(layout);
1030
1031                 // If the entry is obsolete, use the new one instead.
1032                 if (hasLayout) {
1033                         docstring const & obs = tclass[layout]->obsoleted_by();
1034                         if (!obs.empty())
1035                                 layout = obs;
1036                 }
1037
1038                 if (!hasLayout) {
1039                         cur.errorMessage(from_utf8(N_("Layout ")) + cmd.argument() +
1040                                 from_utf8(N_(" not known")));
1041                         break;
1042                 }
1043
1044                 bool change_layout = (old_layout != layout);
1045
1046                 if (!change_layout && cur.selection() &&
1047                         cur.selBegin().pit() != cur.selEnd().pit())
1048                 {
1049                         pit_type spit = cur.selBegin().pit();
1050                         pit_type epit = cur.selEnd().pit() + 1;
1051                         while (spit != epit) {
1052                                 if (pars_[spit].layout()->name() != old_layout) {
1053                                         change_layout = true;
1054                                         break;
1055                                 }
1056                                 ++spit;
1057                         }
1058                 }
1059
1060                 if (change_layout)
1061                         setLayout(cur, layout);
1062
1063                 break;
1064         }
1065
1066         case LFUN_CLIPBOARD_PASTE:
1067                 cur.clearSelection();
1068                 pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1069                                cmd.argument() == "paragraph");
1070                 bv->buffer().errors("Paste");
1071                 break;
1072
1073         case LFUN_PRIMARY_SELECTION_PASTE:
1074                 pasteString(cur, theSelection().get(),
1075                             cmd.argument() == "paragraph");
1076                 break;
1077
1078         case LFUN_UNICODE_INSERT: {
1079                 if (cmd.argument().empty())
1080                         break;
1081                 docstring hexstring = cmd.argument();
1082                 if (isHex(hexstring)) {
1083                         char_type c = hexToInt(hexstring);
1084                         if (c >= 32 && c < 0x10ffff) {
1085                                 lyxerr << "Inserting c: " << c << endl;
1086                                 docstring s = docstring(1, c);
1087                                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, s));
1088                         }
1089                 }
1090                 break;
1091         }
1092
1093         case LFUN_QUOTE_INSERT: {
1094                 Paragraph & par = cur.paragraph();
1095                 pos_type pos = cur.pos();
1096                 BufferParams const & bufparams = bv->buffer().params();
1097                 LayoutPtr const & style = par.layout();
1098                 if (!style->pass_thru
1099                     && par.getFontSettings(bufparams, pos).language()->lang() != "hebrew") {
1100                         // this avoids a double undo
1101                         // FIXME: should not be needed, ideally
1102                         if (!cur.selection())
1103                                 cur.recordUndo();
1104                         cap::replaceSelection(cur);
1105                         pos = cur.pos();
1106                         char_type c;
1107                         if (pos == 0)
1108                                 c = ' ';
1109                         else if (cur.prevInset() && cur.prevInset()->isSpace())
1110                                 c = ' ';
1111                         else
1112                                 c = par.getChar(pos - 1);
1113                         string arg = to_utf8(cmd.argument());
1114                         if (arg == "single")
1115                                 cur.insert(new InsetQuotes(c,
1116                                     bufparams.quotes_language,
1117                                     InsetQuotes::SingleQ));
1118                         else
1119                                 cur.insert(new InsetQuotes(c,
1120                                     bufparams.quotes_language,
1121                                     InsetQuotes::DoubleQ));
1122                         cur.posForward();
1123                 }
1124                 else
1125                         lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, "\""));
1126                 break;
1127         }
1128
1129         case LFUN_DATE_INSERT: {
1130                 string const format = cmd.argument().empty()
1131                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
1132                 string const time = formatted_time(current_time(), format);
1133                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, time));
1134                 break;
1135         }
1136
1137         case LFUN_MOUSE_TRIPLE:
1138                 if (cmd.button() == mouse_button::button1) {
1139                         tm.cursorHome(cur);
1140                         cur.resetAnchor();
1141                         tm.cursorEnd(cur);
1142                         cur.setSelection();
1143                         bv->cursor() = cur;
1144                 }
1145                 break;
1146
1147         case LFUN_MOUSE_DOUBLE:
1148                 if (cmd.button() == mouse_button::button1) {
1149                         selectWord(cur, WHOLE_WORD_STRICT);
1150                         bv->cursor() = cur;
1151                 }
1152                 break;
1153
1154         // Single-click on work area
1155         case LFUN_MOUSE_PRESS: {
1156                 // Right click on a footnote flag opens float menu
1157                 // FIXME: Why should we clear the selection in this case?
1158                 if (cmd.button() == mouse_button::button3)
1159                         cur.clearSelection();
1160
1161                 bool do_selection = cmd.button() == mouse_button::button1
1162                         && cmd.argument() == "region-select";
1163                 // Set the cursor
1164                 bool update = bv->mouseSetCursor(cur, do_selection);
1165
1166                 // Insert primary selection with middle mouse
1167                 // if there is a local selection in the current buffer,
1168                 // insert this
1169                 if (cmd.button() == mouse_button::button2) {
1170                         if (cap::selection()) {
1171                                 // Copy the selection buffer to the clipboard
1172                                 // stack, because we want it to appear in the
1173                                 // "Edit->Paste recent" menu.
1174                                 cap::copySelectionToStack();
1175
1176                                 cap::pasteSelection(bv->cursor(), 
1177                                                     bv->buffer().errorList("Paste"));
1178                                 bv->buffer().errors("Paste");
1179                                 bv->buffer().markDirty();
1180                                 bv->cursor().finishUndo();
1181                         } else {
1182                                 lyx::dispatch(FuncRequest(LFUN_PRIMARY_SELECTION_PASTE, "paragraph"));
1183                         }
1184                 }
1185
1186                 // we have to update after dEPM triggered
1187                 if (!update && cmd.button() == mouse_button::button1) {
1188                         needsUpdate = false;
1189                         cur.noUpdate();
1190                 }
1191
1192                 break;
1193         }
1194
1195         case LFUN_MOUSE_MOTION: {
1196                 // Only use motion with button 1
1197                 //if (cmd.button() != mouse_button::button1)
1198                 //      return false;
1199
1200                 // ignore motions deeper nested than the real anchor
1201                 Cursor & bvcur = cur.bv().cursor();
1202                 if (!bvcur.anchor_.hasPart(cur)) {
1203                         cur.undispatched();
1204                         break;
1205                 }
1206                 CursorSlice old = bvcur.top();
1207
1208                 int const wh = bv->workHeight();
1209                 int const y = max(0, min(wh - 1, cmd.y));
1210
1211                 tm.setCursorFromCoordinates(cur, cmd.x, y);
1212                 cur.setTargetX(cmd.x);
1213                 if (cmd.y >= wh)
1214                         lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1215                 else if (cmd.y < 0)
1216                         lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1217                 // This is to allow jumping over large insets
1218                 if (cur.top() == old) {
1219                         if (cmd.y >= wh)
1220                                 lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1221                         else if (cmd.y < 0)
1222                                 lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1223                 }
1224
1225                 if (cur.top() == old)
1226                         cur.noUpdate();
1227                 else {
1228                         // FIXME: This is brute force! But without it the selected
1229                         // area is not corrected updated while moving the mouse.
1230                         cur.updateFlags(Update::Force | Update::FitCursor);
1231                         // don't set anchor_
1232                         bvcur.setCursor(cur);
1233                         bvcur.selection() = true;
1234                         //lyxerr << "MOTION: " << bv->cursor() << endl;
1235                 }
1236                 break;
1237         }
1238
1239         case LFUN_MOUSE_RELEASE: {
1240                 if (cmd.button() == mouse_button::button2)
1241                         break;
1242
1243                 if (cmd.button() == mouse_button::button1) {
1244                         // if there is new selection, update persistent
1245                         // selection, otherwise, single click does not
1246                         // clear persistent selection buffer
1247                         if (cur.selection()) {
1248                                 // finish selection
1249                                 // if double click, cur is moved to the end of word by selectWord
1250                                 // but bvcur is current mouse position
1251                                 Cursor & bvcur = cur.bv().cursor();
1252                                 bvcur.selection() = true;
1253                         }
1254                         needsUpdate = false;
1255                         cur.noUpdate();
1256                 }
1257
1258                 break;
1259         }
1260
1261         case LFUN_SELF_INSERT: {
1262                 if (cmd.argument().empty())
1263                         break;
1264
1265                 // Automatically delete the currently selected
1266                 // text and replace it with what is being
1267                 // typed in now. Depends on lyxrc settings
1268                 // "auto_region_delete", which defaults to
1269                 // true (on).
1270
1271                 if (lyxrc.auto_region_delete && cur.selection())
1272                         cutSelection(cur, false, false);
1273
1274                 cur.clearSelection();
1275                 Font const old_font = cur.real_current_font;
1276
1277                 docstring::const_iterator cit = cmd.argument().begin();
1278                 docstring::const_iterator end = cmd.argument().end();
1279                 for (; cit != end; ++cit)
1280                         bv->translateAndInsert(*cit, this, cur);
1281
1282                 cur.resetAnchor();
1283                 moveCursor(cur, false);
1284                 break;
1285         }
1286
1287         case LFUN_HYPERLINK_INSERT: {
1288                 InsetCommandParams p(HYPERLINK_CODE);
1289                 docstring content;
1290                 if (cur.selection()) {
1291                         content = cur.selectionAsString(false);
1292                         cutSelection(cur, true, false);
1293                 }
1294                 p["target"] = (cmd.argument().empty()) ?
1295                         content : cmd.argument();
1296                 string const data = InsetCommandMailer::params2string("href", p);
1297                 if (p["target"].empty()) {
1298                         bv->showDialog("href", data);
1299                 } else {
1300                         FuncRequest fr(LFUN_INSET_INSERT, data);
1301                         dispatch(cur, fr);
1302                 }
1303                 break;
1304         }
1305
1306         case LFUN_LABEL_INSERT: {
1307                 InsetCommandParams p(LABEL_CODE);
1308                 // Try to generate a valid label
1309                 p["name"] = (cmd.argument().empty()) ?
1310                         cur.getPossibleLabel() :
1311                         cmd.argument();
1312                 string const data = InsetCommandMailer::params2string("label", p);
1313
1314                 if (cmd.argument().empty()) {
1315                         bv->showDialog("label", data);
1316                 } else {
1317                         FuncRequest fr(LFUN_INSET_INSERT, data);
1318                         dispatch(cur, fr);
1319                 }
1320                 break;
1321         }
1322
1323         case LFUN_INFO_INSERT: {
1324                 Inset * inset = createInset(cur.bv().buffer(), cmd);
1325                 if (!inset)
1326                         break;
1327                 // if an empty inset is created (cmd.argument() is empty)
1328                 // use current selection as parameter.
1329                 if (cmd.argument().empty() && cur.selection()) {
1330                         // use selected text as info to avoid a separate UI
1331                         docstring ds = cur.selectionAsString(false);
1332                         cutSelection(cur, true, false);
1333                         static_cast<InsetInfo *>(inset)->setInfo(to_utf8(ds));
1334                         static_cast<InsetInfo *>(inset)->updateInfo();
1335                 }
1336                 insertInset(cur, inset);
1337                 cur.posForward();
1338                 break;
1339         }
1340 #if 0
1341         case LFUN_LIST_INSERT:
1342 #endif
1343         case LFUN_CAPTION_INSERT:
1344         case LFUN_FOOTNOTE_INSERT:
1345         case LFUN_NOTE_INSERT:
1346         case LFUN_FLEX_INSERT:
1347         case LFUN_BOX_INSERT:
1348         case LFUN_BRANCH_INSERT:
1349         case LFUN_BIBITEM_INSERT:
1350         case LFUN_ERT_INSERT:
1351         case LFUN_LISTING_INSERT:
1352         case LFUN_MARGINALNOTE_INSERT:
1353         case LFUN_OPTIONAL_INSERT:
1354         case LFUN_ENVIRONMENT_INSERT:
1355         case LFUN_INDEX_INSERT:
1356                 // Open the inset, and move the current selection
1357                 // inside it.
1358                 doInsertInset(cur, this, cmd, true, true);
1359                 cur.posForward();
1360                 // Some insets are numbered, others are shown in the outline pane so
1361                 // let's update the labels and the toc backend.
1362                 updateLabels(bv->buffer());
1363                 break;
1364
1365         case LFUN_TABULAR_INSERT:
1366                 // if there were no arguments, just open the dialog
1367                 if (doInsertInset(cur, this, cmd, false, true))
1368                         cur.posForward();
1369                 else
1370                         bv->showDialog("tabularcreate");
1371
1372                 break;
1373
1374         case LFUN_FLOAT_INSERT:
1375         case LFUN_FLOAT_WIDE_INSERT:
1376         case LFUN_WRAP_INSERT: {
1377                 bool content = cur.selection();  // will some text be moved into the inset?
1378
1379                 doInsertInset(cur, this, cmd, true, true);
1380                 cur.posForward();
1381                 ParagraphList & pars = cur.text()->paragraphs();
1382
1383                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1384
1385                 // add a separate paragraph for the caption inset
1386                 pars.push_back(Paragraph());
1387                 pars.back().setInsetOwner(pars[0].inInset());
1388                 pars.back().setEmptyOrDefaultLayout(tclass);
1389                 int cap_pit = pars.size() - 1;
1390
1391                 // if an empty inset was created, we create an additional empty
1392                 // paragraph at the bottom so that the user can choose where to put
1393                 // the graphics (or table).
1394                 if (!content) {
1395                         pars.push_back(Paragraph());
1396                         pars.back().setInsetOwner(pars[0].inInset());
1397                         pars.back().setEmptyOrDefaultLayout(tclass);
1398                 }
1399
1400                 // reposition the cursor to the caption
1401                 cur.pit() = cap_pit;
1402                 cur.pos() = 0;
1403                 // FIXME: This Text/Cursor dispatch handling is a mess!
1404                 // We cannot use Cursor::dispatch here it needs access to up to
1405                 // date metrics.
1406                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
1407                 cur.text()->dispatch(cur, cmd_caption);
1408                 cur.updateFlags(Update::Force);
1409                 // FIXME: When leaving the Float (or Wrap) inset we should
1410                 // delete any empty paragraph left above or below the
1411                 // caption.
1412                 break;
1413         }
1414
1415         case LFUN_NOMENCL_INSERT: {
1416                 FuncRequest cmd1 = cmd;
1417                 if (cmd.argument().empty())
1418                         cmd1 = FuncRequest(cmd,
1419                                 bv->cursor().innerText()->getStringToIndex(bv->cursor()));
1420                 Inset * inset = createInset(cur.bv().buffer(), cmd1);
1421                 if (!inset)
1422                         break;
1423                 cur.recordUndo();
1424                 cur.clearSelection();
1425                 insertInset(cur, inset);
1426                 // Show the dialog for the nomenclature entry, since the
1427                 // description entry still needs to be filled in.
1428                 if (cmd.action == LFUN_NOMENCL_INSERT)
1429                         inset->edit(cur, true);
1430                 cur.posForward();
1431                 break;
1432         }
1433
1434         case LFUN_INDEX_PRINT:
1435         case LFUN_NOMENCL_PRINT:
1436         case LFUN_TOC_INSERT:
1437         case LFUN_HFILL_INSERT:
1438         case LFUN_LINE_INSERT:
1439         case LFUN_NEWPAGE_INSERT:
1440         case LFUN_PAGEBREAK_INSERT:
1441         case LFUN_CLEARPAGE_INSERT:
1442         case LFUN_CLEARDOUBLEPAGE_INSERT:
1443                 // do nothing fancy
1444                 doInsertInset(cur, this, cmd, false, false);
1445                 cur.posForward();
1446                 break;
1447
1448         case LFUN_DEPTH_DECREMENT:
1449                 changeDepth(cur, DEC_DEPTH);
1450                 break;
1451
1452         case LFUN_DEPTH_INCREMENT:
1453                 changeDepth(cur, INC_DEPTH);
1454                 break;
1455
1456         case LFUN_MATH_DISPLAY:
1457                 mathDispatch(cur, cmd, true);
1458                 break;
1459
1460         case LFUN_MATH_IMPORT_SELECTION:
1461         case LFUN_MATH_MODE:
1462                 if (cmd.argument() == "on")
1463                         // don't pass "on" as argument
1464                         mathDispatch(cur, FuncRequest(LFUN_MATH_MODE), false);
1465                 else
1466                         mathDispatch(cur, cmd, false);
1467                 break;
1468
1469         case LFUN_MATH_MACRO:
1470                 if (cmd.argument().empty())
1471                         cur.errorMessage(from_utf8(N_("Missing argument")));
1472                 else {
1473                         string s = to_utf8(cmd.argument());
1474                         string const s1 = token(s, ' ', 1);
1475                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
1476                         string const s2 = token(s, ' ', 2);
1477                         MacroType type = MacroTypeNewcommand;
1478                         if (s2 == "def")
1479                                 type = MacroTypeDef;
1480                         cur.insert(new MathMacroTemplate(from_utf8(token(s, ' ', 0)), nargs, false, type));
1481                         //cur.nextInset()->edit(cur, true);
1482                 }
1483                 break;
1484
1485         // passthrough hat and underscore outside mathed:
1486         case LFUN_MATH_SUBSCRIPT:
1487                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "_"), false);
1488                 break;
1489         case LFUN_MATH_SUPERSCRIPT:
1490                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "^"), false);
1491                 break;
1492
1493         case LFUN_MATH_INSERT:
1494         case LFUN_MATH_MATRIX:
1495         case LFUN_MATH_DELIM:
1496         case LFUN_MATH_BIGDELIM: {
1497                 cap::replaceSelection(cur);
1498                 cur.insert(new InsetMathHull(hullSimple));
1499                 checkAndActivateInset(cur, true);
1500                 BOOST_ASSERT(cur.inMathed());
1501                 cur.dispatch(cmd);
1502                 break;
1503         }
1504
1505         case LFUN_FONT_EMPH: {
1506                 Font font(ignore_font, ignore_language);
1507                 font.fontInfo().setEmph(FONT_TOGGLE);
1508                 toggleAndShow(cur, this, font);
1509                 break;
1510         }
1511
1512         case LFUN_FONT_BOLD: {
1513                 Font font(ignore_font, ignore_language);
1514                 font.fontInfo().setSeries(BOLD_SERIES);
1515                 toggleAndShow(cur, this, font);
1516                 break;
1517         }
1518
1519         case LFUN_FONT_NOUN: {
1520                 Font font(ignore_font, ignore_language);
1521                 font.fontInfo().setNoun(FONT_TOGGLE);
1522                 toggleAndShow(cur, this, font);
1523                 break;
1524         }
1525
1526         case LFUN_FONT_TYPEWRITER: {
1527                 Font font(ignore_font, ignore_language);
1528                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
1529                 toggleAndShow(cur, this, font);
1530                 break;
1531         }
1532
1533         case LFUN_FONT_SANS: {
1534                 Font font(ignore_font, ignore_language);
1535                 font.fontInfo().setFamily(SANS_FAMILY);
1536                 toggleAndShow(cur, this, font);
1537                 break;
1538         }
1539
1540         case LFUN_FONT_ROMAN: {
1541                 Font font(ignore_font, ignore_language);
1542                 font.fontInfo().setFamily(ROMAN_FAMILY);
1543                 toggleAndShow(cur, this, font);
1544                 break;
1545         }
1546
1547         case LFUN_FONT_DEFAULT: {
1548                 Font font(inherit_font, ignore_language);
1549                 toggleAndShow(cur, this, font);
1550                 break;
1551         }
1552
1553         case LFUN_FONT_UNDERLINE: {
1554                 Font font(ignore_font, ignore_language);
1555                 font.fontInfo().setUnderbar(FONT_TOGGLE);
1556                 toggleAndShow(cur, this, font);
1557                 break;
1558         }
1559
1560         case LFUN_FONT_SIZE: {
1561                 Font font(ignore_font, ignore_language);
1562                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
1563                 toggleAndShow(cur, this, font);
1564                 break;
1565         }
1566
1567         case LFUN_LANGUAGE: {
1568                 Language const * lang = languages.getLanguage(to_utf8(cmd.argument()));
1569                 if (!lang)
1570                         break;
1571                 Font font(ignore_font, lang);
1572                 toggleAndShow(cur, this, font);
1573                 break;
1574         }
1575
1576         case LFUN_FONT_FREE_APPLY:
1577                 toggleAndShow(cur, this, freefont, toggleall);
1578                 cur.message(_("Character set"));
1579                 break;
1580
1581         // Set the freefont using the contents of \param data dispatched from
1582         // the frontends and apply it at the current cursor location.
1583         case LFUN_FONT_FREE_UPDATE: {
1584                 Font font;
1585                 bool toggle;
1586                 if (font.fromString(to_utf8(cmd.argument()), toggle)) {
1587                         freefont = font;
1588                         toggleall = toggle;
1589                         toggleAndShow(cur, this, freefont, toggleall);
1590                         cur.message(_("Character set"));
1591                 } else {
1592                         lyxerr << "Argument not ok";
1593                 }
1594                 break;
1595         }
1596
1597         case LFUN_FINISHED_LEFT:
1598                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
1599                 // We're leaving an inset, going left. If the inset is LTR, we're 
1600                 // leaving from the front, so we should not move (remain at --- but
1601                 // not in --- the inset). If the inset is RTL, move left, without 
1602                 // entering the inset itself; i.e., move to after the inset.
1603                 if (cur.paragraph().getFontSettings(
1604                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
1605                         cursorVisLeft(cur, true);
1606                 break;
1607
1608         case LFUN_FINISHED_RIGHT:
1609                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
1610                 // We're leaving an inset, going right. If the inset is RTL, we're 
1611                 // leaving from the front, so we should not move (remain at --- but
1612                 // not in --- the inset). If the inset is LTR, move right, without 
1613                 // entering the inset itself; i.e., move to after the inset.
1614                 if (!cur.paragraph().getFontSettings(
1615                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
1616                         cursorVisRight(cur, true);
1617                 break;
1618
1619         case LFUN_FINISHED_BACKWARD:
1620                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
1621                 break;
1622
1623         case LFUN_FINISHED_FORWARD:
1624                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
1625                 ++cur.pos();
1626                 cur.setCurrentFont();
1627                 break;
1628
1629         case LFUN_LAYOUT_PARAGRAPH: {
1630                 string data;
1631                 params2string(cur.paragraph(), data);
1632                 data = "show\n" + data;
1633                 bv->showDialog("paragraph", data);
1634                 break;
1635         }
1636
1637         case LFUN_PARAGRAPH_UPDATE: {
1638                 string data;
1639                 params2string(cur.paragraph(), data);
1640
1641                 // Will the paragraph accept changes from the dialog?
1642                 bool const accept = 
1643                         cur.inset().allowParagraphCustomization(cur.idx());
1644
1645                 data = "update " + convert<string>(accept) + '\n' + data;
1646                 bv->updateDialog("paragraph", data);
1647                 break;
1648         }
1649
1650         case LFUN_ACCENT_UMLAUT:
1651         case LFUN_ACCENT_CIRCUMFLEX:
1652         case LFUN_ACCENT_GRAVE:
1653         case LFUN_ACCENT_ACUTE:
1654         case LFUN_ACCENT_TILDE:
1655         case LFUN_ACCENT_CEDILLA:
1656         case LFUN_ACCENT_MACRON:
1657         case LFUN_ACCENT_DOT:
1658         case LFUN_ACCENT_UNDERDOT:
1659         case LFUN_ACCENT_UNDERBAR:
1660         case LFUN_ACCENT_CARON:
1661         case LFUN_ACCENT_SPECIAL_CARON:
1662         case LFUN_ACCENT_BREVE:
1663         case LFUN_ACCENT_TIE:
1664         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
1665         case LFUN_ACCENT_CIRCLE:
1666         case LFUN_ACCENT_OGONEK:
1667                 theLyXFunc().handleKeyFunc(cmd.action);
1668                 if (!cmd.argument().empty())
1669                         // FIXME: Are all these characters encoded in one byte in utf8?
1670                         bv->translateAndInsert(cmd.argument()[0], this, cur);
1671                 break;
1672
1673         case LFUN_FLOAT_LIST: {
1674                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1675                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
1676                         cur.recordUndo();
1677                         if (cur.selection())
1678                                 cutSelection(cur, true, false);
1679                         breakParagraph(cur);
1680
1681                         if (cur.lastpos() != 0) {
1682                                 cursorBackward(cur);
1683                                 breakParagraph(cur);
1684                         }
1685
1686                         //FIXME Check if this should be emptyLayout()
1687                         setLayout(cur, tclass.defaultLayoutName());
1688                         ParagraphParameters p;
1689                         setParagraphs(cur, p);
1690                         insertInset(cur, new InsetFloatList(to_utf8(cmd.argument())));
1691                         cur.posForward();
1692                 } else {
1693                         lyxerr << "Non-existent float type: "
1694                                << to_utf8(cmd.argument()) << endl;
1695                 }
1696                 break;
1697         }
1698
1699         case LFUN_CHANGE_ACCEPT: {
1700                 acceptOrRejectChanges(cur, ACCEPT);
1701                 break;
1702         }
1703
1704         case LFUN_CHANGE_REJECT: {
1705                 acceptOrRejectChanges(cur, REJECT);
1706                 break;
1707         }
1708
1709         case LFUN_THESAURUS_ENTRY: {
1710                 docstring arg = cmd.argument();
1711                 if (arg.empty()) {
1712                         arg = cur.selectionAsString(false);
1713                         // FIXME
1714                         if (arg.size() > 100 || arg.empty()) {
1715                                 // Get word or selection
1716                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
1717                                 arg = cur.selectionAsString(false);
1718                         }
1719                 }
1720                 bv->showDialog("thesaurus", to_utf8(arg));
1721                 break;
1722         }
1723
1724         case LFUN_PARAGRAPH_PARAMS_APPLY: {
1725                 // Given data, an encoding of the ParagraphParameters
1726                 // generated in the Paragraph dialog, this function sets
1727                 // the current paragraph, or currently selected paragraphs,
1728                 // appropriately. 
1729                 // NOTE: This function overrides all existing settings.
1730                 setParagraphs(cur, cmd.argument());
1731                 cur.message(_("Paragraph layout set"));
1732                 break;
1733         }
1734         
1735         case LFUN_PARAGRAPH_PARAMS: {
1736                 // Given data, an encoding of the ParagraphParameters as we'd
1737                 // find them in a LyX file, this function modifies the current paragraph, 
1738                 // or currently selected paragraphs. 
1739                 // NOTE: This function only modifies, and does not override, existing
1740                 // settings.
1741                 setParagraphs(cur, cmd.argument(), true);
1742                 cur.message(_("Paragraph layout set"));
1743                 break;
1744         }
1745
1746         case LFUN_ESCAPE:
1747                 if (cur.selection()) {
1748                         cur.selection() = false;
1749                 } else {
1750                         cur.undispatched();
1751                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
1752                         // correct, but I'm not 100% sure -- dov, 071019
1753                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
1754                 }
1755                 break;
1756
1757         case LFUN_OUTLINE_UP:
1758                 outline(OutlineUp, cur);
1759                 setCursor(cur, cur.pit(), 0);
1760                 updateLabels(cur.buffer());
1761                 needsUpdate = true;
1762                 break;
1763
1764         case LFUN_OUTLINE_DOWN:
1765                 outline(OutlineDown, cur);
1766                 setCursor(cur, cur.pit(), 0);
1767                 updateLabels(cur.buffer());
1768                 needsUpdate = true;
1769                 break;
1770
1771         case LFUN_OUTLINE_IN:
1772                 outline(OutlineIn, cur);
1773                 updateLabels(cur.buffer());
1774                 needsUpdate = true;
1775                 break;
1776
1777         case LFUN_OUTLINE_OUT:
1778                 outline(OutlineOut, cur);
1779                 updateLabels(cur.buffer());
1780                 needsUpdate = true;
1781                 break;
1782
1783         default:
1784                 LYXERR(Debug::ACTION, "Command " << cmd << " not DISPATCHED by Text");
1785                 cur.undispatched();
1786                 break;
1787         }
1788
1789         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
1790
1791         // FIXME: The cursor flag is reset two lines below
1792         // so we need to check here if some of the LFUN did touch that.
1793         // for now only Text::erase() and Text::backspace() do that.
1794         // The plan is to verify all the LFUNs and then to remove this
1795         // singleParUpdate boolean altogether.
1796         if (cur.result().update() & Update::Force) {
1797                 singleParUpdate = false;
1798                 needsUpdate = true;
1799         }
1800
1801         // FIXME: the following code should go in favor of fine grained
1802         // update flag treatment.
1803         if (singleParUpdate) {
1804                 // Inserting characters does not change par height in general. So, try
1805                 // to update _only_ this paragraph. BufferView will detect if a full
1806                 // metrics update is needed anyway.
1807                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1808                 return;
1809         }
1810
1811         if (!needsUpdate
1812             && &oldTopSlice.inset() == &cur.inset()
1813             && oldTopSlice.idx() == cur.idx()
1814             && !sel // sel is a backup of cur.selection() at the biginning of the function.
1815             && !cur.selection())
1816                 // FIXME: it would be better if we could just do this
1817                 //
1818                 //if (cur.result().update() != Update::FitCursor)
1819                 //      cur.noUpdate();
1820                 //
1821                 // But some LFUNs do not set Update::FitCursor when needed, so we
1822                 // do it for all. This is not very harmfull as FitCursor will provoke
1823                 // a full redraw only if needed but still, a proper review of all LFUN
1824                 // should be done and this needsUpdate boolean can then be removed.
1825                 cur.updateFlags(Update::FitCursor);
1826         else
1827                 cur.updateFlags(Update::Force | Update::FitCursor);
1828 }
1829
1830
1831 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
1832                         FuncStatus & flag) const
1833 {
1834         BOOST_ASSERT(cur.text() == this);
1835
1836         Font const & font = cur.real_current_font;
1837         FontInfo const & fontinfo = font.fontInfo();
1838         bool enable = true;
1839         InsetCode code = NO_CODE;
1840
1841         switch (cmd.action) {
1842
1843         case LFUN_DEPTH_DECREMENT:
1844                 enable = changeDepthAllowed(cur, DEC_DEPTH);
1845                 break;
1846
1847         case LFUN_DEPTH_INCREMENT:
1848                 enable = changeDepthAllowed(cur, INC_DEPTH);
1849                 break;
1850
1851         case LFUN_APPENDIX:
1852                 flag.setOnOff(cur.paragraph().params().startOfAppendix());
1853                 return true;
1854
1855         case LFUN_BIBITEM_INSERT:
1856                 enable = (cur.paragraph().layout()->labeltype == LABEL_BIBLIO
1857                           && cur.pos() == 0);
1858                 break;
1859
1860         case LFUN_DIALOG_SHOW_NEW_INSET:
1861                 if (cmd.argument() == "bibitem")
1862                         code = BIBITEM_CODE;
1863                 else if (cmd.argument() == "bibtex")
1864                         code = BIBTEX_CODE;
1865                 else if (cmd.argument() == "box")
1866                         code = BOX_CODE;
1867                 else if (cmd.argument() == "branch")
1868                         code = BRANCH_CODE;
1869                 else if (cmd.argument() == "citation")
1870                         code = CITE_CODE;
1871                 else if (cmd.argument() == "ert")
1872                         code = ERT_CODE;
1873                 else if (cmd.argument() == "external")
1874                         code = EXTERNAL_CODE;
1875                 else if (cmd.argument() == "float")
1876                         code = FLOAT_CODE;
1877                 else if (cmd.argument() == "graphics")
1878                         code = GRAPHICS_CODE;
1879                 else if (cmd.argument() == "href")
1880                         code = HYPERLINK_CODE;
1881                 else if (cmd.argument() == "include")
1882                         code = INCLUDE_CODE;
1883                 else if (cmd.argument() == "index")
1884                         code = INDEX_CODE;
1885                 else if (cmd.argument() == "nomenclature")
1886                         code = NOMENCL_CODE;
1887                 else if (cmd.argument() == "label")
1888                         code = LABEL_CODE;
1889                 else if (cmd.argument() == "note")
1890                         code = NOTE_CODE;
1891                 else if (cmd.argument() == "ref")
1892                         code = REF_CODE;
1893                 else if (cmd.argument() == "toc")
1894                         code = TOC_CODE;
1895                 else if (cmd.argument() == "vspace")
1896                         code = VSPACE_CODE;
1897                 else if (cmd.argument() == "wrap")
1898                         code = WRAP_CODE;
1899                 else if (cmd.argument() == "listings")
1900                         code = LISTINGS_CODE;
1901                 break;
1902
1903         case LFUN_ERT_INSERT:
1904                 code = ERT_CODE;
1905                 break;
1906         case LFUN_LISTING_INSERT:
1907             code = LISTINGS_CODE;
1908                 break;
1909         case LFUN_FOOTNOTE_INSERT:
1910                 code = FOOT_CODE;
1911                 break;
1912         case LFUN_TABULAR_INSERT:
1913                 code = TABULAR_CODE;
1914                 break;
1915         case LFUN_MARGINALNOTE_INSERT:
1916                 code = MARGIN_CODE;
1917                 break;
1918         case LFUN_FLOAT_INSERT:
1919         case LFUN_FLOAT_WIDE_INSERT:
1920                 code = FLOAT_CODE;
1921                 break;
1922         case LFUN_WRAP_INSERT:
1923                 code = WRAP_CODE;
1924                 break;
1925         case LFUN_FLOAT_LIST:
1926                 code = FLOAT_LIST_CODE;
1927                 break;
1928 #if 0
1929         case LFUN_LIST_INSERT:
1930                 code = LIST_CODE;
1931                 break;
1932 #endif
1933         case LFUN_CAPTION_INSERT:
1934                 code = CAPTION_CODE;
1935                 break;
1936         case LFUN_NOTE_INSERT:
1937                 code = NOTE_CODE;
1938                 break;
1939         case LFUN_FLEX_INSERT: {
1940                 code = FLEX_CODE;
1941                 string s = cmd.getArg(0);
1942                 InsetLayout il = 
1943                         cur.buffer().params().documentClass().insetLayout(from_utf8(s));
1944                 if (il.lyxtype() != "charstyle" &&
1945                     il.lyxtype() != "custom" &&
1946                     il.lyxtype() != "element" &&
1947                     il.lyxtype ()!= "standard")
1948                         enable = false;
1949                 break;
1950                 }
1951         case LFUN_BOX_INSERT:
1952                 code = BOX_CODE;
1953                 break;
1954         case LFUN_BRANCH_INSERT:
1955                 code = BRANCH_CODE;
1956                 if (cur.buffer().masterBuffer()->params().branchlist().empty())
1957                         enable = false;
1958                 break;
1959         case LFUN_LABEL_INSERT:
1960                 code = LABEL_CODE;
1961                 break;
1962         case LFUN_INFO_INSERT:
1963                 code = INFO_CODE;
1964                 break;
1965         case LFUN_OPTIONAL_INSERT:
1966                 code = OPTARG_CODE;
1967                 enable = cur.paragraph().insetList().count(OPTARG_CODE)
1968                         < cur.paragraph().layout()->optionalargs;
1969                 break;
1970         case LFUN_ENVIRONMENT_INSERT:
1971                 code = BOX_CODE;
1972                 break;
1973         case LFUN_INDEX_INSERT:
1974                 code = INDEX_CODE;
1975                 break;
1976         case LFUN_INDEX_PRINT:
1977                 code = INDEX_PRINT_CODE;
1978                 break;
1979         case LFUN_NOMENCL_INSERT:
1980                 code = NOMENCL_CODE;
1981                 break;
1982         case LFUN_NOMENCL_PRINT:
1983                 code = NOMENCL_PRINT_CODE;
1984                 break;
1985         case LFUN_TOC_INSERT:
1986                 code = TOC_CODE;
1987                 break;
1988         case LFUN_HYPERLINK_INSERT:
1989                 code = HYPERLINK_CODE;
1990                 break;
1991         case LFUN_QUOTE_INSERT:
1992                 // always allow this, since we will inset a raw quote
1993                 // if an inset is not allowed.
1994                 break;
1995         case LFUN_HFILL_INSERT:
1996         case LFUN_SPECIALCHAR_INSERT:
1997                 code = SPECIALCHAR_CODE;
1998                 break;
1999         case LFUN_SPACE_INSERT:
2000                 // slight hack: we know this is allowed in math mode
2001                 if (cur.inTexted())
2002                         code = SPACE_CODE;
2003                 break;
2004
2005         case LFUN_INSET_MODIFY:
2006                 // We need to disable this, because we may get called for a
2007                 // tabular cell via
2008                 // InsetTabular::getStatus() -> InsetText::getStatus()
2009                 // and we don't handle LFUN_INSET_MODIFY.
2010                 enable = false;
2011                 break;
2012
2013         case LFUN_FONT_EMPH:
2014                 flag.setOnOff(fontinfo.emph() == FONT_ON);
2015                 return true;
2016
2017         case LFUN_FONT_NOUN:
2018                 flag.setOnOff(fontinfo.noun() == FONT_ON);
2019                 return true;
2020
2021         case LFUN_FONT_BOLD:
2022                 flag.setOnOff(fontinfo.series() == BOLD_SERIES);
2023                 return true;
2024
2025         case LFUN_FONT_SANS:
2026                 flag.setOnOff(fontinfo.family() == SANS_FAMILY);
2027                 return true;
2028
2029         case LFUN_FONT_ROMAN:
2030                 flag.setOnOff(fontinfo.family() == ROMAN_FAMILY);
2031                 return true;
2032
2033         case LFUN_FONT_TYPEWRITER:
2034                 flag.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
2035                 return true;
2036
2037         case LFUN_CUT:
2038         case LFUN_COPY:
2039                 enable = cur.selection();
2040                 break;
2041
2042         case LFUN_PASTE: {
2043                 if (cmd.argument().empty()) {
2044                         if (theClipboard().isInternal())
2045                                 enable = cap::numberOfSelections() > 0;
2046                         else
2047                                 enable = !theClipboard().empty();
2048                         break;
2049                 }
2050                 
2051                 // we have an argument
2052                 string const arg = to_utf8(cmd.argument());
2053                 if (isStrUnsignedInt(arg)) {
2054                         // it's a number and therefore means the internal stack
2055                         unsigned int n = convert<unsigned int>(arg);
2056                         enable = cap::numberOfSelections() > n;
2057                         break;
2058                 }
2059                 
2060                 // explicit graphics type?
2061                 if ((arg == "pdf" && theClipboard().hasGraphicsContents(Clipboard::PdfGraphicsType))
2062                     || (arg == "png" && theClipboard().hasGraphicsContents(Clipboard::PngGraphicsType))
2063                     || (arg == "jpeg" && theClipboard().hasGraphicsContents(Clipboard::JpegGraphicsType))
2064                     || (arg == "linkback" && theClipboard().hasGraphicsContents(Clipboard::LinkBackGraphicsType))) {
2065                         enable = true;
2066                         break;
2067                 }
2068                 
2069                 // unknown argument
2070                 enable = false;
2071                 break;
2072          }
2073
2074         case LFUN_CLIPBOARD_PASTE:
2075                 enable = !theClipboard().empty();
2076                 break;
2077
2078         case LFUN_PRIMARY_SELECTION_PASTE:
2079                 enable = cur.selection() || !theSelection().empty();
2080                 break;
2081
2082         case LFUN_PARAGRAPH_MOVE_UP:
2083                 enable = cur.pit() > 0 && !cur.selection();
2084                 break;
2085
2086         case LFUN_PARAGRAPH_MOVE_DOWN:
2087                 enable = cur.pit() < cur.lastpit() && !cur.selection();
2088                 break;
2089
2090         case LFUN_INSET_DISSOLVE:
2091                 if (!cmd.argument().empty()) {
2092                         InsetLayout il = cur.inset().getLayout(cur.buffer().params());
2093                         enable = cur.inset().lyxCode() == FLEX_CODE
2094                                  && il.lyxtype() == to_utf8(cmd.argument());
2095                 } else {
2096                         enable = !isMainText(cur.bv().buffer()) 
2097                                  && cur.inset().nargs() == 1;
2098                 }
2099                 break;
2100
2101         case LFUN_CHANGE_ACCEPT:
2102         case LFUN_CHANGE_REJECT:
2103                 // TODO: context-sensitive enabling of LFUN_CHANGE_ACCEPT/REJECT
2104                 // In principle, these LFUNs should only be enabled if there
2105                 // is a change at the current position/in the current selection.
2106                 // However, without proper optimizations, this will inevitably
2107                 // result in unacceptable performance - just imagine a user who
2108                 // wants to select the complete content of a long document.
2109                 enable = true;
2110                 break;
2111
2112         case LFUN_OUTLINE_UP:
2113         case LFUN_OUTLINE_DOWN:
2114         case LFUN_OUTLINE_IN:
2115         case LFUN_OUTLINE_OUT:
2116                 enable = (cur.paragraph().layout()->toclevel != Layout::NOT_IN_TOC);
2117                 break;
2118
2119         case LFUN_WORD_DELETE_FORWARD:
2120         case LFUN_WORD_DELETE_BACKWARD:
2121         case LFUN_LINE_DELETE:
2122         case LFUN_WORD_FORWARD:
2123         case LFUN_WORD_BACKWARD:
2124         case LFUN_WORD_RIGHT:
2125         case LFUN_WORD_LEFT:
2126         case LFUN_CHAR_FORWARD:
2127         case LFUN_CHAR_FORWARD_SELECT:
2128         case LFUN_CHAR_BACKWARD:
2129         case LFUN_CHAR_BACKWARD_SELECT:
2130         case LFUN_CHAR_LEFT:
2131         case LFUN_CHAR_LEFT_SELECT:
2132         case LFUN_CHAR_RIGHT:
2133         case LFUN_CHAR_RIGHT_SELECT:
2134         case LFUN_UP:
2135         case LFUN_UP_SELECT:
2136         case LFUN_DOWN:
2137         case LFUN_DOWN_SELECT:
2138         case LFUN_PARAGRAPH_UP_SELECT:
2139         case LFUN_PARAGRAPH_DOWN_SELECT:
2140         case LFUN_SCREEN_UP_SELECT:
2141         case LFUN_SCREEN_DOWN_SELECT:
2142         case LFUN_LINE_BEGIN_SELECT:
2143         case LFUN_LINE_END_SELECT:
2144         case LFUN_WORD_FORWARD_SELECT:
2145         case LFUN_WORD_BACKWARD_SELECT:
2146         case LFUN_WORD_RIGHT_SELECT:
2147         case LFUN_WORD_LEFT_SELECT:
2148         case LFUN_WORD_SELECT:
2149         case LFUN_PARAGRAPH_UP:
2150         case LFUN_PARAGRAPH_DOWN:
2151         case LFUN_LINE_BEGIN:
2152         case LFUN_LINE_BREAK:
2153         case LFUN_LINE_END:
2154         case LFUN_NEW_LINE:
2155         case LFUN_CHAR_DELETE_FORWARD:
2156         case LFUN_DELETE_FORWARD_SKIP:
2157         case LFUN_CHAR_DELETE_BACKWARD:
2158         case LFUN_DELETE_BACKWARD_SKIP:
2159         case LFUN_BREAK_PARAGRAPH:
2160         case LFUN_BREAK_PARAGRAPH_SKIP:
2161         case LFUN_PARAGRAPH_SPACING:
2162         case LFUN_INSET_INSERT:
2163         case LFUN_WORD_UPCASE:
2164         case LFUN_WORD_LOWCASE:
2165         case LFUN_WORD_CAPITALIZE:
2166         case LFUN_CHARS_TRANSPOSE:
2167         case LFUN_SERVER_GET_XY:
2168         case LFUN_SERVER_SET_XY:
2169         case LFUN_SERVER_GET_FONT:
2170         case LFUN_SERVER_GET_LAYOUT:
2171         case LFUN_LAYOUT:
2172         case LFUN_DATE_INSERT:
2173         case LFUN_SELF_INSERT:
2174         case LFUN_LINE_INSERT:
2175         case LFUN_NEWPAGE_INSERT:
2176         case LFUN_PAGEBREAK_INSERT:
2177         case LFUN_CLEARPAGE_INSERT:
2178         case LFUN_CLEARDOUBLEPAGE_INSERT:
2179         case LFUN_MATH_DISPLAY:
2180         case LFUN_MATH_IMPORT_SELECTION:
2181         case LFUN_MATH_MODE:
2182         case LFUN_MATH_MACRO:
2183         case LFUN_MATH_MATRIX:
2184         case LFUN_MATH_DELIM:
2185         case LFUN_MATH_BIGDELIM:
2186         case LFUN_MATH_INSERT:
2187         case LFUN_MATH_SUBSCRIPT:
2188         case LFUN_MATH_SUPERSCRIPT:
2189         case LFUN_FONT_DEFAULT:
2190         case LFUN_FONT_UNDERLINE:
2191         case LFUN_FONT_SIZE:
2192         case LFUN_LANGUAGE:
2193         case LFUN_FONT_FREE_APPLY:
2194         case LFUN_FONT_FREE_UPDATE:
2195         case LFUN_LAYOUT_PARAGRAPH:
2196         case LFUN_PARAGRAPH_UPDATE:
2197         case LFUN_ACCENT_UMLAUT:
2198         case LFUN_ACCENT_CIRCUMFLEX:
2199         case LFUN_ACCENT_GRAVE:
2200         case LFUN_ACCENT_ACUTE:
2201         case LFUN_ACCENT_TILDE:
2202         case LFUN_ACCENT_CEDILLA:
2203         case LFUN_ACCENT_MACRON:
2204         case LFUN_ACCENT_DOT:
2205         case LFUN_ACCENT_UNDERDOT:
2206         case LFUN_ACCENT_UNDERBAR:
2207         case LFUN_ACCENT_CARON:
2208         case LFUN_ACCENT_SPECIAL_CARON:
2209         case LFUN_ACCENT_BREVE:
2210         case LFUN_ACCENT_TIE:
2211         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2212         case LFUN_ACCENT_CIRCLE:
2213         case LFUN_ACCENT_OGONEK:
2214         case LFUN_THESAURUS_ENTRY:
2215         case LFUN_PARAGRAPH_PARAMS_APPLY:
2216         case LFUN_PARAGRAPH_PARAMS:
2217         case LFUN_ESCAPE:
2218         case LFUN_BUFFER_END:
2219         case LFUN_BUFFER_BEGIN:
2220         case LFUN_BUFFER_BEGIN_SELECT:
2221         case LFUN_BUFFER_END_SELECT:
2222         case LFUN_UNICODE_INSERT:
2223                 // these are handled in our dispatch()
2224                 enable = true;
2225                 break;
2226
2227         default:
2228                 return false;
2229         }
2230
2231         if (code != NO_CODE
2232             && (cur.empty() || !cur.inset().insetAllowed(code)))
2233                 enable = false;
2234
2235         flag.enabled(enable);
2236         return true;
2237 }
2238
2239
2240 void Text::pasteString(Cursor & cur, docstring const & clip,
2241                 bool asParagraphs)
2242 {
2243         cur.clearSelection();
2244         if (!clip.empty()) {
2245                 cur.recordUndo();
2246                 if (asParagraphs)
2247                         insertStringAsParagraphs(cur, clip);
2248                 else
2249                         insertStringAsLines(cur, clip);
2250         }
2251 }
2252
2253 } // namespace lyx