]> git.lyx.org Git - lyx.git/blob - src/BufferView.C
* src/insets/insetbase.h
[lyx.git] / src / BufferView.C
1 /**
2  * \file BufferView.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "BufferView.h"
18
19 #include "buffer.h"
20 #include "buffer_funcs.h"
21 #include "bufferlist.h"
22 #include "bufferparams.h"
23 #include "bufferview_funcs.h"
24 #include "coordcache.h"
25 #include "CutAndPaste.h"
26 #include "debug.h"
27 #include "dispatchresult.h"
28 #include "errorlist.h"
29 #include "factory.h"
30 #include "FloatList.h"
31 #include "funcrequest.h"
32 #include "FuncStatus.h"
33 #include "gettext.h"
34 #include "intl.h"
35 #include "insetiterator.h"
36 #include "language.h"
37 #include "LaTeXFeatures.h"
38 #include "lyx_cb.h" // added for Dispatch functions
39 #include "lyx_main.h"
40 #include "lyxfind.h"
41 #include "lyxfunc.h"
42 #include "lyxlayout.h"
43 #include "lyxtext.h"
44 #include "lyxtextclass.h"
45 #include "lyxrc.h"
46 #include "session.h"
47 #include "paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "pariterator.h"
51 #include "texrow.h"
52 #include "toc.h"
53 #include "undo.h"
54 #include "vspace.h"
55 #include "WordLangTuple.h"
56 #include "metricsinfo.h"
57
58 #include "insets/insetbibtex.h"
59 #include "insets/insetcommand.h" // ChangeRefs
60 #include "insets/insetref.h"
61 #include "insets/insettext.h"
62
63 #include "frontends/Alert.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.h"
66 #include "frontends/Selection.h"
67
68 #include "graphics/Previews.h"
69
70 #include "support/convert.h"
71 #include "support/filefilterlist.h"
72 #include "support/filetools.h"
73 #include "support/package.h"
74 #include "support/types.h"
75
76 #include <boost/bind.hpp>
77 #include <boost/current_function.hpp>
78
79 #include <functional>
80 #include <vector>
81
82
83 namespace lyx {
84
85 using support::addPath;
86 using support::bformat;
87 using support::FileFilterList;
88 using support::FileName;
89 using support::fileSearch;
90 using support::isDirWriteable;
91 using support::isFileReadable;
92 using support::makeDisplayPath;
93 using support::package;
94
95 using std::distance;
96 using std::endl;
97 using std::istringstream;
98 using std::make_pair;
99 using std::min;
100 using std::max;
101 using std::mem_fun_ref;
102 using std::string;
103 using std::vector;
104
105 namespace Alert = frontend::Alert;
106
107 namespace {
108
109 /// Return an inset of this class if it exists at the current cursor position
110 template <class T>
111 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
112 {
113         T * inset = 0;
114         DocIterator it = cur;
115         if (it.nextInset() &&
116             it.nextInset()->lyxCode() == code) {
117                 inset = static_cast<T*>(it.nextInset());
118         }
119         return inset;
120 }
121
122 } // anon namespace
123
124
125 BufferView::BufferView()
126         : width_(0), height_(0), buffer_(0), wh_(0),
127           cursor_(*this),
128           multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
129           intl_(new Intl), last_inset_(0)
130 {
131         xsel_cache_.set = false;
132         intl_->initKeyMapper(lyxrc.use_kbmap);
133 }
134
135
136 BufferView::~BufferView()
137 {
138 }
139
140
141 Buffer * BufferView::buffer() const
142 {
143         return buffer_;
144 }
145
146
147 void BufferView::setBuffer(Buffer * b)
148 {
149         lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
150                             << "[ b = " << b << "]" << endl;
151
152         if (buffer_) {
153                 // Save the actual cursor position and anchor inside the
154                 // buffer so that it can be restored in case we rechange
155                 // to this buffer later on.
156                 buffer_->saveCursor(cursor_.selectionBegin(),
157                                     cursor_.selectionEnd());
158                 // current buffer is going to be switched-off, save cursor pos
159                 LyX::ref().session().lastFilePos().save(FileName(buffer_->fileName()),
160                         boost::tie(cursor_.pit(), cursor_.pos()) );
161         }
162
163         // If we're quitting lyx, don't bother updating stuff
164         if (quitting) {
165                 buffer_ = 0;
166                 return;
167         }
168
169         // If we are closing current buffer, switch to the first in
170         // buffer list.
171         if (!b) {
172                 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
173                                     << " No Buffer!" << endl;
174                 // We are closing the buffer, use the first buffer as current
175                 buffer_ = theBufferList().first();
176         } else {
177                 // Set current buffer
178                 buffer_ = b;
179         }
180
181         // Reset old cursor
182         cursor_ = LCursor(*this);
183         anchor_ref_ = 0;
184         offset_ref_ = 0;
185
186         if (buffer_) {
187                 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
188                                     << "Buffer addr: " << buffer_ << endl;
189                 cursor_.push(buffer_->inset());
190                 cursor_.resetAnchor();
191                 buffer_->text().setCurrentFont(cursor_);
192                 if (buffer_->getCursor().size() > 0 &&
193                     buffer_->getAnchor().size() > 0)
194                 {
195                         cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
196                         cursor_.resetAnchor();
197                         cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
198                         cursor_.setSelection();
199                         theSelection().haveSelection(cursor_.selection());
200                 }
201         }
202
203         if (buffer_)
204                 updateMetrics(false);    
205
206         if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
207                 graphics::Previews::get().generateBufferPreviews(*buffer_);
208 }
209
210
211 bool BufferView::loadLyXFile(FileName const & filename, bool tolastfiles)
212 {
213         // File already open?
214         if (theBufferList().exists(filename.absFilename())) {
215                 docstring const file = makeDisplayPath(filename.absFilename(), 20);
216                 docstring text = bformat(_("The document %1$s is already "
217                                                      "loaded.\n\nDo you want to revert "
218                                                      "to the saved version?"), file);
219                 int const ret = Alert::prompt(_("Revert to saved document?"),
220                         text, 0, 1,  _("&Revert"), _("&Switch to document"));
221
222                 if (ret != 0) {
223                         setBuffer(theBufferList().getBuffer(filename.absFilename()));
224                         return true;
225                 }
226                 // FIXME: should be LFUN_REVERT
227                 if (!theBufferList().close(theBufferList().getBuffer(filename.absFilename()), false))
228                         return false;
229                 // Fall through to new load. (Asger)
230                 buffer_ = 0;
231         }
232
233         Buffer * b = 0;
234
235         if (isFileReadable(filename)) {
236                 b = theBufferList().newBuffer(filename.absFilename());
237                 if (!lyx::loadLyXFile(b, filename)) {
238                         theBufferList().release(b);
239                         return false;
240                 }
241         } else {
242                 docstring text = bformat(_("The document %1$s does not yet "
243                                                      "exist.\n\nDo you want to create "
244                                                      "a new document?"), from_utf8(filename.absFilename()));
245                 int const ret = Alert::prompt(_("Create new document?"),
246                          text, 0, 1, _("&Create"), _("Cancel"));
247
248                 if (ret == 0) {
249                         b = newFile(filename.absFilename(), string(), true);
250                         if (!b)
251                                 return false;
252                 } else
253                         return false;
254         }
255
256         setBuffer(b);
257         // Send the "errors" signal in case of parsing errors
258         b->errors("Parse");
259
260         // Update the labels and section numbering.
261         updateLabels(*buffer_);
262         // scroll to the position when the file was last closed
263         if (lyxrc.use_lastfilepos) {
264                 pit_type pit;
265                 pos_type pos;
266                 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(filename);
267                 // if successfully move to pit (returned par_id is not zero), update metrics
268                 if (moveToPosition(pit, 0, pos).get<1>()) {
269                         if (fitCursor())
270                                 updateMetrics(false);
271                 }
272         }
273
274         if (tolastfiles)
275                 LyX::ref().session().lastFiles().add(FileName(b->fileName()));
276
277         return true;
278 }
279
280
281 void BufferView::resize()
282 {
283         if (!buffer_)
284                 return;
285
286         lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
287
288         updateMetrics(false);
289         switchKeyMap();
290 }
291
292
293 bool BufferView::fitCursor()
294 {
295         if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
296                 frontend::FontMetrics const & fm =
297                         theFontMetrics(cursor_.getFont());
298                 int const asc = fm.maxAscent();
299                 int const des = fm.maxDescent();
300                 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
301                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
302                         return false;
303         }
304         center();
305         return true;
306 }
307
308
309 bool BufferView::multiParSel()
310 {
311         if (!cursor_.selection())
312                 return false;
313         bool ret = multiparsel_cache_;
314         multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
315         // Either this, or previous selection spans paragraphs
316         return ret || multiparsel_cache_;
317 }
318
319
320 bool BufferView::update(Update::flags flags)
321 {
322         // last_inset_ points to the last visited inset. This pointer may become
323         // invalid because of keyboard editing. Since all such operations
324         // causes screen update(), I reset last_inset_ to avoid such a problem.
325         last_inset_ = 0;
326         // This is close to a hot-path.
327         if (lyxerr.debugging(Debug::DEBUG)) {
328                 lyxerr[Debug::DEBUG]
329                         << BOOST_CURRENT_FUNCTION
330                         << "[fitcursor = " << (flags & Update::FitCursor)
331                         << ", forceupdate = " << (flags & Update::Force)
332                         << ", singlepar = " << (flags & Update::SinglePar)
333                         << "]  buffer: " << buffer_ << endl;
334         }
335
336         // Check needed to survive LyX startup
337         if (!buffer_)
338                 return false;
339
340         if (lyxerr.debugging(Debug::WORKAREA)) {
341                 lyxerr[Debug::WORKAREA] << "BufferView::update" << std::endl;
342         }
343
344         // Update macro store
345         buffer_->buildMacros();
346
347         // Now do the first drawing step if needed. This consists on updating
348         // the CoordCache in updateMetrics().
349         // The second drawing step is done in WorkArea::redraw() if needed.
350
351         // Case when no explicit update is requested.
352         if (!flags) {
353                 // no need to redraw anything.
354                 return false;
355         }
356
357         if (flags == Update::FitCursor) {
358                 bool const fit_cursor = fitCursor();
359                 if (fit_cursor)
360                         updateMetrics(false);
361                 // tell the frontend to update the screen if needed.
362                 return fit_cursor;
363         }
364
365         bool full_metrics = flags & Update::Force;
366         if (flags & Update::MultiParSel)
367                 full_metrics |= multiParSel();
368
369         bool const single_par = !full_metrics;
370         updateMetrics(single_par);
371
372         if (flags & Update::FitCursor && fitCursor())
373                 updateMetrics(false);
374
375         // tell the frontend to update the screen.
376         return true;
377 }
378
379
380 void BufferView::updateScrollbar()
381 {
382         if (!buffer_) {
383                 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
384                                      << " no text in updateScrollbar" << endl;
385                 scrollbarParameters_.reset();
386                 return;
387         }
388
389         LyXText & t = buffer_->text();
390         TextMetrics & tm = text_metrics_[&t];
391
392         int const parsize = int(t.paragraphs().size() - 1);
393         if (anchor_ref_ >  parsize)  {
394                 anchor_ref_ = parsize;
395                 offset_ref_ = 0;
396         }
397
398         if (lyxerr.debugging(Debug::GUI)) {
399                 lyxerr[Debug::GUI]
400                         << BOOST_CURRENT_FUNCTION
401                         << " Updating scrollbar: height: " << t.paragraphs().size()
402                         << " curr par: " << cursor_.bottom().pit()
403                         << " default height " << defaultRowHeight() << endl;
404         }
405
406         // It would be better to fix the scrollbar to understand
407         // values in [0..1] and divide everything by wh
408
409         // estimated average paragraph height:
410         if (wh_ == 0)
411                 wh_ = height_ / 4;
412
413         int h = tm.parMetrics(anchor_ref_).height();
414
415         // Normalize anchor/offset (MV):
416         while (offset_ref_ > h && anchor_ref_ < parsize) {
417                 anchor_ref_++;
418                 offset_ref_ -= h;
419                 h = tm.parMetrics(anchor_ref_).height();
420         }
421         // Look at paragraph heights on-screen
422         int sumh = 0;
423         int nh = 0;
424         for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
425                 if (sumh > height_)
426                         break;
427                 int const h2 = tm.parMetrics(pit).height();
428                 sumh += h2;
429                 nh++;
430         }
431
432         BOOST_ASSERT(nh);
433         int const hav = sumh / nh;
434         // More realistic average paragraph height
435         if (hav > wh_)
436                 wh_ = hav;
437
438         BOOST_ASSERT(h);
439         scrollbarParameters_.height = (parsize + 1) * wh_;
440         scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
441         scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
442 }
443
444
445 ScrollbarParameters const & BufferView::scrollbarParameters() const
446 {
447         return scrollbarParameters_;
448 }
449
450
451 void BufferView::scrollDocView(int value)
452 {
453         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
454                            << "[ value = " << value << "]" << endl;
455
456         if (!buffer_)
457                 return;
458
459         LyXText & t = buffer_->text();
460         TextMetrics & tm = text_metrics_[&t];
461
462         float const bar = value / float(wh_ * t.paragraphs().size());
463
464         anchor_ref_ = int(bar * t.paragraphs().size());
465         if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
466                 anchor_ref_ = int(t.paragraphs().size()) - 1;
467
468         tm.redoParagraph(anchor_ref_);
469         int const h = tm.parMetrics(anchor_ref_).height();
470         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
471         updateMetrics(false);
472 }
473
474
475 void BufferView::setCursorFromScrollbar()
476 {
477         LyXText & t = buffer_->text();
478
479         int const height = 2 * defaultRowHeight();
480         int const first = height;
481         int const last = height_ - height;
482         LCursor & cur = cursor_;
483
484         bv_funcs::CurStatus st = bv_funcs::status(this, cur);
485
486         switch (st) {
487         case bv_funcs::CUR_ABOVE:
488                 t.setCursorFromCoordinates(cur, 0, first);
489                 cur.clearSelection();
490                 break;
491         case bv_funcs::CUR_BELOW:
492                 t.setCursorFromCoordinates(cur, 0, last);
493                 cur.clearSelection();
494                 break;
495         case bv_funcs::CUR_INSIDE:
496                 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
497                 int const newy = min(last, max(y, first));
498                 if (y != newy) {
499                         cur.reset(buffer_->inset());
500                         t.setCursorFromCoordinates(cur, 0, newy);
501                 }
502         }
503 }
504
505
506 Change const BufferView::getCurrentChange() const
507 {
508         if (!cursor_.selection())
509                 return Change(Change::UNCHANGED);
510
511         DocIterator dit = cursor_.selectionBegin();
512         return dit.paragraph().lookupChange(dit.pos());
513 }
514
515
516 void BufferView::saveBookmark(bool persistent)
517 {
518         LyX::ref().session().bookmarks().save(
519                 FileName(buffer_->fileName()),
520                 cursor_.pit(),
521                 cursor_.paragraph().id(),
522                 cursor_.pos(),
523                 persistent
524         );
525         if (persistent)
526                 // emit message signal.
527                 message(_("Save bookmark"));
528 }
529
530
531 boost::tuple<pit_type, int> BufferView::moveToPosition(pit_type par_pit, int par_id, pos_type par_pos)
532 {
533         cursor_.clearSelection();
534
535         // if a valid par_id is given, try it first
536         if (par_id > 0) {
537                 ParIterator par = buffer_->getParFromID(par_id);
538                 if (par != buffer_->par_iterator_end()) {
539                         setCursor(makeDocIterator(par, min(par->size(), par_pos)));
540                         return boost::make_tuple(cursor_.pit(), par_id);
541                 }
542         }
543         // if par_id == 0, or searching through par_id failed
544         if (static_cast<size_t>(par_pit) < buffer_->paragraphs().size()) {
545                 ParIterator it = buffer_->par_iterator_begin();
546                 ParIterator const end = buffer_->par_iterator_end();
547                 for (; it != end; ++it)
548                         if (it.pit() == par_pit) {
549                                 // restored pos may be bigger than it->size
550                                 setCursor(makeDocIterator(it, min(par_pos, it->size())));
551                                 return boost::make_tuple(par_pit, it->id());
552                         }
553         }
554         // both methods fail
555         return boost::make_tuple(pit_type(0), 0);
556 }
557
558
559 void BufferView::switchKeyMap()
560 {
561         if (!lyxrc.rtl_support)
562                 return;
563
564         if (getLyXText()->real_current_font.isRightToLeft()) {
565                 if (intl_->keymap == Intl::PRIMARY)
566                         intl_->keyMapSec();
567         } else {
568                 if (intl_->keymap == Intl::SECONDARY)
569                         intl_->keyMapPrim();
570         }
571 }
572
573
574 int BufferView::workWidth() const
575 {
576         return width_;
577 }
578
579
580 void BufferView::center()
581 {
582         CursorSlice & bot = cursor_.bottom();
583         TextMetrics & tm = text_metrics_[bot.text()];
584         pit_type const pit = bot.pit();
585         tm.redoParagraph(pit);
586         ParagraphMetrics const & pm = tm.parMetrics(pit);
587         anchor_ref_ = pit;
588         offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
589                 + pm.ascent() - height_ / 2;
590 }
591
592
593 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
594 {
595         FuncStatus flag;
596
597         switch (cmd.action) {
598
599         case LFUN_UNDO:
600                 flag.enabled(!buffer_->undostack().empty());
601                 break;
602         case LFUN_REDO:
603                 flag.enabled(!buffer_->redostack().empty());
604                 break;
605         case LFUN_FILE_INSERT:
606         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
607         case LFUN_FILE_INSERT_PLAINTEXT:
608         case LFUN_BOOKMARK_SAVE:
609                 // FIXME: Actually, these LFUNS should be moved to LyXText
610                 flag.enabled(cursor_.inTexted());
611                 break;
612         case LFUN_FONT_STATE:
613         case LFUN_LABEL_INSERT:
614         case LFUN_PARAGRAPH_GOTO:
615         // FIXME handle non-trivially
616         case LFUN_OUTLINE_UP:
617         case LFUN_OUTLINE_DOWN:
618         case LFUN_OUTLINE_IN:
619         case LFUN_OUTLINE_OUT:
620         case LFUN_NOTE_NEXT:
621         case LFUN_REFERENCE_NEXT:
622         case LFUN_WORD_FIND:
623         case LFUN_WORD_REPLACE:
624         case LFUN_MARK_OFF:
625         case LFUN_MARK_ON:
626         case LFUN_MARK_TOGGLE:
627         case LFUN_SCREEN_RECENTER:
628         case LFUN_BIBTEX_DATABASE_ADD:
629         case LFUN_BIBTEX_DATABASE_DEL:
630         case LFUN_WORDS_COUNT:
631         case LFUN_NEXT_INSET_TOGGLE:
632                 flag.enabled(true);
633                 break;
634
635         case LFUN_LABEL_GOTO: {
636                 flag.enabled(!cmd.argument().empty()
637                     || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
638                 break;
639         }
640
641         case LFUN_CHANGES_TRACK:
642                 flag.enabled(true);
643                 flag.setOnOff(buffer_->params().trackChanges);
644                 break;
645
646         case LFUN_CHANGES_OUTPUT: {
647                 OutputParams runparams;
648                 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
649                 flag.enabled(buffer_ && features.isAvailable("dvipost"));
650                 flag.setOnOff(buffer_->params().outputChanges);
651                 break;
652         }
653
654         case LFUN_CHANGES_MERGE:
655         case LFUN_CHANGE_NEXT:
656         case LFUN_ALL_CHANGES_ACCEPT:
657         case LFUN_ALL_CHANGES_REJECT:
658                 // TODO: context-sensitive enabling of LFUNs
659                 // In principle, these command should only be enabled if there
660                 // is a change in the document. However, without proper
661                 // optimizations, this will inevitably result in poor performance.
662                 flag.enabled(buffer_);
663                 break;
664
665         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
666                 flag.setOnOff(buffer_->params().compressed);
667                 break;
668         }
669
670         default:
671                 flag.enabled(false);
672         }
673
674         return flag;
675 }
676
677
678 bool BufferView::dispatch(FuncRequest const & cmd)
679 {
680         //lyxerr << BOOST_CURRENT_FUNCTION
681         //       << [ cmd = " << cmd << "]" << endl;
682
683         // Make sure that the cached BufferView is correct.
684         lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
685                 << " action[" << cmd.action << ']'
686                 << " arg[" << to_utf8(cmd.argument()) << ']'
687                 << " x[" << cmd.x << ']'
688                 << " y[" << cmd.y << ']'
689                 << " button[" << cmd.button() << ']'
690                 << endl;
691
692         LCursor & cur = cursor_;
693
694         switch (cmd.action) {
695
696         case LFUN_UNDO:
697                 if (buffer_) {
698                         cur.message(_("Undo"));
699                         cur.clearSelection();
700                         if (!textUndo(*this))
701                                 cur.message(_("No further undo information"));
702                         update();
703                         switchKeyMap();
704                 }
705                 break;
706
707         case LFUN_REDO:
708                 if (buffer_) {
709                         cur.message(_("Redo"));
710                         cur.clearSelection();
711                         if (!textRedo(*this))
712                                 cur.message(_("No further redo information"));
713                         update();
714                         switchKeyMap();
715                 }
716                 break;
717
718         case LFUN_FILE_INSERT:
719                 // FIXME UNICODE
720                 menuInsertLyXFile(to_utf8(cmd.argument()));
721                 break;
722
723         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
724                 // FIXME UNICODE
725                 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
726                 break;
727
728         case LFUN_FILE_INSERT_PLAINTEXT:
729                 // FIXME UNICODE
730                 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
731                 break;
732
733         case LFUN_FONT_STATE:
734                 cur.message(cur.currentState());
735                 break;
736
737         case LFUN_BOOKMARK_SAVE:
738                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
739                 break;
740
741         case LFUN_LABEL_GOTO: {
742                 docstring label = cmd.argument();
743                 if (label.empty()) {
744                         InsetRef * inset =
745                                 getInsetByCode<InsetRef>(cursor_,
746                                                          InsetBase::REF_CODE);
747                         if (inset) {
748                                 label = inset->getParam("reference");
749                                 // persistent=false: use temp_bookmark
750                                 saveBookmark(false);
751                         }
752                 }
753
754                 if (!label.empty())
755                         gotoLabel(label);
756                 break;
757         }
758
759         case LFUN_PARAGRAPH_GOTO: {
760                 int const id = convert<int>(to_utf8(cmd.argument()));
761                 int i = 0;
762                 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
763                         ParIterator par = b->getParFromID(id);
764                         if (par == b->par_iterator_end()) {
765                                 lyxerr[Debug::INFO]
766                                         << "No matching paragraph found! ["
767                                         << id << "]." << endl;
768                         } else {
769                                 lyxerr[Debug::INFO]
770                                         << "Paragraph " << par->id()
771                                         << " found in buffer `"
772                                         << b->fileName() << "'." << endl;
773
774                                 if (b == buffer_) {
775                                         // Set the cursor
776                                         setCursor(makeDocIterator(par, 0));
777                                         update();
778                                         switchKeyMap();
779                                 } else {
780                                         // Switch to other buffer view and resend cmd
781                                         theLyXFunc().dispatch(FuncRequest(
782                                                 LFUN_BUFFER_SWITCH, b->fileName()));
783                                         theLyXFunc().dispatch(cmd);
784                                 }
785                                 break;
786                         }
787                         ++i;
788                 }
789                 break;
790         }
791
792         case LFUN_OUTLINE_UP:
793                 toc::outline(toc::Up, cursor_);
794                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
795                 updateLabels(*buffer_);
796                 break;
797         case LFUN_OUTLINE_DOWN:
798                 toc::outline(toc::Down, cursor_);
799                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
800                 updateLabels(*buffer_);
801                 break;
802         case LFUN_OUTLINE_IN:
803                 toc::outline(toc::In, cursor_);
804                 updateLabels(*buffer_);
805                 break;
806         case LFUN_OUTLINE_OUT:
807                 toc::outline(toc::Out, cursor_);
808                 updateLabels(*buffer_);
809                 break;
810
811         case LFUN_NOTE_NEXT:
812                 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
813                 break;
814
815         case LFUN_REFERENCE_NEXT: {
816                 vector<InsetBase_code> tmp;
817                 tmp.push_back(InsetBase::LABEL_CODE);
818                 tmp.push_back(InsetBase::REF_CODE);
819                 bv_funcs::gotoInset(this, tmp, true);
820                 break;
821         }
822
823         case LFUN_CHANGES_TRACK:
824                 buffer_->params().trackChanges = !buffer_->params().trackChanges;
825                 break;
826
827         case LFUN_CHANGES_OUTPUT: {
828                 buffer_->params().outputChanges = !buffer_->params().outputChanges;
829                 break;
830         }
831
832         case LFUN_CHANGE_NEXT:
833                 findNextChange(this);
834                 break;
835
836         case LFUN_CHANGES_MERGE:
837                 if (findNextChange(this))
838                         showDialog("changes");
839                 break;
840
841         case LFUN_ALL_CHANGES_ACCEPT: {
842                 cursor_.reset(buffer_->inset());
843 #ifdef WITH_WARNINGS
844 #warning FIXME changes
845 #endif
846                 while (findNextChange(this))
847                         getLyXText()->acceptChange(cursor_);
848                 update();
849                 break;
850         }
851
852         case LFUN_ALL_CHANGES_REJECT: {
853                 cursor_.reset(buffer_->inset());
854 #ifdef WITH_WARNINGS
855 #warning FIXME changes
856 #endif
857                 while (findNextChange(this))
858                         getLyXText()->rejectChange(cursor_);
859                 break;
860         }
861
862         case LFUN_WORD_FIND:
863                 find(this, cmd);
864                 break;
865
866         case LFUN_WORD_REPLACE:
867                 replace(this, cmd);
868                 break;
869
870         case LFUN_MARK_OFF:
871                 cur.clearSelection();
872                 cur.resetAnchor();
873                 cur.message(from_utf8(N_("Mark off")));
874                 break;
875
876         case LFUN_MARK_ON:
877                 cur.clearSelection();
878                 cur.mark() = true;
879                 cur.resetAnchor();
880                 cur.message(from_utf8(N_("Mark on")));
881                 break;
882
883         case LFUN_MARK_TOGGLE:
884                 cur.clearSelection();
885                 if (cur.mark()) {
886                         cur.mark() = false;
887                         cur.message(from_utf8(N_("Mark removed")));
888                 } else {
889                         cur.mark() = true;
890                         cur.message(from_utf8(N_("Mark set")));
891                 }
892                 cur.resetAnchor();
893                 break;
894
895         case LFUN_SCREEN_RECENTER:
896                 center();
897                 break;
898
899         case LFUN_BIBTEX_DATABASE_ADD: {
900                 LCursor tmpcur = cursor_;
901                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
902                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
903                                                 InsetBase::BIBTEX_CODE);
904                 if (inset) {
905                         if (inset->addDatabase(to_utf8(cmd.argument())))
906                                 buffer_->updateBibfilesCache();
907                 }
908                 break;
909         }
910
911         case LFUN_BIBTEX_DATABASE_DEL: {
912                 LCursor tmpcur = cursor_;
913                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
914                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
915                                                 InsetBase::BIBTEX_CODE);
916                 if (inset) {
917                         if (inset->delDatabase(to_utf8(cmd.argument())))
918                                 buffer_->updateBibfilesCache();
919                 }
920                 break;
921         }
922
923         case LFUN_WORDS_COUNT: {
924                 DocIterator from, to;
925                 if (cur.selection()) {
926                         from = cur.selectionBegin();
927                         to = cur.selectionEnd();
928                 } else {
929                         from = doc_iterator_begin(buffer_->inset());
930                         to = doc_iterator_end(buffer_->inset());
931                 }
932                 int const count = countWords(from, to);
933                 docstring message;
934                 if (count != 1) {
935                         if (cur.selection())
936                                 message = bformat(_("%1$d words in selection."),
937                                           count);
938                                 else
939                                         message = bformat(_("%1$d words in document."),
940                                                           count);
941                 }
942                 else {
943                         if (cur.selection())
944                                 message = _("One word in selection.");
945                         else
946                                 message = _("One word in document.");
947                 }
948
949                 Alert::information(_("Count words"), message);
950         }
951                 break;
952
953         case LFUN_BUFFER_TOGGLE_COMPRESSION:
954                 // turn compression on/off
955                 buffer_->params().compressed = !buffer_->params().compressed;
956                 break;
957
958         case LFUN_NEXT_INSET_TOGGLE: {
959                 // this is the real function we want to invoke
960                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
961                 // if there is an inset at cursor, see whether it
962                 // wants to toggle.
963                 InsetBase * inset = cur.nextInset();
964                 if (inset && inset->isActive()) {
965                         LCursor tmpcur = cur;
966                         tmpcur.pushLeft(*inset);
967                         inset->dispatch(tmpcur, tmpcmd);
968                         if (tmpcur.result().dispatched()) {
969                                 cur.dispatched();
970                         }
971                 }
972                 // if it did not work, try the underlying inset.
973                 if (!cur.result().dispatched())
974                         cur.dispatch(tmpcmd);
975
976                 if (cur.result().dispatched())
977                         cur.clearSelection();
978
979                 break;
980         }
981
982         default:
983                 return false;
984         }
985
986         return true;
987 }
988
989
990 docstring const BufferView::requestSelection()
991 {
992         if (!buffer_)
993                 return docstring();
994
995         LCursor & cur = cursor_;
996
997         if (!cur.selection()) {
998                 xsel_cache_.set = false;
999                 return docstring();
1000         }
1001
1002         if (!xsel_cache_.set ||
1003             cur.top() != xsel_cache_.cursor ||
1004             cur.anchor_.top() != xsel_cache_.anchor)
1005         {
1006                 xsel_cache_.cursor = cur.top();
1007                 xsel_cache_.anchor = cur.anchor_.top();
1008                 xsel_cache_.set = cur.selection();
1009                 return cur.selectionAsString(false);
1010         }
1011         return docstring();
1012 }
1013
1014
1015 void BufferView::clearSelection()
1016 {
1017         if (buffer_) {
1018                 cursor_.clearSelection();
1019                 xsel_cache_.set = false;
1020                 // The buffer did not really change, but this causes the
1021                 // redraw we need because we cleared the selection above.
1022                 buffer_->changed();
1023         }
1024 }
1025
1026
1027 void BufferView::workAreaResize(int width, int height)
1028 {
1029         // Update from work area
1030         width_ = width;
1031         height_ = height;
1032
1033         // The complete text metrics will be redone.
1034         text_metrics_.clear();
1035
1036         if (buffer_)
1037                 resize();
1038 }
1039
1040
1041 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1042 {
1043         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1044
1045         // This is only called for mouse related events including
1046         // LFUN_FILE_OPEN generated by drag-and-drop.
1047         FuncRequest cmd = cmd0;
1048
1049         // E.g. Qt mouse press when no buffer
1050         if (!buffer_)
1051                 return false;
1052
1053         LCursor cur(*this);
1054         cur.push(buffer_->inset());
1055         cur.selection() = cursor_.selection();
1056
1057         // Either the inset under the cursor or the
1058         // surrounding LyXText will handle this event.
1059
1060         // Build temporary cursor.
1061         cmd.y = min(max(cmd.y, -1), height_);
1062         InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1063
1064         //lyxerr << BOOST_CURRENT_FUNCTION
1065         //       << " * hit inset at tip: " << inset << endl;
1066         //lyxerr << BOOST_CURRENT_FUNCTION
1067         //       << " * created temp cursor:" << cur << endl;
1068
1069         // NOTE: editXY returns the top level inset of nested insets. If you happen
1070         // to move from a text (inset=0) to a text inside an inset (e.g. an opened
1071         // footnote inset, again inset=0), that inset will not be redrawn.
1072         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1073                 bool need_redraw = false;
1074                 
1075                 if (inset != last_inset_) {
1076                         if (last_inset_)
1077                                 need_redraw |= last_inset_->setMouseHover(false);
1078                         if (inset)
1079                                 need_redraw |= inset->setMouseHover(true);
1080                         last_inset_ = inset;
1081                 }
1082
1083                 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1084                 // not expose the button for redraw. We adjust here the metrics dimension
1085                 // to enable a full redraw.
1086                 // FIXME: It is possible to redraw only the area around the button!
1087                 if (need_redraw && metrics_info_.singlepar) {
1088                         // FIXME: It should be possible to redraw only the area around 
1089                         // the button by doing this:
1090                         //
1091                         //metrics_info_.singlepar = false;
1092                         //metrics_info_.y1 = ymin of button;
1093                         //metrics_info_.y2 = ymax of button;
1094                         //
1095                         // Unfortunately, rowpainter.C:paintText() does not distinguish
1096                         // between background updates and text updates. So we use the hammer
1097                         // solution for now. We could also avoid the updateMetrics() below
1098                         // by using the first and last pit of the CoordCache. Have a look
1099                         // at LyXText::getPitNearY() to see what I mean.
1100                         //
1101                         //metrics_info_.pit1 = first pit of CoordCache;
1102                         //metrics_info_.pit2 = last pit of CoordCache;
1103                         //metrics_info_.singlepar = false;
1104                         //metrics_info_.y1 = 0;
1105                         //metrics_info_.y2 = height_;
1106                         //
1107                         updateMetrics(false);
1108                 }
1109
1110                 // This event (moving without mouse click) is not passed further.
1111                 // This should be changed if it is further utilized.
1112                 return need_redraw;
1113         }
1114
1115         // Put anchor at the same position.
1116         cur.resetAnchor();
1117
1118         // Try to dispatch to an non-editable inset near this position
1119         // via the temp cursor. If the inset wishes to change the real
1120         // cursor it has to do so explicitly by using
1121         //  cur.bv().cursor() = cur;  (or similar)
1122         if (inset) {
1123                 inset->dispatch(cur, cmd);
1124         }
1125
1126         // Now dispatch to the temporary cursor. If the real cursor should
1127         // be modified, the inset's dispatch has to do so explicitly.
1128         if (!cur.result().dispatched())
1129                 cur.dispatch(cmd);
1130
1131         // Redraw if requested and necessary.
1132         if (cur.result().dispatched() && cur.result().update())
1133                 return update(cur.result().update());
1134
1135         return false;
1136 }
1137
1138
1139 void BufferView::scroll(int /*lines*/)
1140 {
1141 //      if (!buffer_)
1142 //              return;
1143 //
1144 //      LyXText const * t = &buffer_->text();
1145 //      int const line_height = defaultRowHeight();
1146 //
1147 //      // The new absolute coordinate
1148 //      int new_top_y = top_y() + lines * line_height;
1149 //
1150 //      // Restrict to a valid value
1151 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1152 //      new_top_y = std::max(0, new_top_y);
1153 //
1154 //      scrollDocView(new_top_y);
1155 //
1156 }
1157
1158
1159 void BufferView::setCursorFromRow(int row)
1160 {
1161         int tmpid = -1;
1162         int tmppos = -1;
1163
1164         buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1165
1166         if (tmpid == -1)
1167                 buffer_->text().setCursor(cursor_, 0, 0);
1168         else
1169                 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1170 }
1171
1172
1173 void BufferView::gotoLabel(docstring const & label)
1174 {
1175         for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1176                 vector<docstring> labels;
1177                 it->getLabelList(*buffer_, labels);
1178                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1179                         setCursor(it);
1180                         update();
1181                         return;
1182                 }
1183         }
1184 }
1185
1186
1187 LyXText * BufferView::getLyXText()
1188 {
1189         LyXText * text = cursor_.innerText();
1190         BOOST_ASSERT(text);
1191         return text;
1192 }
1193
1194
1195 LyXText const * BufferView::getLyXText() const
1196 {
1197         LyXText const * text = cursor_.innerText();
1198         BOOST_ASSERT(text);
1199         return text;
1200 }
1201
1202
1203 TextMetrics const & BufferView::textMetrics(LyXText const * t) const
1204 {
1205         return const_cast<BufferView *>(this)->textMetrics(t);
1206 }
1207
1208
1209 TextMetrics & BufferView::textMetrics(LyXText const * t)
1210 {
1211         TextMetricsCache::iterator tmc_it  = text_metrics_.find(t);
1212         if (tmc_it == text_metrics_.end()) {
1213                 tmc_it = text_metrics_.insert(
1214                         make_pair(t, TextMetrics(this, const_cast<LyXText *>(t)))).first;
1215         }       
1216         return tmc_it->second;
1217 }
1218
1219
1220 ParagraphMetrics const & BufferView::parMetrics(LyXText const * t,
1221                 pit_type pit) const
1222 {
1223         return textMetrics(t).parMetrics(pit);
1224 }
1225
1226
1227 int BufferView::workHeight() const
1228 {
1229         return height_;
1230 }
1231
1232
1233 void BufferView::setCursor(DocIterator const & dit)
1234 {
1235         size_t const n = dit.depth();
1236         for (size_t i = 0; i < n; ++i)
1237                 dit[i].inset().edit(cursor_, true);
1238
1239         cursor_.setCursor(dit);
1240         cursor_.selection() = false;
1241 }
1242
1243
1244 bool BufferView::checkDepm(LCursor & cur, LCursor & old)
1245 {
1246         // Would be wrong to delete anything if we have a selection.
1247         if (cur.selection())
1248                 return false;
1249
1250         bool need_anchor_change = false;
1251         bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1252                 need_anchor_change);
1253
1254         if (need_anchor_change)
1255                 cur.resetAnchor();
1256         
1257         if (!changed)
1258                 return false;
1259
1260         updateMetrics(false);
1261         buffer_->changed();
1262         return true;
1263 }
1264
1265
1266 bool BufferView::mouseSetCursor(LCursor & cur)
1267 {
1268         BOOST_ASSERT(&cur.bv() == this);
1269
1270         // Has the cursor just left the inset?
1271         bool badcursor = false;
1272         if (&cursor_.inset() != &cur.inset())
1273                 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1274
1275         // do the dEPM magic if needed
1276         // FIXME: move this to InsetText::notifyCursorLeaves?
1277         bool update = false;
1278         if (!badcursor && cursor_.inTexted())
1279                 checkDepm(cur, cursor_);
1280
1281         // if the cursor was in an empty script inset and the new
1282         // position is in the nucleus of the inset, notifyCursorLeaves
1283         // will kill the script inset itself. So we check all the
1284         // elements of the cursor to make sure that they are correct.
1285         // For an example, see bug 2933: 
1286         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1287         // The code below could maybe be moved to a DocIterator method.
1288         //lyxerr << "cur before " << cur <<std::endl;
1289         DocIterator dit(cur.inset());
1290         dit.push_back(cur.bottom());
1291         size_t i = 1;
1292         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1293                 dit.push_back(cur[i]);
1294                 ++i;
1295         }
1296         //lyxerr << "5 cur after" << dit <<std::endl;
1297
1298         cursor_.setCursor(dit);
1299         cursor_.clearSelection();
1300         // remember new position.
1301         cursor_.setTargetX();
1302         finishUndo();
1303         return update;
1304 }
1305
1306
1307 void BufferView::putSelectionAt(DocIterator const & cur,
1308                                 int length, bool backwards)
1309 {
1310         cursor_.clearSelection();
1311
1312         setCursor(cur);
1313
1314         if (length) {
1315                 if (backwards) {
1316                         cursor_.pos() += length;
1317                         cursor_.setSelection(cursor_, -length);
1318                 } else
1319                         cursor_.setSelection(cursor_, length);
1320                 theSelection().haveSelection(cursor_.selection());
1321         }
1322 }
1323
1324
1325 LCursor & BufferView::cursor()
1326 {
1327         return cursor_;
1328 }
1329
1330
1331 LCursor const & BufferView::cursor() const
1332 {
1333         return cursor_;
1334 }
1335
1336
1337 pit_type BufferView::anchor_ref() const
1338 {
1339         return anchor_ref_;
1340 }
1341
1342
1343 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1344 {
1345         return metrics_info_;
1346 }
1347
1348
1349 // FIXME: We should split-up updateMetrics() for the singlepar case.
1350 void BufferView::updateMetrics(bool singlepar)
1351 {
1352         LyXText & buftext = buffer_->text();
1353         TextMetrics & tm = textMetrics(&buftext);
1354         pit_type size = int(buftext.paragraphs().size());
1355
1356         if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1357                 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1358                 offset_ref_ = 0;
1359         }
1360         
1361         // If the paragraph metrics has changed, we can not
1362         // use the singlepar optimisation.
1363         if (singlepar
1364                 // In Single Paragraph mode, rebreak only
1365                 // the (main text, not inset!) paragraph containing the cursor.
1366                 // (if this paragraph contains insets etc., rebreaking will
1367                 // recursively descend)
1368                 && tm.redoParagraph(cursor_.bottom().pit()))
1369                 singlepar = false;
1370
1371         pit_type const pit = anchor_ref_;
1372         int pit1 = pit;
1373         int pit2 = pit;
1374         size_t const npit = buftext.paragraphs().size();
1375
1376         // Rebreak anchor paragraph.
1377         if (!singlepar)
1378                 tm.redoParagraph(pit);
1379         
1380         // Clear out the position cache in case of full screen redraw.
1381         if (!singlepar)
1382                 coord_cache_.clear();
1383
1384         int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1385
1386         // Redo paragraphs above anchor if necessary.
1387         int y1 = y0;
1388         while (y1 > 0 && pit1 > 0) {
1389                 y1 -= tm.parMetrics(pit1).ascent();
1390                 --pit1;
1391                 if (!singlepar)
1392                         tm.redoParagraph(pit1);
1393                 y1 -= tm.parMetrics(pit1).descent();
1394         }
1395
1396
1397         // Take care of ascent of first line
1398         y1 -= tm.parMetrics(pit1).ascent();
1399
1400         // Normalize anchor for next time
1401         anchor_ref_ = pit1;
1402         offset_ref_ = -y1;
1403
1404         // Grey at the beginning is ugly
1405         if (pit1 == 0 && y1 > 0) {
1406                 y0 -= y1;
1407                 y1 = 0;
1408                 anchor_ref_ = 0;
1409         }
1410
1411         // Redo paragraphs below the anchor if necessary.
1412         int y2 = y0;
1413         while (y2 < height_ && pit2 < int(npit) - 1) {
1414                 y2 += tm.parMetrics(pit2).descent();
1415                 ++pit2;
1416                 if (!singlepar)
1417                         tm.redoParagraph(pit2);
1418                 y2 += tm.parMetrics(pit2).ascent();
1419         }
1420
1421         // Take care of descent of last line
1422         y2 += tm.parMetrics(pit2).descent();
1423
1424         // The coordinates of all these paragraphs are correct, cache them
1425         int y = y1;
1426         CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1427         for (pit_type pit = pit1; pit <= pit2; ++pit) {
1428                 ParagraphMetrics const & pm = tm.parMetrics(pit);
1429                 y += pm.ascent();
1430                 parPos[pit] = Point(0, y);
1431                 if (singlepar && pit == cursor_.bottom().pit()) {
1432                         // In Single Paragraph mode, collect here the
1433                         // y1 and y2 of the (one) paragraph the cursor is in
1434                         y1 = y - pm.ascent();
1435                         y2 = y + pm.descent();
1436                 }
1437                 y += pm.descent();
1438         }
1439
1440         if (singlepar) {
1441                 // collect cursor paragraph iter bounds
1442                 pit1 = cursor_.bottom().pit();
1443                 pit2 = cursor_.bottom().pit();
1444         }
1445
1446         lyxerr[Debug::DEBUG]
1447                 << BOOST_CURRENT_FUNCTION
1448                 << " y1: " << y1
1449                 << " y2: " << y2
1450                 << " pit1: " << pit1
1451                 << " pit2: " << pit2
1452                 << " npit: " << npit
1453                 << " singlepar: " << singlepar
1454                 << "size: " << size
1455                 << endl;
1456
1457         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1458
1459         if (lyxerr.debugging(Debug::WORKAREA)) {
1460                 lyxerr[Debug::WORKAREA] << "BufferView::updateMetrics" << endl;
1461                 coord_cache_.dump();
1462         }
1463 }
1464
1465
1466 void BufferView::menuInsertLyXFile(string const & filenm)
1467 {
1468         BOOST_ASSERT(cursor_.inTexted());
1469         string filename = filenm;
1470
1471         if (filename.empty()) {
1472                 // Launch a file browser
1473                 // FIXME UNICODE
1474                 string initpath = lyxrc.document_path;
1475
1476                 if (buffer_) {
1477                         string const trypath = buffer_->filePath();
1478                         // If directory is writeable, use this as default.
1479                         if (isDirWriteable(FileName(trypath)))
1480                                 initpath = trypath;
1481                 }
1482
1483                 // FIXME UNICODE
1484                 FileDialog fileDlg(_("Select LyX document to insert"),
1485                         LFUN_FILE_INSERT,
1486                         make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1487                         make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support(), "examples"))));
1488
1489                 FileDialog::Result result =
1490                         fileDlg.open(from_utf8(initpath),
1491                                      FileFilterList(_("LyX Documents (*.lyx)")),
1492                                      docstring());
1493
1494                 if (result.first == FileDialog::Later)
1495                         return;
1496
1497                 // FIXME UNICODE
1498                 filename = to_utf8(result.second);
1499
1500                 // check selected filename
1501                 if (filename.empty()) {
1502                         // emit message signal.
1503                         message(_("Canceled."));
1504                         return;
1505                 }
1506         }
1507
1508         // Get absolute path of file and add ".lyx"
1509         // to the filename if necessary
1510         filename = fileSearch(string(), filename, "lyx").absFilename();
1511
1512         docstring const disp_fn = makeDisplayPath(filename);
1513         // emit message signal.
1514         message(bformat(_("Inserting document %1$s..."), disp_fn));
1515
1516         docstring res;
1517         Buffer buf("", false);
1518         if (lyx::loadLyXFile(&buf, FileName(filename))) {
1519                 ErrorList & el = buffer_->errorList("Parse");
1520                 // Copy the inserted document error list into the current buffer one.
1521                 el = buf.errorList("Parse");
1522                 recordUndo(cursor_);
1523                 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1524                                              buf.params().textclass, el);
1525                 res = _("Document %1$s inserted.");
1526         } else
1527                 res = _("Could not insert document %1$s");
1528
1529         // emit message signal.
1530         message(bformat(res, disp_fn));
1531         buffer_->errors("Parse");
1532         resize();
1533 }
1534
1535 } // namespace lyx