]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
Some more small fixes. Hopefully we'll get there soon!
[lyx.git] / src / BufferView_pimpl.C
1 #include <config.h>
2
3 #include <ctime>
4 #include <unistd.h>
5 #include <sys/wait.h>
6 #include <locale.h>
7
8 #ifdef __GNUG__
9 #pragma implementation
10 #endif
11
12 #include "BufferView_pimpl.h"
13 #include "WorkArea.h"
14 #include "lyxscreen.h"
15 #include "lyxtext.h"
16 #include "lyxrow.h"
17 #include "LyXView.h"
18 #include "commandtags.h"
19 #include "lyxfunc.h"
20 #include "debug.h"
21 #include "font.h"
22 #include "bufferview_funcs.h"
23 #include "TextCache.h"
24 #include "bufferlist.h"
25 #include "lyx_gui_misc.h"
26 #include "lyxrc.h"
27 #include "intl.h"
28 #include "support/LAssert.h"
29 #include "support/lstrings.h"
30 #include "frontends/Dialogs.h"
31 #include "insets/insetbib.h"
32 #include "insets/insettext.h"
33 /// added for Dispatch functions
34 #include "lyx_cb.h"
35 #include "frontends/FileDialog.h"
36 #include "lyx_main.h"
37 #include "FloatList.h"
38 #include "support/filetools.h"
39 #include "support/lyxfunctional.h"
40 #include "insets/inseturl.h"
41 #include "insets/insetlatexaccent.h"
42 #include "insets/insettoc.h"
43 #include "insets/insetref.h"
44 #include "insets/insetparent.h"
45 #include "insets/insetindex.h"
46 #include "insets/insetnote.h"
47 #include "insets/insetinclude.h"
48 #include "insets/insetcite.h"
49 #include "insets/insetert.h"
50 #include "insets/insetexternal.h"
51 #include "insets/insetgraphics.h"
52 #include "insets/insetfoot.h"
53 #include "insets/insetmarginal.h"
54 #include "insets/insetminipage.h"
55 #include "insets/insetfloat.h"
56 #include "insets/insettabular.h"
57 #if 0
58 #include "insets/insettheorem.h"
59 #include "insets/insetlist.h"
60 #endif
61 #include "insets/insetcaption.h"
62 #include "insets/insetfloatlist.h"
63 #include "insets/insetspecialchar.h"
64 #include "gettext.h"
65 #include "ParagraphParameters.h"
66 #include "undo_funcs.h"
67 #include "mathed/formulabase.h"
68
69 extern LyXTextClass::size_type current_layout;
70
71 using std::vector;
72 using std::find_if;
73 using std::find;
74 using std::pair;
75 using std::endl;
76 using std::make_pair;
77 using std::min;
78 using SigC::slot;
79
80 /* the selection possible is needed, that only motion events are 
81  * used, where the bottom press event was on the drawing area too */
82 bool selection_possible = false;
83
84 extern BufferList bufferlist;
85 extern char ascii_type;
86
87 extern void sigchldchecker(pid_t pid, int * status);
88 extern int bibitemMaxWidth(BufferView *, LyXFont const &);
89
90
91 namespace {
92
93 const unsigned int saved_positions_num = 20;
94
95 inline
96 void waitForX()
97 {
98         XSync(fl_get_display(), 0);
99 }
100
101
102 void SetXtermCursor(Window win)
103 {
104         static Cursor cursor;
105         static bool cursor_undefined = true;
106         if (cursor_undefined){
107                 cursor = XCreateFontCursor(fl_get_display(), XC_xterm);
108                 XFlush(fl_get_display());
109                 cursor_undefined = false;
110         }
111         XDefineCursor(fl_get_display(), win, cursor);
112         XFlush(fl_get_display());
113 }
114
115 } // anon namespace
116
117
118 BufferView::Pimpl::Pimpl(BufferView * b, LyXView * o,
119              int xpos, int ypos, int width, int height)
120         : bv_(b), owner_(o), buffer_(0),
121           current_scrollbar_value(0), cursor_timeout(400),
122           workarea_(xpos, ypos, width, height), using_xterm_cursor(false),
123           inset_slept(false)
124 {
125         // Setup the signals
126         workarea_.scrollCB.connect(slot(this, &BufferView::Pimpl::scrollCB));
127         workarea_.workAreaExpose
128                 .connect(slot(this, &BufferView::Pimpl::workAreaExpose));
129         workarea_.workAreaEnter
130                 .connect(slot(this, &BufferView::Pimpl::enterView));
131         workarea_.workAreaLeave
132                 .connect(slot(this, &BufferView::Pimpl::leaveView));
133         workarea_.workAreaButtonPress
134                 .connect(slot(this, &BufferView::Pimpl::workAreaButtonPress));
135         workarea_.workAreaButtonRelease
136                 .connect(slot(this,
137                               &BufferView::Pimpl::workAreaButtonRelease));
138         workarea_.workAreaMotionNotify
139                 .connect(slot(this, &BufferView::Pimpl::workAreaMotionNotify));
140         workarea_.workAreaDoubleClick
141                 .connect(slot(this, &BufferView::Pimpl::doubleClick));
142         workarea_.workAreaTripleClick
143                 .connect(slot(this, &BufferView::Pimpl::tripleClick));
144         workarea_.workAreaKeyPress
145                 .connect(slot(this, &BufferView::Pimpl::workAreaKeyPress));
146         
147         cursor_timeout.timeout.connect(slot(this,
148                                             &BufferView::Pimpl::cursorToggle));
149         cursor_timeout.start();
150         workarea_.setFocus();
151         saved_positions.resize(saved_positions_num);
152 }
153
154
155 Painter & BufferView::Pimpl::painter() 
156 {
157         return workarea_.getPainter();
158 }
159
160
161 void BufferView::Pimpl::buffer(Buffer * b)
162 {
163         lyxerr[Debug::INFO] << "Setting buffer in BufferView ("
164                             << b << ")" << endl;
165         if (buffer_) {
166                 insetSleep();
167                 buffer_->delUser(bv_);
168
169                 // Put the old text into the TextCache, but
170                 // only if the buffer is still loaded.
171                 // Also set the owner of the test to 0
172                 //              bv_->text->owner(0);
173                 textcache.add(buffer_, workarea_.workWidth(), bv_->text);
174                 if (lyxerr.debugging())
175                         textcache.show(lyxerr, "BufferView::buffer");
176                 
177                 bv_->text = 0;
178         }
179
180         // Set current buffer
181         buffer_ = b;
182
183         if (bufferlist.getState() == BufferList::CLOSING) return;
184         
185         // Nuke old image
186         // screen is always deleted when the buffer is changed.
187         screen_.reset(0);
188
189         // If we are closing the buffer, use the first buffer as current
190         if (!buffer_) {
191                 buffer_ = bufferlist.first();
192         }
193
194         if (buffer_) {
195                 lyxerr[Debug::INFO] << "Buffer addr: " << buffer_ << endl;
196                 buffer_->addUser(bv_);
197                 // If we don't have a text object for this, we make one
198                 if (bv_->text == 0) {
199                         resizeCurrentBuffer();
200                 } else {
201                         updateScreen();
202                         updateScrollbar();
203                 }
204                 bv_->text->first = screen_->topCursorVisible(bv_->text);
205                 owner_->updateMenubar();
206                 owner_->updateToolbar();
207                 // Similarly, buffer-dependent dialogs should be updated or
208                 // hidden. This should go here because some dialogs (eg ToC)
209                 // require bv_->text.
210                 owner_->getDialogs()->updateBufferDependent(true);
211                 redraw();
212                 insetWakeup();
213         } else {
214                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
215                 owner_->updateMenubar();
216                 owner_->updateToolbar();
217                 owner_->getDialogs()->hideBufferDependent();
218                 updateScrollbar();
219                 workarea_.redraw();
220
221                 // Also remove all remaining text's from the testcache.
222                 // (there should not be any!) (if there is any it is a
223                 // bug!)
224                 if (lyxerr.debugging())
225                         textcache.show(lyxerr, "buffer delete all");
226                 textcache.clear();
227         }
228         // should update layoutchoice even if we don't have a buffer.
229         owner_->updateLayoutChoice();
230
231         owner_->updateWindowTitle();
232 }
233
234
235 void BufferView::Pimpl::resize(int xpos, int ypos, int width, int height)
236 {
237         workarea_.resize(xpos, ypos, width, height);
238         update(bv_->text, SELECT);
239         redraw();
240 }
241
242
243 void BufferView::Pimpl::resize()
244 {
245         if (buffer_)
246                 resizeCurrentBuffer();
247 }
248
249
250 void BufferView::Pimpl::redraw()
251 {
252         lyxerr[Debug::INFO] << "BufferView::redraw()" << endl;
253         workarea_.redraw();
254 }
255
256
257 bool BufferView::Pimpl::fitCursor()
258 {
259         lyx::Assert(screen_.get());
260
261         bool ret;
262
263         if (bv_->theLockingInset()) {
264                 bv_->theLockingInset()->fitInsetCursor(bv_);
265                 ret = true;
266         } else {
267                 ret = screen_->fitCursor(bv_->text, bv_);
268         }
269
270         bv_->owner()->getDialogs()->updateParagraph();
271         if (ret)
272             updateScrollbar();
273         return ret;
274 }
275
276
277 void BufferView::Pimpl::redoCurrentBuffer()
278 {
279         lyxerr[Debug::INFO] << "BufferView::redoCurrentBuffer" << endl;
280         if (buffer_ && bv_->text) {
281                 resize();
282                 owner_->updateLayoutChoice();
283         }
284 }
285
286
287 int BufferView::Pimpl::resizeCurrentBuffer()
288 {
289         lyxerr[Debug::INFO] << "resizeCurrentBuffer" << endl;
290         
291         Paragraph * par = 0;
292         Paragraph * selstartpar = 0;
293         Paragraph * selendpar = 0;
294         UpdatableInset * the_locking_inset = 0;
295         
296         Paragraph::size_type pos = 0;
297         Paragraph::size_type selstartpos = 0;
298         Paragraph::size_type selendpos = 0;
299         bool selection = false;
300         bool mark_set  = false;
301
302         owner_->prohibitInput();
303
304         owner_->message(_("Formatting document..."));
305
306         if (bv_->text) {
307                 par = bv_->text->cursor.par();
308                 pos = bv_->text->cursor.pos();
309                 selstartpar = bv_->text->selection.start.par();
310                 selstartpos = bv_->text->selection.start.pos();
311                 selendpar = bv_->text->selection.end.par();
312                 selendpos = bv_->text->selection.end.pos();
313                 selection = bv_->text->selection.set();
314                 mark_set = bv_->text->selection.mark();
315                 the_locking_inset = bv_->theLockingInset();
316                 delete bv_->text;
317                 bv_->text = new LyXText(bv_);
318                 bv_->text->init(bv_);
319         } else {
320                 // See if we have a text in TextCache that fits
321                 // the new buffer_ with the correct width.
322                 bv_->text = textcache.findFit(buffer_, workarea_.workWidth());
323                 if (bv_->text) {
324                         if (lyxerr.debugging()) {
325                                 lyxerr << "Found a LyXText that fits:\n";
326                                 textcache.show(lyxerr, make_pair(buffer_, make_pair(workarea_.workWidth(), bv_->text)));
327                         }
328                         // Set the owner of the newly found text
329                         //      bv_->text->owner(bv_);
330                         if (lyxerr.debugging())
331                                 textcache.show(lyxerr, "resizeCurrentBuffer");
332                 } else {
333                         bv_->text = new LyXText(bv_);
334                         bv_->text->init(bv_);
335                 }
336         }
337         updateScreen();
338
339         if (par) {
340                 bv_->text->selection.set(true);
341                 /* at this point just to avoid the Delete-Empty-Paragraph
342                  * Mechanism when setting the cursor */
343                 bv_->text->selection.mark(mark_set);
344                 if (selection) {
345                         bv_->text->setCursor(bv_, selstartpar, selstartpos);
346                         bv_->text->selection.cursor = bv_->text->cursor;
347                         bv_->text->setCursor(bv_, selendpar, selendpos);
348                         bv_->text->setSelection(bv_);
349                         bv_->text->setCursor(bv_, par, pos);
350                 } else {
351                         bv_->text->setCursor(bv_, par, pos);
352                         bv_->text->selection.cursor = bv_->text->cursor;
353                         bv_->text->selection.set(false);
354                 }
355                 // remake the inset locking
356                 bv_->theLockingInset(the_locking_inset);
357         }
358         bv_->text->first = screen_->topCursorVisible(bv_->text);
359         buffer_->resizeInsets(bv_);
360         // this will scroll the screen such that the cursor becomes visible
361         updateScrollbar();
362         redraw();
363
364         setState();
365         owner_->allowInput();
366
367         /// clear the "Formatting Document" message 
368         owner_->message("");
369  
370         /// get rid of the splash screen if it's not gone already
371         owner_->getDialogs()->destroySplash();
372  
373         return 0;
374 }
375
376
377 void BufferView::Pimpl::updateScreen()
378 {
379         // Regenerate the screen.
380         screen_.reset(new LyXScreen(workarea_));
381 }
382
383
384 void BufferView::Pimpl::updateScrollbar()
385 {
386         /* If the text is smaller than the working area, the scrollbar
387          * maximum must be the working area height. No scrolling will 
388          * be possible */
389         if (!bv_->text) {
390                 workarea_.setScrollbar(0, 1.0);
391                 return;
392         }
393
394         long const text_height = bv_->text->height;
395
396         double const lineh = bv_->text->defaultHeight();
397         double const slider_size =
398                 (text_height == 0) ? 1.0 : 1.0 / double(text_height);
399
400         static long old_text_height = 0;
401         static double old_lineh = 0;
402         static double old_slider_size = 0;
403
404         if (text_height != old_text_height) {
405                 workarea_.setScrollbarBounds(0, text_height - workarea_.height());
406                 old_text_height = text_height;
407         }
408         if (lineh != old_lineh) {
409                 workarea_.setScrollbarIncrements(lineh);
410                 old_lineh = lineh;
411         }
412         if (current_scrollbar_value != bv_->text->first
413             || slider_size != old_slider_size) {
414                 current_scrollbar_value = bv_->text->first;
415                 workarea_.setScrollbar(current_scrollbar_value, slider_size);
416                 old_slider_size = slider_size;
417         }
418 }
419
420
421 // Callback for scrollbar slider
422 void BufferView::Pimpl::scrollCB(double value)
423 {
424         if (!buffer_) return;
425
426         current_scrollbar_value = long(value);
427         if (current_scrollbar_value < 0)
428                 current_scrollbar_value = 0;
429    
430         if (!screen_.get())
431                 return;
432
433         screen_->draw(bv_->text, bv_, current_scrollbar_value);
434
435         if (!lyxrc.cursor_follows_scrollbar) {
436                 waitForX();
437                 return;
438         }
439  
440         LyXText * vbt = bv_->text;
441  
442         int const height = vbt->defaultHeight();
443         int const first = static_cast<int>((bv_->text->first + height));
444         int const last = static_cast<int>((bv_->text->first + workarea_.height() - height));
445
446         if (vbt->cursor.y() < first)
447                 vbt->setCursorFromCoordinates(bv_, 0, first);
448         else if (vbt->cursor.y() > last)
449                 vbt->setCursorFromCoordinates(bv_, 0, last);
450
451         waitForX();
452 }
453
454
455 int BufferView::Pimpl::scrollUp(long time)
456 {
457         if (!buffer_) return 0;
458         if (!screen_.get()) return 0;
459    
460         double value = workarea_.getScrollbarValue();
461    
462         if (value == 0) return 0;
463
464         float add_value =  (bv_->text->defaultHeight()
465                             + float(time) * float(time) * 0.125);
466    
467         if (add_value > workarea_.height())
468                 add_value = float(workarea_.height() -
469                                   bv_->text->defaultHeight());
470    
471         value -= add_value;
472
473         if (value < 0)
474                 value = 0;
475    
476         workarea_.setScrollbarValue(value);
477    
478         scrollCB(value); 
479         return 0;
480 }
481
482
483 int BufferView::Pimpl::scrollDown(long time)
484 {
485         if (!buffer_) return 0;
486         if (!screen_.get()) return 0;
487    
488         double value = workarea_.getScrollbarValue();
489         pair<float, float> p = workarea_.getScrollbarBounds();
490         double const max = p.second;
491         
492         if (value == max) return 0;
493
494         float add_value =  (bv_->text->defaultHeight()
495                             + float(time) * float(time) * 0.125);
496    
497         if (add_value > workarea_.height())
498                 add_value = float(workarea_.height() -
499                                   bv_->text->defaultHeight());
500    
501         value += add_value;
502    
503         if (value > max)
504                 value = max;
505
506         workarea_.setScrollbarValue(value);
507         
508         scrollCB(value); 
509         return 0;
510 }
511
512
513 void BufferView::Pimpl::workAreaKeyPress(KeySym keysym, unsigned int state)
514 {
515         bv_->owner()->getLyXFunc()->processKeySym(keysym, state);
516 }
517
518
519 void BufferView::Pimpl::workAreaMotionNotify(int x, int y, unsigned int state)
520 {
521         // Only use motion with button 1
522         if (!(state & Button1MotionMask))
523                 return;
524
525         if (!buffer_ || !screen_.get()) return;
526
527         // Check for inset locking
528         if (bv_->theLockingInset()) {
529                 LyXCursor cursor = bv_->text->cursor;
530                 LyXFont font = bv_->text->getFont(buffer_,
531                                                   cursor.par(), cursor.pos());
532                 int width = bv_->theLockingInset()->width(bv_, font);
533                 int inset_x = font.isVisibleRightToLeft()
534                         ? cursor.x() - width : cursor.x();
535                 int start_x = inset_x + bv_->theLockingInset()->scroll();
536                 bv_->theLockingInset()->
537                         insetMotionNotify(bv_,
538                                           x - start_x,
539                                           y - cursor.y() + bv_->text->first,
540                                           state);
541                 return;
542         }
543    
544         /* The test for not selection possible is needed, that only motion
545            events are used, where the bottom press event was on
546            the drawing area too */
547         if (!selection_possible)
548                 return;
549  
550         screen_->hideCursor();
551
552         bv_->text->setCursorFromCoordinates(bv_, x, y + bv_->text->first);
553       
554         if (!bv_->text->selection.set())
555                 update(bv_->text, BufferView::UPDATE); // Maybe an empty line was deleted
556       
557         bv_->text->setSelection(bv_);
558         screen_->toggleToggle(bv_->text, bv_);
559         fitCursor();
560 #if 0
561         screen_->showCursor(bv_->text, bv_);
562 #else
563         showCursor();
564 #endif
565 }
566
567
568 // Single-click on work area
569 void BufferView::Pimpl::workAreaButtonPress(int xpos, int ypos,
570                                             unsigned int button)
571 {
572         if (!buffer_ || !screen_.get()) return;
573
574         Inset * inset_hit = checkInsetHit(bv_->text, xpos, ypos, button);
575
576         // ok ok, this is a hack.
577         if (button == 4 || button == 5) {
578                 switch (button) {
579                 case 4:
580                         scrollUp(lyxrc.wheel_jump); // default 100, set in lyxrc
581                         break;
582                 case 5:
583                         scrollDown(lyxrc.wheel_jump);
584                         break;
585                 }
586         }
587         
588         if (bv_->theLockingInset()) {
589                 // We are in inset locking mode
590                 
591                 /* Check whether the inset was hit. If not reset mode,
592                    otherwise give the event to the inset */
593                 if (inset_hit == bv_->theLockingInset()) {
594                         bv_->theLockingInset()->
595                                 insetButtonPress(bv_,
596                                                  xpos, ypos,
597                                                  button);
598                         return;
599                 } else {
600                         bv_->unlockInset(bv_->theLockingInset());
601                 }
602         }
603         
604         if (!inset_hit)
605                 selection_possible = true;
606         screen_->hideCursor();
607
608         int const screen_first = bv_->text->first;
609         
610         // Middle button press pastes if we have a selection
611         bool paste_internally = false;
612         if (button == 2
613             && bv_->text->selection.set()) {
614                 owner_->getLyXFunc()->dispatch(LFUN_COPY);
615                 paste_internally = true;
616         }
617         
618         // Clear the selection
619         screen_->toggleSelection(bv_->text, bv_);
620         bv_->text->clearSelection();
621         bv_->text->fullRebreak(bv_);
622 #if 0
623         screen_->update(bv_->text, bv_);
624 #else
625         update();
626 #endif
627         updateScrollbar();
628         
629         // Single left click in math inset?
630         if ((inset_hit != 0) &&
631             (inset_hit->editable()==Inset::HIGHLY_EDITABLE)) {
632                 // Highly editable inset, like math
633                 UpdatableInset * inset = static_cast<UpdatableInset *>(inset_hit);
634                 selection_possible = false;
635                 owner_->updateLayoutChoice();
636                 owner_->message(inset->editMessage());
637                 inset->insetButtonPress(bv_, xpos, ypos, button);
638                 inset->edit(bv_, xpos, ypos, button);
639                 return;
640         } 
641         
642         // Right click on a footnote flag opens float menu
643         if (button == 3) { 
644                 selection_possible = false;
645                 return;
646         }
647         
648         if (!inset_hit) // otherwise it was already set in checkInsetHit(...)
649                 bv_->text->setCursorFromCoordinates(bv_, xpos, ypos + screen_first);
650         finishUndo();
651         bv_->text->selection.cursor = bv_->text->cursor;
652         bv_->text->cursor.x_fix(bv_->text->cursor.x());
653         
654         owner_->updateLayoutChoice();
655         if (fitCursor()) {
656                 selection_possible = false;
657         }
658         
659         // Insert primary selection with middle mouse
660         // if there is a local selection in the current buffer,
661         // insert this
662         if (button == 2) {
663                 if (paste_internally)
664                         owner_->getLyXFunc()->dispatch(LFUN_PASTE);
665                 else
666                         owner_->getLyXFunc()->dispatch(LFUN_PASTESELECTION,
667                                                        "paragraph");
668                 selection_possible = false;
669                 return;
670         }
671 }
672
673
674 void BufferView::Pimpl::doubleClick(int /*x*/, int /*y*/, unsigned int button) 
675 {
676         // select a word
677         if (!buffer_)
678             return;
679
680         LyXText * text = bv_->getLyXText();
681
682         if (text->bv_owner && bv_->theLockingInset())
683             return;
684
685         if (screen_.get() && button == 1) {
686             if (text->bv_owner) {
687                 screen_->hideCursor();
688                 screen_->toggleSelection(text, bv_);
689                 text->selectWord(bv_, LyXText::WHOLE_WORD_STRICT);
690                 screen_->toggleSelection(text, bv_, false);
691             } else {
692                 text->selectWord(bv_, LyXText::WHOLE_WORD_STRICT);
693             }
694             /* This will fit the cursor on the screen
695              * if necessary */
696             update(text, BufferView::SELECT|BufferView::FITCUR);
697         }
698 }
699
700
701 void BufferView::Pimpl::tripleClick(int /*x*/, int /*y*/, unsigned int button)
702 {
703         // select a line
704         if (buffer_)
705                 return;
706
707         LyXText * text = bv_->getLyXText();
708
709         if (text->bv_owner && bv_->theLockingInset())
710             return;
711
712         if (screen_.get() && (button == 1)) {
713                 screen_->hideCursor();
714                 screen_->toggleSelection(text, bv_);
715                 text->cursorHome(bv_);
716                 text->selection.cursor = text->cursor;
717                 text->cursorEnd(bv_);
718                 text->setSelection(bv_);
719                 screen_->toggleSelection(text, bv_, false);
720                 /* This will fit the cursor on the screen
721                  * if necessary */
722                 update(text, BufferView::SELECT|BufferView::FITCUR);
723         }
724 }
725
726
727 void BufferView::Pimpl::enterView()
728 {
729         if (active() && available()) {
730                 SetXtermCursor(workarea_.getWin());
731                 using_xterm_cursor = true;
732         }
733 }
734
735
736 void BufferView::Pimpl::leaveView()
737 {
738         if (using_xterm_cursor) {
739                 XUndefineCursor(fl_get_display(), workarea_.getWin());
740                 using_xterm_cursor = false;
741         }
742 }
743
744
745 void BufferView::Pimpl::workAreaButtonRelease(int x, int y,
746                                               unsigned int button)
747 {
748         if (!buffer_ || !screen_.get()) return;
749
750         // If we hit an inset, we have the inset coordinates in these
751         // and inset_hit points to the inset.  If we do not hit an
752         // inset, inset_hit is 0, and inset_x == x, inset_y == y.
753         Inset * inset_hit = checkInsetHit(bv_->text, x, y, button);
754
755         if (bv_->theLockingInset()) {
756                 // We are in inset locking mode.
757
758                 /* LyX does a kind of work-area grabbing for insets.
759                    Only a ButtonPress Event outside the inset will 
760                    force a insetUnlock. */
761                 bv_->theLockingInset()->
762                         insetButtonRelease(bv_, x, y, button);
763                 return;
764         }
765         
766         selection_possible = false;
767         
768         if (button == 2)
769                 return;
770
771         setState();
772         owner_->showState();
773
774         // Did we hit an editable inset?
775         if (inset_hit) {
776                 // Inset like error, notes and figures
777                 selection_possible = false;
778
779                 // CHECK fix this proper in 0.13
780
781                 // Following a ref shouldn't issue
782                 // a push on the undo-stack
783                 // anylonger, now that we have
784                 // keybindings for following
785                 // references and returning from
786                 // references.  IMHO though, it
787                 // should be the inset's own business
788                 // to push or not push on the undo
789                 // stack. They don't *have* to
790                 // alter the document...
791                 // (Joacim)
792                 // ...or maybe the SetCursorParUndo()
793                 // below isn't necessary at all anylonger?
794                 if (inset_hit->lyxCode() == Inset::REF_CODE) {
795                         setCursorParUndo(bv_);
796                 }
797
798                 owner_->message(inset_hit->editMessage());
799
800                 if (inset_hit->editable()==Inset::HIGHLY_EDITABLE) {
801                         // Highly editable inset, like math
802                         UpdatableInset *inset = (UpdatableInset *)inset_hit;
803                         inset->insetButtonRelease(bv_, x, y, button);
804                 } else {
805                         inset_hit->insetButtonRelease(bv_, x, y, button);
806                         inset_hit->edit(bv_, x, y, button);
807                 }
808                 return;
809         }
810
811         // check whether we want to open a float
812         if (bv_->text) {
813                 bool hit = false;
814                 char c = ' ';
815                 if (bv_->text->cursor.pos() <
816                     bv_->text->cursor.par()->size()) {
817                         c = bv_->text->cursor.par()->
818                                 getChar(bv_->text->cursor.pos());
819                 }
820                         if (bv_->text->cursor.pos() - 1 >= 0) {
821                         c = bv_->text->cursor.par()->
822                                 getChar(bv_->text->cursor.pos() - 1);
823                 }
824                 if (hit == true) {
825                         selection_possible = false;
826                         return;
827                 }
828         }
829
830         // Maybe we want to edit a bibitem ale970302
831         if (bv_->text->cursor.par()->bibkey && x < 20 + 
832             bibitemMaxWidth(bv_, textclasslist.
833                             TextClass(buffer_->
834                                       params.textclass).defaultfont())) {
835                 bv_->text->cursor.par()->bibkey->edit(bv_, 0, 0, 0);
836         }
837
838         return;
839 }
840
841
842 /* 
843  * Returns an inset if inset was hit. 0 otherwise.
844  * If hit, the coordinates are changed relative to the inset. 
845  * Otherwise coordinates are not changed, and false is returned.
846  */
847 Inset * BufferView::Pimpl::checkInsetHit(LyXText * text, int & x, int & y,
848                                          unsigned int /* button */)
849 {
850         if (!screen_.get())
851                 return 0;
852   
853         int y_tmp = y + text->first;
854   
855         LyXCursor cursor;
856         text->setCursorFromCoordinates(bv_, cursor, x, y_tmp);
857         text->setCursor(bv_, cursor, cursor.par(),cursor.pos(),true);
858
859
860         if (cursor.pos() < cursor.par()->size()
861             && cursor.par()->getChar(cursor.pos()) == Paragraph::META_INSET
862             && cursor.par()->getInset(cursor.pos())
863             && cursor.par()->getInset(cursor.pos())->editable()) {
864
865                 // Check whether the inset really was hit
866                 Inset * tmpinset = cursor.par()->getInset(cursor.pos());
867                 LyXFont font = text->getFont(buffer_,
868                                                   cursor.par(), cursor.pos());
869                 int const width = tmpinset->width(bv_, font);
870                 int const inset_x = font.isVisibleRightToLeft()
871                         ? cursor.x() - width : cursor.x();
872                 int const start_x = inset_x + tmpinset->scroll();
873                 int const end_x = inset_x + width;
874
875                 if (x > start_x && x < end_x
876                     && y_tmp > cursor.y() - tmpinset->ascent(bv_, font)
877                     && y_tmp < cursor.y() + tmpinset->descent(bv_, font)) {
878                         text->setCursor(bv_, cursor.par(),cursor.pos(), true);
879                         x = x - start_x;
880                         // The origin of an inset is on the baseline
881                         y = y_tmp - (text->cursor.y()); 
882                         return tmpinset;
883                 }
884         }
885
886         if ((cursor.pos() - 1 >= 0) &&
887             (cursor.par()->getChar(cursor.pos()-1) == Paragraph::META_INSET) &&
888             (cursor.par()->getInset(cursor.pos() - 1)) &&
889             (cursor.par()->getInset(cursor.pos() - 1)->editable())) {
890                 Inset * tmpinset = cursor.par()->getInset(cursor.pos()-1);
891                 LyXFont font = text->getFont(buffer_, cursor.par(),
892                                                   cursor.pos()-1);
893                 int const width = tmpinset->width(bv_, font);
894                 int const inset_x = font.isVisibleRightToLeft()
895                         ? cursor.x() : cursor.x() - width;
896                 int const start_x = inset_x + tmpinset->scroll();
897                 int const end_x = inset_x + width;
898
899                 if (x > start_x && x < end_x
900                     && y_tmp > cursor.y() - tmpinset->ascent(bv_, font)
901                     && y_tmp < cursor.y() + tmpinset->descent(bv_, font)) {
902 #if 0
903                         if (move_cursor && (tmpinset != bv_->theLockingInset()))
904 #endif
905                                 text->setCursor(bv_, cursor.par(),
906                                                 cursor.pos() - 1, true);
907                         x = x - start_x;
908                         // The origin of an inset is on the baseline
909                         y = y_tmp - (text->cursor.y()); 
910                         return tmpinset;
911                 }
912         }
913         return 0;
914 }
915
916
917 void BufferView::Pimpl::workAreaExpose()
918 {
919         static int work_area_width;
920         static unsigned int work_area_height;
921
922         bool const widthChange = workarea_.workWidth() != work_area_width;
923         bool const heightChange = workarea_.height() != work_area_height;
924
925         // update from work area
926         work_area_width = workarea_.workWidth();
927         work_area_height = workarea_.height();
928         if (buffer_ != 0) {
929                 if (widthChange) {
930                         // The visible LyXView need a resize
931                         owner_->resize();
932
933                         // Remove all texts from the textcache
934                         // This is not _really_ what we want to do. What
935                         // we really want to do is to delete in textcache
936                         // that does not have a BufferView with matching
937                         // width, but as long as we have only one BufferView
938                         // deleting all gives the same result.
939                         if (lyxerr.debugging())
940                                 textcache.show(lyxerr, "Expose delete all");
941                         textcache.clear();
942                 } else if (heightChange) {
943                         // Rebuild image of current screen
944                         updateScreen();
945                         // fitCursor() ensures we don't jump back
946                         // to the start of the document on vertical
947                         // resize
948                         fitCursor();
949
950                         // The main window size has changed, repaint most stuff
951                         redraw();
952                 } else if (screen_.get())
953                     screen_->redraw(bv_->text, bv_);
954         } else {
955                 // Grey box when we don't have a buffer
956                 workarea_.greyOut();
957         }
958
959         // always make sure that the scrollbar is sane.
960         updateScrollbar();
961         owner_->updateLayoutChoice();
962         return;
963 }
964
965
966 void BufferView::Pimpl::update()
967 {
968         if (screen_.get() &&
969                 (!bv_->theLockingInset() || !bv_->theLockingInset()->nodraw()))
970         {
971                 LyXText::text_status st = bv_->text->status();
972                 screen_->update(bv_->text, bv_);
973                 bool fitc = false;
974                 while(bv_->text->status() == LyXText::CHANGED_IN_DRAW) {
975                         if (bv_->text->fullRebreak(bv_)) {
976                                 st = LyXText::NEED_MORE_REFRESH;
977                                 bv_->text->setCursor(bv_, bv_->text->cursor.par(),
978                                                                          bv_->text->cursor.pos());
979                                 fitc = true;
980                         }
981                         bv_->text->status(bv_, st);
982                         screen_->update(bv_->text, bv_);
983                 }
984                 // do this here instead of in the screen::update because of
985                 // the above loop!
986                 bv_->text->status(bv_, LyXText::UNCHANGED);
987                 if (fitc)
988                         fitCursor();
989         }
990 }
991
992 // Values used when calling update:
993 // -3 - update
994 // -2 - update, move sel_cursor if selection, fitcursor
995 // -1 - update, move sel_cursor if selection, fitcursor, mark dirty
996 //  0 - update, move sel_cursor if selection, fitcursor 
997 //  1 - update, move sel_cursor if selection, fitcursor, mark dirty
998 //  3 - update, move sel_cursor if selection
999 //
1000 // update -
1001 // a simple redraw of the parts that need refresh
1002 //
1003 // move sel_cursor if selection -
1004 // the text's sel_cursor is moved if there is selection is progress
1005 //
1006 // fitcursor -
1007 // fitCursor() is called and the scrollbar updated
1008 //
1009 // mark dirty -
1010 // the buffer is marked dirty.
1011 //
1012 // enum {
1013 //       UPDATE = 0,
1014 //       SELECT = 1,
1015 //       FITCUR = 2,
1016 //       CHANGE = 4 
1017 // };
1018 //
1019 // UPDATE_ONLY = UPDATE;
1020 // UPDATE_SELECT = UPDATE | SELECT;
1021 // UPDATE_SELECT_MOVE = UPDATE | SELECT | FITCUR;
1022 // UPDATE_SELECT_MOVE_AFTER_CHANGE = UPDATE | SELECT | FITCUR | CHANGE;
1023 //
1024 // update(-3) -> update(0)         -> update(0) -> update(UPDATE)
1025 // update(-2) -> update(1 + 2)     -> update(3) -> update(SELECT|FITCUR)
1026 // update(-1) -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1027 // update(1)  -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1028 // update(3)  -> update(1)         -> update(1) -> update(SELECT)
1029
1030 void BufferView::Pimpl::update(LyXText * text, BufferView::UpdateCodes f)
1031 {
1032         owner_->updateLayoutChoice();
1033
1034         if (!text->selection.set() && (f & SELECT)) {
1035                 text->selection.cursor = text->cursor;
1036         }
1037
1038         text->fullRebreak(bv_);
1039
1040         if (text->inset_owner) {
1041                 text->inset_owner->setUpdateStatus(bv_, InsetText::NONE);
1042             updateInset(text->inset_owner, true);
1043         } else {
1044             update();
1045         }
1046                 
1047         if ((f & FITCUR)) {
1048                 fitCursor();
1049         }
1050
1051         if ((f & CHANGE)) {
1052                 buffer_->markDirty();
1053         }
1054 }
1055
1056
1057 // Callback for cursor timer
1058 void BufferView::Pimpl::cursorToggle()
1059 {
1060         // Quite a nice place for asyncron Inset updating, isn't it?
1061         // Actually no! This is run even if no buffer exist... so (Lgb)
1062         if (!buffer_) {
1063                 cursor_timeout.restart();
1064                 return;
1065         }
1066  
1067         int status = 1;
1068         int const pid = waitpid(static_cast<pid_t>(0), &status, WNOHANG);
1069         if (pid == -1) // error find out what is wrong
1070                 ; // ignore it for now.
1071         else if (pid > 0)
1072                 sigchldchecker(pid, &status);
1073
1074         updatelist.update(bv_);
1075         
1076         if (!screen_.get()) {
1077                 cursor_timeout.restart();
1078                 return;
1079         }
1080
1081         if (!bv_->theLockingInset()) {
1082                 screen_->cursorToggle(bv_);
1083         } else {
1084                 bv_->theLockingInset()->toggleInsetCursor(bv_);
1085         }
1086         
1087         cursor_timeout.restart();
1088 }
1089
1090
1091 void BufferView::Pimpl::cursorPrevious(LyXText * text)
1092 {
1093         if (!text->cursor.row()->previous())
1094                 return;
1095         
1096         int y = text->first;
1097         if (text->inset_owner)
1098                 y += bv_->text->first;
1099         Row * cursorrow = text->cursor.row();
1100         text->setCursorFromCoordinates(bv_, bv_->text->cursor.x_fix(), y);
1101         finishUndo();
1102         // This is to allow jumping over large insets
1103         if ((cursorrow == text->cursor.row()))
1104                 text->cursorUp(bv_);
1105         
1106         if (text->inset_owner ||
1107             text->cursor.row()->height() < workarea_.height())
1108                 screen_->draw(bv_->text, bv_,
1109                               text->cursor.y()
1110                               - text->cursor.row()->baseline()
1111                               + text->cursor.row()->height()
1112                               - workarea_.height() + 1 );
1113         updateScrollbar();
1114 }
1115
1116
1117 void BufferView::Pimpl::cursorNext(LyXText * text)
1118 {
1119         if (!text->cursor.row()->next())
1120                 return;
1121         
1122         int y = text->first + workarea_.height();
1123 //      if (text->inset_owner)
1124 //              y += bv_->text->first;
1125         text->getRowNearY(y);
1126     
1127         Row * cursorrow = text->cursor.row();
1128         text->setCursorFromCoordinates(bv_, text->cursor.x_fix(), y); // + workarea_->height());
1129         finishUndo();
1130         // This is to allow jumping over large insets
1131         if ((cursorrow == bv_->text->cursor.row()))
1132                 text->cursorDown(bv_);
1133         
1134         if (text->inset_owner ||
1135             text->cursor.row()->height() < workarea_.height())
1136                 screen_->draw(bv_->text, bv_, text->cursor.y() -
1137                               text->cursor.row()->baseline());
1138         updateScrollbar();
1139 }
1140
1141
1142 bool BufferView::Pimpl::available() const
1143 {
1144         if (buffer_ && bv_->text) return true;
1145         return false;
1146 }
1147
1148
1149 void BufferView::Pimpl::beforeChange(LyXText * text)
1150 {
1151         toggleSelection();
1152         text->clearSelection();
1153 }
1154
1155
1156 void BufferView::Pimpl::savePosition(unsigned int i)
1157 {
1158         if (i >= saved_positions_num)
1159                 return;
1160         saved_positions[i] = Position(buffer_->fileName(),
1161                                       bv_->text->cursor.par()->id(),
1162                                       bv_->text->cursor.pos());
1163         if (i > 0) {
1164                 ostringstream str;
1165                 str << _("Saved bookmark") << ' ' << i;
1166                 owner_->message(str.str().c_str());
1167         }
1168 }
1169
1170
1171 void BufferView::Pimpl::restorePosition(unsigned int i)
1172 {
1173         if (i >= saved_positions_num)
1174                 return;
1175
1176         string const fname = saved_positions[i].filename;
1177
1178         beforeChange(bv_->text);
1179
1180         if (fname != buffer_->fileName()) {
1181                 Buffer * b = bufferlist.exists(fname) ?
1182                         bufferlist.getBuffer(fname) :
1183                         bufferlist.loadLyXFile(fname); // don't ask, just load it
1184                 if (b != 0 ) buffer(b);
1185         }
1186
1187         Paragraph * par = buffer_->getParFromID(saved_positions[i].par_id);
1188         if (!par)
1189                 return;
1190
1191         bv_->text->setCursor(bv_, par,
1192                              min(par->size(), saved_positions[i].par_pos));
1193
1194         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1195         if (i > 0) {
1196                 ostringstream str;
1197                 str << _("Moved to bookmark") << ' ' << i;
1198                 owner_->message(str.str().c_str());
1199         }
1200 }
1201
1202
1203 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
1204 {
1205         if (i >= saved_positions_num)
1206                 return false;
1207
1208         return !saved_positions[i].filename.empty();
1209 }
1210
1211
1212 void BufferView::Pimpl::setState()
1213 {
1214         if (!lyxrc.rtl_support)
1215                 return;
1216
1217         LyXText * text = bv_->getLyXText();
1218         if (text->real_current_font.isRightToLeft()
1219 #ifndef NO_LATEX
1220             &&
1221             text->real_current_font.latex() != LyXFont::ON
1222 #endif
1223                 ) {
1224                 if (owner_->getIntl()->keymap == Intl::PRIMARY)
1225                         owner_->getIntl()->KeyMapSec();
1226         } else {
1227                 if (owner_->getIntl()->keymap == Intl::SECONDARY)
1228                         owner_->getIntl()->KeyMapPrim();
1229         }
1230 }
1231
1232
1233 void BufferView::Pimpl::insetSleep()
1234 {
1235         if (bv_->theLockingInset() && !inset_slept) {
1236                 bv_->theLockingInset()->getCursorPos(bv_, bv_->slx, bv_->sly);
1237                 bv_->theLockingInset()->insetUnlock(bv_);
1238                 inset_slept = true;
1239         }
1240 }
1241
1242
1243 void BufferView::Pimpl::insetWakeup()
1244 {
1245         if (bv_->theLockingInset() && inset_slept) {
1246                 bv_->theLockingInset()->edit(bv_, bv_->slx, bv_->sly, 0);
1247                 inset_slept = false;
1248         }
1249 }
1250
1251
1252 void BufferView::Pimpl::insetUnlock()
1253 {
1254         if (bv_->theLockingInset()) {
1255                 if (!inset_slept)
1256                         bv_->theLockingInset()->insetUnlock(bv_);
1257                 bv_->theLockingInset(0);
1258                 finishUndo();
1259                 inset_slept = false;
1260         }
1261 }
1262
1263
1264 bool BufferView::Pimpl::focus() const
1265 {
1266         return workarea_.hasFocus();
1267 }
1268
1269
1270 void BufferView::Pimpl::focus(bool f)
1271 {
1272         if (f) workarea_.setFocus();
1273 }
1274
1275
1276 bool BufferView::Pimpl::active() const
1277 {
1278         return workarea_.active();
1279 }
1280
1281
1282 bool BufferView::Pimpl::belowMouse() const 
1283 {
1284         return workarea_.belowMouse();
1285 }
1286
1287
1288 void BufferView::Pimpl::showCursor()
1289 {
1290         if (screen_.get()) {
1291                 if (bv_->theLockingInset())
1292                         bv_->theLockingInset()->showInsetCursor(bv_);
1293                 else
1294                         screen_->showCursor(bv_->text, bv_);
1295         }
1296 }
1297
1298
1299 void BufferView::Pimpl::hideCursor()
1300 {
1301         if (screen_.get()) {
1302                 if (!bv_->theLockingInset())
1303 //                      bv_->theLockingInset()->hideInsetCursor(bv_);
1304 //              else
1305                         screen_->hideCursor();
1306         }
1307 }
1308
1309
1310 void BufferView::Pimpl::toggleSelection(bool b)
1311 {
1312         if (screen_.get()) {
1313                 if (bv_->theLockingInset())
1314                         bv_->theLockingInset()->toggleSelection(bv_, b);
1315                 screen_->toggleSelection(bv_->text, bv_, b);
1316         }
1317 }
1318
1319
1320 void BufferView::Pimpl::toggleToggle()
1321 {
1322         if (screen_.get())
1323                 screen_->toggleToggle(bv_->text, bv_);
1324 }
1325
1326
1327 void BufferView::Pimpl::center() 
1328 {
1329         beforeChange(bv_->text);
1330         if (bv_->text->cursor.y() > static_cast<int>((workarea_.height() / 2))) {
1331                 screen_->draw(bv_->text, bv_, bv_->text->cursor.y() - workarea_.height() / 2);
1332         } else {
1333                 screen_->draw(bv_->text, bv_, 0);
1334         }
1335         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1336         redraw();
1337 }
1338
1339
1340 void BufferView::Pimpl::pasteClipboard(bool asPara) 
1341 {
1342         if (!buffer_) return;
1343
1344         screen_->hideCursor();
1345         beforeChange(bv_->text);
1346         
1347         string const clip(workarea_.getClipboard());
1348         
1349         if (clip.empty()) return;
1350
1351         if (asPara) {
1352                 bv_->text->insertStringAsParagraphs(bv_, clip);
1353         } else {
1354                 bv_->text->insertStringAsLines(bv_, clip);
1355         }
1356         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1357 }
1358
1359
1360 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
1361 {
1362         workarea_.putClipboard(stuff);
1363 }
1364
1365
1366 /*
1367  * Dispatch functions for actions which can be valid for BufferView->text
1368  * and/or InsetText->text!!!
1369  */
1370
1371
1372 inline
1373 void BufferView::Pimpl::moveCursorUpdate(bool selecting)
1374 {
1375         LyXText * lt = bv_->getLyXText();
1376         
1377         if (selecting || lt->selection.mark()) {
1378                 lt->setSelection(bv_);
1379                 if (lt->bv_owner)
1380                         toggleToggle();
1381         }
1382         update(lt, BufferView::SELECT|BufferView::FITCUR);
1383         showCursor();
1384         
1385         /* ---> Everytime the cursor is moved, show the current font state. */
1386         // should this too me moved out of this func?
1387         //owner->showState();
1388         setState();
1389 }
1390
1391
1392 Inset * BufferView::Pimpl::getInsetByCode(Inset::Code code)
1393 {
1394         LyXCursor cursor = bv_->getLyXText()->cursor;
1395         Buffer::inset_iterator it =
1396                 find_if(Buffer::inset_iterator(
1397                         cursor.par(), cursor.pos()),
1398                         buffer_->inset_iterator_end(),
1399                         lyx::compare_memfun(&Inset::lyxCode, code));
1400         return it != buffer_->inset_iterator_end() ? (*it) : 0;
1401 }
1402
1403
1404 void BufferView::Pimpl::MenuInsertLyXFile(string const & filen)
1405 {
1406         string filename = filen;
1407
1408         if (filename.empty()) {
1409                 // Launch a file browser
1410                 string initpath = lyxrc.document_path;
1411
1412                 if (available()) {
1413                         string const trypath = owner_->buffer()->filepath;
1414                         // If directory is writeable, use this as default.
1415                         if (IsDirWriteable(trypath))
1416                                 initpath = trypath;
1417                 }
1418
1419                 FileDialog fileDlg(bv_->owner(),
1420                                    _("Select LyX document to insert"),
1421                         LFUN_FILE_INSERT,
1422                         make_pair(string(_("Documents")),
1423                                   string(lyxrc.document_path)),
1424                         make_pair(string(_("Examples")),
1425                                   string(AddPath(system_lyxdir, "examples"))));
1426
1427                 FileDialog::Result result =
1428                         fileDlg.Select(initpath,
1429                                        _("*.lyx| LyX Documents (*.lyx)"));
1430  
1431                 if (result.first == FileDialog::Later)
1432                         return;
1433
1434                 filename = result.second;
1435
1436                 // check selected filename
1437                 if (filename.empty()) {
1438                         owner_->message(_("Canceled."));
1439                         return;
1440                 }
1441         }
1442
1443         // get absolute path of file and add ".lyx" to the filename if
1444         // necessary
1445         filename = FileSearch(string(), filename, "lyx");
1446
1447         string const disp_fn(MakeDisplayPath(filename));
1448         
1449         ostringstream s1;
1450         s1 << _("Inserting document") << ' '
1451            << disp_fn << " ...";
1452         owner_->message(s1.str().c_str());
1453         bool const res = bv_->insertLyXFile(filename);
1454         if (res) {
1455                 ostringstream str;
1456                 str << _("Document") << ' ' << disp_fn
1457                     << ' ' << _("inserted.");
1458                 owner_->message(str.str().c_str());
1459         } else {
1460                 ostringstream str;
1461                 str << _("Could not insert document") << ' '
1462                     << disp_fn;
1463                 owner_->message(str.str().c_str());
1464         }
1465 }
1466
1467
1468 bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
1469 {
1470         lyxerr[Debug::ACTION] << "BufferView::Pimpl::Dispatch: action["
1471                               << action <<"] arg[" << argument << "]" << endl;
1472         
1473         switch (action) {
1474                 // --- Misc -------------------------------------------
1475         case LFUN_APPENDIX:
1476         {
1477                 if (available()) {
1478                         LyXText * lt = bv_->getLyXText();
1479                         lt->toggleAppendix(bv_);
1480                         update(lt,
1481                                BufferView::SELECT
1482                                | BufferView::FITCUR
1483                                | BufferView::CHANGE);
1484                 }
1485         }
1486         break;
1487
1488         case LFUN_TOC_INSERT:
1489         {
1490                 InsetCommandParams p;
1491                 p.setCmdName("tableofcontents");
1492                 Inset * inset = new InsetTOC(p);
1493                 if (!insertInset(inset, "Standard"))
1494                         delete inset;
1495                 break;
1496         }
1497                 
1498         case LFUN_TABULAR_FEATURE:
1499         case LFUN_SCROLL_INSET:
1500                 // this is not handled here as this funktion is only aktive
1501                 // if we have a locking_inset and that one is (or contains)
1502                 // a tabular-inset
1503                 break;
1504
1505         case LFUN_INSET_GRAPHICS:
1506         {
1507                 Inset * new_inset = new InsetGraphics;
1508                 if (!insertInset(new_inset)) {
1509                         delete new_inset;
1510                 } else {
1511                         // this is need because you don't use a inset->Edit()
1512                         updateInset(new_inset, true);
1513                         new_inset->edit(bv_);
1514                 }
1515                 break;
1516         }
1517                 
1518         case LFUN_PASTE:
1519                 bv_->paste();
1520                 setState();
1521                 break;
1522                 
1523         case LFUN_PASTESELECTION:
1524         {
1525                 bool asPara = false;
1526                 if (argument == "paragraph") asPara = true;
1527                 pasteClipboard(asPara);
1528         }
1529         break;
1530         
1531         case LFUN_CUT:
1532                 bv_->cut();
1533                 break;
1534                 
1535         case LFUN_COPY:
1536                 bv_->copy();
1537                 break;
1538                 
1539         case LFUN_LAYOUT_COPY:
1540                 bv_->copyEnvironment();
1541                 break;
1542                 
1543         case LFUN_LAYOUT_PASTE:
1544                 bv_->pasteEnvironment();
1545                 setState();
1546                 break;
1547                 
1548         case LFUN_GOTOERROR:
1549                 gotoInset(Inset::ERROR_CODE, false);
1550                 break;
1551                 
1552         case LFUN_GOTONOTE:
1553                 gotoInset(Inset::IGNORE_CODE, false);
1554                 break;
1555
1556         case LFUN_REFERENCE_GOTO:
1557         {
1558                 vector<Inset::Code> tmp;
1559                 tmp.push_back(Inset::LABEL_CODE);
1560                 tmp.push_back(Inset::REF_CODE);
1561                 gotoInset(tmp, true);
1562                 break;
1563         }
1564
1565         case LFUN_HYPHENATION:
1566                 specialChar(InsetSpecialChar::HYPHENATION);
1567                 break;
1568                 
1569         case LFUN_LIGATURE_BREAK:
1570                 specialChar(InsetSpecialChar::LIGATURE_BREAK);
1571                 break;
1572                 
1573         case LFUN_LDOTS:
1574                 specialChar(InsetSpecialChar::LDOTS);
1575                 break;
1576                 
1577         case LFUN_END_OF_SENTENCE:
1578                 specialChar(InsetSpecialChar::END_OF_SENTENCE);
1579                 break;
1580
1581         case LFUN_MENU_SEPARATOR:
1582                 specialChar(InsetSpecialChar::MENU_SEPARATOR);
1583                 break;
1584                 
1585         case LFUN_HFILL:
1586                 hfill();
1587                 break;
1588                 
1589         case LFUN_DEPTH:
1590                 changeDepth(bv_, bv_->getLyXText(), 0);
1591                 break;
1592                 
1593         case LFUN_DEPTH_MIN:
1594                 changeDepth(bv_, bv_->getLyXText(), -1);
1595                 break;
1596                 
1597         case LFUN_DEPTH_PLUS:
1598                 changeDepth(bv_, bv_->getLyXText(), 1);
1599                 break;
1600                 
1601         case LFUN_FREE:
1602                 owner_->getDialogs()->setUserFreeFont();
1603                 break;
1604
1605 #ifndef NO_LATEX
1606         case LFUN_TEX:
1607                 Tex(bv_);
1608                 setState();
1609                 owner_->showState();
1610                 break;
1611 #endif
1612                 
1613         case LFUN_FILE_INSERT:
1614         {
1615                 MenuInsertLyXFile(argument);
1616         }
1617         break;
1618         
1619         case LFUN_FILE_INSERT_ASCII_PARA:
1620                 InsertAsciiFile(bv_, argument, true);
1621                 break;
1622
1623         case LFUN_FILE_INSERT_ASCII:
1624                 InsertAsciiFile(bv_, argument, false);
1625                 break;
1626                 
1627         case LFUN_LAYOUT:
1628         {
1629                 lyxerr[Debug::INFO] << "LFUN_LAYOUT: (arg) "
1630                                     << argument << endl;
1631                 
1632                 // Derive layout number from given argument (string)
1633                 // and current buffer's textclass (number). */    
1634                 LyXTextClassList::ClassList::size_type tclass =
1635                         buffer_->params.textclass;
1636                 pair <bool, LyXTextClass::size_type> layout = 
1637                         textclasslist.NumberOfLayout(tclass, argument);
1638
1639                 // If the entry is obsolete, use the new one instead.
1640                 if (layout.first) {
1641                         string obs = textclasslist.Style(tclass,layout.second)
1642                                 .obsoleted_by();
1643                         if (!obs.empty()) 
1644                                 layout = 
1645                                         textclasslist.NumberOfLayout(tclass, obs);
1646                 }
1647
1648                 // see if we found the layout number:
1649                 if (!layout.first) {
1650                         owner_->getLyXFunc()->setErrorMessage(
1651                                 string(N_("Layout ")) + argument +
1652                                 N_(" not known"));
1653                         break;
1654                 }
1655
1656                 if (current_layout != layout.second) {
1657                         LyXText * lt = bv_->getLyXText();
1658                         hideCursor();
1659                         current_layout = layout.second;
1660                         update(lt,
1661                                BufferView::SELECT
1662                                | BufferView::FITCUR);
1663                         lt->setLayout(bv_, layout.second);
1664                         owner_->setLayout(layout.second);
1665                         update(lt,
1666                                BufferView::SELECT
1667                                | BufferView::FITCUR
1668                                | BufferView::CHANGE);
1669                         setState();
1670                 }
1671         }
1672         break;
1673
1674         case LFUN_LANGUAGE:
1675                 lang(bv_, argument);
1676                 setState();
1677                 owner_->showState();
1678                 break;
1679
1680         case LFUN_EMPH:
1681                 emph(bv_);
1682                 owner_->showState();
1683                 break;
1684
1685         case LFUN_BOLD:
1686                 bold(bv_);
1687                 owner_->showState();
1688                 break;
1689                 
1690         case LFUN_NOUN:
1691                 noun(bv_);
1692                 owner_->showState();
1693                 break;
1694                 
1695         case LFUN_CODE:
1696                 code(bv_);
1697                 owner_->showState();
1698                 break;
1699                 
1700         case LFUN_SANS:
1701                 sans(bv_);
1702                 owner_->showState();
1703                 break;
1704                 
1705         case LFUN_ROMAN:
1706                 roman(bv_);
1707                 owner_->showState();
1708                 break;
1709                 
1710         case LFUN_DEFAULT:
1711                 styleReset(bv_);
1712                 owner_->showState();
1713                 break;
1714                 
1715         case LFUN_UNDERLINE:
1716                 underline(bv_);
1717                 owner_->showState();
1718                 break;
1719                 
1720         case LFUN_FONT_SIZE:
1721                 fontSize(bv_, argument);
1722                 owner_->showState();
1723                 break;
1724                 
1725         case LFUN_FONT_STATE:
1726                 owner_->getLyXFunc()->setMessage(currentState(bv_));
1727                 break;
1728                 
1729         case LFUN_UPCASE_WORD:
1730         {
1731                 LyXText * lt = bv_->getLyXText();
1732                 
1733                 update(lt,
1734                        BufferView::SELECT
1735                        | BufferView::FITCUR);
1736                 lt->changeCase(bv_, LyXText::text_uppercase);
1737                 if (lt->inset_owner)
1738                         updateInset(lt->inset_owner, true);
1739                 update(lt,
1740                        BufferView::SELECT
1741                        | BufferView::FITCUR
1742                        | BufferView::CHANGE);
1743         }
1744         break;
1745                 
1746         case LFUN_LOWCASE_WORD:
1747         {
1748                 LyXText * lt = bv_->getLyXText();
1749                 
1750                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1751                 lt->changeCase(bv_, LyXText::text_lowercase);
1752                 if (lt->inset_owner)
1753                         updateInset(lt->inset_owner, true);
1754                 update(lt,
1755                        BufferView::SELECT
1756                        | BufferView::FITCUR
1757                        | BufferView::CHANGE);
1758         }
1759         break;
1760                 
1761         case LFUN_CAPITALIZE_WORD:
1762         {
1763                 LyXText * lt = bv_->getLyXText();
1764                 
1765                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1766                 lt->changeCase(bv_, LyXText::text_capitalization);
1767                 if (lt->inset_owner)
1768                         updateInset(lt->inset_owner, true);
1769                 update(lt,
1770                        BufferView::SELECT
1771                        | BufferView::FITCUR
1772                        | BufferView::CHANGE);
1773         }
1774         break;
1775
1776         case LFUN_TRANSPOSE_CHARS:
1777         {
1778                 LyXText * lt = bv_->getLyXText();
1779                 
1780                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1781                 lt->transposeChars(*bv_);
1782                 if (lt->inset_owner)
1783                         updateInset(lt->inset_owner, true);
1784                 update(lt,
1785                        BufferView::SELECT
1786                        | BufferView::FITCUR
1787                        | BufferView::CHANGE);
1788         }
1789         break;
1790                 
1791                                           
1792         case LFUN_INSERT_LABEL:
1793                 MenuInsertLabel(bv_, argument);
1794                 break;
1795                 
1796         case LFUN_REF_INSERT:
1797                 if (argument.empty()) {
1798                         InsetCommandParams p("ref");
1799                         owner_->getDialogs()->createRef(p.getAsString());
1800                 } else {
1801                         InsetCommandParams p;
1802                         p.setFromString(argument);
1803
1804                         InsetRef * inset = new InsetRef(p, *buffer_);
1805                         if (!insertInset(inset))
1806                                 delete inset;
1807                         else
1808                                 updateInset(inset, true);
1809                 }
1810                 break;
1811
1812         case LFUN_BOOKMARK_SAVE:
1813                 savePosition(strToUnsignedInt(argument));
1814                 break;
1815
1816         case LFUN_BOOKMARK_GOTO:
1817                 restorePosition(strToUnsignedInt(argument));
1818                 break;
1819
1820         case LFUN_REF_GOTO:
1821         {
1822                 string label(argument);
1823                 if (label.empty()) {
1824                         InsetRef * inset = 
1825                                 static_cast<InsetRef*>(getInsetByCode(Inset::REF_CODE));
1826                         if (inset) {
1827                                 label = inset->getContents();
1828                                 savePosition(0);
1829                         }
1830                 }
1831                 
1832                 if (!label.empty()) {
1833                         //bv_->savePosition(0);
1834                         if (!bv_->gotoLabel(label))
1835                                 WriteAlert(_("Error"), 
1836                                            _("Couldn't find this label"), 
1837                                            _("in current document."));
1838                 }
1839         }
1840         break;
1841                 
1842                 // --- Cursor Movements -----------------------------
1843         case LFUN_RIGHT:
1844         {
1845                 LyXText * lt = bv_->getLyXText();
1846                 
1847                 bool is_rtl = lt->cursor.par()->isRightToLeftPar(buffer_->params);
1848                 if (!lt->selection.mark())
1849                         beforeChange(lt);
1850                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1851                 if (is_rtl)
1852                         lt->cursorLeft(bv_, false);
1853                 if (lt->cursor.pos() < lt->cursor.par()->size()
1854                     && lt->cursor.par()->getChar(lt->cursor.pos())
1855                     == Paragraph::META_INSET
1856                     && lt->cursor.par()->getInset(lt->cursor.pos())
1857                     && lt->cursor.par()->getInset(lt->cursor.pos())->editable() == Inset::HIGHLY_EDITABLE){
1858                         Inset * tmpinset = lt->cursor.par()->getInset(lt->cursor.pos());
1859                         owner_->getLyXFunc()->setMessage(tmpinset->editMessage());
1860                         if (is_rtl)
1861                                 tmpinset->edit(bv_, false);
1862                         else
1863                                 tmpinset->edit(bv_);
1864                         break;
1865                 }
1866                 if (!is_rtl)
1867                         lt->cursorRight(bv_, false);
1868                 finishUndo();
1869                 moveCursorUpdate(false);
1870                 owner_->showState();
1871         }
1872         break;
1873                 
1874         case LFUN_LEFT:
1875         {
1876                 // This is soooo ugly. Isn`t it possible to make
1877                 // it simpler? (Lgb)
1878                 LyXText * lt = bv_->getLyXText();
1879                 bool is_rtl = lt->cursor.par()->isRightToLeftPar(buffer_->params);
1880                 if (!lt->selection.mark())
1881                         beforeChange(lt);
1882                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1883                 LyXCursor const cur = lt->cursor;
1884                 if (!is_rtl)
1885                         lt->cursorLeft(bv_, false);
1886                 if ((is_rtl || cur != lt->cursor) && // only if really moved!
1887                     lt->cursor.pos() < lt->cursor.par()->size() &&
1888                     (lt->cursor.par()->getChar(lt->cursor.pos()) ==
1889                      Paragraph::META_INSET) &&
1890                     lt->cursor.par()->getInset(lt->cursor.pos()) &&
1891                     (lt->cursor.par()->getInset(lt->cursor.pos())->editable()
1892                      == Inset::HIGHLY_EDITABLE))
1893                 {
1894                         Inset * tmpinset = lt->cursor.par()->getInset(lt->cursor.pos());
1895                         owner_->getLyXFunc()->setMessage(tmpinset->editMessage());
1896                         if (is_rtl)
1897                                 tmpinset->edit(bv_);
1898                         else
1899                                 tmpinset->edit(bv_, false);
1900                         break;
1901                 }
1902                 if  (is_rtl)
1903                         lt->cursorRight(bv_, false);
1904
1905                 finishUndo();
1906                 moveCursorUpdate(false);
1907                 owner_->showState();
1908         }
1909         break;
1910                 
1911         case LFUN_UP:
1912         {
1913                 LyXText * lt = bv_->getLyXText();
1914                 
1915                 if (!lt->selection.mark())
1916                         beforeChange(lt);
1917                 update(lt, BufferView::UPDATE);
1918                 lt->cursorUp(bv_);
1919                 finishUndo();
1920                 moveCursorUpdate(false);
1921                 owner_->showState();
1922         }
1923         break;
1924                 
1925         case LFUN_DOWN:
1926         {
1927                 LyXText * lt = bv_->getLyXText();
1928                 
1929                 if (!lt->selection.mark())
1930                         beforeChange(lt);
1931                 update(lt, BufferView::UPDATE);
1932                 lt->cursorDown(bv_);
1933                 finishUndo();
1934                 moveCursorUpdate(false);
1935                 owner_->showState();
1936         }
1937         break;
1938
1939         case LFUN_UP_PARAGRAPH:
1940         {
1941                 LyXText * lt = bv_->getLyXText();
1942                 
1943                 if (!lt->selection.mark())
1944                         beforeChange(lt);
1945                 update(lt, BufferView::UPDATE);
1946                 lt->cursorUpParagraph(bv_);
1947                 finishUndo();
1948                 moveCursorUpdate(false);
1949                 owner_->showState();
1950         }
1951         break;
1952                 
1953         case LFUN_DOWN_PARAGRAPH:
1954         {
1955                 LyXText * lt = bv_->getLyXText();
1956                 
1957                 if (!lt->selection.mark())
1958                         beforeChange(lt);
1959                 update(lt, BufferView::UPDATE);
1960                 lt->cursorDownParagraph(bv_);
1961                 finishUndo();
1962                 moveCursorUpdate(false);
1963                 owner_->showState();
1964         }
1965         break;
1966                 
1967         case LFUN_PRIOR:
1968         {
1969                 LyXText * lt = bv_->getLyXText();
1970                 
1971                 if (!lt->selection.mark())
1972                         beforeChange(lt);
1973                 update(lt, BufferView::UPDATE);
1974                 cursorPrevious(lt);
1975                 finishUndo();
1976                 moveCursorUpdate(false);
1977                 owner_->showState();
1978         }
1979         break;
1980                 
1981         case LFUN_NEXT:
1982         {
1983                 LyXText * lt = bv_->getLyXText();
1984                 
1985                 if (!lt->selection.mark())
1986                         beforeChange(lt);
1987                 update(lt, BufferView::UPDATE);
1988                 cursorNext(lt);
1989                 finishUndo();
1990                 moveCursorUpdate(false);
1991                 owner_->showState();
1992         }
1993         break;
1994                 
1995         case LFUN_HOME:
1996         {
1997                 LyXText * lt = bv_->getLyXText();
1998                 
1999                 if (!lt->selection.mark())
2000                         beforeChange(lt);
2001                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2002                 lt->cursorHome(bv_);
2003                 finishUndo();
2004                 moveCursorUpdate(false);
2005                 owner_->showState();
2006         }
2007         break;
2008                 
2009         case LFUN_END:
2010         {
2011                 LyXText * lt = bv_->getLyXText();
2012                 
2013                 if (!lt->selection.mark())
2014                         beforeChange(lt);
2015                 update(lt,
2016                        BufferView::SELECT|BufferView::FITCUR);
2017                 lt->cursorEnd(bv_);
2018                 finishUndo();
2019                 moveCursorUpdate(false);
2020                 owner_->showState();
2021         }
2022         break;
2023                 
2024         case LFUN_SHIFT_TAB:
2025         case LFUN_TAB:
2026         {
2027                 LyXText * lt = bv_->getLyXText();
2028                 
2029                 if (!lt->selection.mark())
2030                         beforeChange(lt);
2031                 update(lt,
2032                        BufferView::SELECT|BufferView::FITCUR);
2033                 lt->cursorTab(bv_);
2034                 finishUndo();
2035                 moveCursorUpdate(false);
2036                 owner_->showState();
2037         }
2038         break;
2039                 
2040         case LFUN_WORDRIGHT:
2041         {
2042                 LyXText * lt = bv_->getLyXText();
2043                 
2044                 if (!lt->selection.mark())
2045                         beforeChange(lt);
2046                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2047                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2048                         lt->cursorLeftOneWord(bv_);
2049                 else
2050                         lt->cursorRightOneWord(bv_);
2051                 finishUndo();
2052                 moveCursorUpdate(false);
2053                 owner_->showState();
2054         }
2055         break;
2056                 
2057         case LFUN_WORDLEFT:
2058         {
2059                 LyXText * lt = bv_->getLyXText();
2060                 
2061                 if (!lt->selection.mark())
2062                         beforeChange(lt);
2063                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2064                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2065                         lt->cursorRightOneWord(bv_);
2066                 else
2067                         lt->cursorLeftOneWord(bv_);
2068                 finishUndo();
2069                 moveCursorUpdate(false);
2070                 owner_->showState();
2071         }
2072         break;
2073                 
2074         case LFUN_BEGINNINGBUF:
2075         {
2076                 LyXText * lt = bv_->getLyXText();
2077                 
2078                 if (!lt->selection.mark())
2079                         beforeChange(lt);
2080                 update(lt,
2081                        BufferView::SELECT|BufferView::FITCUR);
2082                 lt->cursorTop(bv_);
2083                 finishUndo();
2084                 moveCursorUpdate(false);
2085                 owner_->showState();
2086         }
2087         break;
2088                 
2089         case LFUN_ENDBUF:
2090         {
2091                 LyXText * lt = bv_->getLyXText();
2092                 
2093                 if (!lt->selection.mark())
2094                         beforeChange(lt);
2095                 update(lt,
2096                        BufferView::SELECT|BufferView::FITCUR);
2097                 lt->cursorBottom(bv_);
2098                 finishUndo();
2099                 moveCursorUpdate(false);
2100                 owner_->showState();
2101         }
2102         break;
2103       
2104                 /* cursor selection ---------------------------- */
2105         case LFUN_RIGHTSEL:
2106         {
2107                 LyXText * lt = bv_->getLyXText();
2108                 
2109                 update(lt,
2110                        BufferView::SELECT|BufferView::FITCUR);
2111                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2112                         lt->cursorLeft(bv_);
2113                 else
2114                         lt->cursorRight(bv_);
2115                 finishUndo();
2116                 moveCursorUpdate(true);
2117                 owner_->showState();
2118         }
2119         break;
2120                 
2121         case LFUN_LEFTSEL:
2122         {
2123                 LyXText * lt = bv_->getLyXText();
2124                 
2125                 update(lt,
2126                        BufferView::SELECT|BufferView::FITCUR);
2127                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2128                         lt->cursorRight(bv_);
2129                 else
2130                         lt->cursorLeft(bv_);
2131                 finishUndo();
2132                 moveCursorUpdate(true);
2133                 owner_->showState();
2134         }
2135         break;
2136                 
2137         case LFUN_UPSEL:
2138         {
2139                 LyXText * lt = bv_->getLyXText();
2140                 
2141                 update(lt,
2142                        BufferView::SELECT|BufferView::FITCUR);
2143                 lt->cursorUp(bv_);
2144                 finishUndo();
2145                 moveCursorUpdate(true);
2146                 owner_->showState();
2147         }
2148         break;
2149                 
2150         case LFUN_DOWNSEL:
2151         {
2152                 LyXText * lt = bv_->getLyXText();
2153                 
2154                 update(lt,
2155                        BufferView::SELECT|BufferView::FITCUR);
2156                 lt->cursorDown(bv_);
2157                 finishUndo();
2158                 moveCursorUpdate(true);
2159                 owner_->showState();
2160         }
2161         break;
2162
2163         case LFUN_UP_PARAGRAPHSEL:
2164         {
2165                 LyXText * lt = bv_->getLyXText();
2166                 
2167                 update(lt,
2168                        BufferView::SELECT|BufferView::FITCUR);
2169                 lt->cursorUpParagraph(bv_);
2170                 finishUndo();
2171                 moveCursorUpdate(true);
2172                 owner_->showState();
2173         }
2174         break;
2175                 
2176         case LFUN_DOWN_PARAGRAPHSEL:
2177         {
2178                 LyXText * lt = bv_->getLyXText();
2179                 
2180                 update(lt,
2181                        BufferView::SELECT|BufferView::FITCUR);
2182                 lt->cursorDownParagraph(bv_);
2183                 finishUndo();
2184                 moveCursorUpdate(true);
2185                 owner_->showState();
2186         }
2187         break;
2188                 
2189         case LFUN_PRIORSEL:
2190         {
2191                 LyXText * lt = bv_->getLyXText();
2192                 
2193                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2194                 cursorPrevious(lt);
2195                 finishUndo();
2196                 moveCursorUpdate(true);
2197                 owner_->showState();
2198         }
2199         break;
2200                 
2201         case LFUN_NEXTSEL:
2202         {
2203                 LyXText * lt = bv_->getLyXText();
2204                 
2205                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2206                 cursorNext(lt);
2207                 finishUndo();
2208                 moveCursorUpdate(true);
2209                 owner_->showState();
2210         }
2211         break;
2212                 
2213         case LFUN_HOMESEL:
2214         {
2215                 LyXText * lt = bv_->getLyXText();
2216                 
2217                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2218                 lt->cursorHome(bv_);
2219                 finishUndo();
2220                 moveCursorUpdate(true);
2221                 owner_->showState();
2222         }
2223         break;
2224                 
2225         case LFUN_ENDSEL:
2226         {
2227                 LyXText * lt = bv_->getLyXText();
2228                 
2229                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2230                 lt->cursorEnd(bv_);
2231                 finishUndo();
2232                 moveCursorUpdate(true);
2233                 owner_->showState();
2234         }
2235         break;
2236                 
2237         case LFUN_WORDRIGHTSEL:
2238         {
2239                 LyXText * lt = bv_->getLyXText();
2240                 
2241                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2242                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2243                         lt->cursorLeftOneWord(bv_);
2244                 else
2245                         lt->cursorRightOneWord(bv_);
2246                 finishUndo();
2247                 moveCursorUpdate(true);
2248                 owner_->showState();
2249         }
2250         break;
2251                 
2252         case LFUN_WORDLEFTSEL:
2253         {
2254                 LyXText * lt = bv_->getLyXText();
2255                 
2256                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2257                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2258                         lt->cursorRightOneWord(bv_);
2259                 else
2260                         lt->cursorLeftOneWord(bv_);
2261                 finishUndo();
2262                 moveCursorUpdate(true);
2263                 owner_->showState();
2264         }
2265         break;
2266                 
2267         case LFUN_BEGINNINGBUFSEL:
2268         {
2269                 LyXText * lt = bv_->getLyXText();
2270                 
2271                 if (lt->inset_owner)
2272                         break;
2273                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2274                 lt->cursorTop(bv_);
2275                 finishUndo();
2276                 moveCursorUpdate(true);
2277                 owner_->showState();
2278         }
2279         break;
2280                 
2281         case LFUN_ENDBUFSEL:
2282         {
2283                 LyXText * lt = bv_->getLyXText();
2284                 
2285                 if (lt->inset_owner)
2286                         break;
2287                 update(lt,
2288                        BufferView::SELECT|BufferView::FITCUR);
2289                 lt->cursorBottom(bv_);
2290                 finishUndo();
2291                 moveCursorUpdate(true);
2292                 owner_->showState();
2293         }
2294         break;
2295
2296                 // --- text changing commands ------------------------
2297         case LFUN_BREAKLINE:
2298         {
2299                 LyXText * lt = bv_->getLyXText();
2300
2301                 beforeChange(lt);
2302                 lt->insertChar(bv_, Paragraph::META_NEWLINE);
2303                 update(lt,
2304                        BufferView::SELECT
2305                        | BufferView::FITCUR
2306                        | BufferView::CHANGE);
2307                 moveCursorUpdate(false);
2308         }
2309         break;
2310                 
2311         case LFUN_PROTECTEDSPACE:
2312         {
2313                 LyXText * lt = bv_->getLyXText();
2314
2315                 LyXLayout const & style = textclasslist
2316                         .Style(buffer_->params.textclass,
2317                                lt->cursor.par()->getLayout());
2318
2319                 if (style.free_spacing) {
2320                         lt->insertChar(bv_, ' ');
2321                         update(lt,
2322                                BufferView::SELECT
2323                                | BufferView::FITCUR
2324                                | BufferView::CHANGE);
2325                 } else {
2326                         protectedBlank(lt);
2327                 }
2328                 moveCursorUpdate(false);
2329         }
2330         break;
2331                 
2332         case LFUN_SETMARK:
2333         {
2334                 LyXText * lt = bv_->getLyXText();
2335
2336                 if (lt->selection.mark()) {
2337                         beforeChange(lt);
2338                         update(lt,
2339                                BufferView::SELECT
2340                                | BufferView::FITCUR);
2341                         owner_->getLyXFunc()->setMessage(N_("Mark removed"));
2342                 } else {
2343                         beforeChange(lt);
2344                         lt->selection.mark(true);
2345                         update(lt,
2346                                BufferView::SELECT
2347                                | BufferView::FITCUR);
2348                         owner_->getLyXFunc()->setMessage(N_("Mark set"));
2349                 }
2350                 lt->selection.cursor = lt->cursor;
2351         }
2352         break;
2353                 
2354         case LFUN_DELETE:
2355         {
2356                 LyXText * lt = bv_->getLyXText();
2357
2358                 if (!lt->selection.set()) {
2359                         lt->Delete(bv_);
2360                         lt->selection.cursor = lt->cursor;
2361                         update(lt,
2362                                BufferView::SELECT
2363                                | BufferView::FITCUR
2364                                | BufferView::CHANGE);
2365                         // It is possible to make it a lot faster still
2366                         // just comment out the line below...
2367                         showCursor();
2368                 } else {
2369                         bv_->cut();
2370                 }
2371                 moveCursorUpdate(false);
2372                 owner_->showState();
2373                 setState();
2374         }
2375         break;
2376
2377         case LFUN_DELETE_SKIP:
2378         {
2379                 LyXText * lt = bv_->getLyXText();
2380
2381                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
2382                 
2383                 LyXCursor cursor = lt->cursor;
2384
2385                 if (!lt->selection.set()) {
2386                         if (cursor.pos() == cursor.par()->size()) {
2387                                 lt->cursorRight(bv_);
2388                                 cursor = lt->cursor;
2389                                 if (cursor.pos() == 0
2390                                     && !(cursor.par()->params().spaceTop()
2391                                          == VSpace (VSpace::NONE))) {
2392                                         lt->setParagraph
2393                                                 (bv_,
2394                                                  cursor.par()->params().lineTop(),
2395                                                  cursor.par()->params().lineBottom(),
2396                                                  cursor.par()->params().pagebreakTop(), 
2397                                                  cursor.par()->params().pagebreakBottom(),
2398                                                  VSpace(VSpace::NONE), 
2399                                                  cursor.par()->params().spaceBottom(),
2400                                                  cursor.par()->params().align(), 
2401                                                  cursor.par()->params().labelWidthString(), 0);
2402                                         lt->cursorLeft(bv_);
2403                                         update(lt, 
2404                                                BufferView::SELECT
2405                                                | BufferView::FITCUR
2406                                                | BufferView::CHANGE);
2407                                 } else {
2408                                         lt->cursorLeft(bv_);
2409                                         lt->Delete(bv_);
2410                                         lt->selection.cursor = lt->cursor;
2411                                         update(lt,
2412                                                BufferView::SELECT
2413                                                | BufferView::FITCUR
2414                                                | BufferView::CHANGE);
2415                                 }
2416                         } else {
2417                                 lt->Delete(bv_);
2418                                 lt->selection.cursor = lt->cursor;
2419                                 update(lt,
2420                                        BufferView::SELECT
2421                                        | BufferView::FITCUR
2422                                        | BufferView::CHANGE);
2423                         }
2424                 } else {
2425                         bv_->cut();
2426                 }
2427         }
2428         break;
2429
2430         /* -------> Delete word forward. */
2431         case LFUN_DELETE_WORD_FORWARD:
2432                 update(bv_->getLyXText(), BufferView::SELECT|BufferView::FITCUR);
2433                 bv_->getLyXText()->deleteWordForward(bv_);
2434                 update(bv_->getLyXText(), BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2435                 moveCursorUpdate(false);
2436                 owner_->showState();
2437                 break;
2438
2439                 /* -------> Delete word backward. */
2440         case LFUN_DELETE_WORD_BACKWARD:
2441         {
2442                 LyXText * lt = bv_->getLyXText();
2443                 
2444                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2445                 lt->deleteWordBackward(bv_);
2446                 update(lt,
2447                        BufferView::SELECT
2448                        | BufferView::FITCUR
2449                        | BufferView::CHANGE);
2450                 moveCursorUpdate(false);
2451                 owner_->showState();
2452         }
2453         break;
2454                 
2455                 /* -------> Kill to end of line. */
2456         case LFUN_DELETE_LINE_FORWARD:
2457         {
2458                 LyXText * lt = bv_->getLyXText();
2459                 
2460                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2461                 lt->deleteLineForward(bv_);
2462                 update(lt,
2463                        BufferView::SELECT
2464                        | BufferView::FITCUR
2465                        | BufferView::CHANGE);
2466                 moveCursorUpdate(false);
2467         }
2468         break;
2469                 
2470                 /* -------> Set mark off. */
2471         case LFUN_MARK_OFF:
2472         {
2473                 LyXText * lt = bv_->getLyXText();
2474                 
2475                 beforeChange(lt);
2476                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2477                 lt->selection.cursor = lt->cursor;
2478                 owner_->getLyXFunc()->setMessage(N_("Mark off"));
2479         }
2480         break;
2481
2482                 /* -------> Set mark on. */
2483         case LFUN_MARK_ON:
2484         {
2485                 LyXText * lt = bv_->getLyXText();
2486                 
2487                 beforeChange(lt);
2488                 lt->selection.mark(true);
2489                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2490                 lt->selection.cursor = lt->cursor;
2491                 owner_->getLyXFunc()->setMessage(N_("Mark on"));
2492         }
2493         break;
2494                 
2495         case LFUN_BACKSPACE:
2496         {
2497                 LyXText * lt = bv_->getLyXText();
2498                 
2499                 if (!lt->selection.set()) {
2500                         if (owner_->getIntl()->getTrans().backspace()) {
2501                                 lt->backspace(bv_);
2502                                 lt->selection.cursor = lt->cursor;
2503                                 update(lt,
2504                                        BufferView::SELECT
2505                                        | BufferView::FITCUR
2506                                        | BufferView::CHANGE);
2507                                 // It is possible to make it a lot faster still
2508                                 // just comment out the line below...
2509                                 showCursor();
2510                         }
2511                 } else {
2512                         bv_->cut();
2513                 }
2514                 owner_->showState();
2515                 setState();
2516         }
2517         break;
2518
2519         case LFUN_BACKSPACE_SKIP:
2520         {
2521                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
2522                 LyXText * lt = bv_->getLyXText();
2523                 
2524                 LyXCursor cursor = lt->cursor;
2525                 
2526                 if (!lt->selection.set()) {
2527                         if (cursor.pos() == 0 
2528                             && !(cursor.par()->params().spaceTop() 
2529                                  == VSpace (VSpace::NONE))) {
2530                                 lt->setParagraph 
2531                                         (bv_,
2532                                          cursor.par()->params().lineTop(),      
2533                                          cursor.par()->params().lineBottom(),
2534                                          cursor.par()->params().pagebreakTop(), 
2535                                          cursor.par()->params().pagebreakBottom(),
2536                                          VSpace(VSpace::NONE), cursor.par()->params().spaceBottom(),
2537                                          cursor.par()->params().align(), 
2538                                          cursor.par()->params().labelWidthString(), 0);
2539                                 update(lt,
2540                                        BufferView::SELECT
2541                                        | BufferView::FITCUR
2542                                        | BufferView::CHANGE);
2543                         } else {
2544                                 lt->backspace(bv_);
2545                                 lt->selection.cursor = cursor;
2546                                 update(lt,
2547                                        BufferView::SELECT
2548                                        | BufferView::FITCUR
2549                                        | BufferView::CHANGE);
2550                         }
2551                 } else
2552                         bv_->cut();
2553         }
2554         break;
2555
2556         case LFUN_BREAKPARAGRAPH:
2557         {
2558                 LyXText * lt = bv_->getLyXText();
2559                 
2560                 beforeChange(lt);
2561                 lt->breakParagraph(bv_, 0);
2562                 update(lt,
2563                        BufferView::SELECT
2564                        | BufferView::FITCUR
2565                        | BufferView::CHANGE);
2566                 lt->selection.cursor = lt->cursor;
2567                 setState();
2568                 owner_->showState();
2569                 break;
2570         }
2571
2572         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
2573         {
2574                 LyXText * lt = bv_->getLyXText();
2575                 
2576                 beforeChange(lt);
2577                 lt->breakParagraph(bv_, 1);
2578                 update(lt,
2579                        BufferView::SELECT
2580                        | BufferView::FITCUR
2581                        | BufferView::CHANGE);
2582                 lt->selection.cursor = lt->cursor;
2583                 setState();
2584                 owner_->showState();
2585                 break;
2586         }
2587         
2588         case LFUN_BREAKPARAGRAPH_SKIP:
2589         {
2590                 // When at the beginning of a paragraph, remove
2591                 // indentation and add a "defskip" at the top.
2592                 // Otherwise, do the same as LFUN_BREAKPARAGRAPH.
2593                 LyXText * lt = bv_->getLyXText();
2594                 
2595                 LyXCursor cursor = lt->cursor;
2596                 
2597                 beforeChange(lt);
2598                 if (cursor.pos() == 0) {
2599                         if (cursor.par()->params().spaceTop() == VSpace(VSpace::NONE)) {
2600                                 lt->setParagraph
2601                                         (bv_,
2602                                          cursor.par()->params().lineTop(),      
2603                                          cursor.par()->params().lineBottom(),
2604                                          cursor.par()->params().pagebreakTop(), 
2605                                          cursor.par()->params().pagebreakBottom(),
2606                                          VSpace(VSpace::DEFSKIP), cursor.par()->params().spaceBottom(),
2607                                          cursor.par()->params().align(), 
2608                                          cursor.par()->params().labelWidthString(), 1);
2609                                 //update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2610                         } 
2611                 }
2612                 else {
2613                         lt->breakParagraph(bv_, 0);
2614                         //update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2615                 }
2616
2617                 update(lt,
2618                        BufferView::SELECT
2619                        | BufferView::FITCUR
2620                        | BufferView::CHANGE);
2621                 lt->selection.cursor = cursor;
2622                 setState();
2623                 owner_->showState();
2624         }
2625         break;
2626
2627         case LFUN_PARAGRAPH_SPACING:
2628         {
2629                 LyXText * lt = bv_->getLyXText();
2630                 
2631                 Paragraph * par = lt->cursor.par();
2632                 Spacing::Space cur_spacing = par->params().spacing().getSpace();
2633                 float cur_value = 1.0;
2634                 if (cur_spacing == Spacing::Other) {
2635                         cur_value = par->params().spacing().getValue();
2636                 }
2637                 
2638                 istringstream istr(argument.c_str());
2639
2640                 string tmp;
2641                 istr >> tmp;
2642                 Spacing::Space new_spacing = cur_spacing;
2643                 float new_value = cur_value;
2644                 if (tmp.empty()) {
2645                         lyxerr << "Missing argument to `paragraph-spacing'"
2646                                << endl;
2647                 } else if (tmp == "single") {
2648                         new_spacing = Spacing::Single;
2649                 } else if (tmp == "onehalf") {
2650                         new_spacing = Spacing::Onehalf;
2651                 } else if (tmp == "double") {
2652                         new_spacing = Spacing::Double;
2653                 } else if (tmp == "other") {
2654                         new_spacing = Spacing::Other;
2655                         float tmpval = 0.0;
2656                         istr >> tmpval;
2657                         lyxerr << "new_value = " << tmpval << endl;
2658                         if (tmpval != 0.0)
2659                                 new_value = tmpval;
2660                 } else if (tmp == "default") {
2661                         new_spacing = Spacing::Default;
2662                 } else {
2663                         lyxerr << _("Unknown spacing argument: ")
2664                                << argument << endl;
2665                 }
2666                 if (cur_spacing != new_spacing || cur_value != new_value) {
2667                         par->params().spacing(Spacing(new_spacing, new_value));
2668                         lt->redoParagraph(bv_);
2669                         update(lt,
2670                                BufferView::SELECT
2671                                | BufferView::FITCUR
2672                                | BufferView::CHANGE);
2673                 }
2674         }
2675         break;
2676         
2677         case LFUN_INSET_TOGGLE:
2678         {
2679                 LyXText * lt = bv_->getLyXText();
2680                 hideCursor();
2681                 beforeChange(lt);
2682                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2683                 lt->toggleInset(bv_);
2684                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2685                 setState();
2686         }       
2687                 break;
2688
2689         case LFUN_QUOTE:
2690                 smartQuote();
2691                 break;
2692
2693         case LFUN_HTMLURL:
2694         case LFUN_URL:
2695         {
2696                 InsetCommandParams p;
2697                 if (action == LFUN_HTMLURL)
2698                         p.setCmdName("htmlurl");
2699                 else
2700                         p.setCmdName("url");
2701                 owner_->getDialogs()->createUrl(p.getAsString());
2702         }
2703         break;
2704         
2705         case LFUN_INSERT_URL:
2706         {
2707                 InsetCommandParams p;
2708                 p.setFromString(argument);
2709
2710                 InsetUrl * inset = new InsetUrl(p);
2711                 if (!insertInset(inset))
2712                         delete inset;
2713                 else
2714                         updateInset(inset, true);
2715         }
2716         break;
2717         
2718         case LFUN_INSET_TEXT:
2719                 insertAndEditInset(new InsetText);
2720                 break;
2721         
2722         case LFUN_INSET_ERT:
2723                 insertAndEditInset(new InsetERT);
2724                 break;
2725         
2726         case LFUN_INSET_EXTERNAL:
2727                 insertAndEditInset(new InsetExternal);
2728                 break;
2729         
2730         case LFUN_INSET_FOOTNOTE:
2731                 insertAndEditInset(new InsetFoot);
2732                 break;
2733
2734         case LFUN_INSET_MARGINAL:
2735                 insertAndEditInset(new InsetMarginal);
2736                 break;
2737
2738         case LFUN_INSET_MINIPAGE:
2739                 insertAndEditInset(new InsetMinipage);
2740                 break;
2741
2742         case LFUN_INSERT_NOTE:
2743                 insertAndEditInset(new InsetNote);
2744                 break;
2745
2746         case LFUN_INSET_FLOAT:
2747                 // check if the float type exist
2748                 if (floatList.typeExist(argument)) {
2749                         insertAndEditInset(new InsetFloat(argument));
2750                 } else {
2751                         lyxerr << "Non-existant float type: "
2752                                << argument << endl;
2753                 }
2754                 break;
2755
2756         case LFUN_INSET_WIDE_FLOAT:
2757         {
2758                 // check if the float type exist
2759                 if (floatList.typeExist(argument)) {
2760                         InsetFloat * new_inset = new InsetFloat(argument);
2761                         new_inset->wide(true);
2762                         if (insertInset(new_inset))
2763                                 new_inset->edit(bv_);
2764                         else
2765                                 delete new_inset;
2766                 } else {
2767                         lyxerr << "Non-existant float type: "
2768                                << argument << endl;
2769                 }
2770                 
2771         }
2772         break;
2773
2774 #if 0
2775         case LFUN_INSET_LIST:
2776                 insertAndEditInset(new InsetList);
2777                 break;
2778
2779         case LFUN_INSET_THEOREM:
2780                 insertAndEditInset(new InsetTheorem);
2781                 break;
2782 #endif
2783                 
2784         case LFUN_INSET_CAPTION:
2785         {
2786                 // Do we have a locking inset...
2787                 if (bv_->theLockingInset()) {
2788                         lyxerr << "Locking inset code: "
2789                                << static_cast<int>(bv_->theLockingInset()->lyxCode());
2790                         InsetCaption * new_inset = new InsetCaption;
2791                         new_inset->setOwner(bv_->theLockingInset());
2792                         new_inset->setAutoBreakRows(true);
2793                         new_inset->setDrawFrame(0, InsetText::LOCKED);
2794                         new_inset->setFrameColor(0, LColor::captionframe);
2795                         if (insertInset(new_inset))
2796                                 new_inset->edit(bv_);
2797                         else
2798                                 delete new_inset;
2799                 }
2800         }
2801         break;
2802         
2803         case LFUN_INSET_TABULAR:
2804         {
2805                 int r = 2;
2806                 int c = 2;
2807                 if (!argument.empty())
2808                         ::sscanf(argument.c_str(),"%d%d", &r, &c);
2809                 InsetTabular * new_inset =
2810                         new InsetTabular(*buffer_, r, c);
2811                 bool const rtl =
2812                         bv_->getLyXText()->real_current_font.isRightToLeft();
2813                 if (!open_new_inset(new_inset, rtl))
2814                         delete new_inset;
2815         }
2816         break;
2817
2818         // --- lyxserver commands ----------------------------
2819
2820         case LFUN_CHARATCURSOR:
2821         {
2822                 Paragraph::size_type pos = bv_->getLyXText()->cursor.pos();
2823                 if (pos < bv_->getLyXText()->cursor.par()->size())
2824                         owner_->getLyXFunc()->setMessage(
2825                                 tostr(bv_->getLyXText()->cursor.par()->getChar(pos)));
2826                 else
2827                         owner_->getLyXFunc()->setMessage("EOF");
2828         }
2829         break;
2830         
2831         case LFUN_GETXY:
2832                 owner_->getLyXFunc()->setMessage(tostr(bv_->getLyXText()->cursor.x())
2833                                                  + ' '
2834                                                  + tostr(bv_->getLyXText()->cursor.y()));
2835                 break;
2836                 
2837         case LFUN_SETXY:
2838         {
2839                 int x = 0;
2840                 int y = 0;
2841                 if (::sscanf(argument.c_str(), " %d %d", &x, &y) != 2) {
2842                         lyxerr << "SETXY: Could not parse coordinates in '"
2843                                << argument << std::endl;
2844                 }
2845                 bv_->getLyXText()->setCursorFromCoordinates(bv_, x, y);
2846         }
2847         break;
2848         
2849         case LFUN_GETLAYOUT:
2850                 owner_->getLyXFunc()->setMessage(tostr(bv_->getLyXText()->cursor.par()->layout));
2851                 break;
2852                         
2853         case LFUN_GETFONT:
2854         {
2855                 LyXFont & font = bv_->getLyXText()->current_font;
2856                 if (font.shape() == LyXFont::ITALIC_SHAPE)
2857                         owner_->getLyXFunc()->setMessage("E");
2858                 else if (font.shape() == LyXFont::SMALLCAPS_SHAPE)
2859                         owner_->getLyXFunc()->setMessage("N");
2860                 else
2861                         owner_->getLyXFunc()->setMessage("0");
2862
2863         }
2864         break;
2865
2866         case LFUN_GETLATEX:
2867         {
2868 #ifndef NO_LATEX
2869                 LyXFont & font = bv_->getLyXText()->current_font;
2870                 if (font.latex() == LyXFont::ON)
2871                         owner_->getLyXFunc()->setMessage("L");
2872                 else
2873 #endif
2874                         owner_->getLyXFunc()->setMessage("0");
2875         }
2876         break;
2877
2878         // --- accented characters ---------------------------
2879                 
2880         case LFUN_UMLAUT:
2881         case LFUN_CIRCUMFLEX:
2882         case LFUN_GRAVE:
2883         case LFUN_ACUTE:
2884         case LFUN_TILDE:
2885         case LFUN_CEDILLA:
2886         case LFUN_MACRON:
2887         case LFUN_DOT:
2888         case LFUN_UNDERDOT:
2889         case LFUN_UNDERBAR:
2890         case LFUN_CARON:
2891         case LFUN_SPECIAL_CARON:
2892         case LFUN_BREVE:
2893         case LFUN_TIE:
2894         case LFUN_HUNG_UMLAUT:
2895         case LFUN_CIRCLE:
2896         case LFUN_OGONEK:
2897                 if (argument.empty()) {
2898                         // As always...
2899                         owner_->getLyXFunc()->handleKeyFunc(action);
2900                 } else {
2901                         owner_->getLyXFunc()->handleKeyFunc(action);
2902                         owner_->getIntl()->getTrans()
2903                                 .TranslateAndInsert(argument[0], bv_->getLyXText());
2904                         update(bv_->getLyXText(),
2905                                BufferView::SELECT
2906                                | BufferView::FITCUR
2907                                | BufferView::CHANGE);
2908                 }
2909                 break;
2910         
2911         case LFUN_MATH_MACRO:
2912                 mathDispatchMathMacro(bv_, argument);
2913                 break;
2914
2915         case LFUN_MATH_DELIM:     
2916                 mathDispatchMathDelim(bv_, argument);
2917                 break;
2918
2919         case LFUN_INSERT_MATRIX:
2920                 mathDispatchInsertMatrix(bv_, argument);
2921                 break;
2922
2923         case LFUN_INSERT_MATH:
2924                 mathDispatchInsertMath(bv_, argument);
2925                 break;
2926
2927         case LFUN_MATH_IMPORT_SELECTION: // Imports LaTeX from the X selection
2928                 mathDispatchMathImportSelection(bv_, argument);
2929                 break;
2930
2931         case LFUN_MATH_DISPLAY:          // Open or create a displayed math inset
2932                 mathDispatchMathDisplay(bv_, argument);
2933                 break;
2934
2935         case LFUN_MATH_MODE:             // Open or create an inlined math inset 
2936                 mathDispatchMathMode(bv_, argument);
2937                 break;
2938                 
2939         case LFUN_CITATION_INSERT:
2940         {
2941                 InsetCommandParams p;
2942                 p.setFromString( argument );
2943
2944                 InsetCitation * inset = new InsetCitation( p );
2945                 if (!insertInset(inset))
2946                         delete inset;
2947                 else
2948                         updateInset( inset, true );
2949         }
2950         break;
2951                     
2952         case LFUN_INSERT_BIBTEX:
2953         {   
2954                 // ale970405+lasgoutt970425
2955                 // The argument can be up to two tokens separated 
2956                 // by a space. The first one is the bibstyle.
2957                 string const db       = token(argument, ' ', 0);
2958                 string bibstyle = token(argument, ' ', 1);
2959                 if (bibstyle.empty())
2960                         bibstyle = "plain";
2961
2962                 InsetCommandParams p( "BibTeX", db, bibstyle );
2963                 InsetBibtex * inset = new InsetBibtex(p);
2964                 
2965                 if (insertInset(inset)) {
2966                         if (argument.empty())
2967                                 inset->edit(bv_);
2968                 } else
2969                         delete inset;
2970         }
2971         break;
2972                 
2973         // BibTeX data bases
2974         case LFUN_BIBDB_ADD:
2975         {
2976                 InsetBibtex * inset = 
2977                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
2978                 if (inset) {
2979                         inset->addDatabase(argument);
2980                 }
2981         }
2982         break;
2983                     
2984         case LFUN_BIBDB_DEL:
2985         {
2986                 InsetBibtex * inset = 
2987                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
2988                 if (inset) {
2989                         inset->delDatabase(argument);
2990                 }
2991         }
2992         break;
2993         
2994         case LFUN_BIBTEX_STYLE:
2995         {
2996                 InsetBibtex * inset = 
2997                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
2998                 if (inset) {
2999                         inset->setOptions(argument);
3000                 }
3001         }
3002         break;
3003                 
3004         case LFUN_INDEX_CREATE:
3005         {
3006                 InsetCommandParams p("index");
3007                 if (argument.empty()) {
3008                         string const idxstring(bv_->getLyXText()->getStringToIndex(bv_));
3009                         if (!idxstring.empty()) {
3010                                 p.setContents(idxstring);
3011                         } else {
3012                                 break;
3013                         }
3014                 } else {
3015                         p.setContents(argument);
3016                 }
3017
3018                 owner_->getDialogs()->createIndex(p.getAsString());
3019         }
3020         break;
3021                     
3022         case LFUN_INDEX_INSERT:
3023         {
3024                 InsetCommandParams p;
3025                 p.setFromString(argument);
3026                 InsetIndex * inset = new InsetIndex(p);
3027
3028                 if (!insertInset(inset))
3029                         delete inset;
3030                 else
3031                         updateInset(inset, true);
3032         }
3033         break;
3034                     
3035         case LFUN_INDEX_INSERT_LAST:
3036         {
3037                 string const idxstring(bv_->getLyXText()->getStringToIndex(bv_));
3038                 if (!idxstring.empty()) {
3039                         owner_->message(_("Word `")
3040                                         + idxstring + _(("' indexed.")));
3041                         InsetCommandParams p("index", idxstring);
3042                         InsetIndex * inset = new InsetIndex(p);
3043                         
3044                         if (!insertInset(inset))
3045                                 delete inset;
3046                         else
3047                                 updateInset(inset, true);
3048                 }
3049         }
3050         break;
3051
3052         case LFUN_INDEX_PRINT:
3053         {
3054                 InsetCommandParams p("printindex");
3055                 Inset * inset = new InsetPrintIndex(p);
3056                 if (!insertInset(inset, "Standard"))
3057                         delete inset;
3058         }
3059         break;
3060
3061         case LFUN_PARENTINSERT:
3062         {
3063                 lyxerr << "arg " << argument << endl;
3064                 InsetCommandParams p( "lyxparent", argument );
3065                 Inset * inset = new InsetParent(p, *buffer_);
3066                 if (!insertInset(inset, "Standard"))
3067                         delete inset;
3068         }
3069                  
3070         break;
3071
3072         case LFUN_CHILD_INSERT:
3073         {
3074                 InsetInclude::Params p;
3075                 p.cparams.setFromString(argument);
3076                 p.masterFilename_ = buffer_->fileName();
3077
3078                 InsetInclude * inset = new InsetInclude(p);
3079                 if (!insertInset(inset))
3080                         delete inset;
3081                 else {
3082                         updateInset(inset, true);
3083                         bv_->owner()->getDialogs()->showInclude(inset);
3084                 }
3085         }
3086         break; 
3087
3088         case LFUN_FLOAT_LIST:
3089         {
3090                 // We should check the argument for validity. (Lgb)
3091                 Inset * inset = new InsetFloatList(argument);
3092                 if (!insertInset(inset, "Standard"))
3093                         delete inset;
3094         }
3095         break;
3096         
3097         case LFUN_THESAURUS_ENTRY:
3098         {
3099                 string arg = argument;
3100
3101                 if (arg.empty()) {
3102                         arg = bv_->getLyXText()->selectionAsString(buffer_);
3103  
3104                         // FIXME
3105                         if (arg.size() > 100 || arg.empty()) {
3106                                 // Get word or selection
3107                                 bv_->getLyXText()->selectWordWhenUnderCursor(bv_, LyXText::WHOLE_WORD);
3108                                 arg = bv_->getLyXText()->selectionAsString(buffer_);
3109                                 // FIXME: where is getLyXText()->unselect(bv_) ?
3110                         }
3111                 }
3112
3113                 bv_->owner()->getDialogs()->showThesaurus(arg);
3114         }
3115                 break;
3116  
3117         case LFUN_SELFINSERT:
3118         {
3119                 if (argument.empty()) break;
3120                 
3121                 /* Automatically delete the currently selected
3122                  * text and replace it with what is being
3123                  * typed in now. Depends on lyxrc settings
3124                  * "auto_region_delete", which defaults to
3125                  * true (on). */
3126
3127                 LyXText * lt = bv_->getLyXText();
3128                 
3129                 if (lyxrc.auto_region_delete) {
3130                         if (lt->selection.set()) {
3131                                 lt->cutSelection(bv_, false);
3132                                 bv_->update(lt,
3133                                             BufferView::SELECT
3134                                             | BufferView::FITCUR
3135                                             | BufferView::CHANGE);
3136                         }
3137                 }
3138                 
3139                 beforeChange(lt);
3140                 LyXFont const old_font(lt->real_current_font);
3141                 
3142                 string::const_iterator cit = argument.begin();
3143                 string::const_iterator end = argument.end();
3144                 for (; cit != end; ++cit) {
3145                         owner_->getIntl()->getTrans().TranslateAndInsert(*cit, lt);
3146                 }
3147                 
3148                 bv_->update(lt,
3149                             BufferView::SELECT
3150                             | BufferView::FITCUR
3151                             | BufferView::CHANGE);
3152                 
3153                 lt->selection.cursor = lt->cursor;
3154                 moveCursorUpdate(false);
3155                 
3156                 // real_current_font.number can change so we need to
3157                 // update the minibuffer
3158                 if (old_font != lt->real_current_font)
3159                         owner_->showState();
3160                 //return string();
3161         }
3162         break;
3163
3164         case LFUN_DATE_INSERT:  // jdblair: date-insert cmd
3165         {
3166                 time_t now_time_t = time(NULL);
3167                 struct tm * now_tm = localtime(&now_time_t);
3168                 setlocale(LC_TIME, "");
3169                 string arg;
3170                 if (!argument.empty())
3171                         arg = argument;
3172                 else 
3173                         arg = lyxrc.date_insert_format;
3174                 char datetmp[32];
3175                 int const datetmp_len =
3176                         ::strftime(datetmp, 32, arg.c_str(), now_tm);
3177
3178                 LyXText * lt = bv_->getLyXText();
3179                 
3180                 for (int i = 0; i < datetmp_len; i++) {
3181                         lt->insertChar(bv_, datetmp[i]);
3182                         update(lt,
3183                                BufferView::SELECT
3184                                | BufferView::FITCUR
3185                                | BufferView::CHANGE);
3186                 }
3187
3188                 lt->selection.cursor = lt->cursor;
3189                 moveCursorUpdate(false);
3190         }
3191         break;
3192
3193         case LFUN_UNKNOWN_ACTION:
3194                 owner_->getLyXFunc()->setErrorMessage(N_("Unknown function!"));
3195                 break;
3196         
3197         default:
3198                 return false;
3199         } // end of switch
3200
3201         return true;
3202 }
3203
3204
3205 void BufferView::Pimpl::newline()
3206 {
3207         if (available()) {
3208                 LyXText * lt = bv_->getLyXText();
3209                 hideCursor();
3210                 update(lt,
3211                        BufferView::SELECT
3212                        | BufferView::FITCUR);
3213                 lt->insertChar(bv_, Paragraph::META_NEWLINE);
3214                 update(lt,
3215                        BufferView::SELECT
3216                        | BufferView::FITCUR
3217                        | BufferView::CHANGE);
3218         }
3219 }
3220
3221
3222 void BufferView::Pimpl::hfill()
3223 {
3224         if (available()) {
3225                 LyXText * lt = bv_->getLyXText();
3226                 hideCursor();
3227                 update(lt,
3228                        BufferView::SELECT
3229                        | BufferView::FITCUR);
3230                 lt->insertChar(bv_, Paragraph::META_HFILL);
3231                 update(lt,
3232                        BufferView::SELECT
3233                        | BufferView::FITCUR
3234                        | BufferView::CHANGE);
3235         }
3236 }
3237
3238
3239 void BufferView::Pimpl::protectedBlank(LyXText * lt)
3240 {
3241         if (available()) {
3242                 hideCursor();
3243                 update(lt, BufferView::SELECT|BufferView::FITCUR);
3244                 InsetSpecialChar * new_inset =
3245                         new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
3246 #ifdef WITH_WARNINGS
3247 #warning Why is this code different from specialChar() below? (JMarc)
3248 // the code in specialChar is a generic version of what used to exist
3249 // for other special chars. I did not merge this case because of the
3250 // call to updateInset(), but what does it do?
3251 #endif
3252                 if (!insertInset(new_inset))
3253                         delete new_inset;
3254                 else
3255                         updateInset(new_inset, true);
3256         }
3257 }
3258
3259
3260 void BufferView::Pimpl::specialChar(InsetSpecialChar::Kind kind)
3261 {
3262         if (available()) {
3263                 LyXText * lt = bv_->getLyXText();
3264                 
3265                 hideCursor();
3266                 update(lt, BufferView::SELECT|BufferView::FITCUR);
3267                 InsetSpecialChar * new_inset = 
3268                         new InsetSpecialChar(kind);
3269                 insertInset(new_inset);
3270         }
3271 }
3272
3273
3274 void BufferView::Pimpl::smartQuote()
3275 {
3276         char c;
3277         LyXText * lt = bv_->getLyXText();
3278
3279         if (lt->cursor.pos())
3280                 c = lt->cursor.par()->getChar(lt->cursor.pos() - 1);
3281         else 
3282                 c = ' ';
3283
3284         hideCursor();
3285
3286         LyXLayout const & style = textclasslist.Style(
3287                 bv_->buffer()->params.textclass,
3288                 lt->cursor.par()->getLayout());
3289         
3290         if (style.pass_thru ||
3291                 (!insertInset(new InsetQuotes(c, bv_->buffer()->params))))
3292                 Dispatch(LFUN_SELFINSERT, "\"");
3293 }
3294
3295
3296 void BufferView::Pimpl::insertAndEditInset(Inset * inset)
3297 {
3298         if (insertInset(inset))
3299                 inset->edit(bv_);
3300         else
3301                 delete inset;
3302 }
3303
3304  
3305 // Open and lock an updatable inset
3306 bool BufferView::Pimpl::open_new_inset(UpdatableInset * new_inset, bool behind)
3307 {
3308         LyXText * lt = bv_->getLyXText();
3309         
3310         beforeChange(lt);
3311         finishUndo();
3312         if (!insertInset(new_inset)) {
3313                 delete new_inset;
3314                 return false;
3315         }
3316         new_inset->edit(bv_, !behind);
3317         return true;
3318 }
3319
3320
3321 bool BufferView::Pimpl::insertInset(Inset * inset, string const & lout)
3322 {
3323         // if we are in a locking inset we should try to insert the
3324         // inset there otherwise this is a illegal function now
3325         if (bv_->theLockingInset()) {
3326                 if (bv_->theLockingInset()->insetAllowed(inset))
3327                     return bv_->theLockingInset()->insertInset(bv_, inset);
3328                 return false;
3329         }
3330
3331         // not quite sure if we want this...
3332         setCursorParUndo(bv_);
3333         freezeUndo();
3334         
3335         beforeChange(bv_->text);
3336         if (!lout.empty()) {
3337                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3338                 bv_->text->breakParagraph(bv_);
3339                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3340
3341                 if (bv_->text->cursor.par()->size()) {
3342                         bv_->text->cursorLeft(bv_);
3343                         
3344                         bv_->text->breakParagraph(bv_);
3345                         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3346                 }
3347
3348                 pair<bool, LyXTextClass::size_type> lres =
3349                         textclasslist.NumberOfLayout(buffer_->params
3350                                                      .textclass, lout);
3351                 LyXTextClass::size_type lay;
3352                 if (lres.first != false) {
3353                         // layout found
3354                         lay = lres.second;
3355                 } else {
3356                         // layout not fount using default "Standard" (0)
3357                         lay = 0;
3358                 }
3359                  
3360                 bv_->text->setLayout(bv_, lay);
3361                 
3362                 bv_->text->setParagraph(bv_, 0, 0,
3363                                    0, 0,
3364                                    VSpace(VSpace::NONE), VSpace(VSpace::NONE),
3365                                    LYX_ALIGN_LAYOUT, 
3366                                    string(),
3367                                    0);
3368                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3369 #ifndef NO_LATEX
3370                 bv_->text->current_font.setLatex(LyXFont::OFF);
3371 #endif
3372         }
3373         
3374         bv_->text->insertInset(bv_, inset);
3375         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3376
3377         unFreezeUndo();
3378         return true;
3379 }
3380
3381
3382 void BufferView::Pimpl::updateInset(Inset * inset, bool mark_dirty)
3383 {
3384         if (!inset)
3385                 return;
3386
3387         // first check for locking insets
3388         if (bv_->theLockingInset()) {
3389                 if (bv_->theLockingInset() == inset) {
3390                         if (bv_->text->updateInset(bv_, inset)) {
3391                                 update();
3392                                 if (mark_dirty) {
3393                                         buffer_->markDirty();
3394                                 }
3395                                 updateScrollbar();
3396                                 return;
3397                         }
3398                 } else if (bv_->theLockingInset()->updateInsetInInset(bv_, inset)) {
3399                         if (bv_->text->updateInset(bv_,
3400                                                    bv_->theLockingInset())) {
3401                                 update();
3402                                 if (mark_dirty){
3403                                         buffer_->markDirty();
3404                                 }
3405                                 updateScrollbar();
3406                                 return;
3407                         }
3408                 }
3409         }
3410   
3411         // then check the current buffer
3412         if (available()) {
3413                 hideCursor();
3414                 update(bv_->text, BufferView::UPDATE);
3415                 if (bv_->text->updateInset(bv_, inset)) {
3416                         if (mark_dirty) {
3417                                 update(bv_->text,
3418                                        BufferView::SELECT
3419                                        | BufferView::FITCUR
3420                                        | BufferView::CHANGE);
3421                         } else {
3422                                 update(bv_->text, SELECT);
3423                         }
3424                         return;
3425                 }
3426         }
3427 }
3428
3429
3430 void BufferView::Pimpl::gotoInset(vector<Inset::Code> const & codes,
3431                                   bool same_content)
3432 {
3433         if (!available()) return;
3434         
3435         hideCursor();
3436         beforeChange(bv_->text);
3437         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3438         
3439         string contents;
3440         if (same_content &&
3441             bv_->text->cursor.par()->getChar(bv_->text->cursor.pos()) == Paragraph::META_INSET) {
3442                 Inset const * inset = bv_->text->cursor.par()->getInset(bv_->text->cursor.pos());
3443                 if (find(codes.begin(), codes.end(), inset->lyxCode())
3444                     != codes.end())
3445                         contents =
3446                                 static_cast<InsetCommand const *>(inset)->getContents();
3447         }
3448         
3449         if (!bv_->text->gotoNextInset(bv_, codes, contents)) {
3450                 if (bv_->text->cursor.pos() 
3451                     || bv_->text->cursor.par() != bv_->text->firstParagraph()) {
3452                         LyXCursor tmp = bv_->text->cursor;
3453                         bv_->text->cursor.par(bv_->text->firstParagraph());
3454                         bv_->text->cursor.pos(0);
3455                         if (!bv_->text->gotoNextInset(bv_, codes, contents)) {
3456                                 bv_->text->cursor = tmp;
3457                                 bv_->owner()->message(_("No more insets"));
3458                         }
3459                 } else {
3460                         bv_->owner()->message(_("No more insets"));
3461                 }
3462         }
3463         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3464         bv_->text->selection.cursor = bv_->text->cursor;
3465 }
3466
3467
3468 void BufferView::Pimpl::gotoInset(Inset::Code code, bool same_content)
3469 {
3470         gotoInset(vector<Inset::Code>(1, code), same_content);
3471 }