4 * This file is part of LyX, the document processor.
5 * Licence details can be found in the file COPYING.
7 * \author Lars Gullik Bjønnes
9 * Full author contact details are available in file CREDITS.
15 #include "OutputEnums.h"
16 #include "OutputParams.h"
18 #include "support/strfwd.h"
19 #include "support/types.h"
54 class ParConstIterator;
64 class GuiBufferDelegate;
65 class WorkAreaManager;
79 typedef std::list<Buffer *> ListOfBuffers;
80 /// a list of Buffers we cloned
81 typedef std::set<Buffer *> CloneList;
84 /** The buffer object.
85 * This is the buffer object. It contains all the information about
86 * a document loaded into LyX.
87 * The buffer object owns the Text (wrapped in an InsetText), which
88 * contains the individual paragraphs of the document.
91 * I am not sure if the class is complete or
92 * minimal, probably not.
93 * \author Lars Gullik Bjønnes
96 class MarkAsExporting;
100 /// What type of log will \c getLogName() return?
102 latexlog, ///< LaTeX log
103 buildlog ///< Literate build log
106 /// Result of \c readFile()
116 ReadEmergencyFailure,
133 ExportNoPathToFormat,
134 ExportTexPathHasSpaces,
135 ExportConverterError,
137 // Implies ExportSuccess.
139 // The exported file exists but there was an error when opening
144 /// Method to check if a file is externally modified, used by
145 /// isExternallyModified()
147 * timestamp is fast but inaccurate. For example, the granularity
148 * of timestamp on a FAT filesystem is 2 seconds. Also, various operations
149 * may touch the timestamp of a file even when its content is unchanged.
151 * checksum is accurate but slow, which can be a problem when it is
152 * frequently used, or used for a large file on a slow (network) file
155 * FIXME: replace this method with support/FileMonitor.
158 checksum_method, ///< Use file checksum
159 timestamp_method ///< Use timestamp, and checksum if timestamp has changed
169 explicit Buffer(std::string const & file, bool readonly = false,
170 Buffer const * cloned_buffer = 0);
175 /// Clones the entire structure of which this Buffer is part, starting
176 /// with the master and cloning all the children, too.
177 Buffer * cloneFromMaster() const;
178 /// Just clones this single Buffer. For autosave.
179 Buffer * cloneBufferOnly() const;
181 bool isClone() const;
183 /** High-level interface to buffer functionality.
184 This function parses a command string and executes it.
186 void dispatch(std::string const & command, DispatchResult & result);
188 /// Maybe we know the function already by number...
189 void dispatch(FuncRequest const & func, DispatchResult & result);
191 /// Can this function be exectued?
192 /// \return true if we made a decision
193 bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
196 DocIterator getParFromID(int id) const;
197 /// do we have a paragraph with this id?
198 bool hasParWithID(int id) const;
201 frontend::WorkAreaManager & workAreaManager() const;
204 Takes care of auto-save files and backup file if requested.
205 Returns \c true if the save is successful, \c false otherwise.
208 /// Renames and saves the buffer
209 bool saveAs(support::FileName const & fn);
211 /// Write document to stream. Returns \c false if unsuccessful.
212 bool write(std::ostream &) const;
213 /// Write file. Returns \c false if unsuccessful.
214 bool writeFile(support::FileName const &) const;
216 /// \name Functions involved in reading files/strings.
218 /// Loads the LyX file into the buffer. This function
219 /// tries to extract the file from version control if it
220 /// cannot be found. If it can be found, it will try to
221 /// read an emergency save file or an autosave file.
222 /// \sa loadThisLyXFile
223 ReadStatus loadLyXFile();
224 /// Loads the LyX file \c fn into the buffer. If you want
225 /// to check for files in a version control container,
226 /// emergency or autosave files, one should use \c loadLyXFile.
228 ReadStatus loadThisLyXFile(support::FileName const & fn);
229 /// import a new document from a string
230 bool importString(std::string const &, docstring const &, ErrorList &);
231 /// import a new file
232 bool importFile(std::string const &, support::FileName const &, ErrorList &);
233 /// read a new document from a string
234 bool readString(std::string const &);
235 /// Reloads the LyX file
237 //FIXME: The following function should be private
239 /// read the header, returns number of unknown tokens
240 int readHeader(Lexer & lex);
242 double fontScalingFactor() const;
246 typedef std::map<Buffer const *, Buffer *> BufferMap;
248 void cloneWithChildren(BufferMap &, CloneList *) const;
249 /// save timestamp and checksum of the given file.
250 void saveCheckSum() const;
252 ReadStatus readFile(support::FileName const & fn);
253 /// Reads a file without header.
254 /// \param par if != 0 insert the file.
255 /// \return \c true if file is not completely read.
256 bool readDocument(Lexer &);
257 /// Try to extract the file from a version control container
258 /// before reading if the file cannot be found.
259 /// \sa LyXVC::file_not_found_hook
260 ReadStatus extractFromVC();
261 /// Reads the first tag of a LyX File and
262 /// returns the file format number.
263 ReadStatus parseLyXFormat(Lexer & lex, support::FileName const & fn,
264 int & file_format) const;
265 /// Convert the LyX file to the LYX_FORMAT using
266 /// the lyx2lyx script and returns the filename
267 /// of the temporary file to be read
268 ReadStatus convertLyXFormat(support::FileName const & fn,
269 support::FileName & tmpfile, int from_format);
273 /// \name Functions involved in autosave and emergency files.
275 /// Save an autosave file to #filename.lyx#
276 bool autoSave() const;
277 /// save emergency file
278 /// \return a status message towards the user.
279 docstring emergencyWrite();
281 //FIXME:The following function should be private
284 void removeAutosaveFile() const;
287 /// Try to load an autosave file associated to \c fn.
288 ReadStatus loadAutosave();
289 /// Try to load an emergency file associated to \c fn.
290 ReadStatus loadEmergency();
291 /// Get the filename of the emergency file associated with the Buffer
292 support::FileName getEmergencyFileName() const;
293 /// Get the filename of the autosave file associated with the Buffer
294 support::FileName getAutosaveFileName() const;
296 void moveAutosaveFile(support::FileName const & old) const;
300 /// Fill in the ErrorList with the TeXErrors
301 void bufferErrors(TeXErrors const &, ErrorList &) const;
311 /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
312 bool makeLaTeXFile(support::FileName const & filename,
313 std::string const & original_path,
314 OutputParams const &,
315 OutputWhat output = FullSource) const;
316 /** Export the buffer to LaTeX.
317 If \p os is a file stream, and params().inputenc is "auto" or
318 "default", and the buffer contains text in different languages
319 with more than one encoding, then this method will change the
320 encoding associated to \p os. Therefore you must not call this
321 method with a string stream if the output is supposed to go to a
324 otexstream os(ofs, texrow);
325 ofs.open("test.tex");
326 writeLaTeXSource(os, ...);
328 \endcode is NOT equivalent to \code
329 odocstringstream oss;
330 otexstream os(oss, texrow);
331 writeLaTeXSource(os, ...);
333 ofs.open("test.tex");
338 void writeLaTeXSource(otexstream & os,
339 std::string const & original_path,
340 OutputParams const &,
341 OutputWhat output = FullSource) const;
343 void makeDocBookFile(support::FileName const & filename,
344 OutputParams const & runparams_in,
345 OutputWhat output = FullSource) const;
347 void writeDocBookSource(odocstream & os, std::string const & filename,
348 OutputParams const & runparams_in,
349 OutputWhat output = FullSource) const;
351 void makeLyXHTMLFile(support::FileName const & filename,
352 OutputParams const & runparams_in) const;
354 void writeLyXHTMLSource(odocstream & os,
355 OutputParams const & runparams_in,
356 OutputWhat output = FullSource) const;
357 /// returns the main language for the buffer (document)
358 Language const * language() const;
359 /// get l10n translated to the buffers language
360 docstring const B_(std::string const & l10n) const;
364 /// return true if the main lyx file does not need saving
365 bool isClean() const;
367 bool isDepClean(std::string const & name) const;
369 /// whether or not disk file has been externally modified
370 bool isExternallyModified(CheckMethod method) const;
372 /// mark the main lyx file as not needing saving
373 void markClean() const;
376 void markDepClean(std::string const & name);
379 void setUnnamed(bool flag = true);
381 /// Whether or not a filename has been assigned to this buffer
382 bool isUnnamed() const;
384 /// Whether or not this buffer is internal.
386 /// An internal buffer does not contain a real document, but some auxiliary text segment.
387 /// It is not associated with a filename, it is never saved, thus it does not need to be
388 /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
389 bool isInternal() const;
391 void setInternal(bool flag);
393 /// Mark this buffer as dirty.
396 /// Returns the buffer's filename. It is always an absolute path.
397 support::FileName fileName() const;
399 /// Returns the buffer's filename. It is always an absolute path.
400 std::string absFileName() const;
402 /// Returns the path where the buffer lives.
403 /// It is always an absolute path.
404 std::string filePath() const;
406 /** A transformed version of the file name, adequate for LaTeX.
407 \param no_path optional if \c true then the path is stripped.
409 std::string latexName(bool no_path = true) const;
411 /// Get the name and type of the log.
412 std::string logName(LogType * type = 0) const;
414 /// Set document's parent Buffer.
415 void setParent(Buffer const *);
416 Buffer const * parent() const;
418 /** Get the document's master (or \c this if this is not a
421 Buffer const * masterBuffer() const;
423 /// \return true if \p child is a child of this \c Buffer.
424 bool isChild(Buffer * child) const;
426 /// \return true if this \c Buffer has children
427 bool hasChildren() const;
429 /// \return a list of the direct children of this Buffer.
430 /// this list has no duplicates and is in the order in which
431 /// the children appear.
432 ListOfBuffers getChildren() const;
434 /// \return a list of all descendents of this Buffer (children,
435 /// grandchildren, etc). this list has no duplicates and is in
436 /// the order in which the children appear.
437 ListOfBuffers getDescendents() const;
439 /// Collect all relative buffers, in the order in which they appear.
440 /// I.e., the "root" Buffer is first, then its first child, then any
441 /// of its children, etc. However, there are no duplicates in this
443 /// This is "stable", too, in the sense that it returns the same
444 /// thing from whichever Buffer it is called.
445 ListOfBuffers allRelatives() const;
447 /// Is buffer read-only?
448 bool isReadonly() const;
450 /// Set buffer read-only flag
451 void setReadonly(bool flag = true);
453 /** Validate a buffer for LaTeX.
454 This validates the buffer, and returns a struct for use by
455 #makeLaTeX# and others. Its main use is to figure out what
456 commands and packages need to be included in the LaTeX file.
457 It (should) also check that the needed constructs are there
458 (i.e. that the \refs points to coresponding \labels). It
459 should perhaps inset "error" insets to help the user correct
462 void validate(LaTeXFeatures &) const;
464 /// Reference information is cached in the Buffer, so we do not
465 /// have to check or read things over and over.
467 /// There are two caches.
469 /// One is a cache of the BibTeX files from which reference info is
470 /// being gathered. This cache is PER BUFFER, and the cache for the
471 /// master essentially includes the cache for its children. This gets
472 /// invalidated when an InsetBibtex is created, deleted, or modified.
474 /// The other is a cache of the reference information itself. This
475 /// exists only in the master buffer, and when it needs to be updated,
476 /// the children add their information to the master's cache.
478 /// Calling this method invalidates the cache and so requires a
480 void invalidateBibinfoCache() const;
481 /// This invalidates the cache of files we need to check.
482 void invalidateBibfileCache() const;
483 /// Updates the cached bibliography information, checking first to see
484 /// whether the cache is valid. If so, we do nothing. If not, then we
485 /// reload all the BibTeX info.
486 /// Note that this operates on the master document.
487 void reloadBibInfoCache() const;
488 /// \return the bibliography information for this buffer's master,
489 /// or just for it, if it isn't a child.
490 BiblioInfo const & masterBibInfo() const;
491 /// collect bibliography info from the various insets in this buffer.
492 void collectBibKeys() const;
493 /// add some BiblioInfo to our cache
494 void addBiblioInfo(BiblioInfo const & bi) const;
495 /// add a single piece of bibliography info to our cache
496 void addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const;
498 void makeCitationLabels() const;
500 bool citeLabelsValid() const;
502 void getLabelList(std::vector<docstring> &) const;
504 /// This removes the .aux and .bbl files from the temp dir.
505 void removeBiblioTempFiles() const;
508 void changeLanguage(Language const * from, Language const * to);
511 bool isMultiLingual() const;
513 std::set<Language const *> getLanguages() const;
516 BufferParams & params();
517 BufferParams const & params() const;
519 BufferParams const & masterParams() const;
521 /** The list of paragraphs.
522 This is a linked list of paragraph, this list holds the
523 whole contents of the document.
525 ParagraphList & paragraphs();
526 ParagraphList const & paragraphs() const;
528 /// LyX version control object.
530 LyXVC const & lyxvc() const;
532 /// Where to put temporary files.
533 std::string const temppath() const;
535 /// Used when typesetting to place errorboxes.
536 TexRow const & texrow() const;
540 ParIterator par_iterator_begin();
542 ParConstIterator par_iterator_begin() const;
544 ParIterator par_iterator_end();
546 ParConstIterator par_iterator_end() const;
548 // Position of the child buffer where it appears first in the master.
549 DocIterator firstChildPosition(Buffer const * child);
551 /** \returns true only when the file is fully loaded.
552 * Used to prevent the premature generation of previews
553 * and by the citation inset.
555 bool isFullyLoaded() const;
556 /// Set by buffer_funcs' newFile.
557 void setFullyLoaded(bool);
559 /// FIXME: Needed by RenderPreview.
560 graphics::PreviewLoader * loader() const;
561 /// Update the LaTeX preview snippets associated with this buffer
562 void updatePreviews() const;
563 /// Remove any previewed LaTeX snippets associated with this buffer
564 void removePreviews() const;
566 /// Our main text (inside the top InsetText)
569 /// Our top InsetText
570 Inset & inset() const;
575 /// Collect macro definitions in paragraphs
576 void updateMacros() const;
577 /// Iterate through the whole buffer and try to resolve macros
578 void updateMacroInstances(UpdateType) const;
580 /// List macro names of this buffer, the parent and the children
581 void listMacroNames(MacroNameSet & macros) const;
582 /// Collect macros of the parent and its children in front of this buffer.
583 void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
585 /// Return macro defined before pos (or in the master buffer)
586 MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
587 /// Return macro defined anywhere in the buffer (or in the master buffer)
588 MacroData const * getMacro(docstring const & name, bool global = true) const;
589 /// Return macro defined before the inclusion of the child
590 MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
592 /// Collect user macro names at loading time
593 typedef std::set<docstring> UserMacroSet;
594 mutable UserMacroSet usermacros;
596 /// Replace the inset contents for insets which InsetCode is equal
597 /// to the passed \p inset_code.
598 void changeRefsIfUnique(docstring const & from, docstring const & to);
600 /// get source code (latex/docbook) for some paragraphs, or all paragraphs
601 /// including preamble
602 void getSourceCode(odocstream & os, std::string const & format,
603 pit_type par_begin, pit_type par_end, OutputWhat output,
606 /// Access to error list.
607 /// This method is used only for GUI visualisation of Buffer related
608 /// errors (like parsing or LateX compilation). This method is const
609 /// because modifying the returned ErrorList does not touch the document
611 ErrorList & errorList(std::string const & type) const;
614 /// This is useful only for screen visualisation of the Buffer. This
615 /// method is const because modifying this backend does not touch
616 /// the document contents.
617 TocBackend & tocBackend() const;
622 /// This function is called when the buffer is changed.
623 void changed(bool update_metrics) const;
625 void setChild(DocIterator const & dit, Buffer * child);
627 void updateTocItem(std::string const &, DocIterator const &) const;
628 /// This function is called when the buffer structure is changed.
629 void structureChanged() const;
630 /// This function is called when some parsing error shows up.
631 void errors(std::string const & err, bool from_master = false) const;
632 /// This function is called when the buffer busy status change.
633 void setBusy(bool on) const;
634 /// Update window titles of all users.
635 void updateTitles() const;
636 /// Reset autosave timers for all users.
637 void resetAutosaveTimers() const;
639 void message(docstring const & msg) const;
642 void setGuiDelegate(frontend::GuiBufferDelegate * gui);
644 bool hasGuiDelegate() const;
647 ExportStatus doExport(std::string const & target, bool put_in_tempdir) const;
648 /// Export buffer to format \p format and open the result in a suitable viewer.
649 /// Note: This has nothing to do with preview of graphics or math formulas.
650 ExportStatus preview(std::string const & format) const;
654 ExportStatus doExport(std::string const & target, bool put_in_tempdir,
655 std::string & result_file) const;
656 /// target is a format name optionally followed by a space
657 /// and a destination file-name
658 ExportStatus doExport(std::string const & target, bool put_in_tempdir,
659 bool includeall, std::string & result_file) const;
661 ExportStatus preview(std::string const & format, bool includeall = false) const;
663 void setMathFlavor(OutputParams & op) const;
667 bool isExporting() const;
670 typedef std::vector<std::pair<Inset *, ParIterator> > References;
672 References const & references(docstring const & label) const;
674 void addReference(docstring const & label, Inset * inset, ParIterator it);
676 void clearReferenceCache() const;
678 void setInsetLabel(docstring const & label, InsetLabel const * il);
680 InsetLabel const * insetLabel(docstring const & label) const;
682 /// return a list of all used branches (also in children)
683 void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
685 /// sets the buffer_ member for every inset in this buffer.
686 // FIXME This really shouldn't be needed, but at the moment it's not
687 // clear how to do it just for the individual pieces we need.
688 void setBuffersForInsets() const;
689 /// Updates screen labels and some other information associated with
690 /// insets and paragraphs. Actually, it's more like a general "recurse
691 /// through the Buffer" routine, that visits all the insets and paragraphs.
692 void updateBuffer() const { updateBuffer(UpdateMaster, InternalUpdate); }
693 /// \param scope: whether to start with the master document or just
695 /// \param output: whether we are preparing for output.
696 void updateBuffer(UpdateScope scope, UpdateType utype) const;
698 void updateBuffer(ParIterator & parit, UpdateType utype) const;
700 /// Spellcheck starting from \p from.
701 /// \p from initial position, will then points to the next misspelled
703 /// \p to will points to the end of the next misspelled word.
704 /// \p word_lang will contain the found misspelled word.
705 /// \return progress if a new word was found.
706 int spellCheck(DocIterator & from, DocIterator & to,
707 WordLangTuple & word_lang, docstring_list & suggestions) const;
709 void checkChildBuffers();
711 void checkMasterBuffer();
713 /// compute statistics between \p from and \p to
714 /// \p from initial position
715 /// \p to points to the end position
716 /// \p skipNoOutput if notes etc. should be ignored
717 void updateStatistics(DocIterator & from, DocIterator & to,
718 bool skipNoOutput = true) const;
719 /// statistics accessor functions
720 int wordCount() const;
721 int charCount(bool with_blanks) const;
724 friend class MarkAsExporting;
725 /// mark the buffer as busy exporting something, or not
726 void setExportStatus(bool e) const;
729 References & getReferenceCache(docstring const & label);
730 /// Change name of buffer. Updates "read-only" flag.
731 void setFileName(support::FileName const & fname);
733 void getLanguages(std::set<Language const *> &) const;
734 /// Checks whether any of the referenced bibfiles have changed since the
735 /// last time we loaded the cache. Note that this does NOT update the
736 /// cached information.
737 void checkIfBibInfoCacheIsValid() const;
738 /// Update the list of all bibfiles in use (including bibfiles
739 /// of loaded child documents).
740 void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
741 /// Return the list with all bibfiles in use (including bibfiles
742 /// of loaded child documents).
743 support::FileNameList const &
744 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
746 void collectChildren(ListOfBuffers & children, bool grand_children) const;
749 Buffer(Buffer const &);
750 void operator=(Buffer const &);
752 /// Use the Pimpl idiom to hide the internals.
754 /// The pointer never changes although *pimpl_'s contents may.
759 /// Helper class, to guarantee that the export status
760 /// gets reset properly. To use, simply create a local variable:
761 /// MarkAsExporting mex(bufptr);
762 /// and leave the rest to us.
763 class MarkAsExporting {
765 MarkAsExporting(Buffer const * buf) : buf_(buf)
767 buf_->setExportStatus(true);
771 buf_->setExportStatus(false);
774 Buffer const * const buf_;