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 "DispatchResult.h"
29 #include "DocIterator.h"
31 #include "ErrorList.h"
34 #include "FuncRequest.h"
35 #include "FuncStatus.h"
36 #include "IndicesList.h"
37 #include "InsetIterator.h"
38 #include "InsetList.h"
40 #include "LaTeXFeatures.h"
44 #include "LyXAction.h"
48 #include "output_docbook.h"
50 #include "output_latex.h"
51 #include "output_xhtml.h"
52 #include "output_plaintext.h"
53 #include "Paragraph.h"
54 #include "ParagraphParameters.h"
55 #include "ParIterator.h"
56 #include "PDFOptions.h"
57 #include "SpellChecker.h"
60 #include "TexStream.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/os.h"
101 #include "support/Package.h"
102 #include "support/Path.h"
103 #include "support/Systemcall.h"
104 #include "support/textutils.h"
105 #include "support/types.h"
107 #include "support/bind.h"
108 #include "support/shared_ptr.h"
120 using namespace lyx::support;
121 using namespace lyx::graphics;
125 namespace Alert = frontend::Alert;
126 namespace os = support::os;
130 int const LYX_FORMAT = LYX_FORMAT_LYX;
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135 void showPrintError(string const & name)
137 docstring str = bformat(_("Could not print the document %1$s.\n"
138 "Check that your printer is set up correctly."),
139 makeDisplayPath(name, 50));
140 Alert::error(_("Print document failed"), str);
146 // A storehouse for the cloned buffers.
147 list<CloneList *> cloned_buffers;
153 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
157 delete preview_loader_;
165 /// search for macro in local (buffer) table or in children
166 MacroData const * getBufferMacro(docstring const & name,
167 DocIterator const & pos) const;
169 /// Update macro table starting with position of it \param it in some
171 void updateMacros(DocIterator & it, DocIterator & scope);
173 void setLabel(ParIterator & it, UpdateType utype) const;
175 /** If we have branches that use the file suffix
176 feature, return the file name with suffix appended.
178 support::FileName exportFileName() const;
185 mutable TexRow texrow;
187 /// need to regenerate .tex?
191 mutable bool lyx_clean;
193 /// is autosave needed?
194 mutable bool bak_clean;
196 /// is this an unnamed file (New...)?
199 /// is this an internal bufffer?
200 bool internal_buffer;
205 /// name of the file the buffer is associated with.
208 /** Set to true only when the file is fully loaded.
209 * Used to prevent the premature generation of previews
210 * and by the citation inset.
212 bool file_fully_loaded;
214 /// Ignore the parent (e.g. when exporting a child standalone)?
218 mutable TocBackend toc_backend;
221 typedef pair<DocIterator, MacroData> ScopeMacro;
222 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
223 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
224 /// map from the macro name to the position map,
225 /// which maps the macro definition position to the scope and the MacroData.
226 NamePositionScopeMacroMap macros;
227 /// This seem to change the way Buffer::getMacro() works
228 mutable bool macro_lock;
230 /// positions of child buffers in the buffer
231 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
232 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
233 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
234 /// position of children buffers in this buffer
235 BufferPositionMap children_positions;
236 /// map from children inclusion positions to their scope and their buffer
237 PositionScopeBufferMap position_to_children;
239 /// Container for all sort of Buffer dependant errors.
240 map<string, ErrorList> errorLists;
242 /// timestamp and checksum used to test if the file has been externally
243 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
245 unsigned long checksum_;
248 frontend::WorkAreaManager * wa_;
250 frontend::GuiBufferDelegate * gui_;
255 /// A cache for the bibfiles (including bibfiles of loaded child
256 /// documents), needed for appropriate update of natbib labels.
257 mutable support::FileNameList bibfiles_cache_;
259 // FIXME The caching mechanism could be improved. At present, we have a
260 // cache for each Buffer, that caches all the bibliography info for that
261 // Buffer. A more efficient solution would be to have a global cache per
262 // file, and then to construct the Buffer's bibinfo from that.
263 /// A cache for bibliography info
264 mutable BiblioInfo bibinfo_;
265 /// whether the bibinfo cache is valid
266 mutable bool bibinfo_cache_valid_;
267 /// whether the bibfile cache is valid
268 mutable bool bibfile_cache_valid_;
269 /// Cache of timestamps of .bib files
270 map<FileName, time_t> bibfile_status_;
271 /// Indicates whether the bibinfo has changed since the last time
272 /// we ran updateBuffer(), i.e., whether citation labels may need
274 mutable bool cite_labels_valid_;
276 mutable RefCache ref_cache_;
278 /// our Text that should be wrapped in an InsetText
282 PreviewLoader * preview_loader_;
284 /// This is here to force the test to be done whenever parent_buffer
286 Buffer const * parent() const {
287 // ignore_parent temporarily "orphans" a buffer
288 // (e.g. if a child is compiled standalone)
291 // if parent_buffer is not loaded, then it has been unloaded,
292 // which means that parent_buffer is an invalid pointer. So we
293 // set it to null in that case.
294 // however, the BufferList doesn't know about cloned buffers, so
295 // they will always be regarded as unloaded. in that case, we hope
297 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
299 return parent_buffer;
303 void setParent(Buffer const * pb) {
304 if (parent_buffer == pb)
307 if (!cloned_buffer_ && parent_buffer && pb)
308 LYXERR0("Warning: a buffer should not have two parents!");
310 if (!cloned_buffer_ && parent_buffer) {
311 parent_buffer->invalidateBibfileCache();
312 parent_buffer->invalidateBibinfoCache();
316 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
317 /// This one is useful for preview detached in a thread.
318 Buffer const * cloned_buffer_;
320 CloneList * clone_list_;
321 /// are we in the process of exporting this buffer?
322 mutable bool doing_export;
324 /// compute statistics
325 /// \p from initial position
326 /// \p to points to the end position
327 void updateStatistics(DocIterator & from, DocIterator & to,
328 bool skipNoOutput = true);
329 /// statistics accessor functions
330 int wordCount() const { return word_count_; }
331 int charCount(bool with_blanks) const {
333 + (with_blanks ? blank_count_ : 0);
337 /// So we can force access via the accessors.
338 mutable Buffer const * parent_buffer;
347 /// Creates the per buffer temporary directory
348 static FileName createBufferTmpDir()
351 // We are in our own directory. Why bother to mangle name?
352 // In fact I wrote this code to circumvent a problematic behaviour
353 // (bug?) of EMX mkstemp().
354 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
355 convert<string>(count++));
357 if (!tmpfl.createDirectory(0777)) {
358 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
359 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
360 from_utf8(tmpfl.absFileName())));
366 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
367 Buffer const * cloned_buffer)
368 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
369 internal_buffer(false), read_only(readonly_), filename(file),
370 file_fully_loaded(false), ignore_parent(false), toc_backend(owner),
371 macro_lock(false), timestamp_(0), checksum_(0), wa_(0), gui_(0),
372 undo_(*owner), bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
373 cite_labels_valid_(false), preview_loader_(0),
374 cloned_buffer_(cloned_buffer), clone_list_(0),
375 doing_export(false), parent_buffer(0)
377 if (!cloned_buffer_) {
378 temppath = createBufferTmpDir();
379 lyxvc.setBuffer(owner_);
381 wa_ = new frontend::WorkAreaManager;
384 temppath = cloned_buffer_->d->temppath;
385 file_fully_loaded = true;
386 params = cloned_buffer_->d->params;
387 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
388 bibinfo_ = cloned_buffer_->d->bibinfo_;
389 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
390 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
391 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
392 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
393 unnamed = cloned_buffer_->d->unnamed;
394 internal_buffer = cloned_buffer_->d->internal_buffer;
398 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
399 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
401 LYXERR(Debug::INFO, "Buffer::Buffer()");
403 d->inset = new InsetText(*cloned_buffer->d->inset);
404 d->inset->setBuffer(*this);
405 // FIXME: optimize this loop somewhat, maybe by creating a new
406 // general recursive Inset::setId().
407 DocIterator it = doc_iterator_begin(this);
408 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
409 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
410 it.paragraph().setId(cloned_it.paragraph().id());
412 d->inset = new InsetText(this);
413 d->inset->setAutoBreakRows(true);
414 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
420 LYXERR(Debug::INFO, "Buffer::~Buffer()");
421 // here the buffer should take care that it is
422 // saved properly, before it goes into the void.
424 // GuiView already destroyed
428 // No need to do additional cleanups for internal buffer.
434 // this is in case of recursive includes: we won't try to delete
435 // ourselves as a child.
436 d->clone_list_->erase(this);
437 // loop over children
438 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
439 Impl::BufferPositionMap::iterator end = d->children_positions.end();
440 for (; it != end; ++it) {
441 Buffer * child = const_cast<Buffer *>(it->first);
442 if (d->clone_list_->erase(child))
445 // if we're the master buffer, then we should get rid of the list
448 // if this is not empty, we have leaked something. worse, one of the
449 // children still has a reference to this list.
450 LASSERT(d->clone_list_->empty(), /* */);
451 list<CloneList *>::iterator it =
452 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
453 LASSERT(it != cloned_buffers.end(), /* */);
454 cloned_buffers.erase(it);
455 delete d->clone_list_;
457 // FIXME Do we really need to do this right before we delete d?
458 // clear references to children in macro tables
459 d->children_positions.clear();
460 d->position_to_children.clear();
462 // loop over children
463 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
464 Impl::BufferPositionMap::iterator end = d->children_positions.end();
465 for (; it != end; ++it) {
466 Buffer * child = const_cast<Buffer *>(it->first);
467 if (theBufferList().isLoaded(child))
468 theBufferList().releaseChild(this, child);
472 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
473 msg += emergencyWrite();
474 Alert::warning(_("Attempting to close changed document!"), msg);
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 if (!d->temppath.destroyDirectory()) {
483 Alert::warning(_("Could not remove temporary directory"),
484 bformat(_("Could not remove the temporary directory %1$s"),
485 from_utf8(d->temppath.absFileName())));
494 Buffer * Buffer::cloneFromMaster() const
497 cloned_buffers.push_back(new CloneList());
498 CloneList * clones = cloned_buffers.back();
500 masterBuffer()->cloneWithChildren(bufmap, clones);
502 // make sure we got cloned
503 BufferMap::const_iterator bit = bufmap.find(this);
504 LASSERT(bit != bufmap.end(), return 0);
505 Buffer * cloned_buffer = bit->second;
507 return cloned_buffer;
511 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
513 // have we already been cloned?
514 if (bufmap.find(this) != bufmap.end())
517 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
518 bufmap[this] = buffer_clone;
519 clones->insert(buffer_clone);
520 buffer_clone->d->clone_list_ = clones;
521 buffer_clone->d->macro_lock = true;
522 buffer_clone->d->children_positions.clear();
523 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
524 // math macro caches need to be rethought and simplified.
525 // I am not sure wether we should handle Buffer cloning here or in BufferList.
526 // Right now BufferList knows nothing about buffer clones.
527 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
528 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
529 for (; it != end; ++it) {
530 DocIterator dit = it->first.clone(buffer_clone);
531 dit.setBuffer(buffer_clone);
532 Buffer * child = const_cast<Buffer *>(it->second.second);
534 child->cloneWithChildren(bufmap, clones);
535 BufferMap::iterator const bit = bufmap.find(child);
536 LASSERT(bit != bufmap.end(), continue);
537 Buffer * child_clone = bit->second;
539 Inset * inset = dit.nextInset();
540 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
541 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
542 inset_inc->setChildBuffer(child_clone);
543 child_clone->d->setParent(buffer_clone);
544 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
545 buffer_clone->setChild(dit, child_clone);
547 buffer_clone->d->macro_lock = false;
552 Buffer * Buffer::cloneBufferOnly() const {
553 cloned_buffers.push_back(new CloneList());
554 CloneList * clones = cloned_buffers.back();
555 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
556 clones->insert(buffer_clone);
557 buffer_clone->d->clone_list_ = clones;
558 // we won't be cloning the children
559 buffer_clone->d->children_positions.clear();
564 bool Buffer::isClone() const
566 return d->cloned_buffer_;
570 void Buffer::changed(bool update_metrics) const
573 d->wa_->redrawAll(update_metrics);
577 frontend::WorkAreaManager & Buffer::workAreaManager() const
579 LASSERT(d->wa_, /**/);
584 Text & Buffer::text() const
586 return d->inset->text();
590 Inset & Buffer::inset() const
596 BufferParams & Buffer::params()
602 BufferParams const & Buffer::params() const
608 ParagraphList & Buffer::paragraphs()
610 return text().paragraphs();
614 ParagraphList const & Buffer::paragraphs() const
616 return text().paragraphs();
620 LyXVC & Buffer::lyxvc()
626 LyXVC const & Buffer::lyxvc() const
632 string const Buffer::temppath() const
634 return d->temppath.absFileName();
638 TexRow & Buffer::texrow()
644 TexRow const & Buffer::texrow() const
650 TocBackend & Buffer::tocBackend() const
652 return d->toc_backend;
656 Undo & Buffer::undo()
662 void Buffer::setChild(DocIterator const & dit, Buffer * child)
664 d->children_positions[child] = dit;
668 string Buffer::latexName(bool const no_path) const
670 FileName latex_name =
671 makeLatexName(d->exportFileName());
672 return no_path ? latex_name.onlyFileName()
673 : latex_name.absFileName();
677 FileName Buffer::Impl::exportFileName() const
679 docstring const branch_suffix =
680 params.branchlist().getFileNameSuffix();
681 if (branch_suffix.empty())
684 string const name = filename.onlyFileNameWithoutExt()
685 + to_utf8(branch_suffix);
686 FileName res(filename.onlyPath().absFileName() + "/" + name);
687 res.changeExtension(filename.extension());
693 string Buffer::logName(LogType * type) const
695 string const filename = latexName(false);
697 if (filename.empty()) {
703 string const path = temppath();
705 FileName const fname(addName(temppath(),
706 onlyFileName(changeExtension(filename,
709 // FIXME: how do we know this is the name of the build log?
710 FileName const bname(
711 addName(path, onlyFileName(
712 changeExtension(filename,
713 formats.extension(params().bufferFormat()) + ".out"))));
715 // Also consider the master buffer log file
716 FileName masterfname = fname;
718 if (masterBuffer() != this) {
719 string const mlogfile = masterBuffer()->logName(&mtype);
720 masterfname = FileName(mlogfile);
723 // If no Latex log or Build log is newer, show Build log
724 if (bname.exists() &&
725 ((!fname.exists() && !masterfname.exists())
726 || (fname.lastModified() < bname.lastModified()
727 && masterfname.lastModified() < bname.lastModified()))) {
728 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
731 return bname.absFileName();
732 // If we have a newer master file log or only a master log, show this
733 } else if (fname != masterfname
734 && (!fname.exists() && (masterfname.exists()
735 || fname.lastModified() < masterfname.lastModified()))) {
736 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
739 return masterfname.absFileName();
741 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
744 return fname.absFileName();
748 void Buffer::setReadonly(bool const flag)
750 if (d->read_only != flag) {
757 void Buffer::setFileName(FileName const & fname)
760 setReadonly(d->filename.isReadOnly());
766 int Buffer::readHeader(Lexer & lex)
768 int unknown_tokens = 0;
770 int begin_header_line = -1;
772 // Initialize parameters that may be/go lacking in header:
773 params().branchlist().clear();
774 params().preamble.erase();
775 params().options.erase();
776 params().master.erase();
777 params().float_placement.erase();
778 params().paperwidth.erase();
779 params().paperheight.erase();
780 params().leftmargin.erase();
781 params().rightmargin.erase();
782 params().topmargin.erase();
783 params().bottommargin.erase();
784 params().headheight.erase();
785 params().headsep.erase();
786 params().footskip.erase();
787 params().columnsep.erase();
788 params().fonts_cjk.erase();
789 params().listings_params.clear();
790 params().clearLayoutModules();
791 params().clearRemovedModules();
792 params().clearIncludedChildren();
793 params().pdfoptions().clear();
794 params().indiceslist().clear();
795 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
796 params().isbackgroundcolor = false;
797 params().fontcolor = RGBColor(0, 0, 0);
798 params().isfontcolor = false;
799 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
800 params().boxbgcolor = RGBColor(0xFF, 0, 0);
801 params().html_latex_start.clear();
802 params().html_latex_end.clear();
803 params().html_math_img_scale = 1.0;
804 params().output_sync_macro.erase();
805 params().local_layout.clear();
807 for (int i = 0; i < 4; ++i) {
808 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
809 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
812 ErrorList & errorList = d->errorLists["Parse"];
821 if (token == "\\end_header")
825 if (token == "\\begin_header") {
826 begin_header_line = line;
830 LYXERR(Debug::PARSER, "Handling document header token: `"
833 string unknown = params().readToken(lex, token, d->filename.onlyPath());
834 if (!unknown.empty()) {
835 if (unknown[0] != '\\' && token == "\\textclass") {
836 Alert::warning(_("Unknown document class"),
837 bformat(_("Using the default document class, because the "
838 "class %1$s is unknown."), from_utf8(unknown)));
841 docstring const s = bformat(_("Unknown token: "
845 errorList.push_back(ErrorItem(_("Document header error"),
850 if (begin_header_line) {
851 docstring const s = _("\\begin_header is missing");
852 errorList.push_back(ErrorItem(_("Document header error"),
856 params().makeDocumentClass();
858 return unknown_tokens;
863 // changed to be public and have one parameter
864 // Returns true if "\end_document" is not read (Asger)
865 bool Buffer::readDocument(Lexer & lex)
867 ErrorList & errorList = d->errorLists["Parse"];
870 // remove dummy empty par
871 paragraphs().clear();
873 if (!lex.checkFor("\\begin_document")) {
874 docstring const s = _("\\begin_document is missing");
875 errorList.push_back(ErrorItem(_("Document header error"),
881 if (params().outputChanges) {
882 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
883 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
884 LaTeXFeatures::isAvailable("xcolor");
886 if (!dvipost && !xcolorulem) {
887 Alert::warning(_("Changes not shown in LaTeX output"),
888 _("Changes will not be highlighted in LaTeX output, "
889 "because neither dvipost nor xcolor/ulem are installed.\n"
890 "Please install these packages or redefine "
891 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
892 } else if (!xcolorulem) {
893 Alert::warning(_("Changes not shown in LaTeX output"),
894 _("Changes will not be highlighted in LaTeX output "
895 "when using pdflatex, because xcolor and ulem are not installed.\n"
896 "Please install both packages or redefine "
897 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
901 if (!params().master.empty()) {
902 FileName const master_file = makeAbsPath(params().master,
903 onlyPath(absFileName()));
904 if (isLyXFileName(master_file.absFileName())) {
906 checkAndLoadLyXFile(master_file, true);
908 // necessary e.g. after a reload
909 // to re-register the child (bug 5873)
910 // FIXME: clean up updateMacros (here, only
911 // child registering is needed).
912 master->updateMacros();
913 // set master as master buffer, but only
914 // if we are a real child
915 if (master->isChild(this))
917 // if the master is not fully loaded
918 // it is probably just loading this
919 // child. No warning needed then.
920 else if (master->isFullyLoaded())
921 LYXERR0("The master '"
923 << "' assigned to this document ("
925 << ") does not include "
926 "this document. Ignoring the master assignment.");
931 // assure we have a default index
932 params().indiceslist().addDefault(B_("Index"));
935 bool const res = text().read(lex, errorList, d->inset);
937 // inform parent buffer about local macros
939 Buffer const * pbuf = parent();
940 UserMacroSet::const_iterator cit = usermacros.begin();
941 UserMacroSet::const_iterator end = usermacros.end();
942 for (; cit != end; ++cit)
943 pbuf->usermacros.insert(*cit);
947 updateMacroInstances(InternalUpdate);
952 bool Buffer::readString(string const & s)
954 params().compressed = false;
959 FileName const fn = FileName::tempName("Buffer_readString");
962 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
963 if (ret_plf != ReadSuccess)
966 if (file_format != LYX_FORMAT) {
967 // We need to call lyx2lyx, so write the input to a file
968 ofstream os(fn.toFilesystemEncoding().c_str());
972 return readFile(fn) == ReadSuccess;
975 if (readDocument(lex))
981 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
985 if (!lex.setFile(fname)) {
986 Alert::error(_("File Not Found"),
987 bformat(_("Unable to open file `%1$s'."),
988 from_utf8(fn.absFileName())));
989 return ReadFileNotFound;
993 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
994 if (ret_plf != ReadSuccess)
997 if (file_format != LYX_FORMAT) {
999 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1000 if (ret_clf != ReadSuccess)
1002 return readFile(tmpFile);
1005 // FIXME: InsetInfo needs to know whether the file is under VCS
1006 // during the parse process, so this has to be done before.
1007 lyxvc().file_found_hook(d->filename);
1009 if (readDocument(lex)) {
1010 Alert::error(_("Document format failure"),
1011 bformat(_("%1$s ended unexpectedly, which means"
1012 " that it is probably corrupted."),
1013 from_utf8(fn.absFileName())));
1014 return ReadDocumentFailure;
1017 d->file_fully_loaded = true;
1018 d->read_only = !d->filename.isWritable();
1019 params().compressed = formats.isZippedFile(d->filename);
1025 bool Buffer::isFullyLoaded() const
1027 return d->file_fully_loaded;
1031 void Buffer::setFullyLoaded(bool value)
1033 d->file_fully_loaded = value;
1037 PreviewLoader * Buffer::loader() const
1039 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1041 if (!d->preview_loader_)
1042 d->preview_loader_ = new PreviewLoader(*this);
1043 return d->preview_loader_;
1047 void Buffer::removePreviews() const
1049 delete d->preview_loader_;
1050 d->preview_loader_ = 0;
1054 void Buffer::updatePreviews() const
1056 PreviewLoader * ploader = loader();
1060 InsetIterator it = inset_iterator_begin(*d->inset);
1061 InsetIterator const end = inset_iterator_end(*d->inset);
1062 for (; it != end; ++it)
1063 it->addPreview(it, *ploader);
1065 ploader->startLoading();
1069 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1070 FileName const & fn, int & file_format) const
1072 if(!lex.checkFor("\\lyxformat")) {
1073 Alert::error(_("Document format failure"),
1074 bformat(_("%1$s is not a readable LyX document."),
1075 from_utf8(fn.absFileName())));
1076 return ReadNoLyXFormat;
1082 // LyX formats 217 and earlier were written as 2.17. This corresponds
1083 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1084 // these cases. See also: www.lyx.org/trac/changeset/1313.
1085 size_t dot = tmp_format.find_first_of(".,");
1086 if (dot != string::npos)
1087 tmp_format.erase(dot, 1);
1089 file_format = convert<int>(tmp_format);
1094 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1095 FileName & tmpfile, int from_format)
1097 tmpfile = FileName::tempName("Buffer_convertLyXFormat");
1098 if(tmpfile.empty()) {
1099 Alert::error(_("Conversion failed"),
1100 bformat(_("%1$s is from a different"
1101 " version of LyX, but a temporary"
1102 " file for converting it could"
1103 " not be created."),
1104 from_utf8(fn.absFileName())));
1105 return LyX2LyXNoTempFile;
1108 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1109 if (lyx2lyx.empty()) {
1110 Alert::error(_("Conversion script not found"),
1111 bformat(_("%1$s is from a different"
1112 " version of LyX, but the"
1113 " conversion script lyx2lyx"
1114 " could not be found."),
1115 from_utf8(fn.absFileName())));
1116 return LyX2LyXNotFound;
1120 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1121 ostringstream command;
1122 command << os::python()
1123 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1124 << " -t " << convert<string>(LYX_FORMAT)
1125 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1126 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1127 string const command_str = command.str();
1129 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1131 cmd_ret const ret = runCommand(command_str);
1132 if (ret.first != 0) {
1133 if (from_format < LYX_FORMAT) {
1134 Alert::error(_("Conversion script failed"),
1135 bformat(_("%1$s is from an older version"
1136 " of LyX and the lyx2lyx script"
1137 " failed to convert it."),
1138 from_utf8(fn.absFileName())));
1139 return LyX2LyXOlderFormat;
1141 Alert::error(_("Conversion script failed"),
1142 bformat(_("%1$s is from a newer version"
1143 " of LyX and the lyx2lyx script"
1144 " failed to convert it."),
1145 from_utf8(fn.absFileName())));
1146 return LyX2LyXNewerFormat;
1153 // Should probably be moved to somewhere else: BufferView? GuiView?
1154 bool Buffer::save() const
1156 docstring const file = makeDisplayPath(absFileName(), 20);
1157 d->filename.refresh();
1159 // check the read-only status before moving the file as a backup
1160 if (d->filename.exists()) {
1161 bool const read_only = !d->filename.isWritable();
1163 Alert::warning(_("File is read-only"),
1164 bformat(_("The file %1$s cannot be written because it "
1165 "is marked as read-only."), file));
1170 // ask if the disk file has been externally modified (use checksum method)
1171 if (fileName().exists() && isExternallyModified(checksum_method)) {
1173 bformat(_("Document %1$s has been externally modified. "
1174 "Are you sure you want to overwrite this file?"), file);
1175 int const ret = Alert::prompt(_("Overwrite modified file?"),
1176 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1181 // We don't need autosaves in the immediate future. (Asger)
1182 resetAutosaveTimers();
1184 FileName backupName;
1185 bool madeBackup = false;
1187 // make a backup if the file already exists
1188 if (lyxrc.make_backup && fileName().exists()) {
1189 backupName = FileName(absFileName() + '~');
1190 if (!lyxrc.backupdir_path.empty()) {
1191 string const mangledName =
1192 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1193 backupName = FileName(addName(lyxrc.backupdir_path,
1197 // Except file is symlink do not copy because of #6587.
1198 // Hard links have bad luck.
1199 if (fileName().isSymLink())
1200 madeBackup = fileName().copyTo(backupName);
1202 madeBackup = fileName().moveTo(backupName);
1205 Alert::error(_("Backup failure"),
1206 bformat(_("Cannot create backup file %1$s.\n"
1207 "Please check whether the directory exists and is writable."),
1208 from_utf8(backupName.absFileName())));
1209 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1213 if (writeFile(d->filename)) {
1217 // Saving failed, so backup is not backup
1219 backupName.moveTo(d->filename);
1225 bool Buffer::writeFile(FileName const & fname) const
1227 // FIXME Do we need to do these here? I don't think writing
1228 // the LyX file depends upon it. (RGH)
1230 // updateMacroInstances();
1232 if (d->read_only && fname == d->filename)
1235 bool retval = false;
1237 docstring const str = bformat(_("Saving document %1$s..."),
1238 makeDisplayPath(fname.absFileName()));
1241 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1243 if (params().compressed) {
1244 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1245 retval = ofs && write(ofs);
1247 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1248 retval = ofs && write(ofs);
1252 message(str + _(" could not write file!"));
1257 // removeAutosaveFile();
1260 message(str + _(" done."));
1266 docstring Buffer::emergencyWrite()
1268 // No need to save if the buffer has not changed.
1272 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1274 docstring user_message = bformat(
1275 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1277 // We try to save three places:
1278 // 1) Same place as document. Unless it is an unnamed doc.
1280 string s = absFileName();
1283 if (writeFile(FileName(s))) {
1285 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1286 return user_message;
1288 user_message += " " + _("Save failed! Trying again...\n");
1292 // 2) In HOME directory.
1293 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1295 lyxerr << ' ' << s << endl;
1296 if (writeFile(FileName(s))) {
1298 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1299 return user_message;
1302 user_message += " " + _("Save failed! Trying yet again...\n");
1304 // 3) In "/tmp" directory.
1305 // MakeAbsPath to prepend the current
1306 // drive letter on OS/2
1307 s = addName(package().temp_dir().absFileName(), absFileName());
1309 lyxerr << ' ' << s << endl;
1310 if (writeFile(FileName(s))) {
1312 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1313 return user_message;
1316 user_message += " " + _("Save failed! Bummer. Document is lost.");
1319 return user_message;
1323 bool Buffer::write(ostream & ofs) const
1326 // Use the standard "C" locale for file output.
1327 ofs.imbue(locale::classic());
1330 // The top of the file should not be written by params().
1332 // write out a comment in the top of the file
1333 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1334 << " created this file. For more info see http://www.lyx.org/\n"
1335 << "\\lyxformat " << LYX_FORMAT << "\n"
1336 << "\\begin_document\n";
1338 /// For each author, set 'used' to true if there is a change
1339 /// by this author in the document; otherwise set it to 'false'.
1340 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1341 AuthorList::Authors::const_iterator a_end = params().authors().end();
1342 for (; a_it != a_end; ++a_it)
1343 a_it->setUsed(false);
1345 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1346 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1347 for ( ; it != end; ++it)
1348 it->checkAuthors(params().authors());
1350 // now write out the buffer parameters.
1351 ofs << "\\begin_header\n";
1352 params().writeFile(ofs);
1353 ofs << "\\end_header\n";
1356 ofs << "\n\\begin_body\n";
1358 ofs << "\n\\end_body\n";
1360 // Write marker that shows file is complete
1361 ofs << "\\end_document" << endl;
1363 // Shouldn't really be needed....
1366 // how to check if close went ok?
1367 // Following is an attempt... (BE 20001011)
1369 // good() returns false if any error occured, including some
1370 // formatting error.
1371 // bad() returns true if something bad happened in the buffer,
1372 // which should include file system full errors.
1377 lyxerr << "File was not closed properly." << endl;
1384 bool Buffer::makeLaTeXFile(FileName const & fname,
1385 string const & original_path,
1386 OutputParams const & runparams_in,
1387 OutputWhat output) const
1389 OutputParams runparams = runparams_in;
1391 // This is necessary for LuaTeX/XeTeX with tex fonts.
1392 // See FIXME in BufferParams::encoding()
1393 if (runparams.isFullUnicode())
1394 runparams.encoding = encodings.fromLyXName("utf8-plain");
1396 string const encoding = runparams.encoding->iconvName();
1397 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1400 try { ofs.reset(encoding); }
1401 catch (iconv_codecvt_facet_exception const & e) {
1402 lyxerr << "Caught iconv exception: " << e.what() << endl;
1403 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1404 "verify that the support software for your encoding (%1$s) is "
1405 "properly installed"), from_ascii(encoding)));
1408 if (!openFileWrite(ofs, fname))
1411 //TexStream ts(ofs.rdbuf(), &texrow());
1412 ErrorList & errorList = d->errorLists["Export"];
1414 bool failed_export = false;
1415 otexstream os(ofs, d->texrow);
1417 // make sure we are ready to export
1418 // this needs to be done before we validate
1419 // FIXME Do we need to do this all the time? I.e., in children
1420 // of a master we are exporting?
1422 updateMacroInstances(OutputUpdate);
1425 os.texrow().reset();
1426 writeLaTeXSource(os, original_path, runparams, output);
1428 catch (EncodingException const & e) {
1429 odocstringstream ods;
1430 ods.put(e.failed_char);
1432 oss << "0x" << hex << e.failed_char << dec;
1433 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1434 " (code point %2$s)"),
1435 ods.str(), from_utf8(oss.str()));
1436 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1437 "representable in the chosen encoding.\n"
1438 "Changing the document encoding to utf8 could help."),
1439 e.par_id, e.pos, e.pos + 1));
1440 failed_export = true;
1442 catch (iconv_codecvt_facet_exception const & e) {
1443 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1444 _(e.what()), -1, 0, 0));
1445 failed_export = true;
1447 catch (exception const & e) {
1448 errorList.push_back(ErrorItem(_("conversion failed"),
1449 _(e.what()), -1, 0, 0));
1450 failed_export = true;
1453 lyxerr << "Caught some really weird exception..." << endl;
1459 failed_export = true;
1460 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1464 return !failed_export;
1468 void Buffer::writeLaTeXSource(otexstream & os,
1469 string const & original_path,
1470 OutputParams const & runparams_in,
1471 OutputWhat output) const
1473 // The child documents, if any, shall be already loaded at this point.
1475 OutputParams runparams = runparams_in;
1477 // If we are compiling a file standalone, even if this is the
1478 // child of some other buffer, let's cut the link here, so the
1479 // file is really independent and no concurring settings from
1480 // the master (e.g. branch state) interfere (see #8100).
1481 if (!runparams.is_child)
1482 d->ignore_parent = true;
1484 // Classify the unicode characters appearing in math insets
1485 Encodings::initUnicodeMath(*this);
1487 // validate the buffer.
1488 LYXERR(Debug::LATEX, " Validating buffer...");
1489 LaTeXFeatures features(*this, params(), runparams);
1491 runparams.use_polyglossia = features.usePolyglossia();
1492 LYXERR(Debug::LATEX, " Buffer validation done.");
1494 bool const output_preamble =
1495 output == FullSource || output == OnlyPreamble;
1496 bool const output_body =
1497 output == FullSource || output == OnlyBody;
1499 // The starting paragraph of the coming rows is the
1500 // first paragraph of the document. (Asger)
1501 if (output_preamble && runparams.nice) {
1502 os << "%% LyX " << lyx_version << " created this file. "
1503 "For more info, see http://www.lyx.org/.\n"
1504 "%% Do not edit unless you really know what "
1507 LYXERR(Debug::INFO, "lyx document header finished");
1509 // There are a few differences between nice LaTeX and usual files:
1510 // usual files have \batchmode and special input@path to allow
1511 // inclusion of figures specified by an explicitly relative path
1512 // (i.e., a path starting with './' or '../') with either \input or
1513 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1514 // input@path is set when the actual parameter original_path is set.
1515 // This is done for usual tex-file, but not for nice-latex-file.
1516 // (Matthias 250696)
1517 // Note that input@path is only needed for something the user does
1518 // in the preamble, included .tex files or ERT, files included by
1519 // LyX work without it.
1520 if (output_preamble) {
1521 if (!runparams.nice) {
1522 // code for usual, NOT nice-latex-file
1523 os << "\\batchmode\n"; // changed from \nonstopmode
1525 if (!original_path.empty()) {
1527 // We don't know the encoding of inputpath
1528 docstring const inputpath = from_utf8(original_path);
1529 docstring uncodable_glyphs;
1530 Encoding const * const enc = runparams.encoding;
1532 for (size_t n = 0; n < inputpath.size(); ++n) {
1533 if (!enc->encodable(inputpath[n])) {
1534 docstring const glyph(1, inputpath[n]);
1535 LYXERR0("Uncodable character '"
1537 << "' in input path!");
1538 uncodable_glyphs += glyph;
1543 // warn user if we found uncodable glyphs.
1544 if (!uncodable_glyphs.empty()) {
1545 frontend::Alert::warning(
1546 _("Uncodable character in file path"),
1548 _("The path of your document\n"
1550 "contains glyphs that are unknown "
1551 "in the current document encoding "
1552 "(namely %2$s). This may result in "
1553 "incomplete output, unless "
1554 "TEXINPUTS contains the document "
1555 "directory and you don't use "
1556 "explicitly relative paths (i.e., "
1557 "paths starting with './' or "
1558 "'../') in the preamble or in ERT."
1559 "\n\nIn case of problems, choose "
1560 "an appropriate document encoding\n"
1561 "(such as utf8) or change the "
1563 inputpath, uncodable_glyphs));
1566 support::latex_path(original_path);
1567 if (contains(docdir, '#')) {
1568 docdir = subst(docdir, "#", "\\#");
1569 os << "\\catcode`\\#=11"
1570 "\\def\\#{#}\\catcode`\\#=6\n";
1572 if (contains(docdir, '%')) {
1573 docdir = subst(docdir, "%", "\\%");
1574 os << "\\catcode`\\%=11"
1575 "\\def\\%{%}\\catcode`\\%=14\n";
1577 os << "\\makeatletter\n"
1578 << "\\def\\input@path{{"
1579 << docdir << "/}}\n"
1580 << "\\makeatother\n";
1584 // get parent macros (if this buffer has a parent) which will be
1585 // written at the document begin further down.
1586 MacroSet parentMacros;
1587 listParentMacros(parentMacros, features);
1589 // Write the preamble
1590 runparams.use_babel = params().writeLaTeX(os, features,
1591 d->filename.onlyPath());
1593 runparams.use_japanese = features.isRequired("japanese");
1599 os << "\\begin{document}\n";
1601 // output the parent macros
1602 MacroSet::iterator it = parentMacros.begin();
1603 MacroSet::iterator end = parentMacros.end();
1604 for (; it != end; ++it) {
1605 int num_lines = (*it)->write(os.os(), true);
1606 os.texrow().newlines(num_lines);
1609 } // output_preamble
1611 os.texrow().start(paragraphs().begin()->id(), 0);
1613 LYXERR(Debug::INFO, "preamble finished, now the body.");
1616 latexParagraphs(*this, text(), os, runparams);
1618 // Restore the parenthood if needed
1619 if (!runparams.is_child)
1620 d->ignore_parent = false;
1622 // add this just in case after all the paragraphs
1625 if (output_preamble) {
1626 os << "\\end{document}\n";
1627 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1629 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1631 runparams_in.encoding = runparams.encoding;
1633 // Just to be sure. (Asger)
1634 os.texrow().newline();
1636 //for (int i = 0; i<d->texrow.rows(); i++) {
1638 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1639 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1642 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1643 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1647 void Buffer::makeDocBookFile(FileName const & fname,
1648 OutputParams const & runparams,
1649 OutputWhat output) const
1651 LYXERR(Debug::LATEX, "makeDocBookFile...");
1654 if (!openFileWrite(ofs, fname))
1657 // make sure we are ready to export
1658 // this needs to be done before we validate
1660 updateMacroInstances(OutputUpdate);
1662 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1666 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1670 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1671 OutputParams const & runparams,
1672 OutputWhat output) const
1674 LaTeXFeatures features(*this, params(), runparams);
1679 DocumentClass const & tclass = params().documentClass();
1680 string const top_element = tclass.latexname();
1682 bool const output_preamble =
1683 output == FullSource || output == OnlyPreamble;
1684 bool const output_body =
1685 output == FullSource || output == OnlyBody;
1687 if (output_preamble) {
1688 if (runparams.flavor == OutputParams::XML)
1689 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1692 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1695 if (! tclass.class_header().empty())
1696 os << from_ascii(tclass.class_header());
1697 else if (runparams.flavor == OutputParams::XML)
1698 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1699 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1701 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1703 docstring preamble = from_utf8(params().preamble);
1704 if (runparams.flavor != OutputParams::XML ) {
1705 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1706 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1707 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1708 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1711 string const name = runparams.nice
1712 ? changeExtension(absFileName(), ".sgml") : fname;
1713 preamble += features.getIncludedFiles(name);
1714 preamble += features.getLyXSGMLEntities();
1716 if (!preamble.empty()) {
1717 os << "\n [ " << preamble << " ]";
1723 string top = top_element;
1725 if (runparams.flavor == OutputParams::XML)
1726 top += params().language->code();
1728 top += params().language->code().substr(0, 2);
1731 if (!params().options.empty()) {
1733 top += params().options;
1736 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1737 << " file was created by LyX " << lyx_version
1738 << "\n See http://www.lyx.org/ for more information -->\n";
1740 params().documentClass().counters().reset();
1742 sgml::openTag(os, top);
1744 docbookParagraphs(text(), *this, os, runparams);
1745 sgml::closeTag(os, top_element);
1750 void Buffer::makeLyXHTMLFile(FileName const & fname,
1751 OutputParams const & runparams) const
1753 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1756 if (!openFileWrite(ofs, fname))
1759 // make sure we are ready to export
1760 // this has to be done before we validate
1761 updateBuffer(UpdateMaster, OutputUpdate);
1762 updateMacroInstances(OutputUpdate);
1764 writeLyXHTMLSource(ofs, runparams, FullSource);
1768 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1772 void Buffer::writeLyXHTMLSource(odocstream & os,
1773 OutputParams const & runparams,
1774 OutputWhat output) const
1776 LaTeXFeatures features(*this, params(), runparams);
1778 d->bibinfo_.makeCitationLabels(*this);
1780 bool const output_preamble =
1781 output == FullSource || output == OnlyPreamble;
1782 bool const output_body =
1783 output == FullSource || output == OnlyBody || output == IncludedFile;
1785 if (output_preamble) {
1786 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1787 << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/TR/2001/REC-MathML2-20010221/dtd/xhtml-math11-f.dtd\">\n"
1788 // FIXME Language should be set properly.
1789 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1791 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1792 // FIXME Presumably need to set this right
1793 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1795 docstring const & doctitle = features.htmlTitle();
1797 << (doctitle.empty() ?
1798 from_ascii("LyX Document") :
1799 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1802 docstring styles = features.getTClassHTMLPreamble();
1803 if (!styles.empty())
1804 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1806 styles = from_utf8(features.getPreambleSnippets());
1807 if (!styles.empty())
1808 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1810 // we will collect CSS information in a stream, and then output it
1811 // either here, as part of the header, or else in a separate file.
1812 odocstringstream css;
1813 styles = from_utf8(features.getCSSSnippets());
1814 if (!styles.empty())
1815 css << "/* LyX Provided Styles */\n" << styles << '\n';
1817 styles = features.getTClassHTMLStyles();
1818 if (!styles.empty())
1819 css << "/* Layout-provided Styles */\n" << styles << '\n';
1821 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1822 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1823 if (needfg || needbg) {
1824 css << "\nbody {\n";
1827 << from_ascii(X11hexname(params().fontcolor))
1830 css << " background-color: "
1831 << from_ascii(X11hexname(params().backgroundcolor))
1836 docstring const dstyles = css.str();
1837 if (!dstyles.empty()) {
1838 bool written = false;
1839 if (params().html_css_as_file) {
1840 // open a file for CSS info
1842 string const fcssname = addName(temppath(), "docstyle.css");
1843 FileName const fcssfile = FileName(fcssname);
1844 if (openFileWrite(ocss, fcssfile)) {
1848 // write link to header
1849 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
1851 runparams.exportdata->addExternalFile("xhtml", fcssfile);
1854 // we are here if the CSS is supposed to be written to the header
1855 // or if we failed to write it to an external file.
1857 os << "<style type='text/css'>\n"
1866 bool const output_body_tag = (output != IncludedFile);
1867 if (output_body_tag)
1870 params().documentClass().counters().reset();
1871 xhtmlParagraphs(text(), *this, xs, runparams);
1872 if (output_body_tag)
1876 if (output_preamble)
1881 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1882 // Other flags: -wall -v0 -x
1883 int Buffer::runChktex()
1887 // get LaTeX-Filename
1888 FileName const path(temppath());
1889 string const name = addName(path.absFileName(), latexName());
1890 string const org_path = filePath();
1892 PathChanger p(path); // path to LaTeX file
1893 message(_("Running chktex..."));
1895 // Generate the LaTeX file if neccessary
1896 OutputParams runparams(¶ms().encoding());
1897 runparams.flavor = OutputParams::LATEX;
1898 runparams.nice = false;
1899 runparams.linelen = lyxrc.plaintext_linelen;
1900 makeLaTeXFile(FileName(name), org_path, runparams);
1903 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1904 int const res = chktex.run(terr); // run chktex
1907 Alert::error(_("chktex failure"),
1908 _("Could not run chktex successfully."));
1909 } else if (res > 0) {
1910 ErrorList & errlist = d->errorLists["ChkTeX"];
1912 bufferErrors(terr, errlist);
1923 void Buffer::validate(LaTeXFeatures & features) const
1925 params().validate(features);
1927 for_each(paragraphs().begin(), paragraphs().end(),
1928 bind(&Paragraph::validate, _1, ref(features)));
1930 if (lyxerr.debugging(Debug::LATEX)) {
1931 features.showStruct();
1936 void Buffer::getLabelList(vector<docstring> & list) const
1938 // If this is a child document, use the master's list instead.
1940 masterBuffer()->getLabelList(list);
1945 Toc & toc = d->toc_backend.toc("label");
1946 TocIterator toc_it = toc.begin();
1947 TocIterator end = toc.end();
1948 for (; toc_it != end; ++toc_it) {
1949 if (toc_it->depth() == 0)
1950 list.push_back(toc_it->str());
1955 void Buffer::updateBibfilesCache(UpdateScope scope) const
1957 // FIXME This is probably unnecssary, given where we call this.
1958 // If this is a child document, use the parent's cache instead.
1959 if (parent() && scope != UpdateChildOnly) {
1960 masterBuffer()->updateBibfilesCache();
1964 d->bibfiles_cache_.clear();
1965 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1966 if (it->lyxCode() == BIBTEX_CODE) {
1967 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
1968 support::FileNameList const bibfiles = inset.getBibFiles();
1969 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1972 } else if (it->lyxCode() == INCLUDE_CODE) {
1973 InsetInclude & inset = static_cast<InsetInclude &>(*it);
1974 Buffer const * const incbuf = inset.getChildBuffer();
1977 support::FileNameList const & bibfiles =
1978 incbuf->getBibfilesCache(UpdateChildOnly);
1979 if (!bibfiles.empty()) {
1980 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1986 d->bibfile_cache_valid_ = true;
1987 d->bibinfo_cache_valid_ = false;
1988 d->cite_labels_valid_ = false;
1992 void Buffer::invalidateBibinfoCache() const
1994 d->bibinfo_cache_valid_ = false;
1995 d->cite_labels_valid_ = false;
1996 // also invalidate the cache for the parent buffer
1997 Buffer const * const pbuf = d->parent();
1999 pbuf->invalidateBibinfoCache();
2003 void Buffer::invalidateBibfileCache() const
2005 d->bibfile_cache_valid_ = false;
2006 d->bibinfo_cache_valid_ = false;
2007 d->cite_labels_valid_ = false;
2008 // also invalidate the cache for the parent buffer
2009 Buffer const * const pbuf = d->parent();
2011 pbuf->invalidateBibfileCache();
2015 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2017 // FIXME This is probably unnecessary, given where we call this.
2018 // If this is a child document, use the master's cache instead.
2019 Buffer const * const pbuf = masterBuffer();
2020 if (pbuf != this && scope != UpdateChildOnly)
2021 return pbuf->getBibfilesCache();
2023 if (!d->bibfile_cache_valid_)
2024 this->updateBibfilesCache(scope);
2026 return d->bibfiles_cache_;
2030 BiblioInfo const & Buffer::masterBibInfo() const
2032 Buffer const * const tmp = masterBuffer();
2034 return tmp->masterBibInfo();
2039 void Buffer::checkIfBibInfoCacheIsValid() const
2041 // use the master's cache
2042 Buffer const * const tmp = masterBuffer();
2044 tmp->checkIfBibInfoCacheIsValid();
2048 // compare the cached timestamps with the actual ones.
2049 FileNameList const & bibfiles_cache = getBibfilesCache();
2050 FileNameList::const_iterator ei = bibfiles_cache.begin();
2051 FileNameList::const_iterator en = bibfiles_cache.end();
2052 for (; ei != en; ++ ei) {
2053 time_t lastw = ei->lastModified();
2054 time_t prevw = d->bibfile_status_[*ei];
2055 if (lastw != prevw) {
2056 d->bibinfo_cache_valid_ = false;
2057 d->cite_labels_valid_ = false;
2058 d->bibfile_status_[*ei] = lastw;
2064 void Buffer::reloadBibInfoCache() const
2066 // use the master's cache
2067 Buffer const * const tmp = masterBuffer();
2069 tmp->reloadBibInfoCache();
2073 checkIfBibInfoCacheIsValid();
2074 if (d->bibinfo_cache_valid_)
2077 d->bibinfo_.clear();
2079 d->bibinfo_cache_valid_ = true;
2083 void Buffer::collectBibKeys() const
2085 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2086 it->collectBibKeys(it);
2090 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2092 Buffer const * tmp = masterBuffer();
2093 BiblioInfo & masterbi = (tmp == this) ?
2094 d->bibinfo_ : tmp->d->bibinfo_;
2095 masterbi.mergeBiblioInfo(bi);
2099 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2101 Buffer const * tmp = masterBuffer();
2102 BiblioInfo & masterbi = (tmp == this) ?
2103 d->bibinfo_ : tmp->d->bibinfo_;
2108 bool Buffer::citeLabelsValid() const
2110 return masterBuffer()->d->cite_labels_valid_;
2114 void Buffer::removeBiblioTempFiles() const
2116 // We remove files that contain LaTeX commands specific to the
2117 // particular bibliographic style being used, in order to avoid
2118 // LaTeX errors when we switch style.
2119 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2120 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2121 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2122 aux_file.removeFile();
2123 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2124 bbl_file.removeFile();
2125 // Also for the parent buffer
2126 Buffer const * const pbuf = parent();
2128 pbuf->removeBiblioTempFiles();
2132 bool Buffer::isDepClean(string const & name) const
2134 DepClean::const_iterator const it = d->dep_clean.find(name);
2135 if (it == d->dep_clean.end())
2141 void Buffer::markDepClean(string const & name)
2143 d->dep_clean[name] = true;
2147 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2150 // FIXME? if there is an Buffer LFUN that can be dispatched even
2151 // if internal, put a switch '(cmd.action)' here.
2157 switch (cmd.action()) {
2159 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2160 flag.setOnOff(isReadonly());
2163 // FIXME: There is need for a command-line import.
2164 //case LFUN_BUFFER_IMPORT:
2166 case LFUN_BUFFER_AUTO_SAVE:
2169 case LFUN_BUFFER_EXPORT_CUSTOM:
2170 // FIXME: Nothing to check here?
2173 case LFUN_BUFFER_EXPORT: {
2174 docstring const arg = cmd.argument();
2175 if (arg == "custom") {
2179 string format = to_utf8(arg);
2180 size_t pos = format.find(' ');
2181 if (pos != string::npos)
2182 format = format.substr(0, pos);
2183 enable = params().isExportable(format);
2185 flag.message(bformat(
2186 _("Don't know how to export to format: %1$s"), arg));
2190 case LFUN_BUFFER_CHKTEX:
2191 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2194 case LFUN_BUILD_PROGRAM:
2195 enable = params().isExportable("program");
2198 case LFUN_BRANCH_ADD:
2199 case LFUN_BRANCHES_RENAME:
2200 case LFUN_BUFFER_PRINT:
2201 // if no Buffer is present, then of course we won't be called!
2204 case LFUN_BUFFER_LANGUAGE:
2205 enable = !isReadonly();
2211 flag.setEnabled(enable);
2216 void Buffer::dispatch(string const & command, DispatchResult & result)
2218 return dispatch(lyxaction.lookupFunc(command), result);
2222 // NOTE We can end up here even if we have no GUI, because we are called
2223 // by LyX::exec to handled command-line requests. So we may need to check
2224 // whether we have a GUI or not. The boolean use_gui holds this information.
2225 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2228 // FIXME? if there is an Buffer LFUN that can be dispatched even
2229 // if internal, put a switch '(cmd.action())' here.
2230 dr.dispatched(false);
2233 string const argument = to_utf8(func.argument());
2234 // We'll set this back to false if need be.
2235 bool dispatched = true;
2236 undo().beginUndoGroup();
2238 switch (func.action()) {
2239 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2240 if (lyxvc().inUse())
2241 lyxvc().toggleReadOnly();
2243 setReadonly(!isReadonly());
2246 case LFUN_BUFFER_EXPORT: {
2247 ExportStatus const status = doExport(argument, false);
2248 dr.setError(status != ExportSuccess);
2249 if (status != ExportSuccess)
2250 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2255 case LFUN_BUILD_PROGRAM:
2256 doExport("program", true);
2259 case LFUN_BUFFER_CHKTEX:
2263 case LFUN_BUFFER_EXPORT_CUSTOM: {
2265 string command = split(argument, format_name, ' ');
2266 Format const * format = formats.getFormat(format_name);
2268 lyxerr << "Format \"" << format_name
2269 << "\" not recognized!"
2274 // The name of the file created by the conversion process
2277 // Output to filename
2278 if (format->name() == "lyx") {
2279 string const latexname = latexName(false);
2280 filename = changeExtension(latexname,
2281 format->extension());
2282 filename = addName(temppath(), filename);
2284 if (!writeFile(FileName(filename)))
2288 doExport(format_name, true, filename);
2291 // Substitute $$FName for filename
2292 if (!contains(command, "$$FName"))
2293 command = "( " + command + " ) < $$FName";
2294 command = subst(command, "$$FName", filename);
2296 // Execute the command in the background
2298 call.startscript(Systemcall::DontWait, command, filePath());
2302 // FIXME: There is need for a command-line import.
2304 case LFUN_BUFFER_IMPORT:
2309 case LFUN_BUFFER_AUTO_SAVE:
2311 resetAutosaveTimers();
2314 case LFUN_BRANCH_ADD: {
2315 docstring branch_name = func.argument();
2316 if (branch_name.empty()) {
2320 BranchList & branch_list = params().branchlist();
2321 vector<docstring> const branches =
2322 getVectorFromString(branch_name, branch_list.separator());
2324 for (vector<docstring>::const_iterator it = branches.begin();
2325 it != branches.end(); ++it) {
2327 Branch * branch = branch_list.find(branch_name);
2329 LYXERR0("Branch " << branch_name << " already exists.");
2333 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2335 branch_list.add(branch_name);
2336 branch = branch_list.find(branch_name);
2337 string const x11hexname = X11hexname(branch->color());
2338 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2339 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2341 dr.screenUpdate(Update::Force);
2349 case LFUN_BRANCHES_RENAME: {
2350 if (func.argument().empty())
2353 docstring const oldname = from_utf8(func.getArg(0));
2354 docstring const newname = from_utf8(func.getArg(1));
2355 InsetIterator it = inset_iterator_begin(inset());
2356 InsetIterator const end = inset_iterator_end(inset());
2357 bool success = false;
2358 for (; it != end; ++it) {
2359 if (it->lyxCode() == BRANCH_CODE) {
2360 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2361 if (ins.branch() == oldname) {
2362 undo().recordUndo(CursorData(it));
2363 ins.rename(newname);
2368 if (it->lyxCode() == INCLUDE_CODE) {
2369 // get buffer of external file
2370 InsetInclude const & ins =
2371 static_cast<InsetInclude const &>(*it);
2372 Buffer * child = ins.getChildBuffer();
2375 child->dispatch(func, dr);
2380 dr.screenUpdate(Update::Force);
2381 dr.forceBufferUpdate();
2386 case LFUN_BUFFER_PRINT: {
2387 // we'll assume there's a problem until we succeed
2389 string target = func.getArg(0);
2390 string target_name = func.getArg(1);
2391 string command = func.getArg(2);
2394 || target_name.empty()
2395 || command.empty()) {
2396 LYXERR0("Unable to parse " << func.argument());
2397 docstring const msg =
2398 bformat(_("Unable to parse \"%1$s\""), func.argument());
2402 if (target != "printer" && target != "file") {
2403 LYXERR0("Unrecognized target \"" << target << '"');
2404 docstring const msg =
2405 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2410 if (!doExport("dvi", true)) {
2411 showPrintError(absFileName());
2412 dr.setMessage(_("Error exporting to DVI."));
2416 // Push directory path.
2417 string const path = temppath();
2418 // Prevent the compiler from optimizing away p
2422 // there are three cases here:
2423 // 1. we print to a file
2424 // 2. we print directly to a printer
2425 // 3. we print using a spool command (print to file first)
2428 string const dviname = changeExtension(latexName(true), "dvi");
2430 if (target == "printer") {
2431 if (!lyxrc.print_spool_command.empty()) {
2432 // case 3: print using a spool
2433 string const psname = changeExtension(dviname,".ps");
2434 command += ' ' + lyxrc.print_to_file
2437 + quoteName(dviname);
2439 string command2 = lyxrc.print_spool_command + ' ';
2440 if (target_name != "default") {
2441 command2 += lyxrc.print_spool_printerprefix
2445 command2 += quoteName(psname);
2447 // If successful, then spool command
2448 res = one.startscript(Systemcall::Wait, command,
2452 // If there's no GUI, we have to wait on this command. Otherwise,
2453 // LyX deletes the temporary directory, and with it the spooled
2454 // file, before it can be printed!!
2455 Systemcall::Starttype stype = use_gui ?
2456 Systemcall::DontWait : Systemcall::Wait;
2457 res = one.startscript(stype, command2,
2461 // case 2: print directly to a printer
2462 if (target_name != "default")
2463 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2465 Systemcall::Starttype stype = use_gui ?
2466 Systemcall::DontWait : Systemcall::Wait;
2467 res = one.startscript(stype, command +
2468 quoteName(dviname), filePath());
2472 // case 1: print to a file
2473 FileName const filename(makeAbsPath(target_name, filePath()));
2474 FileName const dvifile(makeAbsPath(dviname, path));
2475 if (filename.exists()) {
2476 docstring text = bformat(
2477 _("The file %1$s already exists.\n\n"
2478 "Do you want to overwrite that file?"),
2479 makeDisplayPath(filename.absFileName()));
2480 if (Alert::prompt(_("Overwrite file?"),
2481 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2484 command += ' ' + lyxrc.print_to_file
2485 + quoteName(filename.toFilesystemEncoding())
2487 + quoteName(dvifile.toFilesystemEncoding());
2489 Systemcall::Starttype stype = use_gui ?
2490 Systemcall::DontWait : Systemcall::Wait;
2491 res = one.startscript(stype, command, filePath());
2497 dr.setMessage(_("Error running external commands."));
2498 showPrintError(absFileName());
2507 dr.dispatched(dispatched);
2508 undo().endUndoGroup();
2512 void Buffer::changeLanguage(Language const * from, Language const * to)
2514 LASSERT(from, /**/);
2517 for_each(par_iterator_begin(),
2519 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2523 bool Buffer::isMultiLingual() const
2525 ParConstIterator end = par_iterator_end();
2526 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2527 if (it->isMultiLingual(params()))
2534 std::set<Language const *> Buffer::getLanguages() const
2536 std::set<Language const *> languages;
2537 getLanguages(languages);
2542 void Buffer::getLanguages(std::set<Language const *> & languages) const
2544 ParConstIterator end = par_iterator_end();
2545 // add the buffer language, even if it's not actively used
2546 languages.insert(language());
2547 // iterate over the paragraphs
2548 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2549 it->getLanguages(languages);
2551 ListOfBuffers clist = getDescendents();
2552 ListOfBuffers::const_iterator cit = clist.begin();
2553 ListOfBuffers::const_iterator const cen = clist.end();
2554 for (; cit != cen; ++cit)
2555 (*cit)->getLanguages(languages);
2559 DocIterator Buffer::getParFromID(int const id) const
2561 Buffer * buf = const_cast<Buffer *>(this);
2563 // John says this is called with id == -1 from undo
2564 lyxerr << "getParFromID(), id: " << id << endl;
2565 return doc_iterator_end(buf);
2568 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2569 if (it.paragraph().id() == id)
2572 return doc_iterator_end(buf);
2576 bool Buffer::hasParWithID(int const id) const
2578 return !getParFromID(id).atEnd();
2582 ParIterator Buffer::par_iterator_begin()
2584 return ParIterator(doc_iterator_begin(this));
2588 ParIterator Buffer::par_iterator_end()
2590 return ParIterator(doc_iterator_end(this));
2594 ParConstIterator Buffer::par_iterator_begin() const
2596 return ParConstIterator(doc_iterator_begin(this));
2600 ParConstIterator Buffer::par_iterator_end() const
2602 return ParConstIterator(doc_iterator_end(this));
2606 Language const * Buffer::language() const
2608 return params().language;
2612 docstring const Buffer::B_(string const & l10n) const
2614 return params().B_(l10n);
2618 bool Buffer::isClean() const
2620 return d->lyx_clean;
2624 bool Buffer::isExternallyModified(CheckMethod method) const
2626 LASSERT(d->filename.exists(), /**/);
2627 // if method == timestamp, check timestamp before checksum
2628 return (method == checksum_method
2629 || d->timestamp_ != d->filename.lastModified())
2630 && d->checksum_ != d->filename.checksum();
2634 void Buffer::saveCheckSum() const
2636 FileName const & file = d->filename;
2639 if (file.exists()) {
2640 d->timestamp_ = file.lastModified();
2641 d->checksum_ = file.checksum();
2643 // in the case of save to a new file.
2650 void Buffer::markClean() const
2652 if (!d->lyx_clean) {
2653 d->lyx_clean = true;
2656 // if the .lyx file has been saved, we don't need an
2658 d->bak_clean = true;
2659 d->undo_.markDirty();
2663 void Buffer::setUnnamed(bool flag)
2669 bool Buffer::isUnnamed() const
2676 /// Don't check unnamed, here: isInternal() is used in
2677 /// newBuffer(), where the unnamed flag has not been set by anyone
2678 /// yet. Also, for an internal buffer, there should be no need for
2679 /// retrieving fileName() nor for checking if it is unnamed or not.
2680 bool Buffer::isInternal() const
2682 return d->internal_buffer;
2686 void Buffer::setInternal(bool flag)
2688 d->internal_buffer = flag;
2692 void Buffer::markDirty()
2695 d->lyx_clean = false;
2698 d->bak_clean = false;
2700 DepClean::iterator it = d->dep_clean.begin();
2701 DepClean::const_iterator const end = d->dep_clean.end();
2703 for (; it != end; ++it)
2708 FileName Buffer::fileName() const
2714 string Buffer::absFileName() const
2716 return d->filename.absFileName();
2720 string Buffer::filePath() const
2722 int last = d->filename.onlyPath().absFileName().length() - 1;
2724 return d->filename.onlyPath().absFileName()[last] == '/'
2725 ? d->filename.onlyPath().absFileName()
2726 : d->filename.onlyPath().absFileName() + "/";
2730 bool Buffer::isReadonly() const
2732 return d->read_only;
2736 void Buffer::setParent(Buffer const * buffer)
2738 // Avoids recursive include.
2739 d->setParent(buffer == this ? 0 : buffer);
2744 Buffer const * Buffer::parent() const
2750 ListOfBuffers Buffer::allRelatives() const
2752 ListOfBuffers lb = masterBuffer()->getDescendents();
2753 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2758 Buffer const * Buffer::masterBuffer() const
2760 // FIXME Should be make sure we are not in some kind
2761 // of recursive include? A -> B -> A will crash this.
2762 Buffer const * const pbuf = d->parent();
2766 return pbuf->masterBuffer();
2770 bool Buffer::isChild(Buffer * child) const
2772 return d->children_positions.find(child) != d->children_positions.end();
2776 DocIterator Buffer::firstChildPosition(Buffer const * child)
2778 Impl::BufferPositionMap::iterator it;
2779 it = d->children_positions.find(child);
2780 if (it == d->children_positions.end())
2781 return DocIterator(this);
2786 bool Buffer::hasChildren() const
2788 return !d->children_positions.empty();
2792 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2794 // loop over children
2795 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2796 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2797 for (; it != end; ++it) {
2798 Buffer * child = const_cast<Buffer *>(it->first);
2800 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2801 if (bit != clist.end())
2803 clist.push_back(child);
2805 // there might be grandchildren
2806 child->collectChildren(clist, true);
2811 ListOfBuffers Buffer::getChildren() const
2814 collectChildren(v, false);
2815 // Make sure we have not included ourselves.
2816 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2817 if (bit != v.end()) {
2818 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2825 ListOfBuffers Buffer::getDescendents() const
2828 collectChildren(v, true);
2829 // Make sure we have not included ourselves.
2830 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2831 if (bit != v.end()) {
2832 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2839 template<typename M>
2840 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2845 typename M::const_iterator it = m.lower_bound(x);
2846 if (it == m.begin())
2854 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2855 DocIterator const & pos) const
2857 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2859 // if paragraphs have no macro context set, pos will be empty
2863 // we haven't found anything yet
2864 DocIterator bestPos = owner_->par_iterator_begin();
2865 MacroData const * bestData = 0;
2867 // find macro definitions for name
2868 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2869 if (nameIt != macros.end()) {
2870 // find last definition in front of pos or at pos itself
2871 PositionScopeMacroMap::const_iterator it
2872 = greatest_below(nameIt->second, pos);
2873 if (it != nameIt->second.end()) {
2875 // scope ends behind pos?
2876 if (pos < it->second.first) {
2877 // Looks good, remember this. If there
2878 // is no external macro behind this,
2879 // we found the right one already.
2880 bestPos = it->first;
2881 bestData = &it->second.second;
2885 // try previous macro if there is one
2886 if (it == nameIt->second.begin())
2893 // find macros in included files
2894 PositionScopeBufferMap::const_iterator it
2895 = greatest_below(position_to_children, pos);
2896 if (it == position_to_children.end())
2897 // no children before
2901 // do we know something better (i.e. later) already?
2902 if (it->first < bestPos )
2905 // scope ends behind pos?
2906 if (pos < it->second.first
2907 && (cloned_buffer_ ||
2908 theBufferList().isLoaded(it->second.second))) {
2909 // look for macro in external file
2911 MacroData const * data
2912 = it->second.second->getMacro(name, false);
2915 bestPos = it->first;
2921 // try previous file if there is one
2922 if (it == position_to_children.begin())
2927 // return the best macro we have found
2932 MacroData const * Buffer::getMacro(docstring const & name,
2933 DocIterator const & pos, bool global) const
2938 // query buffer macros
2939 MacroData const * data = d->getBufferMacro(name, pos);
2943 // If there is a master buffer, query that
2944 Buffer const * const pbuf = d->parent();
2946 d->macro_lock = true;
2947 MacroData const * macro = pbuf->getMacro(
2948 name, *this, false);
2949 d->macro_lock = false;
2955 data = MacroTable::globalMacros().get(name);
2964 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2966 // set scope end behind the last paragraph
2967 DocIterator scope = par_iterator_begin();
2968 scope.pit() = scope.lastpit() + 1;
2970 return getMacro(name, scope, global);
2974 MacroData const * Buffer::getMacro(docstring const & name,
2975 Buffer const & child, bool global) const
2977 // look where the child buffer is included first
2978 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2979 if (it == d->children_positions.end())
2982 // check for macros at the inclusion position
2983 return getMacro(name, it->second, global);
2987 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2989 pit_type const lastpit = it.lastpit();
2991 // look for macros in each paragraph
2992 while (it.pit() <= lastpit) {
2993 Paragraph & par = it.paragraph();
2995 // iterate over the insets of the current paragraph
2996 InsetList const & insets = par.insetList();
2997 InsetList::const_iterator iit = insets.begin();
2998 InsetList::const_iterator end = insets.end();
2999 for (; iit != end; ++iit) {
3000 it.pos() = iit->pos;
3002 // is it a nested text inset?
3003 if (iit->inset->asInsetText()) {
3004 // Inset needs its own scope?
3005 InsetText const * itext = iit->inset->asInsetText();
3006 bool newScope = itext->isMacroScope();
3008 // scope which ends just behind the inset
3009 DocIterator insetScope = it;
3012 // collect macros in inset
3013 it.push_back(CursorSlice(*iit->inset));
3014 updateMacros(it, newScope ? insetScope : scope);
3019 if (iit->inset->asInsetTabular()) {
3020 CursorSlice slice(*iit->inset);
3021 size_t const numcells = slice.nargs();
3022 for (; slice.idx() < numcells; slice.forwardIdx()) {
3023 it.push_back(slice);
3024 updateMacros(it, scope);
3030 // is it an external file?
3031 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3032 // get buffer of external file
3033 InsetInclude const & inset =
3034 static_cast<InsetInclude const &>(*iit->inset);
3036 Buffer * child = inset.getChildBuffer();
3041 // register its position, but only when it is
3042 // included first in the buffer
3043 if (children_positions.find(child) ==
3044 children_positions.end())
3045 children_positions[child] = it;
3047 // register child with its scope
3048 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3052 InsetMath * im = iit->inset->asInsetMath();
3053 if (doing_export && im) {
3054 InsetMathHull * hull = im->asHullInset();
3056 hull->recordLocation(it);
3059 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3063 MathMacroTemplate & macroTemplate =
3064 *iit->inset->asInsetMath()->asMacroTemplate();
3065 MacroContext mc(owner_, it);
3066 macroTemplate.updateToContext(mc);
3069 bool valid = macroTemplate.validMacro();
3070 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3071 // then the BufferView's cursor will be invalid in
3072 // some cases which leads to crashes.
3077 // FIXME (Abdel), I don't understandt why we pass 'it' here
3078 // instead of 'macroTemplate' defined above... is this correct?
3079 macros[macroTemplate.name()][it] =
3080 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3090 void Buffer::updateMacros() const
3095 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3097 // start with empty table
3099 d->children_positions.clear();
3100 d->position_to_children.clear();
3102 // Iterate over buffer, starting with first paragraph
3103 // The scope must be bigger than any lookup DocIterator
3104 // later. For the global lookup, lastpit+1 is used, hence
3105 // we use lastpit+2 here.
3106 DocIterator it = par_iterator_begin();
3107 DocIterator outerScope = it;
3108 outerScope.pit() = outerScope.lastpit() + 2;
3109 d->updateMacros(it, outerScope);
3113 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3115 InsetIterator it = inset_iterator_begin(inset());
3116 InsetIterator const end = inset_iterator_end(inset());
3117 for (; it != end; ++it) {
3118 if (it->lyxCode() == BRANCH_CODE) {
3119 InsetBranch & br = static_cast<InsetBranch &>(*it);
3120 docstring const name = br.branch();
3121 if (!from_master && !params().branchlist().find(name))
3122 result.push_back(name);
3123 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3124 result.push_back(name);
3127 if (it->lyxCode() == INCLUDE_CODE) {
3128 // get buffer of external file
3129 InsetInclude const & ins =
3130 static_cast<InsetInclude const &>(*it);
3131 Buffer * child = ins.getChildBuffer();
3134 child->getUsedBranches(result, true);
3137 // remove duplicates
3142 void Buffer::updateMacroInstances(UpdateType utype) const
3144 LYXERR(Debug::MACROS, "updateMacroInstances for "
3145 << d->filename.onlyFileName());
3146 DocIterator it = doc_iterator_begin(this);
3148 DocIterator const end = doc_iterator_end(this);
3149 for (; it != end; it.forwardInset()) {
3150 // look for MathData cells in InsetMathNest insets
3151 InsetMath * minset = it.nextInset()->asInsetMath();
3155 // update macro in all cells of the InsetMathNest
3156 DocIterator::idx_type n = minset->nargs();
3157 MacroContext mc = MacroContext(this, it);
3158 for (DocIterator::idx_type i = 0; i < n; ++i) {
3159 MathData & data = minset->cell(i);
3160 data.updateMacros(0, mc, utype);
3166 void Buffer::listMacroNames(MacroNameSet & macros) const
3171 d->macro_lock = true;
3173 // loop over macro names
3174 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3175 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3176 for (; nameIt != nameEnd; ++nameIt)
3177 macros.insert(nameIt->first);
3179 // loop over children
3180 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3181 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3182 for (; it != end; ++it)
3183 it->first->listMacroNames(macros);
3186 Buffer const * const pbuf = d->parent();
3188 pbuf->listMacroNames(macros);
3190 d->macro_lock = false;
3194 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3196 Buffer const * const pbuf = d->parent();
3201 pbuf->listMacroNames(names);
3204 MacroNameSet::iterator it = names.begin();
3205 MacroNameSet::iterator end = names.end();
3206 for (; it != end; ++it) {
3208 MacroData const * data =
3209 pbuf->getMacro(*it, *this, false);
3211 macros.insert(data);
3213 // we cannot access the original MathMacroTemplate anymore
3214 // here to calls validate method. So we do its work here manually.
3215 // FIXME: somehow make the template accessible here.
3216 if (data->optionals() > 0)
3217 features.require("xargs");
3223 Buffer::References & Buffer::references(docstring const & label)
3226 return const_cast<Buffer *>(masterBuffer())->references(label);
3228 RefCache::iterator it = d->ref_cache_.find(label);
3229 if (it != d->ref_cache_.end())
3230 return it->second.second;
3232 static InsetLabel const * dummy_il = 0;
3233 static References const dummy_refs;
3234 it = d->ref_cache_.insert(
3235 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3236 return it->second.second;
3240 Buffer::References const & Buffer::references(docstring const & label) const
3242 return const_cast<Buffer *>(this)->references(label);
3246 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3248 masterBuffer()->d->ref_cache_[label].first = il;
3252 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3254 return masterBuffer()->d->ref_cache_[label].first;
3258 void Buffer::clearReferenceCache() const
3261 d->ref_cache_.clear();
3265 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
3268 //FIXME: This does not work for child documents yet.
3269 LASSERT(code == CITE_CODE, /**/);
3271 reloadBibInfoCache();
3273 // Check if the label 'from' appears more than once
3274 BiblioInfo const & keys = masterBibInfo();
3275 BiblioInfo::const_iterator bit = keys.begin();
3276 BiblioInfo::const_iterator bend = keys.end();
3277 vector<docstring> labels;
3279 for (; bit != bend; ++bit)
3281 labels.push_back(bit->first);
3283 if (count(labels.begin(), labels.end(), from) > 1)
3286 string const paramName = "key";
3287 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3288 if (it->lyxCode() == code) {
3289 InsetCommand * inset = it->asInsetCommand();
3292 docstring const oldValue = inset->getParam(paramName);
3293 if (oldValue == from)
3294 inset->setParam(paramName, to);
3300 void Buffer::getSourceCode(odocstream & os, string const format,
3301 pit_type par_begin, pit_type par_end,
3302 OutputWhat output) const
3304 OutputParams runparams(¶ms().encoding());
3305 runparams.nice = true;
3306 runparams.flavor = params().getOutputFlavor(format);
3307 runparams.linelen = lyxrc.plaintext_linelen;
3308 // No side effect of file copying and image conversion
3309 runparams.dryrun = true;
3311 if (output == CurrentParagraph) {
3312 runparams.par_begin = par_begin;
3313 runparams.par_end = par_end;
3314 if (par_begin + 1 == par_end) {
3316 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3320 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3321 convert<docstring>(par_begin),
3322 convert<docstring>(par_end - 1))
3325 // output paragraphs
3326 if (runparams.flavor == OutputParams::LYX) {
3327 Paragraph const & par = text().paragraphs()[par_begin];
3329 depth_type dt = par.getDepth();
3330 par.write(ods, params(), dt);
3331 os << from_utf8(ods.str());
3332 } else if (runparams.flavor == OutputParams::HTML) {
3334 setMathFlavor(runparams);
3335 xhtmlParagraphs(text(), *this, xs, runparams);
3336 } else if (runparams.flavor == OutputParams::TEXT) {
3338 // FIXME Handles only one paragraph, unlike the others.
3339 // Probably should have some routine with a signature like them.
3340 writePlaintextParagraph(*this,
3341 text().paragraphs()[par_begin], os, runparams, dummy);
3342 } else if (params().isDocBook()) {
3343 docbookParagraphs(text(), *this, os, runparams);
3345 // If we are previewing a paragraph, even if this is the
3346 // child of some other buffer, let's cut the link here,
3347 // so that no concurring settings from the master
3348 // (e.g. branch state) interfere (see #8101).
3349 // FIXME: Add an optional "from master" perspective.
3350 d->ignore_parent = true;
3351 // We need to validate the Buffer params' features here
3352 // in order to know if we should output polyglossia
3353 // macros (instead of babel macros)
3354 LaTeXFeatures features(*this, params(), runparams);
3355 params().validate(features);
3356 runparams.use_polyglossia = features.usePolyglossia();
3361 // latex or literate
3362 otexstream ots(os, texrow);
3365 latexParagraphs(*this, text(), ots, runparams);
3367 // Restore the parenthood
3368 d->ignore_parent = false;
3372 if (output == FullSource)
3373 os << _("Preview source code");
3374 else if (output == OnlyPreamble)
3375 os << _("Preview preamble");
3376 else if (output == OnlyBody)
3377 os << _("Preview body");
3379 if (runparams.flavor == OutputParams::LYX) {
3381 if (output == FullSource)
3383 else if (output == OnlyPreamble)
3384 params().writeFile(ods);
3385 else if (output == OnlyBody)
3387 os << from_utf8(ods.str());
3388 } else if (runparams.flavor == OutputParams::HTML) {
3389 writeLyXHTMLSource(os, runparams, output);
3390 } else if (runparams.flavor == OutputParams::TEXT) {
3391 if (output == OnlyPreamble) {
3392 os << "% "<< _("Plain text does not have a preamble.");
3394 writePlaintextFile(*this, os, runparams);
3395 } else if (params().isDocBook()) {
3396 writeDocBookSource(os, absFileName(), runparams, output);
3398 // latex or literate
3400 d->texrow.newline();
3401 d->texrow.newline();
3402 otexstream ots(os, d->texrow);
3403 writeLaTeXSource(ots, string(), runparams, output);
3409 ErrorList & Buffer::errorList(string const & type) const
3411 return d->errorLists[type];
3415 void Buffer::updateTocItem(std::string const & type,
3416 DocIterator const & dit) const
3419 d->gui_->updateTocItem(type, dit);
3423 void Buffer::structureChanged() const
3426 d->gui_->structureChanged();
3430 void Buffer::errors(string const & err, bool from_master) const
3433 d->gui_->errors(err, from_master);
3437 void Buffer::message(docstring const & msg) const
3440 d->gui_->message(msg);
3444 void Buffer::setBusy(bool on) const
3447 d->gui_->setBusy(on);
3451 void Buffer::updateTitles() const
3454 d->wa_->updateTitles();
3458 void Buffer::resetAutosaveTimers() const
3461 d->gui_->resetAutosaveTimers();
3465 bool Buffer::hasGuiDelegate() const
3471 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3480 class AutoSaveBuffer : public ForkedProcess {
3483 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3484 : buffer_(buffer), fname_(fname) {}
3486 virtual shared_ptr<ForkedProcess> clone() const
3488 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3493 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3494 from_utf8(fname_.absFileName())));
3495 return run(DontWait);
3499 virtual int generateChild();
3501 Buffer const & buffer_;
3506 int AutoSaveBuffer::generateChild()
3508 #if defined(__APPLE__)
3509 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3510 * We should use something else like threads.
3512 * Since I do not know how to determine at run time what is the OS X
3513 * version, I just disable forking altogether for now (JMarc)
3515 pid_t const pid = -1;
3517 // tmp_ret will be located (usually) in /tmp
3518 // will that be a problem?
3519 // Note that this calls ForkedCalls::fork(), so it's
3520 // ok cross-platform.
3521 pid_t const pid = fork();
3522 // If you want to debug the autosave
3523 // you should set pid to -1, and comment out the fork.
3524 if (pid != 0 && pid != -1)
3528 // pid = -1 signifies that lyx was unable
3529 // to fork. But we will do the save
3531 bool failed = false;
3532 FileName const tmp_ret = FileName::tempName("lyxauto");
3533 if (!tmp_ret.empty()) {
3534 buffer_.writeFile(tmp_ret);
3535 // assume successful write of tmp_ret
3536 if (!tmp_ret.moveTo(fname_))
3542 // failed to write/rename tmp_ret so try writing direct
3543 if (!buffer_.writeFile(fname_)) {
3544 // It is dangerous to do this in the child,
3545 // but safe in the parent, so...
3546 if (pid == -1) // emit message signal.
3547 buffer_.message(_("Autosave failed!"));
3551 if (pid == 0) // we are the child so...
3560 FileName Buffer::getEmergencyFileName() const
3562 return FileName(d->filename.absFileName() + ".emergency");
3566 FileName Buffer::getAutosaveFileName() const
3568 // if the document is unnamed try to save in the backup dir, else
3569 // in the default document path, and as a last try in the filePath,
3570 // which will most often be the temporary directory
3573 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3574 : lyxrc.backupdir_path;
3575 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3578 string const fname = "#" + d->filename.onlyFileName() + "#";
3580 return makeAbsPath(fname, fpath);
3584 void Buffer::removeAutosaveFile() const
3586 FileName const f = getAutosaveFileName();
3592 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3594 FileName const newauto = getAutosaveFileName();
3596 if (newauto != oldauto && oldauto.exists())
3597 if (!oldauto.moveTo(newauto))
3598 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3602 bool Buffer::autoSave() const
3604 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3605 if (buf->d->bak_clean || isReadonly())
3608 message(_("Autosaving current document..."));
3609 buf->d->bak_clean = true;
3611 FileName const fname = getAutosaveFileName();
3612 if (d->cloned_buffer_) {
3613 // If this buffer is cloned, we assume that
3614 // we are running in a separate thread already.
3615 FileName const tmp_ret = FileName::tempName("lyxauto");
3616 if (!tmp_ret.empty()) {
3618 // assume successful write of tmp_ret
3619 if (tmp_ret.moveTo(fname))
3622 // failed to write/rename tmp_ret so try writing direct
3623 return writeFile(fname);
3625 /// This function is deprecated as the frontend needs to take care
3626 /// of cloning the buffer and autosaving it in another thread. It
3627 /// is still here to allow (QT_VERSION < 0x040400).
3628 AutoSaveBuffer autosave(*this, fname);
3635 // helper class, to guarantee this gets reset properly
3636 class Buffer::MarkAsExporting {
3638 MarkAsExporting(Buffer const * buf) : buf_(buf)
3640 LASSERT(buf_, /* */);
3641 buf_->setExportStatus(true);
3645 buf_->setExportStatus(false);
3648 Buffer const * const buf_;
3653 void Buffer::setExportStatus(bool e) const
3655 d->doing_export = e;
3656 ListOfBuffers clist = getDescendents();
3657 ListOfBuffers::const_iterator cit = clist.begin();
3658 ListOfBuffers::const_iterator const cen = clist.end();
3659 for (; cit != cen; ++cit)
3660 (*cit)->d->doing_export = e;
3664 bool Buffer::isExporting() const
3666 return d->doing_export;
3670 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3674 return doExport(target, put_in_tempdir, result_file);
3677 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3678 string & result_file) const
3680 bool const update_unincluded =
3681 params().maintain_unincluded_children
3682 && !params().getIncludedChildren().empty();
3684 // (1) export with all included children (omit \includeonly)
3685 if (update_unincluded) {
3686 ExportStatus const status =
3687 doExport(target, put_in_tempdir, true, result_file);
3688 if (status != ExportSuccess)
3691 // (2) export with included children only
3692 return doExport(target, put_in_tempdir, false, result_file);
3696 void Buffer::setMathFlavor(OutputParams & op) const
3698 switch (params().html_math_output) {
3699 case BufferParams::MathML:
3700 op.math_flavor = OutputParams::MathAsMathML;
3702 case BufferParams::HTML:
3703 op.math_flavor = OutputParams::MathAsHTML;
3705 case BufferParams::Images:
3706 op.math_flavor = OutputParams::MathAsImages;
3708 case BufferParams::LaTeX:
3709 op.math_flavor = OutputParams::MathAsLaTeX;
3715 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3716 bool includeall, string & result_file) const
3718 LYXERR(Debug::FILES, "target=" << target);
3719 OutputParams runparams(¶ms().encoding());
3720 string format = target;
3721 string dest_filename;
3722 size_t pos = target.find(' ');
3723 if (pos != string::npos) {
3724 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3725 format = target.substr(0, pos);
3726 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3727 FileName(dest_filename).onlyPath().createPath();
3728 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3730 MarkAsExporting exporting(this);
3731 string backend_format;
3732 runparams.flavor = OutputParams::LATEX;
3733 runparams.linelen = lyxrc.plaintext_linelen;
3734 runparams.includeall = includeall;
3735 vector<string> backs = params().backends();
3736 Converters converters = theConverters();
3737 bool need_nice_file = false;
3738 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3739 // Get shortest path to format
3740 converters.buildGraph();
3741 Graph::EdgePath path;
3742 for (vector<string>::const_iterator it = backs.begin();
3743 it != backs.end(); ++it) {
3744 Graph::EdgePath p = converters.getPath(*it, format);
3745 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3746 backend_format = *it;
3751 if (!put_in_tempdir) {
3752 // Only show this alert if this is an export to a non-temporary
3753 // file (not for previewing).
3754 Alert::error(_("Couldn't export file"), bformat(
3755 _("No information for exporting the format %1$s."),
3756 formats.prettyName(format)));
3758 return ExportNoPathToFormat;
3760 runparams.flavor = converters.getFlavor(path, this);
3761 Graph::EdgePath::const_iterator it = path.begin();
3762 Graph::EdgePath::const_iterator en = path.end();
3763 for (; it != en; ++it)
3764 if (theConverters().get(*it).nice) {
3765 need_nice_file = true;
3770 backend_format = format;
3771 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3772 // FIXME: Don't hardcode format names here, but use a flag
3773 if (backend_format == "pdflatex")
3774 runparams.flavor = OutputParams::PDFLATEX;
3775 else if (backend_format == "luatex")
3776 runparams.flavor = OutputParams::LUATEX;
3777 else if (backend_format == "dviluatex")
3778 runparams.flavor = OutputParams::DVILUATEX;
3779 else if (backend_format == "xetex")
3780 runparams.flavor = OutputParams::XETEX;
3783 string filename = latexName(false);
3784 filename = addName(temppath(), filename);
3785 filename = changeExtension(filename,
3786 formats.extension(backend_format));
3787 LYXERR(Debug::FILES, "filename=" << filename);
3789 // Plain text backend
3790 if (backend_format == "text") {
3791 runparams.flavor = OutputParams::TEXT;
3792 writePlaintextFile(*this, FileName(filename), runparams);
3795 else if (backend_format == "xhtml") {
3796 runparams.flavor = OutputParams::HTML;
3797 setMathFlavor(runparams);
3798 makeLyXHTMLFile(FileName(filename), runparams);
3799 } else if (backend_format == "lyx")
3800 writeFile(FileName(filename));
3802 else if (params().isDocBook()) {
3803 runparams.nice = !put_in_tempdir;
3804 makeDocBookFile(FileName(filename), runparams);
3807 else if (backend_format == format || need_nice_file) {
3808 runparams.nice = true;
3809 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
3810 if (d->cloned_buffer_)
3811 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3814 } else if (!lyxrc.tex_allows_spaces
3815 && contains(filePath(), ' ')) {
3816 Alert::error(_("File name error"),
3817 _("The directory path to the document cannot contain spaces."));
3818 return ExportTexPathHasSpaces;
3820 runparams.nice = false;
3821 bool const success = makeLaTeXFile(
3822 FileName(filename), filePath(), runparams);
3823 if (d->cloned_buffer_)
3824 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3829 string const error_type = (format == "program")
3830 ? "Build" : params().bufferFormat();
3831 ErrorList & error_list = d->errorLists[error_type];
3832 string const ext = formats.extension(format);
3833 FileName const tmp_result_file(changeExtension(filename, ext));
3834 bool const success = converters.convert(this, FileName(filename),
3835 tmp_result_file, FileName(absFileName()), backend_format, format,
3838 // Emit the signal to show the error list or copy it back to the
3839 // cloned Buffer so that it can be emitted afterwards.
3840 if (format != backend_format) {
3841 if (d->cloned_buffer_) {
3842 d->cloned_buffer_->d->errorLists[error_type] =
3843 d->errorLists[error_type];
3846 // also to the children, in case of master-buffer-view
3847 ListOfBuffers clist = getDescendents();
3848 ListOfBuffers::const_iterator cit = clist.begin();
3849 ListOfBuffers::const_iterator const cen = clist.end();
3850 for (; cit != cen; ++cit) {
3851 if (d->cloned_buffer_) {
3852 // Enable reverse search by copying back the
3853 // texrow object to the cloned buffer.
3854 // FIXME: this is not thread safe.
3855 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3856 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3857 (*cit)->d->errorLists[error_type];
3859 (*cit)->errors(error_type, true);
3863 if (d->cloned_buffer_) {
3864 // Enable reverse dvi or pdf to work by copying back the texrow
3865 // object to the cloned buffer.
3866 // FIXME: There is a possibility of concurrent access to texrow
3867 // here from the main GUI thread that should be securized.
3868 d->cloned_buffer_->d->texrow = d->texrow;
3869 string const error_type = params().bufferFormat();
3870 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3874 return ExportConverterError;
3876 if (put_in_tempdir) {
3877 result_file = tmp_result_file.absFileName();
3878 return ExportSuccess;
3881 if (dest_filename.empty())
3882 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3884 result_file = dest_filename;
3885 // We need to copy referenced files (e. g. included graphics
3886 // if format == "dvi") to the result dir.
3887 vector<ExportedFile> const files =
3888 runparams.exportdata->externalFiles(format);
3889 string const dest = runparams.export_folder.empty() ?
3890 onlyPath(result_file) : runparams.export_folder;
3891 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3892 : force_overwrite == ALL_FILES;
3893 CopyStatus status = use_force ? FORCE : SUCCESS;
3895 vector<ExportedFile>::const_iterator it = files.begin();
3896 vector<ExportedFile>::const_iterator const en = files.end();
3897 for (; it != en && status != CANCEL; ++it) {
3898 string const fmt = formats.getFormatFromFile(it->sourceName);
3899 string fixedName = it->exportName;
3900 if (!runparams.export_folder.empty()) {
3901 // Relative pathnames starting with ../ will be sanitized
3902 // if exporting to a different folder
3903 while (fixedName.substr(0, 3) == "../")
3904 fixedName = fixedName.substr(3, fixedName.length() - 3);
3906 FileName fixedFileName = makeAbsPath(fixedName, dest);
3907 fixedFileName.onlyPath().createPath();
3908 status = copyFile(fmt, it->sourceName,
3910 it->exportName, status == FORCE,
3911 runparams.export_folder.empty());
3914 if (status == CANCEL) {
3915 message(_("Document export cancelled."));
3916 return ExportCancel;
3919 if (tmp_result_file.exists()) {
3920 // Finally copy the main file
3921 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3922 : force_overwrite != NO_FILES;
3923 if (status == SUCCESS && use_force)
3925 status = copyFile(format, tmp_result_file,
3926 FileName(result_file), result_file,
3928 if (status == CANCEL) {
3929 message(_("Document export cancelled."));
3930 return ExportCancel;
3932 message(bformat(_("Document exported as %1$s "
3934 formats.prettyName(format),
3935 makeDisplayPath(result_file)));
3938 // This must be a dummy converter like fax (bug 1888)
3939 message(bformat(_("Document exported as %1$s"),
3940 formats.prettyName(format)));
3943 return ExportSuccess;
3947 Buffer::ExportStatus Buffer::preview(string const & format) const
3949 bool const update_unincluded =
3950 params().maintain_unincluded_children
3951 && !params().getIncludedChildren().empty();
3952 return preview(format, update_unincluded);
3955 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
3957 MarkAsExporting exporting(this);
3959 // (1) export with all included children (omit \includeonly)
3961 ExportStatus const status = doExport(format, true, true, result_file);
3962 if (status != ExportSuccess)
3965 // (2) export with included children only
3966 ExportStatus const status = doExport(format, true, false, result_file);
3967 if (status != ExportSuccess)
3969 if (!formats.view(*this, FileName(result_file), format))
3970 return PreviewError;
3971 return PreviewSuccess;
3975 Buffer::ReadStatus Buffer::extractFromVC()
3977 bool const found = LyXVC::file_not_found_hook(d->filename);
3979 return ReadFileNotFound;
3980 if (!d->filename.isReadableFile())
3986 Buffer::ReadStatus Buffer::loadEmergency()
3988 FileName const emergencyFile = getEmergencyFileName();
3989 if (!emergencyFile.exists()
3990 || emergencyFile.lastModified() <= d->filename.lastModified())
3991 return ReadFileNotFound;
3993 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3994 docstring const text = bformat(_("An emergency save of the document "
3995 "%1$s exists.\n\nRecover emergency save?"), file);
3997 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
3998 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4004 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4005 bool const success = (ret_llf == ReadSuccess);
4008 Alert::warning(_("File is read-only"),
4009 bformat(_("An emergency file is successfully loaded, "
4010 "but the original file %1$s is marked read-only. "
4011 "Please make sure to save the document as a different "
4012 "file."), from_utf8(d->filename.absFileName())));
4015 str = _("Document was successfully recovered.");
4017 str = _("Document was NOT successfully recovered.");
4018 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4019 makeDisplayPath(emergencyFile.absFileName()));
4021 int const del_emerg =
4022 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4023 _("&Remove"), _("&Keep"));
4024 if (del_emerg == 0) {
4025 emergencyFile.removeFile();
4027 Alert::warning(_("Emergency file deleted"),
4028 _("Do not forget to save your file now!"), true);
4030 return success ? ReadSuccess : ReadEmergencyFailure;
4033 int const del_emerg =
4034 Alert::prompt(_("Delete emergency file?"),
4035 _("Remove emergency file now?"), 1, 1,
4036 _("&Remove"), _("&Keep"));
4038 emergencyFile.removeFile();
4039 return ReadOriginal;
4049 Buffer::ReadStatus Buffer::loadAutosave()
4051 // Now check if autosave file is newer.
4052 FileName const autosaveFile = getAutosaveFileName();
4053 if (!autosaveFile.exists()
4054 || autosaveFile.lastModified() <= d->filename.lastModified())
4055 return ReadFileNotFound;
4057 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4058 docstring const text = bformat(_("The backup of the document %1$s "
4059 "is newer.\n\nLoad the backup instead?"), file);
4060 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4061 _("&Load backup"), _("Load &original"), _("&Cancel"));
4066 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4067 // the file is not saved if we load the autosave file.
4068 if (ret_llf == ReadSuccess) {
4070 Alert::warning(_("File is read-only"),
4071 bformat(_("A backup file is successfully loaded, "
4072 "but the original file %1$s is marked read-only. "
4073 "Please make sure to save the document as a "
4075 from_utf8(d->filename.absFileName())));
4080 return ReadAutosaveFailure;
4083 // Here we delete the autosave
4084 autosaveFile.removeFile();
4085 return ReadOriginal;
4093 Buffer::ReadStatus Buffer::loadLyXFile()
4095 if (!d->filename.isReadableFile()) {
4096 ReadStatus const ret_rvc = extractFromVC();
4097 if (ret_rvc != ReadSuccess)
4101 ReadStatus const ret_re = loadEmergency();
4102 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4105 ReadStatus const ret_ra = loadAutosave();
4106 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4109 return loadThisLyXFile(d->filename);
4113 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4115 return readFile(fn);
4119 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4121 TeXErrors::Errors::const_iterator it = terr.begin();
4122 TeXErrors::Errors::const_iterator end = terr.end();
4123 ListOfBuffers clist = getDescendents();
4124 ListOfBuffers::const_iterator cen = clist.end();
4126 for (; it != end; ++it) {
4129 int errorRow = it->error_in_line;
4130 Buffer const * buf = 0;
4132 if (it->child_name.empty())
4133 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4135 // The error occurred in a child
4136 ListOfBuffers::const_iterator cit = clist.begin();
4137 for (; cit != cen; ++cit) {
4138 string const child_name =
4139 DocFileName(changeExtension(
4140 (*cit)->absFileName(), "tex")).
4142 if (it->child_name != child_name)
4144 (*cit)->d->texrow.getIdFromRow(errorRow,
4145 id_start, pos_start);
4146 if (id_start != -1) {
4147 buf = d->cloned_buffer_
4148 ? (*cit)->d->cloned_buffer_->d->owner_
4149 : (*cit)->d->owner_;
4160 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4161 } while (found && id_start == id_end && pos_start == pos_end);
4163 if (id_start != id_end) {
4164 // Next registered position is outside the inset where
4165 // the error occurred, so signal end-of-paragraph
4169 errorList.push_back(ErrorItem(it->error_desc,
4170 it->error_text, id_start, pos_start, pos_end, buf));
4175 void Buffer::setBuffersForInsets() const
4177 inset().setBuffer(const_cast<Buffer &>(*this));
4181 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4183 // Use the master text class also for child documents
4184 Buffer const * const master = masterBuffer();
4185 DocumentClass const & textclass = master->params().documentClass();
4187 // do this only if we are the top-level Buffer
4189 reloadBibInfoCache();
4191 // keep the buffers to be children in this set. If the call from the
4192 // master comes back we can see which of them were actually seen (i.e.
4193 // via an InsetInclude). The remaining ones in the set need still be updated.
4194 static std::set<Buffer const *> bufToUpdate;
4195 if (scope == UpdateMaster) {
4196 // If this is a child document start with the master
4197 if (master != this) {
4198 bufToUpdate.insert(this);
4199 master->updateBuffer(UpdateMaster, utype);
4200 // Do this here in case the master has no gui associated with it. Then,
4201 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
4202 if (!master->d->gui_)
4205 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4206 if (bufToUpdate.find(this) == bufToUpdate.end())
4210 // start over the counters in the master
4211 textclass.counters().reset();
4214 // update will be done below for this buffer
4215 bufToUpdate.erase(this);
4217 // update all caches
4218 clearReferenceCache();
4221 Buffer & cbuf = const_cast<Buffer &>(*this);
4223 LASSERT(!text().paragraphs().empty(), /**/);
4226 ParIterator parit = cbuf.par_iterator_begin();
4227 updateBuffer(parit, utype);
4230 // TocBackend update will be done later.
4233 d->bibinfo_cache_valid_ = true;
4234 d->cite_labels_valid_ = true;
4235 cbuf.tocBackend().update();
4236 if (scope == UpdateMaster)
4237 cbuf.structureChanged();
4241 static depth_type getDepth(DocIterator const & it)
4243 depth_type depth = 0;
4244 for (size_t i = 0 ; i < it.depth() ; ++i)
4245 if (!it[i].inset().inMathed())
4246 depth += it[i].paragraph().getDepth() + 1;
4247 // remove 1 since the outer inset does not count
4251 static depth_type getItemDepth(ParIterator const & it)
4253 Paragraph const & par = *it;
4254 LabelType const labeltype = par.layout().labeltype;
4256 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4259 // this will hold the lowest depth encountered up to now.
4260 depth_type min_depth = getDepth(it);
4261 ParIterator prev_it = it;
4264 --prev_it.top().pit();
4266 // start of nested inset: go to outer par
4268 if (prev_it.empty()) {
4269 // start of document: nothing to do
4274 // We search for the first paragraph with same label
4275 // that is not more deeply nested.
4276 Paragraph & prev_par = *prev_it;
4277 depth_type const prev_depth = getDepth(prev_it);
4278 if (labeltype == prev_par.layout().labeltype) {
4279 if (prev_depth < min_depth)
4280 return prev_par.itemdepth + 1;
4281 if (prev_depth == min_depth)
4282 return prev_par.itemdepth;
4284 min_depth = min(min_depth, prev_depth);
4285 // small optimization: if we are at depth 0, we won't
4286 // find anything else
4287 if (prev_depth == 0)
4293 static bool needEnumCounterReset(ParIterator const & it)
4295 Paragraph const & par = *it;
4296 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
4297 depth_type const cur_depth = par.getDepth();
4298 ParIterator prev_it = it;
4299 while (prev_it.pit()) {
4300 --prev_it.top().pit();
4301 Paragraph const & prev_par = *prev_it;
4302 if (prev_par.getDepth() <= cur_depth)
4303 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4305 // start of nested inset: reset
4310 // set the label of a paragraph. This includes the counters.
4311 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4313 BufferParams const & bp = owner_->masterBuffer()->params();
4314 DocumentClass const & textclass = bp.documentClass();
4315 Paragraph & par = it.paragraph();
4316 Layout const & layout = par.layout();
4317 Counters & counters = textclass.counters();
4319 if (par.params().startOfAppendix()) {
4320 // We want to reset the counter corresponding to toplevel sectioning
4321 Layout const & lay = textclass.getTOCLayout();
4322 docstring const cnt = lay.counter;
4324 counters.reset(cnt);
4325 counters.appendix(true);
4327 par.params().appendix(counters.appendix());
4329 // Compute the item depth of the paragraph
4330 par.itemdepth = getItemDepth(it);
4332 if (layout.margintype == MARGIN_MANUAL) {
4333 if (par.params().labelWidthString().empty())
4334 par.params().labelWidthString(par.expandLabel(layout, bp));
4335 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4336 // we do not need to do anything here, since the empty case is
4337 // handled during export.
4339 par.params().labelWidthString(docstring());
4342 switch(layout.labeltype) {
4344 if (layout.toclevel <= bp.secnumdepth
4345 && (layout.latextype != LATEX_ENVIRONMENT
4346 || it.text()->isFirstInSequence(it.pit()))) {
4347 if (counters.hasCounter(layout.counter))
4348 counters.step(layout.counter, utype);
4349 par.params().labelString(par.expandLabel(layout, bp));
4351 par.params().labelString(docstring());
4354 case LABEL_ITEMIZE: {
4355 // At some point of time we should do something more
4356 // clever here, like:
4357 // par.params().labelString(
4358 // bp.user_defined_bullet(par.itemdepth).getText());
4359 // for now, use a simple hardcoded label
4360 docstring itemlabel;
4361 switch (par.itemdepth) {
4363 itemlabel = char_type(0x2022);
4366 itemlabel = char_type(0x2013);
4369 itemlabel = char_type(0x2217);
4372 itemlabel = char_type(0x2219); // or 0x00b7
4375 par.params().labelString(itemlabel);
4379 case LABEL_ENUMERATE: {
4380 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4382 switch (par.itemdepth) {
4391 enumcounter += "iv";
4394 // not a valid enumdepth...
4398 // Maybe we have to reset the enumeration counter.
4399 if (needEnumCounterReset(it))
4400 counters.reset(enumcounter);
4401 counters.step(enumcounter, utype);
4403 string const & lang = par.getParLanguage(bp)->code();
4404 par.params().labelString(counters.theCounter(enumcounter, lang));
4409 case LABEL_SENSITIVE: {
4410 string const & type = counters.current_float();
4411 docstring full_label;
4413 full_label = owner_->B_("Senseless!!! ");
4415 docstring name = owner_->B_(textclass.floats().getType(type).name());
4416 if (counters.hasCounter(from_utf8(type))) {
4417 string const & lang = par.getParLanguage(bp)->code();
4418 counters.step(from_utf8(type), utype);
4419 full_label = bformat(from_ascii("%1$s %2$s:"),
4421 counters.theCounter(from_utf8(type), lang));
4423 full_label = bformat(from_ascii("%1$s #:"), name);
4425 par.params().labelString(full_label);
4429 case LABEL_NO_LABEL:
4430 par.params().labelString(docstring());
4434 case LABEL_TOP_ENVIRONMENT:
4435 case LABEL_CENTERED_TOP_ENVIRONMENT:
4438 par.params().labelString(par.expandLabel(layout, bp));
4444 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4446 LASSERT(parit.pit() == 0, /**/);
4448 // Set the position of the text in the buffer to be able
4449 // to resolve macros in it.
4450 parit.text()->setMacrocontextPosition(parit);
4452 depth_type maxdepth = 0;
4453 pit_type const lastpit = parit.lastpit();
4454 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4455 // reduce depth if necessary
4456 if (parit->params().depth() > maxdepth) {
4457 /** FIXME: this function is const, but
4458 * nevertheless it modifies the buffer. To be
4459 * cleaner, one should modify the buffer in
4460 * another function, which is actually
4461 * non-const. This would however be costly in
4462 * terms of code duplication.
4464 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4465 parit->params().depth(maxdepth);
4467 maxdepth = parit->getMaxDepthAfter();
4469 if (utype == OutputUpdate) {
4470 // track the active counters
4471 // we have to do this for the master buffer, since the local
4472 // buffer isn't tracking anything.
4473 masterBuffer()->params().documentClass().counters().
4474 setActiveLayout(parit->layout());
4477 // set the counter for this paragraph
4478 d->setLabel(parit, utype);
4481 InsetList::const_iterator iit = parit->insetList().begin();
4482 InsetList::const_iterator end = parit->insetList().end();
4483 for (; iit != end; ++iit) {
4484 parit.pos() = iit->pos;
4485 iit->inset->updateBuffer(parit, utype);
4491 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4492 WordLangTuple & word_lang, docstring_list & suggestions) const
4496 suggestions.clear();
4497 word_lang = WordLangTuple();
4498 bool const to_end = to.empty();
4499 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4500 // OK, we start from here.
4501 for (; from != end; from.forwardPos()) {
4502 // We are only interested in text so remove the math CursorSlice.
4503 while (from.inMathed()) {
4507 // If from is at the end of the document (which is possible
4508 // when leaving the mathed) LyX will crash later otherwise.
4509 if (from.atEnd() || (!to_end && from >= end))
4512 from.paragraph().spellCheck();
4513 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4514 if (SpellChecker::misspelled(res)) {
4519 // Do not increase progress when from == to, otherwise the word
4520 // count will be wrong.
4530 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4532 bool inword = false;
4537 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4538 if (!dit.inTexted()) {
4543 Paragraph const & par = dit.paragraph();
4544 pos_type const pos = dit.pos();
4546 // Copied and adapted from isWordSeparator() in Paragraph
4547 if (pos == dit.lastpos()) {
4550 Inset const * ins = par.getInset(pos);
4551 if (ins && skipNoOutput && !ins->producesOutput()) {
4554 // stop if end of range was skipped
4555 if (!to.atEnd() && dit >= to)
4558 } else if (!par.isDeleted(pos)) {
4559 if (par.isWordSeparator(pos))
4565 if (ins && ins->isLetter())
4567 else if (ins && ins->isSpace())
4570 char_type const c = par.getChar(pos);
4571 if (isPrintableNonspace(c))
4573 else if (isSpace(c))
4583 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4585 d->updateStatistics(from, to, skipNoOutput);
4589 int Buffer::wordCount() const
4591 return d->wordCount();
4595 int Buffer::charCount(bool with_blanks) const
4597 return d->charCount(with_blanks);
4601 Buffer::ReadStatus Buffer::reload(bool clearUndo)
4604 // c.f. bug http://www.lyx.org/trac/ticket/6587
4605 removeAutosaveFile();
4606 // e.g., read-only status could have changed due to version control
4607 d->filename.refresh();
4608 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4610 // clear parent. this will get reset if need be.
4612 ReadStatus const status = loadLyXFile();
4613 if (status == ReadSuccess) {
4618 message(bformat(_("Document %1$s reloaded."), disp_fn));
4622 message(bformat(_("Could not reload document %1$s."), disp_fn));
4632 bool Buffer::saveAs(FileName const & fn)
4634 FileName const old_name = fileName();
4635 FileName const old_auto = getAutosaveFileName();
4636 bool const old_unnamed = isUnnamed();
4643 // bring the autosave file with us, just in case.
4644 moveAutosaveFile(old_auto);
4645 // validate version control data and
4646 // correct buffer title
4647 lyxvc().file_found_hook(fileName());
4649 // the file has now been saved to the new location.
4650 // we need to check that the locations of child buffers
4652 checkChildBuffers();
4653 checkMasterBuffer();
4657 // reset the old filename and unnamed state
4658 setFileName(old_name);
4659 setUnnamed(old_unnamed);
4665 // FIXME We could do better here, but it is complicated. What would be
4666 // nice is to offer either (a) to save the child buffer to an appropriate
4667 // location, so that it would "move with the master", or else (b) to update
4668 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4669 // complicated, because the code for this lives in GuiView.
4670 void Buffer::checkChildBuffers()
4672 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4673 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4674 for (; it != en; ++it) {
4675 DocIterator dit = it->second;
4676 Buffer * cbuf = const_cast<Buffer *>(it->first);
4677 if (!cbuf || !theBufferList().isLoaded(cbuf))
4679 Inset * inset = dit.nextInset();
4680 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4681 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4682 docstring const & incfile = inset_inc->getParam("filename");
4683 string oldloc = cbuf->absFileName();
4684 string newloc = makeAbsPath(to_utf8(incfile),
4685 onlyPath(absFileName())).absFileName();
4686 if (oldloc == newloc)
4688 // the location of the child file is incorrect.
4689 Alert::warning(_("Included File Invalid"),
4690 bformat(_("Saving this document to a new location has made the file:\n"
4692 "inaccessible. You will need to update the included filename."),
4693 from_utf8(oldloc)));
4695 inset_inc->setChildBuffer(0);
4697 // invalidate cache of children
4698 d->children_positions.clear();
4699 d->position_to_children.clear();
4703 // If a child has been saved under a different name/path, it might have been
4704 // orphaned. Therefore the master needs to be reset (bug 8161).
4705 void Buffer::checkMasterBuffer()
4707 Buffer const * const master = masterBuffer();
4711 // necessary to re-register the child (bug 5873)
4712 // FIXME: clean up updateMacros (here, only
4713 // child registering is needed).
4714 master->updateMacros();
4715 // (re)set master as master buffer, but only
4716 // if we are a real child
4717 if (master->isChild(this))