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