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