]> git.lyx.org Git - features.git/blob - src/BufferView_pimpl.C
use stringstream, remove some old footnote handling
[features.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 "font.h"
20 #include "bufferview_funcs.h"
21 #include "TextCache.h"
22 #include "bufferlist.h"
23 #include "lyx_gui_misc.h"
24 #include "lyxrc.h"
25 #include "intl.h"
26 #include "support/LAssert.h"
27 #include "frontends/Dialogs.h"
28 #include "insets/insetbib.h"
29 #include "insets/insettext.h"
30 /// added for Dispatch functions
31 #include "lyx_cb.h"
32 #include "frontends/FileDialog.h"
33 #include "lyx_main.h"
34 #include "FloatList.h"
35 #include "support/filetools.h"
36 #include "support/lyxfunctional.h"
37 #include "insets/inseturl.h"
38 #include "insets/insetlatexaccent.h"
39 #include "insets/insettoc.h"
40 #include "insets/insetref.h"
41 #include "insets/insetparent.h"
42 #include "insets/insetindex.h"
43 #include "insets/insetinclude.h"
44 #include "insets/insetcite.h"
45 #include "insets/insetert.h"
46 #include "insets/insetexternal.h"
47 #include "insets/insetgraphics.h"
48 #include "insets/insetfoot.h"
49 #include "insets/insetmarginal.h"
50 #include "insets/insetminipage.h"
51 #include "insets/insetfloat.h"
52 #include "insets/insetlist.h"
53 #include "insets/insettabular.h"
54 #include "insets/insettheorem.h"
55 #include "insets/insetcaption.h"
56 #include "insets/insetfloatlist.h"
57 #include "mathed/formulamacro.h"
58 #include "gettext.h"
59
60 extern LyXTextClass::size_type current_layout;
61 extern int greek_kb_flag;
62
63 using std::vector;
64 using std::find_if;
65 using std::pair;
66 using std::endl;
67 using std::make_pair;
68 using std::min;
69 using SigC::slot;
70
71 /* the selection possible is needed, that only motion events are 
72  * used, where the bottom press event was on the drawing area too */
73 bool selection_possible = false;
74
75 extern BufferList bufferlist;
76 extern char ascii_type;
77
78 extern bool math_insert_greek(BufferView *, char);
79 extern void sigchldhandler(pid_t pid, int * status);
80 extern int bibitemMaxWidth(BufferView *, LyXFont const &);
81
82 const unsigned int saved_positions_num = 20;
83
84 namespace {
85
86 inline
87 void waitForX()
88 {
89         XSync(fl_get_display(), 0);
90 }
91
92
93 void SetXtermCursor(Window win)
94 {
95         static Cursor cursor;
96         static bool cursor_undefined = true;
97         if (cursor_undefined){
98                 cursor = XCreateFontCursor(fl_get_display(), XC_xterm);
99                 XFlush(fl_get_display());
100                 cursor_undefined = false;
101         }
102         XDefineCursor(fl_get_display(), win, cursor);
103         XFlush(fl_get_display());
104 }
105
106 } // anon namespace
107
108
109 BufferView::Pimpl::Pimpl(BufferView * b, LyXView * o,
110              int xpos, int ypos, int width, int height)
111         : bv_(b), owner_(o), buffer_(0),
112           current_scrollbar_value(0), cursor_timeout(400),
113           workarea_(xpos, ypos, width, height), using_xterm_cursor(false)
114 {
115         // Setup the signals
116         workarea_.scrollCB.connect(slot(this, &BufferView::Pimpl::scrollCB));
117         workarea_.workAreaExpose
118                 .connect(slot(this, &BufferView::Pimpl::workAreaExpose));
119         workarea_.workAreaEnter
120                 .connect(slot(this, &BufferView::Pimpl::enterView));
121         workarea_.workAreaLeave
122                 .connect(slot(this, &BufferView::Pimpl::leaveView));
123         workarea_.workAreaButtonPress
124                 .connect(slot(this, &BufferView::Pimpl::workAreaButtonPress));
125         workarea_.workAreaButtonRelease
126                 .connect(slot(this,
127                               &BufferView::Pimpl::workAreaButtonRelease));
128         workarea_.workAreaMotionNotify
129                 .connect(slot(this, &BufferView::Pimpl::workAreaMotionNotify));
130         workarea_.workAreaDoubleClick
131                 .connect(slot(this, &BufferView::Pimpl::doubleClick));
132         workarea_.workAreaTripleClick
133                 .connect(slot(this, &BufferView::Pimpl::tripleClick));
134         workarea_.workAreaKeyPress
135                 .connect(slot(this, &BufferView::Pimpl::workAreaKeyPress));
136         
137         //screen_ = 0;
138
139         cursor_timeout.timeout.connect(slot(this,
140                                             &BufferView::Pimpl::cursorToggle));
141         //current_scrollbar_value = 0;
142         cursor_timeout.start();
143         workarea_.setFocus();
144         //using_xterm_cursor = false;
145         saved_positions.resize(saved_positions_num);
146 }
147
148
149 Painter & BufferView::Pimpl::painter() 
150 {
151         return workarea_.getPainter();
152 }
153
154
155 void BufferView::Pimpl::buffer(Buffer * b)
156 {
157         lyxerr[Debug::INFO] << "Setting buffer in BufferView ("
158                             << b << ")" << endl;
159         if (buffer_) {
160                 bv_->insetSleep();
161                 buffer_->delUser(bv_);
162
163                 // Put the old text into the TextCache, but
164                 // only if the buffer is still loaded.
165                 // Also set the owner of the test to 0
166                 //              bv_->text->owner(0);
167                 textcache.add(buffer_, workarea_.workWidth(), bv_->text);
168                 if (lyxerr.debugging())
169                         textcache.show(lyxerr, "BufferView::buffer");
170                 
171                 bv_->text = 0;
172         }
173
174         // Set current buffer
175         buffer_ = b;
176
177         if (bufferlist.getState() == BufferList::CLOSING) return;
178         
179         // Nuke old image
180         // screen is always deleted when the buffer is changed.
181         screen_.reset(0);
182         //delete screen_;
183         //screen_ = 0;
184
185         // If we are closing the buffer, use the first buffer as current
186         if (!buffer_) {
187                 buffer_ = bufferlist.first();
188         }
189
190         if (buffer_) {
191                 lyxerr[Debug::INFO] << "Buffer addr: " << buffer_ << endl;
192                 buffer_->addUser(bv_);
193                 // If we don't have a text object for this, we make one
194                 if (bv_->text == 0) {
195                         resizeCurrentBuffer();
196                 } else {
197                         updateScreen();
198                         updateScrollbar();
199                 }
200                 bv_->text->first = screen_->TopCursorVisible(bv_->text);
201                 owner_->updateMenubar();
202                 owner_->updateToolbar();
203                 // Similarly, buffer-dependent dialogs should be updated or
204                 // hidden. This should go here because some dialogs (eg ToC)
205                 // require bv_->text.
206                 owner_->getDialogs()->updateBufferDependent(true);
207                 redraw();
208                 bv_->insetWakeup();
209         } else {
210                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
211                 owner_->updateMenubar();
212                 owner_->updateToolbar();
213                 owner_->getDialogs()->hideBufferDependent();
214                 updateScrollbar();
215                 workarea_.redraw();
216
217                 // Also remove all remaining text's from the testcache.
218                 // (there should not be any!) (if there is any it is a
219                 // bug!)
220                 if (lyxerr.debugging())
221                         textcache.show(lyxerr, "buffer delete all");
222                 textcache.clear();
223         }
224         // should update layoutchoice even if we don't have a buffer.
225         owner_->updateLayoutChoice();
226
227         owner_->updateWindowTitle();
228 }
229
230
231 void BufferView::Pimpl::resize(int xpos, int ypos, int width, int height)
232 {
233         workarea_.resize(xpos, ypos, width, height);
234         update(bv_->text, SELECT);
235         redraw();
236 }
237
238
239 void BufferView::Pimpl::resize()
240 {
241         if (buffer_)
242                 resizeCurrentBuffer();
243 }
244
245
246 void BufferView::Pimpl::redraw()
247 {
248         lyxerr[Debug::INFO] << "BufferView::redraw()" << endl;
249         workarea_.redraw();
250 }
251
252
253 bool BufferView::Pimpl::fitCursor(LyXText * text)
254 {
255         lyx::Assert(screen_.get());
256  
257         bool ret = screen_->FitCursor(text, bv_);
258         if (ret)
259             updateScrollbar();
260         return ret;
261 }
262
263
264 void BufferView::Pimpl::redoCurrentBuffer()
265 {
266         lyxerr[Debug::INFO] << "BufferView::redoCurrentBuffer" << endl;
267         if (buffer_ && bv_->text) {
268                 resize();
269                 owner_->updateLayoutChoice();
270         }
271 }
272
273
274 int BufferView::Pimpl::resizeCurrentBuffer()
275 {
276         lyxerr[Debug::INFO] << "resizeCurrentBuffer" << endl;
277         
278         LyXParagraph * par = 0;
279         LyXParagraph * selstartpar = 0;
280         LyXParagraph * selendpar = 0;
281         UpdatableInset * the_locking_inset = 0;
282         
283         LyXParagraph::size_type pos = 0;
284         LyXParagraph::size_type selstartpos = 0;
285         LyXParagraph::size_type selendpos = 0;
286         bool selection = false;
287         bool mark_set  = false;
288
289         ProhibitInput(bv_);
290
291         owner_->message(_("Formatting document..."));
292
293         if (bv_->text) {
294                 par = bv_->text->cursor.par();
295                 pos = bv_->text->cursor.pos();
296                 selstartpar = bv_->text->sel_start_cursor.par();
297                 selstartpos = bv_->text->sel_start_cursor.pos();
298                 selendpar = bv_->text->sel_end_cursor.par();
299                 selendpos = bv_->text->sel_end_cursor.pos();
300                 selection = bv_->text->selection;
301                 mark_set = bv_->text->mark_set;
302                 the_locking_inset = bv_->text->the_locking_inset;
303                 delete bv_->text;
304                 bv_->text = new LyXText(bv_);
305         } else {
306                 // See if we have a text in TextCache that fits
307                 // the new buffer_ with the correct width.
308                 bv_->text = textcache.findFit(buffer_, workarea_.workWidth());
309                 if (bv_->text) {
310                         if (lyxerr.debugging()) {
311                                 lyxerr << "Found a LyXText that fits:\n";
312                                 textcache.show(lyxerr, make_pair(buffer_, make_pair(workarea_.workWidth(), bv_->text)));
313                         }
314                         // Set the owner of the newly found text
315                         //      bv_->text->owner(bv_);
316                         if (lyxerr.debugging())
317                                 textcache.show(lyxerr, "resizeCurrentBuffer");
318                 } else {
319                         bv_->text = new LyXText(bv_);
320                 }
321         }
322         updateScreen();
323
324         if (par) {
325                 bv_->text->selection = true;
326                 /* at this point just to avoid the Delete-Empty-Paragraph
327                  * Mechanism when setting the cursor */
328                 bv_->text->mark_set = mark_set;
329                 if (selection) {
330                         bv_->text->SetCursor(bv_, selstartpar, selstartpos);
331                         bv_->text->sel_cursor = bv_->text->cursor;
332                         bv_->text->SetCursor(bv_, selendpar, selendpos);
333                         bv_->text->SetSelection(bv_);
334                         bv_->text->SetCursor(bv_, par, pos);
335                 } else {
336                         bv_->text->SetCursor(bv_, par, pos);
337                         bv_->text->sel_cursor = bv_->text->cursor;
338                         bv_->text->selection = false;
339                 }
340                 // remake the inset locking
341                 bv_->text->the_locking_inset = the_locking_inset;
342         }
343         bv_->text->first = screen_->TopCursorVisible(bv_->text);
344         buffer_->resizeInsets(bv_);
345         // this will scroll the screen such that the cursor becomes visible
346         updateScrollbar();
347         redraw();
348
349         bv_->setState();
350         AllowInput(bv_);
351
352         /// get rid of the splash screen if it's not gone already
353         owner_->getDialogs()->destroySplash();
354  
355         return 0;
356 }
357
358
359 void BufferView::Pimpl::updateScreen()
360 {
361         // Regenerate the screen.
362         screen_.reset(new LyXScreen(workarea_));
363 }
364
365
366 void BufferView::Pimpl::updateScrollbar()
367 {
368         /* If the text is smaller than the working area, the scrollbar
369          * maximum must be the working area height. No scrolling will 
370          * be possible */
371
372         if (!buffer_) {
373                 workarea_.setScrollbar(0, 1.0);
374                 return;
375         }
376         
377         static unsigned long max2 = 0;
378         static unsigned long height2 = 0;
379
380         unsigned long cbth = 0;
381         long cbsf = 0;
382
383         if (bv_->text) {
384                 cbth = bv_->text->height;
385                 cbsf = bv_->text->first;
386         }
387
388         // check if anything has changed.
389         if (max2 == cbth &&
390             height2 == workarea_.height() &&
391             current_scrollbar_value == cbsf)
392                 return; // no
393         max2 = cbth;
394         height2 = workarea_.height();
395         current_scrollbar_value = cbsf;
396
397         if (cbth <= height2) { // text is smaller than screen
398                 workarea_.setScrollbar(0, 1.0); // right?
399                 return;
400         }
401
402         long maximum_height = workarea_.height() * 3 / 4 + cbth;
403         long value = cbsf;
404
405         // set the scrollbar
406         double hfloat = workarea_.height();
407         double maxfloat = maximum_height;
408
409         float slider_size = 0.0;
410         int slider_value = value;
411
412         workarea_.setScrollbarBounds(0, bv_->text->height - workarea_.height());
413         double const lineh = bv_->text->DefaultHeight();
414         workarea_.setScrollbarIncrements(lineh);
415         if (maxfloat > 0.0) {
416                 if ((hfloat / maxfloat) * float(height2) < 3)
417                         slider_size = 3.0/float(height2);
418                 else
419                         slider_size = hfloat / maxfloat;
420         } else
421                 slider_size = hfloat;
422
423         workarea_.setScrollbar(slider_value, slider_size / workarea_.height());
424 }
425
426
427 // Callback for scrollbar slider
428 void BufferView::Pimpl::scrollCB(double value)
429 {
430         if (!buffer_) return;
431
432         current_scrollbar_value = long(value);
433         if (current_scrollbar_value < 0)
434                 current_scrollbar_value = 0;
435    
436         if (!screen_.get())
437                 return;
438
439         screen_->Draw(bv_->text, bv_, current_scrollbar_value);
440
441         if (!lyxrc.cursor_follows_scrollbar) {
442                 waitForX();
443                 return;
444         }
445  
446         LyXText * vbt = bv_->text;
447  
448         int const height = vbt->DefaultHeight();
449         int const first = static_cast<int>((bv_->text->first + height));
450         int const last = static_cast<int>((bv_->text->first + workarea_.height() - height));
451
452         if (vbt->cursor.y() < first)
453                 vbt->SetCursorFromCoordinates(bv_, 0, first);
454         else if (vbt->cursor.y() > last)
455                 vbt->SetCursorFromCoordinates(bv_, 0, last);
456
457         waitForX();
458 }
459
460
461 int BufferView::Pimpl::scrollUp(long time)
462 {
463         if (!buffer_) return 0;
464         if (!screen_.get()) return 0;
465    
466         double value = workarea_.getScrollbarValue();
467    
468         if (value == 0) return 0;
469
470         float add_value =  (bv_->text->DefaultHeight()
471                             + float(time) * float(time) * 0.125);
472    
473         if (add_value > workarea_.height())
474                 add_value = float(workarea_.height() -
475                                   bv_->text->DefaultHeight());
476    
477         value -= add_value;
478
479         if (value < 0)
480                 value = 0;
481    
482         workarea_.setScrollbarValue(value);
483    
484         scrollCB(value); 
485         return 0;
486 }
487
488
489 int BufferView::Pimpl::scrollDown(long time)
490 {
491         if (!buffer_) return 0;
492         if (!screen_.get()) return 0;
493    
494         double value = workarea_.getScrollbarValue();
495         pair<float, float> p = workarea_.getScrollbarBounds();
496         double max = p.second;
497         
498         if (value == max) return 0;
499
500         float add_value =  (bv_->text->DefaultHeight()
501                             + float(time) * float(time) * 0.125);
502    
503         if (add_value > workarea_.height())
504                 add_value = float(workarea_.height() -
505                                   bv_->text->DefaultHeight());
506    
507         value += add_value;
508    
509         if (value > max)
510                 value = max;
511
512         workarea_.setScrollbarValue(value);
513         
514         scrollCB(value); 
515         return 0;
516 }
517
518
519 void BufferView::Pimpl::workAreaKeyPress(KeySym keysym, unsigned int state)
520 {
521         bv_->owner()->getLyXFunc()->processKeySym(keysym, state);
522 }
523
524
525 void BufferView::Pimpl::workAreaMotionNotify(int x, int y, unsigned int state)
526 {
527         // Only use motion with button 1
528         if (!(state & Button1MotionMask))
529                 return;
530
531         if (!buffer_ || !screen_.get()) return;
532
533         // Check for inset locking
534         if (bv_->theLockingInset()) {
535                 LyXCursor cursor = bv_->text->cursor;
536                 LyXFont font = bv_->text->GetFont(bv_->buffer(),
537                                                   cursor.par(), cursor.pos());
538                 int width = bv_->theLockingInset()->width(bv_, font);
539                 int inset_x = font.isVisibleRightToLeft()
540                         ? cursor.x() - width : cursor.x();
541                 int start_x = inset_x + bv_->theLockingInset()->scroll();
542                 bv_->theLockingInset()->
543                         InsetMotionNotify(bv_,
544                                           x - start_x,
545                                           y - cursor.y() + bv_->text->first,
546                                           state);
547                 return;
548         }
549    
550         /* The test for not selection possible is needed, that only motion events are 
551          * used, where the bottom press event was on the drawing area too */
552         if (!selection_possible)
553                 return;
554  
555         screen_->HideCursor();
556
557         bv_->text->SetCursorFromCoordinates(bv_, x, y + bv_->text->first);
558       
559         if (!bv_->text->selection)
560                 update(bv_->text, BufferView::UPDATE); // Maybe an empty line was deleted
561       
562         bv_->text->SetSelection(bv_);
563         screen_->ToggleToggle(bv_->text, bv_);
564         fitCursor(bv_->text);
565         screen_->ShowCursor(bv_->text, bv_);
566 }
567
568
569 // Single-click on work area
570 void BufferView::Pimpl::workAreaButtonPress(int xpos, int ypos,
571                                             unsigned int button)
572 {
573         last_click_x = -1;
574         last_click_y = -1;
575
576         if (!buffer_ || !screen_.get()) return;
577
578         Inset * inset_hit = checkInsetHit(bv_->text, xpos, ypos, button);
579
580         // ok ok, this is a hack.
581         if (button == 4 || button == 5) {
582                 switch (button) {
583                 case 4:
584                         scrollUp(lyxrc.wheel_jump); // default 100, set in lyxrc
585                         break;
586                 case 5:
587                         scrollDown(lyxrc.wheel_jump);
588                         break;
589                 }
590         }
591         
592         if (bv_->theLockingInset()) {
593                 // We are in inset locking mode
594                 
595                 /* Check whether the inset was hit. If not reset mode,
596                    otherwise give the event to the inset */
597                 if (inset_hit == bv_->theLockingInset()) {
598                         bv_->theLockingInset()->
599                                 InsetButtonPress(bv_,
600                                                  xpos, ypos,
601                                                  button);
602                         return;
603                 } else {
604                         bv_->unlockInset(bv_->theLockingInset());
605                 }
606         }
607         
608         if (!inset_hit)
609                 selection_possible = true;
610         screen_->HideCursor();
611
612         int const screen_first = bv_->text->first;
613         
614         // Middle button press pastes if we have a selection
615         bool paste_internally = false;
616         if (button == 2
617             && bv_->text->selection) {
618                 owner_->getLyXFunc()->Dispatch(LFUN_COPY);
619                 paste_internally = true;
620         }
621         
622         // Clear the selection
623         screen_->ToggleSelection(bv_->text, bv_);
624         bv_->text->ClearSelection(bv_);
625         bv_->text->FullRebreak(bv_);
626         screen_->Update(bv_->text, bv_);
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         bv_->text->FinishUndo();
651         bv_->text->sel_cursor = bv_->text->cursor;
652         bv_->text->cursor.x_fix(bv_->text->cursor.x());
653         
654         owner_->updateLayoutChoice();
655         if (fitCursor(bv_->text)) {
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_);
690                 screen_->ToggleSelection(text, bv_, false);
691             } else {
692                 text->SelectWord(bv_);
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->sel_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         bv_->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                         bv_->text->SetCursorParUndo(bv_->buffer());
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()) == LyXParagraph::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(bv_->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) == LyXParagraph::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(bv_->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 = 0;
920         static unsigned int work_area_height = 0;
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                         // All buffers need a resize
931                         bufferlist.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(bv_->text);
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()) screen_->Update(bv_->text, bv_);
969 }
970
971 // Values used when calling update:
972 // -3 - update
973 // -2 - update, move sel_cursor if selection, fitcursor
974 // -1 - update, move sel_cursor if selection, fitcursor, mark dirty
975 //  0 - update, move sel_cursor if selection, fitcursor 
976 //  1 - update, move sel_cursor if selection, fitcursor, mark dirty
977 //  3 - update, move sel_cursor if selection
978 //
979 // update -
980 // a simple redraw of the parts that need refresh
981 //
982 // move sel_cursor if selection -
983 // the text's sel_cursor is moved if there is selection is progress
984 //
985 // fitcursor -
986 // fitCursor() is called and the scrollbar updated
987 //
988 // mark dirty -
989 // the buffer is marked dirty.
990 //
991 // enum {
992 //       UPDATE = 0,
993 //       SELECT = 1,
994 //       FITCUR = 2,
995 //       CHANGE = 4 
996 // };
997 //
998 // UPDATE_ONLY = UPDATE;
999 // UPDATE_SELECT = UPDATE | SELECT;
1000 // UPDATE_SELECT_MOVE = UPDATE | SELECT | FITCUR;
1001 // UPDATE_SELECT_MOVE_AFTER_CHANGE = UPDATE | SELECT | FITCUR | CHANGE;
1002 //
1003 // update(-3) -> update(0)         -> update(0) -> update(UPDATE)
1004 // update(-2) -> update(1 + 2)     -> update(3) -> update(SELECT|FITCUR)
1005 // update(-1) -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1006 // update(1)  -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1007 // update(3)  -> update(1)         -> update(1) -> update(SELECT)
1008
1009 void BufferView::Pimpl::update(LyXText * text, BufferView::UpdateCodes f)
1010 {
1011         owner_->updateLayoutChoice();
1012
1013         if (!text->selection && (f & SELECT)) {
1014                 text->sel_cursor = text->cursor;
1015         }
1016
1017         text->FullRebreak(bv_);
1018
1019         if (text->inset_owner) {
1020             text->inset_owner->SetUpdateStatus(bv_, InsetText::NONE);
1021             bv_->updateInset(text->inset_owner, true);
1022         } else
1023             update();
1024
1025         if ((f & FITCUR)) {
1026                 fitCursor(text);
1027         }
1028
1029         if ((f & CHANGE)) {
1030                 buffer_->markDirty();
1031         }
1032 }
1033
1034
1035 // Callback for cursor timer
1036 void BufferView::Pimpl::cursorToggle()
1037 {
1038         // Quite a nice place for asyncron Inset updating, isn't it?
1039         // Actually no! This is run even if no buffer exist... so (Lgb)
1040         if (!buffer_) {
1041                 cursor_timeout.restart();
1042                 return;
1043         }
1044  
1045         int status = 1;
1046         int pid = waitpid(static_cast<pid_t>(0), &status, WNOHANG);
1047         if (pid == -1) // error find out what is wrong
1048                 ; // ignore it for now.
1049         else if (pid > 0)
1050                 sigchldhandler(pid, &status);
1051
1052         updatelist.update(bv_);
1053         
1054         if (!screen_.get()) {
1055                 cursor_timeout.restart();
1056                 return;
1057         }
1058
1059         if (!bv_->theLockingInset()) {
1060                 screen_->CursorToggle(bv_->text, bv_);
1061         } else {
1062                 bv_->theLockingInset()->ToggleInsetCursor(bv_);
1063         }
1064         
1065         cursor_timeout.restart();
1066 }
1067
1068
1069 void BufferView::Pimpl::cursorPrevious(LyXText * text)
1070 {
1071         if (!text->cursor.row()->previous())
1072                 return;
1073         
1074         int y = text->first;
1075         if (text->inset_owner)
1076                 y += bv_->text->first;
1077         Row * cursorrow = text->cursor.row();
1078         text->SetCursorFromCoordinates(bv_, bv_->text->cursor.x_fix(), y);
1079         bv_->text->FinishUndo();
1080         // This is to allow jumping over large insets
1081         if ((cursorrow == text->cursor.row()))
1082                 text->CursorUp(bv_);
1083         
1084         if (text->inset_owner ||
1085             text->cursor.row()->height() < workarea_.height())
1086                 screen_->Draw(bv_->text, bv_,
1087                               text->cursor.y()
1088                               - text->cursor.row()->baseline()
1089                               + text->cursor.row()->height()
1090                               - workarea_.height() + 1 );
1091         updateScrollbar();
1092 }
1093
1094
1095 void BufferView::Pimpl::cursorNext(LyXText * text)
1096 {
1097         if (!text->cursor.row()->next())
1098                 return;
1099         
1100         int y = text->first + workarea_.height();
1101 //      if (text->inset_owner)
1102 //              y += bv_->text->first;
1103         text->GetRowNearY(y);
1104     
1105         Row * cursorrow = text->cursor.row();
1106         text->SetCursorFromCoordinates(bv_, text->cursor.x_fix(), y); // + workarea_->height());
1107         bv_->text->FinishUndo();
1108         // This is to allow jumping over large insets
1109         if ((cursorrow == bv_->text->cursor.row()))
1110                 text->CursorDown(bv_);
1111         
1112         if (text->inset_owner ||
1113             text->cursor.row()->height() < workarea_.height())
1114                 screen_->Draw(bv_->text, bv_, text->cursor.y() -
1115                               text->cursor.row()->baseline());
1116         updateScrollbar();
1117 }
1118
1119
1120 bool BufferView::Pimpl::available() const
1121 {
1122         if (buffer_ && bv_->text) return true;
1123         return false;
1124 }
1125
1126
1127 void BufferView::Pimpl::beforeChange(LyXText * text)
1128 {
1129         toggleSelection();
1130         text->ClearSelection(bv_);
1131 }
1132
1133
1134 void BufferView::Pimpl::savePosition(unsigned int i)
1135 {
1136         if (i >= saved_positions_num)
1137                 return;
1138         saved_positions[i] = Position(buffer_->fileName(),
1139                                       bv_->text->cursor.par()->id(),
1140                                       bv_->text->cursor.pos());
1141         if (i > 0) {
1142                 string const str = _("Saved bookmark") + ' ' + tostr(i);
1143                 owner_->message(str);
1144         }
1145 }
1146
1147
1148 void BufferView::Pimpl::restorePosition(unsigned int i)
1149 {
1150         if (i >= saved_positions_num)
1151                 return;
1152
1153         string const fname = saved_positions[i].filename;
1154
1155         beforeChange(bv_->text);
1156
1157         if (fname != buffer_->fileName()) {
1158                 Buffer * b = bufferlist.exists(fname) ?
1159                         bufferlist.getBuffer(fname) :
1160                         bufferlist.loadLyXFile(fname); // don't ask, just load it
1161                 if (b != 0 ) buffer(b);
1162         }
1163
1164         LyXParagraph * par = bv_->text->GetParFromID(saved_positions[i].par_id);
1165         if (!par)
1166                 return;
1167
1168         bv_->text->SetCursor(bv_, par,
1169                              min(par->size(), saved_positions[i].par_pos));
1170
1171         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1172         if (i > 0) {
1173                 string const str = _("Moved to bookmark") + ' ' + tostr(i);
1174                 owner_->message(str);
1175         }
1176 }
1177
1178
1179 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
1180 {
1181         if (i >= saved_positions_num)
1182                 return false;
1183
1184         return !saved_positions[i].filename.empty();
1185 }
1186
1187
1188 void BufferView::Pimpl::setState()
1189 {
1190         if (!lyxrc.rtl_support)
1191                 return;
1192
1193         LyXText * text = bv_->getLyXText();
1194         if (text->real_current_font.isRightToLeft() &&
1195             text->real_current_font.latex() != LyXFont::ON) {
1196                 if (owner_->getIntl()->keymap == Intl::PRIMARY)
1197                         owner_->getIntl()->KeyMapSec();
1198         } else {
1199                 if (owner_->getIntl()->keymap == Intl::SECONDARY)
1200                         owner_->getIntl()->KeyMapPrim();
1201         }
1202 }
1203
1204
1205 void BufferView::Pimpl::insetSleep()
1206 {
1207         if (bv_->theLockingInset() && !bv_->inset_slept) {
1208                 bv_->theLockingInset()->GetCursorPos(bv_, bv_->slx, bv_->sly);
1209                 bv_->theLockingInset()->InsetUnlock(bv_);
1210                 bv_->inset_slept = true;
1211         }
1212 }
1213
1214
1215 void BufferView::Pimpl::insetWakeup()
1216 {
1217         if (bv_->theLockingInset() && bv_->inset_slept) {
1218                 bv_->theLockingInset()->Edit(bv_, bv_->slx, bv_->sly, 0);
1219                 bv_->inset_slept = false;
1220         }
1221 }
1222
1223
1224 void BufferView::Pimpl::insetUnlock()
1225 {
1226         if (bv_->theLockingInset()) {
1227                 if (!bv_->inset_slept)
1228                         bv_->theLockingInset()->InsetUnlock(bv_);
1229                 bv_->theLockingInset(0);
1230                 bv_->text->FinishUndo();
1231                 bv_->inset_slept = false;
1232         }
1233 }
1234
1235
1236 bool BufferView::Pimpl::focus() const
1237 {
1238         return workarea_.hasFocus();
1239 }
1240
1241
1242 void BufferView::Pimpl::focus(bool f)
1243 {
1244         if (f) workarea_.setFocus();
1245 }
1246
1247
1248 bool BufferView::Pimpl::active() const
1249 {
1250         return workarea_.active();
1251 }
1252
1253
1254 bool BufferView::Pimpl::belowMouse() const 
1255 {
1256         return workarea_.belowMouse();
1257 }
1258
1259
1260 void BufferView::Pimpl::showCursor()
1261 {
1262         if (screen_.get())
1263                 screen_->ShowCursor(bv_->text, bv_);
1264 }
1265
1266
1267 void BufferView::Pimpl::hideCursor()
1268 {
1269         if (screen_.get())
1270                 screen_->HideCursor();
1271 }
1272
1273
1274 void BufferView::Pimpl::toggleSelection(bool b)
1275 {
1276         if (screen_.get())
1277                 screen_->ToggleSelection(bv_->text, bv_, b);
1278 }
1279
1280
1281 void BufferView::Pimpl::toggleToggle()
1282 {
1283         if (screen_.get())
1284                 screen_->ToggleToggle(bv_->text, bv_);
1285 }
1286
1287
1288 void BufferView::Pimpl::center() 
1289 {
1290         beforeChange(bv_->text);
1291         if (bv_->text->cursor.y() > static_cast<int>((workarea_.height() / 2))) {
1292                 screen_->Draw(bv_->text, bv_, bv_->text->cursor.y() - workarea_.height() / 2);
1293         } else {
1294                 screen_->Draw(bv_->text, bv_, 0);
1295         }
1296         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1297         redraw();
1298 }
1299
1300
1301 void BufferView::Pimpl::pasteClipboard(bool asPara) 
1302 {
1303         if (!buffer_) return;
1304
1305         screen_->HideCursor();
1306         beforeChange(bv_->text);
1307         
1308         string const clip(workarea_.getClipboard());
1309         
1310         if (clip.empty()) return;
1311
1312         if (asPara) {
1313                 bv_->text->InsertStringB(bv_, clip);
1314         } else {
1315                 bv_->text->InsertStringA(bv_, clip);
1316         }
1317         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1318 }
1319
1320
1321 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
1322 {
1323         workarea_.putClipboard(stuff);
1324 }
1325
1326
1327 /*
1328  * Dispatch functions for actions which can be valid for BufferView->text
1329  * and/or InsetText->text!!!
1330  */
1331 static LyXText * TEXT(BufferView * bv) { return bv->getLyXText(); }
1332
1333 inline
1334 void BufferView::Pimpl::moveCursorUpdate(bool selecting)
1335 {
1336         if (selecting || TEXT(bv_)->mark_set) {
1337                 TEXT(bv_)->SetSelection(bv_);
1338                 if (TEXT(bv_)->bv_owner)
1339                         bv_->toggleToggle();
1340         }
1341         update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR);
1342         showCursor();
1343         
1344         /* ---> Everytime the cursor is moved, show the current font state. */
1345         // should this too me moved out of this func?
1346         //owner->showState();
1347         bv_->setState();
1348 }
1349
1350
1351 Inset * BufferView::Pimpl::getInsetByCode(Inset::Code code)
1352 {
1353         LyXCursor cursor = TEXT(bv_)->cursor;
1354         Buffer::inset_iterator it =
1355                 find_if(Buffer::inset_iterator(
1356                         cursor.par(), cursor.pos()),
1357                         buffer_->inset_iterator_end(),
1358                         lyx::compare_memfun(&Inset::LyxCode, code)
1359                         );
1360         return it != buffer_->inset_iterator_end() ? (*it) : 0;
1361 }
1362
1363
1364 void BufferView::Pimpl::MenuInsertLyXFile(string const & filen)
1365 {
1366         string filename = filen;
1367
1368         if (filename.empty()) {
1369                 // Launch a file browser
1370                 string initpath = lyxrc.document_path;
1371
1372                 if (available()) {
1373                         string const trypath = owner_->buffer()->filepath;
1374                         // If directory is writeable, use this as default.
1375                         if (IsDirWriteable(trypath) == 1)
1376                                 initpath = trypath;
1377                 }
1378
1379                 FileDialog fileDlg(bv_->owner(), _("Select LyX document to insert"),
1380                         LFUN_FILE_INSERT,
1381                         make_pair(string(_("Documents")), string(lyxrc.document_path)),
1382                         make_pair(string(_("Examples")), string(AddPath(system_lyxdir, "examples"))));
1383
1384                 FileDialog::Result result = fileDlg.Select(initpath, _("*.lyx| LyX Documents (*.lyx)"));
1385  
1386                 if (result.first == FileDialog::Later)
1387                         return;
1388
1389                 filename = result.second;
1390
1391                 // check selected filename
1392                 if (filename.empty()) {
1393                         owner_->message(_("Canceled."));
1394                         return;
1395                 }
1396         }
1397
1398         // get absolute path of file and make sure the filename ends
1399         // with .lyx
1400         filename = MakeAbsPath(filename);
1401         if (!IsLyXFilename(filename))
1402                 filename += ".lyx";
1403
1404         // Inserts document
1405         string const s1 = _("Inserting document") + ' '
1406                 + MakeDisplayPath(filename) + " ...";
1407         owner_->message(s1);
1408         bool const res = bv_->insertLyXFile(filename);
1409         if (res) {
1410                 string const str = _("Document") + ' '
1411                         + MakeDisplayPath(filename) + ' ' + _("inserted.");
1412                 owner_->message(str);
1413         } else {
1414                 string const str = _("Could not insert document") + ' '
1415                         + MakeDisplayPath(filename);
1416                 owner_->message(str);
1417         }
1418 }
1419
1420
1421 bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
1422 {
1423         switch (action) {
1424                 // --- Misc -------------------------------------------
1425         case LFUN_APPENDIX:
1426                 if (available()) {
1427                         TEXT(bv_)->toggleAppendix(bv_);
1428                         update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1429                 }
1430                 break;
1431
1432         case LFUN_TOC_INSERT:
1433         {
1434                 InsetCommandParams p;
1435                 p.setCmdName("tableofcontents");
1436                 Inset * inset = new InsetTOC(p);
1437                 if (!bv_->insertInset(inset, "Standard", true))
1438                         delete inset;
1439                 break;
1440         }
1441                 
1442         case LFUN_TABULAR_FEATURE:
1443         case LFUN_SCROLL_INSET:
1444                 // this is not handled here as this funktion is only aktive
1445                 // if we have a locking_inset and that one is (or contains)
1446                 // a tabular-inset
1447                 break;
1448
1449         case LFUN_INSET_GRAPHICS:
1450         {
1451                 Inset * new_inset = new InsetGraphics;
1452                 if (!bv_->insertInset(new_inset)) {
1453                         delete new_inset;
1454                 } else {
1455                         // this is need because you don't use a inset->Edit()
1456                         bv_->updateInset(new_inset, true);
1457                         new_inset->Edit(bv_, 0, 0, 0);
1458                 }
1459                 break;
1460         }
1461                 
1462         case LFUN_PASTE:
1463                 bv_->paste();
1464                 setState();
1465                 break;
1466                 
1467         case LFUN_PASTESELECTION:
1468         {
1469                 bool asPara = false;
1470                 if (argument == "paragraph") asPara = true;
1471                 pasteClipboard(asPara);
1472         }
1473         break;
1474         
1475         case LFUN_CUT:
1476                 bv_->cut();
1477                 break;
1478                 
1479         case LFUN_COPY:
1480                 bv_->copy();
1481                 break;
1482                 
1483         case LFUN_LAYOUT_COPY:
1484                 bv_->copyEnvironment();
1485                 break;
1486                 
1487         case LFUN_LAYOUT_PASTE:
1488                 bv_->pasteEnvironment();
1489                 setState();
1490                 break;
1491                 
1492         case LFUN_GOTOERROR:
1493                 bv_->gotoInset(Inset::ERROR_CODE, false);
1494                 break;
1495                 
1496         case LFUN_GOTONOTE:
1497                 bv_->gotoInset(Inset::IGNORE_CODE, false);
1498                 break;
1499
1500         case LFUN_REFERENCE_GOTO:
1501         {
1502                 vector<Inset::Code> tmp;
1503                 tmp.push_back(Inset::LABEL_CODE);
1504                 tmp.push_back(Inset::REF_CODE);
1505                 bv_->gotoInset(tmp, true);
1506                 break;
1507         }
1508
1509         case LFUN_HYPHENATION:
1510                 bv_->hyphenationPoint();
1511                 break;
1512                 
1513         case LFUN_LDOTS:
1514                 bv_->ldots();
1515                 break;
1516                 
1517         case LFUN_END_OF_SENTENCE:
1518                 bv_->endOfSentenceDot();
1519                 break;
1520
1521         case LFUN_MENU_SEPARATOR:
1522                 bv_->menuSeparator();
1523                 break;
1524                 
1525         case LFUN_HFILL:
1526                 bv_->hfill();
1527                 break;
1528                 
1529         case LFUN_DEPTH:
1530                 changeDepth(bv_, TEXT(bv_), 0);
1531                 break;
1532                 
1533         case LFUN_DEPTH_MIN:
1534                 changeDepth(bv_, TEXT(bv_), -1);
1535                 break;
1536                 
1537         case LFUN_DEPTH_PLUS:
1538                 changeDepth(bv_, TEXT(bv_), 1);
1539                 break;
1540                 
1541         case LFUN_FREE:
1542                 owner_->getDialogs()->setUserFreeFont();
1543                 break;
1544                 
1545         case LFUN_TEX:
1546                 Tex(bv_);
1547                 setState();
1548                 owner_->showState();
1549                 break;
1550
1551         case LFUN_FILE_INSERT:
1552         {
1553                 MenuInsertLyXFile(argument);
1554         }
1555         break;
1556         
1557         case LFUN_FILE_INSERT_ASCII_PARA:
1558                 InsertAsciiFile(bv_, argument, true);
1559                 break;
1560
1561         case LFUN_FILE_INSERT_ASCII:
1562                 InsertAsciiFile(bv_, argument, false);
1563                 break;
1564                 
1565         case LFUN_LAYOUT:
1566         {
1567                 lyxerr.debug() << "LFUN_LAYOUT: (arg) "
1568                                << argument << endl;
1569                 
1570                 // Derive layout number from given argument (string)
1571                 // and current buffer's textclass (number). */    
1572                 LyXTextClassList::ClassList::size_type tclass =
1573                         buffer_->params.textclass;
1574                 pair <bool, LyXTextClass::size_type> layout = 
1575                         textclasslist.NumberOfLayout(tclass, argument);
1576
1577                 // If the entry is obsolete, use the new one instead.
1578                 if (layout.first) {
1579                         string obs = textclasslist.Style(tclass,layout.second)
1580                                 .obsoleted_by();
1581                         if (!obs.empty()) 
1582                                 layout = 
1583                                         textclasslist.NumberOfLayout(tclass, obs);
1584                 }
1585
1586                 // see if we found the layout number:
1587                 if (!layout.first) {
1588                         owner_->getLyXFunc()->setErrorMessage(
1589                                 string(N_("Layout ")) + argument +
1590                                 N_(" not known"));
1591                         break;
1592                 }
1593
1594                 if (current_layout != layout.second) {
1595                         hideCursor();
1596                         current_layout = layout.second;
1597                         update(TEXT(bv_),
1598                                BufferView::SELECT|BufferView::FITCUR);
1599                         TEXT(bv_)->SetLayout(bv_, layout.second);
1600                         owner_->setLayout(layout.second);
1601                         update(TEXT(bv_),
1602                                BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1603                         setState();
1604                 }
1605         }
1606         break;
1607
1608         case LFUN_LANGUAGE:
1609                 Lang(bv_, argument);
1610                 setState();
1611                 owner_->showState();
1612                 break;
1613
1614         case LFUN_EMPH:
1615                 Emph(bv_);
1616                 owner_->showState();
1617                 break;
1618
1619         case LFUN_BOLD:
1620                 Bold(bv_);
1621                 owner_->showState();
1622                 break;
1623                 
1624         case LFUN_NOUN:
1625                 Noun(bv_);
1626                 owner_->showState();
1627                 break;
1628                 
1629         case LFUN_CODE:
1630                 Code(bv_);
1631                 owner_->showState();
1632                 break;
1633                 
1634         case LFUN_SANS:
1635                 Sans(bv_);
1636                 owner_->showState();
1637                 break;
1638                 
1639         case LFUN_ROMAN:
1640                 Roman(bv_);
1641                 owner_->showState();
1642                 break;
1643                 
1644         case LFUN_DEFAULT:
1645                 StyleReset(bv_);
1646                 owner_->showState();
1647                 break;
1648                 
1649         case LFUN_UNDERLINE:
1650                 Underline(bv_);
1651                 owner_->showState();
1652                 break;
1653                 
1654         case LFUN_FONT_SIZE:
1655                 FontSize(bv_, argument);
1656                 owner_->showState();
1657                 break;
1658                 
1659         case LFUN_FONT_STATE:
1660                 owner_->getLyXFunc()->setMessage(CurrentState(bv_));
1661                 break;
1662                 
1663         case LFUN_UPCASE_WORD:
1664                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR);
1665                 TEXT(bv_)->ChangeWordCase(bv_, LyXText::text_uppercase);
1666                 if (TEXT(bv_)->inset_owner)
1667                         bv_->updateInset(TEXT(bv_)->inset_owner, true);
1668                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1669                 break;
1670                 
1671         case LFUN_LOWCASE_WORD:
1672                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR);
1673                 TEXT(bv_)->ChangeWordCase(bv_, LyXText::text_lowercase);
1674                 if (TEXT(bv_)->inset_owner)
1675                         bv_->updateInset(TEXT(bv_)->inset_owner, true);
1676                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1677                 break;
1678                 
1679         case LFUN_CAPITALIZE_WORD:
1680                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR);
1681                 TEXT(bv_)->ChangeWordCase(bv_,
1682                                              LyXText::text_capitalization);
1683                 if (TEXT(bv_)->inset_owner)
1684                         bv_->updateInset(TEXT(bv_)->inset_owner, true);
1685                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1686                 break;
1687
1688         case LFUN_TRANSPOSE_CHARS:
1689                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR);
1690                 TEXT(bv_)->TransposeChars(*bv_);
1691                 if (TEXT(bv_)->inset_owner)
1692                         bv_->updateInset(TEXT(bv_)->inset_owner, true);
1693                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1694                 break;
1695                 
1696                                           
1697         case LFUN_INSERT_LABEL:
1698                 MenuInsertLabel(bv_, argument);
1699                 break;
1700                 
1701         case LFUN_REF_INSERT:
1702                 if (argument.empty()) {
1703                         InsetCommandParams p("ref");
1704                         owner_->getDialogs()->createRef(p.getAsString());
1705                 } else {
1706                         InsetCommandParams p;
1707                         p.setFromString(argument);
1708
1709                         InsetRef * inset = new InsetRef(p, *buffer_);
1710                         if (!bv_->insertInset(inset))
1711                                 delete inset;
1712                         else
1713                                 bv_->updateInset(inset, true);
1714                 }
1715                 break;
1716
1717         case LFUN_BOOKMARK_SAVE:
1718                 savePosition(strToUnsignedInt(argument));
1719                 break;
1720
1721         case LFUN_BOOKMARK_GOTO:
1722                 restorePosition(strToUnsignedInt(argument));
1723                 break;
1724
1725         case LFUN_REF_GOTO:
1726         {
1727                 string label(argument);
1728                 if (label.empty()) {
1729                         InsetRef * inset = 
1730                                 static_cast<InsetRef*>(getInsetByCode(Inset::REF_CODE));
1731                         if (inset) {
1732                                 label = inset->getContents();
1733                                 savePosition(0);
1734                         }
1735                 }
1736                 
1737                 if (!label.empty()) {
1738                         //bv_->savePosition(0);
1739                         if (!bv_->gotoLabel(label))
1740                                 WriteAlert(_("Error"), 
1741                                            _("Couldn't find this label"), 
1742                                            _("in current document."));
1743                 }
1744         }
1745         break;
1746                 
1747                 // --- Cursor Movements -----------------------------
1748         case LFUN_RIGHT:
1749         {
1750                 bool is_rtl = TEXT(bv_)->cursor.par()->isRightToLeftPar(buffer_->params);
1751                 if (!TEXT(bv_)->mark_set)
1752                         beforeChange(TEXT(bv_));
1753                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR);
1754                 if (is_rtl)
1755                         TEXT(bv_)->CursorLeft(bv_, false);
1756                 if (TEXT(bv_)->cursor.pos() < TEXT(bv_)->cursor.par()->size()
1757                     && TEXT(bv_)->cursor.par()->GetChar(TEXT(bv_)->cursor.pos())
1758                     == LyXParagraph::META_INSET
1759                     && TEXT(bv_)->cursor.par()->GetInset(TEXT(bv_)->cursor.pos())
1760                     && TEXT(bv_)->cursor.par()->GetInset(TEXT(bv_)->cursor.pos())->Editable() == Inset::HIGHLY_EDITABLE){
1761                         Inset * tmpinset = TEXT(bv_)->cursor.par()->GetInset(TEXT(bv_)->cursor.pos());
1762                         owner_->getLyXFunc()->setMessage(tmpinset->EditMessage());
1763                         int y = 0;
1764                         if (is_rtl) {
1765                                 LyXFont const font = 
1766                                         TEXT(bv_)->GetFont(buffer_,
1767                                                            TEXT(bv_)->cursor.par(),
1768                                                            TEXT(bv_)->cursor.pos());    
1769                                 y = tmpinset->descent(bv_,font);
1770                         }
1771                         tmpinset->Edit(bv_, 0, y, 0);
1772                         break;
1773                 }
1774                 if (!is_rtl)
1775                         TEXT(bv_)->CursorRight(bv_, false);
1776                 TEXT(bv_)->FinishUndo();
1777                 moveCursorUpdate(false);
1778                 owner_->showState();
1779         }
1780         break;
1781                 
1782         case LFUN_LEFT:
1783         {
1784                 // This is soooo ugly. Isn`t it possible to make
1785                 // it simpler? (Lgb)
1786                 bool is_rtl = TEXT(bv_)->cursor.par()->isRightToLeftPar(buffer_->params);
1787                 if (!TEXT(bv_)->mark_set)
1788                         beforeChange(TEXT(bv_));
1789                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR);
1790                 LyXCursor cur = TEXT(bv_)->cursor;
1791                 if (!is_rtl)
1792                         TEXT(bv_)->CursorLeft(bv_, false);
1793                 if ((is_rtl || cur != TEXT(bv_)->cursor) && // only if really moved!
1794                     TEXT(bv_)->cursor.pos() < TEXT(bv_)->cursor.par()->size() &&
1795                     (TEXT(bv_)->cursor.par()->GetChar(TEXT(bv_)->cursor.pos()) ==
1796                      LyXParagraph::META_INSET) &&
1797                     TEXT(bv_)->cursor.par()->GetInset(TEXT(bv_)->cursor.pos()) &&
1798                     (TEXT(bv_)->cursor.par()->GetInset(TEXT(bv_)->cursor.pos())->Editable()
1799                      == Inset::HIGHLY_EDITABLE))
1800                 {
1801                         Inset * tmpinset = TEXT(bv_)->cursor.par()->GetInset(TEXT(bv_)->cursor.pos());
1802                         owner_->getLyXFunc()->setMessage(tmpinset->EditMessage());
1803                         LyXFont font = TEXT(bv_)->GetFont(buffer_,
1804                                                              TEXT(bv_)->cursor.par(),
1805                                                              TEXT(bv_)->cursor.pos());
1806                         int y = is_rtl ? 0 
1807                                 : tmpinset->descent(bv_,font);
1808                         tmpinset->Edit(bv_,
1809                                        tmpinset->x() +
1810                                        tmpinset->width(bv_,font),
1811                                        y, 0);
1812                         break;
1813                 }
1814                 if  (is_rtl)
1815                         TEXT(bv_)->CursorRight(bv_, false);
1816
1817                 TEXT(bv_)->FinishUndo();
1818                 moveCursorUpdate(false);
1819                 owner_->showState();
1820         }
1821         break;
1822                 
1823         case LFUN_UP:
1824                 if (!TEXT(bv_)->mark_set)
1825                         beforeChange(TEXT(bv_));
1826                 update(TEXT(bv_), BufferView::UPDATE);
1827                 TEXT(bv_)->CursorUp(bv_);
1828                 TEXT(bv_)->FinishUndo();
1829                 moveCursorUpdate(false);
1830                 owner_->showState();
1831                 break;
1832                 
1833         case LFUN_DOWN:
1834                 if (!TEXT(bv_)->mark_set)
1835                         beforeChange(TEXT(bv_));
1836                 update(TEXT(bv_), BufferView::UPDATE);
1837                 TEXT(bv_)->CursorDown(bv_);
1838                 TEXT(bv_)->FinishUndo();
1839                 moveCursorUpdate(false);
1840                 owner_->showState();
1841                 break;
1842
1843         case LFUN_UP_PARAGRAPH:
1844                 if (!TEXT(bv_)->mark_set)
1845                         beforeChange(TEXT(bv_));
1846                 update(TEXT(bv_), BufferView::UPDATE);
1847                 TEXT(bv_)->CursorUpParagraph(bv_);
1848                 TEXT(bv_)->FinishUndo();
1849                 moveCursorUpdate(false);
1850                 owner_->showState();
1851                 break;
1852                 
1853         case LFUN_DOWN_PARAGRAPH:
1854                 if (!TEXT(bv_)->mark_set)
1855                         beforeChange(TEXT(bv_));
1856                 update(TEXT(bv_), BufferView::UPDATE);
1857                 TEXT(bv_)->CursorDownParagraph(bv_);
1858                 TEXT(bv_)->FinishUndo();
1859                 moveCursorUpdate(false);
1860                 owner_->showState();
1861                 break;
1862                 
1863         case LFUN_PRIOR:
1864                 if (!TEXT(bv_)->mark_set)
1865                         beforeChange(TEXT(bv_));
1866                 update(TEXT(bv_), BufferView::UPDATE);
1867                 cursorPrevious(TEXT(bv_));
1868                 TEXT(bv_)->FinishUndo();
1869                 moveCursorUpdate(false);
1870                 owner_->showState();
1871                 break;
1872                 
1873         case LFUN_NEXT:
1874                 if (!TEXT(bv_)->mark_set)
1875                         beforeChange(TEXT(bv_));
1876                 update(TEXT(bv_), BufferView::UPDATE);
1877                 cursorNext(TEXT(bv_));
1878                 TEXT(bv_)->FinishUndo();
1879                 moveCursorUpdate(false);
1880                 owner_->showState();
1881                 break;
1882                 
1883         case LFUN_HOME:
1884                 if (!TEXT(bv_)->mark_set)
1885                         beforeChange(TEXT(bv_));
1886                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR);
1887                 TEXT(bv_)->CursorHome(bv_);
1888                 TEXT(bv_)->FinishUndo();
1889                 moveCursorUpdate(false);
1890                 owner_->showState();
1891                 break;
1892                 
1893         case LFUN_END:
1894                 if (!TEXT(bv_)->mark_set)
1895                         beforeChange(TEXT(bv_));
1896                 update(TEXT(bv_),
1897                        BufferView::SELECT|BufferView::FITCUR);
1898                 TEXT(bv_)->CursorEnd(bv_);
1899                 TEXT(bv_)->FinishUndo();
1900                 moveCursorUpdate(false);
1901                 owner_->showState();
1902                 break;
1903                 
1904         case LFUN_SHIFT_TAB:
1905         case LFUN_TAB:
1906                 if (!TEXT(bv_)->mark_set)
1907                         beforeChange(TEXT(bv_));
1908                 update(TEXT(bv_),
1909                        BufferView::SELECT|BufferView::FITCUR);
1910                 TEXT(bv_)->CursorTab(bv_);
1911                 TEXT(bv_)->FinishUndo();
1912                 moveCursorUpdate(false);
1913                 owner_->showState();
1914                 break;
1915                 
1916         case LFUN_WORDRIGHT:
1917                 if (!TEXT(bv_)->mark_set)
1918                         beforeChange(TEXT(bv_));
1919                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR);
1920                 if (TEXT(bv_)->cursor.par()->isRightToLeftPar(buffer_->params))
1921                         TEXT(bv_)->CursorLeftOneWord(bv_);
1922                 else
1923                         TEXT(bv_)->CursorRightOneWord(bv_);
1924                 TEXT(bv_)->FinishUndo();
1925                 moveCursorUpdate(false);
1926                 owner_->showState();
1927                 break;
1928                 
1929         case LFUN_WORDLEFT:
1930                 if (!TEXT(bv_)->mark_set)
1931                         beforeChange(TEXT(bv_));
1932                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR);
1933                 if (TEXT(bv_)->cursor.par()->isRightToLeftPar(buffer_->params))
1934                         TEXT(bv_)->CursorRightOneWord(bv_);
1935                 else
1936                         TEXT(bv_)->CursorLeftOneWord(bv_);
1937                 TEXT(bv_)->FinishUndo();
1938                 moveCursorUpdate(false);
1939                 owner_->showState();
1940                 break;
1941                 
1942         case LFUN_BEGINNINGBUF:
1943                 if (!TEXT(bv_)->mark_set)
1944                         beforeChange(TEXT(bv_));
1945                 update(TEXT(bv_),
1946                        BufferView::SELECT|BufferView::FITCUR);
1947                 TEXT(bv_)->CursorTop(bv_);
1948                 TEXT(bv_)->FinishUndo();
1949                 moveCursorUpdate(false);
1950                 owner_->showState();
1951                 break;
1952                 
1953         case LFUN_ENDBUF:
1954                 if (!TEXT(bv_)->mark_set)
1955                         beforeChange(TEXT(bv_));
1956                 update(TEXT(bv_),
1957                        BufferView::SELECT|BufferView::FITCUR);
1958                 TEXT(bv_)->CursorBottom(bv_);
1959                 TEXT(bv_)->FinishUndo();
1960                 moveCursorUpdate(false);
1961                 owner_->showState();
1962                 break;
1963
1964       
1965                 /* cursor selection ---------------------------- */
1966         case LFUN_RIGHTSEL:
1967                 update(TEXT(bv_),
1968                        BufferView::SELECT|BufferView::FITCUR);
1969                 if (TEXT(bv_)->cursor.par()->isRightToLeftPar(buffer_->params))
1970                         TEXT(bv_)->CursorLeft(bv_);
1971                 else
1972                         TEXT(bv_)->CursorRight(bv_);
1973                 TEXT(bv_)->FinishUndo();
1974                 moveCursorUpdate(true);
1975                 owner_->showState();
1976                 break;
1977                 
1978         case LFUN_LEFTSEL:
1979                 update(TEXT(bv_),
1980                        BufferView::SELECT|BufferView::FITCUR);
1981                 if (TEXT(bv_)->cursor.par()->isRightToLeftPar(buffer_->params))
1982                         TEXT(bv_)->CursorRight(bv_);
1983                 else
1984                         TEXT(bv_)->CursorLeft(bv_);
1985                 TEXT(bv_)->FinishUndo();
1986                 moveCursorUpdate(true);
1987                 owner_->showState();
1988                 break;
1989                 
1990         case LFUN_UPSEL:
1991                 update(TEXT(bv_),
1992                        BufferView::SELECT|BufferView::FITCUR);
1993                 TEXT(bv_)->CursorUp(bv_);
1994                 TEXT(bv_)->FinishUndo();
1995                 moveCursorUpdate(true);
1996                 owner_->showState();
1997                 break;
1998                 
1999         case LFUN_DOWNSEL:
2000                 update(TEXT(bv_),
2001                        BufferView::SELECT|BufferView::FITCUR);
2002                 TEXT(bv_)->CursorDown(bv_);
2003                 TEXT(bv_)->FinishUndo();
2004                 moveCursorUpdate(true);
2005                 owner_->showState();
2006                 break;
2007
2008         case LFUN_UP_PARAGRAPHSEL:
2009                 update(TEXT(bv_),
2010                        BufferView::SELECT|BufferView::FITCUR);
2011                 TEXT(bv_)->CursorUpParagraph(bv_);
2012                 TEXT(bv_)->FinishUndo();
2013                 moveCursorUpdate(true);
2014                 owner_->showState();
2015                 break;
2016                 
2017         case LFUN_DOWN_PARAGRAPHSEL:
2018                 update(TEXT(bv_),
2019                        BufferView::SELECT|BufferView::FITCUR);
2020                 TEXT(bv_)->CursorDownParagraph(bv_);
2021                 TEXT(bv_)->FinishUndo();
2022                 moveCursorUpdate(true);
2023                 owner_->showState();
2024                 break;
2025                 
2026         case LFUN_PRIORSEL:
2027                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR);
2028                 cursorPrevious(TEXT(bv_));
2029                 TEXT(bv_)->FinishUndo();
2030                 moveCursorUpdate(true);
2031                 owner_->showState();
2032                 break;
2033                 
2034         case LFUN_NEXTSEL:
2035                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR);
2036                 cursorNext(TEXT(bv_));
2037                 TEXT(bv_)->FinishUndo();
2038                 moveCursorUpdate(true);
2039                 owner_->showState();
2040                 break;
2041                 
2042         case LFUN_HOMESEL:
2043                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR);
2044                 TEXT(bv_)->CursorHome(bv_);
2045                 TEXT(bv_)->FinishUndo();
2046                 moveCursorUpdate(true);
2047                 owner_->showState();
2048                 break;
2049                 
2050         case LFUN_ENDSEL:
2051                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR);
2052                 TEXT(bv_)->CursorEnd(bv_);
2053                 TEXT(bv_)->FinishUndo();
2054                 moveCursorUpdate(true);
2055                 owner_->showState();
2056                 break;
2057                 
2058         case LFUN_WORDRIGHTSEL:
2059                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR);
2060                 if (TEXT(bv_)->cursor.par()->isRightToLeftPar(buffer_->params))
2061                         TEXT(bv_)->CursorLeftOneWord(bv_);
2062                 else
2063                         TEXT(bv_)->CursorRightOneWord(bv_);
2064                 TEXT(bv_)->FinishUndo();
2065                 moveCursorUpdate(true);
2066                 owner_->showState();
2067                 break;
2068                 
2069         case LFUN_WORDLEFTSEL:
2070                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR);
2071                 if (TEXT(bv_)->cursor.par()->isRightToLeftPar(buffer_->params))
2072                         TEXT(bv_)->CursorRightOneWord(bv_);
2073                 else
2074                         TEXT(bv_)->CursorLeftOneWord(bv_);
2075                 TEXT(bv_)->FinishUndo();
2076                 moveCursorUpdate(true);
2077                 owner_->showState();
2078                 break;
2079                 
2080         case LFUN_BEGINNINGBUFSEL:
2081                 if (TEXT(bv_)->inset_owner)
2082                         break;
2083                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR);
2084                 TEXT(bv_)->CursorTop(bv_);
2085                 TEXT(bv_)->FinishUndo();
2086                 moveCursorUpdate(true);
2087                 owner_->showState();
2088                 break;
2089                 
2090         case LFUN_ENDBUFSEL:
2091                 if (TEXT(bv_)->inset_owner)
2092                         break;
2093                 update(TEXT(bv_),
2094                        BufferView::SELECT|BufferView::FITCUR);
2095                 TEXT(bv_)->CursorBottom(bv_);
2096                 TEXT(bv_)->FinishUndo();
2097                 moveCursorUpdate(true);
2098                 owner_->showState();
2099                 break;
2100
2101                 // --- text changing commands ------------------------
2102         case LFUN_BREAKLINE:
2103                 beforeChange(TEXT(bv_));
2104                 TEXT(bv_)->InsertChar(bv_, LyXParagraph::META_NEWLINE);
2105                 update(TEXT(bv_),
2106                        BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2107                 moveCursorUpdate(false);
2108                 break;
2109                 
2110         case LFUN_PROTECTEDSPACE:
2111         {
2112                 LyXLayout const & style = textclasslist
2113                         .Style(buffer_->params.textclass,
2114                                TEXT(bv_)->cursor.par()->GetLayout());
2115
2116                 if (style.free_spacing) {
2117                         TEXT(bv_)->InsertChar(bv_, ' ');
2118                         update(TEXT(bv_),
2119                                BufferView::SELECT
2120                                | BufferView::FITCUR
2121                                | BufferView::CHANGE);
2122                 } else {
2123                         bv_->protectedBlank(TEXT(bv_));
2124                 }
2125                 moveCursorUpdate(false);
2126         }
2127         break;
2128                 
2129         case LFUN_SETMARK:
2130                 if (TEXT(bv_)->mark_set) {
2131                         beforeChange(TEXT(bv_));
2132                         update(TEXT(bv_),
2133                                BufferView::SELECT|BufferView::FITCUR);
2134                         owner_->getLyXFunc()->setMessage(N_("Mark removed"));
2135                 } else {
2136                         beforeChange(TEXT(bv_));
2137                         TEXT(bv_)->mark_set = 1;
2138                         update(TEXT(bv_),
2139                                BufferView::SELECT|BufferView::FITCUR);
2140                         owner_->getLyXFunc()->setMessage(N_("Mark set"));
2141                 }
2142                 TEXT(bv_)->sel_cursor = TEXT(bv_)->cursor;
2143                 break;
2144                 
2145         case LFUN_DELETE:
2146                 if (!TEXT(bv_)->selection) {
2147                         TEXT(bv_)->Delete(bv_);
2148                         TEXT(bv_)->sel_cursor = 
2149                                 TEXT(bv_)->cursor;
2150                         update(TEXT(bv_),
2151                                BufferView::SELECT
2152                                | BufferView::FITCUR
2153                                | BufferView::CHANGE);
2154                         // It is possible to make it a lot faster still
2155                         // just comment out the line below...
2156                         showCursor();
2157                 } else {
2158                         bv_->cut();
2159                 }
2160                 moveCursorUpdate(false);
2161                 owner_->showState();
2162                 setState();
2163                 break;
2164
2165         case LFUN_DELETE_SKIP:
2166         {
2167                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
2168                 
2169                 LyXCursor cursor = TEXT(bv_)->cursor;
2170
2171                 if (!TEXT(bv_)->selection) {
2172                         if (cursor.pos() == cursor.par()->size()) {
2173                                 TEXT(bv_)->CursorRight(bv_);
2174                                 cursor = TEXT(bv_)->cursor;
2175                                 if (cursor.pos() == 0
2176                                     && !(cursor.par()->params.spaceTop()
2177                                          == VSpace (VSpace::NONE))) {
2178                                         TEXT(bv_)->SetParagraph
2179                                                 (bv_,
2180                                                  cursor.par()->params.lineTop(),
2181                                                  cursor.par()->params.lineBottom(),
2182                                                  cursor.par()->params.pagebreakTop(), 
2183                                                  cursor.par()->params.pagebreakBottom(),
2184                                                  VSpace(VSpace::NONE), 
2185                                                  cursor.par()->params.spaceBottom(),
2186                                                  cursor.par()->params.align(), 
2187                                                  cursor.par()->params.labelWidthString(), 0);
2188                                         TEXT(bv_)->CursorLeft(bv_);
2189                                         update(TEXT(bv_), 
2190                                                BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2191                                 } else {
2192                                         TEXT(bv_)->CursorLeft(bv_);
2193                                         TEXT(bv_)->Delete(bv_);
2194                                         TEXT(bv_)->sel_cursor = 
2195                                                 TEXT(bv_)->cursor;
2196                                         update(TEXT(bv_),
2197                                                BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2198                                 }
2199                         } else {
2200                                 TEXT(bv_)->Delete(bv_);
2201                                 TEXT(bv_)->sel_cursor = 
2202                                         TEXT(bv_)->cursor;
2203                                 update(TEXT(bv_),
2204                                        BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2205                         }
2206                 } else {
2207                         bv_->cut();
2208                 }
2209         }
2210         break;
2211
2212         /* -------> Delete word forward. */
2213         case LFUN_DELETE_WORD_FORWARD:
2214                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR);
2215                 TEXT(bv_)->DeleteWordForward(bv_);
2216                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2217                 moveCursorUpdate(false);
2218                 owner_->showState();
2219                 break;
2220
2221                 /* -------> Delete word backward. */
2222         case LFUN_DELETE_WORD_BACKWARD:
2223                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR);
2224                 TEXT(bv_)->DeleteWordBackward(bv_);
2225                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2226                 moveCursorUpdate(false);
2227                 owner_->showState();
2228                 break;
2229                 
2230                 /* -------> Kill to end of line. */
2231         case LFUN_DELETE_LINE_FORWARD:
2232                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR);
2233                 TEXT(bv_)->DeleteLineForward(bv_);
2234                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2235                 moveCursorUpdate(false);
2236                 break;
2237                 
2238                 /* -------> Set mark off. */
2239         case LFUN_MARK_OFF:
2240                 beforeChange(TEXT(bv_));
2241                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR);
2242                 TEXT(bv_)->sel_cursor = TEXT(bv_)->cursor;
2243                 owner_->getLyXFunc()->setMessage(N_("Mark off"));
2244                 break;
2245
2246                 /* -------> Set mark on. */
2247         case LFUN_MARK_ON:
2248                 beforeChange(TEXT(bv_));
2249                 TEXT(bv_)->mark_set = 1;
2250                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR);
2251                 TEXT(bv_)->sel_cursor = TEXT(bv_)->cursor;
2252                 owner_->getLyXFunc()->setMessage(N_("Mark on"));
2253                 break;
2254                 
2255         case LFUN_BACKSPACE:
2256         {
2257                 if (!TEXT(bv_)->selection) {
2258                         if (owner_->getIntl()->getTrans().backspace()) {
2259                                 TEXT(bv_)->Backspace(bv_);
2260                                 TEXT(bv_)->sel_cursor = 
2261                                         TEXT(bv_)->cursor;
2262                                 update(TEXT(bv_),
2263                                        BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2264                                 // It is possible to make it a lot faster still
2265                                 // just comment out the line below...
2266                                 showCursor();
2267                         }
2268                 } else {
2269                         bv_->cut();
2270                 }
2271                 owner_->showState();
2272                 setState();
2273         }
2274         break;
2275
2276         case LFUN_BACKSPACE_SKIP:
2277         {
2278                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
2279                 
2280                 LyXCursor cursor = TEXT(bv_)->cursor;
2281                 
2282                 if (!TEXT(bv_)->selection) {
2283                         if (cursor.pos() == 0 
2284                             && !(cursor.par()->params.spaceTop() 
2285                                  == VSpace (VSpace::NONE))) {
2286                                 TEXT(bv_)->SetParagraph 
2287                                         (bv_,
2288                                          cursor.par()->params.lineTop(),      
2289                                          cursor.par()->params.lineBottom(),
2290                                          cursor.par()->params.pagebreakTop(), 
2291                                          cursor.par()->params.pagebreakBottom(),
2292                                          VSpace(VSpace::NONE), cursor.par()->params.spaceBottom(),
2293                                          cursor.par()->params.align(), 
2294                                          cursor.par()->params.labelWidthString(), 0);
2295                                 update(TEXT(bv_),
2296                                        BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2297                         } else {
2298                                 TEXT(bv_)->Backspace(bv_);
2299                                 TEXT(bv_)->sel_cursor 
2300                                         = cursor;
2301                                 update(TEXT(bv_),
2302                                        BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2303                         }
2304                 } else
2305                         bv_->cut();
2306         }
2307         break;
2308
2309         case LFUN_BREAKPARAGRAPH:
2310         {
2311                 beforeChange(TEXT(bv_));
2312                 TEXT(bv_)->BreakParagraph(bv_, 0);
2313                 update(TEXT(bv_),
2314                        BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2315                 TEXT(bv_)->sel_cursor = TEXT(bv_)->cursor;
2316                 setState();
2317                 owner_->showState();
2318                 break;
2319         }
2320
2321         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
2322         {
2323                 beforeChange(TEXT(bv_));
2324                 TEXT(bv_)->BreakParagraph(bv_, 1);
2325                 update(TEXT(bv_),
2326                        BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2327                 TEXT(bv_)->sel_cursor = TEXT(bv_)->cursor;
2328                 setState();
2329                 owner_->showState();
2330                 break;
2331         }
2332         
2333         case LFUN_BREAKPARAGRAPH_SKIP:
2334         {
2335                 // When at the beginning of a paragraph, remove
2336                 // indentation and add a "defskip" at the top.
2337                 // Otherwise, do the same as LFUN_BREAKPARAGRAPH.
2338                 
2339                 LyXCursor cursor = TEXT(bv_)->cursor;
2340                 
2341                 beforeChange(TEXT(bv_));
2342                 if (cursor.pos() == 0) {
2343                         if (cursor.par()->params.spaceTop() == VSpace(VSpace::NONE)) {
2344                                 TEXT(bv_)->SetParagraph
2345                                         (bv_,
2346                                          cursor.par()->params.lineTop(),      
2347                                          cursor.par()->params.lineBottom(),
2348                                          cursor.par()->params.pagebreakTop(), 
2349                                          cursor.par()->params.pagebreakBottom(),
2350                                          VSpace(VSpace::DEFSKIP), cursor.par()->params.spaceBottom(),
2351                                          cursor.par()->params.align(), 
2352                                          cursor.par()->params.labelWidthString(), 1);
2353                                 //update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2354                         } 
2355                 }
2356                 else {
2357                         TEXT(bv_)->BreakParagraph(bv_, 0);
2358                         //update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2359                 }
2360
2361                 update(TEXT(bv_),
2362                        BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2363                 TEXT(bv_)->sel_cursor = cursor;
2364                 setState();
2365                 owner_->showState();
2366         }
2367         break;
2368
2369         case LFUN_PARAGRAPH_SPACING:
2370         {
2371                 LyXParagraph * par = TEXT(bv_)->cursor.par();
2372                 Spacing::Space cur_spacing = par->params.spacing().getSpace();
2373                 float cur_value = 1.0;
2374                 if (cur_spacing == Spacing::Other) {
2375                         cur_value = par->params.spacing().getValue();
2376                 }
2377                 
2378                 istringstream istr(argument.c_str());
2379
2380                 string tmp;
2381                 istr >> tmp;
2382                 Spacing::Space new_spacing = cur_spacing;
2383                 float new_value = cur_value;
2384                 if (tmp.empty()) {
2385                         lyxerr << "Missing argument to `paragraph-spacing'"
2386                                << endl;
2387                 } else if (tmp == "single") {
2388                         new_spacing = Spacing::Single;
2389                 } else if (tmp == "onehalf") {
2390                         new_spacing = Spacing::Onehalf;
2391                 } else if (tmp == "double") {
2392                         new_spacing = Spacing::Double;
2393                 } else if (tmp == "other") {
2394                         new_spacing = Spacing::Other;
2395                         float tmpval = 0.0;
2396                         istr >> tmpval;
2397                         lyxerr << "new_value = " << tmpval << endl;
2398                         if (tmpval != 0.0)
2399                                 new_value = tmpval;
2400                 } else if (tmp == "default") {
2401                         new_spacing = Spacing::Default;
2402                 } else {
2403                         lyxerr << _("Unknown spacing argument: ")
2404                                << argument << endl;
2405                 }
2406                 if (cur_spacing != new_spacing || cur_value != new_value) {
2407                         par->params.spacing(Spacing(new_spacing, new_value));
2408                         TEXT(bv_)->RedoParagraph(bv_);
2409                         update(TEXT(bv_),
2410                                BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2411                 }
2412         }
2413         break;
2414         
2415         case LFUN_QUOTE:
2416                 beforeChange(TEXT(bv_));
2417                 TEXT(bv_)->InsertChar(bv_, '\"');  // This " matches the single quote in the code
2418                 update(TEXT(bv_), BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2419                 moveCursorUpdate(false);
2420                 break;
2421
2422         case LFUN_HTMLURL:
2423         case LFUN_URL:
2424         {
2425                 InsetCommandParams p;
2426                 if (action == LFUN_HTMLURL)
2427                         p.setCmdName("htmlurl");
2428                 else
2429                         p.setCmdName("url");
2430                 owner_->getDialogs()->createUrl( p.getAsString() );
2431         }
2432         break;
2433                     
2434         case LFUN_INSERT_URL:
2435         {
2436                 InsetCommandParams p;
2437                 p.setFromString( argument );
2438
2439                 InsetUrl * inset = new InsetUrl( p );
2440                 if (!bv_->insertInset(inset))
2441                         delete inset;
2442                 else
2443                         bv_->updateInset( inset, true );
2444         }
2445         break;
2446                     
2447         case LFUN_INSET_TEXT:
2448         {
2449                 InsetText * new_inset = new InsetText;
2450                 if (bv_->insertInset(new_inset))
2451                         new_inset->Edit(bv_, 0, 0, 0);
2452                 else
2453                         delete new_inset;
2454         }
2455         break;
2456         
2457         case LFUN_INSET_ERT:
2458         {
2459                 InsetERT * new_inset = new InsetERT;
2460                 if (bv_->insertInset(new_inset))
2461                         new_inset->Edit(bv_, 0, 0, 0);
2462                 else
2463                         delete new_inset;
2464         }
2465         break;
2466         
2467         case LFUN_INSET_EXTERNAL:
2468         {
2469                 InsetExternal * new_inset = new InsetExternal;
2470                 if (bv_->insertInset(new_inset))
2471                         new_inset->Edit(bv_, 0, 0, 0);
2472                 else
2473                         delete new_inset;
2474         }
2475         break;
2476         
2477         case LFUN_INSET_FOOTNOTE:
2478         {
2479                 InsetFoot * new_inset = new InsetFoot;
2480                 if (bv_->insertInset(new_inset))
2481                         new_inset->Edit(bv_, 0, 0, 0);
2482                 else
2483                         delete new_inset;
2484         }
2485         break;
2486
2487         case LFUN_INSET_MARGINAL:
2488         {
2489                 InsetMarginal * new_inset = new InsetMarginal;
2490                 if (bv_->insertInset(new_inset))
2491                         new_inset->Edit(bv_, 0, 0, 0);
2492                 else
2493                         delete new_inset;
2494         }
2495         break;
2496
2497         case LFUN_INSET_MINIPAGE:
2498         {
2499                 InsetMinipage * new_inset = new InsetMinipage;
2500                 if (bv_->insertInset(new_inset))
2501                         new_inset->Edit(bv_, 0, 0, 0);
2502                 else
2503                         delete new_inset;
2504         }
2505         break;
2506
2507         case LFUN_INSET_FLOAT:
2508         {
2509                 // check if the float type exist
2510                 if (floatList.typeExist(argument)) {
2511                         InsetFloat * new_inset = new InsetFloat(argument);
2512                         if (bv_->insertInset(new_inset))
2513                                 new_inset->Edit(bv_, 0, 0, 0);
2514                         else
2515                                 delete new_inset;
2516                 } else {
2517                         lyxerr << "Non-existant float type: "
2518                                << argument << endl;
2519                 }
2520                 
2521         }
2522         break;
2523
2524         case LFUN_INSET_LIST:
2525         {
2526                 InsetList * new_inset = new InsetList;
2527                 if (bv_->insertInset(new_inset))
2528                         new_inset->Edit(bv_, 0, 0, 0);
2529                 else
2530                         delete new_inset;
2531         }
2532         break;
2533
2534         case LFUN_INSET_THEOREM:
2535         {
2536                 InsetTheorem * new_inset = new InsetTheorem;
2537                 if (bv_->insertInset(new_inset))
2538                         new_inset->Edit(bv_, 0, 0, 0);
2539                 else
2540                         delete new_inset;
2541         }
2542         break;
2543
2544         case LFUN_INSET_CAPTION:
2545         {
2546                 // Do we have a locking inset...
2547                 if (bv_->theLockingInset()) {
2548                         lyxerr << "Locking inset code: "
2549                                << static_cast<int>(bv_->theLockingInset()->LyxCode());
2550                         InsetCaption * new_inset = new InsetCaption;
2551                         new_inset->setOwner(bv_->theLockingInset());
2552                         new_inset->SetAutoBreakRows(true);
2553                         new_inset->SetDrawFrame(0, InsetText::LOCKED);
2554                         new_inset->SetFrameColor(0, LColor::footnoteframe);
2555                         if (bv_->insertInset(new_inset))
2556                                 new_inset->Edit(bv_, 0, 0, 0);
2557                         else
2558                                 delete new_inset;
2559                 }
2560         }
2561         break;
2562         
2563         case LFUN_INSET_TABULAR:
2564         {
2565                 int r = 2, c = 2;
2566                 if (!argument.empty())
2567                         ::sscanf(argument.c_str(),"%d%d", &r, &c);
2568                 InsetTabular * new_inset =
2569                         new InsetTabular(*buffer_, r, c);
2570                 bool rtl =
2571                         TEXT(bv_)->real_current_font.isRightToLeft();
2572                 if (!bv_->open_new_inset(new_inset, rtl))
2573                         delete new_inset;
2574         }
2575         break;
2576
2577         // --- lyxserver commands ----------------------------
2578
2579         case LFUN_CHARATCURSOR:
2580         {
2581                 LyXParagraph::size_type pos = TEXT(bv_)->cursor.pos();
2582                 if (pos < TEXT(bv_)->cursor.par()->size())
2583                         owner_->getLyXFunc()->setMessage(
2584                                 tostr(TEXT(bv_)->cursor.par()->GetChar(pos)));
2585                 else
2586                         owner_->getLyXFunc()->setMessage("EOF");
2587         }
2588         break;
2589         
2590         case LFUN_GETXY:
2591                 owner_->getLyXFunc()->setMessage(tostr(TEXT(bv_)->cursor.x())
2592                                                  + ' '
2593                                                  + tostr(TEXT(bv_)->cursor.y()));
2594                 break;
2595                 
2596         case LFUN_SETXY:
2597         {
2598                 int x;
2599                 int y;
2600                 ::sscanf(argument.c_str(), " %d %d", &x, &y);
2601                 TEXT(bv_)->SetCursorFromCoordinates(bv_, x, y);
2602         }
2603         break;
2604         
2605         case LFUN_GETLAYOUT:
2606                 owner_->getLyXFunc()->setMessage(tostr(TEXT(bv_)->cursor.par()->layout));
2607                 break;
2608                         
2609         case LFUN_GETFONT:
2610         {
2611                 LyXFont & font = TEXT(bv_)->current_font;
2612                 if (font.shape() == LyXFont::ITALIC_SHAPE)
2613                         owner_->getLyXFunc()->setMessage("E");
2614                 else if (font.shape() == LyXFont::SMALLCAPS_SHAPE)
2615                         owner_->getLyXFunc()->setMessage("N");
2616                 else
2617                         owner_->getLyXFunc()->setMessage("0");
2618
2619         }
2620         break;
2621
2622         case LFUN_GETLATEX:
2623         {
2624                 LyXFont & font = TEXT(bv_)->current_font;
2625                 if (font.latex() == LyXFont::ON)
2626                         owner_->getLyXFunc()->setMessage("L");
2627                 else
2628                         owner_->getLyXFunc()->setMessage("0");
2629         }
2630         break;
2631
2632         // --- accented characters ---------------------------
2633                 
2634         case LFUN_UMLAUT:
2635         case LFUN_CIRCUMFLEX:
2636         case LFUN_GRAVE:
2637         case LFUN_ACUTE:
2638         case LFUN_TILDE:
2639         case LFUN_CEDILLA:
2640         case LFUN_MACRON:
2641         case LFUN_DOT:
2642         case LFUN_UNDERDOT:
2643         case LFUN_UNDERBAR:
2644         case LFUN_CARON:
2645         case LFUN_SPECIAL_CARON:
2646         case LFUN_BREVE:
2647         case LFUN_TIE:
2648         case LFUN_HUNG_UMLAUT:
2649         case LFUN_CIRCLE:
2650         case LFUN_OGONEK:
2651                 owner_->getLyXFunc()->handleKeyFunc(action);
2652                 break;
2653         
2654         // --- insert characters ----------------------------------------
2655         
2656         case LFUN_MATH_DELIM:     
2657         case LFUN_INSERT_MATRIX:
2658         {          
2659                 if (available()) { 
2660                         if (bv_->open_new_inset(new InsetFormula(false)))
2661                         {
2662                                 bv_->theLockingInset()
2663                                         ->LocalDispatch(bv_, action, argument);
2664                         }
2665                 }
2666         }          
2667         break;
2668                
2669         case LFUN_INSERT_MATH:
2670         {
2671                 if (!available())
2672                         break;
2673  
2674                 InsetFormula * f = new InsetFormula(true);
2675                 bv_->open_new_inset(f);
2676                 f->LocalDispatch(bv_, LFUN_INSERT_MATH, argument);
2677         }
2678         break;
2679         
2680         case LFUN_MATH_DISPLAY:
2681         {
2682                 if (available())
2683                         bv_->open_new_inset(new InsetFormula(true));
2684                 break;
2685         }
2686                     
2687         case LFUN_MATH_MACRO:
2688         {
2689                 if (available()) {
2690                         string s(argument);
2691                         if (s.empty())
2692                                 owner_->getLyXFunc()->setErrorMessage(N_("Missing argument"));
2693                         else {
2694                                 string const s1 = token(s, ' ', 1);
2695                                 int const na = s1.empty() ? 0 : lyx::atoi(s1);
2696                                 bv_->open_new_inset(new InsetFormulaMacro(token(s, ' ', 0), na));
2697                         }
2698                 }
2699         }
2700         break;
2701
2702         case LFUN_MATH_MODE:   // Open or create a math inset
2703         {               
2704                 if (available())
2705                         bv_->open_new_inset(new InsetFormula);
2706                 owner_->getLyXFunc()->setMessage(N_("Math editor mode"));
2707         }
2708         break;
2709           
2710         case LFUN_CITATION_INSERT:
2711         {
2712                 InsetCommandParams p;
2713                 p.setFromString( argument );
2714
2715                 InsetCitation * inset = new InsetCitation( p );
2716                 if (!bv_->insertInset(inset))
2717                         delete inset;
2718                 else
2719                         bv_->updateInset( inset, true );
2720         }
2721         break;
2722                     
2723         case LFUN_INSERT_BIBTEX:
2724         {   
2725                 // ale970405+lasgoutt970425
2726                 // The argument can be up to two tokens separated 
2727                 // by a space. The first one is the bibstyle.
2728                 string const db       = token(argument, ' ', 0);
2729                 string bibstyle = token(argument, ' ', 1);
2730                 if (bibstyle.empty())
2731                         bibstyle = "plain";
2732
2733                 InsetCommandParams p( "BibTeX", db, bibstyle );
2734                 InsetBibtex * inset = new InsetBibtex(p);
2735                 
2736                 if (bv_->insertInset(inset)) {
2737                         if (argument.empty())
2738                                 inset->Edit(bv_, 0, 0, 0);
2739                 } else
2740                         delete inset;
2741         }
2742         break;
2743                 
2744         // BibTeX data bases
2745         case LFUN_BIBDB_ADD:
2746         {
2747                 InsetBibtex * inset = 
2748                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
2749                 if (inset) {
2750                         inset->addDatabase(argument);
2751                 }
2752         }
2753         break;
2754                     
2755         case LFUN_BIBDB_DEL:
2756         {
2757                 InsetBibtex * inset = 
2758                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
2759                 if (inset) {
2760                         inset->delDatabase(argument);
2761                 }
2762         }
2763         break;
2764         
2765         case LFUN_BIBTEX_STYLE:
2766         {
2767                 InsetBibtex * inset = 
2768                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
2769                 if (inset) {
2770                         inset->setOptions(argument);
2771                 }
2772         }
2773         break;
2774                 
2775         case LFUN_INDEX_CREATE:
2776         {
2777                 InsetCommandParams p( "index" );
2778                 
2779                 if (argument.empty()) {
2780                         // Get the word immediately preceding the cursor
2781                         LyXParagraph::size_type curpos = 
2782                                 TEXT(bv_)->cursor.pos() - 1;
2783
2784                         string curstring;
2785                         if (curpos >= 0 )
2786                                 curstring = TEXT(bv_)
2787                                         ->cursor.par()->GetWord(curpos);
2788
2789                         p.setContents( curstring );
2790                 } else {
2791                         p.setContents( argument );
2792                 }
2793
2794                 owner_->getDialogs()->createIndex( p.getAsString() );
2795         }
2796         break;
2797                     
2798         case LFUN_INDEX_INSERT:
2799         {
2800                 InsetCommandParams p;
2801                 p.setFromString(argument);
2802                 InsetIndex * inset = new InsetIndex(p);
2803
2804                 if (!bv_->insertInset(inset))
2805                         delete inset;
2806                 else
2807                         bv_->updateInset(inset, true);
2808         }
2809         break;
2810                     
2811         case LFUN_INDEX_INSERT_LAST:
2812         {
2813                 // Get word immediately preceding the cursor
2814                 LyXParagraph::size_type curpos = 
2815                         TEXT(bv_)->cursor.pos() - 1;
2816                 // Can't do that at the beginning of a paragraph
2817                 if (curpos < 0) break;
2818
2819                 string const curstring(TEXT(bv_)
2820                                        ->cursor.par()->GetWord(curpos));
2821
2822                 InsetCommandParams p("index", curstring);
2823                 InsetIndex * inset = new InsetIndex(p);
2824
2825                 if (!bv_->insertInset(inset))
2826                         delete inset;
2827                 else
2828                         bv_->updateInset(inset, true);
2829         }
2830         break;
2831
2832         case LFUN_INDEX_PRINT:
2833         {
2834                 InsetCommandParams p("printindex");
2835                 Inset * inset = new InsetPrintIndex(p);
2836                 if (!bv_->insertInset(inset, "Standard", true))
2837                         delete inset;
2838         }
2839         break;
2840
2841         case LFUN_PARENTINSERT:
2842         {
2843                 lyxerr << "arg " << argument << endl;
2844                 InsetCommandParams p( "lyxparent", argument );
2845                 Inset * inset = new InsetParent(p, *buffer_);
2846                 if (!bv_->insertInset(inset, "Standard", true))
2847                         delete inset;
2848         }
2849                  
2850         break;
2851
2852         case LFUN_CHILD_INSERT:
2853         {
2854                 InsetInclude::Params p;
2855                 p.cparams.setFromString(argument);
2856                 p.masterFilename_ = buffer_->fileName();
2857
2858                 InsetInclude * inset = new InsetInclude(p);
2859                 if (!bv_->insertInset(inset))
2860                         delete inset;
2861                 else {
2862                         bv_->updateInset(inset, true);
2863                         bv_->owner()->getDialogs()->showInclude(inset);
2864                 }
2865         }
2866         break; 
2867
2868         case LFUN_FLOAT_LIST:
2869         {
2870                 // We should check the argument for validity. (Lgb)
2871                 Inset * inset = new InsetFloatList(argument);
2872                 if (!bv_->insertInset(inset, "Standard", true))
2873                         delete inset;
2874         }
2875         break;
2876         
2877         case LFUN_INSERT_NOTE:
2878                 bv_->insertNote();
2879                 break;
2880
2881         case LFUN_SELFINSERT:
2882         {
2883                 LyXFont const old_font(TEXT(bv_)->real_current_font);
2884                 for (string::size_type i = 0; i < argument.length(); ++i) {
2885                         TEXT(bv_)->InsertChar(bv_, argument[i]);
2886                         // This needs to be in the loop, or else we
2887                         // won't break lines correctly. (Asger)
2888                         update(TEXT(bv_),
2889                                BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2890                 }
2891                 TEXT(bv_)->sel_cursor = TEXT(bv_)->cursor;
2892                 moveCursorUpdate(false);
2893
2894                 // real_current_font.number can change so we need to 
2895                 // update the minibuffer
2896                 if (old_font != TEXT(bv_)->real_current_font)
2897                         owner_->showState();
2898         }
2899         break;
2900
2901         case LFUN_DATE_INSERT:  // jdblair: date-insert cmd
2902         {
2903                 struct tm * now_tm;
2904                 
2905                 time_t now_time_t = time(NULL);
2906                 now_tm = localtime(&now_time_t);
2907                 setlocale(LC_TIME, "");
2908                 string arg;
2909                 if (!argument.empty())
2910                         arg = argument;
2911                 else 
2912                         arg = lyxrc.date_insert_format;
2913                 char datetmp[32];
2914                 int const datetmp_len =
2915                         ::strftime(datetmp, 32, arg.c_str(), now_tm);
2916                 for (int i = 0; i < datetmp_len; i++) {
2917                         TEXT(bv_)->InsertChar(bv_, datetmp[i]);
2918                         update(TEXT(bv_),
2919                                BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2920                 }
2921
2922                 TEXT(bv_)->sel_cursor = TEXT(bv_)->cursor;
2923                 moveCursorUpdate(false);
2924         }
2925         break;
2926
2927         case LFUN_UNKNOWN_ACTION:
2928         {
2929                 if (!buffer_) {
2930                         owner_->getLyXFunc()->setErrorMessage(N_("No document open"));
2931                         break;
2932                 }
2933
2934                 if (buffer_->isReadonly()) {
2935                         owner_->getLyXFunc()->setErrorMessage(N_("Document is read only"));
2936                         break;
2937                 }
2938                 if (!argument.empty()) {
2939                         /* Automatically delete the currently selected
2940                          * text and replace it with what is being
2941                          * typed in now. Depends on lyxrc settings
2942                          * "auto_region_delete", which defaults to
2943                          * true (on). */
2944                 
2945                         if (lyxrc.auto_region_delete) {
2946                                 if (TEXT(bv_)->selection){
2947                                         TEXT(bv_)->CutSelection(bv_, false);
2948                                         update(TEXT(bv_),
2949                                                BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2950                                 }
2951                         }
2952                         
2953                         beforeChange(TEXT(bv_));
2954                         LyXFont const old_font(TEXT(bv_)->real_current_font);
2955                         for (string::size_type i = 0;
2956                              i < argument.length(); ++i) {
2957                                 if (greek_kb_flag) {
2958                                         if (!math_insert_greek(bv_, argument[i]))
2959                                                 owner_->getIntl()->getTrans().TranslateAndInsert(argument[i], TEXT(bv_));
2960                                 } else
2961                                         owner_->getIntl()->getTrans().TranslateAndInsert(argument[i], TEXT(bv_));
2962                         }
2963
2964                         update(TEXT(bv_),BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2965
2966                         TEXT(bv_)->sel_cursor = TEXT(bv_)->cursor;
2967                         moveCursorUpdate(false);
2968
2969                         // real_current_font.number can change so we need to
2970                         // update the minibuffer
2971                         if (old_font != TEXT(bv_)->real_current_font)
2972                                 owner_->showState();
2973                 } else {
2974                         // if we don't have an argument there was something
2975                         // strange going on so we just tell this to someone!
2976                         owner_->getLyXFunc()->setErrorMessage(N_("No argument given"));
2977                 }
2978                 break;
2979         }
2980         default:
2981                 return false;
2982         } // end of switch
2983
2984         return true;
2985 }