3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
28 #include "CutAndPaste.h"
29 #include "DispatchResult.h"
30 #include "DocIterator.h"
31 #include "BufferEncodings.h"
32 #include "ErrorList.h"
35 #include "FuncRequest.h"
36 #include "FuncStatus.h"
37 #include "IndicesList.h"
38 #include "InsetIterator.h"
39 #include "InsetList.h"
41 #include "LaTeXFeatures.h"
45 #include "LyXAction.h"
49 #include "output_docbook.h"
51 #include "output_latex.h"
52 #include "output_xhtml.h"
53 #include "output_plaintext.h"
54 #include "Paragraph.h"
55 #include "ParagraphParameters.h"
56 #include "ParIterator.h"
57 #include "PDFOptions.h"
58 #include "SpellChecker.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
65 #include "VCBackend.h"
67 #include "WordLangTuple.h"
70 #include "insets/InsetBibtex.h"
71 #include "insets/InsetBranch.h"
72 #include "insets/InsetInclude.h"
73 #include "insets/InsetTabular.h"
74 #include "insets/InsetText.h"
76 #include "mathed/InsetMathHull.h"
77 #include "mathed/MacroTable.h"
78 #include "mathed/MathMacroTemplate.h"
79 #include "mathed/MathSupport.h"
81 #include "graphics/PreviewLoader.h"
83 #include "frontends/alert.h"
84 #include "frontends/Delegates.h"
85 #include "frontends/WorkAreaManager.h"
87 #include "support/lassert.h"
88 #include "support/convert.h"
89 #include "support/debug.h"
90 #include "support/docstring_list.h"
91 #include "support/ExceptionMessage.h"
92 #include "support/FileName.h"
93 #include "support/FileNameList.h"
94 #include "support/filetools.h"
95 #include "support/ForkedCalls.h"
96 #include "support/gettext.h"
97 #include "support/gzstream.h"
98 #include "support/lstrings.h"
99 #include "support/lyxalgo.h"
100 #include "support/mutex.h"
101 #include "support/os.h"
102 #include "support/Package.h"
103 #include "support/PathChanger.h"
104 #include "support/Systemcall.h"
105 #include "support/TempFile.h"
106 #include "support/textutils.h"
107 #include "support/types.h"
109 #include "support/bind.h"
110 #include "support/shared_ptr.h"
121 using namespace lyx::support;
122 using namespace lyx::graphics;
126 namespace Alert = frontend::Alert;
127 namespace os = support::os;
131 int const LYX_FORMAT = LYX_FORMAT_LYX;
133 typedef map<string, bool> DepClean;
134 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
136 void showPrintError(string const & name)
138 docstring str = bformat(_("Could not print the document %1$s.\n"
139 "Check that your printer is set up correctly."),
140 makeDisplayPath(name, 50));
141 Alert::error(_("Print document failed"), str);
147 // A storehouse for the cloned buffers.
148 list<CloneList *> cloned_buffers;
154 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
158 delete preview_loader_;
166 /// search for macro in local (buffer) table or in children
167 MacroData const * getBufferMacro(docstring const & name,
168 DocIterator const & pos) const;
170 /// Update macro table starting with position of it \param it in some
172 void updateMacros(DocIterator & it, DocIterator & scope);
174 void setLabel(ParIterator & it, UpdateType utype) const;
176 /** If we have branches that use the file suffix
177 feature, return the file name with suffix appended.
179 support::FileName exportFileName() const;
186 mutable TexRow texrow;
188 /// need to regenerate .tex?
192 mutable bool lyx_clean;
194 /// is autosave needed?
195 mutable bool bak_clean;
197 /// is this an unnamed file (New...)?
200 /// is this an internal bufffer?
201 bool internal_buffer;
206 /// name of the file the buffer is associated with.
209 /** Set to true only when the file is fully loaded.
210 * Used to prevent the premature generation of previews
211 * and by the citation inset.
213 bool file_fully_loaded;
215 /// Ignore the parent (e.g. when exporting a child standalone)?
219 mutable TocBackend toc_backend;
224 ScopeMacro(DocIterator const & s, MacroData const & m)
225 : scope(s), macro(m) {}
229 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
230 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
231 /// map from the macro name to the position map,
232 /// which maps the macro definition position to the scope and the MacroData.
233 NamePositionScopeMacroMap macros;
234 /// This seem to change the way Buffer::getMacro() works
235 mutable bool macro_lock;
237 /// positions of child buffers in the buffer
238 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
241 ScopeBuffer(DocIterator const & s,Buffer const * b)
242 : scope(s), buffer(b) {}
244 Buffer const * buffer;
246 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
247 /// position of children buffers in this buffer
248 BufferPositionMap children_positions;
249 /// map from children inclusion positions to their scope and their buffer
250 PositionScopeBufferMap position_to_children;
252 /// Contains the old buffer filePath() while saving-as, or the
253 /// directory where the document was last saved while loading.
256 /** Keeps track of the path of local layout files.
257 * If possible, it is always relative to the buffer path.
258 * Empty for layouts in system or user directory.
260 string layout_position;
262 /// Container for all sort of Buffer dependant errors.
263 map<string, ErrorList> errorLists;
265 /// timestamp and checksum used to test if the file has been externally
266 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
268 unsigned long checksum_;
271 frontend::WorkAreaManager * wa_;
273 frontend::GuiBufferDelegate * gui_;
278 /// A cache for the bibfiles (including bibfiles of loaded child
279 /// documents), needed for appropriate update of natbib labels.
280 mutable support::FileNameList bibfiles_cache_;
282 // FIXME The caching mechanism could be improved. At present, we have a
283 // cache for each Buffer, that caches all the bibliography info for that
284 // Buffer. A more efficient solution would be to have a global cache per
285 // file, and then to construct the Buffer's bibinfo from that.
286 /// A cache for bibliography info
287 mutable BiblioInfo bibinfo_;
288 /// whether the bibinfo cache is valid
289 mutable bool bibinfo_cache_valid_;
290 /// whether the bibfile cache is valid
291 mutable bool bibfile_cache_valid_;
292 /// Cache of timestamps of .bib files
293 map<FileName, time_t> bibfile_status_;
294 /// Indicates whether the bibinfo has changed since the last time
295 /// we ran updateBuffer(), i.e., whether citation labels may need
297 mutable bool cite_labels_valid_;
299 /// These two hold the file name and format, written to by
300 /// Buffer::preview and read from by LFUN_BUFFER_VIEW_CACHE.
301 FileName preview_file_;
302 string preview_format_;
303 /// If there was an error when previewing, on the next preview we do
304 /// a fresh compile (e.g. in case the user installed a package that
308 mutable RefCache ref_cache_;
310 /// our Text that should be wrapped in an InsetText
314 PreviewLoader * preview_loader_;
316 /// This is here to force the test to be done whenever parent_buffer
318 Buffer const * parent() const
320 // ignore_parent temporarily "orphans" a buffer
321 // (e.g. if a child is compiled standalone)
324 // if parent_buffer is not loaded, then it has been unloaded,
325 // which means that parent_buffer is an invalid pointer. So we
326 // set it to null in that case.
327 // however, the BufferList doesn't know about cloned buffers, so
328 // they will always be regarded as unloaded. in that case, we hope
330 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
332 return parent_buffer;
336 void setParent(Buffer const * pb)
338 if (parent_buffer == pb)
341 if (!cloned_buffer_ && parent_buffer && pb)
342 LYXERR0("Warning: a buffer should not have two parents!");
344 if (!cloned_buffer_ && parent_buffer) {
345 parent_buffer->invalidateBibfileCache();
346 parent_buffer->invalidateBibinfoCache();
350 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
351 /// This one is useful for preview detached in a thread.
352 Buffer const * cloned_buffer_;
354 CloneList * clone_list_;
355 /// are we in the process of exporting this buffer?
356 mutable bool doing_export;
358 /// compute statistics
359 /// \p from initial position
360 /// \p to points to the end position
361 void updateStatistics(DocIterator & from, DocIterator & to,
362 bool skipNoOutput = true);
363 /// statistics accessor functions
364 int wordCount() const
368 int charCount(bool with_blanks) const
371 + (with_blanks ? blank_count_ : 0);
375 /// So we can force access via the accessors.
376 mutable Buffer const * parent_buffer;
385 /// Creates the per buffer temporary directory
386 static FileName createBufferTmpDir()
388 // FIXME This would be the ideal application for a TempDir class (like
389 // TempFile but for directories)
394 Mutex::Locker locker(&mutex);
395 counter = convert<string>(count++);
397 // We are in our own directory. Why bother to mangle name?
398 // In fact I wrote this code to circumvent a problematic behaviour
399 // (bug?) of EMX mkstemp().
400 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
403 if (!tmpfl.createDirectory(0777)) {
404 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
405 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
406 from_utf8(tmpfl.absFileName())));
412 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
413 Buffer const * cloned_buffer)
414 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
415 internal_buffer(false), read_only(readonly_), filename(file),
416 file_fully_loaded(false), ignore_parent(false), toc_backend(owner),
417 macro_lock(false), timestamp_(0), checksum_(0), wa_(0), gui_(0),
418 undo_(*owner), bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
419 cite_labels_valid_(false), inset(0), preview_loader_(0),
420 cloned_buffer_(cloned_buffer), clone_list_(0),
421 doing_export(false), parent_buffer(0),
422 word_count_(0), char_count_(0), blank_count_(0)
424 if (!cloned_buffer_) {
425 temppath = createBufferTmpDir();
426 lyxvc.setBuffer(owner_);
428 wa_ = new frontend::WorkAreaManager;
431 temppath = cloned_buffer_->d->temppath;
432 file_fully_loaded = true;
433 params = cloned_buffer_->d->params;
434 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
435 bibinfo_ = cloned_buffer_->d->bibinfo_;
436 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
437 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
438 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
439 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
440 unnamed = cloned_buffer_->d->unnamed;
441 internal_buffer = cloned_buffer_->d->internal_buffer;
442 layout_position = cloned_buffer_->d->layout_position;
443 preview_file_ = cloned_buffer_->d->preview_file_;
444 preview_format_ = cloned_buffer_->d->preview_format_;
445 preview_error_ = cloned_buffer_->d->preview_error_;
449 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
450 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
452 LYXERR(Debug::INFO, "Buffer::Buffer()");
454 d->inset = new InsetText(*cloned_buffer->d->inset);
455 d->inset->setBuffer(*this);
456 // FIXME: optimize this loop somewhat, maybe by creating a new
457 // general recursive Inset::setId().
458 DocIterator it = doc_iterator_begin(this);
459 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
460 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
461 it.paragraph().setId(cloned_it.paragraph().id());
463 d->inset = new InsetText(this);
464 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
470 LYXERR(Debug::INFO, "Buffer::~Buffer()");
471 // here the buffer should take care that it is
472 // saved properly, before it goes into the void.
474 // GuiView already destroyed
478 // No need to do additional cleanups for internal buffer.
484 // this is in case of recursive includes: we won't try to delete
485 // ourselves as a child.
486 d->clone_list_->erase(this);
487 // loop over children
488 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
489 Impl::BufferPositionMap::iterator end = d->children_positions.end();
490 for (; it != end; ++it) {
491 Buffer * child = const_cast<Buffer *>(it->first);
492 if (d->clone_list_->erase(child))
495 // if we're the master buffer, then we should get rid of the list
498 // If this is not empty, we have leaked something. Worse, one of the
499 // children still has a reference to this list. But we will try to
500 // continue, rather than shut down.
501 LATTEST(d->clone_list_->empty());
502 list<CloneList *>::iterator it =
503 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
504 if (it == cloned_buffers.end()) {
505 // We will leak in this case, but it is safe to continue.
508 cloned_buffers.erase(it);
509 delete d->clone_list_;
511 // FIXME Do we really need to do this right before we delete d?
512 // clear references to children in macro tables
513 d->children_positions.clear();
514 d->position_to_children.clear();
516 // loop over children
517 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
518 Impl::BufferPositionMap::iterator end = d->children_positions.end();
519 for (; it != end; ++it) {
520 Buffer * child = const_cast<Buffer *>(it->first);
521 if (theBufferList().isLoaded(child))
522 theBufferList().releaseChild(this, child);
526 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
527 msg += emergencyWrite();
528 Alert::warning(_("Attempting to close changed document!"), msg);
531 // FIXME Do we really need to do this right before we delete d?
532 // clear references to children in macro tables
533 d->children_positions.clear();
534 d->position_to_children.clear();
536 if (!d->temppath.destroyDirectory()) {
537 Alert::warning(_("Could not remove temporary directory"),
538 bformat(_("Could not remove the temporary directory %1$s"),
539 from_utf8(d->temppath.absFileName())));
548 Buffer * Buffer::cloneFromMaster() const
551 cloned_buffers.push_back(new CloneList);
552 CloneList * clones = cloned_buffers.back();
554 masterBuffer()->cloneWithChildren(bufmap, clones);
556 // make sure we got cloned
557 BufferMap::const_iterator bit = bufmap.find(this);
558 LASSERT(bit != bufmap.end(), return 0);
559 Buffer * cloned_buffer = bit->second;
561 return cloned_buffer;
565 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
567 // have we already been cloned?
568 if (bufmap.find(this) != bufmap.end())
571 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
573 // The clone needs its own DocumentClass, since running updateBuffer() will
574 // modify it, and we would otherwise be sharing it with the original Buffer.
575 buffer_clone->params().makeDocumentClass(true);
577 cap::switchBetweenClasses(
578 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
579 static_cast<InsetText &>(buffer_clone->inset()), el);
581 bufmap[this] = buffer_clone;
582 clones->insert(buffer_clone);
583 buffer_clone->d->clone_list_ = clones;
584 buffer_clone->d->macro_lock = true;
585 buffer_clone->d->children_positions.clear();
587 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
588 // math macro caches need to be rethought and simplified.
589 // I am not sure wether we should handle Buffer cloning here or in BufferList.
590 // Right now BufferList knows nothing about buffer clones.
591 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
592 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
593 for (; it != end; ++it) {
594 DocIterator dit = it->first.clone(buffer_clone);
595 dit.setBuffer(buffer_clone);
596 Buffer * child = const_cast<Buffer *>(it->second.buffer);
598 child->cloneWithChildren(bufmap, clones);
599 BufferMap::iterator const bit = bufmap.find(child);
600 LASSERT(bit != bufmap.end(), continue);
601 Buffer * child_clone = bit->second;
603 Inset * inset = dit.nextInset();
604 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
605 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
606 inset_inc->setChildBuffer(child_clone);
607 child_clone->d->setParent(buffer_clone);
608 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
609 buffer_clone->setChild(dit, child_clone);
611 buffer_clone->d->macro_lock = false;
616 Buffer * Buffer::cloneBufferOnly() const {
617 cloned_buffers.push_back(new CloneList);
618 CloneList * clones = cloned_buffers.back();
619 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
621 // The clone needs its own DocumentClass, since running updateBuffer() will
622 // modify it, and we would otherwise be sharing it with the original Buffer.
623 buffer_clone->params().makeDocumentClass(true);
625 cap::switchBetweenClasses(
626 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
627 static_cast<InsetText &>(buffer_clone->inset()), el);
629 clones->insert(buffer_clone);
630 buffer_clone->d->clone_list_ = clones;
632 // we won't be cloning the children
633 buffer_clone->d->children_positions.clear();
638 bool Buffer::isClone() const
640 return d->cloned_buffer_;
644 void Buffer::changed(bool update_metrics) const
647 d->wa_->redrawAll(update_metrics);
651 frontend::WorkAreaManager & Buffer::workAreaManager() const
658 Text & Buffer::text() const
660 return d->inset->text();
664 Inset & Buffer::inset() const
670 BufferParams & Buffer::params()
676 BufferParams const & Buffer::params() const
682 BufferParams const & Buffer::masterParams() const
684 if (masterBuffer() == this)
687 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
688 // Copy child authors to the params. We need those pointers.
689 AuthorList const & child_authors = params().authors();
690 AuthorList::Authors::const_iterator it = child_authors.begin();
691 for (; it != child_authors.end(); ++it)
692 mparams.authors().record(*it);
697 double Buffer::fontScalingFactor() const
699 return isExporting() ? 75.0 * params().html_math_img_scale
700 : 0.01 * lyxrc.dpi * lyxrc.zoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
704 ParagraphList & Buffer::paragraphs()
706 return text().paragraphs();
710 ParagraphList const & Buffer::paragraphs() const
712 return text().paragraphs();
716 LyXVC & Buffer::lyxvc()
722 LyXVC const & Buffer::lyxvc() const
728 string const Buffer::temppath() const
730 return d->temppath.absFileName();
734 TexRow & Buffer::texrow()
740 TexRow const & Buffer::texrow() const
746 TocBackend & Buffer::tocBackend() const
748 return d->toc_backend;
752 Undo & Buffer::undo()
758 void Buffer::setChild(DocIterator const & dit, Buffer * child)
760 d->children_positions[child] = dit;
764 string Buffer::latexName(bool const no_path) const
766 FileName latex_name =
767 makeLatexName(d->exportFileName());
768 return no_path ? latex_name.onlyFileName()
769 : latex_name.absFileName();
773 FileName Buffer::Impl::exportFileName() const
775 docstring const branch_suffix =
776 params.branchlist().getFileNameSuffix();
777 if (branch_suffix.empty())
780 string const name = filename.onlyFileNameWithoutExt()
781 + to_utf8(branch_suffix);
782 FileName res(filename.onlyPath().absFileName() + "/" + name);
783 res.changeExtension(filename.extension());
789 string Buffer::logName(LogType * type) const
791 string const filename = latexName(false);
793 if (filename.empty()) {
799 string const path = temppath();
801 FileName const fname(addName(temppath(),
802 onlyFileName(changeExtension(filename,
805 // FIXME: how do we know this is the name of the build log?
806 FileName const bname(
807 addName(path, onlyFileName(
808 changeExtension(filename,
809 formats.extension(params().bufferFormat()) + ".out"))));
811 // Also consider the master buffer log file
812 FileName masterfname = fname;
813 LogType mtype = latexlog;
814 if (masterBuffer() != this) {
815 string const mlogfile = masterBuffer()->logName(&mtype);
816 masterfname = FileName(mlogfile);
819 // If no Latex log or Build log is newer, show Build log
820 if (bname.exists() &&
821 ((!fname.exists() && !masterfname.exists())
822 || (fname.lastModified() < bname.lastModified()
823 && masterfname.lastModified() < bname.lastModified()))) {
824 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
827 return bname.absFileName();
828 // If we have a newer master file log or only a master log, show this
829 } else if (fname != masterfname
830 && (!fname.exists() && (masterfname.exists()
831 || fname.lastModified() < masterfname.lastModified()))) {
832 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
835 return masterfname.absFileName();
837 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
840 return fname.absFileName();
844 void Buffer::setReadonly(bool const flag)
846 if (d->read_only != flag) {
853 void Buffer::setFileName(FileName const & fname)
855 bool const changed = fname != d->filename;
858 lyxvc().file_found_hook(fname);
859 setReadonly(d->filename.isReadOnly());
865 int Buffer::readHeader(Lexer & lex)
867 int unknown_tokens = 0;
869 int begin_header_line = -1;
871 // Initialize parameters that may be/go lacking in header:
872 params().branchlist().clear();
873 params().preamble.erase();
874 params().options.erase();
875 params().master.erase();
876 params().float_placement.erase();
877 params().paperwidth.erase();
878 params().paperheight.erase();
879 params().leftmargin.erase();
880 params().rightmargin.erase();
881 params().topmargin.erase();
882 params().bottommargin.erase();
883 params().headheight.erase();
884 params().headsep.erase();
885 params().footskip.erase();
886 params().columnsep.erase();
887 params().fonts_cjk.erase();
888 params().listings_params.clear();
889 params().clearLayoutModules();
890 params().clearRemovedModules();
891 params().clearIncludedChildren();
892 params().pdfoptions().clear();
893 params().indiceslist().clear();
894 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
895 params().isbackgroundcolor = false;
896 params().fontcolor = RGBColor(0, 0, 0);
897 params().isfontcolor = false;
898 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
899 params().boxbgcolor = RGBColor(0xFF, 0, 0);
900 params().html_latex_start.clear();
901 params().html_latex_end.clear();
902 params().html_math_img_scale = 1.0;
903 params().output_sync_macro.erase();
904 params().setLocalLayout(string(), false);
905 params().setLocalLayout(string(), true);
907 for (int i = 0; i < 4; ++i) {
908 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
909 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
912 ErrorList & errorList = d->errorLists["Parse"];
921 if (token == "\\end_header")
925 if (token == "\\begin_header") {
926 begin_header_line = line;
930 LYXERR(Debug::PARSER, "Handling document header token: `"
933 string const result =
934 params().readToken(lex, token, d->filename.onlyPath());
935 if (!result.empty()) {
936 if (token == "\\textclass") {
937 d->layout_position = result;
940 docstring const s = bformat(_("Unknown token: "
944 errorList.push_back(ErrorItem(_("Document header error"),
949 if (begin_header_line) {
950 docstring const s = _("\\begin_header is missing");
951 errorList.push_back(ErrorItem(_("Document header error"),
955 params().makeDocumentClass();
957 return unknown_tokens;
962 // changed to be public and have one parameter
963 // Returns true if "\end_document" is not read (Asger)
964 bool Buffer::readDocument(Lexer & lex)
966 ErrorList & errorList = d->errorLists["Parse"];
969 // remove dummy empty par
970 paragraphs().clear();
972 if (!lex.checkFor("\\begin_document")) {
973 docstring const s = _("\\begin_document is missing");
974 errorList.push_back(ErrorItem(_("Document header error"),
980 if (params().output_changes) {
981 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
982 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
983 LaTeXFeatures::isAvailable("xcolor");
985 if (!dvipost && !xcolorulem) {
986 Alert::warning(_("Changes not shown in LaTeX output"),
987 _("Changes will not be highlighted in LaTeX output, "
988 "because neither dvipost nor xcolor/ulem are installed.\n"
989 "Please install these packages or redefine "
990 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
991 } else if (!xcolorulem) {
992 Alert::warning(_("Changes not shown in LaTeX output"),
993 _("Changes will not be highlighted in LaTeX output "
994 "when using pdflatex, because xcolor and ulem are not installed.\n"
995 "Please install both packages or redefine "
996 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1000 if (!parent() && !params().master.empty()) {
1001 FileName const master_file = makeAbsPath(params().master,
1002 onlyPath(absFileName()));
1003 if (isLyXFileName(master_file.absFileName())) {
1005 checkAndLoadLyXFile(master_file, true);
1007 // necessary e.g. after a reload
1008 // to re-register the child (bug 5873)
1009 // FIXME: clean up updateMacros (here, only
1010 // child registering is needed).
1011 master->updateMacros();
1012 // set master as master buffer, but only
1013 // if we are a real child
1014 if (master->isChild(this))
1016 // if the master is not fully loaded
1017 // it is probably just loading this
1018 // child. No warning needed then.
1019 else if (master->isFullyLoaded())
1020 LYXERR0("The master '"
1022 << "' assigned to this document ("
1024 << ") does not include "
1025 "this document. Ignoring the master assignment.");
1030 // assure we have a default index
1031 params().indiceslist().addDefault(B_("Index"));
1034 d->old_position = originFilePath();
1035 bool const res = text().read(lex, errorList, d->inset);
1036 d->old_position.clear();
1038 // inform parent buffer about local macros
1040 Buffer const * pbuf = parent();
1041 UserMacroSet::const_iterator cit = usermacros.begin();
1042 UserMacroSet::const_iterator end = usermacros.end();
1043 for (; cit != end; ++cit)
1044 pbuf->usermacros.insert(*cit);
1048 updateMacroInstances(InternalUpdate);
1053 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1055 Format const * fmt = formats.getFormat(format);
1058 // It is important to use the correct extension here, since some
1059 // converters create a wrong output file otherwise (e.g. html2latex)
1060 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1061 FileName const name(tempfile.name());
1062 ofdocstream os(name.toFilesystemEncoding().c_str());
1063 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1064 bool const success = !(os << contents).fail();
1067 bool converted = false;
1069 params().compressed = false;
1071 // remove dummy empty par
1072 paragraphs().clear();
1074 converted = importFile(format, name, errorList);
1083 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1085 if (!theConverters().isReachable(format, "lyx"))
1088 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1089 FileName const lyx(tempfile.name());
1090 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1091 return readFile(lyx) == ReadSuccess;
1097 bool Buffer::readString(string const & s)
1099 params().compressed = false;
1102 istringstream is(s);
1104 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1105 FileName const fn = tempfile.name();
1108 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1110 if (success && file_format != LYX_FORMAT) {
1111 // We need to call lyx2lyx, so write the input to a file
1112 ofstream os(fn.toFilesystemEncoding().c_str());
1115 // lyxvc in readFile
1116 if (readFile(fn) != ReadSuccess)
1120 if (readDocument(lex))
1126 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1130 if (!lex.setFile(fname)) {
1131 Alert::error(_("File Not Found"),
1132 bformat(_("Unable to open file `%1$s'."),
1133 from_utf8(fn.absFileName())));
1134 return ReadFileNotFound;
1138 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1139 if (ret_plf != ReadSuccess)
1142 if (file_format != LYX_FORMAT) {
1144 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1145 if (ret_clf != ReadSuccess)
1147 return readFile(tmpFile);
1150 // FIXME: InsetInfo needs to know whether the file is under VCS
1151 // during the parse process, so this has to be done before.
1152 lyxvc().file_found_hook(d->filename);
1154 if (readDocument(lex)) {
1155 Alert::error(_("Document format failure"),
1156 bformat(_("%1$s ended unexpectedly, which means"
1157 " that it is probably corrupted."),
1158 from_utf8(fn.absFileName())));
1159 return ReadDocumentFailure;
1162 d->file_fully_loaded = true;
1163 d->read_only = !d->filename.isWritable();
1164 params().compressed = formats.isZippedFile(d->filename);
1170 bool Buffer::isFullyLoaded() const
1172 return d->file_fully_loaded;
1176 void Buffer::setFullyLoaded(bool value)
1178 d->file_fully_loaded = value;
1182 bool Buffer::lastPreviewError() const
1184 return d->preview_error_;
1188 PreviewLoader * Buffer::loader() const
1190 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1192 if (!d->preview_loader_)
1193 d->preview_loader_ = new PreviewLoader(*this);
1194 return d->preview_loader_;
1198 void Buffer::removePreviews() const
1200 delete d->preview_loader_;
1201 d->preview_loader_ = 0;
1205 void Buffer::updatePreviews() const
1207 PreviewLoader * ploader = loader();
1211 InsetIterator it = inset_iterator_begin(*d->inset);
1212 InsetIterator const end = inset_iterator_end(*d->inset);
1213 for (; it != end; ++it)
1214 it->addPreview(it, *ploader);
1216 ploader->startLoading();
1220 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1221 FileName const & fn, int & file_format) const
1223 if(!lex.checkFor("\\lyxformat")) {
1224 Alert::error(_("Document format failure"),
1225 bformat(_("%1$s is not a readable LyX document."),
1226 from_utf8(fn.absFileName())));
1227 return ReadNoLyXFormat;
1233 // LyX formats 217 and earlier were written as 2.17. This corresponds
1234 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1235 // these cases. See also: www.lyx.org/trac/changeset/1313.
1236 size_t dot = tmp_format.find_first_of(".,");
1237 if (dot != string::npos)
1238 tmp_format.erase(dot, 1);
1240 file_format = convert<int>(tmp_format);
1245 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1246 FileName & tmpfile, int from_format)
1248 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1249 tempfile.setAutoRemove(false);
1250 tmpfile = tempfile.name();
1251 if(tmpfile.empty()) {
1252 Alert::error(_("Conversion failed"),
1253 bformat(_("%1$s is from a different"
1254 " version of LyX, but a temporary"
1255 " file for converting it could"
1256 " not be created."),
1257 from_utf8(fn.absFileName())));
1258 return LyX2LyXNoTempFile;
1261 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1262 if (lyx2lyx.empty()) {
1263 Alert::error(_("Conversion script not found"),
1264 bformat(_("%1$s is from a different"
1265 " version of LyX, but the"
1266 " conversion script lyx2lyx"
1267 " could not be found."),
1268 from_utf8(fn.absFileName())));
1269 return LyX2LyXNotFound;
1273 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1274 ostringstream command;
1275 command << os::python()
1276 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1277 << " -t " << convert<string>(LYX_FORMAT)
1278 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1279 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1280 string const command_str = command.str();
1282 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1284 cmd_ret const ret = runCommand(command_str);
1285 if (ret.first != 0) {
1286 if (from_format < LYX_FORMAT) {
1287 Alert::error(_("Conversion script failed"),
1288 bformat(_("%1$s is from an older version"
1289 " of LyX and the lyx2lyx script"
1290 " failed to convert it."),
1291 from_utf8(fn.absFileName())));
1292 return LyX2LyXOlderFormat;
1294 Alert::error(_("Conversion script failed"),
1295 bformat(_("%1$s is from a newer version"
1296 " of LyX and the lyx2lyx script"
1297 " failed to convert it."),
1298 from_utf8(fn.absFileName())));
1299 return LyX2LyXNewerFormat;
1306 // Should probably be moved to somewhere else: BufferView? GuiView?
1307 bool Buffer::save() const
1309 docstring const file = makeDisplayPath(absFileName(), 20);
1310 d->filename.refresh();
1312 // check the read-only status before moving the file as a backup
1313 if (d->filename.exists()) {
1314 bool const read_only = !d->filename.isWritable();
1316 Alert::warning(_("File is read-only"),
1317 bformat(_("The file %1$s cannot be written because it "
1318 "is marked as read-only."), file));
1323 // ask if the disk file has been externally modified (use checksum method)
1324 if (fileName().exists() && isExternallyModified(checksum_method)) {
1326 bformat(_("Document %1$s has been externally modified. "
1327 "Are you sure you want to overwrite this file?"), file);
1328 int const ret = Alert::prompt(_("Overwrite modified file?"),
1329 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1334 // We don't need autosaves in the immediate future. (Asger)
1335 resetAutosaveTimers();
1337 // if the file does not yet exist, none of the backup activity
1338 // that follows is necessary
1339 if (!fileName().exists())
1340 return writeFile(fileName());
1342 // we first write the file to a new name, then move it to its
1343 // proper location once that has been done successfully. that
1344 // way we preserve the original file if something goes wrong.
1345 string const justname = fileName().onlyFileNameWithoutExt();
1346 boost::scoped_ptr<TempFile>
1347 tempfile(new TempFile(fileName().onlyPath(),
1348 justname + "-XXXXXX.lyx"));
1349 bool const symlink = fileName().isSymLink();
1351 tempfile->setAutoRemove(false);
1353 FileName savefile(tempfile->name());
1354 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1355 if (!writeFile(savefile))
1358 // we will set this to false if we fail
1359 bool made_backup = true;
1361 FileName backupName(absFileName() + '~');
1362 if (lyxrc.make_backup) {
1363 if (!lyxrc.backupdir_path.empty()) {
1364 string const mangledName =
1365 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1366 backupName = FileName(addName(lyxrc.backupdir_path,
1370 LYXERR(Debug::FILES, "Backing up original file to " <<
1371 backupName.absFileName());
1372 // Except file is symlink do not copy because of #6587.
1373 // Hard links have bad luck.
1374 made_backup = symlink ?
1375 fileName().copyTo(backupName):
1376 fileName().moveTo(backupName);
1379 Alert::error(_("Backup failure"),
1380 bformat(_("Cannot create backup file %1$s.\n"
1381 "Please check whether the directory exists and is writable."),
1382 from_utf8(backupName.absFileName())));
1383 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1387 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1388 // Only do this if tempfile is not in autoremove mode
1391 // If we have no symlink, we can simply rename the temp file.
1392 // Otherwise, we need to copy it so the symlink stays intact.
1393 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1394 savefile.moveTo(fileName()))
1396 // saveCheckSum() was already called by writeFile(), but the
1397 // time stamp is invalidated by copying/moving
1402 // else we saved the file, but failed to move it to the right location.
1404 if (lyxrc.make_backup && made_backup && !symlink) {
1405 // the original file was moved to filename.lyx~, so it will look
1406 // to the user as if it was deleted. (see bug #9234.) we could try
1407 // to restore it, but that would basically mean trying to do again
1408 // what we just failed to do. better to leave things as they are.
1409 Alert::error(_("Write failure"),
1410 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1411 "But LyX could not move it to:\n %2$s.\n"
1412 "Your original file has been backed up to:\n %3$s"),
1413 from_utf8(savefile.absFileName()),
1414 from_utf8(fileName().absFileName()),
1415 from_utf8(backupName.absFileName())));
1417 // either we did not try to make a backup, or else we tried and failed,
1418 // or else the original file was a symlink, in which case it was copied,
1419 // not moved. so the original file is intact.
1420 Alert::error(_("Write failure"),
1421 bformat(_("Cannot move saved file to:\n %1$s.\n"
1422 "But the file has successfully been saved as:\n %2$s."),
1423 from_utf8(fileName().absFileName()),
1424 from_utf8(savefile.absFileName())));
1430 bool Buffer::writeFile(FileName const & fname) const
1432 if (d->read_only && fname == d->filename)
1435 bool retval = false;
1437 docstring const str = bformat(_("Saving document %1$s..."),
1438 makeDisplayPath(fname.absFileName()));
1441 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1443 if (params().compressed) {
1444 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1445 retval = ofs && write(ofs);
1447 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1448 retval = ofs && write(ofs);
1452 message(str + _(" could not write file!"));
1457 // removeAutosaveFile();
1460 message(str + _(" done."));
1466 docstring Buffer::emergencyWrite()
1468 // No need to save if the buffer has not changed.
1472 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1474 docstring user_message = bformat(
1475 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1477 // We try to save three places:
1478 // 1) Same place as document. Unless it is an unnamed doc.
1480 string s = absFileName();
1483 if (writeFile(FileName(s))) {
1485 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1486 return user_message;
1488 user_message += " " + _("Save failed! Trying again...\n");
1492 // 2) In HOME directory.
1493 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1495 lyxerr << ' ' << s << endl;
1496 if (writeFile(FileName(s))) {
1498 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1499 return user_message;
1502 user_message += " " + _("Save failed! Trying yet again...\n");
1504 // 3) In "/tmp" directory.
1505 // MakeAbsPath to prepend the current
1506 // drive letter on OS/2
1507 s = addName(package().temp_dir().absFileName(), absFileName());
1509 lyxerr << ' ' << s << endl;
1510 if (writeFile(FileName(s))) {
1512 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1513 return user_message;
1516 user_message += " " + _("Save failed! Bummer. Document is lost.");
1519 return user_message;
1523 bool Buffer::write(ostream & ofs) const
1526 // Use the standard "C" locale for file output.
1527 ofs.imbue(locale::classic());
1530 // The top of the file should not be written by params().
1532 // write out a comment in the top of the file
1533 // Important: Keep the version formatting in sync with lyx2lyx and
1534 // tex2lyx (bug 7951)
1535 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1536 << " created this file. For more info see http://www.lyx.org/\n"
1537 << "\\lyxformat " << LYX_FORMAT << "\n"
1538 << "\\begin_document\n";
1540 /// For each author, set 'used' to true if there is a change
1541 /// by this author in the document; otherwise set it to 'false'.
1542 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1543 AuthorList::Authors::const_iterator a_end = params().authors().end();
1544 for (; a_it != a_end; ++a_it)
1545 a_it->setUsed(false);
1547 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1548 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1549 for ( ; it != end; ++it)
1550 it->checkAuthors(params().authors());
1552 // now write out the buffer parameters.
1553 ofs << "\\begin_header\n";
1554 params().writeFile(ofs, this);
1555 ofs << "\\end_header\n";
1558 ofs << "\n\\begin_body\n";
1560 ofs << "\n\\end_body\n";
1562 // Write marker that shows file is complete
1563 ofs << "\\end_document" << endl;
1565 // Shouldn't really be needed....
1568 // how to check if close went ok?
1569 // Following is an attempt... (BE 20001011)
1571 // good() returns false if any error occurred, including some
1572 // formatting error.
1573 // bad() returns true if something bad happened in the buffer,
1574 // which should include file system full errors.
1579 lyxerr << "File was not closed properly." << endl;
1586 bool Buffer::makeLaTeXFile(FileName const & fname,
1587 string const & original_path,
1588 OutputParams const & runparams_in,
1589 OutputWhat output) const
1591 OutputParams runparams = runparams_in;
1593 // This is necessary for LuaTeX/XeTeX with tex fonts.
1594 // See FIXME in BufferParams::encoding()
1595 if (runparams.isFullUnicode())
1596 runparams.encoding = encodings.fromLyXName("utf8-plain");
1598 string const encoding = runparams.encoding->iconvName();
1599 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1602 try { ofs.reset(encoding); }
1603 catch (iconv_codecvt_facet_exception const & e) {
1604 lyxerr << "Caught iconv exception: " << e.what() << endl;
1605 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1606 "verify that the support software for your encoding (%1$s) is "
1607 "properly installed"), from_ascii(encoding)));
1610 if (!openFileWrite(ofs, fname))
1613 ErrorList & errorList = d->errorLists["Export"];
1615 bool failed_export = false;
1616 otexstream os(ofs, d->texrow);
1618 // make sure we are ready to export
1619 // this needs to be done before we validate
1620 // FIXME Do we need to do this all the time? I.e., in children
1621 // of a master we are exporting?
1623 updateMacroInstances(OutputUpdate);
1626 os.texrow().reset();
1627 writeLaTeXSource(os, original_path, runparams, output);
1629 catch (EncodingException const & e) {
1630 docstring const failed(1, e.failed_char);
1632 oss << "0x" << hex << e.failed_char << dec;
1633 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1634 " (code point %2$s)"),
1635 failed, from_utf8(oss.str()));
1636 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1637 "representable in the chosen encoding.\n"
1638 "Changing the document encoding to utf8 could help."),
1639 e.par_id, e.pos, e.pos + 1));
1640 failed_export = true;
1642 catch (iconv_codecvt_facet_exception const & e) {
1643 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1644 _(e.what()), -1, 0, 0));
1645 failed_export = true;
1647 catch (exception const & e) {
1648 errorList.push_back(ErrorItem(_("conversion failed"),
1649 _(e.what()), -1, 0, 0));
1650 failed_export = true;
1653 lyxerr << "Caught some really weird exception..." << endl;
1659 failed_export = true;
1660 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1663 if (runparams_in.silent)
1667 return !failed_export;
1671 void Buffer::writeLaTeXSource(otexstream & os,
1672 string const & original_path,
1673 OutputParams const & runparams_in,
1674 OutputWhat output) const
1676 // The child documents, if any, shall be already loaded at this point.
1678 OutputParams runparams = runparams_in;
1680 // This is necessary for LuaTeX/XeTeX with tex fonts.
1681 // See FIXME in BufferParams::encoding()
1682 if (runparams.isFullUnicode())
1683 runparams.encoding = encodings.fromLyXName("utf8-plain");
1685 // If we are compiling a file standalone, even if this is the
1686 // child of some other buffer, let's cut the link here, so the
1687 // file is really independent and no concurring settings from
1688 // the master (e.g. branch state) interfere (see #8100).
1689 if (!runparams.is_child)
1690 d->ignore_parent = true;
1692 // Classify the unicode characters appearing in math insets
1693 BufferEncodings::initUnicodeMath(*this);
1695 // validate the buffer.
1696 LYXERR(Debug::LATEX, " Validating buffer...");
1697 LaTeXFeatures features(*this, params(), runparams);
1699 // This is only set once per document (in master)
1700 if (!runparams.is_child)
1701 runparams.use_polyglossia = features.usePolyglossia();
1702 LYXERR(Debug::LATEX, " Buffer validation done.");
1704 bool const output_preamble =
1705 output == FullSource || output == OnlyPreamble;
1706 bool const output_body =
1707 output == FullSource || output == OnlyBody;
1709 // The starting paragraph of the coming rows is the
1710 // first paragraph of the document. (Asger)
1711 if (output_preamble && runparams.nice) {
1712 os << "%% LyX " << lyx_version << " created this file. "
1713 "For more info, see http://www.lyx.org/.\n"
1714 "%% Do not edit unless you really know what "
1717 LYXERR(Debug::INFO, "lyx document header finished");
1719 // There are a few differences between nice LaTeX and usual files:
1720 // usual files have \batchmode and special input@path to allow
1721 // inclusion of figures specified by an explicitly relative path
1722 // (i.e., a path starting with './' or '../') with either \input or
1723 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1724 // input@path is set when the actual parameter original_path is set.
1725 // This is done for usual tex-file, but not for nice-latex-file.
1726 // (Matthias 250696)
1727 // Note that input@path is only needed for something the user does
1728 // in the preamble, included .tex files or ERT, files included by
1729 // LyX work without it.
1730 if (output_preamble) {
1731 if (!runparams.nice) {
1732 // code for usual, NOT nice-latex-file
1733 os << "\\batchmode\n"; // changed from \nonstopmode
1735 if (!original_path.empty()) {
1737 // We don't know the encoding of inputpath
1738 docstring const inputpath = from_utf8(original_path);
1739 docstring uncodable_glyphs;
1740 Encoding const * const enc = runparams.encoding;
1742 for (size_t n = 0; n < inputpath.size(); ++n) {
1743 if (!enc->encodable(inputpath[n])) {
1744 docstring const glyph(1, inputpath[n]);
1745 LYXERR0("Uncodable character '"
1747 << "' in input path!");
1748 uncodable_glyphs += glyph;
1753 // warn user if we found uncodable glyphs.
1754 if (!uncodable_glyphs.empty()) {
1755 frontend::Alert::warning(
1756 _("Uncodable character in file path"),
1758 _("The path of your document\n"
1760 "contains glyphs that are unknown "
1761 "in the current document encoding "
1762 "(namely %2$s). This may result in "
1763 "incomplete output, unless "
1764 "TEXINPUTS contains the document "
1765 "directory and you don't use "
1766 "explicitly relative paths (i.e., "
1767 "paths starting with './' or "
1768 "'../') in the preamble or in ERT."
1769 "\n\nIn case of problems, choose "
1770 "an appropriate document encoding\n"
1771 "(such as utf8) or change the "
1773 inputpath, uncodable_glyphs));
1776 support::latex_path(original_path);
1777 if (contains(docdir, '#')) {
1778 docdir = subst(docdir, "#", "\\#");
1779 os << "\\catcode`\\#=11"
1780 "\\def\\#{#}\\catcode`\\#=6\n";
1782 if (contains(docdir, '%')) {
1783 docdir = subst(docdir, "%", "\\%");
1784 os << "\\catcode`\\%=11"
1785 "\\def\\%{%}\\catcode`\\%=14\n";
1787 os << "\\makeatletter\n"
1788 << "\\def\\input@path{{"
1789 << docdir << "/}}\n"
1790 << "\\makeatother\n";
1794 // get parent macros (if this buffer has a parent) which will be
1795 // written at the document begin further down.
1796 MacroSet parentMacros;
1797 listParentMacros(parentMacros, features);
1799 // Write the preamble
1800 runparams.use_babel = params().writeLaTeX(os, features,
1801 d->filename.onlyPath());
1803 // Japanese might be required only in some children of a document,
1804 // but once required, we must keep use_japanese true.
1805 runparams.use_japanese |= features.isRequired("japanese");
1808 // Restore the parenthood if needed
1809 if (!runparams.is_child)
1810 d->ignore_parent = false;
1815 os << "\\begin{document}\n";
1817 // output the parent macros
1818 MacroSet::iterator it = parentMacros.begin();
1819 MacroSet::iterator end = parentMacros.end();
1820 for (; it != end; ++it) {
1821 int num_lines = (*it)->write(os.os(), true);
1822 os.texrow().newlines(num_lines);
1825 } // output_preamble
1827 os.texrow().start(paragraphs().begin()->id(), 0);
1829 LYXERR(Debug::INFO, "preamble finished, now the body.");
1832 latexParagraphs(*this, text(), os, runparams);
1834 // Restore the parenthood if needed
1835 if (!runparams.is_child)
1836 d->ignore_parent = false;
1838 // add this just in case after all the paragraphs
1841 if (output_preamble) {
1842 os << "\\end{document}\n";
1843 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1845 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1847 runparams_in.encoding = runparams.encoding;
1849 // Just to be sure. (Asger)
1850 os.texrow().newline();
1852 //for (int i = 0; i<d->texrow.rows(); i++) {
1854 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1855 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1858 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1859 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1863 void Buffer::makeDocBookFile(FileName const & fname,
1864 OutputParams const & runparams,
1865 OutputWhat output) const
1867 LYXERR(Debug::LATEX, "makeDocBookFile...");
1870 if (!openFileWrite(ofs, fname))
1873 // make sure we are ready to export
1874 // this needs to be done before we validate
1876 updateMacroInstances(OutputUpdate);
1878 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1882 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1886 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1887 OutputParams const & runparams,
1888 OutputWhat output) const
1890 LaTeXFeatures features(*this, params(), runparams);
1895 DocumentClass const & tclass = params().documentClass();
1896 string const & top_element = tclass.latexname();
1898 bool const output_preamble =
1899 output == FullSource || output == OnlyPreamble;
1900 bool const output_body =
1901 output == FullSource || output == OnlyBody;
1903 if (output_preamble) {
1904 if (runparams.flavor == OutputParams::XML)
1905 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1908 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1911 if (! tclass.class_header().empty())
1912 os << from_ascii(tclass.class_header());
1913 else if (runparams.flavor == OutputParams::XML)
1914 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1915 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1917 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1919 docstring preamble = from_utf8(params().preamble);
1920 if (runparams.flavor != OutputParams::XML ) {
1921 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1922 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1923 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1924 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1927 string const name = runparams.nice
1928 ? changeExtension(absFileName(), ".sgml") : fname;
1929 preamble += features.getIncludedFiles(name);
1930 preamble += features.getLyXSGMLEntities();
1932 if (!preamble.empty()) {
1933 os << "\n [ " << preamble << " ]";
1939 string top = top_element;
1941 if (runparams.flavor == OutputParams::XML)
1942 top += params().language->code();
1944 top += params().language->code().substr(0, 2);
1947 if (!params().options.empty()) {
1949 top += params().options;
1952 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1953 << " file was created by LyX " << lyx_version
1954 << "\n See http://www.lyx.org/ for more information -->\n";
1956 params().documentClass().counters().reset();
1958 sgml::openTag(os, top);
1960 docbookParagraphs(text(), *this, os, runparams);
1961 sgml::closeTag(os, top_element);
1966 void Buffer::makeLyXHTMLFile(FileName const & fname,
1967 OutputParams const & runparams) const
1969 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1972 if (!openFileWrite(ofs, fname))
1975 // make sure we are ready to export
1976 // this has to be done before we validate
1977 updateBuffer(UpdateMaster, OutputUpdate);
1978 updateMacroInstances(OutputUpdate);
1980 writeLyXHTMLSource(ofs, runparams, FullSource);
1984 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1988 void Buffer::writeLyXHTMLSource(odocstream & os,
1989 OutputParams const & runparams,
1990 OutputWhat output) const
1992 LaTeXFeatures features(*this, params(), runparams);
1994 d->bibinfo_.makeCitationLabels(*this);
1996 bool const output_preamble =
1997 output == FullSource || output == OnlyPreamble;
1998 bool const output_body =
1999 output == FullSource || output == OnlyBody || output == IncludedFile;
2001 if (output_preamble) {
2002 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2003 << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/Math/DTD/mathml2/xhtml-math11-f.dtd\">\n"
2004 // FIXME Language should be set properly.
2005 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2007 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2008 // FIXME Presumably need to set this right
2009 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2011 docstring const & doctitle = features.htmlTitle();
2013 << (doctitle.empty() ?
2014 from_ascii("LyX Document") :
2015 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2018 docstring styles = features.getTClassHTMLPreamble();
2019 if (!styles.empty())
2020 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2022 styles = from_utf8(features.getPreambleSnippets());
2023 if (!styles.empty())
2024 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2026 // we will collect CSS information in a stream, and then output it
2027 // either here, as part of the header, or else in a separate file.
2028 odocstringstream css;
2029 styles = from_utf8(features.getCSSSnippets());
2030 if (!styles.empty())
2031 css << "/* LyX Provided Styles */\n" << styles << '\n';
2033 styles = features.getTClassHTMLStyles();
2034 if (!styles.empty())
2035 css << "/* Layout-provided Styles */\n" << styles << '\n';
2037 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2038 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2039 if (needfg || needbg) {
2040 css << "\nbody {\n";
2043 << from_ascii(X11hexname(params().fontcolor))
2046 css << " background-color: "
2047 << from_ascii(X11hexname(params().backgroundcolor))
2052 docstring const dstyles = css.str();
2053 if (!dstyles.empty()) {
2054 bool written = false;
2055 if (params().html_css_as_file) {
2056 // open a file for CSS info
2058 string const fcssname = addName(temppath(), "docstyle.css");
2059 FileName const fcssfile = FileName(fcssname);
2060 if (openFileWrite(ocss, fcssfile)) {
2064 // write link to header
2065 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2067 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2070 // we are here if the CSS is supposed to be written to the header
2071 // or if we failed to write it to an external file.
2073 os << "<style type='text/css'>\n"
2082 bool const output_body_tag = (output != IncludedFile);
2083 if (output_body_tag)
2086 if (output != IncludedFile)
2087 // if we're an included file, the counters are in the master.
2088 params().documentClass().counters().reset();
2089 xhtmlParagraphs(text(), *this, xs, runparams);
2090 if (output_body_tag)
2094 if (output_preamble)
2099 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2100 // Other flags: -wall -v0 -x
2101 int Buffer::runChktex()
2105 // get LaTeX-Filename
2106 FileName const path(temppath());
2107 string const name = addName(path.absFileName(), latexName());
2108 string const org_path = filePath();
2110 PathChanger p(path); // path to LaTeX file
2111 message(_("Running chktex..."));
2113 // Generate the LaTeX file if neccessary
2114 OutputParams runparams(¶ms().encoding());
2115 runparams.flavor = OutputParams::LATEX;
2116 runparams.nice = false;
2117 runparams.linelen = lyxrc.plaintext_linelen;
2118 makeLaTeXFile(FileName(name), org_path, runparams);
2121 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2122 int const res = chktex.run(terr); // run chktex
2125 Alert::error(_("chktex failure"),
2126 _("Could not run chktex successfully."));
2128 ErrorList & errlist = d->errorLists["ChkTeX"];
2130 bufferErrors(terr, errlist);
2135 if (runparams.silent)
2136 d->errorLists["ChkTeX"].clear();
2144 void Buffer::validate(LaTeXFeatures & features) const
2146 // Validate the buffer params, but not for included
2147 // files, since they also use the parent buffer's
2149 if (!features.runparams().is_child)
2150 params().validate(features);
2152 for_each(paragraphs().begin(), paragraphs().end(),
2153 bind(&Paragraph::validate, _1, ref(features)));
2155 if (lyxerr.debugging(Debug::LATEX)) {
2156 features.showStruct();
2161 void Buffer::getLabelList(vector<docstring> & list) const
2163 // If this is a child document, use the master's list instead.
2165 masterBuffer()->getLabelList(list);
2170 Toc & toc = d->toc_backend.toc("label");
2171 TocIterator toc_it = toc.begin();
2172 TocIterator end = toc.end();
2173 for (; toc_it != end; ++toc_it) {
2174 if (toc_it->depth() == 0)
2175 list.push_back(toc_it->str());
2180 void Buffer::updateBibfilesCache(UpdateScope scope) const
2182 // FIXME This is probably unnecssary, given where we call this.
2183 // If this is a child document, use the parent's cache instead.
2184 if (parent() && scope != UpdateChildOnly) {
2185 masterBuffer()->updateBibfilesCache();
2189 d->bibfiles_cache_.clear();
2190 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2191 if (it->lyxCode() == BIBTEX_CODE) {
2192 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2193 support::FileNameList const bibfiles = inset.getBibFiles();
2194 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2197 } else if (it->lyxCode() == INCLUDE_CODE) {
2198 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2199 Buffer const * const incbuf = inset.getChildBuffer();
2202 support::FileNameList const & bibfiles =
2203 incbuf->getBibfilesCache(UpdateChildOnly);
2204 if (!bibfiles.empty()) {
2205 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2211 d->bibfile_cache_valid_ = true;
2212 d->bibinfo_cache_valid_ = false;
2213 d->cite_labels_valid_ = false;
2217 void Buffer::invalidateBibinfoCache() const
2219 d->bibinfo_cache_valid_ = false;
2220 d->cite_labels_valid_ = false;
2221 // also invalidate the cache for the parent buffer
2222 Buffer const * const pbuf = d->parent();
2224 pbuf->invalidateBibinfoCache();
2228 void Buffer::invalidateBibfileCache() const
2230 d->bibfile_cache_valid_ = false;
2231 d->bibinfo_cache_valid_ = false;
2232 d->cite_labels_valid_ = false;
2233 // also invalidate the cache for the parent buffer
2234 Buffer const * const pbuf = d->parent();
2236 pbuf->invalidateBibfileCache();
2240 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2242 // FIXME This is probably unnecessary, given where we call this.
2243 // If this is a child document, use the master's cache instead.
2244 Buffer const * const pbuf = masterBuffer();
2245 if (pbuf != this && scope != UpdateChildOnly)
2246 return pbuf->getBibfilesCache();
2248 if (!d->bibfile_cache_valid_)
2249 this->updateBibfilesCache(scope);
2251 return d->bibfiles_cache_;
2255 BiblioInfo const & Buffer::masterBibInfo() const
2257 Buffer const * const tmp = masterBuffer();
2259 return tmp->masterBibInfo();
2264 void Buffer::checkIfBibInfoCacheIsValid() const
2266 // use the master's cache
2267 Buffer const * const tmp = masterBuffer();
2269 tmp->checkIfBibInfoCacheIsValid();
2273 // compare the cached timestamps with the actual ones.
2274 FileNameList const & bibfiles_cache = getBibfilesCache();
2275 FileNameList::const_iterator ei = bibfiles_cache.begin();
2276 FileNameList::const_iterator en = bibfiles_cache.end();
2277 for (; ei != en; ++ ei) {
2278 time_t lastw = ei->lastModified();
2279 time_t prevw = d->bibfile_status_[*ei];
2280 if (lastw != prevw) {
2281 d->bibinfo_cache_valid_ = false;
2282 d->cite_labels_valid_ = false;
2283 d->bibfile_status_[*ei] = lastw;
2289 void Buffer::reloadBibInfoCache() const
2291 // use the master's cache
2292 Buffer const * const tmp = masterBuffer();
2294 tmp->reloadBibInfoCache();
2298 checkIfBibInfoCacheIsValid();
2299 if (d->bibinfo_cache_valid_)
2302 d->bibinfo_.clear();
2304 d->bibinfo_cache_valid_ = true;
2308 void Buffer::collectBibKeys() const
2310 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2311 it->collectBibKeys(it);
2315 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2317 Buffer const * tmp = masterBuffer();
2318 BiblioInfo & masterbi = (tmp == this) ?
2319 d->bibinfo_ : tmp->d->bibinfo_;
2320 masterbi.mergeBiblioInfo(bi);
2324 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2326 Buffer const * tmp = masterBuffer();
2327 BiblioInfo & masterbi = (tmp == this) ?
2328 d->bibinfo_ : tmp->d->bibinfo_;
2333 void Buffer::makeCitationLabels() const
2335 Buffer const * const master = masterBuffer();
2336 return d->bibinfo_.makeCitationLabels(*master);
2340 bool Buffer::citeLabelsValid() const
2342 return masterBuffer()->d->cite_labels_valid_;
2346 void Buffer::removeBiblioTempFiles() const
2348 // We remove files that contain LaTeX commands specific to the
2349 // particular bibliographic style being used, in order to avoid
2350 // LaTeX errors when we switch style.
2351 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2352 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2353 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2354 aux_file.removeFile();
2355 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2356 bbl_file.removeFile();
2357 // Also for the parent buffer
2358 Buffer const * const pbuf = parent();
2360 pbuf->removeBiblioTempFiles();
2364 bool Buffer::isDepClean(string const & name) const
2366 DepClean::const_iterator const it = d->dep_clean.find(name);
2367 if (it == d->dep_clean.end())
2373 void Buffer::markDepClean(string const & name)
2375 d->dep_clean[name] = true;
2379 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2382 // FIXME? if there is an Buffer LFUN that can be dispatched even
2383 // if internal, put a switch '(cmd.action)' here.
2389 switch (cmd.action()) {
2391 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2392 flag.setOnOff(isReadonly());
2395 // FIXME: There is need for a command-line import.
2396 //case LFUN_BUFFER_IMPORT:
2398 case LFUN_BUFFER_AUTO_SAVE:
2401 case LFUN_BUFFER_EXPORT_CUSTOM:
2402 // FIXME: Nothing to check here?
2405 case LFUN_BUFFER_EXPORT: {
2406 docstring const arg = cmd.argument();
2407 if (arg == "custom") {
2411 string format = to_utf8(arg);
2412 size_t pos = format.find(' ');
2413 if (pos != string::npos)
2414 format = format.substr(0, pos);
2415 enable = params().isExportable(format);
2417 flag.message(bformat(
2418 _("Don't know how to export to format: %1$s"), arg));
2422 case LFUN_BUFFER_CHKTEX:
2423 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2426 case LFUN_BUILD_PROGRAM:
2427 enable = params().isExportable("program");
2430 case LFUN_BRANCH_ACTIVATE:
2431 case LFUN_BRANCH_DEACTIVATE:
2432 case LFUN_BRANCH_MASTER_ACTIVATE:
2433 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2434 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2435 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2436 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2437 : params().branchlist();
2438 docstring const branchName = cmd.argument();
2439 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2443 case LFUN_BRANCH_ADD:
2444 case LFUN_BRANCHES_RENAME:
2445 case LFUN_BUFFER_PRINT:
2446 // if no Buffer is present, then of course we won't be called!
2449 case LFUN_BUFFER_LANGUAGE:
2450 enable = !isReadonly();
2453 case LFUN_BUFFER_VIEW_CACHE:
2454 enable = (d->preview_file_).exists();
2460 flag.setEnabled(enable);
2465 void Buffer::dispatch(string const & command, DispatchResult & result)
2467 return dispatch(lyxaction.lookupFunc(command), result);
2471 // NOTE We can end up here even if we have no GUI, because we are called
2472 // by LyX::exec to handled command-line requests. So we may need to check
2473 // whether we have a GUI or not. The boolean use_gui holds this information.
2474 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2477 // FIXME? if there is an Buffer LFUN that can be dispatched even
2478 // if internal, put a switch '(cmd.action())' here.
2479 dr.dispatched(false);
2482 string const argument = to_utf8(func.argument());
2483 // We'll set this back to false if need be.
2484 bool dispatched = true;
2485 undo().beginUndoGroup();
2487 switch (func.action()) {
2488 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2489 if (lyxvc().inUse()) {
2490 string log = lyxvc().toggleReadOnly();
2495 setReadonly(!isReadonly());
2498 case LFUN_BUFFER_EXPORT: {
2499 ExportStatus const status = doExport(argument, false);
2500 dr.setError(status != ExportSuccess);
2501 if (status != ExportSuccess)
2502 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2507 case LFUN_BUILD_PROGRAM: {
2508 ExportStatus const status = doExport("program", true);
2509 dr.setError(status != ExportSuccess);
2510 if (status != ExportSuccess)
2511 dr.setMessage(_("Error generating literate programming code."));
2515 case LFUN_BUFFER_CHKTEX:
2519 case LFUN_BUFFER_EXPORT_CUSTOM: {
2521 string command = split(argument, format_name, ' ');
2522 Format const * format = formats.getFormat(format_name);
2524 lyxerr << "Format \"" << format_name
2525 << "\" not recognized!"
2530 // The name of the file created by the conversion process
2533 // Output to filename
2534 if (format->name() == "lyx") {
2535 string const latexname = latexName(false);
2536 filename = changeExtension(latexname,
2537 format->extension());
2538 filename = addName(temppath(), filename);
2540 if (!writeFile(FileName(filename)))
2544 doExport(format_name, true, filename);
2547 // Substitute $$FName for filename
2548 if (!contains(command, "$$FName"))
2549 command = "( " + command + " ) < $$FName";
2550 command = subst(command, "$$FName", filename);
2552 // Execute the command in the background
2554 call.startscript(Systemcall::DontWait, command,
2555 filePath(), layoutPos());
2559 // FIXME: There is need for a command-line import.
2561 case LFUN_BUFFER_IMPORT:
2566 case LFUN_BUFFER_AUTO_SAVE:
2568 resetAutosaveTimers();
2571 case LFUN_BRANCH_ACTIVATE:
2572 case LFUN_BRANCH_DEACTIVATE:
2573 case LFUN_BRANCH_MASTER_ACTIVATE:
2574 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2575 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2576 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2577 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2580 docstring const branch_name = func.argument();
2581 // the case without a branch name is handled elsewhere
2582 if (branch_name.empty()) {
2586 Branch * branch = buf->params().branchlist().find(branch_name);
2588 LYXERR0("Branch " << branch_name << " does not exist.");
2590 docstring const msg =
2591 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2595 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2596 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2597 if (branch->isSelected() != activate) {
2598 buf->undo().recordUndoBufferParams(CursorData());
2599 branch->setSelected(activate);
2601 dr.screenUpdate(Update::Force);
2602 dr.forceBufferUpdate();
2607 case LFUN_BRANCH_ADD: {
2608 docstring branch_name = func.argument();
2609 if (branch_name.empty()) {
2613 BranchList & branch_list = params().branchlist();
2614 vector<docstring> const branches =
2615 getVectorFromString(branch_name, branch_list.separator());
2617 for (vector<docstring>::const_iterator it = branches.begin();
2618 it != branches.end(); ++it) {
2620 Branch * branch = branch_list.find(branch_name);
2622 LYXERR0("Branch " << branch_name << " already exists.");
2626 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2628 undo().recordUndoBufferParams(CursorData());
2629 branch_list.add(branch_name);
2630 branch = branch_list.find(branch_name);
2631 string const x11hexname = X11hexname(branch->color());
2632 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2633 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2635 dr.screenUpdate(Update::Force);
2643 case LFUN_BRANCHES_RENAME: {
2644 if (func.argument().empty())
2647 docstring const oldname = from_utf8(func.getArg(0));
2648 docstring const newname = from_utf8(func.getArg(1));
2649 InsetIterator it = inset_iterator_begin(inset());
2650 InsetIterator const end = inset_iterator_end(inset());
2651 bool success = false;
2652 for (; it != end; ++it) {
2653 if (it->lyxCode() == BRANCH_CODE) {
2654 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2655 if (ins.branch() == oldname) {
2656 undo().recordUndo(CursorData(it));
2657 ins.rename(newname);
2662 if (it->lyxCode() == INCLUDE_CODE) {
2663 // get buffer of external file
2664 InsetInclude const & ins =
2665 static_cast<InsetInclude const &>(*it);
2666 Buffer * child = ins.getChildBuffer();
2669 child->dispatch(func, dr);
2674 dr.screenUpdate(Update::Force);
2675 dr.forceBufferUpdate();
2680 case LFUN_BUFFER_PRINT: {
2681 // we'll assume there's a problem until we succeed
2683 string target = func.getArg(0);
2684 string target_name = func.getArg(1);
2685 string command = func.getArg(2);
2688 || target_name.empty()
2689 || command.empty()) {
2690 LYXERR0("Unable to parse " << func.argument());
2691 docstring const msg =
2692 bformat(_("Unable to parse \"%1$s\""), func.argument());
2696 if (target != "printer" && target != "file") {
2697 LYXERR0("Unrecognized target \"" << target << '"');
2698 docstring const msg =
2699 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2704 if (doExport("dvi", true) != ExportSuccess) {
2705 showPrintError(absFileName());
2706 dr.setMessage(_("Error exporting to DVI."));
2710 // Push directory path.
2711 string const path = temppath();
2712 // Prevent the compiler from optimizing away p
2716 // there are three cases here:
2717 // 1. we print to a file
2718 // 2. we print directly to a printer
2719 // 3. we print using a spool command (print to file first)
2722 string const dviname = changeExtension(latexName(true), "dvi");
2724 if (target == "printer") {
2725 if (!lyxrc.print_spool_command.empty()) {
2726 // case 3: print using a spool
2727 string const psname = changeExtension(dviname,".ps");
2728 command += ' ' + lyxrc.print_to_file
2731 + quoteName(dviname);
2733 string command2 = lyxrc.print_spool_command + ' ';
2734 if (target_name != "default") {
2735 command2 += lyxrc.print_spool_printerprefix
2739 command2 += quoteName(psname);
2741 // If successful, then spool command
2742 res = one.startscript(Systemcall::Wait, command,
2743 filePath(), layoutPos());
2746 // If there's no GUI, we have to wait on this command. Otherwise,
2747 // LyX deletes the temporary directory, and with it the spooled
2748 // file, before it can be printed!!
2749 Systemcall::Starttype stype = use_gui ?
2750 Systemcall::DontWait : Systemcall::Wait;
2751 res = one.startscript(stype, command2,
2756 // case 2: print directly to a printer
2757 if (target_name != "default")
2758 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2760 Systemcall::Starttype stype = use_gui ?
2761 Systemcall::DontWait : Systemcall::Wait;
2762 res = one.startscript(stype,
2763 command + quoteName(dviname),
2764 filePath(), layoutPos());
2768 // case 1: print to a file
2769 FileName const filename(makeAbsPath(target_name, filePath()));
2770 FileName const dvifile(makeAbsPath(dviname, path));
2771 if (filename.exists()) {
2772 docstring text = bformat(
2773 _("The file %1$s already exists.\n\n"
2774 "Do you want to overwrite that file?"),
2775 makeDisplayPath(filename.absFileName()));
2776 if (Alert::prompt(_("Overwrite file?"),
2777 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2780 command += ' ' + lyxrc.print_to_file
2781 + quoteName(filename.toFilesystemEncoding())
2783 + quoteName(dvifile.toFilesystemEncoding());
2785 Systemcall::Starttype stype = use_gui ?
2786 Systemcall::DontWait : Systemcall::Wait;
2787 res = one.startscript(stype, command, filePath(), layoutPos());
2793 dr.setMessage(_("Error running external commands."));
2794 showPrintError(absFileName());
2799 case LFUN_BUFFER_VIEW_CACHE:
2800 if (!formats.view(*this, d->preview_file_,
2801 d->preview_format_))
2802 dr.setMessage(_("Error viewing the output file."));
2809 dr.dispatched(dispatched);
2810 undo().endUndoGroup();
2814 void Buffer::changeLanguage(Language const * from, Language const * to)
2816 LASSERT(from, return);
2817 LASSERT(to, return);
2819 for_each(par_iterator_begin(),
2821 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2825 bool Buffer::isMultiLingual() const
2827 ParConstIterator end = par_iterator_end();
2828 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2829 if (it->isMultiLingual(params()))
2836 std::set<Language const *> Buffer::getLanguages() const
2838 std::set<Language const *> languages;
2839 getLanguages(languages);
2844 void Buffer::getLanguages(std::set<Language const *> & languages) const
2846 ParConstIterator end = par_iterator_end();
2847 // add the buffer language, even if it's not actively used
2848 languages.insert(language());
2849 // iterate over the paragraphs
2850 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2851 it->getLanguages(languages);
2853 ListOfBuffers clist = getDescendents();
2854 ListOfBuffers::const_iterator cit = clist.begin();
2855 ListOfBuffers::const_iterator const cen = clist.end();
2856 for (; cit != cen; ++cit)
2857 (*cit)->getLanguages(languages);
2861 DocIterator Buffer::getParFromID(int const id) const
2863 Buffer * buf = const_cast<Buffer *>(this);
2865 // John says this is called with id == -1 from undo
2866 lyxerr << "getParFromID(), id: " << id << endl;
2867 return doc_iterator_end(buf);
2870 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2871 if (it.paragraph().id() == id)
2874 return doc_iterator_end(buf);
2878 bool Buffer::hasParWithID(int const id) const
2880 return !getParFromID(id).atEnd();
2884 ParIterator Buffer::par_iterator_begin()
2886 return ParIterator(doc_iterator_begin(this));
2890 ParIterator Buffer::par_iterator_end()
2892 return ParIterator(doc_iterator_end(this));
2896 ParConstIterator Buffer::par_iterator_begin() const
2898 return ParConstIterator(doc_iterator_begin(this));
2902 ParConstIterator Buffer::par_iterator_end() const
2904 return ParConstIterator(doc_iterator_end(this));
2908 Language const * Buffer::language() const
2910 return params().language;
2914 docstring const Buffer::B_(string const & l10n) const
2916 return params().B_(l10n);
2920 bool Buffer::isClean() const
2922 return d->lyx_clean;
2926 bool Buffer::isExternallyModified(CheckMethod method) const
2928 LASSERT(d->filename.exists(), return false);
2929 // if method == timestamp, check timestamp before checksum
2930 return (method == checksum_method
2931 || d->timestamp_ != d->filename.lastModified())
2932 && d->checksum_ != d->filename.checksum();
2936 void Buffer::saveCheckSum() const
2938 FileName const & file = d->filename;
2941 if (file.exists()) {
2942 d->timestamp_ = file.lastModified();
2943 d->checksum_ = file.checksum();
2945 // in the case of save to a new file.
2952 void Buffer::markClean() const
2954 if (!d->lyx_clean) {
2955 d->lyx_clean = true;
2958 // if the .lyx file has been saved, we don't need an
2960 d->bak_clean = true;
2961 d->undo_.markDirty();
2965 void Buffer::setUnnamed(bool flag)
2971 bool Buffer::isUnnamed() const
2978 /// Don't check unnamed, here: isInternal() is used in
2979 /// newBuffer(), where the unnamed flag has not been set by anyone
2980 /// yet. Also, for an internal buffer, there should be no need for
2981 /// retrieving fileName() nor for checking if it is unnamed or not.
2982 bool Buffer::isInternal() const
2984 return d->internal_buffer;
2988 void Buffer::setInternal(bool flag)
2990 d->internal_buffer = flag;
2994 void Buffer::markDirty()
2997 d->lyx_clean = false;
3000 d->bak_clean = false;
3002 DepClean::iterator it = d->dep_clean.begin();
3003 DepClean::const_iterator const end = d->dep_clean.end();
3005 for (; it != end; ++it)
3010 FileName Buffer::fileName() const
3016 string Buffer::absFileName() const
3018 return d->filename.absFileName();
3022 string Buffer::filePath() const
3024 string const abs = d->filename.onlyPath().absFileName();
3027 int last = abs.length() - 1;
3029 return abs[last] == '/' ? abs : abs + '/';
3033 string Buffer::originFilePath() const
3035 if (FileName::isAbsolute(params().origin))
3036 return params().origin;
3042 string Buffer::layoutPos() const
3044 return d->layout_position;
3048 void Buffer::setLayoutPos(string const & path)
3051 d->layout_position.clear();
3055 LATTEST(FileName::isAbsolute(path));
3057 d->layout_position =
3058 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3060 if (d->layout_position.empty())
3061 d->layout_position = ".";
3065 bool Buffer::isReadonly() const
3067 return d->read_only;
3071 void Buffer::setParent(Buffer const * buffer)
3073 // Avoids recursive include.
3074 d->setParent(buffer == this ? 0 : buffer);
3079 Buffer const * Buffer::parent() const
3085 ListOfBuffers Buffer::allRelatives() const
3087 ListOfBuffers lb = masterBuffer()->getDescendents();
3088 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3093 Buffer const * Buffer::masterBuffer() const
3095 // FIXME Should be make sure we are not in some kind
3096 // of recursive include? A -> B -> A will crash this.
3097 Buffer const * const pbuf = d->parent();
3101 return pbuf->masterBuffer();
3105 bool Buffer::isChild(Buffer * child) const
3107 return d->children_positions.find(child) != d->children_positions.end();
3111 DocIterator Buffer::firstChildPosition(Buffer const * child)
3113 Impl::BufferPositionMap::iterator it;
3114 it = d->children_positions.find(child);
3115 if (it == d->children_positions.end())
3116 return DocIterator(this);
3121 bool Buffer::hasChildren() const
3123 return !d->children_positions.empty();
3127 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3129 // loop over children
3130 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3131 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3132 for (; it != end; ++it) {
3133 Buffer * child = const_cast<Buffer *>(it->first);
3135 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3136 if (bit != clist.end())
3138 clist.push_back(child);
3140 // there might be grandchildren
3141 child->collectChildren(clist, true);
3146 ListOfBuffers Buffer::getChildren() const
3149 collectChildren(v, false);
3150 // Make sure we have not included ourselves.
3151 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3152 if (bit != v.end()) {
3153 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3160 ListOfBuffers Buffer::getDescendents() const
3163 collectChildren(v, true);
3164 // Make sure we have not included ourselves.
3165 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3166 if (bit != v.end()) {
3167 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3174 template<typename M>
3175 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3180 typename M::const_iterator it = m.lower_bound(x);
3181 if (it == m.begin())
3189 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3190 DocIterator const & pos) const
3192 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3194 // if paragraphs have no macro context set, pos will be empty
3198 // we haven't found anything yet
3199 DocIterator bestPos = owner_->par_iterator_begin();
3200 MacroData const * bestData = 0;
3202 // find macro definitions for name
3203 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3204 if (nameIt != macros.end()) {
3205 // find last definition in front of pos or at pos itself
3206 PositionScopeMacroMap::const_iterator it
3207 = greatest_below(nameIt->second, pos);
3208 if (it != nameIt->second.end()) {
3210 // scope ends behind pos?
3211 if (pos < it->second.scope) {
3212 // Looks good, remember this. If there
3213 // is no external macro behind this,
3214 // we found the right one already.
3215 bestPos = it->first;
3216 bestData = &it->second.macro;
3220 // try previous macro if there is one
3221 if (it == nameIt->second.begin())
3228 // find macros in included files
3229 PositionScopeBufferMap::const_iterator it
3230 = greatest_below(position_to_children, pos);
3231 if (it == position_to_children.end())
3232 // no children before
3236 // do we know something better (i.e. later) already?
3237 if (it->first < bestPos )
3240 // scope ends behind pos?
3241 if (pos < it->second.scope
3242 && (cloned_buffer_ ||
3243 theBufferList().isLoaded(it->second.buffer))) {
3244 // look for macro in external file
3246 MacroData const * data
3247 = it->second.buffer->getMacro(name, false);
3250 bestPos = it->first;
3256 // try previous file if there is one
3257 if (it == position_to_children.begin())
3262 // return the best macro we have found
3267 MacroData const * Buffer::getMacro(docstring const & name,
3268 DocIterator const & pos, bool global) const
3273 // query buffer macros
3274 MacroData const * data = d->getBufferMacro(name, pos);
3278 // If there is a master buffer, query that
3279 Buffer const * const pbuf = d->parent();
3281 d->macro_lock = true;
3282 MacroData const * macro = pbuf->getMacro(
3283 name, *this, false);
3284 d->macro_lock = false;
3290 data = MacroTable::globalMacros().get(name);
3299 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3301 // set scope end behind the last paragraph
3302 DocIterator scope = par_iterator_begin();
3303 scope.pit() = scope.lastpit() + 1;
3305 return getMacro(name, scope, global);
3309 MacroData const * Buffer::getMacro(docstring const & name,
3310 Buffer const & child, bool global) const
3312 // look where the child buffer is included first
3313 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3314 if (it == d->children_positions.end())
3317 // check for macros at the inclusion position
3318 return getMacro(name, it->second, global);
3322 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3324 pit_type const lastpit = it.lastpit();
3326 // look for macros in each paragraph
3327 while (it.pit() <= lastpit) {
3328 Paragraph & par = it.paragraph();
3330 // iterate over the insets of the current paragraph
3331 InsetList const & insets = par.insetList();
3332 InsetList::const_iterator iit = insets.begin();
3333 InsetList::const_iterator end = insets.end();
3334 for (; iit != end; ++iit) {
3335 it.pos() = iit->pos;
3337 // is it a nested text inset?
3338 if (iit->inset->asInsetText()) {
3339 // Inset needs its own scope?
3340 InsetText const * itext = iit->inset->asInsetText();
3341 bool newScope = itext->isMacroScope();
3343 // scope which ends just behind the inset
3344 DocIterator insetScope = it;
3347 // collect macros in inset
3348 it.push_back(CursorSlice(*iit->inset));
3349 updateMacros(it, newScope ? insetScope : scope);
3354 if (iit->inset->asInsetTabular()) {
3355 CursorSlice slice(*iit->inset);
3356 size_t const numcells = slice.nargs();
3357 for (; slice.idx() < numcells; slice.forwardIdx()) {
3358 it.push_back(slice);
3359 updateMacros(it, scope);
3365 // is it an external file?
3366 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3367 // get buffer of external file
3368 InsetInclude const & inset =
3369 static_cast<InsetInclude const &>(*iit->inset);
3371 Buffer * child = inset.getChildBuffer();
3376 // register its position, but only when it is
3377 // included first in the buffer
3378 if (children_positions.find(child) ==
3379 children_positions.end())
3380 children_positions[child] = it;
3382 // register child with its scope
3383 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3387 InsetMath * im = iit->inset->asInsetMath();
3388 if (doing_export && im) {
3389 InsetMathHull * hull = im->asHullInset();
3391 hull->recordLocation(it);
3394 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3398 MathMacroTemplate & macroTemplate =
3399 *iit->inset->asInsetMath()->asMacroTemplate();
3400 MacroContext mc(owner_, it);
3401 macroTemplate.updateToContext(mc);
3404 bool valid = macroTemplate.validMacro();
3405 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3406 // then the BufferView's cursor will be invalid in
3407 // some cases which leads to crashes.
3412 // FIXME (Abdel), I don't understand why we pass 'it' here
3413 // instead of 'macroTemplate' defined above... is this correct?
3414 macros[macroTemplate.name()][it] =
3415 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3425 void Buffer::updateMacros() const
3430 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3432 // start with empty table
3434 d->children_positions.clear();
3435 d->position_to_children.clear();
3437 // Iterate over buffer, starting with first paragraph
3438 // The scope must be bigger than any lookup DocIterator
3439 // later. For the global lookup, lastpit+1 is used, hence
3440 // we use lastpit+2 here.
3441 DocIterator it = par_iterator_begin();
3442 DocIterator outerScope = it;
3443 outerScope.pit() = outerScope.lastpit() + 2;
3444 d->updateMacros(it, outerScope);
3448 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3450 InsetIterator it = inset_iterator_begin(inset());
3451 InsetIterator const end = inset_iterator_end(inset());
3452 for (; it != end; ++it) {
3453 if (it->lyxCode() == BRANCH_CODE) {
3454 InsetBranch & br = static_cast<InsetBranch &>(*it);
3455 docstring const name = br.branch();
3456 if (!from_master && !params().branchlist().find(name))
3457 result.push_back(name);
3458 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3459 result.push_back(name);
3462 if (it->lyxCode() == INCLUDE_CODE) {
3463 // get buffer of external file
3464 InsetInclude const & ins =
3465 static_cast<InsetInclude const &>(*it);
3466 Buffer * child = ins.getChildBuffer();
3469 child->getUsedBranches(result, true);
3472 // remove duplicates
3477 void Buffer::updateMacroInstances(UpdateType utype) const
3479 LYXERR(Debug::MACROS, "updateMacroInstances for "
3480 << d->filename.onlyFileName());
3481 DocIterator it = doc_iterator_begin(this);
3483 DocIterator const end = doc_iterator_end(this);
3484 for (; it != end; it.forwardInset()) {
3485 // look for MathData cells in InsetMathNest insets
3486 InsetMath * minset = it.nextInset()->asInsetMath();
3490 // update macro in all cells of the InsetMathNest
3491 DocIterator::idx_type n = minset->nargs();
3492 MacroContext mc = MacroContext(this, it);
3493 for (DocIterator::idx_type i = 0; i < n; ++i) {
3494 MathData & data = minset->cell(i);
3495 data.updateMacros(0, mc, utype);
3501 void Buffer::listMacroNames(MacroNameSet & macros) const
3506 d->macro_lock = true;
3508 // loop over macro names
3509 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3510 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3511 for (; nameIt != nameEnd; ++nameIt)
3512 macros.insert(nameIt->first);
3514 // loop over children
3515 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3516 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3517 for (; it != end; ++it)
3518 it->first->listMacroNames(macros);
3521 Buffer const * const pbuf = d->parent();
3523 pbuf->listMacroNames(macros);
3525 d->macro_lock = false;
3529 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3531 Buffer const * const pbuf = d->parent();
3536 pbuf->listMacroNames(names);
3539 MacroNameSet::iterator it = names.begin();
3540 MacroNameSet::iterator end = names.end();
3541 for (; it != end; ++it) {
3543 MacroData const * data =
3544 pbuf->getMacro(*it, *this, false);
3546 macros.insert(data);
3548 // we cannot access the original MathMacroTemplate anymore
3549 // here to calls validate method. So we do its work here manually.
3550 // FIXME: somehow make the template accessible here.
3551 if (data->optionals() > 0)
3552 features.require("xargs");
3558 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3561 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3563 RefCache::iterator it = d->ref_cache_.find(label);
3564 if (it != d->ref_cache_.end())
3565 return it->second.second;
3567 static InsetLabel const * dummy_il = 0;
3568 static References const dummy_refs;
3569 it = d->ref_cache_.insert(
3570 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3571 return it->second.second;
3575 Buffer::References const & Buffer::references(docstring const & label) const
3577 return const_cast<Buffer *>(this)->getReferenceCache(label);
3581 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3583 References & refs = getReferenceCache(label);
3584 refs.push_back(make_pair(inset, it));
3588 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3590 masterBuffer()->d->ref_cache_[label].first = il;
3594 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3596 return masterBuffer()->d->ref_cache_[label].first;
3600 void Buffer::clearReferenceCache() const
3603 d->ref_cache_.clear();
3607 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3609 //FIXME: This does not work for child documents yet.
3610 reloadBibInfoCache();
3612 // Check if the label 'from' appears more than once
3613 BiblioInfo const & keys = masterBibInfo();
3614 BiblioInfo::const_iterator bit = keys.begin();
3615 BiblioInfo::const_iterator bend = keys.end();
3616 vector<docstring> labels;
3618 for (; bit != bend; ++bit)
3620 labels.push_back(bit->first);
3622 if (count(labels.begin(), labels.end(), from) > 1)
3625 string const paramName = "key";
3626 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3627 if (it->lyxCode() != CITE_CODE)
3629 InsetCommand * inset = it->asInsetCommand();
3630 docstring const oldValue = inset->getParam(paramName);
3631 if (oldValue == from)
3632 inset->setParam(paramName, to);
3637 void Buffer::getSourceCode(odocstream & os, string const & format,
3638 pit_type par_begin, pit_type par_end,
3639 OutputWhat output, bool master) const
3641 OutputParams runparams(¶ms().encoding());
3642 runparams.nice = true;
3643 runparams.flavor = params().getOutputFlavor(format);
3644 runparams.linelen = lyxrc.plaintext_linelen;
3645 // No side effect of file copying and image conversion
3646 runparams.dryrun = true;
3648 if (output == CurrentParagraph) {
3649 runparams.par_begin = par_begin;
3650 runparams.par_end = par_end;
3651 if (par_begin + 1 == par_end) {
3653 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3657 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3658 convert<docstring>(par_begin),
3659 convert<docstring>(par_end - 1))
3662 // output paragraphs
3663 if (runparams.flavor == OutputParams::LYX) {
3664 Paragraph const & par = text().paragraphs()[par_begin];
3666 depth_type dt = par.getDepth();
3667 par.write(ods, params(), dt);
3668 os << from_utf8(ods.str());
3669 } else if (runparams.flavor == OutputParams::HTML) {
3671 setMathFlavor(runparams);
3672 xhtmlParagraphs(text(), *this, xs, runparams);
3673 } else if (runparams.flavor == OutputParams::TEXT) {
3675 // FIXME Handles only one paragraph, unlike the others.
3676 // Probably should have some routine with a signature like them.
3677 writePlaintextParagraph(*this,
3678 text().paragraphs()[par_begin], os, runparams, dummy);
3679 } else if (params().isDocBook()) {
3680 docbookParagraphs(text(), *this, os, runparams);
3682 // If we are previewing a paragraph, even if this is the
3683 // child of some other buffer, let's cut the link here,
3684 // so that no concurring settings from the master
3685 // (e.g. branch state) interfere (see #8101).
3687 d->ignore_parent = true;
3688 // We need to validate the Buffer params' features here
3689 // in order to know if we should output polyglossia
3690 // macros (instead of babel macros)
3691 LaTeXFeatures features(*this, params(), runparams);
3692 params().validate(features);
3693 runparams.use_polyglossia = features.usePolyglossia();
3698 // latex or literate
3699 otexstream ots(os, texrow);
3702 latexParagraphs(*this, text(), ots, runparams);
3704 // Restore the parenthood
3706 d->ignore_parent = false;
3710 if (output == FullSource)
3711 os << _("Preview source code");
3712 else if (output == OnlyPreamble)
3713 os << _("Preview preamble");
3714 else if (output == OnlyBody)
3715 os << _("Preview body");
3717 if (runparams.flavor == OutputParams::LYX) {
3719 if (output == FullSource)
3721 else if (output == OnlyPreamble)
3722 params().writeFile(ods, this);
3723 else if (output == OnlyBody)
3725 os << from_utf8(ods.str());
3726 } else if (runparams.flavor == OutputParams::HTML) {
3727 writeLyXHTMLSource(os, runparams, output);
3728 } else if (runparams.flavor == OutputParams::TEXT) {
3729 if (output == OnlyPreamble) {
3730 os << "% "<< _("Plain text does not have a preamble.");
3732 writePlaintextFile(*this, os, runparams);
3733 } else if (params().isDocBook()) {
3734 writeDocBookSource(os, absFileName(), runparams, output);
3736 // latex or literate
3738 d->texrow.newline();
3739 d->texrow.newline();
3740 otexstream ots(os, d->texrow);
3742 runparams.is_child = true;
3743 writeLaTeXSource(ots, string(), runparams, output);
3749 ErrorList & Buffer::errorList(string const & type) const
3751 return d->errorLists[type];
3755 void Buffer::updateTocItem(std::string const & type,
3756 DocIterator const & dit) const
3759 d->gui_->updateTocItem(type, dit);
3763 void Buffer::structureChanged() const
3766 d->gui_->structureChanged();
3770 void Buffer::errors(string const & err, bool from_master) const
3773 d->gui_->errors(err, from_master);
3777 void Buffer::message(docstring const & msg) const
3780 d->gui_->message(msg);
3784 void Buffer::setBusy(bool on) const
3787 d->gui_->setBusy(on);
3791 void Buffer::updateTitles() const
3794 d->wa_->updateTitles();
3798 void Buffer::resetAutosaveTimers() const
3801 d->gui_->resetAutosaveTimers();
3805 bool Buffer::hasGuiDelegate() const
3811 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3820 class AutoSaveBuffer : public ForkedProcess {
3823 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3824 : buffer_(buffer), fname_(fname) {}
3826 virtual shared_ptr<ForkedProcess> clone() const
3828 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3833 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3834 from_utf8(fname_.absFileName())));
3835 return run(DontWait);
3839 virtual int generateChild();
3841 Buffer const & buffer_;
3846 int AutoSaveBuffer::generateChild()
3848 #if defined(__APPLE__)
3849 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3850 * We should use something else like threads.
3852 * Since I do not know how to determine at run time what is the OS X
3853 * version, I just disable forking altogether for now (JMarc)
3855 pid_t const pid = -1;
3857 // tmp_ret will be located (usually) in /tmp
3858 // will that be a problem?
3859 // Note that this calls ForkedCalls::fork(), so it's
3860 // ok cross-platform.
3861 pid_t const pid = fork();
3862 // If you want to debug the autosave
3863 // you should set pid to -1, and comment out the fork.
3864 if (pid != 0 && pid != -1)
3868 // pid = -1 signifies that lyx was unable
3869 // to fork. But we will do the save
3871 bool failed = false;
3872 TempFile tempfile("lyxautoXXXXXX.lyx");
3873 tempfile.setAutoRemove(false);
3874 FileName const tmp_ret = tempfile.name();
3875 if (!tmp_ret.empty()) {
3876 if (!buffer_.writeFile(tmp_ret))
3878 else if (!tmp_ret.moveTo(fname_))
3884 // failed to write/rename tmp_ret so try writing direct
3885 if (!buffer_.writeFile(fname_)) {
3886 // It is dangerous to do this in the child,
3887 // but safe in the parent, so...
3888 if (pid == -1) // emit message signal.
3889 buffer_.message(_("Autosave failed!"));
3893 if (pid == 0) // we are the child so...
3902 FileName Buffer::getEmergencyFileName() const
3904 return FileName(d->filename.absFileName() + ".emergency");
3908 FileName Buffer::getAutosaveFileName() const
3910 // if the document is unnamed try to save in the backup dir, else
3911 // in the default document path, and as a last try in the filePath,
3912 // which will most often be the temporary directory
3915 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3916 : lyxrc.backupdir_path;
3917 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3920 string const fname = "#" + d->filename.onlyFileName() + "#";
3922 return makeAbsPath(fname, fpath);
3926 void Buffer::removeAutosaveFile() const
3928 FileName const f = getAutosaveFileName();
3934 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3936 FileName const newauto = getAutosaveFileName();
3938 if (newauto != oldauto && oldauto.exists())
3939 if (!oldauto.moveTo(newauto))
3940 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3944 bool Buffer::autoSave() const
3946 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3947 if (buf->d->bak_clean || isReadonly())
3950 message(_("Autosaving current document..."));
3951 buf->d->bak_clean = true;
3953 FileName const fname = getAutosaveFileName();
3954 LASSERT(d->cloned_buffer_, return false);
3956 // If this buffer is cloned, we assume that
3957 // we are running in a separate thread already.
3958 TempFile tempfile("lyxautoXXXXXX.lyx");
3959 tempfile.setAutoRemove(false);
3960 FileName const tmp_ret = tempfile.name();
3961 if (!tmp_ret.empty()) {
3963 // assume successful write of tmp_ret
3964 if (tmp_ret.moveTo(fname))
3967 // failed to write/rename tmp_ret so try writing direct
3968 return writeFile(fname);
3972 void Buffer::setExportStatus(bool e) const
3974 d->doing_export = e;
3975 ListOfBuffers clist = getDescendents();
3976 ListOfBuffers::const_iterator cit = clist.begin();
3977 ListOfBuffers::const_iterator const cen = clist.end();
3978 for (; cit != cen; ++cit)
3979 (*cit)->d->doing_export = e;
3983 bool Buffer::isExporting() const
3985 return d->doing_export;
3989 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3993 return doExport(target, put_in_tempdir, result_file);
3996 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3997 string & result_file) const
3999 bool const update_unincluded =
4000 params().maintain_unincluded_children
4001 && !params().getIncludedChildren().empty();
4003 // (1) export with all included children (omit \includeonly)
4004 if (update_unincluded) {
4005 ExportStatus const status =
4006 doExport(target, put_in_tempdir, true, result_file);
4007 if (status != ExportSuccess)
4010 // (2) export with included children only
4011 return doExport(target, put_in_tempdir, false, result_file);
4015 void Buffer::setMathFlavor(OutputParams & op) const
4017 switch (params().html_math_output) {
4018 case BufferParams::MathML:
4019 op.math_flavor = OutputParams::MathAsMathML;
4021 case BufferParams::HTML:
4022 op.math_flavor = OutputParams::MathAsHTML;
4024 case BufferParams::Images:
4025 op.math_flavor = OutputParams::MathAsImages;
4027 case BufferParams::LaTeX:
4028 op.math_flavor = OutputParams::MathAsLaTeX;
4034 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4035 bool includeall, string & result_file) const
4037 LYXERR(Debug::FILES, "target=" << target);
4038 OutputParams runparams(¶ms().encoding());
4039 string format = target;
4040 string dest_filename;
4041 size_t pos = target.find(' ');
4042 if (pos != string::npos) {
4043 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4044 format = target.substr(0, pos);
4045 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4046 FileName(dest_filename).onlyPath().createPath();
4047 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4049 MarkAsExporting exporting(this);
4050 string backend_format;
4051 runparams.flavor = OutputParams::LATEX;
4052 runparams.linelen = lyxrc.plaintext_linelen;
4053 runparams.includeall = includeall;
4054 vector<string> backs = params().backends();
4055 Converters converters = theConverters();
4056 bool need_nice_file = false;
4057 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4058 // Get shortest path to format
4059 converters.buildGraph();
4060 Graph::EdgePath path;
4061 for (vector<string>::const_iterator it = backs.begin();
4062 it != backs.end(); ++it) {
4063 Graph::EdgePath p = converters.getPath(*it, format);
4064 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4065 backend_format = *it;
4070 if (!put_in_tempdir) {
4071 // Only show this alert if this is an export to a non-temporary
4072 // file (not for previewing).
4073 Alert::error(_("Couldn't export file"), bformat(
4074 _("No information for exporting the format %1$s."),
4075 formats.prettyName(format)));
4077 return ExportNoPathToFormat;
4079 runparams.flavor = converters.getFlavor(path, this);
4080 Graph::EdgePath::const_iterator it = path.begin();
4081 Graph::EdgePath::const_iterator en = path.end();
4082 for (; it != en; ++it)
4083 if (theConverters().get(*it).nice()) {
4084 need_nice_file = true;
4089 backend_format = format;
4090 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4091 // FIXME: Don't hardcode format names here, but use a flag
4092 if (backend_format == "pdflatex")
4093 runparams.flavor = OutputParams::PDFLATEX;
4094 else if (backend_format == "luatex")
4095 runparams.flavor = OutputParams::LUATEX;
4096 else if (backend_format == "dviluatex")
4097 runparams.flavor = OutputParams::DVILUATEX;
4098 else if (backend_format == "xetex")
4099 runparams.flavor = OutputParams::XETEX;
4102 string filename = latexName(false);
4103 filename = addName(temppath(), filename);
4104 filename = changeExtension(filename,
4105 formats.extension(backend_format));
4106 LYXERR(Debug::FILES, "filename=" << filename);
4108 // Plain text backend
4109 if (backend_format == "text") {
4110 runparams.flavor = OutputParams::TEXT;
4111 writePlaintextFile(*this, FileName(filename), runparams);
4114 else if (backend_format == "xhtml") {
4115 runparams.flavor = OutputParams::HTML;
4116 setMathFlavor(runparams);
4117 makeLyXHTMLFile(FileName(filename), runparams);
4118 } else if (backend_format == "lyx")
4119 writeFile(FileName(filename));
4121 else if (params().isDocBook()) {
4122 runparams.nice = !put_in_tempdir;
4123 makeDocBookFile(FileName(filename), runparams);
4126 else if (backend_format == format || need_nice_file) {
4127 runparams.nice = true;
4128 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4129 if (d->cloned_buffer_)
4130 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4133 } else if (!lyxrc.tex_allows_spaces
4134 && contains(filePath(), ' ')) {
4135 Alert::error(_("File name error"),
4136 _("The directory path to the document cannot contain spaces."));
4137 return ExportTexPathHasSpaces;
4139 runparams.nice = false;
4140 bool const success = makeLaTeXFile(
4141 FileName(filename), filePath(), runparams);
4142 if (d->cloned_buffer_)
4143 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4148 string const error_type = (format == "program")
4149 ? "Build" : params().bufferFormat();
4150 ErrorList & error_list = d->errorLists[error_type];
4151 string const ext = formats.extension(format);
4152 FileName const tmp_result_file(changeExtension(filename, ext));
4153 bool const success = converters.convert(this, FileName(filename),
4154 tmp_result_file, FileName(absFileName()), backend_format, format,
4157 // Emit the signal to show the error list or copy it back to the
4158 // cloned Buffer so that it can be emitted afterwards.
4159 if (format != backend_format) {
4160 if (runparams.silent)
4162 else if (d->cloned_buffer_)
4163 d->cloned_buffer_->d->errorLists[error_type] =
4164 d->errorLists[error_type];
4167 // also to the children, in case of master-buffer-view
4168 ListOfBuffers clist = getDescendents();
4169 ListOfBuffers::const_iterator cit = clist.begin();
4170 ListOfBuffers::const_iterator const cen = clist.end();
4171 for (; cit != cen; ++cit) {
4172 if (runparams.silent)
4173 (*cit)->d->errorLists[error_type].clear();
4174 else if (d->cloned_buffer_) {
4175 // Enable reverse search by copying back the
4176 // texrow object to the cloned buffer.
4177 // FIXME: this is not thread safe.
4178 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4179 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4180 (*cit)->d->errorLists[error_type];
4182 (*cit)->errors(error_type, true);
4186 if (d->cloned_buffer_) {
4187 // Enable reverse dvi or pdf to work by copying back the texrow
4188 // object to the cloned buffer.
4189 // FIXME: There is a possibility of concurrent access to texrow
4190 // here from the main GUI thread that should be securized.
4191 d->cloned_buffer_->d->texrow = d->texrow;
4192 string const error_type = params().bufferFormat();
4193 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4197 if (put_in_tempdir) {
4198 result_file = tmp_result_file.absFileName();
4199 return success ? ExportSuccess : ExportConverterError;
4202 if (dest_filename.empty())
4203 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4205 result_file = dest_filename;
4206 // We need to copy referenced files (e. g. included graphics
4207 // if format == "dvi") to the result dir.
4208 vector<ExportedFile> const files =
4209 runparams.exportdata->externalFiles(format);
4210 string const dest = runparams.export_folder.empty() ?
4211 onlyPath(result_file) : runparams.export_folder;
4212 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4213 : force_overwrite == ALL_FILES;
4214 CopyStatus status = use_force ? FORCE : SUCCESS;
4216 vector<ExportedFile>::const_iterator it = files.begin();
4217 vector<ExportedFile>::const_iterator const en = files.end();
4218 for (; it != en && status != CANCEL; ++it) {
4219 string const fmt = formats.getFormatFromFile(it->sourceName);
4220 string fixedName = it->exportName;
4221 if (!runparams.export_folder.empty()) {
4222 // Relative pathnames starting with ../ will be sanitized
4223 // if exporting to a different folder
4224 while (fixedName.substr(0, 3) == "../")
4225 fixedName = fixedName.substr(3, fixedName.length() - 3);
4227 FileName fixedFileName = makeAbsPath(fixedName, dest);
4228 fixedFileName.onlyPath().createPath();
4229 status = copyFile(fmt, it->sourceName,
4231 it->exportName, status == FORCE,
4232 runparams.export_folder.empty());
4235 if (status == CANCEL) {
4236 message(_("Document export cancelled."));
4237 return ExportCancel;
4240 if (tmp_result_file.exists()) {
4241 // Finally copy the main file
4242 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4243 : force_overwrite != NO_FILES;
4244 if (status == SUCCESS && use_force)
4246 status = copyFile(format, tmp_result_file,
4247 FileName(result_file), result_file,
4249 if (status == CANCEL) {
4250 message(_("Document export cancelled."));
4251 return ExportCancel;
4253 message(bformat(_("Document exported as %1$s "
4255 formats.prettyName(format),
4256 makeDisplayPath(result_file)));
4259 // This must be a dummy converter like fax (bug 1888)
4260 message(bformat(_("Document exported as %1$s"),
4261 formats.prettyName(format)));
4264 return success ? ExportSuccess : ExportConverterError;
4268 Buffer::ExportStatus Buffer::preview(string const & format) const
4270 bool const update_unincluded =
4271 params().maintain_unincluded_children
4272 && !params().getIncludedChildren().empty();
4273 return preview(format, update_unincluded);
4277 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4279 MarkAsExporting exporting(this);
4281 // (1) export with all included children (omit \includeonly)
4283 ExportStatus const status = doExport(format, true, true, result_file);
4284 if (status != ExportSuccess)
4287 // (2) export with included children only
4288 ExportStatus const status = doExport(format, true, false, result_file);
4289 FileName const previewFile(result_file);
4291 LATTEST (isClone());
4292 d->cloned_buffer_->d->preview_file_ = previewFile;
4293 d->cloned_buffer_->d->preview_format_ = format;
4294 d->cloned_buffer_->d->preview_error_ = (status != ExportSuccess);
4296 if (status != ExportSuccess)
4298 if (previewFile.exists()) {
4299 if (!formats.view(*this, previewFile, format))
4300 return PreviewError;
4302 return PreviewSuccess;
4305 // Successful export but no output file?
4306 // Probably a bug in error detection.
4307 LATTEST (status != ExportSuccess);
4314 Buffer::ReadStatus Buffer::extractFromVC()
4316 bool const found = LyXVC::file_not_found_hook(d->filename);
4318 return ReadFileNotFound;
4319 if (!d->filename.isReadableFile())
4325 Buffer::ReadStatus Buffer::loadEmergency()
4327 FileName const emergencyFile = getEmergencyFileName();
4328 if (!emergencyFile.exists()
4329 || emergencyFile.lastModified() <= d->filename.lastModified())
4330 return ReadFileNotFound;
4332 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4333 docstring const text = bformat(_("An emergency save of the document "
4334 "%1$s exists.\n\nRecover emergency save?"), file);
4336 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4337 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4343 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4344 bool const success = (ret_llf == ReadSuccess);
4347 Alert::warning(_("File is read-only"),
4348 bformat(_("An emergency file is successfully loaded, "
4349 "but the original file %1$s is marked read-only. "
4350 "Please make sure to save the document as a different "
4351 "file."), from_utf8(d->filename.absFileName())));
4354 lyxvc().file_found_hook(d->filename);
4355 str = _("Document was successfully recovered.");
4357 str = _("Document was NOT successfully recovered.");
4358 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4359 makeDisplayPath(emergencyFile.absFileName()));
4361 int const del_emerg =
4362 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4363 _("&Remove"), _("&Keep"));
4364 if (del_emerg == 0) {
4365 emergencyFile.removeFile();
4367 Alert::warning(_("Emergency file deleted"),
4368 _("Do not forget to save your file now!"), true);
4370 return success ? ReadSuccess : ReadEmergencyFailure;
4373 int const del_emerg =
4374 Alert::prompt(_("Delete emergency file?"),
4375 _("Remove emergency file now?"), 1, 1,
4376 _("&Remove"), _("&Keep"));
4378 emergencyFile.removeFile();
4379 return ReadOriginal;
4389 Buffer::ReadStatus Buffer::loadAutosave()
4391 // Now check if autosave file is newer.
4392 FileName const autosaveFile = getAutosaveFileName();
4393 if (!autosaveFile.exists()
4394 || autosaveFile.lastModified() <= d->filename.lastModified())
4395 return ReadFileNotFound;
4397 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4398 docstring const text = bformat(_("The backup of the document %1$s "
4399 "is newer.\n\nLoad the backup instead?"), file);
4400 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4401 _("&Load backup"), _("Load &original"), _("&Cancel"));
4406 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4407 // the file is not saved if we load the autosave file.
4408 if (ret_llf == ReadSuccess) {
4410 Alert::warning(_("File is read-only"),
4411 bformat(_("A backup file is successfully loaded, "
4412 "but the original file %1$s is marked read-only. "
4413 "Please make sure to save the document as a "
4415 from_utf8(d->filename.absFileName())));
4418 lyxvc().file_found_hook(d->filename);
4421 return ReadAutosaveFailure;
4424 // Here we delete the autosave
4425 autosaveFile.removeFile();
4426 return ReadOriginal;
4434 Buffer::ReadStatus Buffer::loadLyXFile()
4436 if (!d->filename.isReadableFile()) {
4437 ReadStatus const ret_rvc = extractFromVC();
4438 if (ret_rvc != ReadSuccess)
4442 ReadStatus const ret_re = loadEmergency();
4443 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4446 ReadStatus const ret_ra = loadAutosave();
4447 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4450 return loadThisLyXFile(d->filename);
4454 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4456 return readFile(fn);
4460 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4462 TeXErrors::Errors::const_iterator it = terr.begin();
4463 TeXErrors::Errors::const_iterator end = terr.end();
4464 ListOfBuffers clist = getDescendents();
4465 ListOfBuffers::const_iterator cen = clist.end();
4467 for (; it != end; ++it) {
4470 int errorRow = it->error_in_line;
4471 Buffer const * buf = 0;
4473 if (it->child_name.empty())
4474 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4476 // The error occurred in a child
4477 ListOfBuffers::const_iterator cit = clist.begin();
4478 for (; cit != cen; ++cit) {
4479 string const child_name =
4480 DocFileName(changeExtension(
4481 (*cit)->absFileName(), "tex")).
4483 if (it->child_name != child_name)
4485 (*cit)->d->texrow.getIdFromRow(errorRow,
4486 id_start, pos_start);
4487 if (id_start != -1) {
4488 buf = d->cloned_buffer_
4489 ? (*cit)->d->cloned_buffer_->d->owner_
4490 : (*cit)->d->owner_;
4501 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4502 } while (found && id_start == id_end && pos_start == pos_end);
4504 if (id_start != id_end) {
4505 // Next registered position is outside the inset where
4506 // the error occurred, so signal end-of-paragraph
4510 errorList.push_back(ErrorItem(it->error_desc,
4511 it->error_text, id_start, pos_start, pos_end, buf));
4516 void Buffer::setBuffersForInsets() const
4518 inset().setBuffer(const_cast<Buffer &>(*this));
4522 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4524 LBUFERR(!text().paragraphs().empty());
4526 // Use the master text class also for child documents
4527 Buffer const * const master = masterBuffer();
4528 DocumentClass const & textclass = master->params().documentClass();
4530 // do this only if we are the top-level Buffer
4531 if (master == this) {
4532 textclass.counters().reset(from_ascii("bibitem"));
4533 reloadBibInfoCache();
4536 // keep the buffers to be children in this set. If the call from the
4537 // master comes back we can see which of them were actually seen (i.e.
4538 // via an InsetInclude). The remaining ones in the set need still be updated.
4539 static std::set<Buffer const *> bufToUpdate;
4540 if (scope == UpdateMaster) {
4541 // If this is a child document start with the master
4542 if (master != this) {
4543 bufToUpdate.insert(this);
4544 master->updateBuffer(UpdateMaster, utype);
4545 // If the master buffer has no gui associated with it, then the TocModel is
4546 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4547 // (bug 5699). The same happens if the master buffer is open in a different
4548 // window. This test catches both possibilities.
4549 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4550 // There remains a problem here: If there is another child open in yet a third
4551 // window, that TOC is not updated. So some more general solution is needed at
4553 if (master->d->gui_ != d->gui_)
4556 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4557 if (bufToUpdate.find(this) == bufToUpdate.end())
4561 // start over the counters in the master
4562 textclass.counters().reset();
4565 // update will be done below for this buffer
4566 bufToUpdate.erase(this);
4568 // update all caches
4569 clearReferenceCache();
4572 Buffer & cbuf = const_cast<Buffer &>(*this);
4575 ParIterator parit = cbuf.par_iterator_begin();
4576 updateBuffer(parit, utype);
4579 // TocBackend update will be done later.
4582 d->bibinfo_cache_valid_ = true;
4583 d->cite_labels_valid_ = true;
4584 cbuf.tocBackend().update(utype == OutputUpdate);
4585 if (scope == UpdateMaster)
4586 cbuf.structureChanged();
4590 static depth_type getDepth(DocIterator const & it)
4592 depth_type depth = 0;
4593 for (size_t i = 0 ; i < it.depth() ; ++i)
4594 if (!it[i].inset().inMathed())
4595 depth += it[i].paragraph().getDepth() + 1;
4596 // remove 1 since the outer inset does not count
4600 static depth_type getItemDepth(ParIterator const & it)
4602 Paragraph const & par = *it;
4603 LabelType const labeltype = par.layout().labeltype;
4605 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4608 // this will hold the lowest depth encountered up to now.
4609 depth_type min_depth = getDepth(it);
4610 ParIterator prev_it = it;
4613 --prev_it.top().pit();
4615 // start of nested inset: go to outer par
4617 if (prev_it.empty()) {
4618 // start of document: nothing to do
4623 // We search for the first paragraph with same label
4624 // that is not more deeply nested.
4625 Paragraph & prev_par = *prev_it;
4626 depth_type const prev_depth = getDepth(prev_it);
4627 if (labeltype == prev_par.layout().labeltype) {
4628 if (prev_depth < min_depth)
4629 return prev_par.itemdepth + 1;
4630 if (prev_depth == min_depth)
4631 return prev_par.itemdepth;
4633 min_depth = min(min_depth, prev_depth);
4634 // small optimization: if we are at depth 0, we won't
4635 // find anything else
4636 if (prev_depth == 0)
4642 static bool needEnumCounterReset(ParIterator const & it)
4644 Paragraph const & par = *it;
4645 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4646 depth_type const cur_depth = par.getDepth();
4647 ParIterator prev_it = it;
4648 while (prev_it.pit()) {
4649 --prev_it.top().pit();
4650 Paragraph const & prev_par = *prev_it;
4651 if (prev_par.getDepth() <= cur_depth)
4652 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4654 // start of nested inset: reset
4659 // set the label of a paragraph. This includes the counters.
4660 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4662 BufferParams const & bp = owner_->masterBuffer()->params();
4663 DocumentClass const & textclass = bp.documentClass();
4664 Paragraph & par = it.paragraph();
4665 Layout const & layout = par.layout();
4666 Counters & counters = textclass.counters();
4668 if (par.params().startOfAppendix()) {
4669 // We want to reset the counter corresponding to toplevel sectioning
4670 Layout const & lay = textclass.getTOCLayout();
4671 docstring const cnt = lay.counter;
4673 counters.reset(cnt);
4674 counters.appendix(true);
4676 par.params().appendix(counters.appendix());
4678 // Compute the item depth of the paragraph
4679 par.itemdepth = getItemDepth(it);
4681 if (layout.margintype == MARGIN_MANUAL) {
4682 if (par.params().labelWidthString().empty())
4683 par.params().labelWidthString(par.expandLabel(layout, bp));
4684 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4685 // we do not need to do anything here, since the empty case is
4686 // handled during export.
4688 par.params().labelWidthString(docstring());
4691 switch(layout.labeltype) {
4692 case LABEL_ITEMIZE: {
4693 // At some point of time we should do something more
4694 // clever here, like:
4695 // par.params().labelString(
4696 // bp.user_defined_bullet(par.itemdepth).getText());
4697 // for now, use a simple hardcoded label
4698 docstring itemlabel;
4699 switch (par.itemdepth) {
4701 itemlabel = char_type(0x2022);
4704 itemlabel = char_type(0x2013);
4707 itemlabel = char_type(0x2217);
4710 itemlabel = char_type(0x2219); // or 0x00b7
4713 par.params().labelString(itemlabel);
4717 case LABEL_ENUMERATE: {
4718 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4720 switch (par.itemdepth) {
4729 enumcounter += "iv";
4732 // not a valid enumdepth...
4736 // Maybe we have to reset the enumeration counter.
4737 if (needEnumCounterReset(it))
4738 counters.reset(enumcounter);
4739 counters.step(enumcounter, utype);
4741 string const & lang = par.getParLanguage(bp)->code();
4742 par.params().labelString(counters.theCounter(enumcounter, lang));
4747 case LABEL_SENSITIVE: {
4748 string const & type = counters.current_float();
4749 docstring full_label;
4751 full_label = owner_->B_("Senseless!!! ");
4753 docstring name = owner_->B_(textclass.floats().getType(type).name());
4754 if (counters.hasCounter(from_utf8(type))) {
4755 string const & lang = par.getParLanguage(bp)->code();
4756 counters.step(from_utf8(type), utype);
4757 full_label = bformat(from_ascii("%1$s %2$s:"),
4759 counters.theCounter(from_utf8(type), lang));
4761 full_label = bformat(from_ascii("%1$s #:"), name);
4763 par.params().labelString(full_label);
4767 case LABEL_NO_LABEL:
4768 par.params().labelString(docstring());
4772 case LABEL_CENTERED:
4773 case LABEL_STATIC: {
4774 docstring const & lcounter = layout.counter;
4775 if (!lcounter.empty()) {
4776 if (layout.toclevel <= bp.secnumdepth
4777 && (layout.latextype != LATEX_ENVIRONMENT
4778 || it.text()->isFirstInSequence(it.pit()))) {
4779 if (counters.hasCounter(lcounter))
4780 counters.step(lcounter, utype);
4781 par.params().labelString(par.expandLabel(layout, bp));
4783 par.params().labelString(docstring());
4785 par.params().labelString(par.expandLabel(layout, bp));
4791 par.params().labelString(par.expandLabel(layout, bp));
4796 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4798 // LASSERT: Is it safe to continue here, or should we just return?
4799 LASSERT(parit.pit() == 0, /**/);
4801 // Set the position of the text in the buffer to be able
4802 // to resolve macros in it.
4803 parit.text()->setMacrocontextPosition(parit);
4805 depth_type maxdepth = 0;
4806 pit_type const lastpit = parit.lastpit();
4807 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4808 // reduce depth if necessary
4809 if (parit->params().depth() > maxdepth) {
4810 /** FIXME: this function is const, but
4811 * nevertheless it modifies the buffer. To be
4812 * cleaner, one should modify the buffer in
4813 * another function, which is actually
4814 * non-const. This would however be costly in
4815 * terms of code duplication.
4817 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4818 parit->params().depth(maxdepth);
4820 maxdepth = parit->getMaxDepthAfter();
4822 if (utype == OutputUpdate) {
4823 // track the active counters
4824 // we have to do this for the master buffer, since the local
4825 // buffer isn't tracking anything.
4826 masterBuffer()->params().documentClass().counters().
4827 setActiveLayout(parit->layout());
4830 // set the counter for this paragraph
4831 d->setLabel(parit, utype);
4834 InsetList::const_iterator iit = parit->insetList().begin();
4835 InsetList::const_iterator end = parit->insetList().end();
4836 for (; iit != end; ++iit) {
4837 parit.pos() = iit->pos;
4838 iit->inset->updateBuffer(parit, utype);
4844 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4845 WordLangTuple & word_lang, docstring_list & suggestions) const
4849 suggestions.clear();
4850 word_lang = WordLangTuple();
4851 bool const to_end = to.empty();
4852 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4853 // OK, we start from here.
4854 for (; from != end; from.forwardPos()) {
4855 // This skips all insets with spell check disabled.
4856 while (!from.allowSpellCheck()) {
4860 // If from is at the end of the document (which is possible
4861 // when "from" was changed above) LyX will crash later otherwise.
4862 if (from.atEnd() || (!to_end && from >= end))
4865 from.paragraph().spellCheck();
4866 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4867 if (SpellChecker::misspelled(res)) {
4871 // Do not increase progress when from == to, otherwise the word
4872 // count will be wrong.
4882 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4884 bool inword = false;
4889 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4890 if (!dit.inTexted()) {
4895 Paragraph const & par = dit.paragraph();
4896 pos_type const pos = dit.pos();
4898 // Copied and adapted from isWordSeparator() in Paragraph
4899 if (pos == dit.lastpos()) {
4902 Inset const * ins = par.getInset(pos);
4903 if (ins && skipNoOutput && !ins->producesOutput()) {
4906 // stop if end of range was skipped
4907 if (!to.atEnd() && dit >= to)
4910 } else if (!par.isDeleted(pos)) {
4911 if (par.isWordSeparator(pos))
4917 if (ins && ins->isLetter())
4919 else if (ins && ins->isSpace())
4922 char_type const c = par.getChar(pos);
4923 if (isPrintableNonspace(c))
4925 else if (isSpace(c))
4935 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4937 d->updateStatistics(from, to, skipNoOutput);
4941 int Buffer::wordCount() const
4943 return d->wordCount();
4947 int Buffer::charCount(bool with_blanks) const
4949 return d->charCount(with_blanks);
4953 Buffer::ReadStatus Buffer::reload()
4956 // c.f. bug http://www.lyx.org/trac/ticket/6587
4957 removeAutosaveFile();
4958 // e.g., read-only status could have changed due to version control
4959 d->filename.refresh();
4960 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4962 // clear parent. this will get reset if need be.
4964 ReadStatus const status = loadLyXFile();
4965 if (status == ReadSuccess) {
4970 message(bformat(_("Document %1$s reloaded."), disp_fn));
4973 message(bformat(_("Could not reload document %1$s."), disp_fn));
4983 bool Buffer::saveAs(FileName const & fn)
4985 FileName const old_name = fileName();
4986 FileName const old_auto = getAutosaveFileName();
4987 bool const old_unnamed = isUnnamed();
4988 bool success = true;
4989 d->old_position = filePath();
4996 // bring the autosave file with us, just in case.
4997 moveAutosaveFile(old_auto);
4998 // validate version control data and
4999 // correct buffer title
5000 lyxvc().file_found_hook(fileName());
5002 // the file has now been saved to the new location.
5003 // we need to check that the locations of child buffers
5005 checkChildBuffers();
5006 checkMasterBuffer();
5009 // reset the old filename and unnamed state
5010 setFileName(old_name);
5011 setUnnamed(old_unnamed);
5015 d->old_position.clear();
5020 void Buffer::checkChildBuffers()
5022 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
5023 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
5024 for (; it != en; ++it) {
5025 DocIterator dit = it->second;
5026 Buffer * cbuf = const_cast<Buffer *>(it->first);
5027 if (!cbuf || !theBufferList().isLoaded(cbuf))
5029 Inset * inset = dit.nextInset();
5030 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5031 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5032 docstring const & incfile = inset_inc->getParam("filename");
5033 string oldloc = cbuf->absFileName();
5034 string newloc = makeAbsPath(to_utf8(incfile),
5035 onlyPath(absFileName())).absFileName();
5036 if (oldloc == newloc)
5038 // the location of the child file is incorrect.
5040 inset_inc->setChildBuffer(0);
5042 // invalidate cache of children
5043 d->children_positions.clear();
5044 d->position_to_children.clear();
5048 // If a child has been saved under a different name/path, it might have been
5049 // orphaned. Therefore the master needs to be reset (bug 8161).
5050 void Buffer::checkMasterBuffer()
5052 Buffer const * const master = masterBuffer();
5056 // necessary to re-register the child (bug 5873)
5057 // FIXME: clean up updateMacros (here, only
5058 // child registering is needed).
5059 master->updateMacros();
5060 // (re)set master as master buffer, but only
5061 // if we are a real child
5062 if (master->isChild(this))
5069 string Buffer::includedFilePath(string const & name, string const & ext) const
5071 bool isabsolute = FileName::isAbsolute(name);
5072 // old_position already contains a trailing path separator
5073 string const absname = isabsolute ? name : d->old_position + name;
5075 if (d->old_position.empty() || d->old_position == filePath()
5076 || !FileName(addExtension(absname, ext)).exists())
5080 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5082 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5083 from_utf8(filePath())));