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