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