]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
c5e09de014c3509f415d0c433fbec43db73f745d
[lyx.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "OutputEnums.h"
16
17 #include "insets/InsetCode.h"
18
19 #include "support/strfwd.h"
20 #include "support/types.h"
21
22 #include <list>
23 #include <set>
24 #include <string>
25 #include <vector>
26
27
28 namespace lyx {
29
30 class BiblioInfo;
31 class BufferParams;
32 class DispatchResult;
33 class DocIterator;
34 class docstring_list;
35 class ErrorList;
36 class FuncRequest;
37 class FuncStatus;
38 class Inset;
39 class InsetLabel;
40 class InsetRef;
41 class Font;
42 class Format;
43 class Lexer;
44 class Text;
45 class LyXVC;
46 class LaTeXFeatures;
47 class Language;
48 class MacroData;
49 class MacroNameSet;
50 class MacroSet;
51 class OutputParams;
52 class Paragraph;
53 class ParConstIterator;
54 class ParIterator;
55 class ParagraphList;
56 class TeXErrors;
57 class TexRow;
58 class TocBackend;
59 class Undo;
60 class WordLangTuple;
61
62 namespace frontend {
63 class GuiBufferDelegate;
64 class WorkAreaManager;
65 }
66
67 namespace support {
68 class FileName;
69 class FileNameList;
70 }
71
72
73 class Buffer;
74 typedef std::list<Buffer *> ListOfBuffers;
75
76
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.
82  *
83  *
84  * I am not sure if the class is complete or
85  * minimal, probably not.
86  * \author Lars Gullik Bjønnes
87  */
88 class Buffer {
89 public:
90         /// What type of log will \c getLogName() return?
91         enum LogType {
92                 latexlog, ///< LaTeX log
93                 buildlog  ///< Literate build log
94         };
95
96         /// Result of \c readFile()
97         enum ReadStatus {
98                 ReadSuccess,
99                 ReadCancel,
100                 // failures
101                 ReadFailure,
102                 ReadWrongVersion,
103                 ReadFileNotFound,
104                 ReadVCError,
105                 ReadAutosaveFailure,            
106                 ReadEmergencyFailure,
107                 ReadNoLyXFormat,
108                 ReadDocumentFailure,
109                 // lyx2lyx
110                 LyX2LyXNoTempFile,
111                 LyX2LyXNotFound,
112                 LyX2LyXOlderFormat,
113                 LyX2LyXNewerFormat,
114                 // other
115                 ReadOriginal
116         };
117
118
119         /// Method to check if a file is externally modified, used by
120         /// isExternallyModified()
121         /**
122          * timestamp is fast but inaccurate. For example, the granularity
123          * of timestamp on a FAT filesystem is 2 second. Also, various operations
124          * may touch the timestamp of a file even when its content is unchanged.
125          *
126          * checksum is accurate but slow, which can be a problem when it is
127          * frequently used, or used for a large file on a slow (network) file
128          * system.
129          *
130          * FIXME: replace this method with support/FileMonitor.
131          */
132         enum CheckMethod {
133                 checksum_method,  ///< Use file checksum
134                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
135         };
136
137         ///
138         enum UpdateScope {
139                 UpdateMaster,
140                 UpdateChildOnly
141         };
142
143         /// Constructor
144         explicit Buffer(std::string const & file, bool readonly = false,
145                 Buffer const * cloned_buffer = 0);
146
147         /// Destructor
148         ~Buffer();
149
150         ///
151         Buffer * clone() const;
152         ///
153         bool isClone() const;
154
155         /** High-level interface to buffer functionality.
156             This function parses a command string and executes it.
157         */
158         void dispatch(std::string const & command, DispatchResult & result);
159
160         /// Maybe we know the function already by number...
161         void dispatch(FuncRequest const & func, DispatchResult & result);
162
163         /// Can this function be exectued?
164         /// \return true if we made a decision
165         bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
166
167         /// read a new document from a string
168         bool readString(std::string const &);
169         
170         /// Reads the first tag of a LyX File and 
171         /// returns the file format number.
172         ReadStatus parseLyXFormat(Lexer & lex, 
173                 support::FileName const & fn, int & file_format) const;
174         /// read the header, returns number of unknown tokens
175         int readHeader(Lexer & lex);
176         /** Reads a file without header.
177             \param par if != 0 insert the file.
178             \return \c true if file is not completely read.
179         */
180         bool readDocument(Lexer &);
181         /// Convert the LyX file to the LYX_FORMAT using
182         /// the lyx2lyx script and returns the filename
183         /// of the temporary file to be read
184         ReadStatus convertLyXFormat(support::FileName const & fn, 
185                 support::FileName & tmpfile, int from_format);
186
187         ///
188         DocIterator getParFromID(int id) const;
189         /// do we have a paragraph with this id?
190         bool hasParWithID(int id) const;
191
192         ///
193         frontend::WorkAreaManager & workAreaManager() const;
194
195         /** Save file.
196             Takes care of auto-save files and backup file if requested.
197             Returns \c true if the save is successful, \c false otherwise.
198         */
199         bool save() const;
200
201         /// Write document to stream. Returns \c false if unsuccesful.
202         bool write(std::ostream &) const;
203         /// save emergency file
204         /// \return a status message towards the user.
205         docstring emergencyWrite();
206         /// Write file. Returns \c false if unsuccesful.
207         bool writeFile(support::FileName const &) const;
208
209         /// Loads a LyX file \c fn into the buffer. This function
210         /// tries to extract the file from version control if it
211         /// cannot be found. If it can be found, it will try to
212         /// read an emergency save file or an autosave file.
213         ReadStatus loadLyXFile(support::FileName const & fn);
214         /// read a new file
215         ReadStatus readFile(support::FileName const & fn);
216         /// Try to extract the file from a version control container
217         /// before reading if the file cannot be found. This is only
218         /// implemented for RCS.
219         /// \sa LyXVC::file_not_found_hook
220         ReadStatus readFromVC(support::FileName const & fn);
221         /// Try to read an emergency file associated to \c fn. 
222         ReadStatus readEmergency(support::FileName const & fn);
223         /// Try to read an autosave file associated to \c fn.
224         ReadStatus readAutosave(support::FileName const & fn);
225
226         /// Reloads the LyX file
227         bool reload();
228
229         /// Fill in the ErrorList with the TeXErrors
230         void bufferErrors(TeXErrors const &, ErrorList &) const;
231
232         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
233         bool makeLaTeXFile(support::FileName const & filename,
234                            std::string const & original_path,
235                            OutputParams const &,
236                            bool output_preamble = true,
237                            bool output_body = true) const;
238         /** Export the buffer to LaTeX.
239             If \p os is a file stream, and params().inputenc is "auto" or
240             "default", and the buffer contains text in different languages
241             with more than one encoding, then this method will change the
242             encoding associated to \p os. Therefore you must not call this
243             method with a string stream if the output is supposed to go to a
244             file. \code
245             ofdocstream ofs;
246             ofs.open("test.tex");
247             writeLaTeXSource(ofs, ...);
248             ofs.close();
249             \endcode is NOT equivalent to \code
250             odocstringstream oss;
251             writeLaTeXSource(oss, ...);
252             ofdocstream ofs;
253             ofs.open("test.tex");
254             ofs << oss.str();
255             ofs.close();
256             \endcode
257          */
258         void writeLaTeXSource(odocstream & os,
259                            std::string const & original_path,
260                            OutputParams const &,
261                            bool output_preamble = true,
262                            bool output_body = true) const;
263         ///
264         void makeDocBookFile(support::FileName const & filename,
265                              OutputParams const & runparams_in,
266                              bool only_body = false) const;
267         ///
268         void writeDocBookSource(odocstream & os, std::string const & filename,
269                              OutputParams const & runparams_in,
270                              bool only_body = false) const;
271         ///
272         void makeLyXHTMLFile(support::FileName const & filename,
273                              OutputParams const & runparams_in,
274                              bool only_body = false) const;
275         ///
276         void writeLyXHTMLSource(odocstream & os,
277                              OutputParams const & runparams_in,
278                              bool only_body = false) const;
279         /// returns the main language for the buffer (document)
280         Language const * language() const;
281         /// get l10n translated to the buffers language
282         docstring const B_(std::string const & l10n) const;
283
284         ///
285         int runChktex();
286         /// return true if the main lyx file does not need saving
287         bool isClean() const;
288         ///
289         bool isDepClean(std::string const & name) const;
290
291         /// whether or not disk file has been externally modified
292         bool isExternallyModified(CheckMethod method) const;
293
294         /// save timestamp and checksum of the given file.
295         void saveCheckSum(support::FileName const & file) const;
296
297         /// mark the main lyx file as not needing saving
298         void markClean() const;
299
300         ///
301         void markDepClean(std::string const & name);
302
303         ///
304         void setUnnamed(bool flag = true);
305
306         /// Whether or not a filename has been assigned to this buffer
307         bool isUnnamed() const;
308
309         /// Whether or not this buffer is internal.
310         ///
311         /// An internal buffer does not contain a real document, but some auxiliary text segment.
312         /// It is not associated with a filename, it is never saved, thus it does not need to be
313         /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
314         bool isInternal() const;
315
316         /// Mark this buffer as dirty.
317         void markDirty();
318
319         /// Returns the buffer's filename. It is always an absolute path.
320         support::FileName fileName() const;
321
322         /// Returns the buffer's filename. It is always an absolute path.
323         std::string absFileName() const;
324
325         /// Returns the the path where the buffer lives.
326         /// It is always an absolute path.
327         std::string filePath() const;
328
329         /** A transformed version of the file name, adequate for LaTeX.
330             \param no_path optional if \c true then the path is stripped.
331         */
332         std::string latexName(bool no_path = true) const;
333
334         /// Get the name and type of the log.
335         std::string logName(LogType * type = 0) const;
336
337         /// Change name of buffer. Updates "read-only" flag.
338         void setFileName(std::string const & newfile);
339
340         /// Set document's parent Buffer.
341         void setParent(Buffer const *);
342         Buffer const * parent() const;
343
344         /** Get the document's master (or \c this if this is not a
345             child document)
346          */
347         Buffer const * masterBuffer() const;
348
349         /// \return true if \p child is a child of this \c Buffer.
350         bool isChild(Buffer * child) const;
351         
352         /// \return true if this \c Buffer has children
353         bool hasChildren() const;
354         
355         /// \return a list of the direct children of this Buffer.
356         /// this list has no duplicates and is in the order in which
357         /// the children appear.
358         ListOfBuffers getChildren() const;
359         
360         /// \return a list of all descendents of this Buffer (children,
361         /// grandchildren, etc). this list has no duplicates and is in
362         /// the order in which the children appear.
363         ListOfBuffers getDescendents() const;
364
365         /// Collect all relative buffers, in the order in which they appear.
366         /// I.e., the "root" Buffer is first, then its first child, then any
367         /// of its children, etc. However, there are no duplicates in this
368         /// list.
369         /// This is "stable", too, in the sense that it returns the same
370         /// thing from whichever Buffer it is called.
371         ListOfBuffers allRelatives() const;
372
373         /// Is buffer read-only?
374         bool isReadonly() const;
375
376         /// Set buffer read-only flag
377         void setReadonly(bool flag = true);
378
379         /// returns \c true if the buffer contains a LaTeX document
380         bool isLatex() const;
381         /// returns \c true if the buffer contains a DocBook document
382         bool isDocBook() const;
383         /// returns \c true if the buffer contains a Wed document
384         bool isLiterate() const;
385
386         /** Validate a buffer for LaTeX.
387             This validates the buffer, and returns a struct for use by
388             #makeLaTeX# and others. Its main use is to figure out what
389             commands and packages need to be included in the LaTeX file.
390             It (should) also check that the needed constructs are there
391             (i.e. that the \refs points to coresponding \labels). It
392             should perhaps inset "error" insets to help the user correct
393             obvious mistakes.
394         */
395         void validate(LaTeXFeatures &) const;
396
397         /// Reference information is cached in the Buffer, so we do not
398         /// have to check or read things over and over. 
399         ///
400         /// There are two caches.
401         ///
402         /// One is a cache of the BibTeX files from which reference info is
403         /// being gathered. This cache is PER BUFFER, and the cache for the
404         /// master essentially includes the cache for its children. This gets
405         /// invalidated when an InsetBibtex is created, deleted, or modified.
406         /// 
407         /// The other is a cache of the reference information itself. This
408         /// exists only in the master buffer, and when it needs to be updated,
409         /// the children add their information to the master's cache.
410         
411         /// Calling this method invalidates the cache and so requires a
412         /// re-read.
413         void invalidateBibinfoCache() const;
414         /// This invalidates the cache of files we need to check.
415         void invalidateBibfileCache() const;
416         /// Updates the cached bibliography information.
417         /// Note that you MUST call this method to update the cache. It will
418         /// not happen otherwise. (Currently, it is called at the start of
419         /// updateBuffer() and from GuiCitation.)
420         /// Note that this operates on the master document.
421         void checkBibInfoCache() const;
422         /// \return the bibliography information for this buffer's master,
423         /// or just for it, if it isn't a child.
424         BiblioInfo const & masterBibInfo() const;
425         ///
426         void fillWithBibKeys(BiblioInfo & keys) const;
427         ///
428         void getLabelList(std::vector<docstring> &) const;
429
430         ///
431         void changeLanguage(Language const * from, Language const * to);
432
433         ///
434         bool isMultiLingual() const;
435         ///
436         std::set<Language const *> getLanguages() const;
437
438         ///
439         BufferParams & params();
440         BufferParams const & params() const;
441
442         /** The list of paragraphs.
443             This is a linked list of paragraph, this list holds the
444             whole contents of the document.
445          */
446         ParagraphList & paragraphs();
447         ParagraphList const & paragraphs() const;
448
449         /// LyX version control object.
450         LyXVC & lyxvc();
451         LyXVC const & lyxvc() const;
452
453         /// Where to put temporary files.
454         std::string const temppath() const;
455
456         /// Used when typesetting to place errorboxes.
457         TexRow const & texrow() const;
458         TexRow & texrow();
459
460         ///
461         ParIterator par_iterator_begin();
462         ///
463         ParConstIterator par_iterator_begin() const;
464         ///
465         ParIterator par_iterator_end();
466         ///
467         ParConstIterator par_iterator_end() const;
468
469         // Position of the child buffer where it appears first in the master.
470         DocIterator firstChildPosition(Buffer const * child);
471
472         /** \returns true only when the file is fully loaded.
473          *  Used to prevent the premature generation of previews
474          *  and by the citation inset.
475          */
476         bool isFullyLoaded() const;
477         /// Set by buffer_funcs' newFile.
478         void setFullyLoaded(bool);
479
480         /// Our main text (inside the top InsetText)
481         Text & text() const;
482
483         /// Our top InsetText
484         Inset & inset() const;
485
486         //
487         // Macro handling
488         //
489         /// Collect macro definitions in paragraphs
490         void updateMacros() const;
491         /// Iterate through the whole buffer and try to resolve macros
492         void updateMacroInstances() const;
493
494         /// List macro names of this buffer, the parent and the children
495         void listMacroNames(MacroNameSet & macros) const;
496         /// Collect macros of the parent and its children in front of this buffer.
497         void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
498
499         /// Return macro defined before pos (or in the master buffer)
500         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
501         /// Return macro defined anywhere in the buffer (or in the master buffer)
502         MacroData const * getMacro(docstring const & name, bool global = true) const;
503         /// Return macro defined before the inclusion of the child
504         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
505
506         /// Collect user macro names at loading time
507         typedef std::set<docstring> UserMacroSet;
508         UserMacroSet usermacros;
509
510         /// Replace the inset contents for insets which InsetCode is equal
511         /// to the passed \p inset_code.
512         void changeRefsIfUnique(docstring const & from, docstring const & to,
513                 InsetCode code);
514
515         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
516         /// including preamble
517         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
518                 bool full_source) const;
519
520         /// Access to error list.
521         /// This method is used only for GUI visualisation of Buffer related
522         /// errors (like parsing or LateX compilation). This method is const
523         /// because modifying the returned ErrorList does not touch the document
524         /// contents.
525         ErrorList & errorList(std::string const & type) const;
526
527         /// The Toc backend.
528         /// This is useful only for screen visualisation of the Buffer. This
529         /// method is const because modifying this backend does not touch
530         /// the document contents.
531         TocBackend & tocBackend() const;
532
533         ///
534         Undo & undo();
535
536         /// This function is called when the buffer is changed.
537         void changed(bool update_metrics) const;
538         ///
539         void setChild(DocIterator const & dit, Buffer * child);
540         ///
541         void updateTocItem(std::string const &, DocIterator const &) const;
542         /// This function is called when the buffer structure is changed.
543         void structureChanged() const;
544         /// This function is called when some parsing error shows up.
545         void errors(std::string const & err, bool from_master = false) const;
546         /// This function is called when the buffer busy status change.
547         void setBusy(bool on) const;
548         /// Update window titles of all users.
549         void updateTitles() const;
550         /// Reset autosave timers for all users.
551         void resetAutosaveTimers() const;
552         ///
553         void message(docstring const & msg) const;
554
555         ///
556         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
557         ///
558         bool hasGuiDelegate() const;
559
560         ///
561         void autoSave() const;
562         ///
563         void removeAutosaveFile() const;
564         ///
565         void moveAutosaveFile(support::FileName const & old) const;
566         /// Get the filename of the autosave file associated with the Buffer
567         support::FileName getAutosaveFileName() const;
568         /// Get the filename of the autosave file associated with \c fn
569         support::FileName getAutosaveFileNameFor(support::FileName const & fn)
570                 const;
571         /// Get the filename of the emergency file associated with the Buffer
572         support::FileName getEmergencyFileName() const;
573         /// Get the filename of the emergency file associated with \c fn
574         support::FileName getEmergencyFileNameFor(support::FileName const & fn)
575                 const;
576
577         /// return the format of the buffer on a string
578         std::string bufferFormat() const;
579         /// return the default output format of the current backend
580         std::string getDefaultOutputFormat() const;
581
582         ///
583         bool doExport(std::string const & format, bool put_in_tempdir,
584                 bool includeall, std::string & result_file) const;
585         ///
586         bool doExport(std::string const & format, bool put_in_tempdir,
587                       bool includeall = false) const;
588         ///
589         bool preview(std::string const & format, bool includeall = false) const;
590         ///
591         bool isExportable(std::string const & format) const;
592         ///
593         std::vector<Format const *> exportableFormats(bool only_viewable) const;
594         ///
595         bool isExportableFormat(std::string const & format) const;
596         /// mark the buffer as busy exporting something, or not
597         void setExportStatus(bool e) const;
598         ///
599         bool isExporting() const;
600
601         ///
602         typedef std::vector<std::pair<Inset *, ParIterator> > References;
603         References & references(docstring const & label);
604         References const & references(docstring const & label) const;
605         void clearReferenceCache() const;
606         void setInsetLabel(docstring const & label, InsetLabel const * il);
607         InsetLabel const * insetLabel(docstring const & label) const;
608
609         /// return a list of all used branches (also in children)
610         void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
611
612         /// sets the buffer_ member for every inset in this buffer.
613         // FIXME This really shouldn't be needed, but at the moment it's not
614         // clear how to do it just for the individual pieces we need.
615         void setBuffersForInsets() const;
616         /// Updates screen labels and some other information associated with
617         /// insets and paragraphs. Actually, it's more like a general "recurse
618         /// through the Buffer" routine, that visits all the insets and paragraphs.
619         void updateBuffer() const { updateBuffer(UpdateMaster, InternalUpdate); }
620         /// \param scope: whether to start with the master document or just
621         /// do this one.
622         /// \param output: whether we are preparing for output.
623         void updateBuffer(UpdateScope scope, UpdateType utype) const;
624         /// 
625         void updateBuffer(ParIterator & parit, UpdateType utype) const;
626
627         /// Spellcheck starting from \p from.
628         /// \p from initial position, will then points to the next misspelled
629         ///    word.
630         /// \p to will points to the end of the next misspelled word.
631         /// \p word_lang will contain the found misspelled word.
632         /// \return progress if a new word was found.
633         int spellCheck(DocIterator & from, DocIterator & to,
634                 WordLangTuple & word_lang, docstring_list & suggestions) const;
635         ///
636         void checkChildBuffers();
637
638 private:
639         ///
640         std::vector<std::string> backends() const;
641         /** Inserts a file into a document
642             \return \c false if method fails.
643         */
644         ReadStatus readFile(Lexer &, support::FileName const & filename,
645                             bool fromString = false);
646         ///
647         void getLanguages(std::set<Language const *> &) const;
648         /// Update the list of all bibfiles in use (including bibfiles
649         /// of loaded child documents).
650         void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
651         /// Return the list with all bibfiles in use (including bibfiles
652         /// of loaded child documents).
653         support::FileNameList const & 
654                 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
655         ///
656         void collectChildren(ListOfBuffers & children, bool grand_children) const;
657
658         
659         /// Use the Pimpl idiom to hide the internals.
660         class Impl;
661         /// The pointer never changes although *pimpl_'s contents may.
662         Impl * const d;
663 };
664
665
666 } // namespace lyx
667
668 #endif