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