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), inset(0), preview_loader_(0),
389 cloned_buffer_(cloned_buffer), clone_list_(0),
390 doing_export(false), parent_buffer(0),
391 word_count_(0), char_count_(0), blank_count_(0)
393 if (!cloned_buffer_) {
394 temppath = createBufferTmpDir();
395 lyxvc.setBuffer(owner_);
397 wa_ = new frontend::WorkAreaManager;
400 temppath = cloned_buffer_->d->temppath;
401 file_fully_loaded = true;
402 params = cloned_buffer_->d->params;
403 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
404 bibinfo_ = cloned_buffer_->d->bibinfo_;
405 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
406 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
407 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
408 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
409 unnamed = cloned_buffer_->d->unnamed;
410 internal_buffer = cloned_buffer_->d->internal_buffer;
414 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
415 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
417 LYXERR(Debug::INFO, "Buffer::Buffer()");
419 d->inset = new InsetText(*cloned_buffer->d->inset);
420 d->inset->setBuffer(*this);
421 // FIXME: optimize this loop somewhat, maybe by creating a new
422 // general recursive Inset::setId().
423 DocIterator it = doc_iterator_begin(this);
424 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
425 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
426 it.paragraph().setId(cloned_it.paragraph().id());
428 d->inset = new InsetText(this);
429 d->inset->setAutoBreakRows(true);
430 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
436 LYXERR(Debug::INFO, "Buffer::~Buffer()");
437 // here the buffer should take care that it is
438 // saved properly, before it goes into the void.
440 // GuiView already destroyed
444 // No need to do additional cleanups for internal buffer.
450 // this is in case of recursive includes: we won't try to delete
451 // ourselves as a child.
452 d->clone_list_->erase(this);
453 // loop over children
454 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
455 Impl::BufferPositionMap::iterator end = d->children_positions.end();
456 for (; it != end; ++it) {
457 Buffer * child = const_cast<Buffer *>(it->first);
458 if (d->clone_list_->erase(child))
461 // if we're the master buffer, then we should get rid of the list
464 // If this is not empty, we have leaked something. Worse, one of the
465 // children still has a reference to this list. But we will try to
466 // continue, rather than shut down.
467 LATTEST(d->clone_list_->empty());
468 list<CloneList *>::iterator it =
469 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
470 if (it == cloned_buffers.end()) {
471 // We will leak in this case, but it is safe to continue.
474 cloned_buffers.erase(it);
475 delete d->clone_list_;
477 // FIXME Do we really need to do this right before we delete d?
478 // clear references to children in macro tables
479 d->children_positions.clear();
480 d->position_to_children.clear();
482 // loop over children
483 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
484 Impl::BufferPositionMap::iterator end = d->children_positions.end();
485 for (; it != end; ++it) {
486 Buffer * child = const_cast<Buffer *>(it->first);
487 if (theBufferList().isLoaded(child))
488 theBufferList().releaseChild(this, child);
492 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
493 msg += emergencyWrite();
494 Alert::warning(_("Attempting to close changed document!"), msg);
497 // FIXME Do we really need to do this right before we delete d?
498 // clear references to children in macro tables
499 d->children_positions.clear();
500 d->position_to_children.clear();
502 if (!d->temppath.destroyDirectory()) {
503 Alert::warning(_("Could not remove temporary directory"),
504 bformat(_("Could not remove the temporary directory %1$s"),
505 from_utf8(d->temppath.absFileName())));
514 Buffer * Buffer::cloneFromMaster() const
517 cloned_buffers.push_back(new CloneList);
518 CloneList * clones = cloned_buffers.back();
520 masterBuffer()->cloneWithChildren(bufmap, clones);
522 // make sure we got cloned
523 BufferMap::const_iterator bit = bufmap.find(this);
524 LASSERT(bit != bufmap.end(), return 0);
525 Buffer * cloned_buffer = bit->second;
527 return cloned_buffer;
531 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
533 // have we already been cloned?
534 if (bufmap.find(this) != bufmap.end())
537 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
539 // The clone needs its own DocumentClass, since running updateBuffer() will
540 // modify it, and we would otherwise be sharing it with the original Buffer.
541 buffer_clone->params().makeDocumentClass(true);
543 cap::switchBetweenClasses(
544 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
545 static_cast<InsetText &>(buffer_clone->inset()), el);
547 bufmap[this] = buffer_clone;
548 clones->insert(buffer_clone);
549 buffer_clone->d->clone_list_ = clones;
550 buffer_clone->d->macro_lock = true;
551 buffer_clone->d->children_positions.clear();
553 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
554 // math macro caches need to be rethought and simplified.
555 // I am not sure wether we should handle Buffer cloning here or in BufferList.
556 // Right now BufferList knows nothing about buffer clones.
557 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
558 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
559 for (; it != end; ++it) {
560 DocIterator dit = it->first.clone(buffer_clone);
561 dit.setBuffer(buffer_clone);
562 Buffer * child = const_cast<Buffer *>(it->second.second);
564 child->cloneWithChildren(bufmap, clones);
565 BufferMap::iterator const bit = bufmap.find(child);
566 LASSERT(bit != bufmap.end(), continue);
567 Buffer * child_clone = bit->second;
569 Inset * inset = dit.nextInset();
570 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
571 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
572 inset_inc->setChildBuffer(child_clone);
573 child_clone->d->setParent(buffer_clone);
574 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
575 buffer_clone->setChild(dit, child_clone);
577 buffer_clone->d->macro_lock = false;
582 Buffer * Buffer::cloneBufferOnly() const {
583 cloned_buffers.push_back(new CloneList);
584 CloneList * clones = cloned_buffers.back();
585 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
587 // The clone needs its own DocumentClass, since running updateBuffer() will
588 // modify it, and we would otherwise be sharing it with the original Buffer.
589 buffer_clone->params().makeDocumentClass(true);
591 cap::switchBetweenClasses(
592 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
593 static_cast<InsetText &>(buffer_clone->inset()), el);
595 clones->insert(buffer_clone);
596 buffer_clone->d->clone_list_ = clones;
598 // we won't be cloning the children
599 buffer_clone->d->children_positions.clear();
604 bool Buffer::isClone() const
606 return d->cloned_buffer_;
610 void Buffer::changed(bool update_metrics) const
613 d->wa_->redrawAll(update_metrics);
617 frontend::WorkAreaManager & Buffer::workAreaManager() const
624 Text & Buffer::text() const
626 return d->inset->text();
630 Inset & Buffer::inset() const
636 BufferParams & Buffer::params()
642 BufferParams const & Buffer::params() const
648 BufferParams const & Buffer::masterParams() const
650 if (masterBuffer() == this)
653 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
654 // Copy child authors to the params. We need those pointers.
655 AuthorList const & child_authors = params().authors();
656 AuthorList::Authors::const_iterator it = child_authors.begin();
657 for (; it != child_authors.end(); ++it)
658 mparams.authors().record(*it);
663 double Buffer::fontScalingFactor() const
665 return isExporting() ? 75.0 * params().html_math_img_scale
666 : 0.01 * lyxrc.dpi * lyxrc.zoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
670 ParagraphList & Buffer::paragraphs()
672 return text().paragraphs();
676 ParagraphList const & Buffer::paragraphs() const
678 return text().paragraphs();
682 LyXVC & Buffer::lyxvc()
688 LyXVC const & Buffer::lyxvc() const
694 string const Buffer::temppath() const
696 return d->temppath.absFileName();
700 TexRow & Buffer::texrow()
706 TexRow const & Buffer::texrow() const
712 TocBackend & Buffer::tocBackend() const
714 return d->toc_backend;
718 Undo & Buffer::undo()
724 void Buffer::setChild(DocIterator const & dit, Buffer * child)
726 d->children_positions[child] = dit;
730 string Buffer::latexName(bool const no_path) const
732 FileName latex_name =
733 makeLatexName(d->exportFileName());
734 return no_path ? latex_name.onlyFileName()
735 : latex_name.absFileName();
739 FileName Buffer::Impl::exportFileName() const
741 docstring const branch_suffix =
742 params.branchlist().getFileNameSuffix();
743 if (branch_suffix.empty())
746 string const name = filename.onlyFileNameWithoutExt()
747 + to_utf8(branch_suffix);
748 FileName res(filename.onlyPath().absFileName() + "/" + name);
749 res.changeExtension(filename.extension());
755 string Buffer::logName(LogType * type) const
757 string const filename = latexName(false);
759 if (filename.empty()) {
765 string const path = temppath();
767 FileName const fname(addName(temppath(),
768 onlyFileName(changeExtension(filename,
771 // FIXME: how do we know this is the name of the build log?
772 FileName const bname(
773 addName(path, onlyFileName(
774 changeExtension(filename,
775 formats.extension(params().bufferFormat()) + ".out"))));
777 // Also consider the master buffer log file
778 FileName masterfname = fname;
779 LogType mtype = latexlog;
780 if (masterBuffer() != this) {
781 string const mlogfile = masterBuffer()->logName(&mtype);
782 masterfname = FileName(mlogfile);
785 // If no Latex log or Build log is newer, show Build log
786 if (bname.exists() &&
787 ((!fname.exists() && !masterfname.exists())
788 || (fname.lastModified() < bname.lastModified()
789 && masterfname.lastModified() < bname.lastModified()))) {
790 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
793 return bname.absFileName();
794 // If we have a newer master file log or only a master log, show this
795 } else if (fname != masterfname
796 && (!fname.exists() && (masterfname.exists()
797 || fname.lastModified() < masterfname.lastModified()))) {
798 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
801 return masterfname.absFileName();
803 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
806 return fname.absFileName();
810 void Buffer::setReadonly(bool const flag)
812 if (d->read_only != flag) {
819 void Buffer::setFileName(FileName const & fname)
821 bool const changed = fname != d->filename;
824 lyxvc().file_found_hook(fname);
825 setReadonly(d->filename.isReadOnly());
831 int Buffer::readHeader(Lexer & lex)
833 int unknown_tokens = 0;
835 int begin_header_line = -1;
837 // Initialize parameters that may be/go lacking in header:
838 params().branchlist().clear();
839 params().preamble.erase();
840 params().options.erase();
841 params().master.erase();
842 params().float_placement.erase();
843 params().paperwidth.erase();
844 params().paperheight.erase();
845 params().leftmargin.erase();
846 params().rightmargin.erase();
847 params().topmargin.erase();
848 params().bottommargin.erase();
849 params().headheight.erase();
850 params().headsep.erase();
851 params().footskip.erase();
852 params().columnsep.erase();
853 params().fonts_cjk.erase();
854 params().listings_params.clear();
855 params().clearLayoutModules();
856 params().clearRemovedModules();
857 params().clearIncludedChildren();
858 params().pdfoptions().clear();
859 params().indiceslist().clear();
860 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
861 params().isbackgroundcolor = false;
862 params().fontcolor = RGBColor(0, 0, 0);
863 params().isfontcolor = false;
864 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
865 params().boxbgcolor = RGBColor(0xFF, 0, 0);
866 params().html_latex_start.clear();
867 params().html_latex_end.clear();
868 params().html_math_img_scale = 1.0;
869 params().output_sync_macro.erase();
870 params().setLocalLayout(string(), false);
871 params().setLocalLayout(string(), true);
873 for (int i = 0; i < 4; ++i) {
874 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
875 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
878 ErrorList & errorList = d->errorLists["Parse"];
887 if (token == "\\end_header")
891 if (token == "\\begin_header") {
892 begin_header_line = line;
896 LYXERR(Debug::PARSER, "Handling document header token: `"
899 string unknown = params().readToken(lex, token, d->filename.onlyPath());
900 if (!unknown.empty()) {
901 if (unknown[0] != '\\' && token == "\\textclass") {
902 Alert::warning(_("Unknown document class"),
903 bformat(_("Using the default document class, because the "
904 "class %1$s is unknown."), from_utf8(unknown)));
907 docstring const s = bformat(_("Unknown token: "
911 errorList.push_back(ErrorItem(_("Document header error"),
916 if (begin_header_line) {
917 docstring const s = _("\\begin_header is missing");
918 errorList.push_back(ErrorItem(_("Document header error"),
922 params().makeDocumentClass();
924 return unknown_tokens;
929 // changed to be public and have one parameter
930 // Returns true if "\end_document" is not read (Asger)
931 bool Buffer::readDocument(Lexer & lex)
933 ErrorList & errorList = d->errorLists["Parse"];
936 // remove dummy empty par
937 paragraphs().clear();
939 if (!lex.checkFor("\\begin_document")) {
940 docstring const s = _("\\begin_document is missing");
941 errorList.push_back(ErrorItem(_("Document header error"),
947 if (params().output_changes) {
948 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
949 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
950 LaTeXFeatures::isAvailable("xcolor");
952 if (!dvipost && !xcolorulem) {
953 Alert::warning(_("Changes not shown in LaTeX output"),
954 _("Changes will not be highlighted in LaTeX output, "
955 "because neither dvipost nor xcolor/ulem are installed.\n"
956 "Please install these packages or redefine "
957 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
958 } else if (!xcolorulem) {
959 Alert::warning(_("Changes not shown in LaTeX output"),
960 _("Changes will not be highlighted in LaTeX output "
961 "when using pdflatex, because xcolor and ulem are not installed.\n"
962 "Please install both packages or redefine "
963 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
967 if (!parent() && !params().master.empty()) {
968 FileName const master_file = makeAbsPath(params().master,
969 onlyPath(absFileName()));
970 if (isLyXFileName(master_file.absFileName())) {
972 checkAndLoadLyXFile(master_file, true);
974 // necessary e.g. after a reload
975 // to re-register the child (bug 5873)
976 // FIXME: clean up updateMacros (here, only
977 // child registering is needed).
978 master->updateMacros();
979 // set master as master buffer, but only
980 // if we are a real child
981 if (master->isChild(this))
983 // if the master is not fully loaded
984 // it is probably just loading this
985 // child. No warning needed then.
986 else if (master->isFullyLoaded())
987 LYXERR0("The master '"
989 << "' assigned to this document ("
991 << ") does not include "
992 "this document. Ignoring the master assignment.");
997 // assure we have a default index
998 params().indiceslist().addDefault(B_("Index"));
1001 bool const res = text().read(lex, errorList, d->inset);
1003 // inform parent buffer about local macros
1005 Buffer const * pbuf = parent();
1006 UserMacroSet::const_iterator cit = usermacros.begin();
1007 UserMacroSet::const_iterator end = usermacros.end();
1008 for (; cit != end; ++cit)
1009 pbuf->usermacros.insert(*cit);
1013 updateMacroInstances(InternalUpdate);
1018 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1020 Format const * fmt = formats.getFormat(format);
1023 // It is important to use the correct extension here, since some
1024 // converters create a wrong output file otherwise (e.g. html2latex)
1025 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1026 FileName const name(tempfile.name());
1027 ofdocstream os(name.toFilesystemEncoding().c_str());
1028 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1029 bool const success = !(os << contents).fail();
1032 bool converted = false;
1034 params().compressed = false;
1036 // remove dummy empty par
1037 paragraphs().clear();
1039 converted = importFile(format, name, errorList);
1048 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1050 if (!theConverters().isReachable(format, "lyx"))
1053 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1054 FileName const lyx(tempfile.name());
1055 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1056 return readFile(lyx) == ReadSuccess;
1062 bool Buffer::readString(string const & s)
1064 params().compressed = false;
1067 istringstream is(s);
1069 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1070 FileName const fn = tempfile.name();
1073 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1075 if (success && file_format != LYX_FORMAT) {
1076 // We need to call lyx2lyx, so write the input to a file
1077 ofstream os(fn.toFilesystemEncoding().c_str());
1080 // lyxvc in readFile
1081 if (readFile(fn) != ReadSuccess)
1085 if (readDocument(lex))
1091 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1095 if (!lex.setFile(fname)) {
1096 Alert::error(_("File Not Found"),
1097 bformat(_("Unable to open file `%1$s'."),
1098 from_utf8(fn.absFileName())));
1099 return ReadFileNotFound;
1103 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1104 if (ret_plf != ReadSuccess)
1107 if (file_format != LYX_FORMAT) {
1109 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1110 if (ret_clf != ReadSuccess)
1112 return readFile(tmpFile);
1115 // FIXME: InsetInfo needs to know whether the file is under VCS
1116 // during the parse process, so this has to be done before.
1117 lyxvc().file_found_hook(d->filename);
1119 if (readDocument(lex)) {
1120 Alert::error(_("Document format failure"),
1121 bformat(_("%1$s ended unexpectedly, which means"
1122 " that it is probably corrupted."),
1123 from_utf8(fn.absFileName())));
1124 return ReadDocumentFailure;
1127 d->file_fully_loaded = true;
1128 d->read_only = !d->filename.isWritable();
1129 params().compressed = formats.isZippedFile(d->filename);
1135 bool Buffer::isFullyLoaded() const
1137 return d->file_fully_loaded;
1141 void Buffer::setFullyLoaded(bool value)
1143 d->file_fully_loaded = value;
1147 PreviewLoader * Buffer::loader() const
1149 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1151 if (!d->preview_loader_)
1152 d->preview_loader_ = new PreviewLoader(*this);
1153 return d->preview_loader_;
1157 void Buffer::removePreviews() const
1159 delete d->preview_loader_;
1160 d->preview_loader_ = 0;
1164 void Buffer::updatePreviews() const
1166 PreviewLoader * ploader = loader();
1170 InsetIterator it = inset_iterator_begin(*d->inset);
1171 InsetIterator const end = inset_iterator_end(*d->inset);
1172 for (; it != end; ++it)
1173 it->addPreview(it, *ploader);
1175 ploader->startLoading();
1179 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1180 FileName const & fn, int & file_format) const
1182 if(!lex.checkFor("\\lyxformat")) {
1183 Alert::error(_("Document format failure"),
1184 bformat(_("%1$s is not a readable LyX document."),
1185 from_utf8(fn.absFileName())));
1186 return ReadNoLyXFormat;
1192 // LyX formats 217 and earlier were written as 2.17. This corresponds
1193 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1194 // these cases. See also: www.lyx.org/trac/changeset/1313.
1195 size_t dot = tmp_format.find_first_of(".,");
1196 if (dot != string::npos)
1197 tmp_format.erase(dot, 1);
1199 file_format = convert<int>(tmp_format);
1204 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1205 FileName & tmpfile, int from_format)
1207 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1208 tempfile.setAutoRemove(false);
1209 tmpfile = tempfile.name();
1210 if(tmpfile.empty()) {
1211 Alert::error(_("Conversion failed"),
1212 bformat(_("%1$s is from a different"
1213 " version of LyX, but a temporary"
1214 " file for converting it could"
1215 " not be created."),
1216 from_utf8(fn.absFileName())));
1217 return LyX2LyXNoTempFile;
1220 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1221 if (lyx2lyx.empty()) {
1222 Alert::error(_("Conversion script not found"),
1223 bformat(_("%1$s is from a different"
1224 " version of LyX, but the"
1225 " conversion script lyx2lyx"
1226 " could not be found."),
1227 from_utf8(fn.absFileName())));
1228 return LyX2LyXNotFound;
1232 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1233 ostringstream command;
1234 command << os::python()
1235 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1236 << " -t " << convert<string>(LYX_FORMAT)
1237 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1238 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1239 string const command_str = command.str();
1241 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1243 cmd_ret const ret = runCommand(command_str);
1244 if (ret.first != 0) {
1245 if (from_format < LYX_FORMAT) {
1246 Alert::error(_("Conversion script failed"),
1247 bformat(_("%1$s is from an older version"
1248 " of LyX and the lyx2lyx script"
1249 " failed to convert it."),
1250 from_utf8(fn.absFileName())));
1251 return LyX2LyXOlderFormat;
1253 Alert::error(_("Conversion script failed"),
1254 bformat(_("%1$s is from a newer version"
1255 " of LyX and the lyx2lyx script"
1256 " failed to convert it."),
1257 from_utf8(fn.absFileName())));
1258 return LyX2LyXNewerFormat;
1265 // Should probably be moved to somewhere else: BufferView? GuiView?
1266 bool Buffer::save() const
1268 docstring const file = makeDisplayPath(absFileName(), 20);
1269 d->filename.refresh();
1271 // check the read-only status before moving the file as a backup
1272 if (d->filename.exists()) {
1273 bool const read_only = !d->filename.isWritable();
1275 Alert::warning(_("File is read-only"),
1276 bformat(_("The file %1$s cannot be written because it "
1277 "is marked as read-only."), file));
1282 // ask if the disk file has been externally modified (use checksum method)
1283 if (fileName().exists() && isExternallyModified(checksum_method)) {
1285 bformat(_("Document %1$s has been externally modified. "
1286 "Are you sure you want to overwrite this file?"), file);
1287 int const ret = Alert::prompt(_("Overwrite modified file?"),
1288 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1293 // We don't need autosaves in the immediate future. (Asger)
1294 resetAutosaveTimers();
1296 // if the file does not yet exist, none of the backup activity
1297 // that follows is necessary
1298 if (!fileName().exists())
1299 return writeFile(fileName());
1301 // we first write the file to a new name, then move it to its
1302 // proper location once that has been done successfully. that
1303 // way we preserve the original file if something goes wrong.
1304 string const justname = fileName().onlyFileNameWithoutExt();
1305 boost::scoped_ptr<TempFile>
1306 tempfile(new TempFile(fileName().onlyPath(),
1307 justname + "-XXXXXX.lyx"));
1308 bool const symlink = fileName().isSymLink();
1310 tempfile->setAutoRemove(false);
1312 FileName savefile(tempfile->name());
1313 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1314 if (!writeFile(savefile))
1317 // we will set this to false if we fail
1318 bool made_backup = true;
1320 FileName backupName(absFileName() + '~');
1321 if (lyxrc.make_backup) {
1322 if (!lyxrc.backupdir_path.empty()) {
1323 string const mangledName =
1324 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1325 backupName = FileName(addName(lyxrc.backupdir_path,
1329 LYXERR(Debug::FILES, "Backing up original file to " <<
1330 backupName.absFileName());
1331 // Except file is symlink do not copy because of #6587.
1332 // Hard links have bad luck.
1333 made_backup = symlink ?
1334 fileName().copyTo(backupName):
1335 fileName().moveTo(backupName);
1338 Alert::error(_("Backup failure"),
1339 bformat(_("Cannot create backup file %1$s.\n"
1340 "Please check whether the directory exists and is writable."),
1341 from_utf8(backupName.absFileName())));
1342 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1346 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1347 // Only do this if tempfile is not in autoremove mode
1350 // If we have no symlink, we can simply rename the temp file.
1351 // Otherwise, we need to copy it so the symlink stays intact.
1352 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1353 savefile.moveTo(fileName()))
1355 // saveCheckSum() was already called by writeFile(), but the
1356 // time stamp is invalidated by copying/moving
1361 // else we saved the file, but failed to move it to the right location.
1363 if (lyxrc.make_backup && made_backup && !symlink) {
1364 // the original file was moved to filename.lyx~, so it will look
1365 // to the user as if it was deleted. (see bug #9234.) we could try
1366 // to restore it, but that would basically mean trying to do again
1367 // what we just failed to do. better to leave things as they are.
1368 Alert::error(_("Write failure"),
1369 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1370 "But LyX could not move it to:\n %2$s.\n"
1371 "Your original file has been backed up to:\n %3$s"),
1372 from_utf8(savefile.absFileName()),
1373 from_utf8(fileName().absFileName()),
1374 from_utf8(backupName.absFileName())));
1376 // either we did not try to make a backup, or else we tried and failed,
1377 // or else the original file was a symlink, in which case it was copied,
1378 // not moved. so the original file is intact.
1379 Alert::error(_("Write failure"),
1380 bformat(_("Cannot move saved file to:\n %1$s.\n"
1381 "But the file has successfully been saved as:\n %2$s."),
1382 from_utf8(fileName().absFileName()),
1383 from_utf8(savefile.absFileName())));
1389 bool Buffer::writeFile(FileName const & fname) const
1391 if (d->read_only && fname == d->filename)
1394 bool retval = false;
1396 docstring const str = bformat(_("Saving document %1$s..."),
1397 makeDisplayPath(fname.absFileName()));
1400 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1402 if (params().compressed) {
1403 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1404 retval = ofs && write(ofs);
1406 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1407 retval = ofs && write(ofs);
1411 message(str + _(" could not write file!"));
1416 // removeAutosaveFile();
1419 message(str + _(" done."));
1425 docstring Buffer::emergencyWrite()
1427 // No need to save if the buffer has not changed.
1431 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1433 docstring user_message = bformat(
1434 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1436 // We try to save three places:
1437 // 1) Same place as document. Unless it is an unnamed doc.
1439 string s = absFileName();
1442 if (writeFile(FileName(s))) {
1444 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1445 return user_message;
1447 user_message += " " + _("Save failed! Trying again...\n");
1451 // 2) In HOME directory.
1452 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1454 lyxerr << ' ' << s << endl;
1455 if (writeFile(FileName(s))) {
1457 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1458 return user_message;
1461 user_message += " " + _("Save failed! Trying yet again...\n");
1463 // 3) In "/tmp" directory.
1464 // MakeAbsPath to prepend the current
1465 // drive letter on OS/2
1466 s = addName(package().temp_dir().absFileName(), absFileName());
1468 lyxerr << ' ' << s << endl;
1469 if (writeFile(FileName(s))) {
1471 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1472 return user_message;
1475 user_message += " " + _("Save failed! Bummer. Document is lost.");
1478 return user_message;
1482 bool Buffer::write(ostream & ofs) const
1485 // Use the standard "C" locale for file output.
1486 ofs.imbue(locale::classic());
1489 // The top of the file should not be written by params().
1491 // write out a comment in the top of the file
1492 // Important: Keep the version formatting in sync with lyx2lyx and
1493 // tex2lyx (bug 7951)
1494 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1495 << " created this file. For more info see http://www.lyx.org/\n"
1496 << "\\lyxformat " << LYX_FORMAT << "\n"
1497 << "\\begin_document\n";
1499 /// For each author, set 'used' to true if there is a change
1500 /// by this author in the document; otherwise set it to 'false'.
1501 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1502 AuthorList::Authors::const_iterator a_end = params().authors().end();
1503 for (; a_it != a_end; ++a_it)
1504 a_it->setUsed(false);
1506 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1507 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1508 for ( ; it != end; ++it)
1509 it->checkAuthors(params().authors());
1511 // now write out the buffer parameters.
1512 ofs << "\\begin_header\n";
1513 params().writeFile(ofs);
1514 ofs << "\\end_header\n";
1517 ofs << "\n\\begin_body\n";
1519 ofs << "\n\\end_body\n";
1521 // Write marker that shows file is complete
1522 ofs << "\\end_document" << endl;
1524 // Shouldn't really be needed....
1527 // how to check if close went ok?
1528 // Following is an attempt... (BE 20001011)
1530 // good() returns false if any error occurred, including some
1531 // formatting error.
1532 // bad() returns true if something bad happened in the buffer,
1533 // which should include file system full errors.
1538 lyxerr << "File was not closed properly." << endl;
1545 bool Buffer::makeLaTeXFile(FileName const & fname,
1546 string const & original_path,
1547 OutputParams const & runparams_in,
1548 OutputWhat output) const
1550 OutputParams runparams = runparams_in;
1552 // This is necessary for LuaTeX/XeTeX with tex fonts.
1553 // See FIXME in BufferParams::encoding()
1554 if (runparams.isFullUnicode())
1555 runparams.encoding = encodings.fromLyXName("utf8-plain");
1557 string const encoding = runparams.encoding->iconvName();
1558 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1561 try { ofs.reset(encoding); }
1562 catch (iconv_codecvt_facet_exception const & e) {
1563 lyxerr << "Caught iconv exception: " << e.what() << endl;
1564 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1565 "verify that the support software for your encoding (%1$s) is "
1566 "properly installed"), from_ascii(encoding)));
1569 if (!openFileWrite(ofs, fname))
1572 ErrorList & errorList = d->errorLists["Export"];
1574 bool failed_export = false;
1575 otexstream os(ofs, d->texrow);
1577 // make sure we are ready to export
1578 // this needs to be done before we validate
1579 // FIXME Do we need to do this all the time? I.e., in children
1580 // of a master we are exporting?
1582 updateMacroInstances(OutputUpdate);
1585 os.texrow().reset();
1586 writeLaTeXSource(os, original_path, runparams, output);
1588 catch (EncodingException const & e) {
1589 docstring const failed(1, e.failed_char);
1591 oss << "0x" << hex << e.failed_char << dec;
1592 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1593 " (code point %2$s)"),
1594 failed, from_utf8(oss.str()));
1595 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1596 "representable in the chosen encoding.\n"
1597 "Changing the document encoding to utf8 could help."),
1598 e.par_id, e.pos, e.pos + 1));
1599 failed_export = true;
1601 catch (iconv_codecvt_facet_exception const & e) {
1602 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1603 _(e.what()), -1, 0, 0));
1604 failed_export = true;
1606 catch (exception const & e) {
1607 errorList.push_back(ErrorItem(_("conversion failed"),
1608 _(e.what()), -1, 0, 0));
1609 failed_export = true;
1612 lyxerr << "Caught some really weird exception..." << endl;
1618 failed_export = true;
1619 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1622 if (runparams_in.silent)
1626 return !failed_export;
1630 void Buffer::writeLaTeXSource(otexstream & os,
1631 string const & original_path,
1632 OutputParams const & runparams_in,
1633 OutputWhat output) const
1635 // The child documents, if any, shall be already loaded at this point.
1637 OutputParams runparams = runparams_in;
1639 // This is necessary for LuaTeX/XeTeX with tex fonts.
1640 // See FIXME in BufferParams::encoding()
1641 if (runparams.isFullUnicode())
1642 runparams.encoding = encodings.fromLyXName("utf8-plain");
1644 // If we are compiling a file standalone, even if this is the
1645 // child of some other buffer, let's cut the link here, so the
1646 // file is really independent and no concurring settings from
1647 // the master (e.g. branch state) interfere (see #8100).
1648 if (!runparams.is_child)
1649 d->ignore_parent = true;
1651 // Classify the unicode characters appearing in math insets
1652 BufferEncodings::initUnicodeMath(*this);
1654 // validate the buffer.
1655 LYXERR(Debug::LATEX, " Validating buffer...");
1656 LaTeXFeatures features(*this, params(), runparams);
1658 // This is only set once per document (in master)
1659 if (!runparams.is_child)
1660 runparams.use_polyglossia = features.usePolyglossia();
1661 LYXERR(Debug::LATEX, " Buffer validation done.");
1663 bool const output_preamble =
1664 output == FullSource || output == OnlyPreamble;
1665 bool const output_body =
1666 output == FullSource || output == OnlyBody;
1668 // The starting paragraph of the coming rows is the
1669 // first paragraph of the document. (Asger)
1670 if (output_preamble && runparams.nice) {
1671 os << "%% LyX " << lyx_version << " created this file. "
1672 "For more info, see http://www.lyx.org/.\n"
1673 "%% Do not edit unless you really know what "
1676 LYXERR(Debug::INFO, "lyx document header finished");
1678 // There are a few differences between nice LaTeX and usual files:
1679 // usual files have \batchmode and special input@path to allow
1680 // inclusion of figures specified by an explicitly relative path
1681 // (i.e., a path starting with './' or '../') with either \input or
1682 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1683 // input@path is set when the actual parameter original_path is set.
1684 // This is done for usual tex-file, but not for nice-latex-file.
1685 // (Matthias 250696)
1686 // Note that input@path is only needed for something the user does
1687 // in the preamble, included .tex files or ERT, files included by
1688 // LyX work without it.
1689 if (output_preamble) {
1690 if (!runparams.nice) {
1691 // code for usual, NOT nice-latex-file
1692 os << "\\batchmode\n"; // changed from \nonstopmode
1694 if (!original_path.empty()) {
1696 // We don't know the encoding of inputpath
1697 docstring const inputpath = from_utf8(original_path);
1698 docstring uncodable_glyphs;
1699 Encoding const * const enc = runparams.encoding;
1701 for (size_t n = 0; n < inputpath.size(); ++n) {
1702 if (!enc->encodable(inputpath[n])) {
1703 docstring const glyph(1, inputpath[n]);
1704 LYXERR0("Uncodable character '"
1706 << "' in input path!");
1707 uncodable_glyphs += glyph;
1712 // warn user if we found uncodable glyphs.
1713 if (!uncodable_glyphs.empty()) {
1714 frontend::Alert::warning(
1715 _("Uncodable character in file path"),
1717 _("The path of your document\n"
1719 "contains glyphs that are unknown "
1720 "in the current document encoding "
1721 "(namely %2$s). This may result in "
1722 "incomplete output, unless "
1723 "TEXINPUTS contains the document "
1724 "directory and you don't use "
1725 "explicitly relative paths (i.e., "
1726 "paths starting with './' or "
1727 "'../') in the preamble or in ERT."
1728 "\n\nIn case of problems, choose "
1729 "an appropriate document encoding\n"
1730 "(such as utf8) or change the "
1732 inputpath, uncodable_glyphs));
1735 support::latex_path(original_path);
1736 if (contains(docdir, '#')) {
1737 docdir = subst(docdir, "#", "\\#");
1738 os << "\\catcode`\\#=11"
1739 "\\def\\#{#}\\catcode`\\#=6\n";
1741 if (contains(docdir, '%')) {
1742 docdir = subst(docdir, "%", "\\%");
1743 os << "\\catcode`\\%=11"
1744 "\\def\\%{%}\\catcode`\\%=14\n";
1746 os << "\\makeatletter\n"
1747 << "\\def\\input@path{{"
1748 << docdir << "/}}\n"
1749 << "\\makeatother\n";
1753 // get parent macros (if this buffer has a parent) which will be
1754 // written at the document begin further down.
1755 MacroSet parentMacros;
1756 listParentMacros(parentMacros, features);
1758 // Write the preamble
1759 runparams.use_babel = params().writeLaTeX(os, features,
1760 d->filename.onlyPath());
1762 // Japanese might be required only in some children of a document,
1763 // but once required, we must keep use_japanese true.
1764 runparams.use_japanese |= features.isRequired("japanese");
1767 // Restore the parenthood if needed
1768 if (!runparams.is_child)
1769 d->ignore_parent = false;
1774 os << "\\begin{document}\n";
1776 // output the parent macros
1777 MacroSet::iterator it = parentMacros.begin();
1778 MacroSet::iterator end = parentMacros.end();
1779 for (; it != end; ++it) {
1780 int num_lines = (*it)->write(os.os(), true);
1781 os.texrow().newlines(num_lines);
1784 } // output_preamble
1786 os.texrow().start(paragraphs().begin()->id(), 0);
1788 LYXERR(Debug::INFO, "preamble finished, now the body.");
1791 latexParagraphs(*this, text(), os, runparams);
1793 // Restore the parenthood if needed
1794 if (!runparams.is_child)
1795 d->ignore_parent = false;
1797 // add this just in case after all the paragraphs
1800 if (output_preamble) {
1801 os << "\\end{document}\n";
1802 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1804 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1806 runparams_in.encoding = runparams.encoding;
1808 // Just to be sure. (Asger)
1809 os.texrow().newline();
1811 //for (int i = 0; i<d->texrow.rows(); i++) {
1813 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1814 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1817 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1818 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1822 void Buffer::makeDocBookFile(FileName const & fname,
1823 OutputParams const & runparams,
1824 OutputWhat output) const
1826 LYXERR(Debug::LATEX, "makeDocBookFile...");
1829 if (!openFileWrite(ofs, fname))
1832 // make sure we are ready to export
1833 // this needs to be done before we validate
1835 updateMacroInstances(OutputUpdate);
1837 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1841 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1845 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1846 OutputParams const & runparams,
1847 OutputWhat output) const
1849 LaTeXFeatures features(*this, params(), runparams);
1854 DocumentClass const & tclass = params().documentClass();
1855 string const & top_element = tclass.latexname();
1857 bool const output_preamble =
1858 output == FullSource || output == OnlyPreamble;
1859 bool const output_body =
1860 output == FullSource || output == OnlyBody;
1862 if (output_preamble) {
1863 if (runparams.flavor == OutputParams::XML)
1864 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1867 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1870 if (! tclass.class_header().empty())
1871 os << from_ascii(tclass.class_header());
1872 else if (runparams.flavor == OutputParams::XML)
1873 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1874 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1876 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1878 docstring preamble = from_utf8(params().preamble);
1879 if (runparams.flavor != OutputParams::XML ) {
1880 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1881 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1882 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1883 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1886 string const name = runparams.nice
1887 ? changeExtension(absFileName(), ".sgml") : fname;
1888 preamble += features.getIncludedFiles(name);
1889 preamble += features.getLyXSGMLEntities();
1891 if (!preamble.empty()) {
1892 os << "\n [ " << preamble << " ]";
1898 string top = top_element;
1900 if (runparams.flavor == OutputParams::XML)
1901 top += params().language->code();
1903 top += params().language->code().substr(0, 2);
1906 if (!params().options.empty()) {
1908 top += params().options;
1911 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1912 << " file was created by LyX " << lyx_version
1913 << "\n See http://www.lyx.org/ for more information -->\n";
1915 params().documentClass().counters().reset();
1917 sgml::openTag(os, top);
1919 docbookParagraphs(text(), *this, os, runparams);
1920 sgml::closeTag(os, top_element);
1925 void Buffer::makeLyXHTMLFile(FileName const & fname,
1926 OutputParams const & runparams) const
1928 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1931 if (!openFileWrite(ofs, fname))
1934 // make sure we are ready to export
1935 // this has to be done before we validate
1936 updateBuffer(UpdateMaster, OutputUpdate);
1937 updateMacroInstances(OutputUpdate);
1939 writeLyXHTMLSource(ofs, runparams, FullSource);
1943 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1947 void Buffer::writeLyXHTMLSource(odocstream & os,
1948 OutputParams const & runparams,
1949 OutputWhat output) const
1951 LaTeXFeatures features(*this, params(), runparams);
1953 d->bibinfo_.makeCitationLabels(*this);
1955 bool const output_preamble =
1956 output == FullSource || output == OnlyPreamble;
1957 bool const output_body =
1958 output == FullSource || output == OnlyBody || output == IncludedFile;
1960 if (output_preamble) {
1961 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1962 << "<!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"
1963 // FIXME Language should be set properly.
1964 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1966 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1967 // FIXME Presumably need to set this right
1968 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1970 docstring const & doctitle = features.htmlTitle();
1972 << (doctitle.empty() ?
1973 from_ascii("LyX Document") :
1974 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1977 docstring styles = features.getTClassHTMLPreamble();
1978 if (!styles.empty())
1979 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1981 styles = from_utf8(features.getPreambleSnippets());
1982 if (!styles.empty())
1983 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1985 // we will collect CSS information in a stream, and then output it
1986 // either here, as part of the header, or else in a separate file.
1987 odocstringstream css;
1988 styles = from_utf8(features.getCSSSnippets());
1989 if (!styles.empty())
1990 css << "/* LyX Provided Styles */\n" << styles << '\n';
1992 styles = features.getTClassHTMLStyles();
1993 if (!styles.empty())
1994 css << "/* Layout-provided Styles */\n" << styles << '\n';
1996 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1997 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1998 if (needfg || needbg) {
1999 css << "\nbody {\n";
2002 << from_ascii(X11hexname(params().fontcolor))
2005 css << " background-color: "
2006 << from_ascii(X11hexname(params().backgroundcolor))
2011 docstring const dstyles = css.str();
2012 if (!dstyles.empty()) {
2013 bool written = false;
2014 if (params().html_css_as_file) {
2015 // open a file for CSS info
2017 string const fcssname = addName(temppath(), "docstyle.css");
2018 FileName const fcssfile = FileName(fcssname);
2019 if (openFileWrite(ocss, fcssfile)) {
2023 // write link to header
2024 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2026 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2029 // we are here if the CSS is supposed to be written to the header
2030 // or if we failed to write it to an external file.
2032 os << "<style type='text/css'>\n"
2041 bool const output_body_tag = (output != IncludedFile);
2042 if (output_body_tag)
2045 if (output != IncludedFile)
2046 // if we're an included file, the counters are in the master.
2047 params().documentClass().counters().reset();
2048 xhtmlParagraphs(text(), *this, xs, runparams);
2049 if (output_body_tag)
2053 if (output_preamble)
2058 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2059 // Other flags: -wall -v0 -x
2060 int Buffer::runChktex()
2064 // get LaTeX-Filename
2065 FileName const path(temppath());
2066 string const name = addName(path.absFileName(), latexName());
2067 string const org_path = filePath();
2069 PathChanger p(path); // path to LaTeX file
2070 message(_("Running chktex..."));
2072 // Generate the LaTeX file if neccessary
2073 OutputParams runparams(¶ms().encoding());
2074 runparams.flavor = OutputParams::LATEX;
2075 runparams.nice = false;
2076 runparams.linelen = lyxrc.plaintext_linelen;
2077 makeLaTeXFile(FileName(name), org_path, runparams);
2080 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2081 int const res = chktex.run(terr); // run chktex
2084 Alert::error(_("chktex failure"),
2085 _("Could not run chktex successfully."));
2087 ErrorList & errlist = d->errorLists["ChkTeX"];
2089 bufferErrors(terr, errlist);
2094 if (runparams.silent)
2095 d->errorLists["ChkTeX"].clear();
2103 void Buffer::validate(LaTeXFeatures & features) const
2105 // Validate the buffer params, but not for included
2106 // files, since they also use the parent buffer's
2108 if (!features.runparams().is_child)
2109 params().validate(features);
2111 for_each(paragraphs().begin(), paragraphs().end(),
2112 bind(&Paragraph::validate, _1, ref(features)));
2114 if (lyxerr.debugging(Debug::LATEX)) {
2115 features.showStruct();
2120 void Buffer::getLabelList(vector<docstring> & list) const
2122 // If this is a child document, use the master's list instead.
2124 masterBuffer()->getLabelList(list);
2129 Toc & toc = d->toc_backend.toc("label");
2130 TocIterator toc_it = toc.begin();
2131 TocIterator end = toc.end();
2132 for (; toc_it != end; ++toc_it) {
2133 if (toc_it->depth() == 0)
2134 list.push_back(toc_it->str());
2139 void Buffer::updateBibfilesCache(UpdateScope scope) const
2141 // FIXME This is probably unnecssary, given where we call this.
2142 // If this is a child document, use the parent's cache instead.
2143 if (parent() && scope != UpdateChildOnly) {
2144 masterBuffer()->updateBibfilesCache();
2148 d->bibfiles_cache_.clear();
2149 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2150 if (it->lyxCode() == BIBTEX_CODE) {
2151 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2152 support::FileNameList const bibfiles = inset.getBibFiles();
2153 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2156 } else if (it->lyxCode() == INCLUDE_CODE) {
2157 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2158 Buffer const * const incbuf = inset.getChildBuffer();
2161 support::FileNameList const & bibfiles =
2162 incbuf->getBibfilesCache(UpdateChildOnly);
2163 if (!bibfiles.empty()) {
2164 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2170 d->bibfile_cache_valid_ = true;
2171 d->bibinfo_cache_valid_ = false;
2172 d->cite_labels_valid_ = false;
2176 void Buffer::invalidateBibinfoCache() const
2178 d->bibinfo_cache_valid_ = false;
2179 d->cite_labels_valid_ = false;
2180 // also invalidate the cache for the parent buffer
2181 Buffer const * const pbuf = d->parent();
2183 pbuf->invalidateBibinfoCache();
2187 void Buffer::invalidateBibfileCache() const
2189 d->bibfile_cache_valid_ = false;
2190 d->bibinfo_cache_valid_ = false;
2191 d->cite_labels_valid_ = false;
2192 // also invalidate the cache for the parent buffer
2193 Buffer const * const pbuf = d->parent();
2195 pbuf->invalidateBibfileCache();
2199 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2201 // FIXME This is probably unnecessary, given where we call this.
2202 // If this is a child document, use the master's cache instead.
2203 Buffer const * const pbuf = masterBuffer();
2204 if (pbuf != this && scope != UpdateChildOnly)
2205 return pbuf->getBibfilesCache();
2207 if (!d->bibfile_cache_valid_)
2208 this->updateBibfilesCache(scope);
2210 return d->bibfiles_cache_;
2214 BiblioInfo const & Buffer::masterBibInfo() const
2216 Buffer const * const tmp = masterBuffer();
2218 return tmp->masterBibInfo();
2223 void Buffer::checkIfBibInfoCacheIsValid() const
2225 // use the master's cache
2226 Buffer const * const tmp = masterBuffer();
2228 tmp->checkIfBibInfoCacheIsValid();
2232 // compare the cached timestamps with the actual ones.
2233 FileNameList const & bibfiles_cache = getBibfilesCache();
2234 FileNameList::const_iterator ei = bibfiles_cache.begin();
2235 FileNameList::const_iterator en = bibfiles_cache.end();
2236 for (; ei != en; ++ ei) {
2237 time_t lastw = ei->lastModified();
2238 time_t prevw = d->bibfile_status_[*ei];
2239 if (lastw != prevw) {
2240 d->bibinfo_cache_valid_ = false;
2241 d->cite_labels_valid_ = false;
2242 d->bibfile_status_[*ei] = lastw;
2248 void Buffer::reloadBibInfoCache() const
2250 // use the master's cache
2251 Buffer const * const tmp = masterBuffer();
2253 tmp->reloadBibInfoCache();
2257 checkIfBibInfoCacheIsValid();
2258 if (d->bibinfo_cache_valid_)
2261 d->bibinfo_.clear();
2263 d->bibinfo_cache_valid_ = true;
2267 void Buffer::collectBibKeys() const
2269 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2270 it->collectBibKeys(it);
2274 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2276 Buffer const * tmp = masterBuffer();
2277 BiblioInfo & masterbi = (tmp == this) ?
2278 d->bibinfo_ : tmp->d->bibinfo_;
2279 masterbi.mergeBiblioInfo(bi);
2283 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2285 Buffer const * tmp = masterBuffer();
2286 BiblioInfo & masterbi = (tmp == this) ?
2287 d->bibinfo_ : tmp->d->bibinfo_;
2292 void Buffer::makeCitationLabels() const
2294 Buffer const * const master = masterBuffer();
2295 return d->bibinfo_.makeCitationLabels(*master);
2299 bool Buffer::citeLabelsValid() const
2301 return masterBuffer()->d->cite_labels_valid_;
2305 void Buffer::removeBiblioTempFiles() const
2307 // We remove files that contain LaTeX commands specific to the
2308 // particular bibliographic style being used, in order to avoid
2309 // LaTeX errors when we switch style.
2310 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2311 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2312 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2313 aux_file.removeFile();
2314 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2315 bbl_file.removeFile();
2316 // Also for the parent buffer
2317 Buffer const * const pbuf = parent();
2319 pbuf->removeBiblioTempFiles();
2323 bool Buffer::isDepClean(string const & name) const
2325 DepClean::const_iterator const it = d->dep_clean.find(name);
2326 if (it == d->dep_clean.end())
2332 void Buffer::markDepClean(string const & name)
2334 d->dep_clean[name] = true;
2338 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2341 // FIXME? if there is an Buffer LFUN that can be dispatched even
2342 // if internal, put a switch '(cmd.action)' here.
2348 switch (cmd.action()) {
2350 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2351 flag.setOnOff(isReadonly());
2354 // FIXME: There is need for a command-line import.
2355 //case LFUN_BUFFER_IMPORT:
2357 case LFUN_BUFFER_AUTO_SAVE:
2360 case LFUN_BUFFER_EXPORT_CUSTOM:
2361 // FIXME: Nothing to check here?
2364 case LFUN_BUFFER_EXPORT: {
2365 docstring const arg = cmd.argument();
2366 if (arg == "custom") {
2370 string format = to_utf8(arg);
2371 size_t pos = format.find(' ');
2372 if (pos != string::npos)
2373 format = format.substr(0, pos);
2374 enable = params().isExportable(format);
2376 flag.message(bformat(
2377 _("Don't know how to export to format: %1$s"), arg));
2381 case LFUN_BUFFER_CHKTEX:
2382 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2385 case LFUN_BUILD_PROGRAM:
2386 enable = params().isExportable("program");
2389 case LFUN_BRANCH_ACTIVATE:
2390 case LFUN_BRANCH_DEACTIVATE:
2391 case LFUN_BRANCH_MASTER_ACTIVATE:
2392 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2393 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2394 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2395 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2396 : params().branchlist();
2397 docstring const branchName = cmd.argument();
2398 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2402 case LFUN_BRANCH_ADD:
2403 case LFUN_BRANCHES_RENAME:
2404 case LFUN_BUFFER_PRINT:
2405 // if no Buffer is present, then of course we won't be called!
2408 case LFUN_BUFFER_LANGUAGE:
2409 enable = !isReadonly();
2415 flag.setEnabled(enable);
2420 void Buffer::dispatch(string const & command, DispatchResult & result)
2422 return dispatch(lyxaction.lookupFunc(command), result);
2426 // NOTE We can end up here even if we have no GUI, because we are called
2427 // by LyX::exec to handled command-line requests. So we may need to check
2428 // whether we have a GUI or not. The boolean use_gui holds this information.
2429 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2432 // FIXME? if there is an Buffer LFUN that can be dispatched even
2433 // if internal, put a switch '(cmd.action())' here.
2434 dr.dispatched(false);
2437 string const argument = to_utf8(func.argument());
2438 // We'll set this back to false if need be.
2439 bool dispatched = true;
2440 undo().beginUndoGroup();
2442 switch (func.action()) {
2443 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2444 if (lyxvc().inUse()) {
2445 string log = lyxvc().toggleReadOnly();
2450 setReadonly(!isReadonly());
2453 case LFUN_BUFFER_EXPORT: {
2454 ExportStatus const status = doExport(argument, false);
2455 dr.setError(status != ExportSuccess);
2456 if (status != ExportSuccess)
2457 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2462 case LFUN_BUILD_PROGRAM: {
2463 ExportStatus const status = doExport("program", true);
2464 dr.setError(status != ExportSuccess);
2465 if (status != ExportSuccess)
2466 dr.setMessage(_("Error generating literate programming code."));
2470 case LFUN_BUFFER_CHKTEX:
2474 case LFUN_BUFFER_EXPORT_CUSTOM: {
2476 string command = split(argument, format_name, ' ');
2477 Format const * format = formats.getFormat(format_name);
2479 lyxerr << "Format \"" << format_name
2480 << "\" not recognized!"
2485 // The name of the file created by the conversion process
2488 // Output to filename
2489 if (format->name() == "lyx") {
2490 string const latexname = latexName(false);
2491 filename = changeExtension(latexname,
2492 format->extension());
2493 filename = addName(temppath(), filename);
2495 if (!writeFile(FileName(filename)))
2499 doExport(format_name, true, filename);
2502 // Substitute $$FName for filename
2503 if (!contains(command, "$$FName"))
2504 command = "( " + command + " ) < $$FName";
2505 command = subst(command, "$$FName", filename);
2507 // Execute the command in the background
2509 call.startscript(Systemcall::DontWait, command, filePath());
2513 // FIXME: There is need for a command-line import.
2515 case LFUN_BUFFER_IMPORT:
2520 case LFUN_BUFFER_AUTO_SAVE:
2522 resetAutosaveTimers();
2525 case LFUN_BRANCH_ACTIVATE:
2526 case LFUN_BRANCH_DEACTIVATE:
2527 case LFUN_BRANCH_MASTER_ACTIVATE:
2528 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2529 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2530 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2531 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2534 docstring const branch_name = func.argument();
2535 // the case without a branch name is handled elsewhere
2536 if (branch_name.empty()) {
2540 Branch * branch = buf->params().branchlist().find(branch_name);
2542 LYXERR0("Branch " << branch_name << " does not exist.");
2544 docstring const msg =
2545 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2549 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2550 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2551 if (branch->isSelected() != activate) {
2552 buf->undo().recordUndoBufferParams(CursorData());
2553 branch->setSelected(activate);
2555 dr.screenUpdate(Update::Force);
2556 dr.forceBufferUpdate();
2561 case LFUN_BRANCH_ADD: {
2562 docstring branch_name = func.argument();
2563 if (branch_name.empty()) {
2567 BranchList & branch_list = params().branchlist();
2568 vector<docstring> const branches =
2569 getVectorFromString(branch_name, branch_list.separator());
2571 for (vector<docstring>::const_iterator it = branches.begin();
2572 it != branches.end(); ++it) {
2574 Branch * branch = branch_list.find(branch_name);
2576 LYXERR0("Branch " << branch_name << " already exists.");
2580 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2582 undo().recordUndoBufferParams(CursorData());
2583 branch_list.add(branch_name);
2584 branch = branch_list.find(branch_name);
2585 string const x11hexname = X11hexname(branch->color());
2586 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2587 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2589 dr.screenUpdate(Update::Force);
2597 case LFUN_BRANCHES_RENAME: {
2598 if (func.argument().empty())
2601 docstring const oldname = from_utf8(func.getArg(0));
2602 docstring const newname = from_utf8(func.getArg(1));
2603 InsetIterator it = inset_iterator_begin(inset());
2604 InsetIterator const end = inset_iterator_end(inset());
2605 bool success = false;
2606 for (; it != end; ++it) {
2607 if (it->lyxCode() == BRANCH_CODE) {
2608 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2609 if (ins.branch() == oldname) {
2610 undo().recordUndo(CursorData(it));
2611 ins.rename(newname);
2616 if (it->lyxCode() == INCLUDE_CODE) {
2617 // get buffer of external file
2618 InsetInclude const & ins =
2619 static_cast<InsetInclude const &>(*it);
2620 Buffer * child = ins.getChildBuffer();
2623 child->dispatch(func, dr);
2628 dr.screenUpdate(Update::Force);
2629 dr.forceBufferUpdate();
2634 case LFUN_BUFFER_PRINT: {
2635 // we'll assume there's a problem until we succeed
2637 string target = func.getArg(0);
2638 string target_name = func.getArg(1);
2639 string command = func.getArg(2);
2642 || target_name.empty()
2643 || command.empty()) {
2644 LYXERR0("Unable to parse " << func.argument());
2645 docstring const msg =
2646 bformat(_("Unable to parse \"%1$s\""), func.argument());
2650 if (target != "printer" && target != "file") {
2651 LYXERR0("Unrecognized target \"" << target << '"');
2652 docstring const msg =
2653 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2658 if (doExport("dvi", true) != ExportSuccess) {
2659 showPrintError(absFileName());
2660 dr.setMessage(_("Error exporting to DVI."));
2664 // Push directory path.
2665 string const path = temppath();
2666 // Prevent the compiler from optimizing away p
2670 // there are three cases here:
2671 // 1. we print to a file
2672 // 2. we print directly to a printer
2673 // 3. we print using a spool command (print to file first)
2676 string const dviname = changeExtension(latexName(true), "dvi");
2678 if (target == "printer") {
2679 if (!lyxrc.print_spool_command.empty()) {
2680 // case 3: print using a spool
2681 string const psname = changeExtension(dviname,".ps");
2682 command += ' ' + lyxrc.print_to_file
2685 + quoteName(dviname);
2687 string command2 = lyxrc.print_spool_command + ' ';
2688 if (target_name != "default") {
2689 command2 += lyxrc.print_spool_printerprefix
2693 command2 += quoteName(psname);
2695 // If successful, then spool command
2696 res = one.startscript(Systemcall::Wait, command,
2700 // If there's no GUI, we have to wait on this command. Otherwise,
2701 // LyX deletes the temporary directory, and with it the spooled
2702 // file, before it can be printed!!
2703 Systemcall::Starttype stype = use_gui ?
2704 Systemcall::DontWait : Systemcall::Wait;
2705 res = one.startscript(stype, command2,
2709 // case 2: print directly to a printer
2710 if (target_name != "default")
2711 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2713 Systemcall::Starttype stype = use_gui ?
2714 Systemcall::DontWait : Systemcall::Wait;
2715 res = one.startscript(stype, command +
2716 quoteName(dviname), filePath());
2720 // case 1: print to a file
2721 FileName const filename(makeAbsPath(target_name, filePath()));
2722 FileName const dvifile(makeAbsPath(dviname, path));
2723 if (filename.exists()) {
2724 docstring text = bformat(
2725 _("The file %1$s already exists.\n\n"
2726 "Do you want to overwrite that file?"),
2727 makeDisplayPath(filename.absFileName()));
2728 if (Alert::prompt(_("Overwrite file?"),
2729 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2732 command += ' ' + lyxrc.print_to_file
2733 + quoteName(filename.toFilesystemEncoding())
2735 + quoteName(dvifile.toFilesystemEncoding());
2737 Systemcall::Starttype stype = use_gui ?
2738 Systemcall::DontWait : Systemcall::Wait;
2739 res = one.startscript(stype, command, filePath());
2745 dr.setMessage(_("Error running external commands."));
2746 showPrintError(absFileName());
2755 dr.dispatched(dispatched);
2756 undo().endUndoGroup();
2760 void Buffer::changeLanguage(Language const * from, Language const * to)
2762 LASSERT(from, return);
2763 LASSERT(to, return);
2765 for_each(par_iterator_begin(),
2767 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2771 bool Buffer::isMultiLingual() const
2773 ParConstIterator end = par_iterator_end();
2774 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2775 if (it->isMultiLingual(params()))
2782 std::set<Language const *> Buffer::getLanguages() const
2784 std::set<Language const *> languages;
2785 getLanguages(languages);
2790 void Buffer::getLanguages(std::set<Language const *> & languages) const
2792 ParConstIterator end = par_iterator_end();
2793 // add the buffer language, even if it's not actively used
2794 languages.insert(language());
2795 // iterate over the paragraphs
2796 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2797 it->getLanguages(languages);
2799 ListOfBuffers clist = getDescendents();
2800 ListOfBuffers::const_iterator cit = clist.begin();
2801 ListOfBuffers::const_iterator const cen = clist.end();
2802 for (; cit != cen; ++cit)
2803 (*cit)->getLanguages(languages);
2807 DocIterator Buffer::getParFromID(int const id) const
2809 Buffer * buf = const_cast<Buffer *>(this);
2811 // John says this is called with id == -1 from undo
2812 lyxerr << "getParFromID(), id: " << id << endl;
2813 return doc_iterator_end(buf);
2816 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2817 if (it.paragraph().id() == id)
2820 return doc_iterator_end(buf);
2824 bool Buffer::hasParWithID(int const id) const
2826 return !getParFromID(id).atEnd();
2830 ParIterator Buffer::par_iterator_begin()
2832 return ParIterator(doc_iterator_begin(this));
2836 ParIterator Buffer::par_iterator_end()
2838 return ParIterator(doc_iterator_end(this));
2842 ParConstIterator Buffer::par_iterator_begin() const
2844 return ParConstIterator(doc_iterator_begin(this));
2848 ParConstIterator Buffer::par_iterator_end() const
2850 return ParConstIterator(doc_iterator_end(this));
2854 Language const * Buffer::language() const
2856 return params().language;
2860 docstring const Buffer::B_(string const & l10n) const
2862 return params().B_(l10n);
2866 bool Buffer::isClean() const
2868 return d->lyx_clean;
2872 bool Buffer::isExternallyModified(CheckMethod method) const
2874 LASSERT(d->filename.exists(), return false);
2875 // if method == timestamp, check timestamp before checksum
2876 return (method == checksum_method
2877 || d->timestamp_ != d->filename.lastModified())
2878 && d->checksum_ != d->filename.checksum();
2882 void Buffer::saveCheckSum() const
2884 FileName const & file = d->filename;
2887 if (file.exists()) {
2888 d->timestamp_ = file.lastModified();
2889 d->checksum_ = file.checksum();
2891 // in the case of save to a new file.
2898 void Buffer::markClean() const
2900 if (!d->lyx_clean) {
2901 d->lyx_clean = true;
2904 // if the .lyx file has been saved, we don't need an
2906 d->bak_clean = true;
2907 d->undo_.markDirty();
2911 void Buffer::setUnnamed(bool flag)
2917 bool Buffer::isUnnamed() const
2924 /// Don't check unnamed, here: isInternal() is used in
2925 /// newBuffer(), where the unnamed flag has not been set by anyone
2926 /// yet. Also, for an internal buffer, there should be no need for
2927 /// retrieving fileName() nor for checking if it is unnamed or not.
2928 bool Buffer::isInternal() const
2930 return d->internal_buffer;
2934 void Buffer::setInternal(bool flag)
2936 d->internal_buffer = flag;
2940 void Buffer::markDirty()
2943 d->lyx_clean = false;
2946 d->bak_clean = false;
2948 DepClean::iterator it = d->dep_clean.begin();
2949 DepClean::const_iterator const end = d->dep_clean.end();
2951 for (; it != end; ++it)
2956 FileName Buffer::fileName() const
2962 string Buffer::absFileName() const
2964 return d->filename.absFileName();
2968 string Buffer::filePath() const
2970 string const abs = d->filename.onlyPath().absFileName();
2973 int last = abs.length() - 1;
2975 return abs[last] == '/' ? abs : abs + '/';
2979 bool Buffer::isReadonly() const
2981 return d->read_only;
2985 void Buffer::setParent(Buffer const * buffer)
2987 // Avoids recursive include.
2988 d->setParent(buffer == this ? 0 : buffer);
2993 Buffer const * Buffer::parent() const
2999 ListOfBuffers Buffer::allRelatives() const
3001 ListOfBuffers lb = masterBuffer()->getDescendents();
3002 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3007 Buffer const * Buffer::masterBuffer() const
3009 // FIXME Should be make sure we are not in some kind
3010 // of recursive include? A -> B -> A will crash this.
3011 Buffer const * const pbuf = d->parent();
3015 return pbuf->masterBuffer();
3019 bool Buffer::isChild(Buffer * child) const
3021 return d->children_positions.find(child) != d->children_positions.end();
3025 DocIterator Buffer::firstChildPosition(Buffer const * child)
3027 Impl::BufferPositionMap::iterator it;
3028 it = d->children_positions.find(child);
3029 if (it == d->children_positions.end())
3030 return DocIterator(this);
3035 bool Buffer::hasChildren() const
3037 return !d->children_positions.empty();
3041 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3043 // loop over children
3044 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3045 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3046 for (; it != end; ++it) {
3047 Buffer * child = const_cast<Buffer *>(it->first);
3049 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3050 if (bit != clist.end())
3052 clist.push_back(child);
3054 // there might be grandchildren
3055 child->collectChildren(clist, true);
3060 ListOfBuffers Buffer::getChildren() const
3063 collectChildren(v, false);
3064 // Make sure we have not included ourselves.
3065 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3066 if (bit != v.end()) {
3067 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3074 ListOfBuffers Buffer::getDescendents() const
3077 collectChildren(v, true);
3078 // Make sure we have not included ourselves.
3079 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3080 if (bit != v.end()) {
3081 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3088 template<typename M>
3089 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3094 typename M::const_iterator it = m.lower_bound(x);
3095 if (it == m.begin())
3103 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3104 DocIterator const & pos) const
3106 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3108 // if paragraphs have no macro context set, pos will be empty
3112 // we haven't found anything yet
3113 DocIterator bestPos = owner_->par_iterator_begin();
3114 MacroData const * bestData = 0;
3116 // find macro definitions for name
3117 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3118 if (nameIt != macros.end()) {
3119 // find last definition in front of pos or at pos itself
3120 PositionScopeMacroMap::const_iterator it
3121 = greatest_below(nameIt->second, pos);
3122 if (it != nameIt->second.end()) {
3124 // scope ends behind pos?
3125 if (pos < it->second.first) {
3126 // Looks good, remember this. If there
3127 // is no external macro behind this,
3128 // we found the right one already.
3129 bestPos = it->first;
3130 bestData = &it->second.second;
3134 // try previous macro if there is one
3135 if (it == nameIt->second.begin())
3142 // find macros in included files
3143 PositionScopeBufferMap::const_iterator it
3144 = greatest_below(position_to_children, pos);
3145 if (it == position_to_children.end())
3146 // no children before
3150 // do we know something better (i.e. later) already?
3151 if (it->first < bestPos )
3154 // scope ends behind pos?
3155 if (pos < it->second.first
3156 && (cloned_buffer_ ||
3157 theBufferList().isLoaded(it->second.second))) {
3158 // look for macro in external file
3160 MacroData const * data
3161 = it->second.second->getMacro(name, false);
3164 bestPos = it->first;
3170 // try previous file if there is one
3171 if (it == position_to_children.begin())
3176 // return the best macro we have found
3181 MacroData const * Buffer::getMacro(docstring const & name,
3182 DocIterator const & pos, bool global) const
3187 // query buffer macros
3188 MacroData const * data = d->getBufferMacro(name, pos);
3192 // If there is a master buffer, query that
3193 Buffer const * const pbuf = d->parent();
3195 d->macro_lock = true;
3196 MacroData const * macro = pbuf->getMacro(
3197 name, *this, false);
3198 d->macro_lock = false;
3204 data = MacroTable::globalMacros().get(name);
3213 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3215 // set scope end behind the last paragraph
3216 DocIterator scope = par_iterator_begin();
3217 scope.pit() = scope.lastpit() + 1;
3219 return getMacro(name, scope, global);
3223 MacroData const * Buffer::getMacro(docstring const & name,
3224 Buffer const & child, bool global) const
3226 // look where the child buffer is included first
3227 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3228 if (it == d->children_positions.end())
3231 // check for macros at the inclusion position
3232 return getMacro(name, it->second, global);
3236 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3238 pit_type const lastpit = it.lastpit();
3240 // look for macros in each paragraph
3241 while (it.pit() <= lastpit) {
3242 Paragraph & par = it.paragraph();
3244 // iterate over the insets of the current paragraph
3245 InsetList const & insets = par.insetList();
3246 InsetList::const_iterator iit = insets.begin();
3247 InsetList::const_iterator end = insets.end();
3248 for (; iit != end; ++iit) {
3249 it.pos() = iit->pos;
3251 // is it a nested text inset?
3252 if (iit->inset->asInsetText()) {
3253 // Inset needs its own scope?
3254 InsetText const * itext = iit->inset->asInsetText();
3255 bool newScope = itext->isMacroScope();
3257 // scope which ends just behind the inset
3258 DocIterator insetScope = it;
3261 // collect macros in inset
3262 it.push_back(CursorSlice(*iit->inset));
3263 updateMacros(it, newScope ? insetScope : scope);
3268 if (iit->inset->asInsetTabular()) {
3269 CursorSlice slice(*iit->inset);
3270 size_t const numcells = slice.nargs();
3271 for (; slice.idx() < numcells; slice.forwardIdx()) {
3272 it.push_back(slice);
3273 updateMacros(it, scope);
3279 // is it an external file?
3280 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3281 // get buffer of external file
3282 InsetInclude const & inset =
3283 static_cast<InsetInclude const &>(*iit->inset);
3285 Buffer * child = inset.getChildBuffer();
3290 // register its position, but only when it is
3291 // included first in the buffer
3292 if (children_positions.find(child) ==
3293 children_positions.end())
3294 children_positions[child] = it;
3296 // register child with its scope
3297 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3301 InsetMath * im = iit->inset->asInsetMath();
3302 if (doing_export && im) {
3303 InsetMathHull * hull = im->asHullInset();
3305 hull->recordLocation(it);
3308 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3312 MathMacroTemplate & macroTemplate =
3313 *iit->inset->asInsetMath()->asMacroTemplate();
3314 MacroContext mc(owner_, it);
3315 macroTemplate.updateToContext(mc);
3318 bool valid = macroTemplate.validMacro();
3319 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3320 // then the BufferView's cursor will be invalid in
3321 // some cases which leads to crashes.
3326 // FIXME (Abdel), I don't understandt why we pass 'it' here
3327 // instead of 'macroTemplate' defined above... is this correct?
3328 macros[macroTemplate.name()][it] =
3329 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3339 void Buffer::updateMacros() const
3344 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3346 // start with empty table
3348 d->children_positions.clear();
3349 d->position_to_children.clear();
3351 // Iterate over buffer, starting with first paragraph
3352 // The scope must be bigger than any lookup DocIterator
3353 // later. For the global lookup, lastpit+1 is used, hence
3354 // we use lastpit+2 here.
3355 DocIterator it = par_iterator_begin();
3356 DocIterator outerScope = it;
3357 outerScope.pit() = outerScope.lastpit() + 2;
3358 d->updateMacros(it, outerScope);
3362 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3364 InsetIterator it = inset_iterator_begin(inset());
3365 InsetIterator const end = inset_iterator_end(inset());
3366 for (; it != end; ++it) {
3367 if (it->lyxCode() == BRANCH_CODE) {
3368 InsetBranch & br = static_cast<InsetBranch &>(*it);
3369 docstring const name = br.branch();
3370 if (!from_master && !params().branchlist().find(name))
3371 result.push_back(name);
3372 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3373 result.push_back(name);
3376 if (it->lyxCode() == INCLUDE_CODE) {
3377 // get buffer of external file
3378 InsetInclude const & ins =
3379 static_cast<InsetInclude const &>(*it);
3380 Buffer * child = ins.getChildBuffer();
3383 child->getUsedBranches(result, true);
3386 // remove duplicates
3391 void Buffer::updateMacroInstances(UpdateType utype) const
3393 LYXERR(Debug::MACROS, "updateMacroInstances for "
3394 << d->filename.onlyFileName());
3395 DocIterator it = doc_iterator_begin(this);
3397 DocIterator const end = doc_iterator_end(this);
3398 for (; it != end; it.forwardInset()) {
3399 // look for MathData cells in InsetMathNest insets
3400 InsetMath * minset = it.nextInset()->asInsetMath();
3404 // update macro in all cells of the InsetMathNest
3405 DocIterator::idx_type n = minset->nargs();
3406 MacroContext mc = MacroContext(this, it);
3407 for (DocIterator::idx_type i = 0; i < n; ++i) {
3408 MathData & data = minset->cell(i);
3409 data.updateMacros(0, mc, utype);
3415 void Buffer::listMacroNames(MacroNameSet & macros) const
3420 d->macro_lock = true;
3422 // loop over macro names
3423 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3424 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3425 for (; nameIt != nameEnd; ++nameIt)
3426 macros.insert(nameIt->first);
3428 // loop over children
3429 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3430 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3431 for (; it != end; ++it)
3432 it->first->listMacroNames(macros);
3435 Buffer const * const pbuf = d->parent();
3437 pbuf->listMacroNames(macros);
3439 d->macro_lock = false;
3443 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3445 Buffer const * const pbuf = d->parent();
3450 pbuf->listMacroNames(names);
3453 MacroNameSet::iterator it = names.begin();
3454 MacroNameSet::iterator end = names.end();
3455 for (; it != end; ++it) {
3457 MacroData const * data =
3458 pbuf->getMacro(*it, *this, false);
3460 macros.insert(data);
3462 // we cannot access the original MathMacroTemplate anymore
3463 // here to calls validate method. So we do its work here manually.
3464 // FIXME: somehow make the template accessible here.
3465 if (data->optionals() > 0)
3466 features.require("xargs");
3472 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3475 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3477 RefCache::iterator it = d->ref_cache_.find(label);
3478 if (it != d->ref_cache_.end())
3479 return it->second.second;
3481 static InsetLabel const * dummy_il = 0;
3482 static References const dummy_refs;
3483 it = d->ref_cache_.insert(
3484 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3485 return it->second.second;
3489 Buffer::References const & Buffer::references(docstring const & label) const
3491 return const_cast<Buffer *>(this)->getReferenceCache(label);
3495 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3497 References & refs = getReferenceCache(label);
3498 refs.push_back(make_pair(inset, it));
3502 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3504 masterBuffer()->d->ref_cache_[label].first = il;
3508 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3510 return masterBuffer()->d->ref_cache_[label].first;
3514 void Buffer::clearReferenceCache() const
3517 d->ref_cache_.clear();
3521 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3523 //FIXME: This does not work for child documents yet.
3524 reloadBibInfoCache();
3526 // Check if the label 'from' appears more than once
3527 BiblioInfo const & keys = masterBibInfo();
3528 BiblioInfo::const_iterator bit = keys.begin();
3529 BiblioInfo::const_iterator bend = keys.end();
3530 vector<docstring> labels;
3532 for (; bit != bend; ++bit)
3534 labels.push_back(bit->first);
3536 if (count(labels.begin(), labels.end(), from) > 1)
3539 string const paramName = "key";
3540 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3541 if (it->lyxCode() != CITE_CODE)
3543 InsetCommand * inset = it->asInsetCommand();
3544 docstring const oldValue = inset->getParam(paramName);
3545 if (oldValue == from)
3546 inset->setParam(paramName, to);
3551 void Buffer::getSourceCode(odocstream & os, string const & format,
3552 pit_type par_begin, pit_type par_end,
3553 OutputWhat output, bool master) const
3555 OutputParams runparams(¶ms().encoding());
3556 runparams.nice = true;
3557 runparams.flavor = params().getOutputFlavor(format);
3558 runparams.linelen = lyxrc.plaintext_linelen;
3559 // No side effect of file copying and image conversion
3560 runparams.dryrun = true;
3562 if (output == CurrentParagraph) {
3563 runparams.par_begin = par_begin;
3564 runparams.par_end = par_end;
3565 if (par_begin + 1 == par_end) {
3567 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3571 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3572 convert<docstring>(par_begin),
3573 convert<docstring>(par_end - 1))
3576 // output paragraphs
3577 if (runparams.flavor == OutputParams::LYX) {
3578 Paragraph const & par = text().paragraphs()[par_begin];
3580 depth_type dt = par.getDepth();
3581 par.write(ods, params(), dt);
3582 os << from_utf8(ods.str());
3583 } else if (runparams.flavor == OutputParams::HTML) {
3585 setMathFlavor(runparams);
3586 xhtmlParagraphs(text(), *this, xs, runparams);
3587 } else if (runparams.flavor == OutputParams::TEXT) {
3589 // FIXME Handles only one paragraph, unlike the others.
3590 // Probably should have some routine with a signature like them.
3591 writePlaintextParagraph(*this,
3592 text().paragraphs()[par_begin], os, runparams, dummy);
3593 } else if (params().isDocBook()) {
3594 docbookParagraphs(text(), *this, os, runparams);
3596 // If we are previewing a paragraph, even if this is the
3597 // child of some other buffer, let's cut the link here,
3598 // so that no concurring settings from the master
3599 // (e.g. branch state) interfere (see #8101).
3601 d->ignore_parent = true;
3602 // We need to validate the Buffer params' features here
3603 // in order to know if we should output polyglossia
3604 // macros (instead of babel macros)
3605 LaTeXFeatures features(*this, params(), runparams);
3606 params().validate(features);
3607 runparams.use_polyglossia = features.usePolyglossia();
3612 // latex or literate
3613 otexstream ots(os, texrow);
3616 latexParagraphs(*this, text(), ots, runparams);
3618 // Restore the parenthood
3620 d->ignore_parent = false;
3624 if (output == FullSource)
3625 os << _("Preview source code");
3626 else if (output == OnlyPreamble)
3627 os << _("Preview preamble");
3628 else if (output == OnlyBody)
3629 os << _("Preview body");
3631 if (runparams.flavor == OutputParams::LYX) {
3633 if (output == FullSource)
3635 else if (output == OnlyPreamble)
3636 params().writeFile(ods);
3637 else if (output == OnlyBody)
3639 os << from_utf8(ods.str());
3640 } else if (runparams.flavor == OutputParams::HTML) {
3641 writeLyXHTMLSource(os, runparams, output);
3642 } else if (runparams.flavor == OutputParams::TEXT) {
3643 if (output == OnlyPreamble) {
3644 os << "% "<< _("Plain text does not have a preamble.");
3646 writePlaintextFile(*this, os, runparams);
3647 } else if (params().isDocBook()) {
3648 writeDocBookSource(os, absFileName(), runparams, output);
3650 // latex or literate
3652 d->texrow.newline();
3653 d->texrow.newline();
3654 otexstream ots(os, d->texrow);
3656 runparams.is_child = true;
3657 writeLaTeXSource(ots, string(), runparams, output);
3663 ErrorList & Buffer::errorList(string const & type) const
3665 return d->errorLists[type];
3669 void Buffer::updateTocItem(std::string const & type,
3670 DocIterator const & dit) const
3673 d->gui_->updateTocItem(type, dit);
3677 void Buffer::structureChanged() const
3680 d->gui_->structureChanged();
3684 void Buffer::errors(string const & err, bool from_master) const
3687 d->gui_->errors(err, from_master);
3691 void Buffer::message(docstring const & msg) const
3694 d->gui_->message(msg);
3698 void Buffer::setBusy(bool on) const
3701 d->gui_->setBusy(on);
3705 void Buffer::updateTitles() const
3708 d->wa_->updateTitles();
3712 void Buffer::resetAutosaveTimers() const
3715 d->gui_->resetAutosaveTimers();
3719 bool Buffer::hasGuiDelegate() const
3725 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3734 class AutoSaveBuffer : public ForkedProcess {
3737 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3738 : buffer_(buffer), fname_(fname) {}
3740 virtual shared_ptr<ForkedProcess> clone() const
3742 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3747 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3748 from_utf8(fname_.absFileName())));
3749 return run(DontWait);
3753 virtual int generateChild();
3755 Buffer const & buffer_;
3760 int AutoSaveBuffer::generateChild()
3762 #if defined(__APPLE__)
3763 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3764 * We should use something else like threads.
3766 * Since I do not know how to determine at run time what is the OS X
3767 * version, I just disable forking altogether for now (JMarc)
3769 pid_t const pid = -1;
3771 // tmp_ret will be located (usually) in /tmp
3772 // will that be a problem?
3773 // Note that this calls ForkedCalls::fork(), so it's
3774 // ok cross-platform.
3775 pid_t const pid = fork();
3776 // If you want to debug the autosave
3777 // you should set pid to -1, and comment out the fork.
3778 if (pid != 0 && pid != -1)
3782 // pid = -1 signifies that lyx was unable
3783 // to fork. But we will do the save
3785 bool failed = false;
3786 TempFile tempfile("lyxautoXXXXXX.lyx");
3787 tempfile.setAutoRemove(false);
3788 FileName const tmp_ret = tempfile.name();
3789 if (!tmp_ret.empty()) {
3790 if (!buffer_.writeFile(tmp_ret))
3792 else if (!tmp_ret.moveTo(fname_))
3798 // failed to write/rename tmp_ret so try writing direct
3799 if (!buffer_.writeFile(fname_)) {
3800 // It is dangerous to do this in the child,
3801 // but safe in the parent, so...
3802 if (pid == -1) // emit message signal.
3803 buffer_.message(_("Autosave failed!"));
3807 if (pid == 0) // we are the child so...
3816 FileName Buffer::getEmergencyFileName() const
3818 return FileName(d->filename.absFileName() + ".emergency");
3822 FileName Buffer::getAutosaveFileName() const
3824 // if the document is unnamed try to save in the backup dir, else
3825 // in the default document path, and as a last try in the filePath,
3826 // which will most often be the temporary directory
3829 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3830 : lyxrc.backupdir_path;
3831 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3834 string const fname = "#" + d->filename.onlyFileName() + "#";
3836 return makeAbsPath(fname, fpath);
3840 void Buffer::removeAutosaveFile() const
3842 FileName const f = getAutosaveFileName();
3848 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3850 FileName const newauto = getAutosaveFileName();
3852 if (newauto != oldauto && oldauto.exists())
3853 if (!oldauto.moveTo(newauto))
3854 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3858 bool Buffer::autoSave() const
3860 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3861 if (buf->d->bak_clean || isReadonly())
3864 message(_("Autosaving current document..."));
3865 buf->d->bak_clean = true;
3867 FileName const fname = getAutosaveFileName();
3868 LASSERT(d->cloned_buffer_, return false);
3870 // If this buffer is cloned, we assume that
3871 // we are running in a separate thread already.
3872 TempFile tempfile("lyxautoXXXXXX.lyx");
3873 tempfile.setAutoRemove(false);
3874 FileName const tmp_ret = tempfile.name();
3875 if (!tmp_ret.empty()) {
3877 // assume successful write of tmp_ret
3878 if (tmp_ret.moveTo(fname))
3881 // failed to write/rename tmp_ret so try writing direct
3882 return writeFile(fname);
3886 void Buffer::setExportStatus(bool e) const
3888 d->doing_export = e;
3889 ListOfBuffers clist = getDescendents();
3890 ListOfBuffers::const_iterator cit = clist.begin();
3891 ListOfBuffers::const_iterator const cen = clist.end();
3892 for (; cit != cen; ++cit)
3893 (*cit)->d->doing_export = e;
3897 bool Buffer::isExporting() const
3899 return d->doing_export;
3903 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3907 return doExport(target, put_in_tempdir, result_file);
3910 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3911 string & result_file) const
3913 bool const update_unincluded =
3914 params().maintain_unincluded_children
3915 && !params().getIncludedChildren().empty();
3917 // (1) export with all included children (omit \includeonly)
3918 if (update_unincluded) {
3919 ExportStatus const status =
3920 doExport(target, put_in_tempdir, true, result_file);
3921 if (status != ExportSuccess)
3924 // (2) export with included children only
3925 return doExport(target, put_in_tempdir, false, result_file);
3929 void Buffer::setMathFlavor(OutputParams & op) const
3931 switch (params().html_math_output) {
3932 case BufferParams::MathML:
3933 op.math_flavor = OutputParams::MathAsMathML;
3935 case BufferParams::HTML:
3936 op.math_flavor = OutputParams::MathAsHTML;
3938 case BufferParams::Images:
3939 op.math_flavor = OutputParams::MathAsImages;
3941 case BufferParams::LaTeX:
3942 op.math_flavor = OutputParams::MathAsLaTeX;
3948 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3949 bool includeall, string & result_file) const
3951 LYXERR(Debug::FILES, "target=" << target);
3952 OutputParams runparams(¶ms().encoding());
3953 string format = target;
3954 string dest_filename;
3955 size_t pos = target.find(' ');
3956 if (pos != string::npos) {
3957 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3958 format = target.substr(0, pos);
3959 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3960 FileName(dest_filename).onlyPath().createPath();
3961 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3963 MarkAsExporting exporting(this);
3964 string backend_format;
3965 runparams.flavor = OutputParams::LATEX;
3966 runparams.linelen = lyxrc.plaintext_linelen;
3967 runparams.includeall = includeall;
3968 vector<string> backs = params().backends();
3969 Converters converters = theConverters();
3970 bool need_nice_file = false;
3971 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3972 // Get shortest path to format
3973 converters.buildGraph();
3974 Graph::EdgePath path;
3975 for (vector<string>::const_iterator it = backs.begin();
3976 it != backs.end(); ++it) {
3977 Graph::EdgePath p = converters.getPath(*it, format);
3978 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3979 backend_format = *it;
3984 if (!put_in_tempdir) {
3985 // Only show this alert if this is an export to a non-temporary
3986 // file (not for previewing).
3987 Alert::error(_("Couldn't export file"), bformat(
3988 _("No information for exporting the format %1$s."),
3989 formats.prettyName(format)));
3991 return ExportNoPathToFormat;
3993 runparams.flavor = converters.getFlavor(path, this);
3994 Graph::EdgePath::const_iterator it = path.begin();
3995 Graph::EdgePath::const_iterator en = path.end();
3996 for (; it != en; ++it)
3997 if (theConverters().get(*it).nice()) {
3998 need_nice_file = true;
4003 backend_format = format;
4004 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4005 // FIXME: Don't hardcode format names here, but use a flag
4006 if (backend_format == "pdflatex")
4007 runparams.flavor = OutputParams::PDFLATEX;
4008 else if (backend_format == "luatex")
4009 runparams.flavor = OutputParams::LUATEX;
4010 else if (backend_format == "dviluatex")
4011 runparams.flavor = OutputParams::DVILUATEX;
4012 else if (backend_format == "xetex")
4013 runparams.flavor = OutputParams::XETEX;
4016 string filename = latexName(false);
4017 filename = addName(temppath(), filename);
4018 filename = changeExtension(filename,
4019 formats.extension(backend_format));
4020 LYXERR(Debug::FILES, "filename=" << filename);
4022 // Plain text backend
4023 if (backend_format == "text") {
4024 runparams.flavor = OutputParams::TEXT;
4025 writePlaintextFile(*this, FileName(filename), runparams);
4028 else if (backend_format == "xhtml") {
4029 runparams.flavor = OutputParams::HTML;
4030 setMathFlavor(runparams);
4031 makeLyXHTMLFile(FileName(filename), runparams);
4032 } else if (backend_format == "lyx")
4033 writeFile(FileName(filename));
4035 else if (params().isDocBook()) {
4036 runparams.nice = !put_in_tempdir;
4037 makeDocBookFile(FileName(filename), runparams);
4040 else if (backend_format == format || need_nice_file) {
4041 runparams.nice = true;
4042 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4043 if (d->cloned_buffer_)
4044 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4047 } else if (!lyxrc.tex_allows_spaces
4048 && contains(filePath(), ' ')) {
4049 Alert::error(_("File name error"),
4050 _("The directory path to the document cannot contain spaces."));
4051 return ExportTexPathHasSpaces;
4053 runparams.nice = false;
4054 bool const success = makeLaTeXFile(
4055 FileName(filename), filePath(), runparams);
4056 if (d->cloned_buffer_)
4057 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4062 string const error_type = (format == "program")
4063 ? "Build" : params().bufferFormat();
4064 ErrorList & error_list = d->errorLists[error_type];
4065 string const ext = formats.extension(format);
4066 FileName const tmp_result_file(changeExtension(filename, ext));
4067 bool const success = converters.convert(this, FileName(filename),
4068 tmp_result_file, FileName(absFileName()), backend_format, format,
4071 // Emit the signal to show the error list or copy it back to the
4072 // cloned Buffer so that it can be emitted afterwards.
4073 if (format != backend_format) {
4074 if (runparams.silent)
4076 else if (d->cloned_buffer_)
4077 d->cloned_buffer_->d->errorLists[error_type] =
4078 d->errorLists[error_type];
4081 // also to the children, in case of master-buffer-view
4082 ListOfBuffers clist = getDescendents();
4083 ListOfBuffers::const_iterator cit = clist.begin();
4084 ListOfBuffers::const_iterator const cen = clist.end();
4085 for (; cit != cen; ++cit) {
4086 if (runparams.silent)
4087 (*cit)->d->errorLists[error_type].clear();
4088 else if (d->cloned_buffer_) {
4089 // Enable reverse search by copying back the
4090 // texrow object to the cloned buffer.
4091 // FIXME: this is not thread safe.
4092 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4093 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4094 (*cit)->d->errorLists[error_type];
4096 (*cit)->errors(error_type, true);
4100 if (d->cloned_buffer_) {
4101 // Enable reverse dvi or pdf to work by copying back the texrow
4102 // object to the cloned buffer.
4103 // FIXME: There is a possibility of concurrent access to texrow
4104 // here from the main GUI thread that should be securized.
4105 d->cloned_buffer_->d->texrow = d->texrow;
4106 string const error_type = params().bufferFormat();
4107 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4111 return ExportConverterError;
4113 if (put_in_tempdir) {
4114 result_file = tmp_result_file.absFileName();
4115 return ExportSuccess;
4118 if (dest_filename.empty())
4119 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4121 result_file = dest_filename;
4122 // We need to copy referenced files (e. g. included graphics
4123 // if format == "dvi") to the result dir.
4124 vector<ExportedFile> const files =
4125 runparams.exportdata->externalFiles(format);
4126 string const dest = runparams.export_folder.empty() ?
4127 onlyPath(result_file) : runparams.export_folder;
4128 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4129 : force_overwrite == ALL_FILES;
4130 CopyStatus status = use_force ? FORCE : SUCCESS;
4132 vector<ExportedFile>::const_iterator it = files.begin();
4133 vector<ExportedFile>::const_iterator const en = files.end();
4134 for (; it != en && status != CANCEL; ++it) {
4135 string const fmt = formats.getFormatFromFile(it->sourceName);
4136 string fixedName = it->exportName;
4137 if (!runparams.export_folder.empty()) {
4138 // Relative pathnames starting with ../ will be sanitized
4139 // if exporting to a different folder
4140 while (fixedName.substr(0, 3) == "../")
4141 fixedName = fixedName.substr(3, fixedName.length() - 3);
4143 FileName fixedFileName = makeAbsPath(fixedName, dest);
4144 fixedFileName.onlyPath().createPath();
4145 status = copyFile(fmt, it->sourceName,
4147 it->exportName, status == FORCE,
4148 runparams.export_folder.empty());
4151 if (status == CANCEL) {
4152 message(_("Document export cancelled."));
4153 return ExportCancel;
4156 if (tmp_result_file.exists()) {
4157 // Finally copy the main file
4158 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4159 : force_overwrite != NO_FILES;
4160 if (status == SUCCESS && use_force)
4162 status = copyFile(format, tmp_result_file,
4163 FileName(result_file), result_file,
4165 if (status == CANCEL) {
4166 message(_("Document export cancelled."));
4167 return ExportCancel;
4169 message(bformat(_("Document exported as %1$s "
4171 formats.prettyName(format),
4172 makeDisplayPath(result_file)));
4175 // This must be a dummy converter like fax (bug 1888)
4176 message(bformat(_("Document exported as %1$s"),
4177 formats.prettyName(format)));
4180 return ExportSuccess;
4184 Buffer::ExportStatus Buffer::preview(string const & format) const
4186 bool const update_unincluded =
4187 params().maintain_unincluded_children
4188 && !params().getIncludedChildren().empty();
4189 return preview(format, update_unincluded);
4193 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4195 MarkAsExporting exporting(this);
4197 // (1) export with all included children (omit \includeonly)
4199 ExportStatus const status = doExport(format, true, true, result_file);
4200 if (status != ExportSuccess)
4203 // (2) export with included children only
4204 ExportStatus const status = doExport(format, true, false, result_file);
4205 if (status != ExportSuccess)
4207 if (!formats.view(*this, FileName(result_file), format))
4208 return PreviewError;
4209 return PreviewSuccess;
4213 Buffer::ReadStatus Buffer::extractFromVC()
4215 bool const found = LyXVC::file_not_found_hook(d->filename);
4217 return ReadFileNotFound;
4218 if (!d->filename.isReadableFile())
4224 Buffer::ReadStatus Buffer::loadEmergency()
4226 FileName const emergencyFile = getEmergencyFileName();
4227 if (!emergencyFile.exists()
4228 || emergencyFile.lastModified() <= d->filename.lastModified())
4229 return ReadFileNotFound;
4231 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4232 docstring const text = bformat(_("An emergency save of the document "
4233 "%1$s exists.\n\nRecover emergency save?"), file);
4235 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4236 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4242 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4243 bool const success = (ret_llf == ReadSuccess);
4246 Alert::warning(_("File is read-only"),
4247 bformat(_("An emergency file is successfully loaded, "
4248 "but the original file %1$s is marked read-only. "
4249 "Please make sure to save the document as a different "
4250 "file."), from_utf8(d->filename.absFileName())));
4253 lyxvc().file_found_hook(d->filename);
4254 str = _("Document was successfully recovered.");
4256 str = _("Document was NOT successfully recovered.");
4257 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4258 makeDisplayPath(emergencyFile.absFileName()));
4260 int const del_emerg =
4261 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4262 _("&Remove"), _("&Keep"));
4263 if (del_emerg == 0) {
4264 emergencyFile.removeFile();
4266 Alert::warning(_("Emergency file deleted"),
4267 _("Do not forget to save your file now!"), true);
4269 return success ? ReadSuccess : ReadEmergencyFailure;
4272 int const del_emerg =
4273 Alert::prompt(_("Delete emergency file?"),
4274 _("Remove emergency file now?"), 1, 1,
4275 _("&Remove"), _("&Keep"));
4277 emergencyFile.removeFile();
4278 return ReadOriginal;
4288 Buffer::ReadStatus Buffer::loadAutosave()
4290 // Now check if autosave file is newer.
4291 FileName const autosaveFile = getAutosaveFileName();
4292 if (!autosaveFile.exists()
4293 || autosaveFile.lastModified() <= d->filename.lastModified())
4294 return ReadFileNotFound;
4296 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4297 docstring const text = bformat(_("The backup of the document %1$s "
4298 "is newer.\n\nLoad the backup instead?"), file);
4299 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4300 _("&Load backup"), _("Load &original"), _("&Cancel"));
4305 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4306 // the file is not saved if we load the autosave file.
4307 if (ret_llf == ReadSuccess) {
4309 Alert::warning(_("File is read-only"),
4310 bformat(_("A backup file is successfully loaded, "
4311 "but the original file %1$s is marked read-only. "
4312 "Please make sure to save the document as a "
4314 from_utf8(d->filename.absFileName())));
4317 lyxvc().file_found_hook(d->filename);
4320 return ReadAutosaveFailure;
4323 // Here we delete the autosave
4324 autosaveFile.removeFile();
4325 return ReadOriginal;
4333 Buffer::ReadStatus Buffer::loadLyXFile()
4335 if (!d->filename.isReadableFile()) {
4336 ReadStatus const ret_rvc = extractFromVC();
4337 if (ret_rvc != ReadSuccess)
4341 ReadStatus const ret_re = loadEmergency();
4342 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4345 ReadStatus const ret_ra = loadAutosave();
4346 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4349 return loadThisLyXFile(d->filename);
4353 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4355 return readFile(fn);
4359 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4361 TeXErrors::Errors::const_iterator it = terr.begin();
4362 TeXErrors::Errors::const_iterator end = terr.end();
4363 ListOfBuffers clist = getDescendents();
4364 ListOfBuffers::const_iterator cen = clist.end();
4366 for (; it != end; ++it) {
4369 int errorRow = it->error_in_line;
4370 Buffer const * buf = 0;
4372 if (it->child_name.empty())
4373 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4375 // The error occurred in a child
4376 ListOfBuffers::const_iterator cit = clist.begin();
4377 for (; cit != cen; ++cit) {
4378 string const child_name =
4379 DocFileName(changeExtension(
4380 (*cit)->absFileName(), "tex")).
4382 if (it->child_name != child_name)
4384 (*cit)->d->texrow.getIdFromRow(errorRow,
4385 id_start, pos_start);
4386 if (id_start != -1) {
4387 buf = d->cloned_buffer_
4388 ? (*cit)->d->cloned_buffer_->d->owner_
4389 : (*cit)->d->owner_;
4400 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4401 } while (found && id_start == id_end && pos_start == pos_end);
4403 if (id_start != id_end) {
4404 // Next registered position is outside the inset where
4405 // the error occurred, so signal end-of-paragraph
4409 errorList.push_back(ErrorItem(it->error_desc,
4410 it->error_text, id_start, pos_start, pos_end, buf));
4415 void Buffer::setBuffersForInsets() const
4417 inset().setBuffer(const_cast<Buffer &>(*this));
4421 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4423 LBUFERR(!text().paragraphs().empty());
4425 // Use the master text class also for child documents
4426 Buffer const * const master = masterBuffer();
4427 DocumentClass const & textclass = master->params().documentClass();
4429 // do this only if we are the top-level Buffer
4430 if (master == this) {
4431 textclass.counters().reset(from_ascii("bibitem"));
4432 reloadBibInfoCache();
4435 // keep the buffers to be children in this set. If the call from the
4436 // master comes back we can see which of them were actually seen (i.e.
4437 // via an InsetInclude). The remaining ones in the set need still be updated.
4438 static std::set<Buffer const *> bufToUpdate;
4439 if (scope == UpdateMaster) {
4440 // If this is a child document start with the master
4441 if (master != this) {
4442 bufToUpdate.insert(this);
4443 master->updateBuffer(UpdateMaster, utype);
4444 // If the master buffer has no gui associated with it, then the TocModel is
4445 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4446 // (bug 5699). The same happens if the master buffer is open in a different
4447 // window. This test catches both possibilities.
4448 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4449 // There remains a problem here: If there is another child open in yet a third
4450 // window, that TOC is not updated. So some more general solution is needed at
4452 if (master->d->gui_ != d->gui_)
4455 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4456 if (bufToUpdate.find(this) == bufToUpdate.end())
4460 // start over the counters in the master
4461 textclass.counters().reset();
4464 // update will be done below for this buffer
4465 bufToUpdate.erase(this);
4467 // update all caches
4468 clearReferenceCache();
4471 Buffer & cbuf = const_cast<Buffer &>(*this);
4474 ParIterator parit = cbuf.par_iterator_begin();
4475 updateBuffer(parit, utype);
4478 // TocBackend update will be done later.
4481 d->bibinfo_cache_valid_ = true;
4482 d->cite_labels_valid_ = true;
4483 cbuf.tocBackend().update(utype == OutputUpdate);
4484 if (scope == UpdateMaster)
4485 cbuf.structureChanged();
4489 static depth_type getDepth(DocIterator const & it)
4491 depth_type depth = 0;
4492 for (size_t i = 0 ; i < it.depth() ; ++i)
4493 if (!it[i].inset().inMathed())
4494 depth += it[i].paragraph().getDepth() + 1;
4495 // remove 1 since the outer inset does not count
4499 static depth_type getItemDepth(ParIterator const & it)
4501 Paragraph const & par = *it;
4502 LabelType const labeltype = par.layout().labeltype;
4504 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4507 // this will hold the lowest depth encountered up to now.
4508 depth_type min_depth = getDepth(it);
4509 ParIterator prev_it = it;
4512 --prev_it.top().pit();
4514 // start of nested inset: go to outer par
4516 if (prev_it.empty()) {
4517 // start of document: nothing to do
4522 // We search for the first paragraph with same label
4523 // that is not more deeply nested.
4524 Paragraph & prev_par = *prev_it;
4525 depth_type const prev_depth = getDepth(prev_it);
4526 if (labeltype == prev_par.layout().labeltype) {
4527 if (prev_depth < min_depth)
4528 return prev_par.itemdepth + 1;
4529 if (prev_depth == min_depth)
4530 return prev_par.itemdepth;
4532 min_depth = min(min_depth, prev_depth);
4533 // small optimization: if we are at depth 0, we won't
4534 // find anything else
4535 if (prev_depth == 0)
4541 static bool needEnumCounterReset(ParIterator const & it)
4543 Paragraph const & par = *it;
4544 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4545 depth_type const cur_depth = par.getDepth();
4546 ParIterator prev_it = it;
4547 while (prev_it.pit()) {
4548 --prev_it.top().pit();
4549 Paragraph const & prev_par = *prev_it;
4550 if (prev_par.getDepth() <= cur_depth)
4551 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4553 // start of nested inset: reset
4558 // set the label of a paragraph. This includes the counters.
4559 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4561 BufferParams const & bp = owner_->masterBuffer()->params();
4562 DocumentClass const & textclass = bp.documentClass();
4563 Paragraph & par = it.paragraph();
4564 Layout const & layout = par.layout();
4565 Counters & counters = textclass.counters();
4567 if (par.params().startOfAppendix()) {
4568 // We want to reset the counter corresponding to toplevel sectioning
4569 Layout const & lay = textclass.getTOCLayout();
4570 docstring const cnt = lay.counter;
4572 counters.reset(cnt);
4573 counters.appendix(true);
4575 par.params().appendix(counters.appendix());
4577 // Compute the item depth of the paragraph
4578 par.itemdepth = getItemDepth(it);
4580 if (layout.margintype == MARGIN_MANUAL) {
4581 if (par.params().labelWidthString().empty())
4582 par.params().labelWidthString(par.expandLabel(layout, bp));
4583 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4584 // we do not need to do anything here, since the empty case is
4585 // handled during export.
4587 par.params().labelWidthString(docstring());
4590 switch(layout.labeltype) {
4591 case LABEL_ITEMIZE: {
4592 // At some point of time we should do something more
4593 // clever here, like:
4594 // par.params().labelString(
4595 // bp.user_defined_bullet(par.itemdepth).getText());
4596 // for now, use a simple hardcoded label
4597 docstring itemlabel;
4598 switch (par.itemdepth) {
4600 itemlabel = char_type(0x2022);
4603 itemlabel = char_type(0x2013);
4606 itemlabel = char_type(0x2217);
4609 itemlabel = char_type(0x2219); // or 0x00b7
4612 par.params().labelString(itemlabel);
4616 case LABEL_ENUMERATE: {
4617 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4619 switch (par.itemdepth) {
4628 enumcounter += "iv";
4631 // not a valid enumdepth...
4635 // Maybe we have to reset the enumeration counter.
4636 if (needEnumCounterReset(it))
4637 counters.reset(enumcounter);
4638 counters.step(enumcounter, utype);
4640 string const & lang = par.getParLanguage(bp)->code();
4641 par.params().labelString(counters.theCounter(enumcounter, lang));
4646 case LABEL_SENSITIVE: {
4647 string const & type = counters.current_float();
4648 docstring full_label;
4650 full_label = owner_->B_("Senseless!!! ");
4652 docstring name = owner_->B_(textclass.floats().getType(type).name());
4653 if (counters.hasCounter(from_utf8(type))) {
4654 string const & lang = par.getParLanguage(bp)->code();
4655 counters.step(from_utf8(type), utype);
4656 full_label = bformat(from_ascii("%1$s %2$s:"),
4658 counters.theCounter(from_utf8(type), lang));
4660 full_label = bformat(from_ascii("%1$s #:"), name);
4662 par.params().labelString(full_label);
4666 case LABEL_NO_LABEL:
4667 par.params().labelString(docstring());
4671 case LABEL_CENTERED:
4672 case LABEL_STATIC: {
4673 docstring const & lcounter = layout.counter;
4674 if (!lcounter.empty()) {
4675 if (layout.toclevel <= bp.secnumdepth
4676 && (layout.latextype != LATEX_ENVIRONMENT
4677 || it.text()->isFirstInSequence(it.pit()))) {
4678 if (counters.hasCounter(lcounter))
4679 counters.step(lcounter, utype);
4680 par.params().labelString(par.expandLabel(layout, bp));
4682 par.params().labelString(docstring());
4684 par.params().labelString(par.expandLabel(layout, bp));
4690 par.params().labelString(par.expandLabel(layout, bp));
4695 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4697 // LASSERT: Is it safe to continue here, or should we just return?
4698 LASSERT(parit.pit() == 0, /**/);
4700 // Set the position of the text in the buffer to be able
4701 // to resolve macros in it.
4702 parit.text()->setMacrocontextPosition(parit);
4704 depth_type maxdepth = 0;
4705 pit_type const lastpit = parit.lastpit();
4706 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4707 // reduce depth if necessary
4708 if (parit->params().depth() > maxdepth) {
4709 /** FIXME: this function is const, but
4710 * nevertheless it modifies the buffer. To be
4711 * cleaner, one should modify the buffer in
4712 * another function, which is actually
4713 * non-const. This would however be costly in
4714 * terms of code duplication.
4716 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4717 parit->params().depth(maxdepth);
4719 maxdepth = parit->getMaxDepthAfter();
4721 if (utype == OutputUpdate) {
4722 // track the active counters
4723 // we have to do this for the master buffer, since the local
4724 // buffer isn't tracking anything.
4725 masterBuffer()->params().documentClass().counters().
4726 setActiveLayout(parit->layout());
4729 // set the counter for this paragraph
4730 d->setLabel(parit, utype);
4733 InsetList::const_iterator iit = parit->insetList().begin();
4734 InsetList::const_iterator end = parit->insetList().end();
4735 for (; iit != end; ++iit) {
4736 parit.pos() = iit->pos;
4737 iit->inset->updateBuffer(parit, utype);
4743 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4744 WordLangTuple & word_lang, docstring_list & suggestions) const
4748 suggestions.clear();
4749 word_lang = WordLangTuple();
4750 bool const to_end = to.empty();
4751 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4752 // OK, we start from here.
4753 for (; from != end; from.forwardPos()) {
4754 // We are only interested in text so remove the math CursorSlice.
4755 while (from.inMathed()) {
4759 // If from is at the end of the document (which is possible
4760 // when leaving the mathed) LyX will crash later otherwise.
4761 if (from.atEnd() || (!to_end && from >= end))
4764 from.paragraph().spellCheck();
4765 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4766 if (SpellChecker::misspelled(res)) {
4771 // Do not increase progress when from == to, otherwise the word
4772 // count will be wrong.
4782 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4784 bool inword = false;
4789 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4790 if (!dit.inTexted()) {
4795 Paragraph const & par = dit.paragraph();
4796 pos_type const pos = dit.pos();
4798 // Copied and adapted from isWordSeparator() in Paragraph
4799 if (pos == dit.lastpos()) {
4802 Inset const * ins = par.getInset(pos);
4803 if (ins && skipNoOutput && !ins->producesOutput()) {
4806 // stop if end of range was skipped
4807 if (!to.atEnd() && dit >= to)
4810 } else if (!par.isDeleted(pos)) {
4811 if (par.isWordSeparator(pos))
4817 if (ins && ins->isLetter())
4819 else if (ins && ins->isSpace())
4822 char_type const c = par.getChar(pos);
4823 if (isPrintableNonspace(c))
4825 else if (isSpace(c))
4835 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4837 d->updateStatistics(from, to, skipNoOutput);
4841 int Buffer::wordCount() const
4843 return d->wordCount();
4847 int Buffer::charCount(bool with_blanks) const
4849 return d->charCount(with_blanks);
4853 Buffer::ReadStatus Buffer::reload()
4856 // c.f. bug http://www.lyx.org/trac/ticket/6587
4857 removeAutosaveFile();
4858 // e.g., read-only status could have changed due to version control
4859 d->filename.refresh();
4860 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4862 // clear parent. this will get reset if need be.
4864 ReadStatus const status = loadLyXFile();
4865 if (status == ReadSuccess) {
4870 message(bformat(_("Document %1$s reloaded."), disp_fn));
4873 message(bformat(_("Could not reload document %1$s."), disp_fn));
4883 bool Buffer::saveAs(FileName const & fn)
4885 FileName const old_name = fileName();
4886 FileName const old_auto = getAutosaveFileName();
4887 bool const old_unnamed = isUnnamed();
4894 // bring the autosave file with us, just in case.
4895 moveAutosaveFile(old_auto);
4896 // validate version control data and
4897 // correct buffer title
4898 lyxvc().file_found_hook(fileName());
4900 // the file has now been saved to the new location.
4901 // we need to check that the locations of child buffers
4903 checkChildBuffers();
4904 checkMasterBuffer();
4908 // reset the old filename and unnamed state
4909 setFileName(old_name);
4910 setUnnamed(old_unnamed);
4916 // FIXME We could do better here, but it is complicated. What would be
4917 // nice is to offer either (a) to save the child buffer to an appropriate
4918 // location, so that it would "move with the master", or else (b) to update
4919 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4920 // complicated, because the code for this lives in GuiView.
4921 void Buffer::checkChildBuffers()
4923 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4924 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4925 for (; it != en; ++it) {
4926 DocIterator dit = it->second;
4927 Buffer * cbuf = const_cast<Buffer *>(it->first);
4928 if (!cbuf || !theBufferList().isLoaded(cbuf))
4930 Inset * inset = dit.nextInset();
4931 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4932 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4933 docstring const & incfile = inset_inc->getParam("filename");
4934 string oldloc = cbuf->absFileName();
4935 string newloc = makeAbsPath(to_utf8(incfile),
4936 onlyPath(absFileName())).absFileName();
4937 if (oldloc == newloc)
4939 // the location of the child file is incorrect.
4940 Alert::warning(_("Included File Invalid"),
4941 bformat(_("Saving this document to a new location has made the file:\n"
4943 "inaccessible. You will need to update the included filename."),
4944 from_utf8(oldloc)));
4946 inset_inc->setChildBuffer(0);
4948 // invalidate cache of children
4949 d->children_positions.clear();
4950 d->position_to_children.clear();
4954 // If a child has been saved under a different name/path, it might have been
4955 // orphaned. Therefore the master needs to be reset (bug 8161).
4956 void Buffer::checkMasterBuffer()
4958 Buffer const * const master = masterBuffer();
4962 // necessary to re-register the child (bug 5873)
4963 // FIXME: clean up updateMacros (here, only
4964 // child registering is needed).
4965 master->updateMacros();
4966 // (re)set master as master buffer, but only
4967 // if we are a real child
4968 if (master->isChild(this))