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"
17 #include "insets/InsetCode.h"
19 #include "support/strfwd.h"
20 #include "support/types.h"
53 class ParConstIterator;
63 class GuiBufferDelegate;
64 class WorkAreaManager;
74 typedef std::list<Buffer *> ListOfBuffers;
77 /** The buffer object.
78 * This is the buffer object. It contains all the informations about
79 * a document loaded into LyX.
80 * The buffer object owns the Text (wrapped in an InsetText), which
81 * contains the individual paragraphs of the document.
84 * I am not sure if the class is complete or
85 * minimal, probably not.
86 * \author Lars Gullik Bjønnes
90 /// What type of log will \c getLogName() return?
92 latexlog, ///< LaTeX log
93 buildlog ///< Literate build log
96 /// Result of \c readFile()
106 ReadEmergencyFailure,
112 /// Method to check if a file is externally modified, used by
113 /// isExternallyModified()
115 * timestamp is fast but inaccurate. For example, the granularity
116 * of timestamp on a FAT filesystem is 2 second. Also, various operations
117 * may touch the timestamp of a file even when its content is unchanged.
119 * checksum is accurate but slow, which can be a problem when it is
120 * frequently used, or used for a large file on a slow (network) file
123 * FIXME: replace this method with support/FileMonitor.
126 checksum_method, ///< Use file checksum
127 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
137 explicit Buffer(std::string const & file, bool readonly = false,
138 Buffer const * cloned_buffer = 0);
144 Buffer * clone() const;
146 bool isClone() const;
148 /** High-level interface to buffer functionality.
149 This function parses a command string and executes it.
151 void dispatch(std::string const & command, DispatchResult & result);
153 /// Maybe we know the function already by number...
154 void dispatch(FuncRequest const & func, DispatchResult & result);
156 /// Can this function be exectued?
157 /// \return true if we made a decision
158 bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
160 /// read a new document from a string
161 bool readString(std::string const &);
163 /// read the header, returns number of unknown tokens
164 int readHeader(Lexer & lex);
166 /** Reads a file without header.
167 \param par if != 0 insert the file.
168 \return \c true if file is not completely read.
170 bool readDocument(Lexer &);
173 DocIterator getParFromID(int id) const;
174 /// do we have a paragraph with this id?
175 bool hasParWithID(int id) const;
178 frontend::WorkAreaManager & workAreaManager() const;
181 Takes care of auto-save files and backup file if requested.
182 Returns \c true if the save is successful, \c false otherwise.
186 /// Write document to stream. Returns \c false if unsuccesful.
187 bool write(std::ostream &) const;
188 /// save emergency file
189 /// \return a status message towards the user.
190 docstring emergencyWrite();
191 /// Write file. Returns \c false if unsuccesful.
192 bool writeFile(support::FileName const &) const;
194 /// Loads a LyX file \c fn into the buffer. This function
195 /// tries to extract the file from version control if it
196 /// cannot be found. If it can be found, it will try to
197 /// read an emergency save file or an autosave file.
198 ReadStatus loadLyXFile(support::FileName const & fn);
200 ReadStatus readFile(support::FileName const & fn);
201 /// Try to extract the file from a version control container
202 /// before reading if the file cannot be found. This is only
203 /// implemented for RCS.
204 /// \sa LyXVC::file_not_found_hook
205 ReadStatus readFromVC(support::FileName const & fn);
206 /// Try to read an emergency file associated to \c fn.
207 ReadStatus readEmergency(support::FileName const & fn);
208 /// Try to read an autosave file associated to \c fn.
209 ReadStatus readAutosave(support::FileName const & fn);
211 /// Reloads the LyX file
214 /// Fill in the ErrorList with the TeXErrors
215 void bufferErrors(TeXErrors const &, ErrorList &) const;
217 /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
218 bool makeLaTeXFile(support::FileName const & filename,
219 std::string const & original_path,
220 OutputParams const &,
221 bool output_preamble = true,
222 bool output_body = true) const;
223 /** Export the buffer to LaTeX.
224 If \p os is a file stream, and params().inputenc is "auto" or
225 "default", and the buffer contains text in different languages
226 with more than one encoding, then this method will change the
227 encoding associated to \p os. Therefore you must not call this
228 method with a string stream if the output is supposed to go to a
231 ofs.open("test.tex");
232 writeLaTeXSource(ofs, ...);
234 \endcode is NOT equivalent to \code
235 odocstringstream oss;
236 writeLaTeXSource(oss, ...);
238 ofs.open("test.tex");
243 void writeLaTeXSource(odocstream & os,
244 std::string const & original_path,
245 OutputParams const &,
246 bool output_preamble = true,
247 bool output_body = true) const;
249 void makeDocBookFile(support::FileName const & filename,
250 OutputParams const & runparams_in,
251 bool only_body = false) const;
253 void writeDocBookSource(odocstream & os, std::string const & filename,
254 OutputParams const & runparams_in,
255 bool only_body = false) const;
257 void makeLyXHTMLFile(support::FileName const & filename,
258 OutputParams const & runparams_in,
259 bool only_body = false) const;
261 void writeLyXHTMLSource(odocstream & os,
262 OutputParams const & runparams_in,
263 bool only_body = false) const;
264 /// returns the main language for the buffer (document)
265 Language const * language() const;
266 /// get l10n translated to the buffers language
267 docstring const B_(std::string const & l10n) const;
271 /// return true if the main lyx file does not need saving
272 bool isClean() const;
274 bool isDepClean(std::string const & name) const;
276 /// whether or not disk file has been externally modified
277 bool isExternallyModified(CheckMethod method) const;
279 /// save timestamp and checksum of the given file.
280 void saveCheckSum(support::FileName const & file) const;
282 /// mark the main lyx file as not needing saving
283 void markClean() const;
286 void markDepClean(std::string const & name);
289 void setUnnamed(bool flag = true);
291 /// Whether or not a filename has been assigned to this buffer
292 bool isUnnamed() const;
294 /// Whether or not this buffer is internal.
296 /// An internal buffer does not contain a real document, but some auxiliary text segment.
297 /// It is not associated with a filename, it is never saved, thus it does not need to be
298 /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
299 bool isInternal() const;
301 /// Mark this buffer as dirty.
304 /// Returns the buffer's filename. It is always an absolute path.
305 support::FileName fileName() const;
307 /// Returns the buffer's filename. It is always an absolute path.
308 std::string absFileName() const;
310 /// Returns the the path where the buffer lives.
311 /// It is always an absolute path.
312 std::string filePath() const;
314 /** A transformed version of the file name, adequate for LaTeX.
315 \param no_path optional if \c true then the path is stripped.
317 std::string latexName(bool no_path = true) const;
319 /// Get the name and type of the log.
320 std::string logName(LogType * type = 0) const;
322 /// Change name of buffer. Updates "read-only" flag.
323 void setFileName(std::string const & newfile);
325 /// Set document's parent Buffer.
326 void setParent(Buffer const *);
327 Buffer const * parent() const;
329 /** Get the document's master (or \c this if this is not a
332 Buffer const * masterBuffer() const;
334 /// \return true if \p child is a child of this \c Buffer.
335 bool isChild(Buffer * child) const;
337 /// \return true if this \c Buffer has children
338 bool hasChildren() const;
340 /// \return a list of the direct children of this Buffer.
341 /// this list has no duplicates and is in the order in which
342 /// the children appear.
343 ListOfBuffers getChildren() const;
345 /// \return a list of all descendents of this Buffer (children,
346 /// grandchildren, etc). this list has no duplicates and is in
347 /// the order in which the children appear.
348 ListOfBuffers getDescendents() const;
350 /// Collect all relative buffers, in the order in which they appear.
351 /// I.e., the "root" Buffer is first, then its first child, then any
352 /// of its children, etc. However, there are no duplicates in this
354 /// This is "stable", too, in the sense that it returns the same
355 /// thing from whichever Buffer it is called.
356 ListOfBuffers allRelatives() const;
358 /// Is buffer read-only?
359 bool isReadonly() const;
361 /// Set buffer read-only flag
362 void setReadonly(bool flag = true);
364 /// returns \c true if the buffer contains a LaTeX document
365 bool isLatex() const;
366 /// returns \c true if the buffer contains a DocBook document
367 bool isDocBook() const;
368 /// returns \c true if the buffer contains a Wed document
369 bool isLiterate() const;
371 /** Validate a buffer for LaTeX.
372 This validates the buffer, and returns a struct for use by
373 #makeLaTeX# and others. Its main use is to figure out what
374 commands and packages need to be included in the LaTeX file.
375 It (should) also check that the needed constructs are there
376 (i.e. that the \refs points to coresponding \labels). It
377 should perhaps inset "error" insets to help the user correct
380 void validate(LaTeXFeatures &) const;
382 /// Reference information is cached in the Buffer, so we do not
383 /// have to check or read things over and over.
385 /// There are two caches.
387 /// One is a cache of the BibTeX files from which reference info is
388 /// being gathered. This cache is PER BUFFER, and the cache for the
389 /// master essentially includes the cache for its children. This gets
390 /// invalidated when an InsetBibtex is created, deleted, or modified.
392 /// The other is a cache of the reference information itself. This
393 /// exists only in the master buffer, and when it needs to be updated,
394 /// the children add their information to the master's cache.
396 /// Calling this method invalidates the cache and so requires a
398 void invalidateBibinfoCache() const;
399 /// This invalidates the cache of files we need to check.
400 void invalidateBibfileCache() const;
401 /// Updates the cached bibliography information.
402 /// Note that you MUST call this method to update the cache. It will
403 /// not happen otherwise. (Currently, it is called at the start of
404 /// updateBuffer() and from GuiCitation.)
405 /// Note that this operates on the master document.
406 void checkBibInfoCache() const;
407 /// \return the bibliography information for this buffer's master,
408 /// or just for it, if it isn't a child.
409 BiblioInfo const & masterBibInfo() const;
411 void fillWithBibKeys(BiblioInfo & keys) const;
413 void getLabelList(std::vector<docstring> &) const;
416 void changeLanguage(Language const * from, Language const * to);
419 bool isMultiLingual() const;
421 std::set<Language const *> getLanguages() const;
424 BufferParams & params();
425 BufferParams const & params() const;
427 /** The list of paragraphs.
428 This is a linked list of paragraph, this list holds the
429 whole contents of the document.
431 ParagraphList & paragraphs();
432 ParagraphList const & paragraphs() const;
434 /// LyX version control object.
436 LyXVC const & lyxvc() const;
438 /// Where to put temporary files.
439 std::string const temppath() const;
441 /// Used when typesetting to place errorboxes.
442 TexRow const & texrow() const;
446 ParIterator par_iterator_begin();
448 ParConstIterator par_iterator_begin() const;
450 ParIterator par_iterator_end();
452 ParConstIterator par_iterator_end() const;
454 // Position of the child buffer where it appears first in the master.
455 DocIterator firstChildPosition(Buffer const * child);
457 /** \returns true only when the file is fully loaded.
458 * Used to prevent the premature generation of previews
459 * and by the citation inset.
461 bool isFullyLoaded() const;
462 /// Set by buffer_funcs' newFile.
463 void setFullyLoaded(bool);
465 /// Our main text (inside the top InsetText)
468 /// Our top InsetText
469 Inset & inset() const;
474 /// Collect macro definitions in paragraphs
475 void updateMacros() const;
476 /// Iterate through the whole buffer and try to resolve macros
477 void updateMacroInstances() const;
479 /// List macro names of this buffer, the parent and the children
480 void listMacroNames(MacroNameSet & macros) const;
481 /// Collect macros of the parent and its children in front of this buffer.
482 void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
484 /// Return macro defined before pos (or in the master buffer)
485 MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
486 /// Return macro defined anywhere in the buffer (or in the master buffer)
487 MacroData const * getMacro(docstring const & name, bool global = true) const;
488 /// Return macro defined before the inclusion of the child
489 MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
491 /// Collect user macro names at loading time
492 typedef std::set<docstring> UserMacroSet;
493 UserMacroSet usermacros;
495 /// Replace the inset contents for insets which InsetCode is equal
496 /// to the passed \p inset_code.
497 void changeRefsIfUnique(docstring const & from, docstring const & to,
500 /// get source code (latex/docbook) for some paragraphs, or all paragraphs
501 /// including preamble
502 void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
503 bool full_source) const;
505 /// Access to error list.
506 /// This method is used only for GUI visualisation of Buffer related
507 /// errors (like parsing or LateX compilation). This method is const
508 /// because modifying the returned ErrorList does not touch the document
510 ErrorList & errorList(std::string const & type) const;
513 /// This is useful only for screen visualisation of the Buffer. This
514 /// method is const because modifying this backend does not touch
515 /// the document contents.
516 TocBackend & tocBackend() const;
521 /// This function is called when the buffer is changed.
522 void changed(bool update_metrics) const;
524 void setChild(DocIterator const & dit, Buffer * child);
526 void updateTocItem(std::string const &, DocIterator const &) const;
527 /// This function is called when the buffer structure is changed.
528 void structureChanged() const;
529 /// This function is called when some parsing error shows up.
530 void errors(std::string const & err, bool from_master = false) const;
531 /// This function is called when the buffer busy status change.
532 void setBusy(bool on) const;
533 /// Update window titles of all users.
534 void updateTitles() const;
535 /// Reset autosave timers for all users.
536 void resetAutosaveTimers() const;
538 void message(docstring const & msg) const;
541 void setGuiDelegate(frontend::GuiBufferDelegate * gui);
543 bool hasGuiDelegate() const;
546 void autoSave() const;
548 void removeAutosaveFile() const;
550 void moveAutosaveFile(support::FileName const & old) const;
551 /// Get the filename of the autosave file associated with the Buffer
552 support::FileName getAutosaveFileName() const;
553 /// Get the filename of the autosave file associated with \c fn
554 support::FileName getAutosaveFileNameFor(support::FileName const & fn)
556 /// Get the filename of the emergency file associated with the Buffer
557 support::FileName getEmergencyFileName() const;
558 /// Get the filename of the emergency file associated with \c fn
559 support::FileName getEmergencyFileNameFor(support::FileName const & fn)
562 /// return the format of the buffer on a string
563 std::string bufferFormat() const;
564 /// return the default output format of the current backend
565 std::string getDefaultOutputFormat() const;
568 bool doExport(std::string const & format, bool put_in_tempdir,
569 bool includeall, std::string & result_file) const;
571 bool doExport(std::string const & format, bool put_in_tempdir,
572 bool includeall = false) const;
574 bool preview(std::string const & format, bool includeall = false) const;
576 bool isExportable(std::string const & format) const;
578 std::vector<Format const *> exportableFormats(bool only_viewable) const;
580 bool isExportableFormat(std::string const & format) const;
581 /// mark the buffer as busy exporting something, or not
582 void setExportStatus(bool e) const;
584 bool isExporting() const;
587 typedef std::vector<std::pair<Inset *, ParIterator> > References;
588 References & references(docstring const & label);
589 References const & references(docstring const & label) const;
590 void clearReferenceCache() const;
591 void setInsetLabel(docstring const & label, InsetLabel const * il);
592 InsetLabel const * insetLabel(docstring const & label) const;
594 /// return a list of all used branches (also in children)
595 void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
597 /// sets the buffer_ member for every inset in this buffer.
598 // FIXME This really shouldn't be needed, but at the moment it's not
599 // clear how to do it just for the individual pieces we need.
600 void setBuffersForInsets() const;
601 /// Updates screen labels and some other information associated with
602 /// insets and paragraphs. Actually, it's more like a general "recurse
603 /// through the Buffer" routine, that visits all the insets and paragraphs.
604 void updateBuffer() const { updateBuffer(UpdateMaster, InternalUpdate); }
605 /// \param scope: whether to start with the master document or just
607 /// \param output: whether we are preparing for output.
608 void updateBuffer(UpdateScope scope, UpdateType utype) const;
610 void updateBuffer(ParIterator & parit, UpdateType utype) const;
612 /// Spellcheck starting from \p from.
613 /// \p from initial position, will then points to the next misspelled
615 /// \p to will points to the end of the next misspelled word.
616 /// \p word_lang will contain the found misspelled word.
617 /// \return progress if a new word was found.
618 int spellCheck(DocIterator & from, DocIterator & to,
619 WordLangTuple & word_lang, docstring_list & suggestions) const;
621 void checkChildBuffers();
625 std::vector<std::string> backends() const;
626 /** Inserts a file into a document
627 \return \c false if method fails.
629 ReadStatus readFile(Lexer &, support::FileName const & filename,
630 bool fromString = false);
632 void getLanguages(std::set<Language const *> &) const;
633 /// Update the list of all bibfiles in use (including bibfiles
634 /// of loaded child documents).
635 void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
636 /// Return the list with all bibfiles in use (including bibfiles
637 /// of loaded child documents).
638 support::FileNameList const &
639 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
641 void collectChildren(ListOfBuffers & children, bool grand_children) const;
644 /// Use the Pimpl idiom to hide the internals.
646 /// The pointer never changes although *pimpl_'s contents may.