一千萬個為什麽

搜索
當前位置: 首頁 > 生成目錄

生成目錄

這是我最老的問題。它仍然沒有在那裏產生有用的答案,所以我想我會在這裏試試。 問題是:我似乎無法找到為Mathematica筆記本生成目錄的方法。 AuthorTools,一個舊的V5.1實用程序包仍然隱藏在Mathematica中,但它不適用於我。 TOC應包含正確的章節號(如果在樣式表中存在)和列表頁碼(這要求考慮頁面大小設置)。

最佳答案

OP的一點警告:這段代碼鎖定了我的Mathematica會話,所以在嘗試這個之前一定要保存所有內容。 更新:問題似乎與MMA在為我的特定筆記本分頁時遇到的問題有關(請參閱評論)。

此代碼為保存在位置 bookUrl 的筆記本創建單獨的TOC。它通過遍歷書中的所有單元來工作。如果遇到其類型在 typeList 中的單元格,則將標記添加到單元格,並將一行寫入TOC筆記本。我們使用 CounterBox [“Page”,{bookUrl,tag}] 來打印適當的頁碼。 Note that due to the nature of CounterBox, the page numbers are only shown in the TOC is the notebook of the book is open and ShowPageBreaks -> True is set, but you should be able to print the TOC to a pdf. createToc[bookUrl, typeList] := Module[{toc, book, createCell, counter, cell, type, tag},

(*create TOC file and open book*)
toc = CreateDocument[];
book = NotebookOpen[bookUrl];
SetOptions[book, ShowPageBreaks -> True];

(* helper file for creating cell *)
createCell[text_, tag_, level_] := Cell[BoxData[
     TagBox[GridBox[{{"", text, CounterBox["Page", {bookUrl, tag}]}},  
       GridBoxAlignment -> {"Columns" -> {Left, Left, Right}}, 
       GridBoxItemSize -> {"Columns" -> {2 level - 1, 35 - 2 level, 5}}], 
      "Grid"]], "Text"];

(* iterate over cells to set tags and write lines to TOC *)
Scan[(counter[#] = 0) &, typeList];
SelectionMove[book, Before, Notebook];
SelectionMove[book, Next, Cell];
While[(cell = NotebookRead[book]) =!= {},
  If[Length[cell] >= 2,
   type = cell[[2]];
   If[MemberQ[typeList, type],
    counter[type] += 1;
    tag = type <> ToString[counter[type]];
    SetOptions[NotebookSelection[book], 
     CellTags -> Union[Flatten[{Options[NotebookSelection[book], 
       CellTags][[1, 2]], tag}]]];
    SelectionMove[book, All, CellContents];
    NotebookWrite[toc, 
     createCell[NotebookRead[book], tag, 
      Position[typeList, type][[1, 1]]]]];
   SelectionMove[book, Next, Cell]]];
SetSelectedNotebook[toc]];

要查看實際的代碼,可以創建一個非常簡單的文檔,其中包含3個頁面中的2個部分和3個小節 book = CreateDocument[]; NotebookWrite[book, Cell["This is section 1", "Section"]]; NotebookWrite[book, Cell["This is a subsection", "Subsection"]]; NotebookWrite[book, Cell["This is some text", "Text"]]; NotebookWrite[book, Cell["Another section which begins on a new page", "Section", PageBreakAbove -> True]]; NotebookWrite[book, Cell["Subsection 2.1", "Subsection", PageBreakBelow -> True]]; NotebookWrite[book, Cell["Subsection 2.2", "Subsection"]]; bookUrl = ExpandFileName["book1.nb"]; NotebookSave[book, bookUrl];

然後 createToc [bookUrl,{“Section”,“Subsection”}] 創建這樣的東西

轉載註明原文: 生成目錄