3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
10 * \author Jürgen Vigna
12 * Full author contact details are available in file CREDITS.
17 #include "BufferView.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "bufferview_funcs.h"
24 #include "CoordCache.h"
25 #include "CutAndPaste.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
35 #include "InsetIterator.h"
37 #include "LaTeXFeatures.h"
38 #include "callback.h" // added for Dispatch functions
44 #include "TextClass.h"
47 #include "Paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "ParIterator.h"
55 #include "WordLangTuple.h"
56 #include "MetricsInfo.h"
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCommand.h" // ChangeRefs
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
63 #include "frontends/alert.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.h"
67 #include "graphics/Previews.h"
69 #include "support/convert.h"
70 #include "support/FileFilterList.h"
71 #include "support/filetools.h"
72 #include "support/Package.h"
73 #include "support/types.h"
75 #include <boost/bind.hpp>
76 #include <boost/current_function.hpp>
84 using support::addPath;
85 using support::bformat;
86 using support::FileFilterList;
87 using support::FileName;
88 using support::fileSearch;
89 using support::isDirWriteable;
90 using support::isFileReadable;
91 using support::makeDisplayPath;
92 using support::package;
96 using std::istringstream;
100 using std::mem_fun_ref;
104 namespace Alert = frontend::Alert;
108 /// Return an inset of this class if it exists at the current cursor position
110 T * getInsetByCode(Cursor & cur, Inset::Code code)
113 DocIterator it = cur;
114 if (it.nextInset() &&
115 it.nextInset()->lyxCode() == code) {
116 inset = static_cast<T*>(it.nextInset());
124 BufferView::BufferView()
125 : width_(0), height_(0), buffer_(0), wh_(0),
127 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
128 intl_(new Intl), last_inset_(0)
130 xsel_cache_.set = false;
131 intl_->initKeyMapper(lyxrc.use_kbmap);
135 BufferView::~BufferView()
140 Buffer * BufferView::buffer() const
146 void BufferView::setBuffer(Buffer * b)
148 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
149 << "[ b = " << b << "]" << endl;
152 // Save the actual cursor position and anchor inside the
153 // buffer so that it can be restored in case we rechange
154 // to this buffer later on.
155 buffer_->saveCursor(cursor_.selectionBegin(),
156 cursor_.selectionEnd());
157 // update bookmark pit of the current buffer before switch
158 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i) {
159 BookmarksSection::Bookmark const & bm = LyX::ref().session().bookmarks().bookmark(i);
160 if (buffer()->fileName() != bm.filename.absFilename())
162 // if top_id or bottom_pit, bottom_pos has been changed, update bookmark
163 // see http://bugzilla.lyx.org/show_bug.cgi?id=3092
167 boost::tie(new_pit, new_pos, new_id) = moveToPosition(bm.bottom_pit, bm.bottom_pos, bm.top_id, bm.top_pos);
168 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos || bm.top_id != new_id )
169 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(new_pit, new_pos, new_id);
171 // current buffer is going to be switched-off, save cursor pos
172 // Ideally, the whole cursor stack should be saved, but session
173 // currently can only handle bottom (whole document) level pit and pos.
174 // That is to say, if a cursor is in a nested inset, it will be
175 // restore to the left of the top level inset.
176 LyX::ref().session().lastFilePos().save(FileName(buffer_->fileName()),
177 boost::tie(cursor_.bottom().pit(), cursor_.bottom().pos()) );
180 // If we're quitting lyx, don't bother updating stuff
186 //FIXME Fix for bug 3440 is here.
187 // If we are closing current buffer, switch to the first in
190 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
191 << " No Buffer!" << endl;
192 // We are closing the buffer, use the first buffer as current
194 // if (last_buffer_) buffer_ = last_buffer_;
195 // also check that this is in theBufferList()?
196 buffer_ = theBufferList().first();
199 // last_buffer = buffer_;
200 // Set current buffer
205 cursor_ = Cursor(*this);
212 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
213 << "Buffer addr: " << buffer_ << endl;
214 cursor_.push(buffer_->inset());
215 cursor_.resetAnchor();
216 buffer_->text().setCurrentFont(cursor_);
217 if (buffer_->getCursor().size() > 0 &&
218 buffer_->getAnchor().size() > 0)
220 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
221 cursor_.resetAnchor();
222 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
223 cursor_.setSelection();
224 // do not set selection to the new buffer because we
225 // only paste recent selection.
227 // Make sure that the restored cursor is not broken. This can happen for
228 // example if this Buffer has been modified by another view.
229 cursor_.fixIfBroken();
231 updateMetrics(false);
232 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
233 graphics::Previews::get().generateBufferPreviews(*buffer_);
237 bool BufferView::loadLyXFile(FileName const & filename, bool tolastfiles)
239 // File already open?
240 if (theBufferList().exists(filename.absFilename())) {
241 docstring const file = makeDisplayPath(filename.absFilename(), 20);
242 docstring text = bformat(_("The document %1$s is already "
243 "loaded.\n\nDo you want to revert "
244 "to the saved version?"), file);
245 int const ret = Alert::prompt(_("Revert to saved document?"),
246 text, 0, 1, _("&Revert"), _("&Switch to document"));
249 setBuffer(theBufferList().getBuffer(filename.absFilename()));
252 // FIXME: should be LFUN_REVERT
253 if (!theBufferList().close(theBufferList().getBuffer(filename.absFilename()), false))
255 // Fall through to new load. (Asger)
261 if (isFileReadable(filename)) {
262 b = theBufferList().newBuffer(filename.absFilename());
263 if (!lyx::loadLyXFile(b, filename)) {
264 theBufferList().release(b);
268 docstring text = bformat(_("The document %1$s does not yet "
269 "exist.\n\nDo you want to create "
270 "a new document?"), from_utf8(filename.absFilename()));
271 int const ret = Alert::prompt(_("Create new document?"),
272 text, 0, 1, _("&Create"), _("Cancel"));
275 b = newFile(filename.absFilename(), string(), true);
283 // Send the "errors" signal in case of parsing errors
286 // Update the labels and section numbering.
287 updateLabels(*buffer_);
288 // scroll to the position when the file was last closed
289 if (lyxrc.use_lastfilepos) {
292 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(filename);
293 // if successfully move to pit (returned par_id is not zero), update metrics and reset font
294 if (moveToPosition(pit, pos, 0, 0).get<1>()) {
296 updateMetrics(false);
297 buffer_->text().setCurrentFont(cursor_);
302 LyX::ref().session().lastFiles().add(FileName(b->fileName()));
308 void BufferView::resize()
313 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << endl;
315 updateMetrics(false);
320 bool BufferView::fitCursor()
322 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
323 frontend::FontMetrics const & fm =
324 theFontMetrics(cursor_.getFont());
325 int const asc = fm.maxAscent();
326 int const des = fm.maxDescent();
327 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
328 if (p.y_ - asc >= 0 && p.y_ + des < height_)
336 bool BufferView::multiParSel()
338 if (!cursor_.selection())
340 bool ret = multiparsel_cache_;
341 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
342 // Either this, or previous selection spans paragraphs
343 return ret || multiparsel_cache_;
347 bool BufferView::update(Update::flags flags)
349 // last_inset_ points to the last visited inset. This pointer may become
350 // invalid because of keyboard editing. Since all such operations
351 // causes screen update(), I reset last_inset_ to avoid such a problem.
353 // This is close to a hot-path.
355 << BOOST_CURRENT_FUNCTION
356 << "[fitcursor = " << (flags & Update::FitCursor)
357 << ", forceupdate = " << (flags & Update::Force)
358 << ", singlepar = " << (flags & Update::SinglePar)
359 << "] buffer: " << buffer_ << endl;
361 // Check needed to survive LyX startup
365 LYXERR(Debug::WORKAREA) << "BufferView::update" << std::endl;
367 // Update macro store
368 if (!(cursor().inMathed() && cursor().inMacroMode()))
369 buffer_->buildMacros();
371 // Now do the first drawing step if needed. This consists on updating
372 // the CoordCache in updateMetrics().
373 // The second drawing step is done in WorkArea::redraw() if needed.
375 // Case when no explicit update is requested.
377 // no need to redraw anything.
378 metrics_info_.update_strategy = NoScreenUpdate;
382 if (flags == Update::Decoration) {
383 metrics_info_.update_strategy = DecorationUpdate;
387 if (flags == Update::FitCursor
388 || flags == (Update::Decoration | Update::FitCursor)) {
389 bool const fit_cursor = fitCursor();
390 // tell the frontend to update the screen if needed.
392 updateMetrics(false);
395 if (flags & Update::Decoration) {
396 metrics_info_.update_strategy = DecorationUpdate;
399 // no screen update is needed.
400 metrics_info_.update_strategy = NoScreenUpdate;
404 bool full_metrics = flags & Update::Force;
405 if (flags & Update::MultiParSel)
406 full_metrics |= multiParSel();
408 bool const single_par = !full_metrics;
409 updateMetrics(single_par);
411 if (flags & Update::FitCursor && fitCursor())
412 updateMetrics(false);
414 // tell the frontend to update the screen.
419 void BufferView::updateScrollbar()
422 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
423 << " no text in updateScrollbar" << endl;
424 scrollbarParameters_.reset();
428 Text & t = buffer_->text();
429 TextMetrics & tm = text_metrics_[&t];
431 int const parsize = int(t.paragraphs().size() - 1);
432 if (anchor_ref_ > parsize) {
433 anchor_ref_ = parsize;
438 << BOOST_CURRENT_FUNCTION
439 << " Updating scrollbar: height: " << t.paragraphs().size()
440 << " curr par: " << cursor_.bottom().pit()
441 << " default height " << defaultRowHeight() << endl;
443 // It would be better to fix the scrollbar to understand
444 // values in [0..1] and divide everything by wh
446 // estimated average paragraph height:
450 int h = tm.parMetrics(anchor_ref_).height();
452 // Normalize anchor/offset (MV):
453 while (offset_ref_ > h && anchor_ref_ < parsize) {
456 h = tm.parMetrics(anchor_ref_).height();
458 // Look at paragraph heights on-screen
461 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
464 int const h2 = tm.parMetrics(pit).height();
470 int const hav = sumh / nh;
471 // More realistic average paragraph height
476 scrollbarParameters_.height = (parsize + 1) * wh_;
477 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
478 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
482 ScrollbarParameters const & BufferView::scrollbarParameters() const
484 return scrollbarParameters_;
488 void BufferView::scrollDocView(int value)
490 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
491 << "[ value = " << value << "]" << endl;
496 Text & t = buffer_->text();
497 TextMetrics & tm = text_metrics_[&t];
499 float const bar = value / float(wh_ * t.paragraphs().size());
501 anchor_ref_ = int(bar * t.paragraphs().size());
502 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
503 anchor_ref_ = int(t.paragraphs().size()) - 1;
505 tm.redoParagraph(anchor_ref_);
506 int const h = tm.parMetrics(anchor_ref_).height();
507 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
508 updateMetrics(false);
512 void BufferView::setCursorFromScrollbar()
517 Text & t = buffer_->text();
519 int const height = 2 * defaultRowHeight();
520 int const first = height;
521 int const last = height_ - height;
522 Cursor & cur = cursor_;
524 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
527 case bv_funcs::CUR_ABOVE:
528 // We reset the cursor because bv_funcs::status() does not
529 // work when the cursor is within mathed.
530 cur.reset(buffer_->inset());
531 t.setCursorFromCoordinates(cur, 0, first);
532 cur.clearSelection();
534 case bv_funcs::CUR_BELOW:
535 // We reset the cursor because bv_funcs::status() does not
536 // work when the cursor is within mathed.
537 cur.reset(buffer_->inset());
538 t.setCursorFromCoordinates(cur, 0, last);
539 cur.clearSelection();
541 case bv_funcs::CUR_INSIDE:
542 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
543 int const newy = min(last, max(y, first));
545 cur.reset(buffer_->inset());
546 t.setCursorFromCoordinates(cur, 0, newy);
552 Change const BufferView::getCurrentChange() const
554 if (!cursor_.selection())
555 return Change(Change::UNCHANGED);
557 DocIterator dit = cursor_.selectionBegin();
558 return dit.paragraph().lookupChange(dit.pos());
562 void BufferView::saveBookmark(unsigned int idx)
564 // tenatively save bookmark, id and pos will be used to
565 // acturately locate a bookmark in a 'live' lyx session.
566 // pit and pos will be updated with bottom level pit/pos
568 LyX::ref().session().bookmarks().save(
569 FileName(buffer_->fileName()),
570 cursor_.bottom().pit(),
571 cursor_.bottom().pos(),
572 cursor_.paragraph().id(),
577 // emit message signal.
578 message(_("Save bookmark"));
582 boost::tuple<pit_type, pos_type, int> BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
583 int top_id, pos_type top_pos)
585 cursor_.clearSelection();
587 // if a valid par_id is given, try it first
588 // This is the case for a 'live' bookmark when unique paragraph ID
589 // is used to track bookmarks.
591 ParIterator par = buffer_->getParFromID(top_id);
592 if (par != buffer_->par_iterator_end()) {
593 DocIterator dit = makeDocIterator(par, min(par->size(), top_pos));
594 // Some slices of the iterator may not be
595 // reachable (e.g. closed collapsable inset)
596 // so the dociterator may need to be
597 // shortened. Otherwise, setCursor may crash
598 // lyx when the cursor can not be set to these
600 size_t const n = dit.depth();
601 for (size_t i = 0; i < n; ++i)
602 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
607 // Note: return bottom (document) level pit.
608 return boost::make_tuple(cursor_.bottom().pit(), cursor_.bottom().pos(), top_id);
611 // if top_id == 0, or searching through top_id failed
612 // This is the case for a 'restored' bookmark when only bottom
613 // (document level) pit was saved. Because of this, bookmark
614 // restoration is inaccurate. If a bookmark was within an inset,
615 // it will be restored to the left of the outmost inset that contains
617 if (static_cast<size_t>(bottom_pit) < buffer_->paragraphs().size()) {
618 DocIterator it = doc_iterator_begin(buffer_->inset());
619 it.pit() = bottom_pit;
620 it.pos() = min(bottom_pos, it.paragraph().size());
622 return boost::make_tuple(it.pit(), it.pos(),
623 it.paragraph().id());
626 return boost::make_tuple(pit_type(0), pos_type(0), 0);
630 void BufferView::switchKeyMap()
632 if (!lyxrc.rtl_support)
635 if (cursor_.innerText()->real_current_font.isRightToLeft()) {
636 if (intl_->keymap == Intl::PRIMARY)
639 if (intl_->keymap == Intl::SECONDARY)
645 int BufferView::workWidth() const
651 void BufferView::center()
653 CursorSlice & bot = cursor_.bottom();
654 TextMetrics & tm = text_metrics_[bot.text()];
655 pit_type const pit = bot.pit();
656 tm.redoParagraph(pit);
657 ParagraphMetrics const & pm = tm.parMetrics(pit);
659 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
660 + pm.ascent() - height_ / 2;
664 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
668 Cursor & cur = cursor_;
670 switch (cmd.action) {
673 flag.enabled(!buffer_->undostack().empty());
676 flag.enabled(!buffer_->redostack().empty());
678 case LFUN_FILE_INSERT:
679 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
680 case LFUN_FILE_INSERT_PLAINTEXT:
681 case LFUN_BOOKMARK_SAVE:
682 // FIXME: Actually, these LFUNS should be moved to Text
683 flag.enabled(cur.inTexted());
685 case LFUN_FONT_STATE:
686 case LFUN_LABEL_INSERT:
687 case LFUN_PARAGRAPH_GOTO:
688 // FIXME handle non-trivially
689 case LFUN_OUTLINE_UP:
690 case LFUN_OUTLINE_DOWN:
691 case LFUN_OUTLINE_IN:
692 case LFUN_OUTLINE_OUT:
694 case LFUN_REFERENCE_NEXT:
698 case LFUN_MARK_TOGGLE:
699 case LFUN_SCREEN_RECENTER:
700 case LFUN_BIBTEX_DATABASE_ADD:
701 case LFUN_BIBTEX_DATABASE_DEL:
702 case LFUN_WORDS_COUNT:
703 case LFUN_NEXT_INSET_TOGGLE:
707 case LFUN_WORD_REPLACE:
708 flag.enabled(!cur.paragraph().isDeleted(cur.pos()));
711 case LFUN_LABEL_GOTO: {
712 flag.enabled(!cmd.argument().empty()
713 || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
717 case LFUN_CHANGES_TRACK:
719 flag.setOnOff(buffer_->params().trackChanges);
722 case LFUN_CHANGES_OUTPUT:
723 flag.enabled(buffer_);
724 flag.setOnOff(buffer_->params().outputChanges);
727 case LFUN_CHANGES_MERGE:
728 case LFUN_CHANGE_NEXT:
729 case LFUN_ALL_CHANGES_ACCEPT:
730 case LFUN_ALL_CHANGES_REJECT:
731 // TODO: context-sensitive enabling of LFUNs
732 // In principle, these command should only be enabled if there
733 // is a change in the document. However, without proper
734 // optimizations, this will inevitably result in poor performance.
735 flag.enabled(buffer_);
738 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
739 flag.setOnOff(buffer_->params().compressed);
751 Update::flags BufferView::dispatch(FuncRequest const & cmd)
753 //lyxerr << BOOST_CURRENT_FUNCTION
754 // << [ cmd = " << cmd << "]" << endl;
756 // Make sure that the cached BufferView is correct.
757 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
758 << " action[" << cmd.action << ']'
759 << " arg[" << to_utf8(cmd.argument()) << ']'
760 << " x[" << cmd.x << ']'
761 << " y[" << cmd.y << ']'
762 << " button[" << cmd.button() << ']'
765 // FIXME: this should not be possible.
769 Cursor & cur = cursor_;
770 // Default Update flags.
771 Update::flags updateFlags = Update::Force | Update::FitCursor;
773 switch (cmd.action) {
776 cur.message(_("Undo"));
777 cur.clearSelection();
778 if (!textUndo(*this)) {
779 cur.message(_("No further undo information"));
780 updateFlags = Update::None;
786 cur.message(_("Redo"));
787 cur.clearSelection();
788 if (!textRedo(*this)) {
789 cur.message(_("No further redo information"));
790 updateFlags = Update::None;
795 case LFUN_FILE_INSERT:
797 menuInsertLyXFile(to_utf8(cmd.argument()));
800 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
802 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
805 case LFUN_FILE_INSERT_PLAINTEXT:
807 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
810 case LFUN_FONT_STATE:
811 cur.message(cur.currentState());
814 case LFUN_BOOKMARK_SAVE:
815 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
818 case LFUN_LABEL_GOTO: {
819 docstring label = cmd.argument();
822 getInsetByCode<InsetRef>(cursor_,
825 label = inset->getParam("reference");
826 // persistent=false: use temp_bookmark
836 case LFUN_PARAGRAPH_GOTO: {
837 int const id = convert<int>(to_utf8(cmd.argument()));
839 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
840 ParIterator par = b->getParFromID(id);
841 if (par == b->par_iterator_end()) {
843 << "No matching paragraph found! ["
844 << id << "]." << endl;
847 << "Paragraph " << par->id()
848 << " found in buffer `"
849 << b->fileName() << "'." << endl;
853 setCursor(makeDocIterator(par, 0));
856 // Switch to other buffer view and resend cmd
857 theLyXFunc().dispatch(FuncRequest(
858 LFUN_BUFFER_SWITCH, b->fileName()));
859 theLyXFunc().dispatch(cmd);
860 updateFlags = Update::None;
869 case LFUN_OUTLINE_UP:
870 toc::outline(toc::Up, cursor_);
871 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
872 updateLabels(*buffer_);
874 case LFUN_OUTLINE_DOWN:
875 toc::outline(toc::Down, cursor_);
876 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
877 updateLabels(*buffer_);
879 case LFUN_OUTLINE_IN:
880 toc::outline(toc::In, cursor_);
881 updateLabels(*buffer_);
883 case LFUN_OUTLINE_OUT:
884 toc::outline(toc::Out, cursor_);
885 updateLabels(*buffer_);
889 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
892 case LFUN_REFERENCE_NEXT: {
893 vector<Inset_code> tmp;
894 tmp.push_back(Inset::LABEL_CODE);
895 tmp.push_back(Inset::REF_CODE);
896 bv_funcs::gotoInset(this, tmp, true);
900 case LFUN_CHANGES_TRACK:
901 buffer_->params().trackChanges = !buffer_->params().trackChanges;
904 case LFUN_CHANGES_OUTPUT:
905 buffer_->params().outputChanges = !buffer_->params().outputChanges;
906 if (buffer_->params().outputChanges) {
907 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
908 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
909 LaTeXFeatures::isAvailable("xcolor");
911 if (!dvipost && !xcolorsoul) {
912 Alert::warning(_("Changes not shown in LaTeX output"),
913 _("Changes will not be highlighted in LaTeX output, "
914 "because neither dvipost nor xcolor/soul are installed.\n"
915 "Please install these packages or redefine "
916 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
917 } else if (!xcolorsoul) {
918 Alert::warning(_("Changes not shown in LaTeX output"),
919 _("Changes will not be highlighted in LaTeX output "
920 "when using pdflatex, because xcolor and soul are not installed.\n"
921 "Please install both packages or redefine "
922 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
927 case LFUN_CHANGE_NEXT:
928 findNextChange(this);
931 case LFUN_CHANGES_MERGE:
932 if (findNextChange(this))
933 showDialog("changes");
936 case LFUN_ALL_CHANGES_ACCEPT:
937 // select complete document
938 cursor_.reset(buffer_->inset());
939 cursor_.selHandle(true);
940 buffer_->text().cursorBottom(cursor_);
941 // accept everything in a single step to support atomic undo
942 buffer_->text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
945 case LFUN_ALL_CHANGES_REJECT:
946 // select complete document
947 cursor_.reset(buffer_->inset());
948 cursor_.selHandle(true);
949 buffer_->text().cursorBottom(cursor_);
950 // reject everything in a single step to support atomic undo
951 // Note: reject does not work recursively; the user may have to repeat the operation
952 buffer_->text().acceptOrRejectChanges(cursor_, Text::REJECT);
959 case LFUN_WORD_REPLACE:
964 cur.clearSelection();
966 cur.message(from_utf8(N_("Mark off")));
970 cur.clearSelection();
973 cur.message(from_utf8(N_("Mark on")));
976 case LFUN_MARK_TOGGLE:
977 cur.clearSelection();
980 cur.message(from_utf8(N_("Mark removed")));
983 cur.message(from_utf8(N_("Mark set")));
988 case LFUN_SCREEN_RECENTER:
992 case LFUN_BIBTEX_DATABASE_ADD: {
993 Cursor tmpcur = cursor_;
994 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
995 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
998 if (inset->addDatabase(to_utf8(cmd.argument())))
999 buffer_->updateBibfilesCache();
1004 case LFUN_BIBTEX_DATABASE_DEL: {
1005 Cursor tmpcur = cursor_;
1006 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
1007 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1008 Inset::BIBTEX_CODE);
1010 if (inset->delDatabase(to_utf8(cmd.argument())))
1011 buffer_->updateBibfilesCache();
1016 case LFUN_WORDS_COUNT: {
1017 DocIterator from, to;
1018 if (cur.selection()) {
1019 from = cur.selectionBegin();
1020 to = cur.selectionEnd();
1022 from = doc_iterator_begin(buffer_->inset());
1023 to = doc_iterator_end(buffer_->inset());
1025 int const count = countWords(from, to);
1028 if (cur.selection())
1029 message = bformat(_("%1$d words in selection."),
1032 message = bformat(_("%1$d words in document."),
1036 if (cur.selection())
1037 message = _("One word in selection.");
1039 message = _("One word in document.");
1042 Alert::information(_("Count words"), message);
1046 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1047 // turn compression on/off
1048 buffer_->params().compressed = !buffer_->params().compressed;
1051 case LFUN_NEXT_INSET_TOGGLE: {
1052 // this is the real function we want to invoke
1053 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1054 // if there is an inset at cursor, see whether it
1056 Inset * inset = cur.nextInset();
1057 if (inset && inset->isActive()) {
1058 Cursor tmpcur = cur;
1059 tmpcur.pushLeft(*inset);
1060 inset->dispatch(tmpcur, tmpcmd);
1061 if (tmpcur.result().dispatched()) {
1065 // if it did not work, try the underlying inset.
1066 if (!cur.result().dispatched())
1067 cur.dispatch(tmpcmd);
1069 if (cur.result().dispatched())
1070 cur.clearSelection();
1076 updateFlags = Update::None;
1083 docstring const BufferView::requestSelection()
1088 Cursor & cur = cursor_;
1090 if (!cur.selection()) {
1091 xsel_cache_.set = false;
1095 if (!xsel_cache_.set ||
1096 cur.top() != xsel_cache_.cursor ||
1097 cur.anchor_.top() != xsel_cache_.anchor)
1099 xsel_cache_.cursor = cur.top();
1100 xsel_cache_.anchor = cur.anchor_.top();
1101 xsel_cache_.set = cur.selection();
1102 return cur.selectionAsString(false);
1108 void BufferView::clearSelection()
1111 cursor_.clearSelection();
1112 // Clear the selection buffer. Otherwise a subsequent
1113 // middle-mouse-button paste would use the selection buffer,
1114 // not the more current external selection.
1115 cap::clearSelection();
1116 xsel_cache_.set = false;
1117 // The buffer did not really change, but this causes the
1118 // redraw we need because we cleared the selection above.
1124 void BufferView::workAreaResize(int width, int height)
1126 // Update from work area
1130 // The complete text metrics will be redone.
1131 text_metrics_.clear();
1138 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1140 pit_type pit = text.getPitNearY(*this, y);
1141 BOOST_ASSERT(pit != -1);
1142 Paragraph const & par = text.getPar(pit);
1144 LYXERR(Debug::DEBUG)
1145 << BOOST_CURRENT_FUNCTION
1150 InsetList::const_iterator iit = par.insetlist.begin();
1151 InsetList::const_iterator iend = par.insetlist.end();
1152 for (; iit != iend; ++iit) {
1153 Inset * const inset = iit->inset;
1154 if (inset->covers(*this, x, y)) {
1155 if (!inset->descendable())
1156 // No need to go further down if the inset is not
1160 size_t cell_number = inset->nargs();
1161 // Check all the inner cell.
1162 for (size_t i = 0; i != cell_number; ++i) {
1163 Text const * inner_text = inset->getText(i);
1166 Inset const * inset_deeper =
1167 getCoveringInset(*inner_text, x, y);
1169 return inset_deeper;
1173 LYXERR(Debug::DEBUG)
1174 << BOOST_CURRENT_FUNCTION
1175 << ": Hit inset: " << inset << endl;
1179 LYXERR(Debug::DEBUG)
1180 << BOOST_CURRENT_FUNCTION
1181 << ": No inset hit. " << endl;
1186 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1188 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1190 // This is only called for mouse related events including
1191 // LFUN_FILE_OPEN generated by drag-and-drop.
1192 FuncRequest cmd = cmd0;
1194 // E.g. Qt mouse press when no buffer
1199 cur.push(buffer_->inset());
1200 cur.selection() = cursor_.selection();
1202 // Either the inset under the cursor or the
1203 // surrounding Text will handle this event.
1205 // make sure we stay within the screen...
1206 cmd.y = min(max(cmd.y, -1), height_);
1208 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1210 // Get inset under mouse, if there is one.
1211 Inset const * covering_inset =
1212 getCoveringInset(buffer_->text(), cmd.x, cmd.y);
1213 if (covering_inset == last_inset_)
1214 // Same inset, no need to do anything...
1217 bool need_redraw = false;
1218 // const_cast because of setMouseHover().
1219 Inset * inset = const_cast<Inset *>(covering_inset);
1221 // Remove the hint on the last hovered inset (if any).
1222 need_redraw |= last_inset_->setMouseHover(false);
1224 // Highlighted the newly hovered inset (if any).
1225 need_redraw |= inset->setMouseHover(true);
1226 last_inset_ = inset;
1228 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1229 // not expose the button for redraw. We adjust here the metrics dimension
1230 // to enable a full redraw.
1231 // FIXME: It is possible to redraw only the area around the button!
1233 && metrics_info_.update_strategy == SingleParUpdate) {
1234 // FIXME: It should be possible to redraw only the area around
1235 // the button by doing this:
1237 //metrics_info_.singlepar = false;
1238 //metrics_info_.y1 = ymin of button;
1239 //metrics_info_.y2 = ymax of button;
1241 // Unfortunately, rowpainter.cpp:paintText() does not distinguish
1242 // between background updates and text updates. So we use the hammer
1243 // solution for now. We could also avoid the updateMetrics() below
1244 // by using the first and last pit of the CoordCache. Have a look
1245 // at Text::getPitNearY() to see what I mean.
1247 //metrics_info_.pit1 = first pit of CoordCache;
1248 //metrics_info_.pit2 = last pit of CoordCache;
1249 //metrics_info_.singlepar = false;
1250 //metrics_info_.y1 = 0;
1251 //metrics_info_.y2 = height_;
1253 updateMetrics(false);
1256 // This event (moving without mouse click) is not passed further.
1257 // This should be changed if it is further utilized.
1261 // Build temporary cursor.
1262 Inset * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1264 // Put anchor at the same position.
1267 // Try to dispatch to an non-editable inset near this position
1268 // via the temp cursor. If the inset wishes to change the real
1269 // cursor it has to do so explicitly by using
1270 // cur.bv().cursor() = cur; (or similar)
1272 inset->dispatch(cur, cmd);
1275 // Now dispatch to the temporary cursor. If the real cursor should
1276 // be modified, the inset's dispatch has to do so explicitly.
1277 if (!cur.result().dispatched())
1280 // Redraw if requested and necessary.
1281 if (cur.result().dispatched() && cur.result().update())
1282 return update(cur.result().update());
1288 void BufferView::scroll(int /*lines*/)
1293 // Text const * t = &buffer_->text();
1294 // int const line_height = defaultRowHeight();
1296 // // The new absolute coordinate
1297 // int new_top_y = top_y() + lines * line_height;
1299 // // Restrict to a valid value
1300 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1301 // new_top_y = std::max(0, new_top_y);
1303 // scrollDocView(new_top_y);
1308 void BufferView::setCursorFromRow(int row)
1313 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1316 buffer_->text().setCursor(cursor_, 0, 0);
1318 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1322 void BufferView::gotoLabel(docstring const & label)
1324 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1325 vector<docstring> labels;
1326 it->getLabelList(*buffer_, labels);
1327 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1336 TextMetrics const & BufferView::textMetrics(Text const * t) const
1338 return const_cast<BufferView *>(this)->textMetrics(t);
1342 TextMetrics & BufferView::textMetrics(Text const * t)
1344 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1345 if (tmc_it == text_metrics_.end()) {
1346 tmc_it = text_metrics_.insert(
1347 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1349 return tmc_it->second;
1353 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1356 return textMetrics(t).parMetrics(pit);
1360 int BufferView::workHeight() const
1366 void BufferView::setCursor(DocIterator const & dit)
1368 size_t const n = dit.depth();
1369 for (size_t i = 0; i < n; ++i)
1370 dit[i].inset().edit(cursor_, true);
1372 cursor_.setCursor(dit);
1373 cursor_.selection() = false;
1377 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1379 // Would be wrong to delete anything if we have a selection.
1380 if (cur.selection())
1383 bool need_anchor_change = false;
1384 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1385 need_anchor_change);
1387 if (need_anchor_change)
1393 updateLabels(*buffer_);
1395 updateMetrics(false);
1401 bool BufferView::mouseSetCursor(Cursor & cur)
1403 BOOST_ASSERT(&cur.bv() == this);
1405 // Has the cursor just left the inset?
1406 bool badcursor = false;
1407 bool leftinset = (&cursor_.inset() != &cur.inset());
1409 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1411 // do the dEPM magic if needed
1412 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1413 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1414 // the leftinset bool would not be necessary (badcursor instead).
1415 bool update = leftinset;
1416 if (!badcursor && cursor_.inTexted())
1417 update |= checkDepm(cur, cursor_);
1419 // if the cursor was in an empty script inset and the new
1420 // position is in the nucleus of the inset, notifyCursorLeaves
1421 // will kill the script inset itself. So we check all the
1422 // elements of the cursor to make sure that they are correct.
1423 // For an example, see bug 2933:
1424 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1425 // The code below could maybe be moved to a DocIterator method.
1426 //lyxerr << "cur before " << cur <<std::endl;
1427 DocIterator dit(cur.inset());
1428 dit.push_back(cur.bottom());
1430 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1431 dit.push_back(cur[i]);
1434 //lyxerr << "5 cur after" << dit <<std::endl;
1436 cursor_.setCursor(dit);
1437 cursor_.boundary(cur.boundary());
1438 cursor_.clearSelection();
1444 void BufferView::putSelectionAt(DocIterator const & cur,
1445 int length, bool backwards)
1447 cursor_.clearSelection();
1453 cursor_.pos() += length;
1454 cursor_.setSelection(cursor_, -length);
1456 cursor_.setSelection(cursor_, length);
1457 cap::saveSelection(cursor_);
1462 Cursor & BufferView::cursor()
1468 Cursor const & BufferView::cursor() const
1474 pit_type BufferView::anchor_ref() const
1480 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1482 return metrics_info_;
1486 // FIXME: We should split-up updateMetrics() for the singlepar case.
1487 void BufferView::updateMetrics(bool singlepar)
1489 Text & buftext = buffer_->text();
1490 TextMetrics & tm = textMetrics(&buftext);
1491 pit_type size = int(buftext.paragraphs().size());
1493 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1494 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1498 // If the paragraph metrics has changed, we can not
1499 // use the singlepar optimisation.
1501 // In Single Paragraph mode, rebreak only
1502 // the (main text, not inset!) paragraph containing the cursor.
1503 // (if this paragraph contains insets etc., rebreaking will
1504 // recursively descend)
1505 && tm.redoParagraph(cursor_.bottom().pit()))
1508 pit_type const pit = anchor_ref_;
1511 size_t const npit = buftext.paragraphs().size();
1513 // Rebreak anchor paragraph.
1515 tm.redoParagraph(pit);
1517 // Clear out the position cache in case of full screen redraw.
1519 coord_cache_.clear();
1521 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1523 // Redo paragraphs above anchor if necessary.
1525 while (y1 > 0 && pit1 > 0) {
1526 y1 -= tm.parMetrics(pit1).ascent();
1529 tm.redoParagraph(pit1);
1530 y1 -= tm.parMetrics(pit1).descent();
1534 // Take care of ascent of first line
1535 y1 -= tm.parMetrics(pit1).ascent();
1537 // Normalize anchor for next time
1541 // Grey at the beginning is ugly
1542 if (pit1 == 0 && y1 > 0) {
1548 // Redo paragraphs below the anchor if necessary.
1550 while (y2 < height_ && pit2 < int(npit) - 1) {
1551 y2 += tm.parMetrics(pit2).descent();
1554 tm.redoParagraph(pit2);
1555 y2 += tm.parMetrics(pit2).ascent();
1558 // Take care of descent of last line
1559 y2 += tm.parMetrics(pit2).descent();
1561 // The coordinates of all these paragraphs are correct, cache them
1563 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1564 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1565 ParagraphMetrics const & pm = tm.parMetrics(pit);
1567 parPos[pit] = Point(0, y);
1568 if (singlepar && pit == cursor_.bottom().pit()) {
1569 // In Single Paragraph mode, collect here the
1570 // y1 and y2 of the (one) paragraph the cursor is in
1571 y1 = y - pm.ascent();
1572 y2 = y + pm.descent();
1578 // collect cursor paragraph iter bounds
1579 pit1 = cursor_.bottom().pit();
1580 pit2 = cursor_.bottom().pit();
1583 LYXERR(Debug::DEBUG)
1584 << BOOST_CURRENT_FUNCTION
1587 << " pit1: " << pit1
1588 << " pit2: " << pit2
1589 << " npit: " << npit
1590 << " singlepar: " << singlepar
1594 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1595 singlepar? SingleParUpdate: FullScreenUpdate, size);
1597 if (lyxerr.debugging(Debug::WORKAREA)) {
1598 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1599 coord_cache_.dump();
1604 void BufferView::menuInsertLyXFile(string const & filenm)
1606 BOOST_ASSERT(cursor_.inTexted());
1607 string filename = filenm;
1609 if (filename.empty()) {
1610 // Launch a file browser
1612 string initpath = lyxrc.document_path;
1615 string const trypath = buffer_->filePath();
1616 // If directory is writeable, use this as default.
1617 if (isDirWriteable(FileName(trypath)))
1622 FileDialog fileDlg(_("Select LyX document to insert"),
1624 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1625 make_pair(_("Examples|#E#e"),
1626 from_utf8(addPath(package().system_support().absFilename(),
1629 FileDialog::Result result =
1630 fileDlg.open(from_utf8(initpath),
1631 FileFilterList(_("LyX Documents (*.lyx)")),
1634 if (result.first == FileDialog::Later)
1638 filename = to_utf8(result.second);
1640 // check selected filename
1641 if (filename.empty()) {
1642 // emit message signal.
1643 message(_("Canceled."));
1648 // Get absolute path of file and add ".lyx"
1649 // to the filename if necessary
1650 filename = fileSearch(string(), filename, "lyx").absFilename();
1652 docstring const disp_fn = makeDisplayPath(filename);
1653 // emit message signal.
1654 message(bformat(_("Inserting document %1$s..."), disp_fn));
1657 Buffer buf("", false);
1658 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1659 ErrorList & el = buffer_->errorList("Parse");
1660 // Copy the inserted document error list into the current buffer one.
1661 el = buf.errorList("Parse");
1662 recordUndo(cursor_);
1663 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1664 buf.params().textclass, el);
1665 res = _("Document %1$s inserted.");
1667 res = _("Could not insert document %1$s");
1669 // emit message signal.
1670 message(bformat(res, disp_fn));
1671 buffer_->errors("Parse");