3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
28 #include "CutAndPaste.h"
29 #include "DispatchResult.h"
30 #include "DocIterator.h"
31 #include "BufferEncodings.h"
32 #include "ErrorList.h"
35 #include "FuncRequest.h"
36 #include "FuncStatus.h"
37 #include "IndicesList.h"
38 #include "InsetIterator.h"
39 #include "InsetList.h"
41 #include "LaTeXFeatures.h"
45 #include "LyXAction.h"
49 #include "output_docbook.h"
51 #include "output_latex.h"
52 #include "output_xhtml.h"
53 #include "output_plaintext.h"
54 #include "Paragraph.h"
55 #include "ParagraphParameters.h"
56 #include "ParIterator.h"
57 #include "PDFOptions.h"
58 #include "SpellChecker.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
65 #include "VCBackend.h"
67 #include "WordLangTuple.h"
70 #include "insets/InsetBibtex.h"
71 #include "insets/InsetBranch.h"
72 #include "insets/InsetInclude.h"
73 #include "insets/InsetTabular.h"
74 #include "insets/InsetText.h"
76 #include "mathed/InsetMathHull.h"
77 #include "mathed/MacroTable.h"
78 #include "mathed/MathMacroTemplate.h"
79 #include "mathed/MathSupport.h"
81 #include "graphics/PreviewLoader.h"
83 #include "frontends/alert.h"
84 #include "frontends/Delegates.h"
85 #include "frontends/WorkAreaManager.h"
87 #include "support/lassert.h"
88 #include "support/convert.h"
89 #include "support/debug.h"
90 #include "support/docstring_list.h"
91 #include "support/ExceptionMessage.h"
92 #include "support/FileName.h"
93 #include "support/FileNameList.h"
94 #include "support/filetools.h"
95 #include "support/ForkedCalls.h"
96 #include "support/gettext.h"
97 #include "support/gzstream.h"
98 #include "support/lstrings.h"
99 #include "support/lyxalgo.h"
100 #include "support/mutex.h"
101 #include "support/os.h"
102 #include "support/Package.h"
103 #include "support/PathChanger.h"
104 #include "support/Systemcall.h"
105 #include "support/TempFile.h"
106 #include "support/textutils.h"
107 #include "support/types.h"
109 #include "support/bind.h"
110 #include "support/shared_ptr.h"
121 using namespace lyx::support;
122 using namespace lyx::graphics;
126 namespace Alert = frontend::Alert;
127 namespace os = support::os;
131 int const LYX_FORMAT = LYX_FORMAT_LYX;
133 typedef map<string, bool> DepClean;
134 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
136 void showPrintError(string const & name)
138 docstring str = bformat(_("Could not print the document %1$s.\n"
139 "Check that your printer is set up correctly."),
140 makeDisplayPath(name, 50));
141 Alert::error(_("Print document failed"), str);
147 // A storehouse for the cloned buffers.
148 list<CloneList *> cloned_buffers;
154 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
158 delete preview_loader_;
166 /// search for macro in local (buffer) table or in children
167 MacroData const * getBufferMacro(docstring const & name,
168 DocIterator const & pos) const;
170 /// Update macro table starting with position of it \param it in some
172 void updateMacros(DocIterator & it, DocIterator & scope);
174 void setLabel(ParIterator & it, UpdateType utype) const;
176 /** If we have branches that use the file suffix
177 feature, return the file name with suffix appended.
179 support::FileName exportFileName() const;
186 mutable TexRow texrow;
188 /// need to regenerate .tex?
192 mutable bool lyx_clean;
194 /// is autosave needed?
195 mutable bool bak_clean;
197 /// is this an unnamed file (New...)?
200 /// is this an internal bufffer?
201 bool internal_buffer;
206 /// name of the file the buffer is associated with.
209 /** Set to true only when the file is fully loaded.
210 * Used to prevent the premature generation of previews
211 * and by the citation inset.
213 bool file_fully_loaded;
215 /// Ignore the parent (e.g. when exporting a child standalone)?
219 mutable TocBackend toc_backend;
224 ScopeMacro(DocIterator const & s, MacroData const & m)
225 : scope(s), macro(m) {}
229 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
230 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
231 /// map from the macro name to the position map,
232 /// which maps the macro definition position to the scope and the MacroData.
233 NamePositionScopeMacroMap macros;
234 /// This seem to change the way Buffer::getMacro() works
235 mutable bool macro_lock;
237 /// positions of child buffers in the buffer
238 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
241 ScopeBuffer(DocIterator const & s,Buffer const * b)
242 : scope(s), buffer(b) {}
244 Buffer const * buffer;
246 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
247 /// position of children buffers in this buffer
248 BufferPositionMap children_positions;
249 /// map from children inclusion positions to their scope and their buffer
250 PositionScopeBufferMap position_to_children;
252 /// Container for all sort of Buffer dependant errors.
253 map<string, ErrorList> errorLists;
255 /// timestamp and checksum used to test if the file has been externally
256 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
258 unsigned long checksum_;
261 frontend::WorkAreaManager * wa_;
263 frontend::GuiBufferDelegate * gui_;
268 /// A cache for the bibfiles (including bibfiles of loaded child
269 /// documents), needed for appropriate update of natbib labels.
270 mutable support::FileNameList bibfiles_cache_;
272 // FIXME The caching mechanism could be improved. At present, we have a
273 // cache for each Buffer, that caches all the bibliography info for that
274 // Buffer. A more efficient solution would be to have a global cache per
275 // file, and then to construct the Buffer's bibinfo from that.
276 /// A cache for bibliography info
277 mutable BiblioInfo bibinfo_;
278 /// whether the bibinfo cache is valid
279 mutable bool bibinfo_cache_valid_;
280 /// whether the bibfile cache is valid
281 mutable bool bibfile_cache_valid_;
282 /// Cache of timestamps of .bib files
283 map<FileName, time_t> bibfile_status_;
284 /// Indicates whether the bibinfo has changed since the last time
285 /// we ran updateBuffer(), i.e., whether citation labels may need
287 mutable bool cite_labels_valid_;
288 /// these hold the file name and format, written to by Buffer::preview
289 /// and read from by LFUN_BUFFER_VIEW_CACHE.
290 FileName preview_file_;
291 string preview_format_;
293 mutable RefCache ref_cache_;
295 /// our Text that should be wrapped in an InsetText
299 PreviewLoader * preview_loader_;
301 /// This is here to force the test to be done whenever parent_buffer
303 Buffer const * parent() const
305 // ignore_parent temporarily "orphans" a buffer
306 // (e.g. if a child is compiled standalone)
309 // if parent_buffer is not loaded, then it has been unloaded,
310 // which means that parent_buffer is an invalid pointer. So we
311 // set it to null in that case.
312 // however, the BufferList doesn't know about cloned buffers, so
313 // they will always be regarded as unloaded. in that case, we hope
315 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
317 return parent_buffer;
321 void setParent(Buffer const * pb)
323 if (parent_buffer == pb)
326 if (!cloned_buffer_ && parent_buffer && pb)
327 LYXERR0("Warning: a buffer should not have two parents!");
329 if (!cloned_buffer_ && parent_buffer) {
330 parent_buffer->invalidateBibfileCache();
331 parent_buffer->invalidateBibinfoCache();
335 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
336 /// This one is useful for preview detached in a thread.
337 Buffer const * cloned_buffer_;
339 CloneList * clone_list_;
340 /// are we in the process of exporting this buffer?
341 mutable bool doing_export;
343 /// compute statistics
344 /// \p from initial position
345 /// \p to points to the end position
346 void updateStatistics(DocIterator & from, DocIterator & to,
347 bool skipNoOutput = true);
348 /// statistics accessor functions
349 int wordCount() const
353 int charCount(bool with_blanks) const
356 + (with_blanks ? blank_count_ : 0);
360 /// So we can force access via the accessors.
361 mutable Buffer const * parent_buffer;
370 /// Creates the per buffer temporary directory
371 static FileName createBufferTmpDir()
373 // FIXME This would be the ideal application for a TempDir class (like
374 // TempFile but for directories)
379 Mutex::Locker locker(&mutex);
380 counter = convert<string>(count++);
382 // We are in our own directory. Why bother to mangle name?
383 // In fact I wrote this code to circumvent a problematic behaviour
384 // (bug?) of EMX mkstemp().
385 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
388 if (!tmpfl.createDirectory(0777)) {
389 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
390 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
391 from_utf8(tmpfl.absFileName())));
397 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
398 Buffer const * cloned_buffer)
399 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
400 internal_buffer(false), read_only(readonly_), filename(file),
401 file_fully_loaded(false), ignore_parent(false), toc_backend(owner),
402 macro_lock(false), timestamp_(0), checksum_(0), wa_(0), gui_(0),
403 undo_(*owner), bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
404 cite_labels_valid_(false), inset(0), preview_loader_(0),
405 cloned_buffer_(cloned_buffer), clone_list_(0),
406 doing_export(false), parent_buffer(0),
407 word_count_(0), char_count_(0), blank_count_(0)
409 if (!cloned_buffer_) {
410 temppath = createBufferTmpDir();
411 lyxvc.setBuffer(owner_);
413 wa_ = new frontend::WorkAreaManager;
416 temppath = cloned_buffer_->d->temppath;
417 file_fully_loaded = true;
418 params = cloned_buffer_->d->params;
419 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
420 bibinfo_ = cloned_buffer_->d->bibinfo_;
421 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
422 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
423 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
424 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
425 unnamed = cloned_buffer_->d->unnamed;
426 internal_buffer = cloned_buffer_->d->internal_buffer;
427 preview_file_ = cloned_buffer_->d->preview_file_;
428 preview_format_ = cloned_buffer_->d->preview_format_;
432 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
433 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
435 LYXERR(Debug::INFO, "Buffer::Buffer()");
437 d->inset = new InsetText(*cloned_buffer->d->inset);
438 d->inset->setBuffer(*this);
439 // FIXME: optimize this loop somewhat, maybe by creating a new
440 // general recursive Inset::setId().
441 DocIterator it = doc_iterator_begin(this);
442 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
443 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
444 it.paragraph().setId(cloned_it.paragraph().id());
446 d->inset = new InsetText(this);
447 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
453 LYXERR(Debug::INFO, "Buffer::~Buffer()");
454 // here the buffer should take care that it is
455 // saved properly, before it goes into the void.
457 // GuiView already destroyed
461 // No need to do additional cleanups for internal buffer.
467 // this is in case of recursive includes: we won't try to delete
468 // ourselves as a child.
469 d->clone_list_->erase(this);
470 // loop over children
471 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
472 Impl::BufferPositionMap::iterator end = d->children_positions.end();
473 for (; it != end; ++it) {
474 Buffer * child = const_cast<Buffer *>(it->first);
475 if (d->clone_list_->erase(child))
478 // if we're the master buffer, then we should get rid of the list
481 // If this is not empty, we have leaked something. Worse, one of the
482 // children still has a reference to this list. But we will try to
483 // continue, rather than shut down.
484 LATTEST(d->clone_list_->empty());
485 list<CloneList *>::iterator it =
486 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
487 if (it == cloned_buffers.end()) {
488 // We will leak in this case, but it is safe to continue.
491 cloned_buffers.erase(it);
492 delete d->clone_list_;
494 // FIXME Do we really need to do this right before we delete d?
495 // clear references to children in macro tables
496 d->children_positions.clear();
497 d->position_to_children.clear();
499 // loop over children
500 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
501 Impl::BufferPositionMap::iterator end = d->children_positions.end();
502 for (; it != end; ++it) {
503 Buffer * child = const_cast<Buffer *>(it->first);
504 if (theBufferList().isLoaded(child))
505 theBufferList().releaseChild(this, child);
509 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
510 msg += emergencyWrite();
511 Alert::warning(_("Attempting to close changed document!"), msg);
514 // FIXME Do we really need to do this right before we delete d?
515 // clear references to children in macro tables
516 d->children_positions.clear();
517 d->position_to_children.clear();
519 if (!d->temppath.destroyDirectory()) {
520 Alert::warning(_("Could not remove temporary directory"),
521 bformat(_("Could not remove the temporary directory %1$s"),
522 from_utf8(d->temppath.absFileName())));
531 Buffer * Buffer::cloneFromMaster() const
534 cloned_buffers.push_back(new CloneList);
535 CloneList * clones = cloned_buffers.back();
537 masterBuffer()->cloneWithChildren(bufmap, clones);
539 // make sure we got cloned
540 BufferMap::const_iterator bit = bufmap.find(this);
541 LASSERT(bit != bufmap.end(), return 0);
542 Buffer * cloned_buffer = bit->second;
544 return cloned_buffer;
548 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
550 // have we already been cloned?
551 if (bufmap.find(this) != bufmap.end())
554 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
556 // The clone needs its own DocumentClass, since running updateBuffer() will
557 // modify it, and we would otherwise be sharing it with the original Buffer.
558 buffer_clone->params().makeDocumentClass(true);
560 cap::switchBetweenClasses(
561 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
562 static_cast<InsetText &>(buffer_clone->inset()), el);
564 bufmap[this] = buffer_clone;
565 clones->insert(buffer_clone);
566 buffer_clone->d->clone_list_ = clones;
567 buffer_clone->d->macro_lock = true;
568 buffer_clone->d->children_positions.clear();
570 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
571 // math macro caches need to be rethought and simplified.
572 // I am not sure wether we should handle Buffer cloning here or in BufferList.
573 // Right now BufferList knows nothing about buffer clones.
574 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
575 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
576 for (; it != end; ++it) {
577 DocIterator dit = it->first.clone(buffer_clone);
578 dit.setBuffer(buffer_clone);
579 Buffer * child = const_cast<Buffer *>(it->second.buffer);
581 child->cloneWithChildren(bufmap, clones);
582 BufferMap::iterator const bit = bufmap.find(child);
583 LASSERT(bit != bufmap.end(), continue);
584 Buffer * child_clone = bit->second;
586 Inset * inset = dit.nextInset();
587 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
588 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
589 inset_inc->setChildBuffer(child_clone);
590 child_clone->d->setParent(buffer_clone);
591 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
592 buffer_clone->setChild(dit, child_clone);
594 buffer_clone->d->macro_lock = false;
599 Buffer * Buffer::cloneBufferOnly() const {
600 cloned_buffers.push_back(new CloneList);
601 CloneList * clones = cloned_buffers.back();
602 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
604 // The clone needs its own DocumentClass, since running updateBuffer() will
605 // modify it, and we would otherwise be sharing it with the original Buffer.
606 buffer_clone->params().makeDocumentClass(true);
608 cap::switchBetweenClasses(
609 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
610 static_cast<InsetText &>(buffer_clone->inset()), el);
612 clones->insert(buffer_clone);
613 buffer_clone->d->clone_list_ = clones;
615 // we won't be cloning the children
616 buffer_clone->d->children_positions.clear();
621 bool Buffer::isClone() const
623 return d->cloned_buffer_;
627 void Buffer::changed(bool update_metrics) const
630 d->wa_->redrawAll(update_metrics);
634 frontend::WorkAreaManager & Buffer::workAreaManager() const
641 Text & Buffer::text() const
643 return d->inset->text();
647 Inset & Buffer::inset() const
653 BufferParams & Buffer::params()
659 BufferParams const & Buffer::params() const
665 BufferParams const & Buffer::masterParams() const
667 if (masterBuffer() == this)
670 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
671 // Copy child authors to the params. We need those pointers.
672 AuthorList const & child_authors = params().authors();
673 AuthorList::Authors::const_iterator it = child_authors.begin();
674 for (; it != child_authors.end(); ++it)
675 mparams.authors().record(*it);
680 double Buffer::fontScalingFactor() const
682 return isExporting() ? 75.0 * params().html_math_img_scale
683 : 0.01 * lyxrc.dpi * lyxrc.zoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
687 ParagraphList & Buffer::paragraphs()
689 return text().paragraphs();
693 ParagraphList const & Buffer::paragraphs() const
695 return text().paragraphs();
699 LyXVC & Buffer::lyxvc()
705 LyXVC const & Buffer::lyxvc() const
711 string const Buffer::temppath() const
713 return d->temppath.absFileName();
717 TexRow & Buffer::texrow()
723 TexRow const & Buffer::texrow() const
729 TocBackend & Buffer::tocBackend() const
731 return d->toc_backend;
735 Undo & Buffer::undo()
741 void Buffer::setChild(DocIterator const & dit, Buffer * child)
743 d->children_positions[child] = dit;
747 string Buffer::latexName(bool const no_path) const
749 FileName latex_name =
750 makeLatexName(d->exportFileName());
751 return no_path ? latex_name.onlyFileName()
752 : latex_name.absFileName();
756 FileName Buffer::Impl::exportFileName() const
758 docstring const branch_suffix =
759 params.branchlist().getFileNameSuffix();
760 if (branch_suffix.empty())
763 string const name = filename.onlyFileNameWithoutExt()
764 + to_utf8(branch_suffix);
765 FileName res(filename.onlyPath().absFileName() + "/" + name);
766 res.changeExtension(filename.extension());
772 string Buffer::logName(LogType * type) const
774 string const filename = latexName(false);
776 if (filename.empty()) {
782 string const path = temppath();
784 FileName const fname(addName(temppath(),
785 onlyFileName(changeExtension(filename,
788 // FIXME: how do we know this is the name of the build log?
789 FileName const bname(
790 addName(path, onlyFileName(
791 changeExtension(filename,
792 formats.extension(params().bufferFormat()) + ".out"))));
794 // Also consider the master buffer log file
795 FileName masterfname = fname;
796 LogType mtype = latexlog;
797 if (masterBuffer() != this) {
798 string const mlogfile = masterBuffer()->logName(&mtype);
799 masterfname = FileName(mlogfile);
802 // If no Latex log or Build log is newer, show Build log
803 if (bname.exists() &&
804 ((!fname.exists() && !masterfname.exists())
805 || (fname.lastModified() < bname.lastModified()
806 && masterfname.lastModified() < bname.lastModified()))) {
807 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
810 return bname.absFileName();
811 // If we have a newer master file log or only a master log, show this
812 } else if (fname != masterfname
813 && (!fname.exists() && (masterfname.exists()
814 || fname.lastModified() < masterfname.lastModified()))) {
815 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
818 return masterfname.absFileName();
820 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
823 return fname.absFileName();
827 void Buffer::setReadonly(bool const flag)
829 if (d->read_only != flag) {
836 void Buffer::setFileName(FileName const & fname)
838 bool const changed = fname != d->filename;
841 lyxvc().file_found_hook(fname);
842 setReadonly(d->filename.isReadOnly());
848 int Buffer::readHeader(Lexer & lex)
850 int unknown_tokens = 0;
852 int begin_header_line = -1;
854 // Initialize parameters that may be/go lacking in header:
855 params().branchlist().clear();
856 params().preamble.erase();
857 params().options.erase();
858 params().master.erase();
859 params().float_placement.erase();
860 params().paperwidth.erase();
861 params().paperheight.erase();
862 params().leftmargin.erase();
863 params().rightmargin.erase();
864 params().topmargin.erase();
865 params().bottommargin.erase();
866 params().headheight.erase();
867 params().headsep.erase();
868 params().footskip.erase();
869 params().columnsep.erase();
870 params().fonts_cjk.erase();
871 params().listings_params.clear();
872 params().clearLayoutModules();
873 params().clearRemovedModules();
874 params().clearIncludedChildren();
875 params().pdfoptions().clear();
876 params().indiceslist().clear();
877 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
878 params().isbackgroundcolor = false;
879 params().fontcolor = RGBColor(0, 0, 0);
880 params().isfontcolor = false;
881 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
882 params().boxbgcolor = RGBColor(0xFF, 0, 0);
883 params().html_latex_start.clear();
884 params().html_latex_end.clear();
885 params().html_math_img_scale = 1.0;
886 params().output_sync_macro.erase();
887 params().setLocalLayout(string(), false);
888 params().setLocalLayout(string(), true);
890 for (int i = 0; i < 4; ++i) {
891 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
892 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
895 ErrorList & errorList = d->errorLists["Parse"];
904 if (token == "\\end_header")
908 if (token == "\\begin_header") {
909 begin_header_line = line;
913 LYXERR(Debug::PARSER, "Handling document header token: `"
916 string unknown = params().readToken(lex, token, d->filename.onlyPath());
917 if (!unknown.empty()) {
918 if (unknown[0] != '\\' && token == "\\textclass") {
919 Alert::warning(_("Unknown document class"),
920 bformat(_("Using the default document class, because the "
921 "class %1$s is unknown."), from_utf8(unknown)));
924 docstring const s = bformat(_("Unknown token: "
928 errorList.push_back(ErrorItem(_("Document header error"),
933 if (begin_header_line) {
934 docstring const s = _("\\begin_header is missing");
935 errorList.push_back(ErrorItem(_("Document header error"),
939 params().makeDocumentClass();
941 return unknown_tokens;
946 // changed to be public and have one parameter
947 // Returns true if "\end_document" is not read (Asger)
948 bool Buffer::readDocument(Lexer & lex)
950 ErrorList & errorList = d->errorLists["Parse"];
953 // remove dummy empty par
954 paragraphs().clear();
956 if (!lex.checkFor("\\begin_document")) {
957 docstring const s = _("\\begin_document is missing");
958 errorList.push_back(ErrorItem(_("Document header error"),
964 if (params().output_changes) {
965 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
966 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
967 LaTeXFeatures::isAvailable("xcolor");
969 if (!dvipost && !xcolorulem) {
970 Alert::warning(_("Changes not shown in LaTeX output"),
971 _("Changes will not be highlighted in LaTeX output, "
972 "because neither dvipost nor xcolor/ulem are installed.\n"
973 "Please install these packages or redefine "
974 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
975 } else if (!xcolorulem) {
976 Alert::warning(_("Changes not shown in LaTeX output"),
977 _("Changes will not be highlighted in LaTeX output "
978 "when using pdflatex, because xcolor and ulem are not installed.\n"
979 "Please install both packages or redefine "
980 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
984 if (!parent() && !params().master.empty()) {
985 FileName const master_file = makeAbsPath(params().master,
986 onlyPath(absFileName()));
987 if (isLyXFileName(master_file.absFileName())) {
989 checkAndLoadLyXFile(master_file, true);
991 // necessary e.g. after a reload
992 // to re-register the child (bug 5873)
993 // FIXME: clean up updateMacros (here, only
994 // child registering is needed).
995 master->updateMacros();
996 // set master as master buffer, but only
997 // if we are a real child
998 if (master->isChild(this))
1000 // if the master is not fully loaded
1001 // it is probably just loading this
1002 // child. No warning needed then.
1003 else if (master->isFullyLoaded())
1004 LYXERR0("The master '"
1006 << "' assigned to this document ("
1008 << ") does not include "
1009 "this document. Ignoring the master assignment.");
1014 // assure we have a default index
1015 params().indiceslist().addDefault(B_("Index"));
1018 bool const res = text().read(lex, errorList, d->inset);
1020 // inform parent buffer about local macros
1022 Buffer const * pbuf = parent();
1023 UserMacroSet::const_iterator cit = usermacros.begin();
1024 UserMacroSet::const_iterator end = usermacros.end();
1025 for (; cit != end; ++cit)
1026 pbuf->usermacros.insert(*cit);
1030 updateMacroInstances(InternalUpdate);
1035 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1037 Format const * fmt = formats.getFormat(format);
1040 // It is important to use the correct extension here, since some
1041 // converters create a wrong output file otherwise (e.g. html2latex)
1042 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1043 FileName const name(tempfile.name());
1044 ofdocstream os(name.toFilesystemEncoding().c_str());
1045 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1046 bool const success = !(os << contents).fail();
1049 bool converted = false;
1051 params().compressed = false;
1053 // remove dummy empty par
1054 paragraphs().clear();
1056 converted = importFile(format, name, errorList);
1065 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1067 if (!theConverters().isReachable(format, "lyx"))
1070 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1071 FileName const lyx(tempfile.name());
1072 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1073 return readFile(lyx) == ReadSuccess;
1079 bool Buffer::readString(string const & s)
1081 params().compressed = false;
1084 istringstream is(s);
1086 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1087 FileName const fn = tempfile.name();
1090 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1092 if (success && file_format != LYX_FORMAT) {
1093 // We need to call lyx2lyx, so write the input to a file
1094 ofstream os(fn.toFilesystemEncoding().c_str());
1097 // lyxvc in readFile
1098 if (readFile(fn) != ReadSuccess)
1102 if (readDocument(lex))
1108 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1112 if (!lex.setFile(fname)) {
1113 Alert::error(_("File Not Found"),
1114 bformat(_("Unable to open file `%1$s'."),
1115 from_utf8(fn.absFileName())));
1116 return ReadFileNotFound;
1120 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1121 if (ret_plf != ReadSuccess)
1124 if (file_format != LYX_FORMAT) {
1126 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1127 if (ret_clf != ReadSuccess)
1129 return readFile(tmpFile);
1132 // FIXME: InsetInfo needs to know whether the file is under VCS
1133 // during the parse process, so this has to be done before.
1134 lyxvc().file_found_hook(d->filename);
1136 if (readDocument(lex)) {
1137 Alert::error(_("Document format failure"),
1138 bformat(_("%1$s ended unexpectedly, which means"
1139 " that it is probably corrupted."),
1140 from_utf8(fn.absFileName())));
1141 return ReadDocumentFailure;
1144 d->file_fully_loaded = true;
1145 d->read_only = !d->filename.isWritable();
1146 params().compressed = formats.isZippedFile(d->filename);
1152 bool Buffer::isFullyLoaded() const
1154 return d->file_fully_loaded;
1158 void Buffer::setFullyLoaded(bool value)
1160 d->file_fully_loaded = value;
1164 PreviewLoader * Buffer::loader() const
1166 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1168 if (!d->preview_loader_)
1169 d->preview_loader_ = new PreviewLoader(*this);
1170 return d->preview_loader_;
1174 void Buffer::removePreviews() const
1176 delete d->preview_loader_;
1177 d->preview_loader_ = 0;
1181 void Buffer::updatePreviews() const
1183 PreviewLoader * ploader = loader();
1187 InsetIterator it = inset_iterator_begin(*d->inset);
1188 InsetIterator const end = inset_iterator_end(*d->inset);
1189 for (; it != end; ++it)
1190 it->addPreview(it, *ploader);
1192 ploader->startLoading();
1196 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1197 FileName const & fn, int & file_format) const
1199 if(!lex.checkFor("\\lyxformat")) {
1200 Alert::error(_("Document format failure"),
1201 bformat(_("%1$s is not a readable LyX document."),
1202 from_utf8(fn.absFileName())));
1203 return ReadNoLyXFormat;
1209 // LyX formats 217 and earlier were written as 2.17. This corresponds
1210 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1211 // these cases. See also: www.lyx.org/trac/changeset/1313.
1212 size_t dot = tmp_format.find_first_of(".,");
1213 if (dot != string::npos)
1214 tmp_format.erase(dot, 1);
1216 file_format = convert<int>(tmp_format);
1221 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1222 FileName & tmpfile, int from_format)
1224 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1225 tempfile.setAutoRemove(false);
1226 tmpfile = tempfile.name();
1227 if(tmpfile.empty()) {
1228 Alert::error(_("Conversion failed"),
1229 bformat(_("%1$s is from a different"
1230 " version of LyX, but a temporary"
1231 " file for converting it could"
1232 " not be created."),
1233 from_utf8(fn.absFileName())));
1234 return LyX2LyXNoTempFile;
1237 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1238 if (lyx2lyx.empty()) {
1239 Alert::error(_("Conversion script not found"),
1240 bformat(_("%1$s is from a different"
1241 " version of LyX, but the"
1242 " conversion script lyx2lyx"
1243 " could not be found."),
1244 from_utf8(fn.absFileName())));
1245 return LyX2LyXNotFound;
1249 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1250 ostringstream command;
1251 command << os::python()
1252 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1253 << " -t " << convert<string>(LYX_FORMAT)
1254 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1255 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1256 string const command_str = command.str();
1258 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1260 cmd_ret const ret = runCommand(command_str);
1261 if (ret.first != 0) {
1262 if (from_format < LYX_FORMAT) {
1263 Alert::error(_("Conversion script failed"),
1264 bformat(_("%1$s is from an older version"
1265 " of LyX and the lyx2lyx script"
1266 " failed to convert it."),
1267 from_utf8(fn.absFileName())));
1268 return LyX2LyXOlderFormat;
1270 Alert::error(_("Conversion script failed"),
1271 bformat(_("%1$s is from a newer version"
1272 " of LyX and the lyx2lyx script"
1273 " failed to convert it."),
1274 from_utf8(fn.absFileName())));
1275 return LyX2LyXNewerFormat;
1282 // Should probably be moved to somewhere else: BufferView? GuiView?
1283 bool Buffer::save() const
1285 docstring const file = makeDisplayPath(absFileName(), 20);
1286 d->filename.refresh();
1288 // check the read-only status before moving the file as a backup
1289 if (d->filename.exists()) {
1290 bool const read_only = !d->filename.isWritable();
1292 Alert::warning(_("File is read-only"),
1293 bformat(_("The file %1$s cannot be written because it "
1294 "is marked as read-only."), file));
1299 // ask if the disk file has been externally modified (use checksum method)
1300 if (fileName().exists() && isExternallyModified(checksum_method)) {
1302 bformat(_("Document %1$s has been externally modified. "
1303 "Are you sure you want to overwrite this file?"), file);
1304 int const ret = Alert::prompt(_("Overwrite modified file?"),
1305 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1310 // We don't need autosaves in the immediate future. (Asger)
1311 resetAutosaveTimers();
1313 // if the file does not yet exist, none of the backup activity
1314 // that follows is necessary
1315 if (!fileName().exists())
1316 return writeFile(fileName());
1318 // we first write the file to a new name, then move it to its
1319 // proper location once that has been done successfully. that
1320 // way we preserve the original file if something goes wrong.
1321 string const justname = fileName().onlyFileNameWithoutExt();
1322 boost::scoped_ptr<TempFile>
1323 tempfile(new TempFile(fileName().onlyPath(),
1324 justname + "-XXXXXX.lyx"));
1325 bool const symlink = fileName().isSymLink();
1327 tempfile->setAutoRemove(false);
1329 FileName savefile(tempfile->name());
1330 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1331 if (!writeFile(savefile))
1334 // we will set this to false if we fail
1335 bool made_backup = true;
1337 FileName backupName(absFileName() + '~');
1338 if (lyxrc.make_backup) {
1339 if (!lyxrc.backupdir_path.empty()) {
1340 string const mangledName =
1341 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1342 backupName = FileName(addName(lyxrc.backupdir_path,
1346 LYXERR(Debug::FILES, "Backing up original file to " <<
1347 backupName.absFileName());
1348 // Except file is symlink do not copy because of #6587.
1349 // Hard links have bad luck.
1350 made_backup = symlink ?
1351 fileName().copyTo(backupName):
1352 fileName().moveTo(backupName);
1355 Alert::error(_("Backup failure"),
1356 bformat(_("Cannot create backup file %1$s.\n"
1357 "Please check whether the directory exists and is writable."),
1358 from_utf8(backupName.absFileName())));
1359 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1363 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1364 // Only do this if tempfile is not in autoremove mode
1367 // If we have no symlink, we can simply rename the temp file.
1368 // Otherwise, we need to copy it so the symlink stays intact.
1369 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1370 savefile.moveTo(fileName()))
1372 // saveCheckSum() was already called by writeFile(), but the
1373 // time stamp is invalidated by copying/moving
1378 // else we saved the file, but failed to move it to the right location.
1380 if (lyxrc.make_backup && made_backup && !symlink) {
1381 // the original file was moved to filename.lyx~, so it will look
1382 // to the user as if it was deleted. (see bug #9234.) we could try
1383 // to restore it, but that would basically mean trying to do again
1384 // what we just failed to do. better to leave things as they are.
1385 Alert::error(_("Write failure"),
1386 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1387 "But LyX could not move it to:\n %2$s.\n"
1388 "Your original file has been backed up to:\n %3$s"),
1389 from_utf8(savefile.absFileName()),
1390 from_utf8(fileName().absFileName()),
1391 from_utf8(backupName.absFileName())));
1393 // either we did not try to make a backup, or else we tried and failed,
1394 // or else the original file was a symlink, in which case it was copied,
1395 // not moved. so the original file is intact.
1396 Alert::error(_("Write failure"),
1397 bformat(_("Cannot move saved file to:\n %1$s.\n"
1398 "But the file has successfully been saved as:\n %2$s."),
1399 from_utf8(fileName().absFileName()),
1400 from_utf8(savefile.absFileName())));
1406 bool Buffer::writeFile(FileName const & fname) const
1408 if (d->read_only && fname == d->filename)
1411 bool retval = false;
1413 docstring const str = bformat(_("Saving document %1$s..."),
1414 makeDisplayPath(fname.absFileName()));
1417 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1419 if (params().compressed) {
1420 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1421 retval = ofs && write(ofs);
1423 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1424 retval = ofs && write(ofs);
1428 message(str + _(" could not write file!"));
1433 // removeAutosaveFile();
1436 message(str + _(" done."));
1442 docstring Buffer::emergencyWrite()
1444 // No need to save if the buffer has not changed.
1448 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1450 docstring user_message = bformat(
1451 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1453 // We try to save three places:
1454 // 1) Same place as document. Unless it is an unnamed doc.
1456 string s = absFileName();
1459 if (writeFile(FileName(s))) {
1461 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1462 return user_message;
1464 user_message += " " + _("Save failed! Trying again...\n");
1468 // 2) In HOME directory.
1469 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1471 lyxerr << ' ' << s << endl;
1472 if (writeFile(FileName(s))) {
1474 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1475 return user_message;
1478 user_message += " " + _("Save failed! Trying yet again...\n");
1480 // 3) In "/tmp" directory.
1481 // MakeAbsPath to prepend the current
1482 // drive letter on OS/2
1483 s = addName(package().temp_dir().absFileName(), absFileName());
1485 lyxerr << ' ' << s << endl;
1486 if (writeFile(FileName(s))) {
1488 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1489 return user_message;
1492 user_message += " " + _("Save failed! Bummer. Document is lost.");
1495 return user_message;
1499 bool Buffer::write(ostream & ofs) const
1502 // Use the standard "C" locale for file output.
1503 ofs.imbue(locale::classic());
1506 // The top of the file should not be written by params().
1508 // write out a comment in the top of the file
1509 // Important: Keep the version formatting in sync with lyx2lyx and
1510 // tex2lyx (bug 7951)
1511 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1512 << " created this file. For more info see http://www.lyx.org/\n"
1513 << "\\lyxformat " << LYX_FORMAT << "\n"
1514 << "\\begin_document\n";
1516 /// For each author, set 'used' to true if there is a change
1517 /// by this author in the document; otherwise set it to 'false'.
1518 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1519 AuthorList::Authors::const_iterator a_end = params().authors().end();
1520 for (; a_it != a_end; ++a_it)
1521 a_it->setUsed(false);
1523 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1524 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1525 for ( ; it != end; ++it)
1526 it->checkAuthors(params().authors());
1528 // now write out the buffer parameters.
1529 ofs << "\\begin_header\n";
1530 params().writeFile(ofs);
1531 ofs << "\\end_header\n";
1534 ofs << "\n\\begin_body\n";
1536 ofs << "\n\\end_body\n";
1538 // Write marker that shows file is complete
1539 ofs << "\\end_document" << endl;
1541 // Shouldn't really be needed....
1544 // how to check if close went ok?
1545 // Following is an attempt... (BE 20001011)
1547 // good() returns false if any error occurred, including some
1548 // formatting error.
1549 // bad() returns true if something bad happened in the buffer,
1550 // which should include file system full errors.
1555 lyxerr << "File was not closed properly." << endl;
1562 bool Buffer::makeLaTeXFile(FileName const & fname,
1563 string const & original_path,
1564 OutputParams const & runparams_in,
1565 OutputWhat output) const
1567 OutputParams runparams = runparams_in;
1569 // This is necessary for LuaTeX/XeTeX with tex fonts.
1570 // See FIXME in BufferParams::encoding()
1571 if (runparams.isFullUnicode())
1572 runparams.encoding = encodings.fromLyXName("utf8-plain");
1574 string const encoding = runparams.encoding->iconvName();
1575 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1578 try { ofs.reset(encoding); }
1579 catch (iconv_codecvt_facet_exception const & e) {
1580 lyxerr << "Caught iconv exception: " << e.what() << endl;
1581 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1582 "verify that the support software for your encoding (%1$s) is "
1583 "properly installed"), from_ascii(encoding)));
1586 if (!openFileWrite(ofs, fname))
1589 ErrorList & errorList = d->errorLists["Export"];
1591 bool failed_export = false;
1592 otexstream os(ofs, d->texrow);
1594 // make sure we are ready to export
1595 // this needs to be done before we validate
1596 // FIXME Do we need to do this all the time? I.e., in children
1597 // of a master we are exporting?
1599 updateMacroInstances(OutputUpdate);
1602 os.texrow().reset();
1603 writeLaTeXSource(os, original_path, runparams, output);
1605 catch (EncodingException const & e) {
1606 docstring const failed(1, e.failed_char);
1608 oss << "0x" << hex << e.failed_char << dec;
1609 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1610 " (code point %2$s)"),
1611 failed, from_utf8(oss.str()));
1612 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1613 "representable in the chosen encoding.\n"
1614 "Changing the document encoding to utf8 could help."),
1615 e.par_id, e.pos, e.pos + 1));
1616 failed_export = true;
1618 catch (iconv_codecvt_facet_exception const & e) {
1619 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1620 _(e.what()), -1, 0, 0));
1621 failed_export = true;
1623 catch (exception const & e) {
1624 errorList.push_back(ErrorItem(_("conversion failed"),
1625 _(e.what()), -1, 0, 0));
1626 failed_export = true;
1629 lyxerr << "Caught some really weird exception..." << endl;
1635 failed_export = true;
1636 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1639 if (runparams_in.silent)
1643 return !failed_export;
1647 void Buffer::writeLaTeXSource(otexstream & os,
1648 string const & original_path,
1649 OutputParams const & runparams_in,
1650 OutputWhat output) const
1652 // The child documents, if any, shall be already loaded at this point.
1654 OutputParams runparams = runparams_in;
1656 // This is necessary for LuaTeX/XeTeX with tex fonts.
1657 // See FIXME in BufferParams::encoding()
1658 if (runparams.isFullUnicode())
1659 runparams.encoding = encodings.fromLyXName("utf8-plain");
1661 // If we are compiling a file standalone, even if this is the
1662 // child of some other buffer, let's cut the link here, so the
1663 // file is really independent and no concurring settings from
1664 // the master (e.g. branch state) interfere (see #8100).
1665 if (!runparams.is_child)
1666 d->ignore_parent = true;
1668 // Classify the unicode characters appearing in math insets
1669 BufferEncodings::initUnicodeMath(*this);
1671 // validate the buffer.
1672 LYXERR(Debug::LATEX, " Validating buffer...");
1673 LaTeXFeatures features(*this, params(), runparams);
1675 // This is only set once per document (in master)
1676 if (!runparams.is_child)
1677 runparams.use_polyglossia = features.usePolyglossia();
1678 LYXERR(Debug::LATEX, " Buffer validation done.");
1680 bool const output_preamble =
1681 output == FullSource || output == OnlyPreamble;
1682 bool const output_body =
1683 output == FullSource || output == OnlyBody;
1685 // The starting paragraph of the coming rows is the
1686 // first paragraph of the document. (Asger)
1687 if (output_preamble && runparams.nice) {
1688 os << "%% LyX " << lyx_version << " created this file. "
1689 "For more info, see http://www.lyx.org/.\n"
1690 "%% Do not edit unless you really know what "
1693 LYXERR(Debug::INFO, "lyx document header finished");
1695 // There are a few differences between nice LaTeX and usual files:
1696 // usual files have \batchmode and special input@path to allow
1697 // inclusion of figures specified by an explicitly relative path
1698 // (i.e., a path starting with './' or '../') with either \input or
1699 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1700 // input@path is set when the actual parameter original_path is set.
1701 // This is done for usual tex-file, but not for nice-latex-file.
1702 // (Matthias 250696)
1703 // Note that input@path is only needed for something the user does
1704 // in the preamble, included .tex files or ERT, files included by
1705 // LyX work without it.
1706 if (output_preamble) {
1707 if (!runparams.nice) {
1708 // code for usual, NOT nice-latex-file
1709 os << "\\batchmode\n"; // changed from \nonstopmode
1711 if (!original_path.empty()) {
1713 // We don't know the encoding of inputpath
1714 docstring const inputpath = from_utf8(original_path);
1715 docstring uncodable_glyphs;
1716 Encoding const * const enc = runparams.encoding;
1718 for (size_t n = 0; n < inputpath.size(); ++n) {
1719 if (!enc->encodable(inputpath[n])) {
1720 docstring const glyph(1, inputpath[n]);
1721 LYXERR0("Uncodable character '"
1723 << "' in input path!");
1724 uncodable_glyphs += glyph;
1729 // warn user if we found uncodable glyphs.
1730 if (!uncodable_glyphs.empty()) {
1731 frontend::Alert::warning(
1732 _("Uncodable character in file path"),
1734 _("The path of your document\n"
1736 "contains glyphs that are unknown "
1737 "in the current document encoding "
1738 "(namely %2$s). This may result in "
1739 "incomplete output, unless "
1740 "TEXINPUTS contains the document "
1741 "directory and you don't use "
1742 "explicitly relative paths (i.e., "
1743 "paths starting with './' or "
1744 "'../') in the preamble or in ERT."
1745 "\n\nIn case of problems, choose "
1746 "an appropriate document encoding\n"
1747 "(such as utf8) or change the "
1749 inputpath, uncodable_glyphs));
1752 support::latex_path(original_path);
1753 if (contains(docdir, '#')) {
1754 docdir = subst(docdir, "#", "\\#");
1755 os << "\\catcode`\\#=11"
1756 "\\def\\#{#}\\catcode`\\#=6\n";
1758 if (contains(docdir, '%')) {
1759 docdir = subst(docdir, "%", "\\%");
1760 os << "\\catcode`\\%=11"
1761 "\\def\\%{%}\\catcode`\\%=14\n";
1763 os << "\\makeatletter\n"
1764 << "\\def\\input@path{{"
1765 << docdir << "/}}\n"
1766 << "\\makeatother\n";
1770 // get parent macros (if this buffer has a parent) which will be
1771 // written at the document begin further down.
1772 MacroSet parentMacros;
1773 listParentMacros(parentMacros, features);
1775 // Write the preamble
1776 runparams.use_babel = params().writeLaTeX(os, features,
1777 d->filename.onlyPath());
1779 // Japanese might be required only in some children of a document,
1780 // but once required, we must keep use_japanese true.
1781 runparams.use_japanese |= features.isRequired("japanese");
1784 // Restore the parenthood if needed
1785 if (!runparams.is_child)
1786 d->ignore_parent = false;
1791 os << "\\begin{document}\n";
1793 // output the parent macros
1794 MacroSet::iterator it = parentMacros.begin();
1795 MacroSet::iterator end = parentMacros.end();
1796 for (; it != end; ++it) {
1797 int num_lines = (*it)->write(os.os(), true);
1798 os.texrow().newlines(num_lines);
1801 } // output_preamble
1803 os.texrow().start(paragraphs().begin()->id(), 0);
1805 LYXERR(Debug::INFO, "preamble finished, now the body.");
1808 latexParagraphs(*this, text(), os, runparams);
1810 // Restore the parenthood if needed
1811 if (!runparams.is_child)
1812 d->ignore_parent = false;
1814 // add this just in case after all the paragraphs
1817 if (output_preamble) {
1818 os << "\\end{document}\n";
1819 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1821 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1823 runparams_in.encoding = runparams.encoding;
1825 // Just to be sure. (Asger)
1826 os.texrow().newline();
1828 //for (int i = 0; i<d->texrow.rows(); i++) {
1830 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1831 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1834 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1835 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1839 void Buffer::makeDocBookFile(FileName const & fname,
1840 OutputParams const & runparams,
1841 OutputWhat output) const
1843 LYXERR(Debug::LATEX, "makeDocBookFile...");
1846 if (!openFileWrite(ofs, fname))
1849 // make sure we are ready to export
1850 // this needs to be done before we validate
1852 updateMacroInstances(OutputUpdate);
1854 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1858 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1862 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1863 OutputParams const & runparams,
1864 OutputWhat output) const
1866 LaTeXFeatures features(*this, params(), runparams);
1871 DocumentClass const & tclass = params().documentClass();
1872 string const & top_element = tclass.latexname();
1874 bool const output_preamble =
1875 output == FullSource || output == OnlyPreamble;
1876 bool const output_body =
1877 output == FullSource || output == OnlyBody;
1879 if (output_preamble) {
1880 if (runparams.flavor == OutputParams::XML)
1881 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1884 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1887 if (! tclass.class_header().empty())
1888 os << from_ascii(tclass.class_header());
1889 else if (runparams.flavor == OutputParams::XML)
1890 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1891 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1893 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1895 docstring preamble = from_utf8(params().preamble);
1896 if (runparams.flavor != OutputParams::XML ) {
1897 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1898 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1899 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1900 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1903 string const name = runparams.nice
1904 ? changeExtension(absFileName(), ".sgml") : fname;
1905 preamble += features.getIncludedFiles(name);
1906 preamble += features.getLyXSGMLEntities();
1908 if (!preamble.empty()) {
1909 os << "\n [ " << preamble << " ]";
1915 string top = top_element;
1917 if (runparams.flavor == OutputParams::XML)
1918 top += params().language->code();
1920 top += params().language->code().substr(0, 2);
1923 if (!params().options.empty()) {
1925 top += params().options;
1928 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1929 << " file was created by LyX " << lyx_version
1930 << "\n See http://www.lyx.org/ for more information -->\n";
1932 params().documentClass().counters().reset();
1934 sgml::openTag(os, top);
1936 docbookParagraphs(text(), *this, os, runparams);
1937 sgml::closeTag(os, top_element);
1942 void Buffer::makeLyXHTMLFile(FileName const & fname,
1943 OutputParams const & runparams) const
1945 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1948 if (!openFileWrite(ofs, fname))
1951 // make sure we are ready to export
1952 // this has to be done before we validate
1953 updateBuffer(UpdateMaster, OutputUpdate);
1954 updateMacroInstances(OutputUpdate);
1956 writeLyXHTMLSource(ofs, runparams, FullSource);
1960 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1964 void Buffer::writeLyXHTMLSource(odocstream & os,
1965 OutputParams const & runparams,
1966 OutputWhat output) const
1968 LaTeXFeatures features(*this, params(), runparams);
1970 d->bibinfo_.makeCitationLabels(*this);
1972 bool const output_preamble =
1973 output == FullSource || output == OnlyPreamble;
1974 bool const output_body =
1975 output == FullSource || output == OnlyBody || output == IncludedFile;
1977 if (output_preamble) {
1978 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1979 << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/Math/DTD/mathml2/xhtml-math11-f.dtd\">\n"
1980 // FIXME Language should be set properly.
1981 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1983 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1984 // FIXME Presumably need to set this right
1985 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1987 docstring const & doctitle = features.htmlTitle();
1989 << (doctitle.empty() ?
1990 from_ascii("LyX Document") :
1991 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1994 docstring styles = features.getTClassHTMLPreamble();
1995 if (!styles.empty())
1996 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1998 styles = from_utf8(features.getPreambleSnippets());
1999 if (!styles.empty())
2000 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2002 // we will collect CSS information in a stream, and then output it
2003 // either here, as part of the header, or else in a separate file.
2004 odocstringstream css;
2005 styles = from_utf8(features.getCSSSnippets());
2006 if (!styles.empty())
2007 css << "/* LyX Provided Styles */\n" << styles << '\n';
2009 styles = features.getTClassHTMLStyles();
2010 if (!styles.empty())
2011 css << "/* Layout-provided Styles */\n" << styles << '\n';
2013 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2014 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2015 if (needfg || needbg) {
2016 css << "\nbody {\n";
2019 << from_ascii(X11hexname(params().fontcolor))
2022 css << " background-color: "
2023 << from_ascii(X11hexname(params().backgroundcolor))
2028 docstring const dstyles = css.str();
2029 if (!dstyles.empty()) {
2030 bool written = false;
2031 if (params().html_css_as_file) {
2032 // open a file for CSS info
2034 string const fcssname = addName(temppath(), "docstyle.css");
2035 FileName const fcssfile = FileName(fcssname);
2036 if (openFileWrite(ocss, fcssfile)) {
2040 // write link to header
2041 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2043 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2046 // we are here if the CSS is supposed to be written to the header
2047 // or if we failed to write it to an external file.
2049 os << "<style type='text/css'>\n"
2058 bool const output_body_tag = (output != IncludedFile);
2059 if (output_body_tag)
2062 if (output != IncludedFile)
2063 // if we're an included file, the counters are in the master.
2064 params().documentClass().counters().reset();
2065 xhtmlParagraphs(text(), *this, xs, runparams);
2066 if (output_body_tag)
2070 if (output_preamble)
2075 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2076 // Other flags: -wall -v0 -x
2077 int Buffer::runChktex()
2081 // get LaTeX-Filename
2082 FileName const path(temppath());
2083 string const name = addName(path.absFileName(), latexName());
2084 string const org_path = filePath();
2086 PathChanger p(path); // path to LaTeX file
2087 message(_("Running chktex..."));
2089 // Generate the LaTeX file if neccessary
2090 OutputParams runparams(¶ms().encoding());
2091 runparams.flavor = OutputParams::LATEX;
2092 runparams.nice = false;
2093 runparams.linelen = lyxrc.plaintext_linelen;
2094 makeLaTeXFile(FileName(name), org_path, runparams);
2097 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2098 int const res = chktex.run(terr); // run chktex
2101 Alert::error(_("chktex failure"),
2102 _("Could not run chktex successfully."));
2104 ErrorList & errlist = d->errorLists["ChkTeX"];
2106 bufferErrors(terr, errlist);
2111 if (runparams.silent)
2112 d->errorLists["ChkTeX"].clear();
2120 void Buffer::validate(LaTeXFeatures & features) const
2122 // Validate the buffer params, but not for included
2123 // files, since they also use the parent buffer's
2125 if (!features.runparams().is_child)
2126 params().validate(features);
2128 for_each(paragraphs().begin(), paragraphs().end(),
2129 bind(&Paragraph::validate, _1, ref(features)));
2131 if (lyxerr.debugging(Debug::LATEX)) {
2132 features.showStruct();
2137 void Buffer::getLabelList(vector<docstring> & list) const
2139 // If this is a child document, use the master's list instead.
2141 masterBuffer()->getLabelList(list);
2146 Toc & toc = d->toc_backend.toc("label");
2147 TocIterator toc_it = toc.begin();
2148 TocIterator end = toc.end();
2149 for (; toc_it != end; ++toc_it) {
2150 if (toc_it->depth() == 0)
2151 list.push_back(toc_it->str());
2156 void Buffer::updateBibfilesCache(UpdateScope scope) const
2158 // FIXME This is probably unnecssary, given where we call this.
2159 // If this is a child document, use the parent's cache instead.
2160 if (parent() && scope != UpdateChildOnly) {
2161 masterBuffer()->updateBibfilesCache();
2165 d->bibfiles_cache_.clear();
2166 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2167 if (it->lyxCode() == BIBTEX_CODE) {
2168 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2169 support::FileNameList const bibfiles = inset.getBibFiles();
2170 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2173 } else if (it->lyxCode() == INCLUDE_CODE) {
2174 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2175 Buffer const * const incbuf = inset.getChildBuffer();
2178 support::FileNameList const & bibfiles =
2179 incbuf->getBibfilesCache(UpdateChildOnly);
2180 if (!bibfiles.empty()) {
2181 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2187 d->bibfile_cache_valid_ = true;
2188 d->bibinfo_cache_valid_ = false;
2189 d->cite_labels_valid_ = false;
2193 void Buffer::invalidateBibinfoCache() const
2195 d->bibinfo_cache_valid_ = false;
2196 d->cite_labels_valid_ = false;
2197 // also invalidate the cache for the parent buffer
2198 Buffer const * const pbuf = d->parent();
2200 pbuf->invalidateBibinfoCache();
2204 void Buffer::invalidateBibfileCache() const
2206 d->bibfile_cache_valid_ = false;
2207 d->bibinfo_cache_valid_ = false;
2208 d->cite_labels_valid_ = false;
2209 // also invalidate the cache for the parent buffer
2210 Buffer const * const pbuf = d->parent();
2212 pbuf->invalidateBibfileCache();
2216 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2218 // FIXME This is probably unnecessary, given where we call this.
2219 // If this is a child document, use the master's cache instead.
2220 Buffer const * const pbuf = masterBuffer();
2221 if (pbuf != this && scope != UpdateChildOnly)
2222 return pbuf->getBibfilesCache();
2224 if (!d->bibfile_cache_valid_)
2225 this->updateBibfilesCache(scope);
2227 return d->bibfiles_cache_;
2231 BiblioInfo const & Buffer::masterBibInfo() const
2233 Buffer const * const tmp = masterBuffer();
2235 return tmp->masterBibInfo();
2240 void Buffer::checkIfBibInfoCacheIsValid() const
2242 // use the master's cache
2243 Buffer const * const tmp = masterBuffer();
2245 tmp->checkIfBibInfoCacheIsValid();
2249 // compare the cached timestamps with the actual ones.
2250 FileNameList const & bibfiles_cache = getBibfilesCache();
2251 FileNameList::const_iterator ei = bibfiles_cache.begin();
2252 FileNameList::const_iterator en = bibfiles_cache.end();
2253 for (; ei != en; ++ ei) {
2254 time_t lastw = ei->lastModified();
2255 time_t prevw = d->bibfile_status_[*ei];
2256 if (lastw != prevw) {
2257 d->bibinfo_cache_valid_ = false;
2258 d->cite_labels_valid_ = false;
2259 d->bibfile_status_[*ei] = lastw;
2265 void Buffer::reloadBibInfoCache() const
2267 // use the master's cache
2268 Buffer const * const tmp = masterBuffer();
2270 tmp->reloadBibInfoCache();
2274 checkIfBibInfoCacheIsValid();
2275 if (d->bibinfo_cache_valid_)
2278 d->bibinfo_.clear();
2280 d->bibinfo_cache_valid_ = true;
2284 void Buffer::collectBibKeys() const
2286 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2287 it->collectBibKeys(it);
2291 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2293 Buffer const * tmp = masterBuffer();
2294 BiblioInfo & masterbi = (tmp == this) ?
2295 d->bibinfo_ : tmp->d->bibinfo_;
2296 masterbi.mergeBiblioInfo(bi);
2300 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2302 Buffer const * tmp = masterBuffer();
2303 BiblioInfo & masterbi = (tmp == this) ?
2304 d->bibinfo_ : tmp->d->bibinfo_;
2309 void Buffer::makeCitationLabels() const
2311 Buffer const * const master = masterBuffer();
2312 return d->bibinfo_.makeCitationLabels(*master);
2316 bool Buffer::citeLabelsValid() const
2318 return masterBuffer()->d->cite_labels_valid_;
2322 void Buffer::removeBiblioTempFiles() const
2324 // We remove files that contain LaTeX commands specific to the
2325 // particular bibliographic style being used, in order to avoid
2326 // LaTeX errors when we switch style.
2327 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2328 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2329 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2330 aux_file.removeFile();
2331 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2332 bbl_file.removeFile();
2333 // Also for the parent buffer
2334 Buffer const * const pbuf = parent();
2336 pbuf->removeBiblioTempFiles();
2340 bool Buffer::isDepClean(string const & name) const
2342 DepClean::const_iterator const it = d->dep_clean.find(name);
2343 if (it == d->dep_clean.end())
2349 void Buffer::markDepClean(string const & name)
2351 d->dep_clean[name] = true;
2355 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2358 // FIXME? if there is an Buffer LFUN that can be dispatched even
2359 // if internal, put a switch '(cmd.action)' here.
2365 switch (cmd.action()) {
2367 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2368 flag.setOnOff(isReadonly());
2371 // FIXME: There is need for a command-line import.
2372 //case LFUN_BUFFER_IMPORT:
2374 case LFUN_BUFFER_AUTO_SAVE:
2377 case LFUN_BUFFER_EXPORT_CUSTOM:
2378 // FIXME: Nothing to check here?
2381 case LFUN_BUFFER_EXPORT: {
2382 docstring const arg = cmd.argument();
2383 if (arg == "custom") {
2387 string format = to_utf8(arg);
2388 size_t pos = format.find(' ');
2389 if (pos != string::npos)
2390 format = format.substr(0, pos);
2391 enable = params().isExportable(format);
2393 flag.message(bformat(
2394 _("Don't know how to export to format: %1$s"), arg));
2398 case LFUN_BUFFER_CHKTEX:
2399 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2402 case LFUN_BUILD_PROGRAM:
2403 enable = params().isExportable("program");
2406 case LFUN_BRANCH_ACTIVATE:
2407 case LFUN_BRANCH_DEACTIVATE:
2408 case LFUN_BRANCH_MASTER_ACTIVATE:
2409 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2410 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2411 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2412 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2413 : params().branchlist();
2414 docstring const branchName = cmd.argument();
2415 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2419 case LFUN_BRANCH_ADD:
2420 case LFUN_BRANCHES_RENAME:
2421 case LFUN_BUFFER_PRINT:
2422 // if no Buffer is present, then of course we won't be called!
2425 case LFUN_BUFFER_LANGUAGE:
2426 enable = !isReadonly();
2429 case LFUN_BUFFER_VIEW_CACHE:
2430 enable = (d->preview_file_).exists();
2436 flag.setEnabled(enable);
2441 void Buffer::dispatch(string const & command, DispatchResult & result)
2443 return dispatch(lyxaction.lookupFunc(command), result);
2447 // NOTE We can end up here even if we have no GUI, because we are called
2448 // by LyX::exec to handled command-line requests. So we may need to check
2449 // whether we have a GUI or not. The boolean use_gui holds this information.
2450 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2453 // FIXME? if there is an Buffer LFUN that can be dispatched even
2454 // if internal, put a switch '(cmd.action())' here.
2455 dr.dispatched(false);
2458 string const argument = to_utf8(func.argument());
2459 // We'll set this back to false if need be.
2460 bool dispatched = true;
2461 undo().beginUndoGroup();
2463 switch (func.action()) {
2464 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2465 if (lyxvc().inUse()) {
2466 string log = lyxvc().toggleReadOnly();
2471 setReadonly(!isReadonly());
2474 case LFUN_BUFFER_EXPORT: {
2475 ExportStatus const status = doExport(argument, false);
2476 dr.setError(status != ExportSuccess);
2477 if (status != ExportSuccess)
2478 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2483 case LFUN_BUILD_PROGRAM: {
2484 ExportStatus const status = doExport("program", true);
2485 dr.setError(status != ExportSuccess);
2486 if (status != ExportSuccess)
2487 dr.setMessage(_("Error generating literate programming code."));
2491 case LFUN_BUFFER_CHKTEX:
2495 case LFUN_BUFFER_EXPORT_CUSTOM: {
2497 string command = split(argument, format_name, ' ');
2498 Format const * format = formats.getFormat(format_name);
2500 lyxerr << "Format \"" << format_name
2501 << "\" not recognized!"
2506 // The name of the file created by the conversion process
2509 // Output to filename
2510 if (format->name() == "lyx") {
2511 string const latexname = latexName(false);
2512 filename = changeExtension(latexname,
2513 format->extension());
2514 filename = addName(temppath(), filename);
2516 if (!writeFile(FileName(filename)))
2520 doExport(format_name, true, filename);
2523 // Substitute $$FName for filename
2524 if (!contains(command, "$$FName"))
2525 command = "( " + command + " ) < $$FName";
2526 command = subst(command, "$$FName", filename);
2528 // Execute the command in the background
2530 call.startscript(Systemcall::DontWait, command, filePath());
2534 // FIXME: There is need for a command-line import.
2536 case LFUN_BUFFER_IMPORT:
2541 case LFUN_BUFFER_AUTO_SAVE:
2543 resetAutosaveTimers();
2546 case LFUN_BRANCH_ACTIVATE:
2547 case LFUN_BRANCH_DEACTIVATE:
2548 case LFUN_BRANCH_MASTER_ACTIVATE:
2549 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2550 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2551 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2552 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2555 docstring const branch_name = func.argument();
2556 // the case without a branch name is handled elsewhere
2557 if (branch_name.empty()) {
2561 Branch * branch = buf->params().branchlist().find(branch_name);
2563 LYXERR0("Branch " << branch_name << " does not exist.");
2565 docstring const msg =
2566 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2570 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2571 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2572 if (branch->isSelected() != activate) {
2573 buf->undo().recordUndoBufferParams(CursorData());
2574 branch->setSelected(activate);
2576 dr.screenUpdate(Update::Force);
2577 dr.forceBufferUpdate();
2582 case LFUN_BRANCH_ADD: {
2583 docstring branch_name = func.argument();
2584 if (branch_name.empty()) {
2588 BranchList & branch_list = params().branchlist();
2589 vector<docstring> const branches =
2590 getVectorFromString(branch_name, branch_list.separator());
2592 for (vector<docstring>::const_iterator it = branches.begin();
2593 it != branches.end(); ++it) {
2595 Branch * branch = branch_list.find(branch_name);
2597 LYXERR0("Branch " << branch_name << " already exists.");
2601 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2603 undo().recordUndoBufferParams(CursorData());
2604 branch_list.add(branch_name);
2605 branch = branch_list.find(branch_name);
2606 string const x11hexname = X11hexname(branch->color());
2607 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2608 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2610 dr.screenUpdate(Update::Force);
2618 case LFUN_BRANCHES_RENAME: {
2619 if (func.argument().empty())
2622 docstring const oldname = from_utf8(func.getArg(0));
2623 docstring const newname = from_utf8(func.getArg(1));
2624 InsetIterator it = inset_iterator_begin(inset());
2625 InsetIterator const end = inset_iterator_end(inset());
2626 bool success = false;
2627 for (; it != end; ++it) {
2628 if (it->lyxCode() == BRANCH_CODE) {
2629 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2630 if (ins.branch() == oldname) {
2631 undo().recordUndo(CursorData(it));
2632 ins.rename(newname);
2637 if (it->lyxCode() == INCLUDE_CODE) {
2638 // get buffer of external file
2639 InsetInclude const & ins =
2640 static_cast<InsetInclude const &>(*it);
2641 Buffer * child = ins.getChildBuffer();
2644 child->dispatch(func, dr);
2649 dr.screenUpdate(Update::Force);
2650 dr.forceBufferUpdate();
2655 case LFUN_BUFFER_PRINT: {
2656 // we'll assume there's a problem until we succeed
2658 string target = func.getArg(0);
2659 string target_name = func.getArg(1);
2660 string command = func.getArg(2);
2663 || target_name.empty()
2664 || command.empty()) {
2665 LYXERR0("Unable to parse " << func.argument());
2666 docstring const msg =
2667 bformat(_("Unable to parse \"%1$s\""), func.argument());
2671 if (target != "printer" && target != "file") {
2672 LYXERR0("Unrecognized target \"" << target << '"');
2673 docstring const msg =
2674 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2679 if (doExport("dvi", true) != ExportSuccess) {
2680 showPrintError(absFileName());
2681 dr.setMessage(_("Error exporting to DVI."));
2685 // Push directory path.
2686 string const path = temppath();
2687 // Prevent the compiler from optimizing away p
2691 // there are three cases here:
2692 // 1. we print to a file
2693 // 2. we print directly to a printer
2694 // 3. we print using a spool command (print to file first)
2697 string const dviname = changeExtension(latexName(true), "dvi");
2699 if (target == "printer") {
2700 if (!lyxrc.print_spool_command.empty()) {
2701 // case 3: print using a spool
2702 string const psname = changeExtension(dviname,".ps");
2703 command += ' ' + lyxrc.print_to_file
2706 + quoteName(dviname);
2708 string command2 = lyxrc.print_spool_command + ' ';
2709 if (target_name != "default") {
2710 command2 += lyxrc.print_spool_printerprefix
2714 command2 += quoteName(psname);
2716 // If successful, then spool command
2717 res = one.startscript(Systemcall::Wait, command,
2721 // If there's no GUI, we have to wait on this command. Otherwise,
2722 // LyX deletes the temporary directory, and with it the spooled
2723 // file, before it can be printed!!
2724 Systemcall::Starttype stype = use_gui ?
2725 Systemcall::DontWait : Systemcall::Wait;
2726 res = one.startscript(stype, command2,
2730 // case 2: print directly to a printer
2731 if (target_name != "default")
2732 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2734 Systemcall::Starttype stype = use_gui ?
2735 Systemcall::DontWait : Systemcall::Wait;
2736 res = one.startscript(stype, command +
2737 quoteName(dviname), filePath());
2741 // case 1: print to a file
2742 FileName const filename(makeAbsPath(target_name, filePath()));
2743 FileName const dvifile(makeAbsPath(dviname, path));
2744 if (filename.exists()) {
2745 docstring text = bformat(
2746 _("The file %1$s already exists.\n\n"
2747 "Do you want to overwrite that file?"),
2748 makeDisplayPath(filename.absFileName()));
2749 if (Alert::prompt(_("Overwrite file?"),
2750 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2753 command += ' ' + lyxrc.print_to_file
2754 + quoteName(filename.toFilesystemEncoding())
2756 + quoteName(dvifile.toFilesystemEncoding());
2758 Systemcall::Starttype stype = use_gui ?
2759 Systemcall::DontWait : Systemcall::Wait;
2760 res = one.startscript(stype, command, filePath());
2766 dr.setMessage(_("Error running external commands."));
2767 showPrintError(absFileName());
2772 case LFUN_BUFFER_VIEW_CACHE:
2773 if (!formats.view(*this, d->preview_file_,
2774 d->preview_format_))
2775 dr.setMessage(_("Error viewing the output file."));
2782 dr.dispatched(dispatched);
2783 undo().endUndoGroup();
2787 void Buffer::changeLanguage(Language const * from, Language const * to)
2789 LASSERT(from, return);
2790 LASSERT(to, return);
2792 for_each(par_iterator_begin(),
2794 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2798 bool Buffer::isMultiLingual() const
2800 ParConstIterator end = par_iterator_end();
2801 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2802 if (it->isMultiLingual(params()))
2809 std::set<Language const *> Buffer::getLanguages() const
2811 std::set<Language const *> languages;
2812 getLanguages(languages);
2817 void Buffer::getLanguages(std::set<Language const *> & languages) const
2819 ParConstIterator end = par_iterator_end();
2820 // add the buffer language, even if it's not actively used
2821 languages.insert(language());
2822 // iterate over the paragraphs
2823 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2824 it->getLanguages(languages);
2826 ListOfBuffers clist = getDescendents();
2827 ListOfBuffers::const_iterator cit = clist.begin();
2828 ListOfBuffers::const_iterator const cen = clist.end();
2829 for (; cit != cen; ++cit)
2830 (*cit)->getLanguages(languages);
2834 DocIterator Buffer::getParFromID(int const id) const
2836 Buffer * buf = const_cast<Buffer *>(this);
2838 // John says this is called with id == -1 from undo
2839 lyxerr << "getParFromID(), id: " << id << endl;
2840 return doc_iterator_end(buf);
2843 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2844 if (it.paragraph().id() == id)
2847 return doc_iterator_end(buf);
2851 bool Buffer::hasParWithID(int const id) const
2853 return !getParFromID(id).atEnd();
2857 ParIterator Buffer::par_iterator_begin()
2859 return ParIterator(doc_iterator_begin(this));
2863 ParIterator Buffer::par_iterator_end()
2865 return ParIterator(doc_iterator_end(this));
2869 ParConstIterator Buffer::par_iterator_begin() const
2871 return ParConstIterator(doc_iterator_begin(this));
2875 ParConstIterator Buffer::par_iterator_end() const
2877 return ParConstIterator(doc_iterator_end(this));
2881 Language const * Buffer::language() const
2883 return params().language;
2887 docstring const Buffer::B_(string const & l10n) const
2889 return params().B_(l10n);
2893 bool Buffer::isClean() const
2895 return d->lyx_clean;
2899 bool Buffer::isExternallyModified(CheckMethod method) const
2901 LASSERT(d->filename.exists(), return false);
2902 // if method == timestamp, check timestamp before checksum
2903 return (method == checksum_method
2904 || d->timestamp_ != d->filename.lastModified())
2905 && d->checksum_ != d->filename.checksum();
2909 void Buffer::saveCheckSum() const
2911 FileName const & file = d->filename;
2914 if (file.exists()) {
2915 d->timestamp_ = file.lastModified();
2916 d->checksum_ = file.checksum();
2918 // in the case of save to a new file.
2925 void Buffer::markClean() const
2927 if (!d->lyx_clean) {
2928 d->lyx_clean = true;
2931 // if the .lyx file has been saved, we don't need an
2933 d->bak_clean = true;
2934 d->undo_.markDirty();
2938 void Buffer::setUnnamed(bool flag)
2944 bool Buffer::isUnnamed() const
2951 /// Don't check unnamed, here: isInternal() is used in
2952 /// newBuffer(), where the unnamed flag has not been set by anyone
2953 /// yet. Also, for an internal buffer, there should be no need for
2954 /// retrieving fileName() nor for checking if it is unnamed or not.
2955 bool Buffer::isInternal() const
2957 return d->internal_buffer;
2961 void Buffer::setInternal(bool flag)
2963 d->internal_buffer = flag;
2967 void Buffer::markDirty()
2970 d->lyx_clean = false;
2973 d->bak_clean = false;
2975 DepClean::iterator it = d->dep_clean.begin();
2976 DepClean::const_iterator const end = d->dep_clean.end();
2978 for (; it != end; ++it)
2983 FileName Buffer::fileName() const
2989 string Buffer::absFileName() const
2991 return d->filename.absFileName();
2995 string Buffer::filePath() const
2997 string const abs = d->filename.onlyPath().absFileName();
3000 int last = abs.length() - 1;
3002 return abs[last] == '/' ? abs : abs + '/';
3006 bool Buffer::isReadonly() const
3008 return d->read_only;
3012 void Buffer::setParent(Buffer const * buffer)
3014 // Avoids recursive include.
3015 d->setParent(buffer == this ? 0 : buffer);
3020 Buffer const * Buffer::parent() const
3026 ListOfBuffers Buffer::allRelatives() const
3028 ListOfBuffers lb = masterBuffer()->getDescendents();
3029 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3034 Buffer const * Buffer::masterBuffer() const
3036 // FIXME Should be make sure we are not in some kind
3037 // of recursive include? A -> B -> A will crash this.
3038 Buffer const * const pbuf = d->parent();
3042 return pbuf->masterBuffer();
3046 bool Buffer::isChild(Buffer * child) const
3048 return d->children_positions.find(child) != d->children_positions.end();
3052 DocIterator Buffer::firstChildPosition(Buffer const * child)
3054 Impl::BufferPositionMap::iterator it;
3055 it = d->children_positions.find(child);
3056 if (it == d->children_positions.end())
3057 return DocIterator(this);
3062 bool Buffer::hasChildren() const
3064 return !d->children_positions.empty();
3068 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3070 // loop over children
3071 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3072 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3073 for (; it != end; ++it) {
3074 Buffer * child = const_cast<Buffer *>(it->first);
3076 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3077 if (bit != clist.end())
3079 clist.push_back(child);
3081 // there might be grandchildren
3082 child->collectChildren(clist, true);
3087 ListOfBuffers Buffer::getChildren() const
3090 collectChildren(v, false);
3091 // Make sure we have not included ourselves.
3092 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3093 if (bit != v.end()) {
3094 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3101 ListOfBuffers Buffer::getDescendents() const
3104 collectChildren(v, true);
3105 // Make sure we have not included ourselves.
3106 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3107 if (bit != v.end()) {
3108 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3115 template<typename M>
3116 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3121 typename M::const_iterator it = m.lower_bound(x);
3122 if (it == m.begin())
3130 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3131 DocIterator const & pos) const
3133 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3135 // if paragraphs have no macro context set, pos will be empty
3139 // we haven't found anything yet
3140 DocIterator bestPos = owner_->par_iterator_begin();
3141 MacroData const * bestData = 0;
3143 // find macro definitions for name
3144 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3145 if (nameIt != macros.end()) {
3146 // find last definition in front of pos or at pos itself
3147 PositionScopeMacroMap::const_iterator it
3148 = greatest_below(nameIt->second, pos);
3149 if (it != nameIt->second.end()) {
3151 // scope ends behind pos?
3152 if (pos < it->second.scope) {
3153 // Looks good, remember this. If there
3154 // is no external macro behind this,
3155 // we found the right one already.
3156 bestPos = it->first;
3157 bestData = &it->second.macro;
3161 // try previous macro if there is one
3162 if (it == nameIt->second.begin())
3169 // find macros in included files
3170 PositionScopeBufferMap::const_iterator it
3171 = greatest_below(position_to_children, pos);
3172 if (it == position_to_children.end())
3173 // no children before
3177 // do we know something better (i.e. later) already?
3178 if (it->first < bestPos )
3181 // scope ends behind pos?
3182 if (pos < it->second.scope
3183 && (cloned_buffer_ ||
3184 theBufferList().isLoaded(it->second.buffer))) {
3185 // look for macro in external file
3187 MacroData const * data
3188 = it->second.buffer->getMacro(name, false);
3191 bestPos = it->first;
3197 // try previous file if there is one
3198 if (it == position_to_children.begin())
3203 // return the best macro we have found
3208 MacroData const * Buffer::getMacro(docstring const & name,
3209 DocIterator const & pos, bool global) const
3214 // query buffer macros
3215 MacroData const * data = d->getBufferMacro(name, pos);
3219 // If there is a master buffer, query that
3220 Buffer const * const pbuf = d->parent();
3222 d->macro_lock = true;
3223 MacroData const * macro = pbuf->getMacro(
3224 name, *this, false);
3225 d->macro_lock = false;
3231 data = MacroTable::globalMacros().get(name);
3240 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3242 // set scope end behind the last paragraph
3243 DocIterator scope = par_iterator_begin();
3244 scope.pit() = scope.lastpit() + 1;
3246 return getMacro(name, scope, global);
3250 MacroData const * Buffer::getMacro(docstring const & name,
3251 Buffer const & child, bool global) const
3253 // look where the child buffer is included first
3254 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3255 if (it == d->children_positions.end())
3258 // check for macros at the inclusion position
3259 return getMacro(name, it->second, global);
3263 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3265 pit_type const lastpit = it.lastpit();
3267 // look for macros in each paragraph
3268 while (it.pit() <= lastpit) {
3269 Paragraph & par = it.paragraph();
3271 // iterate over the insets of the current paragraph
3272 InsetList const & insets = par.insetList();
3273 InsetList::const_iterator iit = insets.begin();
3274 InsetList::const_iterator end = insets.end();
3275 for (; iit != end; ++iit) {
3276 it.pos() = iit->pos;
3278 // is it a nested text inset?
3279 if (iit->inset->asInsetText()) {
3280 // Inset needs its own scope?
3281 InsetText const * itext = iit->inset->asInsetText();
3282 bool newScope = itext->isMacroScope();
3284 // scope which ends just behind the inset
3285 DocIterator insetScope = it;
3288 // collect macros in inset
3289 it.push_back(CursorSlice(*iit->inset));
3290 updateMacros(it, newScope ? insetScope : scope);
3295 if (iit->inset->asInsetTabular()) {
3296 CursorSlice slice(*iit->inset);
3297 size_t const numcells = slice.nargs();
3298 for (; slice.idx() < numcells; slice.forwardIdx()) {
3299 it.push_back(slice);
3300 updateMacros(it, scope);
3306 // is it an external file?
3307 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3308 // get buffer of external file
3309 InsetInclude const & inset =
3310 static_cast<InsetInclude const &>(*iit->inset);
3312 Buffer * child = inset.getChildBuffer();
3317 // register its position, but only when it is
3318 // included first in the buffer
3319 if (children_positions.find(child) ==
3320 children_positions.end())
3321 children_positions[child] = it;
3323 // register child with its scope
3324 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3328 InsetMath * im = iit->inset->asInsetMath();
3329 if (doing_export && im) {
3330 InsetMathHull * hull = im->asHullInset();
3332 hull->recordLocation(it);
3335 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3339 MathMacroTemplate & macroTemplate =
3340 *iit->inset->asInsetMath()->asMacroTemplate();
3341 MacroContext mc(owner_, it);
3342 macroTemplate.updateToContext(mc);
3345 bool valid = macroTemplate.validMacro();
3346 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3347 // then the BufferView's cursor will be invalid in
3348 // some cases which leads to crashes.
3353 // FIXME (Abdel), I don't understand why we pass 'it' here
3354 // instead of 'macroTemplate' defined above... is this correct?
3355 macros[macroTemplate.name()][it] =
3356 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3366 void Buffer::updateMacros() const
3371 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3373 // start with empty table
3375 d->children_positions.clear();
3376 d->position_to_children.clear();
3378 // Iterate over buffer, starting with first paragraph
3379 // The scope must be bigger than any lookup DocIterator
3380 // later. For the global lookup, lastpit+1 is used, hence
3381 // we use lastpit+2 here.
3382 DocIterator it = par_iterator_begin();
3383 DocIterator outerScope = it;
3384 outerScope.pit() = outerScope.lastpit() + 2;
3385 d->updateMacros(it, outerScope);
3389 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3391 InsetIterator it = inset_iterator_begin(inset());
3392 InsetIterator const end = inset_iterator_end(inset());
3393 for (; it != end; ++it) {
3394 if (it->lyxCode() == BRANCH_CODE) {
3395 InsetBranch & br = static_cast<InsetBranch &>(*it);
3396 docstring const name = br.branch();
3397 if (!from_master && !params().branchlist().find(name))
3398 result.push_back(name);
3399 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3400 result.push_back(name);
3403 if (it->lyxCode() == INCLUDE_CODE) {
3404 // get buffer of external file
3405 InsetInclude const & ins =
3406 static_cast<InsetInclude const &>(*it);
3407 Buffer * child = ins.getChildBuffer();
3410 child->getUsedBranches(result, true);
3413 // remove duplicates
3418 void Buffer::updateMacroInstances(UpdateType utype) const
3420 LYXERR(Debug::MACROS, "updateMacroInstances for "
3421 << d->filename.onlyFileName());
3422 DocIterator it = doc_iterator_begin(this);
3424 DocIterator const end = doc_iterator_end(this);
3425 for (; it != end; it.forwardInset()) {
3426 // look for MathData cells in InsetMathNest insets
3427 InsetMath * minset = it.nextInset()->asInsetMath();
3431 // update macro in all cells of the InsetMathNest
3432 DocIterator::idx_type n = minset->nargs();
3433 MacroContext mc = MacroContext(this, it);
3434 for (DocIterator::idx_type i = 0; i < n; ++i) {
3435 MathData & data = minset->cell(i);
3436 data.updateMacros(0, mc, utype);
3442 void Buffer::listMacroNames(MacroNameSet & macros) const
3447 d->macro_lock = true;
3449 // loop over macro names
3450 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3451 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3452 for (; nameIt != nameEnd; ++nameIt)
3453 macros.insert(nameIt->first);
3455 // loop over children
3456 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3457 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3458 for (; it != end; ++it)
3459 it->first->listMacroNames(macros);
3462 Buffer const * const pbuf = d->parent();
3464 pbuf->listMacroNames(macros);
3466 d->macro_lock = false;
3470 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3472 Buffer const * const pbuf = d->parent();
3477 pbuf->listMacroNames(names);
3480 MacroNameSet::iterator it = names.begin();
3481 MacroNameSet::iterator end = names.end();
3482 for (; it != end; ++it) {
3484 MacroData const * data =
3485 pbuf->getMacro(*it, *this, false);
3487 macros.insert(data);
3489 // we cannot access the original MathMacroTemplate anymore
3490 // here to calls validate method. So we do its work here manually.
3491 // FIXME: somehow make the template accessible here.
3492 if (data->optionals() > 0)
3493 features.require("xargs");
3499 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3502 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3504 RefCache::iterator it = d->ref_cache_.find(label);
3505 if (it != d->ref_cache_.end())
3506 return it->second.second;
3508 static InsetLabel const * dummy_il = 0;
3509 static References const dummy_refs;
3510 it = d->ref_cache_.insert(
3511 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3512 return it->second.second;
3516 Buffer::References const & Buffer::references(docstring const & label) const
3518 return const_cast<Buffer *>(this)->getReferenceCache(label);
3522 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3524 References & refs = getReferenceCache(label);
3525 refs.push_back(make_pair(inset, it));
3529 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3531 masterBuffer()->d->ref_cache_[label].first = il;
3535 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3537 return masterBuffer()->d->ref_cache_[label].first;
3541 void Buffer::clearReferenceCache() const
3544 d->ref_cache_.clear();
3548 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3550 //FIXME: This does not work for child documents yet.
3551 reloadBibInfoCache();
3553 // Check if the label 'from' appears more than once
3554 BiblioInfo const & keys = masterBibInfo();
3555 BiblioInfo::const_iterator bit = keys.begin();
3556 BiblioInfo::const_iterator bend = keys.end();
3557 vector<docstring> labels;
3559 for (; bit != bend; ++bit)
3561 labels.push_back(bit->first);
3563 if (count(labels.begin(), labels.end(), from) > 1)
3566 string const paramName = "key";
3567 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3568 if (it->lyxCode() != CITE_CODE)
3570 InsetCommand * inset = it->asInsetCommand();
3571 docstring const oldValue = inset->getParam(paramName);
3572 if (oldValue == from)
3573 inset->setParam(paramName, to);
3578 void Buffer::getSourceCode(odocstream & os, string const & format,
3579 pit_type par_begin, pit_type par_end,
3580 OutputWhat output, bool master) const
3582 OutputParams runparams(¶ms().encoding());
3583 runparams.nice = true;
3584 runparams.flavor = params().getOutputFlavor(format);
3585 runparams.linelen = lyxrc.plaintext_linelen;
3586 // No side effect of file copying and image conversion
3587 runparams.dryrun = true;
3589 if (output == CurrentParagraph) {
3590 runparams.par_begin = par_begin;
3591 runparams.par_end = par_end;
3592 if (par_begin + 1 == par_end) {
3594 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3598 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3599 convert<docstring>(par_begin),
3600 convert<docstring>(par_end - 1))
3603 // output paragraphs
3604 if (runparams.flavor == OutputParams::LYX) {
3605 Paragraph const & par = text().paragraphs()[par_begin];
3607 depth_type dt = par.getDepth();
3608 par.write(ods, params(), dt);
3609 os << from_utf8(ods.str());
3610 } else if (runparams.flavor == OutputParams::HTML) {
3612 setMathFlavor(runparams);
3613 xhtmlParagraphs(text(), *this, xs, runparams);
3614 } else if (runparams.flavor == OutputParams::TEXT) {
3616 // FIXME Handles only one paragraph, unlike the others.
3617 // Probably should have some routine with a signature like them.
3618 writePlaintextParagraph(*this,
3619 text().paragraphs()[par_begin], os, runparams, dummy);
3620 } else if (params().isDocBook()) {
3621 docbookParagraphs(text(), *this, os, runparams);
3623 // If we are previewing a paragraph, even if this is the
3624 // child of some other buffer, let's cut the link here,
3625 // so that no concurring settings from the master
3626 // (e.g. branch state) interfere (see #8101).
3628 d->ignore_parent = true;
3629 // We need to validate the Buffer params' features here
3630 // in order to know if we should output polyglossia
3631 // macros (instead of babel macros)
3632 LaTeXFeatures features(*this, params(), runparams);
3633 params().validate(features);
3634 runparams.use_polyglossia = features.usePolyglossia();
3639 // latex or literate
3640 otexstream ots(os, texrow);
3643 latexParagraphs(*this, text(), ots, runparams);
3645 // Restore the parenthood
3647 d->ignore_parent = false;
3651 if (output == FullSource)
3652 os << _("Preview source code");
3653 else if (output == OnlyPreamble)
3654 os << _("Preview preamble");
3655 else if (output == OnlyBody)
3656 os << _("Preview body");
3658 if (runparams.flavor == OutputParams::LYX) {
3660 if (output == FullSource)
3662 else if (output == OnlyPreamble)
3663 params().writeFile(ods);
3664 else if (output == OnlyBody)
3666 os << from_utf8(ods.str());
3667 } else if (runparams.flavor == OutputParams::HTML) {
3668 writeLyXHTMLSource(os, runparams, output);
3669 } else if (runparams.flavor == OutputParams::TEXT) {
3670 if (output == OnlyPreamble) {
3671 os << "% "<< _("Plain text does not have a preamble.");
3673 writePlaintextFile(*this, os, runparams);
3674 } else if (params().isDocBook()) {
3675 writeDocBookSource(os, absFileName(), runparams, output);
3677 // latex or literate
3679 d->texrow.newline();
3680 d->texrow.newline();
3681 otexstream ots(os, d->texrow);
3683 runparams.is_child = true;
3684 writeLaTeXSource(ots, string(), runparams, output);
3690 ErrorList & Buffer::errorList(string const & type) const
3692 return d->errorLists[type];
3696 void Buffer::updateTocItem(std::string const & type,
3697 DocIterator const & dit) const
3700 d->gui_->updateTocItem(type, dit);
3704 void Buffer::structureChanged() const
3707 d->gui_->structureChanged();
3711 void Buffer::errors(string const & err, bool from_master) const
3714 d->gui_->errors(err, from_master);
3718 void Buffer::message(docstring const & msg) const
3721 d->gui_->message(msg);
3725 void Buffer::setBusy(bool on) const
3728 d->gui_->setBusy(on);
3732 void Buffer::updateTitles() const
3735 d->wa_->updateTitles();
3739 void Buffer::resetAutosaveTimers() const
3742 d->gui_->resetAutosaveTimers();
3746 bool Buffer::hasGuiDelegate() const
3752 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3761 class AutoSaveBuffer : public ForkedProcess {
3764 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3765 : buffer_(buffer), fname_(fname) {}
3767 virtual shared_ptr<ForkedProcess> clone() const
3769 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3774 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3775 from_utf8(fname_.absFileName())));
3776 return run(DontWait);
3780 virtual int generateChild();
3782 Buffer const & buffer_;
3787 int AutoSaveBuffer::generateChild()
3789 #if defined(__APPLE__)
3790 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3791 * We should use something else like threads.
3793 * Since I do not know how to determine at run time what is the OS X
3794 * version, I just disable forking altogether for now (JMarc)
3796 pid_t const pid = -1;
3798 // tmp_ret will be located (usually) in /tmp
3799 // will that be a problem?
3800 // Note that this calls ForkedCalls::fork(), so it's
3801 // ok cross-platform.
3802 pid_t const pid = fork();
3803 // If you want to debug the autosave
3804 // you should set pid to -1, and comment out the fork.
3805 if (pid != 0 && pid != -1)
3809 // pid = -1 signifies that lyx was unable
3810 // to fork. But we will do the save
3812 bool failed = false;
3813 TempFile tempfile("lyxautoXXXXXX.lyx");
3814 tempfile.setAutoRemove(false);
3815 FileName const tmp_ret = tempfile.name();
3816 if (!tmp_ret.empty()) {
3817 if (!buffer_.writeFile(tmp_ret))
3819 else if (!tmp_ret.moveTo(fname_))
3825 // failed to write/rename tmp_ret so try writing direct
3826 if (!buffer_.writeFile(fname_)) {
3827 // It is dangerous to do this in the child,
3828 // but safe in the parent, so...
3829 if (pid == -1) // emit message signal.
3830 buffer_.message(_("Autosave failed!"));
3834 if (pid == 0) // we are the child so...
3843 FileName Buffer::getEmergencyFileName() const
3845 return FileName(d->filename.absFileName() + ".emergency");
3849 FileName Buffer::getAutosaveFileName() const
3851 // if the document is unnamed try to save in the backup dir, else
3852 // in the default document path, and as a last try in the filePath,
3853 // which will most often be the temporary directory
3856 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3857 : lyxrc.backupdir_path;
3858 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3861 string const fname = "#" + d->filename.onlyFileName() + "#";
3863 return makeAbsPath(fname, fpath);
3867 void Buffer::removeAutosaveFile() const
3869 FileName const f = getAutosaveFileName();
3875 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3877 FileName const newauto = getAutosaveFileName();
3879 if (newauto != oldauto && oldauto.exists())
3880 if (!oldauto.moveTo(newauto))
3881 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3885 bool Buffer::autoSave() const
3887 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3888 if (buf->d->bak_clean || isReadonly())
3891 message(_("Autosaving current document..."));
3892 buf->d->bak_clean = true;
3894 FileName const fname = getAutosaveFileName();
3895 LASSERT(d->cloned_buffer_, return false);
3897 // If this buffer is cloned, we assume that
3898 // we are running in a separate thread already.
3899 TempFile tempfile("lyxautoXXXXXX.lyx");
3900 tempfile.setAutoRemove(false);
3901 FileName const tmp_ret = tempfile.name();
3902 if (!tmp_ret.empty()) {
3904 // assume successful write of tmp_ret
3905 if (tmp_ret.moveTo(fname))
3908 // failed to write/rename tmp_ret so try writing direct
3909 return writeFile(fname);
3913 void Buffer::setExportStatus(bool e) const
3915 d->doing_export = e;
3916 ListOfBuffers clist = getDescendents();
3917 ListOfBuffers::const_iterator cit = clist.begin();
3918 ListOfBuffers::const_iterator const cen = clist.end();
3919 for (; cit != cen; ++cit)
3920 (*cit)->d->doing_export = e;
3924 bool Buffer::isExporting() const
3926 return d->doing_export;
3930 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3934 return doExport(target, put_in_tempdir, result_file);
3937 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3938 string & result_file) const
3940 bool const update_unincluded =
3941 params().maintain_unincluded_children
3942 && !params().getIncludedChildren().empty();
3944 // (1) export with all included children (omit \includeonly)
3945 if (update_unincluded) {
3946 ExportStatus const status =
3947 doExport(target, put_in_tempdir, true, result_file);
3948 if (status != ExportSuccess)
3951 // (2) export with included children only
3952 return doExport(target, put_in_tempdir, false, result_file);
3956 void Buffer::setMathFlavor(OutputParams & op) const
3958 switch (params().html_math_output) {
3959 case BufferParams::MathML:
3960 op.math_flavor = OutputParams::MathAsMathML;
3962 case BufferParams::HTML:
3963 op.math_flavor = OutputParams::MathAsHTML;
3965 case BufferParams::Images:
3966 op.math_flavor = OutputParams::MathAsImages;
3968 case BufferParams::LaTeX:
3969 op.math_flavor = OutputParams::MathAsLaTeX;
3975 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3976 bool includeall, string & result_file) const
3978 LYXERR(Debug::FILES, "target=" << target);
3979 OutputParams runparams(¶ms().encoding());
3980 string format = target;
3981 string dest_filename;
3982 size_t pos = target.find(' ');
3983 if (pos != string::npos) {
3984 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3985 format = target.substr(0, pos);
3986 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3987 FileName(dest_filename).onlyPath().createPath();
3988 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3990 MarkAsExporting exporting(this);
3991 string backend_format;
3992 runparams.flavor = OutputParams::LATEX;
3993 runparams.linelen = lyxrc.plaintext_linelen;
3994 runparams.includeall = includeall;
3995 vector<string> backs = params().backends();
3996 Converters converters = theConverters();
3997 bool need_nice_file = false;
3998 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3999 // Get shortest path to format
4000 converters.buildGraph();
4001 Graph::EdgePath path;
4002 for (vector<string>::const_iterator it = backs.begin();
4003 it != backs.end(); ++it) {
4004 Graph::EdgePath p = converters.getPath(*it, format);
4005 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4006 backend_format = *it;
4011 if (!put_in_tempdir) {
4012 // Only show this alert if this is an export to a non-temporary
4013 // file (not for previewing).
4014 Alert::error(_("Couldn't export file"), bformat(
4015 _("No information for exporting the format %1$s."),
4016 formats.prettyName(format)));
4018 return ExportNoPathToFormat;
4020 runparams.flavor = converters.getFlavor(path, this);
4021 Graph::EdgePath::const_iterator it = path.begin();
4022 Graph::EdgePath::const_iterator en = path.end();
4023 for (; it != en; ++it)
4024 if (theConverters().get(*it).nice()) {
4025 need_nice_file = true;
4030 backend_format = format;
4031 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4032 // FIXME: Don't hardcode format names here, but use a flag
4033 if (backend_format == "pdflatex")
4034 runparams.flavor = OutputParams::PDFLATEX;
4035 else if (backend_format == "luatex")
4036 runparams.flavor = OutputParams::LUATEX;
4037 else if (backend_format == "dviluatex")
4038 runparams.flavor = OutputParams::DVILUATEX;
4039 else if (backend_format == "xetex")
4040 runparams.flavor = OutputParams::XETEX;
4043 string filename = latexName(false);
4044 filename = addName(temppath(), filename);
4045 filename = changeExtension(filename,
4046 formats.extension(backend_format));
4047 LYXERR(Debug::FILES, "filename=" << filename);
4049 // Plain text backend
4050 if (backend_format == "text") {
4051 runparams.flavor = OutputParams::TEXT;
4052 writePlaintextFile(*this, FileName(filename), runparams);
4055 else if (backend_format == "xhtml") {
4056 runparams.flavor = OutputParams::HTML;
4057 setMathFlavor(runparams);
4058 makeLyXHTMLFile(FileName(filename), runparams);
4059 } else if (backend_format == "lyx")
4060 writeFile(FileName(filename));
4062 else if (params().isDocBook()) {
4063 runparams.nice = !put_in_tempdir;
4064 makeDocBookFile(FileName(filename), runparams);
4067 else if (backend_format == format || need_nice_file) {
4068 runparams.nice = true;
4069 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4070 if (d->cloned_buffer_)
4071 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4074 } else if (!lyxrc.tex_allows_spaces
4075 && contains(filePath(), ' ')) {
4076 Alert::error(_("File name error"),
4077 _("The directory path to the document cannot contain spaces."));
4078 return ExportTexPathHasSpaces;
4080 runparams.nice = false;
4081 bool const success = makeLaTeXFile(
4082 FileName(filename), filePath(), runparams);
4083 if (d->cloned_buffer_)
4084 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4089 string const error_type = (format == "program")
4090 ? "Build" : params().bufferFormat();
4091 ErrorList & error_list = d->errorLists[error_type];
4092 string const ext = formats.extension(format);
4093 FileName const tmp_result_file(changeExtension(filename, ext));
4094 bool const success = converters.convert(this, FileName(filename),
4095 tmp_result_file, FileName(absFileName()), backend_format, format,
4098 // Emit the signal to show the error list or copy it back to the
4099 // cloned Buffer so that it can be emitted afterwards.
4100 if (format != backend_format) {
4101 if (runparams.silent)
4103 else if (d->cloned_buffer_)
4104 d->cloned_buffer_->d->errorLists[error_type] =
4105 d->errorLists[error_type];
4108 // also to the children, in case of master-buffer-view
4109 ListOfBuffers clist = getDescendents();
4110 ListOfBuffers::const_iterator cit = clist.begin();
4111 ListOfBuffers::const_iterator const cen = clist.end();
4112 for (; cit != cen; ++cit) {
4113 if (runparams.silent)
4114 (*cit)->d->errorLists[error_type].clear();
4115 else if (d->cloned_buffer_) {
4116 // Enable reverse search by copying back the
4117 // texrow object to the cloned buffer.
4118 // FIXME: this is not thread safe.
4119 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4120 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4121 (*cit)->d->errorLists[error_type];
4123 (*cit)->errors(error_type, true);
4127 if (d->cloned_buffer_) {
4128 // Enable reverse dvi or pdf to work by copying back the texrow
4129 // object to the cloned buffer.
4130 // FIXME: There is a possibility of concurrent access to texrow
4131 // here from the main GUI thread that should be securized.
4132 d->cloned_buffer_->d->texrow = d->texrow;
4133 string const error_type = params().bufferFormat();
4134 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4138 if (put_in_tempdir) {
4139 result_file = tmp_result_file.absFileName();
4140 return success ? ExportSuccess : ExportConverterError;
4143 if (dest_filename.empty())
4144 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4146 result_file = dest_filename;
4147 // We need to copy referenced files (e. g. included graphics
4148 // if format == "dvi") to the result dir.
4149 vector<ExportedFile> const files =
4150 runparams.exportdata->externalFiles(format);
4151 string const dest = runparams.export_folder.empty() ?
4152 onlyPath(result_file) : runparams.export_folder;
4153 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4154 : force_overwrite == ALL_FILES;
4155 CopyStatus status = use_force ? FORCE : SUCCESS;
4157 vector<ExportedFile>::const_iterator it = files.begin();
4158 vector<ExportedFile>::const_iterator const en = files.end();
4159 for (; it != en && status != CANCEL; ++it) {
4160 string const fmt = formats.getFormatFromFile(it->sourceName);
4161 string fixedName = it->exportName;
4162 if (!runparams.export_folder.empty()) {
4163 // Relative pathnames starting with ../ will be sanitized
4164 // if exporting to a different folder
4165 while (fixedName.substr(0, 3) == "../")
4166 fixedName = fixedName.substr(3, fixedName.length() - 3);
4168 FileName fixedFileName = makeAbsPath(fixedName, dest);
4169 fixedFileName.onlyPath().createPath();
4170 status = copyFile(fmt, it->sourceName,
4172 it->exportName, status == FORCE,
4173 runparams.export_folder.empty());
4176 if (status == CANCEL) {
4177 message(_("Document export cancelled."));
4178 return ExportCancel;
4181 if (tmp_result_file.exists()) {
4182 // Finally copy the main file
4183 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4184 : force_overwrite != NO_FILES;
4185 if (status == SUCCESS && use_force)
4187 status = copyFile(format, tmp_result_file,
4188 FileName(result_file), result_file,
4190 if (status == CANCEL) {
4191 message(_("Document export cancelled."));
4192 return ExportCancel;
4194 message(bformat(_("Document exported as %1$s "
4196 formats.prettyName(format),
4197 makeDisplayPath(result_file)));
4200 // This must be a dummy converter like fax (bug 1888)
4201 message(bformat(_("Document exported as %1$s"),
4202 formats.prettyName(format)));
4205 return success ? ExportSuccess : ExportConverterError;
4209 Buffer::ExportStatus Buffer::preview(string const & format) const
4211 bool const update_unincluded =
4212 params().maintain_unincluded_children
4213 && !params().getIncludedChildren().empty();
4214 return preview(format, update_unincluded);
4218 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4220 MarkAsExporting exporting(this);
4222 // (1) export with all included children (omit \includeonly)
4224 ExportStatus const status = doExport(format, true, true, result_file);
4225 if (status != ExportSuccess)
4228 // (2) export with included children only
4229 ExportStatus const status = doExport(format, true, false, result_file);
4230 FileName const previewFile(result_file);
4232 LATTEST (isClone());
4233 d->cloned_buffer_->d->preview_file_ = previewFile;
4234 d->cloned_buffer_->d->preview_format_ = format;
4236 if (status != ExportSuccess)
4238 if (previewFile.exists()) {
4239 if (!formats.view(*this, previewFile, format))
4240 return PreviewError;
4242 return PreviewSuccess;
4245 // Successful export but no output file?
4246 // Probably a bug in error detection.
4247 LATTEST (status != ExportSuccess);
4254 Buffer::ReadStatus Buffer::extractFromVC()
4256 bool const found = LyXVC::file_not_found_hook(d->filename);
4258 return ReadFileNotFound;
4259 if (!d->filename.isReadableFile())
4265 Buffer::ReadStatus Buffer::loadEmergency()
4267 FileName const emergencyFile = getEmergencyFileName();
4268 if (!emergencyFile.exists()
4269 || emergencyFile.lastModified() <= d->filename.lastModified())
4270 return ReadFileNotFound;
4272 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4273 docstring const text = bformat(_("An emergency save of the document "
4274 "%1$s exists.\n\nRecover emergency save?"), file);
4276 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4277 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4283 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4284 bool const success = (ret_llf == ReadSuccess);
4287 Alert::warning(_("File is read-only"),
4288 bformat(_("An emergency file is successfully loaded, "
4289 "but the original file %1$s is marked read-only. "
4290 "Please make sure to save the document as a different "
4291 "file."), from_utf8(d->filename.absFileName())));
4294 lyxvc().file_found_hook(d->filename);
4295 str = _("Document was successfully recovered.");
4297 str = _("Document was NOT successfully recovered.");
4298 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4299 makeDisplayPath(emergencyFile.absFileName()));
4301 int const del_emerg =
4302 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4303 _("&Remove"), _("&Keep"));
4304 if (del_emerg == 0) {
4305 emergencyFile.removeFile();
4307 Alert::warning(_("Emergency file deleted"),
4308 _("Do not forget to save your file now!"), true);
4310 return success ? ReadSuccess : ReadEmergencyFailure;
4313 int const del_emerg =
4314 Alert::prompt(_("Delete emergency file?"),
4315 _("Remove emergency file now?"), 1, 1,
4316 _("&Remove"), _("&Keep"));
4318 emergencyFile.removeFile();
4319 return ReadOriginal;
4329 Buffer::ReadStatus Buffer::loadAutosave()
4331 // Now check if autosave file is newer.
4332 FileName const autosaveFile = getAutosaveFileName();
4333 if (!autosaveFile.exists()
4334 || autosaveFile.lastModified() <= d->filename.lastModified())
4335 return ReadFileNotFound;
4337 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4338 docstring const text = bformat(_("The backup of the document %1$s "
4339 "is newer.\n\nLoad the backup instead?"), file);
4340 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4341 _("&Load backup"), _("Load &original"), _("&Cancel"));
4346 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4347 // the file is not saved if we load the autosave file.
4348 if (ret_llf == ReadSuccess) {
4350 Alert::warning(_("File is read-only"),
4351 bformat(_("A backup file is successfully loaded, "
4352 "but the original file %1$s is marked read-only. "
4353 "Please make sure to save the document as a "
4355 from_utf8(d->filename.absFileName())));
4358 lyxvc().file_found_hook(d->filename);
4361 return ReadAutosaveFailure;
4364 // Here we delete the autosave
4365 autosaveFile.removeFile();
4366 return ReadOriginal;
4374 Buffer::ReadStatus Buffer::loadLyXFile()
4376 if (!d->filename.isReadableFile()) {
4377 ReadStatus const ret_rvc = extractFromVC();
4378 if (ret_rvc != ReadSuccess)
4382 ReadStatus const ret_re = loadEmergency();
4383 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4386 ReadStatus const ret_ra = loadAutosave();
4387 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4390 return loadThisLyXFile(d->filename);
4394 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4396 return readFile(fn);
4400 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4402 TeXErrors::Errors::const_iterator it = terr.begin();
4403 TeXErrors::Errors::const_iterator end = terr.end();
4404 ListOfBuffers clist = getDescendents();
4405 ListOfBuffers::const_iterator cen = clist.end();
4407 for (; it != end; ++it) {
4410 int errorRow = it->error_in_line;
4411 Buffer const * buf = 0;
4413 if (it->child_name.empty())
4414 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4416 // The error occurred in a child
4417 ListOfBuffers::const_iterator cit = clist.begin();
4418 for (; cit != cen; ++cit) {
4419 string const child_name =
4420 DocFileName(changeExtension(
4421 (*cit)->absFileName(), "tex")).
4423 if (it->child_name != child_name)
4425 (*cit)->d->texrow.getIdFromRow(errorRow,
4426 id_start, pos_start);
4427 if (id_start != -1) {
4428 buf = d->cloned_buffer_
4429 ? (*cit)->d->cloned_buffer_->d->owner_
4430 : (*cit)->d->owner_;
4441 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4442 } while (found && id_start == id_end && pos_start == pos_end);
4444 if (id_start != id_end) {
4445 // Next registered position is outside the inset where
4446 // the error occurred, so signal end-of-paragraph
4450 errorList.push_back(ErrorItem(it->error_desc,
4451 it->error_text, id_start, pos_start, pos_end, buf));
4456 void Buffer::setBuffersForInsets() const
4458 inset().setBuffer(const_cast<Buffer &>(*this));
4462 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4464 LBUFERR(!text().paragraphs().empty());
4466 // Use the master text class also for child documents
4467 Buffer const * const master = masterBuffer();
4468 DocumentClass const & textclass = master->params().documentClass();
4470 // do this only if we are the top-level Buffer
4471 if (master == this) {
4472 textclass.counters().reset(from_ascii("bibitem"));
4473 reloadBibInfoCache();
4476 // keep the buffers to be children in this set. If the call from the
4477 // master comes back we can see which of them were actually seen (i.e.
4478 // via an InsetInclude). The remaining ones in the set need still be updated.
4479 static std::set<Buffer const *> bufToUpdate;
4480 if (scope == UpdateMaster) {
4481 // If this is a child document start with the master
4482 if (master != this) {
4483 bufToUpdate.insert(this);
4484 master->updateBuffer(UpdateMaster, utype);
4485 // If the master buffer has no gui associated with it, then the TocModel is
4486 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4487 // (bug 5699). The same happens if the master buffer is open in a different
4488 // window. This test catches both possibilities.
4489 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4490 // There remains a problem here: If there is another child open in yet a third
4491 // window, that TOC is not updated. So some more general solution is needed at
4493 if (master->d->gui_ != d->gui_)
4496 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4497 if (bufToUpdate.find(this) == bufToUpdate.end())
4501 // start over the counters in the master
4502 textclass.counters().reset();
4505 // update will be done below for this buffer
4506 bufToUpdate.erase(this);
4508 // update all caches
4509 clearReferenceCache();
4512 Buffer & cbuf = const_cast<Buffer &>(*this);
4515 ParIterator parit = cbuf.par_iterator_begin();
4516 updateBuffer(parit, utype);
4519 // TocBackend update will be done later.
4522 d->bibinfo_cache_valid_ = true;
4523 d->cite_labels_valid_ = true;
4524 cbuf.tocBackend().update(utype == OutputUpdate);
4525 if (scope == UpdateMaster)
4526 cbuf.structureChanged();
4530 static depth_type getDepth(DocIterator const & it)
4532 depth_type depth = 0;
4533 for (size_t i = 0 ; i < it.depth() ; ++i)
4534 if (!it[i].inset().inMathed())
4535 depth += it[i].paragraph().getDepth() + 1;
4536 // remove 1 since the outer inset does not count
4540 static depth_type getItemDepth(ParIterator const & it)
4542 Paragraph const & par = *it;
4543 LabelType const labeltype = par.layout().labeltype;
4545 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4548 // this will hold the lowest depth encountered up to now.
4549 depth_type min_depth = getDepth(it);
4550 ParIterator prev_it = it;
4553 --prev_it.top().pit();
4555 // start of nested inset: go to outer par
4557 if (prev_it.empty()) {
4558 // start of document: nothing to do
4563 // We search for the first paragraph with same label
4564 // that is not more deeply nested.
4565 Paragraph & prev_par = *prev_it;
4566 depth_type const prev_depth = getDepth(prev_it);
4567 if (labeltype == prev_par.layout().labeltype) {
4568 if (prev_depth < min_depth)
4569 return prev_par.itemdepth + 1;
4570 if (prev_depth == min_depth)
4571 return prev_par.itemdepth;
4573 min_depth = min(min_depth, prev_depth);
4574 // small optimization: if we are at depth 0, we won't
4575 // find anything else
4576 if (prev_depth == 0)
4582 static bool needEnumCounterReset(ParIterator const & it)
4584 Paragraph const & par = *it;
4585 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4586 depth_type const cur_depth = par.getDepth();
4587 ParIterator prev_it = it;
4588 while (prev_it.pit()) {
4589 --prev_it.top().pit();
4590 Paragraph const & prev_par = *prev_it;
4591 if (prev_par.getDepth() <= cur_depth)
4592 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4594 // start of nested inset: reset
4599 // set the label of a paragraph. This includes the counters.
4600 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4602 BufferParams const & bp = owner_->masterBuffer()->params();
4603 DocumentClass const & textclass = bp.documentClass();
4604 Paragraph & par = it.paragraph();
4605 Layout const & layout = par.layout();
4606 Counters & counters = textclass.counters();
4608 if (par.params().startOfAppendix()) {
4609 // We want to reset the counter corresponding to toplevel sectioning
4610 Layout const & lay = textclass.getTOCLayout();
4611 docstring const cnt = lay.counter;
4613 counters.reset(cnt);
4614 counters.appendix(true);
4616 par.params().appendix(counters.appendix());
4618 // Compute the item depth of the paragraph
4619 par.itemdepth = getItemDepth(it);
4621 if (layout.margintype == MARGIN_MANUAL) {
4622 if (par.params().labelWidthString().empty())
4623 par.params().labelWidthString(par.expandLabel(layout, bp));
4624 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4625 // we do not need to do anything here, since the empty case is
4626 // handled during export.
4628 par.params().labelWidthString(docstring());
4631 switch(layout.labeltype) {
4632 case LABEL_ITEMIZE: {
4633 // At some point of time we should do something more
4634 // clever here, like:
4635 // par.params().labelString(
4636 // bp.user_defined_bullet(par.itemdepth).getText());
4637 // for now, use a simple hardcoded label
4638 docstring itemlabel;
4639 switch (par.itemdepth) {
4641 itemlabel = char_type(0x2022);
4644 itemlabel = char_type(0x2013);
4647 itemlabel = char_type(0x2217);
4650 itemlabel = char_type(0x2219); // or 0x00b7
4653 par.params().labelString(itemlabel);
4657 case LABEL_ENUMERATE: {
4658 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4660 switch (par.itemdepth) {
4669 enumcounter += "iv";
4672 // not a valid enumdepth...
4676 // Maybe we have to reset the enumeration counter.
4677 if (needEnumCounterReset(it))
4678 counters.reset(enumcounter);
4679 counters.step(enumcounter, utype);
4681 string const & lang = par.getParLanguage(bp)->code();
4682 par.params().labelString(counters.theCounter(enumcounter, lang));
4687 case LABEL_SENSITIVE: {
4688 string const & type = counters.current_float();
4689 docstring full_label;
4691 full_label = owner_->B_("Senseless!!! ");
4693 docstring name = owner_->B_(textclass.floats().getType(type).name());
4694 if (counters.hasCounter(from_utf8(type))) {
4695 string const & lang = par.getParLanguage(bp)->code();
4696 counters.step(from_utf8(type), utype);
4697 full_label = bformat(from_ascii("%1$s %2$s:"),
4699 counters.theCounter(from_utf8(type), lang));
4701 full_label = bformat(from_ascii("%1$s #:"), name);
4703 par.params().labelString(full_label);
4707 case LABEL_NO_LABEL:
4708 par.params().labelString(docstring());
4712 case LABEL_CENTERED:
4713 case LABEL_STATIC: {
4714 docstring const & lcounter = layout.counter;
4715 if (!lcounter.empty()) {
4716 if (layout.toclevel <= bp.secnumdepth
4717 && (layout.latextype != LATEX_ENVIRONMENT
4718 || it.text()->isFirstInSequence(it.pit()))) {
4719 if (counters.hasCounter(lcounter))
4720 counters.step(lcounter, utype);
4721 par.params().labelString(par.expandLabel(layout, bp));
4723 par.params().labelString(docstring());
4725 par.params().labelString(par.expandLabel(layout, bp));
4731 par.params().labelString(par.expandLabel(layout, bp));
4736 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4738 // LASSERT: Is it safe to continue here, or should we just return?
4739 LASSERT(parit.pit() == 0, /**/);
4741 // Set the position of the text in the buffer to be able
4742 // to resolve macros in it.
4743 parit.text()->setMacrocontextPosition(parit);
4745 depth_type maxdepth = 0;
4746 pit_type const lastpit = parit.lastpit();
4747 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4748 // reduce depth if necessary
4749 if (parit->params().depth() > maxdepth) {
4750 /** FIXME: this function is const, but
4751 * nevertheless it modifies the buffer. To be
4752 * cleaner, one should modify the buffer in
4753 * another function, which is actually
4754 * non-const. This would however be costly in
4755 * terms of code duplication.
4757 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4758 parit->params().depth(maxdepth);
4760 maxdepth = parit->getMaxDepthAfter();
4762 if (utype == OutputUpdate) {
4763 // track the active counters
4764 // we have to do this for the master buffer, since the local
4765 // buffer isn't tracking anything.
4766 masterBuffer()->params().documentClass().counters().
4767 setActiveLayout(parit->layout());
4770 // set the counter for this paragraph
4771 d->setLabel(parit, utype);
4774 InsetList::const_iterator iit = parit->insetList().begin();
4775 InsetList::const_iterator end = parit->insetList().end();
4776 for (; iit != end; ++iit) {
4777 parit.pos() = iit->pos;
4778 iit->inset->updateBuffer(parit, utype);
4784 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4785 WordLangTuple & word_lang, docstring_list & suggestions) const
4789 suggestions.clear();
4790 word_lang = WordLangTuple();
4791 bool const to_end = to.empty();
4792 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4793 // OK, we start from here.
4794 for (; from != end; from.forwardPos()) {
4795 // We are only interested in text so remove the math CursorSlice.
4796 while (from.inMathed()) {
4800 // If from is at the end of the document (which is possible
4801 // when leaving the mathed) LyX will crash later otherwise.
4802 if (from.atEnd() || (!to_end && from >= end))
4805 from.paragraph().spellCheck();
4806 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4807 if (SpellChecker::misspelled(res)) {
4812 // Do not increase progress when from == to, otherwise the word
4813 // count will be wrong.
4823 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4825 bool inword = false;
4830 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4831 if (!dit.inTexted()) {
4836 Paragraph const & par = dit.paragraph();
4837 pos_type const pos = dit.pos();
4839 // Copied and adapted from isWordSeparator() in Paragraph
4840 if (pos == dit.lastpos()) {
4843 Inset const * ins = par.getInset(pos);
4844 if (ins && skipNoOutput && !ins->producesOutput()) {
4847 // stop if end of range was skipped
4848 if (!to.atEnd() && dit >= to)
4851 } else if (!par.isDeleted(pos)) {
4852 if (par.isWordSeparator(pos))
4858 if (ins && ins->isLetter())
4860 else if (ins && ins->isSpace())
4863 char_type const c = par.getChar(pos);
4864 if (isPrintableNonspace(c))
4866 else if (isSpace(c))
4876 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4878 d->updateStatistics(from, to, skipNoOutput);
4882 int Buffer::wordCount() const
4884 return d->wordCount();
4888 int Buffer::charCount(bool with_blanks) const
4890 return d->charCount(with_blanks);
4894 Buffer::ReadStatus Buffer::reload()
4897 // c.f. bug http://www.lyx.org/trac/ticket/6587
4898 removeAutosaveFile();
4899 // e.g., read-only status could have changed due to version control
4900 d->filename.refresh();
4901 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4903 // clear parent. this will get reset if need be.
4905 ReadStatus const status = loadLyXFile();
4906 if (status == ReadSuccess) {
4911 message(bformat(_("Document %1$s reloaded."), disp_fn));
4914 message(bformat(_("Could not reload document %1$s."), disp_fn));
4924 bool Buffer::saveAs(FileName const & fn)
4926 FileName const old_name = fileName();
4927 FileName const old_auto = getAutosaveFileName();
4928 bool const old_unnamed = isUnnamed();
4935 // bring the autosave file with us, just in case.
4936 moveAutosaveFile(old_auto);
4937 // validate version control data and
4938 // correct buffer title
4939 lyxvc().file_found_hook(fileName());
4941 // the file has now been saved to the new location.
4942 // we need to check that the locations of child buffers
4944 checkChildBuffers();
4945 checkMasterBuffer();
4949 // reset the old filename and unnamed state
4950 setFileName(old_name);
4951 setUnnamed(old_unnamed);
4957 // FIXME We could do better here, but it is complicated. What would be
4958 // nice is to offer either (a) to save the child buffer to an appropriate
4959 // location, so that it would "move with the master", or else (b) to update
4960 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4961 // complicated, because the code for this lives in GuiView.
4962 void Buffer::checkChildBuffers()
4964 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4965 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4966 for (; it != en; ++it) {
4967 DocIterator dit = it->second;
4968 Buffer * cbuf = const_cast<Buffer *>(it->first);
4969 if (!cbuf || !theBufferList().isLoaded(cbuf))
4971 Inset * inset = dit.nextInset();
4972 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4973 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4974 docstring const & incfile = inset_inc->getParam("filename");
4975 string oldloc = cbuf->absFileName();
4976 string newloc = makeAbsPath(to_utf8(incfile),
4977 onlyPath(absFileName())).absFileName();
4978 if (oldloc == newloc)
4980 // the location of the child file is incorrect.
4981 Alert::warning(_("Included File Invalid"),
4982 bformat(_("Saving this document to a new location has made the file:\n"
4984 "inaccessible. You will need to update the included filename."),
4985 from_utf8(oldloc)));
4987 inset_inc->setChildBuffer(0);
4989 // invalidate cache of children
4990 d->children_positions.clear();
4991 d->position_to_children.clear();
4995 // If a child has been saved under a different name/path, it might have been
4996 // orphaned. Therefore the master needs to be reset (bug 8161).
4997 void Buffer::checkMasterBuffer()
4999 Buffer const * const master = masterBuffer();
5003 // necessary to re-register the child (bug 5873)
5004 // FIXME: clean up updateMacros (here, only
5005 // child registering is needed).
5006 master->updateMacros();
5007 // (re)set master as master buffer, but only
5008 // if we are a real child
5009 if (master->isChild(this))