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;
222 typedef pair<DocIterator, MacroData> ScopeMacro;
223 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
224 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
225 /// map from the macro name to the position map,
226 /// which maps the macro definition position to the scope and the MacroData.
227 NamePositionScopeMacroMap macros;
228 /// This seem to change the way Buffer::getMacro() works
229 mutable bool macro_lock;
231 /// positions of child buffers in the buffer
232 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
233 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
234 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
235 /// position of children buffers in this buffer
236 BufferPositionMap children_positions;
237 /// map from children inclusion positions to their scope and their buffer
238 PositionScopeBufferMap position_to_children;
240 /// Container for all sort of Buffer dependant errors.
241 map<string, ErrorList> errorLists;
243 /// timestamp and checksum used to test if the file has been externally
244 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
246 unsigned long checksum_;
249 frontend::WorkAreaManager * wa_;
251 frontend::GuiBufferDelegate * gui_;
256 /// A cache for the bibfiles (including bibfiles of loaded child
257 /// documents), needed for appropriate update of natbib labels.
258 mutable support::FileNameList bibfiles_cache_;
260 // FIXME The caching mechanism could be improved. At present, we have a
261 // cache for each Buffer, that caches all the bibliography info for that
262 // Buffer. A more efficient solution would be to have a global cache per
263 // file, and then to construct the Buffer's bibinfo from that.
264 /// A cache for bibliography info
265 mutable BiblioInfo bibinfo_;
266 /// whether the bibinfo cache is valid
267 mutable bool bibinfo_cache_valid_;
268 /// whether the bibfile cache is valid
269 mutable bool bibfile_cache_valid_;
270 /// Cache of timestamps of .bib files
271 map<FileName, time_t> bibfile_status_;
272 /// Indicates whether the bibinfo has changed since the last time
273 /// we ran updateBuffer(), i.e., whether citation labels may need
275 mutable bool cite_labels_valid_;
277 mutable RefCache ref_cache_;
279 /// our Text that should be wrapped in an InsetText
283 PreviewLoader * preview_loader_;
285 /// This is here to force the test to be done whenever parent_buffer
287 Buffer const * parent() const
289 // ignore_parent temporarily "orphans" a buffer
290 // (e.g. if a child is compiled standalone)
293 // if parent_buffer is not loaded, then it has been unloaded,
294 // which means that parent_buffer is an invalid pointer. So we
295 // set it to null in that case.
296 // however, the BufferList doesn't know about cloned buffers, so
297 // they will always be regarded as unloaded. in that case, we hope
299 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
301 return parent_buffer;
305 void setParent(Buffer const * pb)
307 if (parent_buffer == pb)
310 if (!cloned_buffer_ && parent_buffer && pb)
311 LYXERR0("Warning: a buffer should not have two parents!");
313 if (!cloned_buffer_ && parent_buffer) {
314 parent_buffer->invalidateBibfileCache();
315 parent_buffer->invalidateBibinfoCache();
319 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
320 /// This one is useful for preview detached in a thread.
321 Buffer const * cloned_buffer_;
323 CloneList * clone_list_;
324 /// are we in the process of exporting this buffer?
325 mutable bool doing_export;
327 /// compute statistics
328 /// \p from initial position
329 /// \p to points to the end position
330 void updateStatistics(DocIterator & from, DocIterator & to,
331 bool skipNoOutput = true);
332 /// statistics accessor functions
333 int wordCount() const
337 int charCount(bool with_blanks) const
340 + (with_blanks ? blank_count_ : 0);
344 /// So we can force access via the accessors.
345 mutable Buffer const * parent_buffer;
354 /// Creates the per buffer temporary directory
355 static FileName createBufferTmpDir()
357 // FIXME This would be the ideal application for a TempDir class (like
358 // TempFile but for directories)
363 Mutex::Locker locker(&mutex);
364 counter = convert<string>(count++);
366 // We are in our own directory. Why bother to mangle name?
367 // In fact I wrote this code to circumvent a problematic behaviour
368 // (bug?) of EMX mkstemp().
369 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
372 if (!tmpfl.createDirectory(0777)) {
373 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
374 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
375 from_utf8(tmpfl.absFileName())));
381 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
382 Buffer const * cloned_buffer)
383 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
384 internal_buffer(false), read_only(readonly_), filename(file),
385 file_fully_loaded(false), ignore_parent(false), toc_backend(owner),
386 macro_lock(false), timestamp_(0), checksum_(0), wa_(0), gui_(0),
387 undo_(*owner), bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
388 cite_labels_valid_(false), preview_loader_(0),
389 cloned_buffer_(cloned_buffer), clone_list_(0),
390 doing_export(false), parent_buffer(0)
392 if (!cloned_buffer_) {
393 temppath = createBufferTmpDir();
394 lyxvc.setBuffer(owner_);
396 wa_ = new frontend::WorkAreaManager;
399 temppath = cloned_buffer_->d->temppath;
400 file_fully_loaded = true;
401 params = cloned_buffer_->d->params;
402 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
403 bibinfo_ = cloned_buffer_->d->bibinfo_;
404 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
405 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
406 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
407 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
408 unnamed = cloned_buffer_->d->unnamed;
409 internal_buffer = cloned_buffer_->d->internal_buffer;
413 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
414 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
416 LYXERR(Debug::INFO, "Buffer::Buffer()");
418 d->inset = new InsetText(*cloned_buffer->d->inset);
419 d->inset->setBuffer(*this);
420 // FIXME: optimize this loop somewhat, maybe by creating a new
421 // general recursive Inset::setId().
422 DocIterator it = doc_iterator_begin(this);
423 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
424 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
425 it.paragraph().setId(cloned_it.paragraph().id());
427 d->inset = new InsetText(this);
428 d->inset->setAutoBreakRows(true);
429 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
435 LYXERR(Debug::INFO, "Buffer::~Buffer()");
436 // here the buffer should take care that it is
437 // saved properly, before it goes into the void.
439 // GuiView already destroyed
443 // No need to do additional cleanups for internal buffer.
449 // this is in case of recursive includes: we won't try to delete
450 // ourselves as a child.
451 d->clone_list_->erase(this);
452 // loop over children
453 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
454 Impl::BufferPositionMap::iterator end = d->children_positions.end();
455 for (; it != end; ++it) {
456 Buffer * child = const_cast<Buffer *>(it->first);
457 if (d->clone_list_->erase(child))
460 // if we're the master buffer, then we should get rid of the list
463 // If this is not empty, we have leaked something. Worse, one of the
464 // children still has a reference to this list. But we will try to
465 // continue, rather than shut down.
466 LATTEST(d->clone_list_->empty());
467 list<CloneList *>::iterator it =
468 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
469 if (it == cloned_buffers.end()) {
470 // We will leak in this case, but it is safe to continue.
473 cloned_buffers.erase(it);
474 delete d->clone_list_;
476 // FIXME Do we really need to do this right before we delete d?
477 // clear references to children in macro tables
478 d->children_positions.clear();
479 d->position_to_children.clear();
481 // loop over children
482 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
483 Impl::BufferPositionMap::iterator end = d->children_positions.end();
484 for (; it != end; ++it) {
485 Buffer * child = const_cast<Buffer *>(it->first);
486 if (theBufferList().isLoaded(child))
487 theBufferList().releaseChild(this, child);
491 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
492 msg += emergencyWrite();
493 Alert::warning(_("Attempting to close changed document!"), msg);
496 // FIXME Do we really need to do this right before we delete d?
497 // clear references to children in macro tables
498 d->children_positions.clear();
499 d->position_to_children.clear();
501 if (!d->temppath.destroyDirectory()) {
502 Alert::warning(_("Could not remove temporary directory"),
503 bformat(_("Could not remove the temporary directory %1$s"),
504 from_utf8(d->temppath.absFileName())));
513 Buffer * Buffer::cloneFromMaster() const
516 cloned_buffers.push_back(new CloneList);
517 CloneList * clones = cloned_buffers.back();
519 masterBuffer()->cloneWithChildren(bufmap, clones);
521 // make sure we got cloned
522 BufferMap::const_iterator bit = bufmap.find(this);
523 LASSERT(bit != bufmap.end(), return 0);
524 Buffer * cloned_buffer = bit->second;
526 return cloned_buffer;
530 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
532 // have we already been cloned?
533 if (bufmap.find(this) != bufmap.end())
536 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
538 // The clone needs its own DocumentClass, since running updateBuffer() will
539 // modify it, and we would otherwise be sharing it with the original Buffer.
540 buffer_clone->params().makeDocumentClass(true);
542 cap::switchBetweenClasses(
543 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
544 static_cast<InsetText &>(buffer_clone->inset()), el);
546 bufmap[this] = buffer_clone;
547 clones->insert(buffer_clone);
548 buffer_clone->d->clone_list_ = clones;
549 buffer_clone->d->macro_lock = true;
550 buffer_clone->d->children_positions.clear();
552 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
553 // math macro caches need to be rethought and simplified.
554 // I am not sure wether we should handle Buffer cloning here or in BufferList.
555 // Right now BufferList knows nothing about buffer clones.
556 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
557 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
558 for (; it != end; ++it) {
559 DocIterator dit = it->first.clone(buffer_clone);
560 dit.setBuffer(buffer_clone);
561 Buffer * child = const_cast<Buffer *>(it->second.second);
563 child->cloneWithChildren(bufmap, clones);
564 BufferMap::iterator const bit = bufmap.find(child);
565 LASSERT(bit != bufmap.end(), continue);
566 Buffer * child_clone = bit->second;
568 Inset * inset = dit.nextInset();
569 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
570 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
571 inset_inc->setChildBuffer(child_clone);
572 child_clone->d->setParent(buffer_clone);
573 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
574 buffer_clone->setChild(dit, child_clone);
576 buffer_clone->d->macro_lock = false;
581 Buffer * Buffer::cloneBufferOnly() const {
582 cloned_buffers.push_back(new CloneList);
583 CloneList * clones = cloned_buffers.back();
584 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
586 // The clone needs its own DocumentClass, since running updateBuffer() will
587 // modify it, and we would otherwise be sharing it with the original Buffer.
588 buffer_clone->params().makeDocumentClass(true);
590 cap::switchBetweenClasses(
591 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
592 static_cast<InsetText &>(buffer_clone->inset()), el);
594 clones->insert(buffer_clone);
595 buffer_clone->d->clone_list_ = clones;
597 // we won't be cloning the children
598 buffer_clone->d->children_positions.clear();
603 bool Buffer::isClone() const
605 return d->cloned_buffer_;
609 void Buffer::changed(bool update_metrics) const
612 d->wa_->redrawAll(update_metrics);
616 frontend::WorkAreaManager & Buffer::workAreaManager() const
623 Text & Buffer::text() const
625 return d->inset->text();
629 Inset & Buffer::inset() const
635 BufferParams & Buffer::params()
641 BufferParams const & Buffer::params() const
647 BufferParams const & Buffer::masterParams() const
649 if (masterBuffer() == this)
652 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
653 // Copy child authors to the params. We need those pointers.
654 AuthorList const & child_authors = params().authors();
655 AuthorList::Authors::const_iterator it = child_authors.begin();
656 for (; it != child_authors.end(); ++it)
657 mparams.authors().record(*it);
662 ParagraphList & Buffer::paragraphs()
664 return text().paragraphs();
668 ParagraphList const & Buffer::paragraphs() const
670 return text().paragraphs();
674 LyXVC & Buffer::lyxvc()
680 LyXVC const & Buffer::lyxvc() const
686 string const Buffer::temppath() const
688 return d->temppath.absFileName();
692 TexRow & Buffer::texrow()
698 TexRow const & Buffer::texrow() const
704 TocBackend & Buffer::tocBackend() const
706 return d->toc_backend;
710 Undo & Buffer::undo()
716 void Buffer::setChild(DocIterator const & dit, Buffer * child)
718 d->children_positions[child] = dit;
722 string Buffer::latexName(bool const no_path) const
724 FileName latex_name =
725 makeLatexName(d->exportFileName());
726 return no_path ? latex_name.onlyFileName()
727 : latex_name.absFileName();
731 FileName Buffer::Impl::exportFileName() const
733 docstring const branch_suffix =
734 params.branchlist().getFileNameSuffix();
735 if (branch_suffix.empty())
738 string const name = filename.onlyFileNameWithoutExt()
739 + to_utf8(branch_suffix);
740 FileName res(filename.onlyPath().absFileName() + "/" + name);
741 res.changeExtension(filename.extension());
747 string Buffer::logName(LogType * type) const
749 string const filename = latexName(false);
751 if (filename.empty()) {
757 string const path = temppath();
759 FileName const fname(addName(temppath(),
760 onlyFileName(changeExtension(filename,
763 // FIXME: how do we know this is the name of the build log?
764 FileName const bname(
765 addName(path, onlyFileName(
766 changeExtension(filename,
767 formats.extension(params().bufferFormat()) + ".out"))));
769 // Also consider the master buffer log file
770 FileName masterfname = fname;
772 if (masterBuffer() != this) {
773 string const mlogfile = masterBuffer()->logName(&mtype);
774 masterfname = FileName(mlogfile);
777 // If no Latex log or Build log is newer, show Build log
778 if (bname.exists() &&
779 ((!fname.exists() && !masterfname.exists())
780 || (fname.lastModified() < bname.lastModified()
781 && masterfname.lastModified() < bname.lastModified()))) {
782 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
785 return bname.absFileName();
786 // If we have a newer master file log or only a master log, show this
787 } else if (fname != masterfname
788 && (!fname.exists() && (masterfname.exists()
789 || fname.lastModified() < masterfname.lastModified()))) {
790 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
793 return masterfname.absFileName();
795 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
798 return fname.absFileName();
802 void Buffer::setReadonly(bool const flag)
804 if (d->read_only != flag) {
811 void Buffer::setFileName(FileName const & fname)
813 bool const changed = fname != d->filename;
816 lyxvc().file_found_hook(fname);
817 setReadonly(d->filename.isReadOnly());
823 int Buffer::readHeader(Lexer & lex)
825 int unknown_tokens = 0;
827 int begin_header_line = -1;
829 // Initialize parameters that may be/go lacking in header:
830 params().branchlist().clear();
831 params().preamble.erase();
832 params().options.erase();
833 params().master.erase();
834 params().float_placement.erase();
835 params().paperwidth.erase();
836 params().paperheight.erase();
837 params().leftmargin.erase();
838 params().rightmargin.erase();
839 params().topmargin.erase();
840 params().bottommargin.erase();
841 params().headheight.erase();
842 params().headsep.erase();
843 params().footskip.erase();
844 params().columnsep.erase();
845 params().fonts_cjk.erase();
846 params().listings_params.clear();
847 params().clearLayoutModules();
848 params().clearRemovedModules();
849 params().clearIncludedChildren();
850 params().pdfoptions().clear();
851 params().indiceslist().clear();
852 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
853 params().isbackgroundcolor = false;
854 params().fontcolor = RGBColor(0, 0, 0);
855 params().isfontcolor = false;
856 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
857 params().boxbgcolor = RGBColor(0xFF, 0, 0);
858 params().html_latex_start.clear();
859 params().html_latex_end.clear();
860 params().html_math_img_scale = 1.0;
861 params().output_sync_macro.erase();
862 params().setLocalLayout(string(), false);
863 params().setLocalLayout(string(), true);
865 for (int i = 0; i < 4; ++i) {
866 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
867 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
870 ErrorList & errorList = d->errorLists["Parse"];
879 if (token == "\\end_header")
883 if (token == "\\begin_header") {
884 begin_header_line = line;
888 LYXERR(Debug::PARSER, "Handling document header token: `"
891 string unknown = params().readToken(lex, token, d->filename.onlyPath());
892 if (!unknown.empty()) {
893 if (unknown[0] != '\\' && token == "\\textclass") {
894 Alert::warning(_("Unknown document class"),
895 bformat(_("Using the default document class, because the "
896 "class %1$s is unknown."), from_utf8(unknown)));
899 docstring const s = bformat(_("Unknown token: "
903 errorList.push_back(ErrorItem(_("Document header error"),
908 if (begin_header_line) {
909 docstring const s = _("\\begin_header is missing");
910 errorList.push_back(ErrorItem(_("Document header error"),
914 params().makeDocumentClass();
916 return unknown_tokens;
921 // changed to be public and have one parameter
922 // Returns true if "\end_document" is not read (Asger)
923 bool Buffer::readDocument(Lexer & lex)
925 ErrorList & errorList = d->errorLists["Parse"];
928 // remove dummy empty par
929 paragraphs().clear();
931 if (!lex.checkFor("\\begin_document")) {
932 docstring const s = _("\\begin_document is missing");
933 errorList.push_back(ErrorItem(_("Document header error"),
939 if (params().output_changes) {
940 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
941 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
942 LaTeXFeatures::isAvailable("xcolor");
944 if (!dvipost && !xcolorulem) {
945 Alert::warning(_("Changes not shown in LaTeX output"),
946 _("Changes will not be highlighted in LaTeX output, "
947 "because neither dvipost nor xcolor/ulem are installed.\n"
948 "Please install these packages or redefine "
949 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
950 } else if (!xcolorulem) {
951 Alert::warning(_("Changes not shown in LaTeX output"),
952 _("Changes will not be highlighted in LaTeX output "
953 "when using pdflatex, because xcolor and ulem are not installed.\n"
954 "Please install both packages or redefine "
955 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
959 if (!parent() && !params().master.empty()) {
960 FileName const master_file = makeAbsPath(params().master,
961 onlyPath(absFileName()));
962 if (isLyXFileName(master_file.absFileName())) {
964 checkAndLoadLyXFile(master_file, true);
966 // necessary e.g. after a reload
967 // to re-register the child (bug 5873)
968 // FIXME: clean up updateMacros (here, only
969 // child registering is needed).
970 master->updateMacros();
971 // set master as master buffer, but only
972 // if we are a real child
973 if (master->isChild(this))
975 // if the master is not fully loaded
976 // it is probably just loading this
977 // child. No warning needed then.
978 else if (master->isFullyLoaded())
979 LYXERR0("The master '"
981 << "' assigned to this document ("
983 << ") does not include "
984 "this document. Ignoring the master assignment.");
989 // assure we have a default index
990 params().indiceslist().addDefault(B_("Index"));
993 bool const res = text().read(lex, errorList, d->inset);
995 // inform parent buffer about local macros
997 Buffer const * pbuf = parent();
998 UserMacroSet::const_iterator cit = usermacros.begin();
999 UserMacroSet::const_iterator end = usermacros.end();
1000 for (; cit != end; ++cit)
1001 pbuf->usermacros.insert(*cit);
1005 updateMacroInstances(InternalUpdate);
1010 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1012 Format const * fmt = formats.getFormat(format);
1015 // It is important to use the correct extension here, since some
1016 // converters create a wrong output file otherwise (e.g. html2latex)
1017 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1018 FileName const name(tempfile.name());
1019 ofdocstream os(name.toFilesystemEncoding().c_str());
1020 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1021 bool const success = !(os << contents).fail();
1024 bool converted = false;
1026 params().compressed = false;
1028 // remove dummy empty par
1029 paragraphs().clear();
1031 converted = importFile(format, name, errorList);
1040 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1042 if (!theConverters().isReachable(format, "lyx"))
1045 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1046 FileName const lyx(tempfile.name());
1047 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1048 return readFile(lyx) == ReadSuccess;
1054 bool Buffer::readString(string const & s)
1056 params().compressed = false;
1059 istringstream is(s);
1061 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1062 FileName const fn = tempfile.name();
1065 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1067 if (success && file_format != LYX_FORMAT) {
1068 // We need to call lyx2lyx, so write the input to a file
1069 ofstream os(fn.toFilesystemEncoding().c_str());
1072 // lyxvc in readFile
1073 if (readFile(fn) != ReadSuccess)
1077 if (readDocument(lex))
1083 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1087 if (!lex.setFile(fname)) {
1088 Alert::error(_("File Not Found"),
1089 bformat(_("Unable to open file `%1$s'."),
1090 from_utf8(fn.absFileName())));
1091 return ReadFileNotFound;
1095 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1096 if (ret_plf != ReadSuccess)
1099 if (file_format != LYX_FORMAT) {
1101 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1102 if (ret_clf != ReadSuccess)
1104 return readFile(tmpFile);
1107 // FIXME: InsetInfo needs to know whether the file is under VCS
1108 // during the parse process, so this has to be done before.
1109 lyxvc().file_found_hook(d->filename);
1111 if (readDocument(lex)) {
1112 Alert::error(_("Document format failure"),
1113 bformat(_("%1$s ended unexpectedly, which means"
1114 " that it is probably corrupted."),
1115 from_utf8(fn.absFileName())));
1116 return ReadDocumentFailure;
1119 d->file_fully_loaded = true;
1120 d->read_only = !d->filename.isWritable();
1121 params().compressed = formats.isZippedFile(d->filename);
1127 bool Buffer::isFullyLoaded() const
1129 return d->file_fully_loaded;
1133 void Buffer::setFullyLoaded(bool value)
1135 d->file_fully_loaded = value;
1139 PreviewLoader * Buffer::loader() const
1141 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1143 if (!d->preview_loader_)
1144 d->preview_loader_ = new PreviewLoader(*this);
1145 return d->preview_loader_;
1149 void Buffer::removePreviews() const
1151 delete d->preview_loader_;
1152 d->preview_loader_ = 0;
1156 void Buffer::updatePreviews() const
1158 PreviewLoader * ploader = loader();
1162 InsetIterator it = inset_iterator_begin(*d->inset);
1163 InsetIterator const end = inset_iterator_end(*d->inset);
1164 for (; it != end; ++it)
1165 it->addPreview(it, *ploader);
1167 ploader->startLoading();
1171 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1172 FileName const & fn, int & file_format) const
1174 if(!lex.checkFor("\\lyxformat")) {
1175 Alert::error(_("Document format failure"),
1176 bformat(_("%1$s is not a readable LyX document."),
1177 from_utf8(fn.absFileName())));
1178 return ReadNoLyXFormat;
1184 // LyX formats 217 and earlier were written as 2.17. This corresponds
1185 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1186 // these cases. See also: www.lyx.org/trac/changeset/1313.
1187 size_t dot = tmp_format.find_first_of(".,");
1188 if (dot != string::npos)
1189 tmp_format.erase(dot, 1);
1191 file_format = convert<int>(tmp_format);
1196 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1197 FileName & tmpfile, int from_format)
1199 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1200 tempfile.setAutoRemove(false);
1201 tmpfile = tempfile.name();
1202 if(tmpfile.empty()) {
1203 Alert::error(_("Conversion failed"),
1204 bformat(_("%1$s is from a different"
1205 " version of LyX, but a temporary"
1206 " file for converting it could"
1207 " not be created."),
1208 from_utf8(fn.absFileName())));
1209 return LyX2LyXNoTempFile;
1212 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1213 if (lyx2lyx.empty()) {
1214 Alert::error(_("Conversion script not found"),
1215 bformat(_("%1$s is from a different"
1216 " version of LyX, but the"
1217 " conversion script lyx2lyx"
1218 " could not be found."),
1219 from_utf8(fn.absFileName())));
1220 return LyX2LyXNotFound;
1224 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1225 ostringstream command;
1226 command << os::python()
1227 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1228 << " -t " << convert<string>(LYX_FORMAT)
1229 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1230 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1231 string const command_str = command.str();
1233 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1235 cmd_ret const ret = runCommand(command_str);
1236 if (ret.first != 0) {
1237 if (from_format < LYX_FORMAT) {
1238 Alert::error(_("Conversion script failed"),
1239 bformat(_("%1$s is from an older version"
1240 " of LyX and the lyx2lyx script"
1241 " failed to convert it."),
1242 from_utf8(fn.absFileName())));
1243 return LyX2LyXOlderFormat;
1245 Alert::error(_("Conversion script failed"),
1246 bformat(_("%1$s is from a newer version"
1247 " of LyX and the lyx2lyx script"
1248 " failed to convert it."),
1249 from_utf8(fn.absFileName())));
1250 return LyX2LyXNewerFormat;
1257 // Should probably be moved to somewhere else: BufferView? GuiView?
1258 bool Buffer::save() const
1260 docstring const file = makeDisplayPath(absFileName(), 20);
1261 d->filename.refresh();
1263 // check the read-only status before moving the file as a backup
1264 if (d->filename.exists()) {
1265 bool const read_only = !d->filename.isWritable();
1267 Alert::warning(_("File is read-only"),
1268 bformat(_("The file %1$s cannot be written because it "
1269 "is marked as read-only."), file));
1274 // ask if the disk file has been externally modified (use checksum method)
1275 if (fileName().exists() && isExternallyModified(checksum_method)) {
1277 bformat(_("Document %1$s has been externally modified. "
1278 "Are you sure you want to overwrite this file?"), file);
1279 int const ret = Alert::prompt(_("Overwrite modified file?"),
1280 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1285 // We don't need autosaves in the immediate future. (Asger)
1286 resetAutosaveTimers();
1288 // if the file does not yet exist, none of the backup activity
1289 // that follows is necessary
1290 if (!fileName().exists())
1291 return writeFile(fileName());
1293 // we first write the file to a new name, then move it to its
1294 // proper location once that has been done successfully. that
1295 // way we preserve the original file if something goes wrong.
1296 TempFile tempfile(fileName().onlyPath(), "tmpXXXXXX.lyx");
1297 FileName savefile(tempfile.name());
1299 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1300 if (!writeFile(savefile))
1303 // we will set this to false if we fail
1304 bool made_backup = true;
1305 bool const symlink = fileName().isSymLink();
1306 if (lyxrc.make_backup) {
1307 FileName backupName(absFileName() + '~');
1308 if (!lyxrc.backupdir_path.empty()) {
1309 string const mangledName =
1310 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1311 backupName = FileName(addName(lyxrc.backupdir_path,
1315 LYXERR(Debug::FILES, "Backing up original file to " <<
1316 backupName.absFileName());
1317 // Except file is symlink do not copy because of #6587.
1318 // Hard links have bad luck.
1319 made_backup = symlink ?
1320 fileName().copyTo(backupName):
1321 fileName().moveTo(backupName);
1324 Alert::error(_("Backup failure"),
1325 bformat(_("Cannot create backup file %1$s.\n"
1326 "Please check whether the directory exists and is writable."),
1327 from_utf8(backupName.absFileName())));
1328 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1332 // If we have no symlink, we can simply rename the temp file.
1333 // Otherwise, we need to copy it so the symlink stays intact.
1335 tempfile.setAutoRemove(false);
1337 (symlink ? savefile.copyTo(fileName(), true) : savefile.moveTo(fileName()))) {
1338 // saveCheckSum() was already called by writeFile(), but the
1339 // time stamp is invalidated by copying/moving
1345 Alert::error(_("Write failure"),
1346 bformat(_("Cannot move saved file to:\n %1$s.\n"
1347 "But the file has successfully been saved as:\n %2$s."),
1348 from_utf8(fileName().absFileName()),
1349 from_utf8(savefile.absFileName())));
1354 bool Buffer::writeFile(FileName const & fname) const
1356 if (d->read_only && fname == d->filename)
1359 bool retval = false;
1361 docstring const str = bformat(_("Saving document %1$s..."),
1362 makeDisplayPath(fname.absFileName()));
1365 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1367 if (params().compressed) {
1368 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1369 retval = ofs && write(ofs);
1371 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1372 retval = ofs && write(ofs);
1376 message(str + _(" could not write file!"));
1381 // removeAutosaveFile();
1384 message(str + _(" done."));
1390 docstring Buffer::emergencyWrite()
1392 // No need to save if the buffer has not changed.
1396 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1398 docstring user_message = bformat(
1399 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1401 // We try to save three places:
1402 // 1) Same place as document. Unless it is an unnamed doc.
1404 string s = absFileName();
1407 if (writeFile(FileName(s))) {
1409 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1410 return user_message;
1412 user_message += " " + _("Save failed! Trying again...\n");
1416 // 2) In HOME directory.
1417 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1419 lyxerr << ' ' << s << endl;
1420 if (writeFile(FileName(s))) {
1422 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1423 return user_message;
1426 user_message += " " + _("Save failed! Trying yet again...\n");
1428 // 3) In "/tmp" directory.
1429 // MakeAbsPath to prepend the current
1430 // drive letter on OS/2
1431 s = addName(package().temp_dir().absFileName(), absFileName());
1433 lyxerr << ' ' << s << endl;
1434 if (writeFile(FileName(s))) {
1436 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1437 return user_message;
1440 user_message += " " + _("Save failed! Bummer. Document is lost.");
1443 return user_message;
1447 bool Buffer::write(ostream & ofs) const
1450 // Use the standard "C" locale for file output.
1451 ofs.imbue(locale::classic());
1454 // The top of the file should not be written by params().
1456 // write out a comment in the top of the file
1457 // Important: Keep the version formatting in sync with lyx2lyx and
1458 // tex2lyx (bug 7951)
1459 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1460 << " created this file. For more info see http://www.lyx.org/\n"
1461 << "\\lyxformat " << LYX_FORMAT << "\n"
1462 << "\\begin_document\n";
1464 /// For each author, set 'used' to true if there is a change
1465 /// by this author in the document; otherwise set it to 'false'.
1466 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1467 AuthorList::Authors::const_iterator a_end = params().authors().end();
1468 for (; a_it != a_end; ++a_it)
1469 a_it->setUsed(false);
1471 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1472 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1473 for ( ; it != end; ++it)
1474 it->checkAuthors(params().authors());
1476 // now write out the buffer parameters.
1477 ofs << "\\begin_header\n";
1478 params().writeFile(ofs);
1479 ofs << "\\end_header\n";
1482 ofs << "\n\\begin_body\n";
1484 ofs << "\n\\end_body\n";
1486 // Write marker that shows file is complete
1487 ofs << "\\end_document" << endl;
1489 // Shouldn't really be needed....
1492 // how to check if close went ok?
1493 // Following is an attempt... (BE 20001011)
1495 // good() returns false if any error occured, including some
1496 // formatting error.
1497 // bad() returns true if something bad happened in the buffer,
1498 // which should include file system full errors.
1503 lyxerr << "File was not closed properly." << endl;
1510 bool Buffer::makeLaTeXFile(FileName const & fname,
1511 string const & original_path,
1512 OutputParams const & runparams_in,
1513 OutputWhat output) const
1515 OutputParams runparams = runparams_in;
1517 // This is necessary for LuaTeX/XeTeX with tex fonts.
1518 // See FIXME in BufferParams::encoding()
1519 if (runparams.isFullUnicode())
1520 runparams.encoding = encodings.fromLyXName("utf8-plain");
1522 string const encoding = runparams.encoding->iconvName();
1523 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1526 try { ofs.reset(encoding); }
1527 catch (iconv_codecvt_facet_exception const & e) {
1528 lyxerr << "Caught iconv exception: " << e.what() << endl;
1529 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1530 "verify that the support software for your encoding (%1$s) is "
1531 "properly installed"), from_ascii(encoding)));
1534 if (!openFileWrite(ofs, fname))
1537 ErrorList & errorList = d->errorLists["Export"];
1539 bool failed_export = false;
1540 otexstream os(ofs, d->texrow);
1542 // make sure we are ready to export
1543 // this needs to be done before we validate
1544 // FIXME Do we need to do this all the time? I.e., in children
1545 // of a master we are exporting?
1547 updateMacroInstances(OutputUpdate);
1550 os.texrow().reset();
1551 writeLaTeXSource(os, original_path, runparams, output);
1553 catch (EncodingException const & e) {
1554 odocstringstream ods;
1555 ods.put(e.failed_char);
1557 oss << "0x" << hex << e.failed_char << dec;
1558 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1559 " (code point %2$s)"),
1560 ods.str(), from_utf8(oss.str()));
1561 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1562 "representable in the chosen encoding.\n"
1563 "Changing the document encoding to utf8 could help."),
1564 e.par_id, e.pos, e.pos + 1));
1565 failed_export = true;
1567 catch (iconv_codecvt_facet_exception const & e) {
1568 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1569 _(e.what()), -1, 0, 0));
1570 failed_export = true;
1572 catch (exception const & e) {
1573 errorList.push_back(ErrorItem(_("conversion failed"),
1574 _(e.what()), -1, 0, 0));
1575 failed_export = true;
1578 lyxerr << "Caught some really weird exception..." << endl;
1584 failed_export = true;
1585 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1588 if (runparams_in.silent)
1592 return !failed_export;
1596 void Buffer::writeLaTeXSource(otexstream & os,
1597 string const & original_path,
1598 OutputParams const & runparams_in,
1599 OutputWhat output) const
1601 // The child documents, if any, shall be already loaded at this point.
1603 OutputParams runparams = runparams_in;
1605 // If we are compiling a file standalone, even if this is the
1606 // child of some other buffer, let's cut the link here, so the
1607 // file is really independent and no concurring settings from
1608 // the master (e.g. branch state) interfere (see #8100).
1609 if (!runparams.is_child)
1610 d->ignore_parent = true;
1612 // Classify the unicode characters appearing in math insets
1613 BufferEncodings::initUnicodeMath(*this);
1615 // validate the buffer.
1616 LYXERR(Debug::LATEX, " Validating buffer...");
1617 LaTeXFeatures features(*this, params(), runparams);
1619 // This is only set once per document (in master)
1620 if (!runparams.is_child)
1621 runparams.use_polyglossia = features.usePolyglossia();
1622 LYXERR(Debug::LATEX, " Buffer validation done.");
1624 bool const output_preamble =
1625 output == FullSource || output == OnlyPreamble;
1626 bool const output_body =
1627 output == FullSource || output == OnlyBody;
1629 // The starting paragraph of the coming rows is the
1630 // first paragraph of the document. (Asger)
1631 if (output_preamble && runparams.nice) {
1632 os << "%% LyX " << lyx_version << " created this file. "
1633 "For more info, see http://www.lyx.org/.\n"
1634 "%% Do not edit unless you really know what "
1637 LYXERR(Debug::INFO, "lyx document header finished");
1639 // There are a few differences between nice LaTeX and usual files:
1640 // usual files have \batchmode and special input@path to allow
1641 // inclusion of figures specified by an explicitly relative path
1642 // (i.e., a path starting with './' or '../') with either \input or
1643 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1644 // input@path is set when the actual parameter original_path is set.
1645 // This is done for usual tex-file, but not for nice-latex-file.
1646 // (Matthias 250696)
1647 // Note that input@path is only needed for something the user does
1648 // in the preamble, included .tex files or ERT, files included by
1649 // LyX work without it.
1650 if (output_preamble) {
1651 if (!runparams.nice) {
1652 // code for usual, NOT nice-latex-file
1653 os << "\\batchmode\n"; // changed from \nonstopmode
1655 if (!original_path.empty()) {
1657 // We don't know the encoding of inputpath
1658 docstring const inputpath = from_utf8(original_path);
1659 docstring uncodable_glyphs;
1660 Encoding const * const enc = runparams.encoding;
1662 for (size_t n = 0; n < inputpath.size(); ++n) {
1663 if (!enc->encodable(inputpath[n])) {
1664 docstring const glyph(1, inputpath[n]);
1665 LYXERR0("Uncodable character '"
1667 << "' in input path!");
1668 uncodable_glyphs += glyph;
1673 // warn user if we found uncodable glyphs.
1674 if (!uncodable_glyphs.empty()) {
1675 frontend::Alert::warning(
1676 _("Uncodable character in file path"),
1678 _("The path of your document\n"
1680 "contains glyphs that are unknown "
1681 "in the current document encoding "
1682 "(namely %2$s). This may result in "
1683 "incomplete output, unless "
1684 "TEXINPUTS contains the document "
1685 "directory and you don't use "
1686 "explicitly relative paths (i.e., "
1687 "paths starting with './' or "
1688 "'../') in the preamble or in ERT."
1689 "\n\nIn case of problems, choose "
1690 "an appropriate document encoding\n"
1691 "(such as utf8) or change the "
1693 inputpath, uncodable_glyphs));
1696 support::latex_path(original_path);
1697 if (contains(docdir, '#')) {
1698 docdir = subst(docdir, "#", "\\#");
1699 os << "\\catcode`\\#=11"
1700 "\\def\\#{#}\\catcode`\\#=6\n";
1702 if (contains(docdir, '%')) {
1703 docdir = subst(docdir, "%", "\\%");
1704 os << "\\catcode`\\%=11"
1705 "\\def\\%{%}\\catcode`\\%=14\n";
1707 os << "\\makeatletter\n"
1708 << "\\def\\input@path{{"
1709 << docdir << "/}}\n"
1710 << "\\makeatother\n";
1714 // get parent macros (if this buffer has a parent) which will be
1715 // written at the document begin further down.
1716 MacroSet parentMacros;
1717 listParentMacros(parentMacros, features);
1719 // Write the preamble
1720 runparams.use_babel = params().writeLaTeX(os, features,
1721 d->filename.onlyPath());
1723 // Japanese might be required only in some children of a document,
1724 // but once required, we must keep use_japanese true.
1725 runparams.use_japanese |= features.isRequired("japanese");
1728 // Restore the parenthood if needed
1729 if (!runparams.is_child)
1730 d->ignore_parent = false;
1735 os << "\\begin{document}\n";
1737 // output the parent macros
1738 MacroSet::iterator it = parentMacros.begin();
1739 MacroSet::iterator end = parentMacros.end();
1740 for (; it != end; ++it) {
1741 int num_lines = (*it)->write(os.os(), true);
1742 os.texrow().newlines(num_lines);
1745 } // output_preamble
1747 os.texrow().start(paragraphs().begin()->id(), 0);
1749 LYXERR(Debug::INFO, "preamble finished, now the body.");
1752 latexParagraphs(*this, text(), os, runparams);
1754 // Restore the parenthood if needed
1755 if (!runparams.is_child)
1756 d->ignore_parent = false;
1758 // add this just in case after all the paragraphs
1761 if (output_preamble) {
1762 os << "\\end{document}\n";
1763 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1765 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1767 runparams_in.encoding = runparams.encoding;
1769 // Just to be sure. (Asger)
1770 os.texrow().newline();
1772 //for (int i = 0; i<d->texrow.rows(); i++) {
1774 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1775 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1778 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1779 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1783 void Buffer::makeDocBookFile(FileName const & fname,
1784 OutputParams const & runparams,
1785 OutputWhat output) const
1787 LYXERR(Debug::LATEX, "makeDocBookFile...");
1790 if (!openFileWrite(ofs, fname))
1793 // make sure we are ready to export
1794 // this needs to be done before we validate
1796 updateMacroInstances(OutputUpdate);
1798 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1802 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1806 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1807 OutputParams const & runparams,
1808 OutputWhat output) const
1810 LaTeXFeatures features(*this, params(), runparams);
1815 DocumentClass const & tclass = params().documentClass();
1816 string const top_element = tclass.latexname();
1818 bool const output_preamble =
1819 output == FullSource || output == OnlyPreamble;
1820 bool const output_body =
1821 output == FullSource || output == OnlyBody;
1823 if (output_preamble) {
1824 if (runparams.flavor == OutputParams::XML)
1825 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1828 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1831 if (! tclass.class_header().empty())
1832 os << from_ascii(tclass.class_header());
1833 else if (runparams.flavor == OutputParams::XML)
1834 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1835 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1837 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1839 docstring preamble = from_utf8(params().preamble);
1840 if (runparams.flavor != OutputParams::XML ) {
1841 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1842 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1843 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1844 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1847 string const name = runparams.nice
1848 ? changeExtension(absFileName(), ".sgml") : fname;
1849 preamble += features.getIncludedFiles(name);
1850 preamble += features.getLyXSGMLEntities();
1852 if (!preamble.empty()) {
1853 os << "\n [ " << preamble << " ]";
1859 string top = top_element;
1861 if (runparams.flavor == OutputParams::XML)
1862 top += params().language->code();
1864 top += params().language->code().substr(0, 2);
1867 if (!params().options.empty()) {
1869 top += params().options;
1872 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1873 << " file was created by LyX " << lyx_version
1874 << "\n See http://www.lyx.org/ for more information -->\n";
1876 params().documentClass().counters().reset();
1878 sgml::openTag(os, top);
1880 docbookParagraphs(text(), *this, os, runparams);
1881 sgml::closeTag(os, top_element);
1886 void Buffer::makeLyXHTMLFile(FileName const & fname,
1887 OutputParams const & runparams) const
1889 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1892 if (!openFileWrite(ofs, fname))
1895 // make sure we are ready to export
1896 // this has to be done before we validate
1897 updateBuffer(UpdateMaster, OutputUpdate);
1898 updateMacroInstances(OutputUpdate);
1900 writeLyXHTMLSource(ofs, runparams, FullSource);
1904 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1908 void Buffer::writeLyXHTMLSource(odocstream & os,
1909 OutputParams const & runparams,
1910 OutputWhat output) const
1912 LaTeXFeatures features(*this, params(), runparams);
1914 d->bibinfo_.makeCitationLabels(*this);
1916 bool const output_preamble =
1917 output == FullSource || output == OnlyPreamble;
1918 bool const output_body =
1919 output == FullSource || output == OnlyBody || output == IncludedFile;
1921 if (output_preamble) {
1922 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1923 << "<!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"
1924 // FIXME Language should be set properly.
1925 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1927 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1928 // FIXME Presumably need to set this right
1929 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1931 docstring const & doctitle = features.htmlTitle();
1933 << (doctitle.empty() ?
1934 from_ascii("LyX Document") :
1935 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1938 docstring styles = features.getTClassHTMLPreamble();
1939 if (!styles.empty())
1940 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1942 styles = from_utf8(features.getPreambleSnippets());
1943 if (!styles.empty())
1944 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1946 // we will collect CSS information in a stream, and then output it
1947 // either here, as part of the header, or else in a separate file.
1948 odocstringstream css;
1949 styles = from_utf8(features.getCSSSnippets());
1950 if (!styles.empty())
1951 css << "/* LyX Provided Styles */\n" << styles << '\n';
1953 styles = features.getTClassHTMLStyles();
1954 if (!styles.empty())
1955 css << "/* Layout-provided Styles */\n" << styles << '\n';
1957 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1958 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1959 if (needfg || needbg) {
1960 css << "\nbody {\n";
1963 << from_ascii(X11hexname(params().fontcolor))
1966 css << " background-color: "
1967 << from_ascii(X11hexname(params().backgroundcolor))
1972 docstring const dstyles = css.str();
1973 if (!dstyles.empty()) {
1974 bool written = false;
1975 if (params().html_css_as_file) {
1976 // open a file for CSS info
1978 string const fcssname = addName(temppath(), "docstyle.css");
1979 FileName const fcssfile = FileName(fcssname);
1980 if (openFileWrite(ocss, fcssfile)) {
1984 // write link to header
1985 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
1987 runparams.exportdata->addExternalFile("xhtml", fcssfile);
1990 // we are here if the CSS is supposed to be written to the header
1991 // or if we failed to write it to an external file.
1993 os << "<style type='text/css'>\n"
2002 bool const output_body_tag = (output != IncludedFile);
2003 if (output_body_tag)
2006 if (output != IncludedFile)
2007 // if we're an included file, the counters are in the master.
2008 params().documentClass().counters().reset();
2009 xhtmlParagraphs(text(), *this, xs, runparams);
2010 if (output_body_tag)
2014 if (output_preamble)
2019 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2020 // Other flags: -wall -v0 -x
2021 int Buffer::runChktex()
2025 // get LaTeX-Filename
2026 FileName const path(temppath());
2027 string const name = addName(path.absFileName(), latexName());
2028 string const org_path = filePath();
2030 PathChanger p(path); // path to LaTeX file
2031 message(_("Running chktex..."));
2033 // Generate the LaTeX file if neccessary
2034 OutputParams runparams(¶ms().encoding());
2035 runparams.flavor = OutputParams::LATEX;
2036 runparams.nice = false;
2037 runparams.linelen = lyxrc.plaintext_linelen;
2038 makeLaTeXFile(FileName(name), org_path, runparams);
2041 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2042 int const res = chktex.run(terr); // run chktex
2045 Alert::error(_("chktex failure"),
2046 _("Could not run chktex successfully."));
2048 ErrorList & errlist = d->errorLists["ChkTeX"];
2050 bufferErrors(terr, errlist);
2055 if (runparams.silent)
2056 d->errorLists["ChkTeX"].clear();
2064 void Buffer::validate(LaTeXFeatures & features) const
2066 // Validate the buffer params, but not for included
2067 // files, since they also use the parent buffer's
2069 if (!features.runparams().is_child)
2070 params().validate(features);
2072 for_each(paragraphs().begin(), paragraphs().end(),
2073 bind(&Paragraph::validate, _1, ref(features)));
2075 if (lyxerr.debugging(Debug::LATEX)) {
2076 features.showStruct();
2081 void Buffer::getLabelList(vector<docstring> & list) const
2083 // If this is a child document, use the master's list instead.
2085 masterBuffer()->getLabelList(list);
2090 Toc & toc = d->toc_backend.toc("label");
2091 TocIterator toc_it = toc.begin();
2092 TocIterator end = toc.end();
2093 for (; toc_it != end; ++toc_it) {
2094 if (toc_it->depth() == 0)
2095 list.push_back(toc_it->str());
2100 void Buffer::updateBibfilesCache(UpdateScope scope) const
2102 // FIXME This is probably unnecssary, given where we call this.
2103 // If this is a child document, use the parent's cache instead.
2104 if (parent() && scope != UpdateChildOnly) {
2105 masterBuffer()->updateBibfilesCache();
2109 d->bibfiles_cache_.clear();
2110 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2111 if (it->lyxCode() == BIBTEX_CODE) {
2112 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2113 support::FileNameList const bibfiles = inset.getBibFiles();
2114 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2117 } else if (it->lyxCode() == INCLUDE_CODE) {
2118 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2119 Buffer const * const incbuf = inset.getChildBuffer();
2122 support::FileNameList const & bibfiles =
2123 incbuf->getBibfilesCache(UpdateChildOnly);
2124 if (!bibfiles.empty()) {
2125 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2131 d->bibfile_cache_valid_ = true;
2132 d->bibinfo_cache_valid_ = false;
2133 d->cite_labels_valid_ = false;
2137 void Buffer::invalidateBibinfoCache() const
2139 d->bibinfo_cache_valid_ = false;
2140 d->cite_labels_valid_ = false;
2141 // also invalidate the cache for the parent buffer
2142 Buffer const * const pbuf = d->parent();
2144 pbuf->invalidateBibinfoCache();
2148 void Buffer::invalidateBibfileCache() const
2150 d->bibfile_cache_valid_ = false;
2151 d->bibinfo_cache_valid_ = false;
2152 d->cite_labels_valid_ = false;
2153 // also invalidate the cache for the parent buffer
2154 Buffer const * const pbuf = d->parent();
2156 pbuf->invalidateBibfileCache();
2160 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2162 // FIXME This is probably unnecessary, given where we call this.
2163 // If this is a child document, use the master's cache instead.
2164 Buffer const * const pbuf = masterBuffer();
2165 if (pbuf != this && scope != UpdateChildOnly)
2166 return pbuf->getBibfilesCache();
2168 if (!d->bibfile_cache_valid_)
2169 this->updateBibfilesCache(scope);
2171 return d->bibfiles_cache_;
2175 BiblioInfo const & Buffer::masterBibInfo() const
2177 Buffer const * const tmp = masterBuffer();
2179 return tmp->masterBibInfo();
2184 void Buffer::checkIfBibInfoCacheIsValid() const
2186 // use the master's cache
2187 Buffer const * const tmp = masterBuffer();
2189 tmp->checkIfBibInfoCacheIsValid();
2193 // compare the cached timestamps with the actual ones.
2194 FileNameList const & bibfiles_cache = getBibfilesCache();
2195 FileNameList::const_iterator ei = bibfiles_cache.begin();
2196 FileNameList::const_iterator en = bibfiles_cache.end();
2197 for (; ei != en; ++ ei) {
2198 time_t lastw = ei->lastModified();
2199 time_t prevw = d->bibfile_status_[*ei];
2200 if (lastw != prevw) {
2201 d->bibinfo_cache_valid_ = false;
2202 d->cite_labels_valid_ = false;
2203 d->bibfile_status_[*ei] = lastw;
2209 void Buffer::reloadBibInfoCache() const
2211 // use the master's cache
2212 Buffer const * const tmp = masterBuffer();
2214 tmp->reloadBibInfoCache();
2218 checkIfBibInfoCacheIsValid();
2219 if (d->bibinfo_cache_valid_)
2222 d->bibinfo_.clear();
2224 d->bibinfo_cache_valid_ = true;
2228 void Buffer::collectBibKeys() const
2230 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2231 it->collectBibKeys(it);
2235 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2237 Buffer const * tmp = masterBuffer();
2238 BiblioInfo & masterbi = (tmp == this) ?
2239 d->bibinfo_ : tmp->d->bibinfo_;
2240 masterbi.mergeBiblioInfo(bi);
2244 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2246 Buffer const * tmp = masterBuffer();
2247 BiblioInfo & masterbi = (tmp == this) ?
2248 d->bibinfo_ : tmp->d->bibinfo_;
2253 void Buffer::makeCitationLabels() const
2255 Buffer const * const master = masterBuffer();
2256 return d->bibinfo_.makeCitationLabels(*master);
2260 bool Buffer::citeLabelsValid() const
2262 return masterBuffer()->d->cite_labels_valid_;
2266 void Buffer::removeBiblioTempFiles() const
2268 // We remove files that contain LaTeX commands specific to the
2269 // particular bibliographic style being used, in order to avoid
2270 // LaTeX errors when we switch style.
2271 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2272 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2273 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2274 aux_file.removeFile();
2275 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2276 bbl_file.removeFile();
2277 // Also for the parent buffer
2278 Buffer const * const pbuf = parent();
2280 pbuf->removeBiblioTempFiles();
2284 bool Buffer::isDepClean(string const & name) const
2286 DepClean::const_iterator const it = d->dep_clean.find(name);
2287 if (it == d->dep_clean.end())
2293 void Buffer::markDepClean(string const & name)
2295 d->dep_clean[name] = true;
2299 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2302 // FIXME? if there is an Buffer LFUN that can be dispatched even
2303 // if internal, put a switch '(cmd.action)' here.
2309 switch (cmd.action()) {
2311 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2312 flag.setOnOff(isReadonly());
2315 // FIXME: There is need for a command-line import.
2316 //case LFUN_BUFFER_IMPORT:
2318 case LFUN_BUFFER_AUTO_SAVE:
2321 case LFUN_BUFFER_EXPORT_CUSTOM:
2322 // FIXME: Nothing to check here?
2325 case LFUN_BUFFER_EXPORT: {
2326 docstring const arg = cmd.argument();
2327 if (arg == "custom") {
2331 string format = to_utf8(arg);
2332 size_t pos = format.find(' ');
2333 if (pos != string::npos)
2334 format = format.substr(0, pos);
2335 enable = params().isExportable(format);
2337 flag.message(bformat(
2338 _("Don't know how to export to format: %1$s"), arg));
2342 case LFUN_BUFFER_CHKTEX:
2343 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2346 case LFUN_BUILD_PROGRAM:
2347 enable = params().isExportable("program");
2350 case LFUN_BRANCH_ACTIVATE:
2351 case LFUN_BRANCH_DEACTIVATE:
2352 case LFUN_BRANCH_MASTER_ACTIVATE:
2353 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2354 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2355 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2356 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2357 : params().branchlist();
2358 docstring const branchName = cmd.argument();
2359 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2363 case LFUN_BRANCH_ADD:
2364 case LFUN_BRANCHES_RENAME:
2365 case LFUN_BUFFER_PRINT:
2366 // if no Buffer is present, then of course we won't be called!
2369 case LFUN_BUFFER_LANGUAGE:
2370 enable = !isReadonly();
2376 flag.setEnabled(enable);
2381 void Buffer::dispatch(string const & command, DispatchResult & result)
2383 return dispatch(lyxaction.lookupFunc(command), result);
2387 // NOTE We can end up here even if we have no GUI, because we are called
2388 // by LyX::exec to handled command-line requests. So we may need to check
2389 // whether we have a GUI or not. The boolean use_gui holds this information.
2390 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2393 // FIXME? if there is an Buffer LFUN that can be dispatched even
2394 // if internal, put a switch '(cmd.action())' here.
2395 dr.dispatched(false);
2398 string const argument = to_utf8(func.argument());
2399 // We'll set this back to false if need be.
2400 bool dispatched = true;
2401 undo().beginUndoGroup();
2403 switch (func.action()) {
2404 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2405 if (lyxvc().inUse()) {
2406 string log = lyxvc().toggleReadOnly();
2411 setReadonly(!isReadonly());
2414 case LFUN_BUFFER_EXPORT: {
2415 ExportStatus const status = doExport(argument, false);
2416 dr.setError(status != ExportSuccess);
2417 if (status != ExportSuccess)
2418 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2423 case LFUN_BUILD_PROGRAM: {
2424 ExportStatus const status = doExport("program", true);
2425 dr.setError(status != ExportSuccess);
2426 if (status != ExportSuccess)
2427 dr.setMessage(_("Error generating literate programming code."));
2431 case LFUN_BUFFER_CHKTEX:
2435 case LFUN_BUFFER_EXPORT_CUSTOM: {
2437 string command = split(argument, format_name, ' ');
2438 Format const * format = formats.getFormat(format_name);
2440 lyxerr << "Format \"" << format_name
2441 << "\" not recognized!"
2446 // The name of the file created by the conversion process
2449 // Output to filename
2450 if (format->name() == "lyx") {
2451 string const latexname = latexName(false);
2452 filename = changeExtension(latexname,
2453 format->extension());
2454 filename = addName(temppath(), filename);
2456 if (!writeFile(FileName(filename)))
2460 doExport(format_name, true, filename);
2463 // Substitute $$FName for filename
2464 if (!contains(command, "$$FName"))
2465 command = "( " + command + " ) < $$FName";
2466 command = subst(command, "$$FName", filename);
2468 // Execute the command in the background
2470 call.startscript(Systemcall::DontWait, command, filePath());
2474 // FIXME: There is need for a command-line import.
2476 case LFUN_BUFFER_IMPORT:
2481 case LFUN_BUFFER_AUTO_SAVE:
2483 resetAutosaveTimers();
2486 case LFUN_BRANCH_ACTIVATE:
2487 case LFUN_BRANCH_DEACTIVATE:
2488 case LFUN_BRANCH_MASTER_ACTIVATE:
2489 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2490 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2491 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2492 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2495 docstring const branch_name = func.argument();
2496 // the case without a branch name is handled elsewhere
2497 if (branch_name.empty()) {
2501 Branch * branch = buf->params().branchlist().find(branch_name);
2503 LYXERR0("Branch " << branch_name << " does not exist.");
2505 docstring const msg =
2506 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2510 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2511 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2512 if (branch->isSelected() != activate) {
2513 buf->undo().recordUndoFullDocument(CursorData());
2514 branch->setSelected(activate);
2516 dr.screenUpdate(Update::Force);
2517 dr.forceBufferUpdate();
2522 case LFUN_BRANCH_ADD: {
2523 docstring branch_name = func.argument();
2524 if (branch_name.empty()) {
2528 BranchList & branch_list = params().branchlist();
2529 vector<docstring> const branches =
2530 getVectorFromString(branch_name, branch_list.separator());
2532 for (vector<docstring>::const_iterator it = branches.begin();
2533 it != branches.end(); ++it) {
2535 Branch * branch = branch_list.find(branch_name);
2537 LYXERR0("Branch " << branch_name << " already exists.");
2541 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2543 undo().recordUndoFullDocument(CursorData());
2544 branch_list.add(branch_name);
2545 branch = branch_list.find(branch_name);
2546 string const x11hexname = X11hexname(branch->color());
2547 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2548 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2550 dr.screenUpdate(Update::Force);
2558 case LFUN_BRANCHES_RENAME: {
2559 if (func.argument().empty())
2562 docstring const oldname = from_utf8(func.getArg(0));
2563 docstring const newname = from_utf8(func.getArg(1));
2564 InsetIterator it = inset_iterator_begin(inset());
2565 InsetIterator const end = inset_iterator_end(inset());
2566 bool success = false;
2567 for (; it != end; ++it) {
2568 if (it->lyxCode() == BRANCH_CODE) {
2569 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2570 if (ins.branch() == oldname) {
2571 undo().recordUndo(CursorData(it));
2572 ins.rename(newname);
2577 if (it->lyxCode() == INCLUDE_CODE) {
2578 // get buffer of external file
2579 InsetInclude const & ins =
2580 static_cast<InsetInclude const &>(*it);
2581 Buffer * child = ins.getChildBuffer();
2584 child->dispatch(func, dr);
2589 dr.screenUpdate(Update::Force);
2590 dr.forceBufferUpdate();
2595 case LFUN_BUFFER_PRINT: {
2596 // we'll assume there's a problem until we succeed
2598 string target = func.getArg(0);
2599 string target_name = func.getArg(1);
2600 string command = func.getArg(2);
2603 || target_name.empty()
2604 || command.empty()) {
2605 LYXERR0("Unable to parse " << func.argument());
2606 docstring const msg =
2607 bformat(_("Unable to parse \"%1$s\""), func.argument());
2611 if (target != "printer" && target != "file") {
2612 LYXERR0("Unrecognized target \"" << target << '"');
2613 docstring const msg =
2614 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2619 if (doExport("dvi", true) != ExportSuccess) {
2620 showPrintError(absFileName());
2621 dr.setMessage(_("Error exporting to DVI."));
2625 // Push directory path.
2626 string const path = temppath();
2627 // Prevent the compiler from optimizing away p
2631 // there are three cases here:
2632 // 1. we print to a file
2633 // 2. we print directly to a printer
2634 // 3. we print using a spool command (print to file first)
2637 string const dviname = changeExtension(latexName(true), "dvi");
2639 if (target == "printer") {
2640 if (!lyxrc.print_spool_command.empty()) {
2641 // case 3: print using a spool
2642 string const psname = changeExtension(dviname,".ps");
2643 command += ' ' + lyxrc.print_to_file
2646 + quoteName(dviname);
2648 string command2 = lyxrc.print_spool_command + ' ';
2649 if (target_name != "default") {
2650 command2 += lyxrc.print_spool_printerprefix
2654 command2 += quoteName(psname);
2656 // If successful, then spool command
2657 res = one.startscript(Systemcall::Wait, command,
2661 // If there's no GUI, we have to wait on this command. Otherwise,
2662 // LyX deletes the temporary directory, and with it the spooled
2663 // file, before it can be printed!!
2664 Systemcall::Starttype stype = use_gui ?
2665 Systemcall::DontWait : Systemcall::Wait;
2666 res = one.startscript(stype, command2,
2670 // case 2: print directly to a printer
2671 if (target_name != "default")
2672 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2674 Systemcall::Starttype stype = use_gui ?
2675 Systemcall::DontWait : Systemcall::Wait;
2676 res = one.startscript(stype, command +
2677 quoteName(dviname), filePath());
2681 // case 1: print to a file
2682 FileName const filename(makeAbsPath(target_name, filePath()));
2683 FileName const dvifile(makeAbsPath(dviname, path));
2684 if (filename.exists()) {
2685 docstring text = bformat(
2686 _("The file %1$s already exists.\n\n"
2687 "Do you want to overwrite that file?"),
2688 makeDisplayPath(filename.absFileName()));
2689 if (Alert::prompt(_("Overwrite file?"),
2690 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2693 command += ' ' + lyxrc.print_to_file
2694 + quoteName(filename.toFilesystemEncoding())
2696 + quoteName(dvifile.toFilesystemEncoding());
2698 Systemcall::Starttype stype = use_gui ?
2699 Systemcall::DontWait : Systemcall::Wait;
2700 res = one.startscript(stype, command, filePath());
2706 dr.setMessage(_("Error running external commands."));
2707 showPrintError(absFileName());
2716 dr.dispatched(dispatched);
2717 undo().endUndoGroup();
2721 void Buffer::changeLanguage(Language const * from, Language const * to)
2723 LASSERT(from, return);
2724 LASSERT(to, return);
2726 for_each(par_iterator_begin(),
2728 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2732 bool Buffer::isMultiLingual() const
2734 ParConstIterator end = par_iterator_end();
2735 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2736 if (it->isMultiLingual(params()))
2743 std::set<Language const *> Buffer::getLanguages() const
2745 std::set<Language const *> languages;
2746 getLanguages(languages);
2751 void Buffer::getLanguages(std::set<Language const *> & languages) const
2753 ParConstIterator end = par_iterator_end();
2754 // add the buffer language, even if it's not actively used
2755 languages.insert(language());
2756 // iterate over the paragraphs
2757 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2758 it->getLanguages(languages);
2760 ListOfBuffers clist = getDescendents();
2761 ListOfBuffers::const_iterator cit = clist.begin();
2762 ListOfBuffers::const_iterator const cen = clist.end();
2763 for (; cit != cen; ++cit)
2764 (*cit)->getLanguages(languages);
2768 DocIterator Buffer::getParFromID(int const id) const
2770 Buffer * buf = const_cast<Buffer *>(this);
2772 // John says this is called with id == -1 from undo
2773 lyxerr << "getParFromID(), id: " << id << endl;
2774 return doc_iterator_end(buf);
2777 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2778 if (it.paragraph().id() == id)
2781 return doc_iterator_end(buf);
2785 bool Buffer::hasParWithID(int const id) const
2787 return !getParFromID(id).atEnd();
2791 ParIterator Buffer::par_iterator_begin()
2793 return ParIterator(doc_iterator_begin(this));
2797 ParIterator Buffer::par_iterator_end()
2799 return ParIterator(doc_iterator_end(this));
2803 ParConstIterator Buffer::par_iterator_begin() const
2805 return ParConstIterator(doc_iterator_begin(this));
2809 ParConstIterator Buffer::par_iterator_end() const
2811 return ParConstIterator(doc_iterator_end(this));
2815 Language const * Buffer::language() const
2817 return params().language;
2821 docstring const Buffer::B_(string const & l10n) const
2823 return params().B_(l10n);
2827 bool Buffer::isClean() const
2829 return d->lyx_clean;
2833 bool Buffer::isExternallyModified(CheckMethod method) const
2835 LASSERT(d->filename.exists(), return false);
2836 // if method == timestamp, check timestamp before checksum
2837 return (method == checksum_method
2838 || d->timestamp_ != d->filename.lastModified())
2839 && d->checksum_ != d->filename.checksum();
2843 void Buffer::saveCheckSum() const
2845 FileName const & file = d->filename;
2848 if (file.exists()) {
2849 d->timestamp_ = file.lastModified();
2850 d->checksum_ = file.checksum();
2852 // in the case of save to a new file.
2859 void Buffer::markClean() const
2861 if (!d->lyx_clean) {
2862 d->lyx_clean = true;
2865 // if the .lyx file has been saved, we don't need an
2867 d->bak_clean = true;
2868 d->undo_.markDirty();
2872 void Buffer::setUnnamed(bool flag)
2878 bool Buffer::isUnnamed() const
2885 /// Don't check unnamed, here: isInternal() is used in
2886 /// newBuffer(), where the unnamed flag has not been set by anyone
2887 /// yet. Also, for an internal buffer, there should be no need for
2888 /// retrieving fileName() nor for checking if it is unnamed or not.
2889 bool Buffer::isInternal() const
2891 return d->internal_buffer;
2895 void Buffer::setInternal(bool flag)
2897 d->internal_buffer = flag;
2901 void Buffer::markDirty()
2904 d->lyx_clean = false;
2907 d->bak_clean = false;
2909 DepClean::iterator it = d->dep_clean.begin();
2910 DepClean::const_iterator const end = d->dep_clean.end();
2912 for (; it != end; ++it)
2917 FileName Buffer::fileName() const
2923 string Buffer::absFileName() const
2925 return d->filename.absFileName();
2929 string Buffer::filePath() const
2931 string const abs = d->filename.onlyPath().absFileName();
2934 int last = abs.length() - 1;
2936 return abs[last] == '/' ? abs : abs + '/';
2940 bool Buffer::isReadonly() const
2942 return d->read_only;
2946 void Buffer::setParent(Buffer const * buffer)
2948 // Avoids recursive include.
2949 d->setParent(buffer == this ? 0 : buffer);
2954 Buffer const * Buffer::parent() const
2960 ListOfBuffers Buffer::allRelatives() const
2962 ListOfBuffers lb = masterBuffer()->getDescendents();
2963 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2968 Buffer const * Buffer::masterBuffer() const
2970 // FIXME Should be make sure we are not in some kind
2971 // of recursive include? A -> B -> A will crash this.
2972 Buffer const * const pbuf = d->parent();
2976 return pbuf->masterBuffer();
2980 bool Buffer::isChild(Buffer * child) const
2982 return d->children_positions.find(child) != d->children_positions.end();
2986 DocIterator Buffer::firstChildPosition(Buffer const * child)
2988 Impl::BufferPositionMap::iterator it;
2989 it = d->children_positions.find(child);
2990 if (it == d->children_positions.end())
2991 return DocIterator(this);
2996 bool Buffer::hasChildren() const
2998 return !d->children_positions.empty();
3002 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3004 // loop over children
3005 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3006 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3007 for (; it != end; ++it) {
3008 Buffer * child = const_cast<Buffer *>(it->first);
3010 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3011 if (bit != clist.end())
3013 clist.push_back(child);
3015 // there might be grandchildren
3016 child->collectChildren(clist, true);
3021 ListOfBuffers Buffer::getChildren() const
3024 collectChildren(v, false);
3025 // Make sure we have not included ourselves.
3026 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3027 if (bit != v.end()) {
3028 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3035 ListOfBuffers Buffer::getDescendents() const
3038 collectChildren(v, true);
3039 // Make sure we have not included ourselves.
3040 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3041 if (bit != v.end()) {
3042 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3049 template<typename M>
3050 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3055 typename M::const_iterator it = m.lower_bound(x);
3056 if (it == m.begin())
3064 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3065 DocIterator const & pos) const
3067 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3069 // if paragraphs have no macro context set, pos will be empty
3073 // we haven't found anything yet
3074 DocIterator bestPos = owner_->par_iterator_begin();
3075 MacroData const * bestData = 0;
3077 // find macro definitions for name
3078 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3079 if (nameIt != macros.end()) {
3080 // find last definition in front of pos or at pos itself
3081 PositionScopeMacroMap::const_iterator it
3082 = greatest_below(nameIt->second, pos);
3083 if (it != nameIt->second.end()) {
3085 // scope ends behind pos?
3086 if (pos < it->second.first) {
3087 // Looks good, remember this. If there
3088 // is no external macro behind this,
3089 // we found the right one already.
3090 bestPos = it->first;
3091 bestData = &it->second.second;
3095 // try previous macro if there is one
3096 if (it == nameIt->second.begin())
3103 // find macros in included files
3104 PositionScopeBufferMap::const_iterator it
3105 = greatest_below(position_to_children, pos);
3106 if (it == position_to_children.end())
3107 // no children before
3111 // do we know something better (i.e. later) already?
3112 if (it->first < bestPos )
3115 // scope ends behind pos?
3116 if (pos < it->second.first
3117 && (cloned_buffer_ ||
3118 theBufferList().isLoaded(it->second.second))) {
3119 // look for macro in external file
3121 MacroData const * data
3122 = it->second.second->getMacro(name, false);
3125 bestPos = it->first;
3131 // try previous file if there is one
3132 if (it == position_to_children.begin())
3137 // return the best macro we have found
3142 MacroData const * Buffer::getMacro(docstring const & name,
3143 DocIterator const & pos, bool global) const
3148 // query buffer macros
3149 MacroData const * data = d->getBufferMacro(name, pos);
3153 // If there is a master buffer, query that
3154 Buffer const * const pbuf = d->parent();
3156 d->macro_lock = true;
3157 MacroData const * macro = pbuf->getMacro(
3158 name, *this, false);
3159 d->macro_lock = false;
3165 data = MacroTable::globalMacros().get(name);
3174 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3176 // set scope end behind the last paragraph
3177 DocIterator scope = par_iterator_begin();
3178 scope.pit() = scope.lastpit() + 1;
3180 return getMacro(name, scope, global);
3184 MacroData const * Buffer::getMacro(docstring const & name,
3185 Buffer const & child, bool global) const
3187 // look where the child buffer is included first
3188 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3189 if (it == d->children_positions.end())
3192 // check for macros at the inclusion position
3193 return getMacro(name, it->second, global);
3197 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3199 pit_type const lastpit = it.lastpit();
3201 // look for macros in each paragraph
3202 while (it.pit() <= lastpit) {
3203 Paragraph & par = it.paragraph();
3205 // iterate over the insets of the current paragraph
3206 InsetList const & insets = par.insetList();
3207 InsetList::const_iterator iit = insets.begin();
3208 InsetList::const_iterator end = insets.end();
3209 for (; iit != end; ++iit) {
3210 it.pos() = iit->pos;
3212 // is it a nested text inset?
3213 if (iit->inset->asInsetText()) {
3214 // Inset needs its own scope?
3215 InsetText const * itext = iit->inset->asInsetText();
3216 bool newScope = itext->isMacroScope();
3218 // scope which ends just behind the inset
3219 DocIterator insetScope = it;
3222 // collect macros in inset
3223 it.push_back(CursorSlice(*iit->inset));
3224 updateMacros(it, newScope ? insetScope : scope);
3229 if (iit->inset->asInsetTabular()) {
3230 CursorSlice slice(*iit->inset);
3231 size_t const numcells = slice.nargs();
3232 for (; slice.idx() < numcells; slice.forwardIdx()) {
3233 it.push_back(slice);
3234 updateMacros(it, scope);
3240 // is it an external file?
3241 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3242 // get buffer of external file
3243 InsetInclude const & inset =
3244 static_cast<InsetInclude const &>(*iit->inset);
3246 Buffer * child = inset.getChildBuffer();
3251 // register its position, but only when it is
3252 // included first in the buffer
3253 if (children_positions.find(child) ==
3254 children_positions.end())
3255 children_positions[child] = it;
3257 // register child with its scope
3258 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3262 InsetMath * im = iit->inset->asInsetMath();
3263 if (doing_export && im) {
3264 InsetMathHull * hull = im->asHullInset();
3266 hull->recordLocation(it);
3269 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3273 MathMacroTemplate & macroTemplate =
3274 *iit->inset->asInsetMath()->asMacroTemplate();
3275 MacroContext mc(owner_, it);
3276 macroTemplate.updateToContext(mc);
3279 bool valid = macroTemplate.validMacro();
3280 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3281 // then the BufferView's cursor will be invalid in
3282 // some cases which leads to crashes.
3287 // FIXME (Abdel), I don't understandt why we pass 'it' here
3288 // instead of 'macroTemplate' defined above... is this correct?
3289 macros[macroTemplate.name()][it] =
3290 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3300 void Buffer::updateMacros() const
3305 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3307 // start with empty table
3309 d->children_positions.clear();
3310 d->position_to_children.clear();
3312 // Iterate over buffer, starting with first paragraph
3313 // The scope must be bigger than any lookup DocIterator
3314 // later. For the global lookup, lastpit+1 is used, hence
3315 // we use lastpit+2 here.
3316 DocIterator it = par_iterator_begin();
3317 DocIterator outerScope = it;
3318 outerScope.pit() = outerScope.lastpit() + 2;
3319 d->updateMacros(it, outerScope);
3323 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3325 InsetIterator it = inset_iterator_begin(inset());
3326 InsetIterator const end = inset_iterator_end(inset());
3327 for (; it != end; ++it) {
3328 if (it->lyxCode() == BRANCH_CODE) {
3329 InsetBranch & br = static_cast<InsetBranch &>(*it);
3330 docstring const name = br.branch();
3331 if (!from_master && !params().branchlist().find(name))
3332 result.push_back(name);
3333 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3334 result.push_back(name);
3337 if (it->lyxCode() == INCLUDE_CODE) {
3338 // get buffer of external file
3339 InsetInclude const & ins =
3340 static_cast<InsetInclude const &>(*it);
3341 Buffer * child = ins.getChildBuffer();
3344 child->getUsedBranches(result, true);
3347 // remove duplicates
3352 void Buffer::updateMacroInstances(UpdateType utype) const
3354 LYXERR(Debug::MACROS, "updateMacroInstances for "
3355 << d->filename.onlyFileName());
3356 DocIterator it = doc_iterator_begin(this);
3358 DocIterator const end = doc_iterator_end(this);
3359 for (; it != end; it.forwardInset()) {
3360 // look for MathData cells in InsetMathNest insets
3361 InsetMath * minset = it.nextInset()->asInsetMath();
3365 // update macro in all cells of the InsetMathNest
3366 DocIterator::idx_type n = minset->nargs();
3367 MacroContext mc = MacroContext(this, it);
3368 for (DocIterator::idx_type i = 0; i < n; ++i) {
3369 MathData & data = minset->cell(i);
3370 data.updateMacros(0, mc, utype);
3376 void Buffer::listMacroNames(MacroNameSet & macros) const
3381 d->macro_lock = true;
3383 // loop over macro names
3384 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3385 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3386 for (; nameIt != nameEnd; ++nameIt)
3387 macros.insert(nameIt->first);
3389 // loop over children
3390 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3391 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3392 for (; it != end; ++it)
3393 it->first->listMacroNames(macros);
3396 Buffer const * const pbuf = d->parent();
3398 pbuf->listMacroNames(macros);
3400 d->macro_lock = false;
3404 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3406 Buffer const * const pbuf = d->parent();
3411 pbuf->listMacroNames(names);
3414 MacroNameSet::iterator it = names.begin();
3415 MacroNameSet::iterator end = names.end();
3416 for (; it != end; ++it) {
3418 MacroData const * data =
3419 pbuf->getMacro(*it, *this, false);
3421 macros.insert(data);
3423 // we cannot access the original MathMacroTemplate anymore
3424 // here to calls validate method. So we do its work here manually.
3425 // FIXME: somehow make the template accessible here.
3426 if (data->optionals() > 0)
3427 features.require("xargs");
3433 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3436 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3438 RefCache::iterator it = d->ref_cache_.find(label);
3439 if (it != d->ref_cache_.end())
3440 return it->second.second;
3442 static InsetLabel const * dummy_il = 0;
3443 static References const dummy_refs;
3444 it = d->ref_cache_.insert(
3445 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3446 return it->second.second;
3450 Buffer::References const & Buffer::references(docstring const & label) const
3452 return const_cast<Buffer *>(this)->getReferenceCache(label);
3456 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3458 References & refs = getReferenceCache(label);
3459 refs.push_back(make_pair(inset, it));
3463 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3465 masterBuffer()->d->ref_cache_[label].first = il;
3469 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3471 return masterBuffer()->d->ref_cache_[label].first;
3475 void Buffer::clearReferenceCache() const
3478 d->ref_cache_.clear();
3482 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3484 //FIXME: This does not work for child documents yet.
3485 reloadBibInfoCache();
3487 // Check if the label 'from' appears more than once
3488 BiblioInfo const & keys = masterBibInfo();
3489 BiblioInfo::const_iterator bit = keys.begin();
3490 BiblioInfo::const_iterator bend = keys.end();
3491 vector<docstring> labels;
3493 for (; bit != bend; ++bit)
3495 labels.push_back(bit->first);
3497 if (count(labels.begin(), labels.end(), from) > 1)
3500 string const paramName = "key";
3501 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3502 if (it->lyxCode() != CITE_CODE)
3504 InsetCommand * inset = it->asInsetCommand();
3505 docstring const oldValue = inset->getParam(paramName);
3506 if (oldValue == from)
3507 inset->setParam(paramName, to);
3512 void Buffer::getSourceCode(odocstream & os, string const & format,
3513 pit_type par_begin, pit_type par_end,
3514 OutputWhat output, bool master) const
3516 OutputParams runparams(¶ms().encoding());
3517 runparams.nice = true;
3518 runparams.flavor = params().getOutputFlavor(format);
3519 runparams.linelen = lyxrc.plaintext_linelen;
3520 // No side effect of file copying and image conversion
3521 runparams.dryrun = true;
3523 if (output == CurrentParagraph) {
3524 runparams.par_begin = par_begin;
3525 runparams.par_end = par_end;
3526 if (par_begin + 1 == par_end) {
3528 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3532 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3533 convert<docstring>(par_begin),
3534 convert<docstring>(par_end - 1))
3537 // output paragraphs
3538 if (runparams.flavor == OutputParams::LYX) {
3539 Paragraph const & par = text().paragraphs()[par_begin];
3541 depth_type dt = par.getDepth();
3542 par.write(ods, params(), dt);
3543 os << from_utf8(ods.str());
3544 } else if (runparams.flavor == OutputParams::HTML) {
3546 setMathFlavor(runparams);
3547 xhtmlParagraphs(text(), *this, xs, runparams);
3548 } else if (runparams.flavor == OutputParams::TEXT) {
3550 // FIXME Handles only one paragraph, unlike the others.
3551 // Probably should have some routine with a signature like them.
3552 writePlaintextParagraph(*this,
3553 text().paragraphs()[par_begin], os, runparams, dummy);
3554 } else if (params().isDocBook()) {
3555 docbookParagraphs(text(), *this, os, runparams);
3557 // If we are previewing a paragraph, even if this is the
3558 // child of some other buffer, let's cut the link here,
3559 // so that no concurring settings from the master
3560 // (e.g. branch state) interfere (see #8101).
3562 d->ignore_parent = true;
3563 // We need to validate the Buffer params' features here
3564 // in order to know if we should output polyglossia
3565 // macros (instead of babel macros)
3566 LaTeXFeatures features(*this, params(), runparams);
3567 params().validate(features);
3568 runparams.use_polyglossia = features.usePolyglossia();
3573 // latex or literate
3574 otexstream ots(os, texrow);
3577 latexParagraphs(*this, text(), ots, runparams);
3579 // Restore the parenthood
3581 d->ignore_parent = false;
3585 if (output == FullSource)
3586 os << _("Preview source code");
3587 else if (output == OnlyPreamble)
3588 os << _("Preview preamble");
3589 else if (output == OnlyBody)
3590 os << _("Preview body");
3592 if (runparams.flavor == OutputParams::LYX) {
3594 if (output == FullSource)
3596 else if (output == OnlyPreamble)
3597 params().writeFile(ods);
3598 else if (output == OnlyBody)
3600 os << from_utf8(ods.str());
3601 } else if (runparams.flavor == OutputParams::HTML) {
3602 writeLyXHTMLSource(os, runparams, output);
3603 } else if (runparams.flavor == OutputParams::TEXT) {
3604 if (output == OnlyPreamble) {
3605 os << "% "<< _("Plain text does not have a preamble.");
3607 writePlaintextFile(*this, os, runparams);
3608 } else if (params().isDocBook()) {
3609 writeDocBookSource(os, absFileName(), runparams, output);
3611 // latex or literate
3613 d->texrow.newline();
3614 d->texrow.newline();
3615 otexstream ots(os, d->texrow);
3617 runparams.is_child = true;
3618 writeLaTeXSource(ots, string(), runparams, output);
3624 ErrorList & Buffer::errorList(string const & type) const
3626 return d->errorLists[type];
3630 void Buffer::updateTocItem(std::string const & type,
3631 DocIterator const & dit) const
3634 d->gui_->updateTocItem(type, dit);
3638 void Buffer::structureChanged() const
3641 d->gui_->structureChanged();
3645 void Buffer::errors(string const & err, bool from_master) const
3648 d->gui_->errors(err, from_master);
3652 void Buffer::message(docstring const & msg) const
3655 d->gui_->message(msg);
3659 void Buffer::setBusy(bool on) const
3662 d->gui_->setBusy(on);
3666 void Buffer::updateTitles() const
3669 d->wa_->updateTitles();
3673 void Buffer::resetAutosaveTimers() const
3676 d->gui_->resetAutosaveTimers();
3680 bool Buffer::hasGuiDelegate() const
3686 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3695 class AutoSaveBuffer : public ForkedProcess {
3698 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3699 : buffer_(buffer), fname_(fname) {}
3701 virtual shared_ptr<ForkedProcess> clone() const
3703 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3708 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3709 from_utf8(fname_.absFileName())));
3710 return run(DontWait);
3714 virtual int generateChild();
3716 Buffer const & buffer_;
3721 int AutoSaveBuffer::generateChild()
3723 #if defined(__APPLE__)
3724 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3725 * We should use something else like threads.
3727 * Since I do not know how to determine at run time what is the OS X
3728 * version, I just disable forking altogether for now (JMarc)
3730 pid_t const pid = -1;
3732 // tmp_ret will be located (usually) in /tmp
3733 // will that be a problem?
3734 // Note that this calls ForkedCalls::fork(), so it's
3735 // ok cross-platform.
3736 pid_t const pid = fork();
3737 // If you want to debug the autosave
3738 // you should set pid to -1, and comment out the fork.
3739 if (pid != 0 && pid != -1)
3743 // pid = -1 signifies that lyx was unable
3744 // to fork. But we will do the save
3746 bool failed = false;
3747 TempFile tempfile("lyxautoXXXXXX.lyx");
3748 tempfile.setAutoRemove(false);
3749 FileName const tmp_ret = tempfile.name();
3750 if (!tmp_ret.empty()) {
3751 if (!buffer_.writeFile(tmp_ret))
3753 else if (!tmp_ret.moveTo(fname_))
3759 // failed to write/rename tmp_ret so try writing direct
3760 if (!buffer_.writeFile(fname_)) {
3761 // It is dangerous to do this in the child,
3762 // but safe in the parent, so...
3763 if (pid == -1) // emit message signal.
3764 buffer_.message(_("Autosave failed!"));
3768 if (pid == 0) // we are the child so...
3777 FileName Buffer::getEmergencyFileName() const
3779 return FileName(d->filename.absFileName() + ".emergency");
3783 FileName Buffer::getAutosaveFileName() const
3785 // if the document is unnamed try to save in the backup dir, else
3786 // in the default document path, and as a last try in the filePath,
3787 // which will most often be the temporary directory
3790 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3791 : lyxrc.backupdir_path;
3792 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3795 string const fname = "#" + d->filename.onlyFileName() + "#";
3797 return makeAbsPath(fname, fpath);
3801 void Buffer::removeAutosaveFile() const
3803 FileName const f = getAutosaveFileName();
3809 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3811 FileName const newauto = getAutosaveFileName();
3813 if (newauto != oldauto && oldauto.exists())
3814 if (!oldauto.moveTo(newauto))
3815 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3819 bool Buffer::autoSave() const
3821 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3822 if (buf->d->bak_clean || isReadonly())
3825 message(_("Autosaving current document..."));
3826 buf->d->bak_clean = true;
3828 FileName const fname = getAutosaveFileName();
3829 LASSERT(d->cloned_buffer_, return false);
3831 // If this buffer is cloned, we assume that
3832 // we are running in a separate thread already.
3833 TempFile tempfile("lyxautoXXXXXX.lyx");
3834 tempfile.setAutoRemove(false);
3835 FileName const tmp_ret = tempfile.name();
3836 if (!tmp_ret.empty()) {
3838 // assume successful write of tmp_ret
3839 if (tmp_ret.moveTo(fname))
3842 // failed to write/rename tmp_ret so try writing direct
3843 return writeFile(fname);
3847 void Buffer::setExportStatus(bool e) const
3849 d->doing_export = e;
3850 ListOfBuffers clist = getDescendents();
3851 ListOfBuffers::const_iterator cit = clist.begin();
3852 ListOfBuffers::const_iterator const cen = clist.end();
3853 for (; cit != cen; ++cit)
3854 (*cit)->d->doing_export = e;
3858 bool Buffer::isExporting() const
3860 return d->doing_export;
3864 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3868 return doExport(target, put_in_tempdir, result_file);
3871 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3872 string & result_file) const
3874 bool const update_unincluded =
3875 params().maintain_unincluded_children
3876 && !params().getIncludedChildren().empty();
3878 // (1) export with all included children (omit \includeonly)
3879 if (update_unincluded) {
3880 ExportStatus const status =
3881 doExport(target, put_in_tempdir, true, result_file);
3882 if (status != ExportSuccess)
3885 // (2) export with included children only
3886 return doExport(target, put_in_tempdir, false, result_file);
3890 void Buffer::setMathFlavor(OutputParams & op) const
3892 switch (params().html_math_output) {
3893 case BufferParams::MathML:
3894 op.math_flavor = OutputParams::MathAsMathML;
3896 case BufferParams::HTML:
3897 op.math_flavor = OutputParams::MathAsHTML;
3899 case BufferParams::Images:
3900 op.math_flavor = OutputParams::MathAsImages;
3902 case BufferParams::LaTeX:
3903 op.math_flavor = OutputParams::MathAsLaTeX;
3909 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3910 bool includeall, string & result_file) const
3912 LYXERR(Debug::FILES, "target=" << target);
3913 OutputParams runparams(¶ms().encoding());
3914 string format = target;
3915 string dest_filename;
3916 size_t pos = target.find(' ');
3917 if (pos != string::npos) {
3918 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3919 format = target.substr(0, pos);
3920 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3921 FileName(dest_filename).onlyPath().createPath();
3922 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3924 MarkAsExporting exporting(this);
3925 string backend_format;
3926 runparams.flavor = OutputParams::LATEX;
3927 runparams.linelen = lyxrc.plaintext_linelen;
3928 runparams.includeall = includeall;
3929 vector<string> backs = params().backends();
3930 Converters converters = theConverters();
3931 bool need_nice_file = false;
3932 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3933 // Get shortest path to format
3934 converters.buildGraph();
3935 Graph::EdgePath path;
3936 for (vector<string>::const_iterator it = backs.begin();
3937 it != backs.end(); ++it) {
3938 Graph::EdgePath p = converters.getPath(*it, format);
3939 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3940 backend_format = *it;
3945 if (!put_in_tempdir) {
3946 // Only show this alert if this is an export to a non-temporary
3947 // file (not for previewing).
3948 Alert::error(_("Couldn't export file"), bformat(
3949 _("No information for exporting the format %1$s."),
3950 formats.prettyName(format)));
3952 return ExportNoPathToFormat;
3954 runparams.flavor = converters.getFlavor(path, this);
3955 Graph::EdgePath::const_iterator it = path.begin();
3956 Graph::EdgePath::const_iterator en = path.end();
3957 for (; it != en; ++it)
3958 if (theConverters().get(*it).nice) {
3959 need_nice_file = true;
3964 backend_format = format;
3965 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3966 // FIXME: Don't hardcode format names here, but use a flag
3967 if (backend_format == "pdflatex")
3968 runparams.flavor = OutputParams::PDFLATEX;
3969 else if (backend_format == "luatex")
3970 runparams.flavor = OutputParams::LUATEX;
3971 else if (backend_format == "dviluatex")
3972 runparams.flavor = OutputParams::DVILUATEX;
3973 else if (backend_format == "xetex")
3974 runparams.flavor = OutputParams::XETEX;
3977 string filename = latexName(false);
3978 filename = addName(temppath(), filename);
3979 filename = changeExtension(filename,
3980 formats.extension(backend_format));
3981 LYXERR(Debug::FILES, "filename=" << filename);
3983 // Plain text backend
3984 if (backend_format == "text") {
3985 runparams.flavor = OutputParams::TEXT;
3986 writePlaintextFile(*this, FileName(filename), runparams);
3989 else if (backend_format == "xhtml") {
3990 runparams.flavor = OutputParams::HTML;
3991 setMathFlavor(runparams);
3992 makeLyXHTMLFile(FileName(filename), runparams);
3993 } else if (backend_format == "lyx")
3994 writeFile(FileName(filename));
3996 else if (params().isDocBook()) {
3997 runparams.nice = !put_in_tempdir;
3998 makeDocBookFile(FileName(filename), runparams);
4001 else if (backend_format == format || need_nice_file) {
4002 runparams.nice = true;
4003 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4004 if (d->cloned_buffer_)
4005 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4008 } else if (!lyxrc.tex_allows_spaces
4009 && contains(filePath(), ' ')) {
4010 Alert::error(_("File name error"),
4011 _("The directory path to the document cannot contain spaces."));
4012 return ExportTexPathHasSpaces;
4014 runparams.nice = false;
4015 bool const success = makeLaTeXFile(
4016 FileName(filename), filePath(), runparams);
4017 if (d->cloned_buffer_)
4018 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4023 string const error_type = (format == "program")
4024 ? "Build" : params().bufferFormat();
4025 ErrorList & error_list = d->errorLists[error_type];
4026 string const ext = formats.extension(format);
4027 FileName const tmp_result_file(changeExtension(filename, ext));
4028 bool const success = converters.convert(this, FileName(filename),
4029 tmp_result_file, FileName(absFileName()), backend_format, format,
4032 // Emit the signal to show the error list or copy it back to the
4033 // cloned Buffer so that it can be emitted afterwards.
4034 if (format != backend_format) {
4035 if (runparams.silent)
4037 else if (d->cloned_buffer_)
4038 d->cloned_buffer_->d->errorLists[error_type] =
4039 d->errorLists[error_type];
4042 // also to the children, in case of master-buffer-view
4043 ListOfBuffers clist = getDescendents();
4044 ListOfBuffers::const_iterator cit = clist.begin();
4045 ListOfBuffers::const_iterator const cen = clist.end();
4046 for (; cit != cen; ++cit) {
4047 if (runparams.silent)
4048 (*cit)->d->errorLists[error_type].clear();
4049 else if (d->cloned_buffer_) {
4050 // Enable reverse search by copying back the
4051 // texrow object to the cloned buffer.
4052 // FIXME: this is not thread safe.
4053 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4054 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4055 (*cit)->d->errorLists[error_type];
4057 (*cit)->errors(error_type, true);
4061 if (d->cloned_buffer_) {
4062 // Enable reverse dvi or pdf to work by copying back the texrow
4063 // object to the cloned buffer.
4064 // FIXME: There is a possibility of concurrent access to texrow
4065 // here from the main GUI thread that should be securized.
4066 d->cloned_buffer_->d->texrow = d->texrow;
4067 string const error_type = params().bufferFormat();
4068 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4072 return ExportConverterError;
4074 if (put_in_tempdir) {
4075 result_file = tmp_result_file.absFileName();
4076 return ExportSuccess;
4079 if (dest_filename.empty())
4080 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4082 result_file = dest_filename;
4083 // We need to copy referenced files (e. g. included graphics
4084 // if format == "dvi") to the result dir.
4085 vector<ExportedFile> const files =
4086 runparams.exportdata->externalFiles(format);
4087 string const dest = runparams.export_folder.empty() ?
4088 onlyPath(result_file) : runparams.export_folder;
4089 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4090 : force_overwrite == ALL_FILES;
4091 CopyStatus status = use_force ? FORCE : SUCCESS;
4093 vector<ExportedFile>::const_iterator it = files.begin();
4094 vector<ExportedFile>::const_iterator const en = files.end();
4095 for (; it != en && status != CANCEL; ++it) {
4096 string const fmt = formats.getFormatFromFile(it->sourceName);
4097 string fixedName = it->exportName;
4098 if (!runparams.export_folder.empty()) {
4099 // Relative pathnames starting with ../ will be sanitized
4100 // if exporting to a different folder
4101 while (fixedName.substr(0, 3) == "../")
4102 fixedName = fixedName.substr(3, fixedName.length() - 3);
4104 FileName fixedFileName = makeAbsPath(fixedName, dest);
4105 fixedFileName.onlyPath().createPath();
4106 status = copyFile(fmt, it->sourceName,
4108 it->exportName, status == FORCE,
4109 runparams.export_folder.empty());
4112 if (status == CANCEL) {
4113 message(_("Document export cancelled."));
4114 return ExportCancel;
4117 if (tmp_result_file.exists()) {
4118 // Finally copy the main file
4119 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4120 : force_overwrite != NO_FILES;
4121 if (status == SUCCESS && use_force)
4123 status = copyFile(format, tmp_result_file,
4124 FileName(result_file), result_file,
4126 if (status == CANCEL) {
4127 message(_("Document export cancelled."));
4128 return ExportCancel;
4130 message(bformat(_("Document exported as %1$s "
4132 formats.prettyName(format),
4133 makeDisplayPath(result_file)));
4136 // This must be a dummy converter like fax (bug 1888)
4137 message(bformat(_("Document exported as %1$s"),
4138 formats.prettyName(format)));
4141 return ExportSuccess;
4145 Buffer::ExportStatus Buffer::preview(string const & format) const
4147 bool const update_unincluded =
4148 params().maintain_unincluded_children
4149 && !params().getIncludedChildren().empty();
4150 return preview(format, update_unincluded);
4153 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4155 MarkAsExporting exporting(this);
4157 // (1) export with all included children (omit \includeonly)
4159 ExportStatus const status = doExport(format, true, true, result_file);
4160 if (status != ExportSuccess)
4163 // (2) export with included children only
4164 ExportStatus const status = doExport(format, true, false, result_file);
4165 if (status != ExportSuccess)
4167 if (!formats.view(*this, FileName(result_file), format))
4168 return PreviewError;
4169 return PreviewSuccess;
4173 Buffer::ReadStatus Buffer::extractFromVC()
4175 bool const found = LyXVC::file_not_found_hook(d->filename);
4177 return ReadFileNotFound;
4178 if (!d->filename.isReadableFile())
4184 Buffer::ReadStatus Buffer::loadEmergency()
4186 FileName const emergencyFile = getEmergencyFileName();
4187 if (!emergencyFile.exists()
4188 || emergencyFile.lastModified() <= d->filename.lastModified())
4189 return ReadFileNotFound;
4191 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4192 docstring const text = bformat(_("An emergency save of the document "
4193 "%1$s exists.\n\nRecover emergency save?"), file);
4195 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4196 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4202 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4203 bool const success = (ret_llf == ReadSuccess);
4206 Alert::warning(_("File is read-only"),
4207 bformat(_("An emergency file is successfully loaded, "
4208 "but the original file %1$s is marked read-only. "
4209 "Please make sure to save the document as a different "
4210 "file."), from_utf8(d->filename.absFileName())));
4213 lyxvc().file_found_hook(d->filename);
4214 str = _("Document was successfully recovered.");
4216 str = _("Document was NOT successfully recovered.");
4217 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4218 makeDisplayPath(emergencyFile.absFileName()));
4220 int const del_emerg =
4221 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4222 _("&Remove"), _("&Keep"));
4223 if (del_emerg == 0) {
4224 emergencyFile.removeFile();
4226 Alert::warning(_("Emergency file deleted"),
4227 _("Do not forget to save your file now!"), true);
4229 return success ? ReadSuccess : ReadEmergencyFailure;
4232 int const del_emerg =
4233 Alert::prompt(_("Delete emergency file?"),
4234 _("Remove emergency file now?"), 1, 1,
4235 _("&Remove"), _("&Keep"));
4237 emergencyFile.removeFile();
4238 return ReadOriginal;
4248 Buffer::ReadStatus Buffer::loadAutosave()
4250 // Now check if autosave file is newer.
4251 FileName const autosaveFile = getAutosaveFileName();
4252 if (!autosaveFile.exists()
4253 || autosaveFile.lastModified() <= d->filename.lastModified())
4254 return ReadFileNotFound;
4256 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4257 docstring const text = bformat(_("The backup of the document %1$s "
4258 "is newer.\n\nLoad the backup instead?"), file);
4259 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4260 _("&Load backup"), _("Load &original"), _("&Cancel"));
4265 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4266 // the file is not saved if we load the autosave file.
4267 if (ret_llf == ReadSuccess) {
4269 Alert::warning(_("File is read-only"),
4270 bformat(_("A backup file is successfully loaded, "
4271 "but the original file %1$s is marked read-only. "
4272 "Please make sure to save the document as a "
4274 from_utf8(d->filename.absFileName())));
4277 lyxvc().file_found_hook(d->filename);
4280 return ReadAutosaveFailure;
4283 // Here we delete the autosave
4284 autosaveFile.removeFile();
4285 return ReadOriginal;
4293 Buffer::ReadStatus Buffer::loadLyXFile()
4295 if (!d->filename.isReadableFile()) {
4296 ReadStatus const ret_rvc = extractFromVC();
4297 if (ret_rvc != ReadSuccess)
4301 ReadStatus const ret_re = loadEmergency();
4302 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4305 ReadStatus const ret_ra = loadAutosave();
4306 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4309 return loadThisLyXFile(d->filename);
4313 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4315 return readFile(fn);
4319 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4321 TeXErrors::Errors::const_iterator it = terr.begin();
4322 TeXErrors::Errors::const_iterator end = terr.end();
4323 ListOfBuffers clist = getDescendents();
4324 ListOfBuffers::const_iterator cen = clist.end();
4326 for (; it != end; ++it) {
4329 int errorRow = it->error_in_line;
4330 Buffer const * buf = 0;
4332 if (it->child_name.empty())
4333 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4335 // The error occurred in a child
4336 ListOfBuffers::const_iterator cit = clist.begin();
4337 for (; cit != cen; ++cit) {
4338 string const child_name =
4339 DocFileName(changeExtension(
4340 (*cit)->absFileName(), "tex")).
4342 if (it->child_name != child_name)
4344 (*cit)->d->texrow.getIdFromRow(errorRow,
4345 id_start, pos_start);
4346 if (id_start != -1) {
4347 buf = d->cloned_buffer_
4348 ? (*cit)->d->cloned_buffer_->d->owner_
4349 : (*cit)->d->owner_;
4360 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4361 } while (found && id_start == id_end && pos_start == pos_end);
4363 if (id_start != id_end) {
4364 // Next registered position is outside the inset where
4365 // the error occurred, so signal end-of-paragraph
4369 errorList.push_back(ErrorItem(it->error_desc,
4370 it->error_text, id_start, pos_start, pos_end, buf));
4375 void Buffer::setBuffersForInsets() const
4377 inset().setBuffer(const_cast<Buffer &>(*this));
4381 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4383 LBUFERR(!text().paragraphs().empty());
4385 // Use the master text class also for child documents
4386 Buffer const * const master = masterBuffer();
4387 DocumentClass const & textclass = master->params().documentClass();
4389 // do this only if we are the top-level Buffer
4390 if (master == this) {
4391 textclass.counters().reset(from_ascii("bibitem"));
4392 reloadBibInfoCache();
4395 // keep the buffers to be children in this set. If the call from the
4396 // master comes back we can see which of them were actually seen (i.e.
4397 // via an InsetInclude). The remaining ones in the set need still be updated.
4398 static std::set<Buffer const *> bufToUpdate;
4399 if (scope == UpdateMaster) {
4400 // If this is a child document start with the master
4401 if (master != this) {
4402 bufToUpdate.insert(this);
4403 master->updateBuffer(UpdateMaster, utype);
4404 // If the master buffer has no gui associated with it, then the TocModel is
4405 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4406 // (bug 5699). The same happens if the master buffer is open in a different
4407 // window. This test catches both possibilities.
4408 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4409 // There remains a problem here: If there is another child open in yet a third
4410 // window, that TOC is not updated. So some more general solution is needed at
4412 if (master->d->gui_ != d->gui_)
4415 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4416 if (bufToUpdate.find(this) == bufToUpdate.end())
4420 // start over the counters in the master
4421 textclass.counters().reset();
4424 // update will be done below for this buffer
4425 bufToUpdate.erase(this);
4427 // update all caches
4428 clearReferenceCache();
4431 Buffer & cbuf = const_cast<Buffer &>(*this);
4434 ParIterator parit = cbuf.par_iterator_begin();
4435 updateBuffer(parit, utype);
4438 // TocBackend update will be done later.
4441 d->bibinfo_cache_valid_ = true;
4442 d->cite_labels_valid_ = true;
4443 cbuf.tocBackend().update(utype == OutputUpdate);
4444 if (scope == UpdateMaster)
4445 cbuf.structureChanged();
4449 static depth_type getDepth(DocIterator const & it)
4451 depth_type depth = 0;
4452 for (size_t i = 0 ; i < it.depth() ; ++i)
4453 if (!it[i].inset().inMathed())
4454 depth += it[i].paragraph().getDepth() + 1;
4455 // remove 1 since the outer inset does not count
4459 static depth_type getItemDepth(ParIterator const & it)
4461 Paragraph const & par = *it;
4462 LabelType const labeltype = par.layout().labeltype;
4464 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4467 // this will hold the lowest depth encountered up to now.
4468 depth_type min_depth = getDepth(it);
4469 ParIterator prev_it = it;
4472 --prev_it.top().pit();
4474 // start of nested inset: go to outer par
4476 if (prev_it.empty()) {
4477 // start of document: nothing to do
4482 // We search for the first paragraph with same label
4483 // that is not more deeply nested.
4484 Paragraph & prev_par = *prev_it;
4485 depth_type const prev_depth = getDepth(prev_it);
4486 if (labeltype == prev_par.layout().labeltype) {
4487 if (prev_depth < min_depth)
4488 return prev_par.itemdepth + 1;
4489 if (prev_depth == min_depth)
4490 return prev_par.itemdepth;
4492 min_depth = min(min_depth, prev_depth);
4493 // small optimization: if we are at depth 0, we won't
4494 // find anything else
4495 if (prev_depth == 0)
4501 static bool needEnumCounterReset(ParIterator const & it)
4503 Paragraph const & par = *it;
4504 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4505 depth_type const cur_depth = par.getDepth();
4506 ParIterator prev_it = it;
4507 while (prev_it.pit()) {
4508 --prev_it.top().pit();
4509 Paragraph const & prev_par = *prev_it;
4510 if (prev_par.getDepth() <= cur_depth)
4511 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4513 // start of nested inset: reset
4518 // set the label of a paragraph. This includes the counters.
4519 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4521 BufferParams const & bp = owner_->masterBuffer()->params();
4522 DocumentClass const & textclass = bp.documentClass();
4523 Paragraph & par = it.paragraph();
4524 Layout const & layout = par.layout();
4525 Counters & counters = textclass.counters();
4527 if (par.params().startOfAppendix()) {
4528 // We want to reset the counter corresponding to toplevel sectioning
4529 Layout const & lay = textclass.getTOCLayout();
4530 docstring const cnt = lay.counter;
4532 counters.reset(cnt);
4533 counters.appendix(true);
4535 par.params().appendix(counters.appendix());
4537 // Compute the item depth of the paragraph
4538 par.itemdepth = getItemDepth(it);
4540 if (layout.margintype == MARGIN_MANUAL) {
4541 if (par.params().labelWidthString().empty())
4542 par.params().labelWidthString(par.expandLabel(layout, bp));
4543 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4544 // we do not need to do anything here, since the empty case is
4545 // handled during export.
4547 par.params().labelWidthString(docstring());
4550 switch(layout.labeltype) {
4551 case LABEL_ITEMIZE: {
4552 // At some point of time we should do something more
4553 // clever here, like:
4554 // par.params().labelString(
4555 // bp.user_defined_bullet(par.itemdepth).getText());
4556 // for now, use a simple hardcoded label
4557 docstring itemlabel;
4558 switch (par.itemdepth) {
4560 itemlabel = char_type(0x2022);
4563 itemlabel = char_type(0x2013);
4566 itemlabel = char_type(0x2217);
4569 itemlabel = char_type(0x2219); // or 0x00b7
4572 par.params().labelString(itemlabel);
4576 case LABEL_ENUMERATE: {
4577 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4579 switch (par.itemdepth) {
4588 enumcounter += "iv";
4591 // not a valid enumdepth...
4595 // Maybe we have to reset the enumeration counter.
4596 if (needEnumCounterReset(it))
4597 counters.reset(enumcounter);
4598 counters.step(enumcounter, utype);
4600 string const & lang = par.getParLanguage(bp)->code();
4601 par.params().labelString(counters.theCounter(enumcounter, lang));
4606 case LABEL_SENSITIVE: {
4607 string const & type = counters.current_float();
4608 docstring full_label;
4610 full_label = owner_->B_("Senseless!!! ");
4612 docstring name = owner_->B_(textclass.floats().getType(type).name());
4613 if (counters.hasCounter(from_utf8(type))) {
4614 string const & lang = par.getParLanguage(bp)->code();
4615 counters.step(from_utf8(type), utype);
4616 full_label = bformat(from_ascii("%1$s %2$s:"),
4618 counters.theCounter(from_utf8(type), lang));
4620 full_label = bformat(from_ascii("%1$s #:"), name);
4622 par.params().labelString(full_label);
4626 case LABEL_NO_LABEL:
4627 par.params().labelString(docstring());
4631 case LABEL_CENTERED:
4632 case LABEL_STATIC: {
4633 docstring const & lcounter = layout.counter;
4634 if (!lcounter.empty()) {
4635 if (layout.toclevel <= bp.secnumdepth
4636 && (layout.latextype != LATEX_ENVIRONMENT
4637 || it.text()->isFirstInSequence(it.pit()))) {
4638 if (counters.hasCounter(lcounter))
4639 counters.step(lcounter, utype);
4640 par.params().labelString(par.expandLabel(layout, bp));
4642 par.params().labelString(docstring());
4644 par.params().labelString(par.expandLabel(layout, bp));
4650 par.params().labelString(par.expandLabel(layout, bp));
4655 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4657 // LASSERT: Is it safe to continue here, or should we just return?
4658 LASSERT(parit.pit() == 0, /**/);
4660 // Set the position of the text in the buffer to be able
4661 // to resolve macros in it.
4662 parit.text()->setMacrocontextPosition(parit);
4664 depth_type maxdepth = 0;
4665 pit_type const lastpit = parit.lastpit();
4666 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4667 // reduce depth if necessary
4668 if (parit->params().depth() > maxdepth) {
4669 /** FIXME: this function is const, but
4670 * nevertheless it modifies the buffer. To be
4671 * cleaner, one should modify the buffer in
4672 * another function, which is actually
4673 * non-const. This would however be costly in
4674 * terms of code duplication.
4676 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4677 parit->params().depth(maxdepth);
4679 maxdepth = parit->getMaxDepthAfter();
4681 if (utype == OutputUpdate) {
4682 // track the active counters
4683 // we have to do this for the master buffer, since the local
4684 // buffer isn't tracking anything.
4685 masterBuffer()->params().documentClass().counters().
4686 setActiveLayout(parit->layout());
4689 // set the counter for this paragraph
4690 d->setLabel(parit, utype);
4693 InsetList::const_iterator iit = parit->insetList().begin();
4694 InsetList::const_iterator end = parit->insetList().end();
4695 for (; iit != end; ++iit) {
4696 parit.pos() = iit->pos;
4697 iit->inset->updateBuffer(parit, utype);
4703 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4704 WordLangTuple & word_lang, docstring_list & suggestions) const
4708 suggestions.clear();
4709 word_lang = WordLangTuple();
4710 bool const to_end = to.empty();
4711 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4712 // OK, we start from here.
4713 for (; from != end; from.forwardPos()) {
4714 // We are only interested in text so remove the math CursorSlice.
4715 while (from.inMathed()) {
4719 // If from is at the end of the document (which is possible
4720 // when leaving the mathed) LyX will crash later otherwise.
4721 if (from.atEnd() || (!to_end && from >= end))
4724 from.paragraph().spellCheck();
4725 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4726 if (SpellChecker::misspelled(res)) {
4731 // Do not increase progress when from == to, otherwise the word
4732 // count will be wrong.
4742 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4744 bool inword = false;
4749 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4750 if (!dit.inTexted()) {
4755 Paragraph const & par = dit.paragraph();
4756 pos_type const pos = dit.pos();
4758 // Copied and adapted from isWordSeparator() in Paragraph
4759 if (pos == dit.lastpos()) {
4762 Inset const * ins = par.getInset(pos);
4763 if (ins && skipNoOutput && !ins->producesOutput()) {
4766 // stop if end of range was skipped
4767 if (!to.atEnd() && dit >= to)
4770 } else if (!par.isDeleted(pos)) {
4771 if (par.isWordSeparator(pos))
4777 if (ins && ins->isLetter())
4779 else if (ins && ins->isSpace())
4782 char_type const c = par.getChar(pos);
4783 if (isPrintableNonspace(c))
4785 else if (isSpace(c))
4795 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4797 d->updateStatistics(from, to, skipNoOutput);
4801 int Buffer::wordCount() const
4803 return d->wordCount();
4807 int Buffer::charCount(bool with_blanks) const
4809 return d->charCount(with_blanks);
4813 Buffer::ReadStatus Buffer::reload()
4816 // c.f. bug http://www.lyx.org/trac/ticket/6587
4817 removeAutosaveFile();
4818 // e.g., read-only status could have changed due to version control
4819 d->filename.refresh();
4820 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4822 // clear parent. this will get reset if need be.
4824 ReadStatus const status = loadLyXFile();
4825 if (status == ReadSuccess) {
4830 message(bformat(_("Document %1$s reloaded."), disp_fn));
4833 message(bformat(_("Could not reload document %1$s."), disp_fn));
4843 bool Buffer::saveAs(FileName const & fn)
4845 FileName const old_name = fileName();
4846 FileName const old_auto = getAutosaveFileName();
4847 bool const old_unnamed = isUnnamed();
4854 // bring the autosave file with us, just in case.
4855 moveAutosaveFile(old_auto);
4856 // validate version control data and
4857 // correct buffer title
4858 lyxvc().file_found_hook(fileName());
4860 // the file has now been saved to the new location.
4861 // we need to check that the locations of child buffers
4863 checkChildBuffers();
4864 checkMasterBuffer();
4868 // reset the old filename and unnamed state
4869 setFileName(old_name);
4870 setUnnamed(old_unnamed);
4876 // FIXME We could do better here, but it is complicated. What would be
4877 // nice is to offer either (a) to save the child buffer to an appropriate
4878 // location, so that it would "move with the master", or else (b) to update
4879 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4880 // complicated, because the code for this lives in GuiView.
4881 void Buffer::checkChildBuffers()
4883 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4884 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4885 for (; it != en; ++it) {
4886 DocIterator dit = it->second;
4887 Buffer * cbuf = const_cast<Buffer *>(it->first);
4888 if (!cbuf || !theBufferList().isLoaded(cbuf))
4890 Inset * inset = dit.nextInset();
4891 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4892 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4893 docstring const & incfile = inset_inc->getParam("filename");
4894 string oldloc = cbuf->absFileName();
4895 string newloc = makeAbsPath(to_utf8(incfile),
4896 onlyPath(absFileName())).absFileName();
4897 if (oldloc == newloc)
4899 // the location of the child file is incorrect.
4900 Alert::warning(_("Included File Invalid"),
4901 bformat(_("Saving this document to a new location has made the file:\n"
4903 "inaccessible. You will need to update the included filename."),
4904 from_utf8(oldloc)));
4906 inset_inc->setChildBuffer(0);
4908 // invalidate cache of children
4909 d->children_positions.clear();
4910 d->position_to_children.clear();
4914 // If a child has been saved under a different name/path, it might have been
4915 // orphaned. Therefore the master needs to be reset (bug 8161).
4916 void Buffer::checkMasterBuffer()
4918 Buffer const * const master = masterBuffer();
4922 // necessary to re-register the child (bug 5873)
4923 // FIXME: clean up updateMacros (here, only
4924 // child registering is needed).
4925 master->updateMacros();
4926 // (re)set master as master buffer, but only
4927 // if we are a real child
4928 if (master->isChild(this))