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 "insets/InsetCode.h"
20 #include "support/strfwd.h"
21 #include "support/types.h"
56 class ParConstIterator;
66 class GuiBufferDelegate;
67 class WorkAreaManager;
81 typedef std::list<Buffer *> ListOfBuffers;
82 /// a list of Buffers we cloned
83 typedef std::set<Buffer *> CloneList;
86 /** The buffer object.
87 * This is the buffer object. It contains all the information about
88 * a document loaded into LyX.
89 * The buffer object owns the Text (wrapped in an InsetText), which
90 * contains the individual paragraphs of the document.
93 * I am not sure if the class is complete or
94 * minimal, probably not.
95 * \author Lars Gullik Bjønnes
99 /// What type of log will \c getLogName() return?
101 latexlog, ///< LaTeX log
102 buildlog ///< Literate build log
105 /// Result of \c readFile()
115 ReadEmergencyFailure,
132 ExportNoPathToFormat,
133 ExportTexPathHasSpaces,
134 ExportConverterError,
140 /// Method to check if a file is externally modified, used by
141 /// isExternallyModified()
143 * timestamp is fast but inaccurate. For example, the granularity
144 * of timestamp on a FAT filesystem is 2 seconds. Also, various operations
145 * may touch the timestamp of a file even when its content is unchanged.
147 * checksum is accurate but slow, which can be a problem when it is
148 * frequently used, or used for a large file on a slow (network) file
151 * FIXME: replace this method with support/FileMonitor.
154 checksum_method, ///< Use file checksum
155 timestamp_method ///< Use timestamp, and checksum if timestamp has changed
165 explicit Buffer(std::string const & file, bool readonly = false,
166 Buffer const * cloned_buffer = 0);
171 /// Clones the entire structure of which this Buffer is part, starting
172 /// with the master and cloning all the children, too.
173 Buffer * cloneFromMaster() const;
174 /// Just clones this single Buffer. For autosave.
175 Buffer * cloneBufferOnly() const;
177 bool isClone() const;
179 /** High-level interface to buffer functionality.
180 This function parses a command string and executes it.
182 void dispatch(std::string const & command, DispatchResult & result);
184 /// Maybe we know the function already by number...
185 void dispatch(FuncRequest const & func, DispatchResult & result);
187 /// Can this function be exectued?
188 /// \return true if we made a decision
189 bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
192 DocIterator getParFromID(int id) const;
193 /// do we have a paragraph with this id?
194 bool hasParWithID(int id) const;
197 frontend::WorkAreaManager & workAreaManager() const;
200 Takes care of auto-save files and backup file if requested.
201 Returns \c true if the save is successful, \c false otherwise.
204 /// Renames and saves the buffer
205 bool saveAs(support::FileName const & fn);
207 /// Write document to stream. Returns \c false if unsuccessful.
208 bool write(std::ostream &) const;
209 /// Write file. Returns \c false if unsuccessful.
210 bool writeFile(support::FileName const &) const;
212 /// \name Functions involved in reading files/strings.
214 /// Loads the LyX file into the buffer. This function
215 /// tries to extract the file from version control if it
216 /// cannot be found. If it can be found, it will try to
217 /// read an emergency save file or an autosave file.
218 /// \sa loadThisLyXFile
219 ReadStatus loadLyXFile();
220 /// Loads the LyX file \c fn into the buffer. If you want
221 /// to check for files in a version control container,
222 /// emergency or autosave files, one should use \c loadLyXFile.
224 ReadStatus loadThisLyXFile(support::FileName const & fn);
225 /// read a new document from a string
226 bool readString(std::string const &);
227 /// Reloads the LyX file
228 /// \param clearUndo if false, leave alone the undo stack.
229 ReadStatus reload(bool clearUndo = true);
230 //FIXME: The following function should be private
232 /// read the header, returns number of unknown tokens
233 int readHeader(Lexer & lex);
237 typedef std::map<Buffer const *, Buffer *> BufferMap;
239 void cloneWithChildren(BufferMap &, CloneList *) const;
240 /// save timestamp and checksum of the given file.
241 void saveCheckSum() const;
243 ReadStatus readFile(support::FileName const & fn);
244 /// Reads a file without header.
245 /// \param par if != 0 insert the file.
246 /// \return \c true if file is not completely read.
247 bool readDocument(Lexer &);
248 /// Try to extract the file from a version control container
249 /// before reading if the file cannot be found.
250 /// \sa LyXVC::file_not_found_hook
251 ReadStatus extractFromVC();
252 /// Reads the first tag of a LyX File and
253 /// returns the file format number.
254 ReadStatus parseLyXFormat(Lexer & lex, support::FileName const & fn,
255 int & file_format) const;
256 /// Convert the LyX file to the LYX_FORMAT using
257 /// the lyx2lyx script and returns the filename
258 /// of the temporary file to be read
259 ReadStatus convertLyXFormat(support::FileName const & fn,
260 support::FileName & tmpfile, int from_format);
264 /// \name Functions involved in autosave and emergency files.
266 /// Save an autosave file to #filename.lyx#
267 bool autoSave() const;
268 /// save emergency file
269 /// \return a status message towards the user.
270 docstring emergencyWrite();
272 //FIXME:The following function should be private
275 void removeAutosaveFile() const;
278 /// Try to load an autosave file associated to \c fn.
279 ReadStatus loadAutosave();
280 /// Try to load an emergency file associated to \c fn.
281 ReadStatus loadEmergency();
282 /// Get the filename of the emergency file associated with the Buffer
283 support::FileName getEmergencyFileName() const;
284 /// Get the filename of the autosave file associated with the Buffer
285 support::FileName getAutosaveFileName() const;
287 void moveAutosaveFile(support::FileName const & old) const;
291 /// Fill in the ErrorList with the TeXErrors
292 void bufferErrors(TeXErrors const &, ErrorList &) const;
302 /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
303 bool makeLaTeXFile(support::FileName const & filename,
304 std::string const & original_path,
305 OutputParams const &,
306 OutputWhat output = FullSource) const;
307 /** Export the buffer to LaTeX.
308 If \p os is a file stream, and params().inputenc is "auto" or
309 "default", and the buffer contains text in different languages
310 with more than one encoding, then this method will change the
311 encoding associated to \p os. Therefore you must not call this
312 method with a string stream if the output is supposed to go to a
315 otexstream os(ofs, texrow);
316 ofs.open("test.tex");
317 writeLaTeXSource(os, ...);
319 \endcode is NOT equivalent to \code
320 odocstringstream oss;
321 otexstream os(oss, texrow);
322 writeLaTeXSource(os, ...);
324 ofs.open("test.tex");
329 void writeLaTeXSource(otexstream & os,
330 std::string const & original_path,
331 OutputParams const &,
332 OutputWhat output = FullSource) const;
334 void makeDocBookFile(support::FileName const & filename,
335 OutputParams const & runparams_in,
336 OutputWhat output = FullSource) const;
338 void writeDocBookSource(odocstream & os, std::string const & filename,
339 OutputParams const & runparams_in,
340 OutputWhat output = FullSource) const;
342 void makeLyXHTMLFile(support::FileName const & filename,
343 OutputParams const & runparams_in) const;
345 void writeLyXHTMLSource(odocstream & os,
346 OutputParams const & runparams_in,
347 OutputWhat output = FullSource) const;
348 /// returns the main language for the buffer (document)
349 Language const * language() const;
350 /// get l10n translated to the buffers language
351 docstring const B_(std::string const & l10n) const;
355 /// return true if the main lyx file does not need saving
356 bool isClean() const;
358 bool isDepClean(std::string const & name) const;
360 /// whether or not disk file has been externally modified
361 bool isExternallyModified(CheckMethod method) const;
363 /// mark the main lyx file as not needing saving
364 void markClean() const;
367 void markDepClean(std::string const & name);
370 void setUnnamed(bool flag = true);
372 /// Whether or not a filename has been assigned to this buffer
373 bool isUnnamed() const;
375 /// Whether or not this buffer is internal.
377 /// An internal buffer does not contain a real document, but some auxiliary text segment.
378 /// It is not associated with a filename, it is never saved, thus it does not need to be
379 /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
380 bool isInternal() const;
382 void setInternal(bool flag);
384 /// Mark this buffer as dirty.
387 /// Returns the buffer's filename. It is always an absolute path.
388 support::FileName fileName() const;
390 /// Returns the buffer's filename. It is always an absolute path.
391 std::string absFileName() const;
393 /// Returns the the path where the buffer lives.
394 /// It is always an absolute path.
395 std::string filePath() const;
397 /** A transformed version of the file name, adequate for LaTeX.
398 \param no_path optional if \c true then the path is stripped.
400 std::string latexName(bool no_path = true) const;
402 /// Get the name and type of the log.
403 std::string logName(LogType * type = 0) const;
405 /// Set document's parent Buffer.
406 void setParent(Buffer const *);
407 Buffer const * parent() const;
409 /** Get the document's master (or \c this if this is not a
412 Buffer const * masterBuffer() const;
414 /// \return true if \p child is a child of this \c Buffer.
415 bool isChild(Buffer * child) const;
417 /// \return true if this \c Buffer has children
418 bool hasChildren() const;
420 /// \return a list of the direct children of this Buffer.
421 /// this list has no duplicates and is in the order in which
422 /// the children appear.
423 ListOfBuffers getChildren() const;
425 /// \return a list of all descendents of this Buffer (children,
426 /// grandchildren, etc). this list has no duplicates and is in
427 /// the order in which the children appear.
428 ListOfBuffers getDescendents() const;
430 /// Collect all relative buffers, in the order in which they appear.
431 /// I.e., the "root" Buffer is first, then its first child, then any
432 /// of its children, etc. However, there are no duplicates in this
434 /// This is "stable", too, in the sense that it returns the same
435 /// thing from whichever Buffer it is called.
436 ListOfBuffers allRelatives() const;
438 /// Is buffer read-only?
439 bool isReadonly() const;
441 /// Set buffer read-only flag
442 void setReadonly(bool flag = true);
444 /** Validate a buffer for LaTeX.
445 This validates the buffer, and returns a struct for use by
446 #makeLaTeX# and others. Its main use is to figure out what
447 commands and packages need to be included in the LaTeX file.
448 It (should) also check that the needed constructs are there
449 (i.e. that the \refs points to coresponding \labels). It
450 should perhaps inset "error" insets to help the user correct
453 void validate(LaTeXFeatures &) const;
455 /// Reference information is cached in the Buffer, so we do not
456 /// have to check or read things over and over.
458 /// There are two caches.
460 /// One is a cache of the BibTeX files from which reference info is
461 /// being gathered. This cache is PER BUFFER, and the cache for the
462 /// master essentially includes the cache for its children. This gets
463 /// invalidated when an InsetBibtex is created, deleted, or modified.
465 /// The other is a cache of the reference information itself. This
466 /// exists only in the master buffer, and when it needs to be updated,
467 /// the children add their information to the master's cache.
469 /// Calling this method invalidates the cache and so requires a
471 void invalidateBibinfoCache() const;
472 /// This invalidates the cache of files we need to check.
473 void invalidateBibfileCache() const;
474 /// Updates the cached bibliography information, checking first to see
475 /// whether the cache is valid. If so, we do nothing. If not, then we
476 /// reload all the BibTeX info.
477 /// Note that this operates on the master document.
478 void reloadBibInfoCache() const;
479 /// \return the bibliography information for this buffer's master,
480 /// or just for it, if it isn't a child.
481 BiblioInfo const & masterBibInfo() const;
482 /// collect bibliography info from the various insets in this buffer.
483 void collectBibKeys() const;
484 /// add some BiblioInfo to our cache
485 void addBiblioInfo(BiblioInfo const & bi) const;
486 /// add a single piece of bibliography info to our cache
487 void addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const;
489 void makeCitationLabels() const;
491 bool citeLabelsValid() const;
493 void getLabelList(std::vector<docstring> &) const;
495 /// This removes the .aux and .bbl files from the temp dir.
496 void removeBiblioTempFiles() const;
499 void changeLanguage(Language const * from, Language const * to);
502 bool isMultiLingual() const;
504 std::set<Language const *> getLanguages() const;
507 BufferParams & params();
508 BufferParams const & params() const;
510 /** The list of paragraphs.
511 This is a linked list of paragraph, this list holds the
512 whole contents of the document.
514 ParagraphList & paragraphs();
515 ParagraphList const & paragraphs() const;
517 /// LyX version control object.
519 LyXVC const & lyxvc() const;
521 /// Where to put temporary files.
522 std::string const temppath() const;
524 /// Used when typesetting to place errorboxes.
525 TexRow const & texrow() const;
529 ParIterator par_iterator_begin();
531 ParConstIterator par_iterator_begin() const;
533 ParIterator par_iterator_end();
535 ParConstIterator par_iterator_end() const;
537 // Position of the child buffer where it appears first in the master.
538 DocIterator firstChildPosition(Buffer const * child);
540 /** \returns true only when the file is fully loaded.
541 * Used to prevent the premature generation of previews
542 * and by the citation inset.
544 bool isFullyLoaded() const;
545 /// Set by buffer_funcs' newFile.
546 void setFullyLoaded(bool);
548 /// FIXME: Needed by RenderPreview.
549 graphics::PreviewLoader * loader() const;
550 /// Update the LaTeX preview snippets associated with this buffer
551 void updatePreviews() const;
552 /// Remove any previewed LaTeX snippets associated with this buffer
553 void removePreviews() const;
555 /// Our main text (inside the top InsetText)
558 /// Our top InsetText
559 Inset & inset() const;
564 /// Collect macro definitions in paragraphs
565 void updateMacros() const;
566 /// Iterate through the whole buffer and try to resolve macros
567 void updateMacroInstances(UpdateType) const;
569 /// List macro names of this buffer, the parent and the children
570 void listMacroNames(MacroNameSet & macros) const;
571 /// Collect macros of the parent and its children in front of this buffer.
572 void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
574 /// Return macro defined before pos (or in the master buffer)
575 MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
576 /// Return macro defined anywhere in the buffer (or in the master buffer)
577 MacroData const * getMacro(docstring const & name, bool global = true) const;
578 /// Return macro defined before the inclusion of the child
579 MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
581 /// Collect user macro names at loading time
582 typedef std::set<docstring> UserMacroSet;
583 mutable UserMacroSet usermacros;
585 /// Replace the inset contents for insets which InsetCode is equal
586 /// to the passed \p inset_code.
587 void changeRefsIfUnique(docstring const & from, docstring const & to,
590 /// get source code (latex/docbook) for some paragraphs, or all paragraphs
591 /// including preamble
592 void getSourceCode(odocstream & os, std::string const format,
593 pit_type par_begin, pit_type par_end, OutputWhat output,
596 /// Access to error list.
597 /// This method is used only for GUI visualisation of Buffer related
598 /// errors (like parsing or LateX compilation). This method is const
599 /// because modifying the returned ErrorList does not touch the document
601 ErrorList & errorList(std::string const & type) const;
604 /// This is useful only for screen visualisation of the Buffer. This
605 /// method is const because modifying this backend does not touch
606 /// the document contents.
607 TocBackend & tocBackend() const;
612 /// This function is called when the buffer is changed.
613 void changed(bool update_metrics) const;
615 void setChild(DocIterator const & dit, Buffer * child);
617 void updateTocItem(std::string const &, DocIterator const &) const;
618 /// This function is called when the buffer structure is changed.
619 void structureChanged() const;
620 /// This function is called when some parsing error shows up.
621 void errors(std::string const & err, bool from_master = false) const;
622 /// This function is called when the buffer busy status change.
623 void setBusy(bool on) const;
624 /// Update window titles of all users.
625 void updateTitles() const;
626 /// Reset autosave timers for all users.
627 void resetAutosaveTimers() const;
629 void message(docstring const & msg) const;
632 void setGuiDelegate(frontend::GuiBufferDelegate * gui);
634 bool hasGuiDelegate() const;
637 ExportStatus doExport(std::string const & target, bool put_in_tempdir) const;
639 ExportStatus doExport(std::string const & target, bool put_in_tempdir,
640 std::string & result_file) const;
642 ExportStatus preview(std::string const & format) const;
645 /// target is a format name optionally followed by a space
646 /// and a destination file-name
647 ExportStatus doExport(std::string const & target, bool put_in_tempdir,
648 bool includeall, std::string & result_file) const;
650 ExportStatus doExport(std::string const & target, bool put_in_tempdir,
651 bool includeall) const;
653 ExportStatus preview(std::string const & format, bool includeall = false) const;
655 void setMathFlavor(OutputParams & op) const;
659 bool isExporting() const;
662 typedef std::vector<std::pair<Inset *, ParIterator> > References;
664 References const & references(docstring const & label) const;
666 void addReference(docstring const & label, Inset * inset, ParIterator it);
668 void clearReferenceCache() const;
670 void setInsetLabel(docstring const & label, InsetLabel const * il);
672 InsetLabel const * insetLabel(docstring const & label) const;
674 /// return a list of all used branches (also in children)
675 void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
677 /// sets the buffer_ member for every inset in this buffer.
678 // FIXME This really shouldn't be needed, but at the moment it's not
679 // clear how to do it just for the individual pieces we need.
680 void setBuffersForInsets() const;
681 /// Updates screen labels and some other information associated with
682 /// insets and paragraphs. Actually, it's more like a general "recurse
683 /// through the Buffer" routine, that visits all the insets and paragraphs.
684 void updateBuffer() const { updateBuffer(UpdateMaster, InternalUpdate); }
685 /// \param scope: whether to start with the master document or just
687 /// \param output: whether we are preparing for output.
688 void updateBuffer(UpdateScope scope, UpdateType utype) const;
690 void updateBuffer(ParIterator & parit, UpdateType utype) const;
692 /// Spellcheck starting from \p from.
693 /// \p from initial position, will then points to the next misspelled
695 /// \p to will points to the end of the next misspelled word.
696 /// \p word_lang will contain the found misspelled word.
697 /// \return progress if a new word was found.
698 int spellCheck(DocIterator & from, DocIterator & to,
699 WordLangTuple & word_lang, docstring_list & suggestions) const;
701 void checkChildBuffers();
703 void checkMasterBuffer();
705 /// compute statistics between \p from and \p to
706 /// \p from initial position
707 /// \p to points to the end position
708 /// \p skipNoOutput if notes etc. should be ignored
709 void updateStatistics(DocIterator & from, DocIterator & to,
710 bool skipNoOutput = true) const;
711 /// statistics accessor functions
712 int wordCount() const;
713 int charCount(bool with_blanks) const;
716 class MarkAsExporting;
717 friend class MarkAsExporting;
718 /// mark the buffer as busy exporting something, or not
719 void setExportStatus(bool e) const;
722 References & getReferenceCache(docstring const & label);
723 /// Change name of buffer. Updates "read-only" flag.
724 void setFileName(support::FileName const & fname);
726 void getLanguages(std::set<Language const *> &) const;
727 /// Checks whether any of the referenced bibfiles have changed since the
728 /// last time we loaded the cache. Note that this does NOT update the
729 /// cached information.
730 void checkIfBibInfoCacheIsValid() const;
731 /// Update the list of all bibfiles in use (including bibfiles
732 /// of loaded child documents).
733 void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
734 /// Return the list with all bibfiles in use (including bibfiles
735 /// of loaded child documents).
736 support::FileNameList const &
737 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
739 void collectChildren(ListOfBuffers & children, bool grand_children) const;
742 Buffer(Buffer const &);
743 void operator=(Buffer const &);
745 /// Use the Pimpl idiom to hide the internals.
747 /// The pointer never changes although *pimpl_'s contents may.