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