ti.twjr 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325
  1. \input texinfo @c -*-texinfo-*-
  2. @c vim: filetype=texinfo tabstop=2 expandtab
  3. @c $Id$
  4. @c %**start of header (This is for running Texinfo on a region.)
  5. @setfilename texindex.info
  6. @settitle Texindex @VERSION@: A program for sorting indices
  7. @c %**end of header (This is for running Texinfo on a region.)
  8. @c Better brace handling, this texindex is needed to process!
  9. @allowindexbraces
  10. @c Merge the function and variable indexes into the concept index,
  11. @c but without the code font; in the index entries we'll do the
  12. @c font management ourselves. Also merge in the chunk definition
  13. @c and reference entries, which jrweave creates for us.
  14. @c (Ordinarily this would be in the header, but jrweave puts the
  15. @c defindexes later.)
  16. @synindex fn cp
  17. @synindex vr cp
  18. @synindex cd cp
  19. @synindex cr cp
  20. @copying
  21. This @command{texindex} program (version @VERSION@, @UPDATED@) sorts the
  22. raw index files created by @file{texinfo.tex}. (This Texinfo source is
  23. a literate program written using TexiWeb@tie{}Jr., not a user manual.)
  24. Copyright @copyright{} 2014, 2015, 2016, 2017 Free Software Foundation,
  25. Inc.
  26. @quotation
  27. This program is free software: you can redistribute it and/or modify
  28. it under the terms of the GNU General Public License as published by
  29. the Free Software Foundation, either version 3 of the License, or
  30. (at your option) any later version.
  31. This program is distributed in the hope that it will be useful,
  32. but WITHOUT ANY WARRANTY; without even the implied warranty of
  33. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  34. GNU General Public License for more details.
  35. You should have received a copy of the GNU General Public License
  36. along with this program. If not, see @url{http://www.gnu.org/licenses/}.
  37. @end quotation
  38. @end copying
  39. @titlepage
  40. @title Texindex
  41. @subtitle version @VERSION@, @UPDATED@
  42. @author Arnold D. Robbins
  43. @author and Texinfo maintainers
  44. @page
  45. @vskip 0pt plus 1filll
  46. @insertcopying
  47. @end titlepage
  48. @contents
  49. @ifnottex
  50. @node Top
  51. @top Texindex
  52. This file defines @command{texindex} (version @VERSION@,
  53. @UPDATED@), an @code{awk} program that processes the raw index
  54. files produced by the @file{texinfo.tex} file.
  55. @end ifnottex
  56. @menu
  57. * Preface:: Introductory remarks.
  58. * Requirements:: How the program needs to work.
  59. * High-level organization:: The overall outline.
  60. * Processing records:: Processing each record.
  61. * Necessary stuff:: Copyright, helper functions, i18n.
  62. * Index:: Combined index.
  63. @end menu
  64. @node Preface
  65. @unnumbered Preface
  66. This file defines @file{texindex.awk}, a reimplementation of the C
  67. program @file{texindex.c}. The purpose is to make the program more
  68. maintainable. As a practical benefit, it also supports correct sorting
  69. and initials for the @samp{@{} and @samp{@}} characters in an index.
  70. @cindex @{ (left brace), example index entry for
  71. @cindex @} (right brace), example index entry for
  72. @cindex TexiWeb Jr.@: literate programming system
  73. @cindex Texinfo document formatting language
  74. This is a @dfn{literate program}, written using the
  75. @uref{https://github.com/arnoldrobbins/texiwebjr, @sc{TexiWeb Jr.@:}
  76. literate programming system}. The underlying documentation system is
  77. @uref{http://www.gnu.org/software/texinfo, Texinfo} the GNU
  78. documentation formatting language. A single source file produces the
  79. runnable program, a printable document, and an online document.
  80. @menu
  81. * Intended audience::
  82. @end menu
  83. @node Intended audience
  84. @section Intended audience
  85. You should read this if you want to understand how @file{texindex.awk}
  86. works. You should be familiar with the @command{awk} programming
  87. language.
  88. If you are interested in array indexing, you've come to
  89. the wrong place. @xref{knuth}.
  90. @c Scale figure to 4.5 inches which is good for both smallbook
  91. @c and regular. TeX will scale height also automatically.
  92. @float Figure,knuth
  93. @caption{Indexing (@url{http://xkcd.com/163/})}
  94. @center @image{dek_idx, 5in, , Indexing}
  95. @end float
  96. @node Requirements
  97. @chapter Requirements
  98. The input to this program is the list of unsorted index entries produced
  99. by @file{texinfo.tex} when a Texinfo document is processed. For
  100. example, two lines resulting from the @command{gawk} manual might look
  101. like this:
  102. @example
  103. \entry@{POSIX awk@}@{5@}@{POSIX \command @{awk@}@}
  104. @dots{}
  105. \entry@{POSIX awk@}@{106@}@{POSIX \command @{awk@}@}
  106. @end example
  107. As shown, there are three ``fields'' enclosed in braces:
  108. @itemize @bullet
  109. @item
  110. The sort key. This is the text of the entry with all markup removed.
  111. It should contain only ASCII characters.
  112. @item
  113. The page number for this entry.
  114. @item
  115. The display text to be shown in the printed index, which can include markup.
  116. @end itemize
  117. The braces are balanced in all cases, although for use by this program,
  118. literal braces (not necessarily balanced) can be included in the sort
  119. key by escaping them with the @dfn{command character}. This is the
  120. first character on the line. It is either the backslash used by @TeX{}
  121. (@samp{\}) or the at sign used by Texinfo (@samp{@@}).
  122. @cindex backslash vs.@: at
  123. @cindex command character, @samp{\} vs.@: @samp{@@}
  124. Historically, @file{texinfo.tex} has used @samp{\} as the command
  125. character in index files. This causes complications with index entries
  126. containing backslashes and braces; C @command{texindex} has never output
  127. the correct initial (a left brace) for an index entry like
  128. @samp{@@cindex @@@{@}}, or done technically-correct sorting with such
  129. entries. @xref{Details of @t{texindex},,, texinfo, GNU Texinfo}.
  130. The present @code{awk} implementation handles these cases better. It
  131. also supports @samp{@@} as the command character, which allows
  132. @file{texinfo.tex} to output cleaner raw index files. (For
  133. compatibility, for now this is only done if a ``secret'' @TeX{} variable
  134. is set: @code{\global\usebracesinindexestrue}.) The first character of
  135. the raw input file is taken as the command character.
  136. @subheading Processing
  137. The job is to sort the entries, and merge those which are identical
  138. except for the page numbers. Thus, for the above two entries, the
  139. output should be:
  140. @example
  141. \entry @{POSIX \command @{awk@}@}@{5, 106@}
  142. @end example
  143. The sorting should be in the order of: all symbols first, then all
  144. digits, then all letters, with uppercase letters following lowercase
  145. ones, so we will need some smarts.
  146. Input lines might be duplicated (same entry, same page, more than once),
  147. so we will have to deal with that.
  148. In addition, @command{texindex} must output special lines indicating the
  149. first character (the @dfn{initial}) of keys grouped together, but only
  150. if there is more than one initial used throughout the input file. This
  151. output looks like:
  152. @example
  153. \initial @{A@}
  154. @end example
  155. @subheading Assumptions
  156. In the rest of the program we make two fundamental assumptions:
  157. @enumerate 1
  158. @item
  159. If a given sort key has more than one display text, we only take the
  160. first (this matches the behavior of C @command{texindex}). Put another
  161. way, if the same sort key has two different display texts, it means that
  162. different markup was used, probably inadvertently, and we just take the
  163. first. As an example, consider these two Texinfo commands:
  164. @example
  165. @@cindex @@file@{field_split()@} function
  166. @dots{}
  167. @@cindex @@code@{field_split()@} function
  168. @end example
  169. @noindent
  170. They produce the following output via @file{texinfo.tex},
  171. which in turn is the input to @command{texindex}:
  172. @example
  173. \entry@{field_split() function@}@{2@}@{\file @{field_split()@} function@}
  174. \entry@{field_split() function@}@{7@}@{\code @{field_split()@} function@}
  175. @end example
  176. @noindent The result will be a single entry, using @code{\file},
  177. accumulating the page numbers.
  178. @example
  179. \entry @{\file @{field_split()@} function@}@{2, 7@}
  180. @end example
  181. @item
  182. @cindex roman numerals
  183. For the same sort key and text, page numbers will be monotonically
  184. increasing. This means we can just use a new page number when it comes
  185. in, and not have to sort entries based on both sort key and page number.
  186. (Which, in turn, means that we don't need to worry about page numbers
  187. that are roman numerals.)
  188. @end enumerate
  189. An additional requirement, for ease of deployment, is that the program
  190. be written in portable @command{awk}, and not use features found only in
  191. GNU @command{awk} (@command{gawk}). For our purposes, ``portable''
  192. means ``new'' @command{awk} as defined in the 1988 book by Aho,
  193. Weinberger and Kernighan. This gives us functions, multidimensional
  194. arrays and a number of other important features over the original
  195. @command{awk} shipped with V7 Unix.
  196. @node High-level organization
  197. @chapter High-level organization
  198. The general outline is as follows:
  199. @file_update_recipe
  200. @end file_update_recipe
  201. @file_update texindex.awk . ""
  202. @(texindex.awk@) =
  203. @<First line@>
  204. @<GPL v3 copyright statement@>
  205. @<Library functions@>
  206. @<Helper functions@>
  207. BEGIN {
  208. @<Initial setup@>
  209. @<Argument processing@>
  210. }
  211. @<@code{beginfile()} function@>
  212. @<@code{endfile()} function@>
  213. @<Process a record@>
  214. @<Work functions@>
  215. @
  216. @menu
  217. * First line::
  218. * Initial setup::
  219. * Argument processing::
  220. @end menu
  221. @node First line
  222. @section First line
  223. @cindex first line
  224. @cindex @code{#!} header
  225. @cindex header, shebang
  226. For the first line of the generated output, we hardwire our intended
  227. output file name and how it got made. We do not use a @samp{#!} header
  228. because, being a GNU program, we need to accept the @option{--help} and
  229. @option{--version} options. This cannot be done with a standalone
  230. @code{awk} script; we need a shell wrapper, and hence, the @code{awk}
  231. script itself need not be executable, and it's simpler not to worry
  232. about the location of the @code{awk} program.
  233. @<First line@> =
  234. # texindex.awk, generated by jrtangle from ti.twjr.
  235. @
  236. @node Initial setup
  237. @section Initial setup
  238. @cindex initial setup
  239. The initial setup sets up some constants, including the version of the
  240. program. In the program itself, we follow a convenient convention:
  241. global variable and array names start with a capital letter.
  242. @cindex @code{Invocation_name} variable
  243. Per GNU standards, we sometimes hardwire the string @samp{texindex} as
  244. the name of the program, and sometimes use the name by which the program
  245. was invoked. We'll call the latter @code{Invocation_name}; it's
  246. supposed to be passed in from the shell wrapper.
  247. @cindex @code{Can_split_null} variable
  248. The last line below sets up @code{Can_split_null}, which tells us if the
  249. built-in @code{split()} function will split apart a string into its
  250. individual characters or if we have to do it manually.
  251. @cindex @code{TRUE} constant
  252. @cindex @code{FALSE} constant
  253. @cindex @code{EXIT_SUCCESS} constant
  254. @cindex @code{EXIT_FAILURE} constant
  255. @cindex @code{Texindex_version} variable
  256. @cindex @code{check_split_null()} function
  257. @<Initial setup@>=
  258. TRUE = 1
  259. FALSE = 0
  260. EXIT_SUCCESS = 0
  261. EXIT_FAILURE = 1
  262. Texindex_version = "@VERSION@"
  263. if (! Invocation_name) {
  264. # provide fallback in case it's not passed in.
  265. Invocation_name = "texindex"
  266. }
  267. Can_split_null = check_split_null()
  268. @
  269. @node Argument processing
  270. @section Argument processing
  271. @cindex argument processing
  272. @cindex @code{usage()} function
  273. @cindex @code{version()} function
  274. Argument processing is straightforward, though manual. The important
  275. thing is to remove options and their arguments from @code{ARGV} so that
  276. they're not treated as filenames. The options that print version or
  277. help information automatically exit, so there's no need to mess with
  278. @code{ARGV} in those cases.
  279. @cindex @code{-o} (@code{--output}) option, unimplemented
  280. The C implementation of @command{texindex} provided an option @code{-o}
  281. (@code{--output}) @var{file} to write the output to @var{file}. We've
  282. chosen to omit it from this incarnation of the program unless and until
  283. we receive information that it was ever useful.
  284. @cindex @code{-h} (@code{--help}) option
  285. @cindex @code{-k} (@code{--keep}), no-op option
  286. @cindex @code{--} option
  287. @cindex @code{--version} option
  288. @<Argument processing@>=
  289. for (i = 1; i < ARGC; i++) {
  290. if (ARGV[i] == "-h" || ARGV[i] == "--help") {
  291. usage(EXIT_SUCCESS)
  292. } else if (ARGV[i] == "--version") {
  293. version()
  294. } else if (ARGV[i] == "-k" || ARGV[i] == "--keep") {
  295. # do nothing, backwards compatibility
  296. delete ARGV[i]
  297. } else if (ARGV[i] == "--") {
  298. delete ARGV[i]
  299. break
  300. } else if (ARGV[i] ~ /^--?.+/) {
  301. fatal(_"%s: unrecognized option `%s'\n" \
  302. "Try `%s --help' for more information.\n",
  303. Invocation_name, ARGV[i], Invocation_name)
  304. exit EXIT_FAILURE
  305. } else {
  306. break
  307. }
  308. }
  309. @
  310. @node Processing records
  311. @chapter Processing records
  312. Processing records includes setting things up for each input file,
  313. pulling apart each record, sorting the data at the end, and writing out
  314. the data properly.
  315. @menu
  316. * Setup for each input file:: What happens at the start of each file.
  317. * Processing each record::
  318. * End-of-file sorting and printing::
  319. @end menu
  320. @node Setup for each input file
  321. @section Setup for each input file
  322. At the beginning of each input file, the @code{beginfile()} function
  323. clears our variables from any previous processing (@code{Data},
  324. @code{Keys}, etc.)@: and sets up the output file name. We always append
  325. an @samp{s} to the name of the input file, which has become the standard
  326. convention. (As mentioned above, the @option{-o} option in the C
  327. implementation of @command{texindex} has been omitted here, until the
  328. need is seen.)
  329. When @code{beginfile()} is called, the first record has already been
  330. read, so it's possible to perform the checks for a Texinfo index file:
  331. The first character must be either @samp{\} or @samp{@@}
  332. (@pxref{Requirements}), and the next five characters must be the word
  333. @samp{entry}.
  334. @cindex @code{Special_chars} variable
  335. @code{Special_chars} are the two characters that must be preceded by
  336. the command character inside the first key.
  337. @cindex @code{beginfile()} function
  338. @cindex @code{Output_file} variable
  339. @cindex @code{Data} array
  340. @cindex @code{Keys} array
  341. @cindex @code{Seen} array
  342. @cindex @code{Entries} variable
  343. @cindex @code{Do_initials} variable
  344. @cindex @code{Prev_initial} variable
  345. @cindex @code{del_array()} function
  346. @cindex @code{Command_char} variable
  347. @cindex @code{Special_chars} variable
  348. @<@code{beginfile()} function@>=
  349. function beginfile(filename)
  350. {
  351. Output_file = filename "s"
  352. # Reinitialize these for each input file
  353. del_array(Data)
  354. del_array(Keys)
  355. del_array(Seen)
  356. Entries = 0
  357. Do_initials = FALSE
  358. Prev_initial = ""
  359. Command_char = substr($0, 1, 1)
  360. if ( (Command_char != "\\" && Command_char != "@") \
  361. || substr($0, 2, 5) != "entry")
  362. fatal(_"%s is not a Texinfo index file\n", filename)
  363. Special_chars = "{}"
  364. }
  365. @
  366. @node Processing each record
  367. @section Processing each record
  368. Record processing consists of building the data structures for use in
  369. sorting and printing once the whole file has been processed.
  370. @<Process a record@> =
  371. {
  372. @<Remove duplicates@>
  373. @<Remove leading @code{\entry}@>
  374. @<Get the initial@>
  375. @<Set up @code{fields} array with the data@>
  376. @<Name the fields@>
  377. @<Store the data for this line in the @code{Data} array@>
  378. @<Check for more than one initial@>
  379. }
  380. @
  381. @menu
  382. * Remove duplicates::
  383. * Remove leading @code{\entry}::
  384. * Get the initial::
  385. * Set up and name fields::
  386. * Store the data for this line::
  387. * Check for more than one initial::
  388. * Splitting the record::
  389. @end menu
  390. @node Remove duplicates
  391. @subsection Remove duplicates
  392. @cindex removing duplicates
  393. @cindex duplicates, removing
  394. @cindex @code{Seen} array
  395. Duplicates are going to be exact. Removing them is thus easy; store
  396. each incoming line as the index of an array named @code{Seen}. If a
  397. line is not there, it has not been seen. Otherwise it has, and we move
  398. on to the next record.
  399. @<Remove duplicates@>=
  400. # Remove duplicates, which can happen
  401. if ($0 in Seen)
  402. next
  403. Seen[$0] = TRUE
  404. @
  405. @node Remove leading @code{\entry}
  406. @subsection Remove leading @code{\entry}
  407. We use @code{substr()} here to avoid possible hassles with leading
  408. backslashes in @code{sub()}.
  409. @<Remove leading @code{\entry}@>=
  410. $0 = substr($0, 7) # remove leading \entry
  411. @
  412. @node Get the initial
  413. @subsection Get the initial
  414. @cindex @code{extract_initial()} function
  415. @<Get the initial@>=
  416. initial = extract_initial($0)
  417. @
  418. The key argument here is the rest of the line after @samp{\entry},
  419. starting with an open brace.
  420. The very first field character of the sort key can be an open brace.
  421. If so, we extract the component of the sort key surrounded by balanced
  422. braces. We don't account for \@{ or \@} inside this component, as
  423. @file{texinfo.tex} isn't expected to produce such output.
  424. An example can be seen in what older versions of @file{texinfo.tex}
  425. generated if you needed to index a real backslash, namely an input line
  426. something like the following:
  427. @example
  428. \entry@{@{\tt \indexbackslash @} (backslash)@}@{14@}@{\code @{@{\tt @dots{}
  429. @end example
  430. Earlier versions of @command{texindex} took the the first non-brace
  431. character as the initial, in this example @samp{\}, and output it as
  432. @samp{\\}; this was not, however, a control sequence recognized by the
  433. older versions of @file{texinfo.tex}.
  434. @cindex @code{extract_initial()} function
  435. @cindex @code{char_split()} function
  436. @<Work functions@>=
  437. function extract_initial(key, initial, nextchar, i, l, kchars)
  438. {
  439. l = char_split(key, kchars)
  440. if (l >= 3 && kchars[2] == "{") {
  441. bracecount = 1
  442. i = 3
  443. while (bracecount > 0 && i <= l) {
  444. if (kchars[i] == "{")
  445. bracecount++
  446. else if (kchars[i] == "}")
  447. bracecount--
  448. i++
  449. }
  450. if (i > l)
  451. fatal(_"%s:%d: Bad key %s in record\n", FILENAME, FNR, key)
  452. initial = substr(key, 2, i - 2)
  453. } else if (kchars[2] == Command_char) {
  454. nextchar = kchars[3]
  455. if (initial == Command_char && (nextchar == "{" || nextchar == "}"))
  456. initial = substr(key, 2, 3)
  457. else {
  458. initial = toupper(nextchar)
  459. }
  460. } else {
  461. initial = toupper(kchars[2])
  462. }
  463. return initial
  464. }
  465. @
  466. @node Set up and name fields
  467. @subsection Set up and name fields
  468. The next part is to pull out the data of interest from the three sets of
  469. braces. This is delegated to a function named @code{field_split()}.
  470. There must be exactly three fields.
  471. @cindex @code{field_split()} function
  472. @cindex @code{fields} array, setting up
  473. @<Set up @code{fields} array with the data@>=
  474. numfields = field_split($0, fields, "{", "}", Command_char)
  475. if (numfields != 3)
  476. fatal(_"%s:%d: Bad entry; expected three fields, not %d\n",
  477. FILENAME, FNR, numfields)
  478. @
  479. We give the fields names for later use.
  480. @<Name the fields@>=
  481. key = fields[1]
  482. pagenum = fields[2]
  483. text = fields[3]
  484. @
  485. @node Store the data for this line
  486. @subsection Store the data for this line
  487. @cindex storing data
  488. @cindex @code{Data} array
  489. We use a traditional @command{awk} multidimensional array, @code{Data}.
  490. The sort key from the input is invariant across entries, so we use that
  491. as the basis for the keys in the @code{Data} array.
  492. The @code{Data} values are the the output @code{"text"}, the
  493. @code{"pagenum"} list, and the @code{"initial"}.
  494. In the event that a particular key has more than one associated output
  495. text, we'll keep the first and ignore the remainder (this is the same
  496. behavior as the C implementation). @xref{Requirements}.
  497. For page numbers, we merely append the page number field from the input,
  498. preceded by a comma and space, unless that page number was already the
  499. last that's been stored. (We're assuming the page numbers don't jump
  500. around, which, in fact, they don't, so we don't need a more complex
  501. approach.)
  502. @cindex @code{Keys} array
  503. @cindex @code{Entries} variable
  504. In addition to all this updating of the @code{Data} array, the key is
  505. stored in the @code{Keys} array the first time it is seen; this array
  506. is sorted later on. For now, its indices are just incremented integers,
  507. stored in the global @code{Entries} variable.
  508. @<Store the data for this line in the @code{Data} array@>=
  509. if (! ((key, "text") in Data)) {
  510. # first time we've seen this full line
  511. Keys[++Entries] = key
  512. Data[key, "text"] = text
  513. Data[key, "pagenum"] = pagenum
  514. Data[key, "initial"] = initial
  515. } else
  516. # seen this key before; add the current pagenum
  517. # unless we've already seen that too.
  518. if ( Data[key, "pagenum"] != pagenum \
  519. && Data[key, "pagenum"] !~ (", " pagenum "$")) {
  520. Data[key, "pagenum"] = Data[key, "pagenum"] ", " pagenum
  521. }
  522. @
  523. @node Check for more than one initial
  524. @subsection Check for more than one initial
  525. @cindex initial, checking for more than one
  526. Finally, we need to determine if more than one initial occurs in the
  527. input. If so, we set @code{Do_initials} to true. As soon as it's true,
  528. we don't need to do further checking on subsequent lines.
  529. @cindex @code{Do_initials} variable
  530. @cindex @code{Prev_initial} variable
  531. @<Check for more than one initial@> =
  532. if (! Do_initials) {
  533. if (Prev_initial == "")
  534. Prev_initial = initial
  535. else if (initial != Prev_initial)
  536. Do_initials = TRUE
  537. }
  538. @
  539. @node Splitting the record
  540. @subsection Splitting the record: @code{field_split}
  541. Let's take a look at the function that breaks apart the record. Upon
  542. entry to the function, the value of @code{record} looks something like:
  543. @example
  544. @{POSIX awk@}@{5@}@{POSIX \command @{awk@}@}
  545. @end example
  546. The first field may have instances of @samp{@@@{} and/or @samp{@@@}} (or
  547. @samp{\@{} and/or @samp{\@}}), so the braces aren't necessarily exactly
  548. balanced.
  549. The @code{field_split()} function uses fairly straightforward ``count
  550. the delimiters'' code. The loop starts at 2, since we know the first
  551. character is an open brace. The main things to handle are the command
  552. character and the final closing brace. The third field is taken as a
  553. whole; this is described shortly.
  554. @cindex @code{field_split()} function
  555. @cindex @code{char_split()} function
  556. @<Work functions@>=
  557. function field_split( \
  558. record, fields, start, end, com_ch, # parameters
  559. chars, numchars, out, delim_count, i, j, k) # locals
  560. {
  561. del_array(fields)
  562. numchars = char_split(record, chars)
  563. j = 1 # index into fields
  564. k = 1 # index into out
  565. delim_count = 1
  566. for (i = 2; i <= numchars; i++) {
  567. if (chars[i] == com_ch) {
  568. @<Handle the character after the command character@>
  569. } else if (chars[i] == start) {
  570. delim_count++
  571. out[k++] = chars[i]
  572. } else if (chars[i] == end) {
  573. delim_count--
  574. if (delim_count == 0) {
  575. @<Finish off the field, set up for next field@>
  576. } else
  577. out[k++] = chars[i]
  578. } else
  579. out[k++] = chars[i]
  580. @<Take the third field as a whole@>
  581. }
  582. return j # num fields
  583. }
  584. @
  585. If the character following the command character is an open brace, close
  586. brace, or the command character itself, we pull it in. Otherwise, the
  587. command character is left alone as part of the field.
  588. @<Handle the character after the command character@>=
  589. if (index(Special_chars, chars[i+1]) != 0) {
  590. out[k++] = chars[i+1]
  591. i++
  592. } else
  593. out[k++] = chars[i]
  594. @
  595. Upon seeing the final closing brace, we put all the characters back
  596. together into a string using @code{join()}. We then reset the
  597. @code{out} array for the next time through. If the next character isn't
  598. an open brace, then the line is bad and we print a fatal error.
  599. Otherwise, we reset @code{delim_count} to one.
  600. @cindex @code{join()} function
  601. @<Finish off the field, set up for next field@>=
  602. fields[j++] = join(out, 1, k-1, SUBSEP)
  603. del_array(out) # reset for next time through
  604. k = 1
  605. i++
  606. if (i <= numchars && chars[i] != start)
  607. fatal(_"%s:%d: Bad entry; expected %s at column %d\n",
  608. FILENAME, FNR, start, i)
  609. delim_count = 1
  610. @
  611. The third field is the printable version, and may have unbalanced braces
  612. or other oddities. We just take the whole thing as is. This is done by
  613. stripping off the outermost braces, using @code{substr()}. We then
  614. break out of the loop, since we're done.
  615. @<Take the third field as a whole@>=
  616. if (j == 3) { # Per Karl, just grab the whole rest of the line
  617. # extract everything between the outer delimiters
  618. fields[3] = substr(record, i + 1, numchars - i - 1)
  619. break
  620. }
  621. @
  622. @node End-of-file sorting and printing
  623. @section End-of-file sorting and printing
  624. Upon end of input, the processing is straightforward: sort the entries
  625. and write them out. Additionally, if we are printing the initial,
  626. handle that. (That printing task is delegated to a small function.)
  627. @cindex @code{endfile()} function
  628. @cindex @code{quicksort()} function
  629. @cindex @code{Entries} variable
  630. @cindex @code{Keys} array
  631. @cindex @code{Data} array
  632. @cindex @code{print_initial()} function
  633. @cindex @code{Output_file} variable
  634. @<@code{endfile()} function@>=
  635. function endfile(filename, i, prev_initial, initial)
  636. {
  637. # sort the entries
  638. quicksort(Keys, 1, Entries)
  639. for (i = 1; i <= Entries; i++) {
  640. # deal with initial
  641. initial = Data[Keys[i], "initial"]
  642. if (initial != prev_initial) {
  643. prev_initial = initial
  644. print_initial(initial)
  645. }
  646. # write the actual line \entry {...}{...}
  647. printf("%centry {%s}{%s}\n",
  648. Command_char,
  649. Data[Keys[i], "text"],
  650. Data[Keys[i], "pagenum"]) > Output_file
  651. }
  652. close(Output_file)
  653. }
  654. @
  655. Printing the initial is not complicated. The main thing is to precede
  656. special characters with the command character.
  657. @cindex @code{Command_char} variable
  658. @cindex @code{Special_chars} variable
  659. @cindex @code{Do_initials} variable
  660. @cindex @code{print_initial()} function
  661. @<Work functions@>=
  662. function print_initial(initial)
  663. {
  664. if (Do_initials) {
  665. if (index(Special_chars, initial) != 0)
  666. initial = Command_char initial
  667. printf("%cinitial {%s}\n",
  668. Command_char, initial) > Output_file
  669. }
  670. }
  671. @
  672. @menu
  673. * Quicksort:: Sorting our input.
  674. * Comparing index entries:: The heart of the sorting algorithm.
  675. @end menu
  676. @node Quicksort
  677. @subsection Quicksort
  678. @cindex quicksort
  679. @cindex Hoare, C.A.R.
  680. Sorting uses a standard quicksort algorithm, with a @code{less_than()}
  681. function (defined in the next function) supplying the comparison.
  682. @cindex @code{less_than()} function
  683. @cindex @code{quicksort()} function
  684. @cindex @code{quicksort_swap()} function
  685. @<Helper functions@>=
  686. # quicksort --- C.A.R. Hoare's quick sort algorithm. See Wikipedia
  687. # or almost any algorithms or computer science text
  688. # Adapted from K&R-II, page 110
  689. #
  690. function quicksort(data, left, right, i, last)
  691. {
  692. if (left >= right) # do nothing if array contains fewer
  693. return # than two elements
  694. quicksort_swap(data, left, int((left + right) / 2))
  695. last = left
  696. for (i = left + 1; i <= right; i++)
  697. if (less_than(data[i], data[left]))
  698. quicksort_swap(data, ++last, i)
  699. quicksort_swap(data, left, last)
  700. quicksort(data, left, last - 1)
  701. quicksort(data, last + 1, right)
  702. }
  703. # quicksort_swap --- quicksort helper function, could be inline
  704. #
  705. function quicksort_swap(data, i, j, temp)
  706. {
  707. temp = data[i]
  708. data[i] = data[j]
  709. data[j] = temp
  710. }
  711. @
  712. @node Comparing index entries
  713. @subsection Comparing index entries
  714. The comparison function is the heart of the sorting algorithm. The
  715. comparison is based on the indexing rules, which are:
  716. @itemize @bullet
  717. @item
  718. All symbols first.
  719. @item
  720. Followed by digits.
  721. @item
  722. Followed by letters. Lowercase precedes uppercase and both ``a'' and
  723. ``A'' precede anything starting with ``b'' or ``B'' (etc.).
  724. @end itemize
  725. Implementing these rules is a little complicated. The first thing we
  726. need is a table that maps characters to comparison values. The
  727. following code is based on the original C @command{texindex}, although
  728. the actual comparison algorithm is more sophisticated.
  729. We set up an @code{Ordval} array to map characters to numeric values.
  730. Most characters map to their ASCII code. We add 512 to the value of
  731. each of the digits. Both uppercase and lowercase letters map to the
  732. same numeric value, which is the ASCII code for the uppercase letter
  733. plus 512. (This code should also work for EBCDIC systems,
  734. although @TeX{} does everything in ASCII, so it's not likely to make a
  735. difference.)
  736. The table must be built completely before changing the mapping of the
  737. letters, because all of the uppercase and lowercase letters must be in
  738. the table before we can change their values.
  739. @cindex @code{Ordval} array
  740. @<Work functions@>=
  741. BEGIN {
  742. for (i = 0; i < 256; i++) {
  743. c = sprintf("%c", i)
  744. Ordval[c] = i # map character to value
  745. if ((n = isdigit(c)) > 0) {
  746. Ordval[c] += 512
  747. }
  748. }
  749. # Give both 'A' and 'a' the same code
  750. i = Ordval["A"]
  751. j = Ordval["Z"]
  752. for (; i <= j; i++) {
  753. c = sprintf("%c", i)
  754. # In ASCII, 'A' is before 'a', so this is
  755. # the right order to check
  756. #
  757. # Checking isupper() lets this work for EBCDIC, too.
  758. if (isupper(c)) {
  759. Ordval[c] += 512
  760. Ordval[tolower(c)] = Ordval[c]
  761. }
  762. }
  763. }
  764. @
  765. Here is the @code{less_than()} function. It returns true if the
  766. @code{left} string is ``less than'' the @code{right} string.
  767. The comparison algorithm is not too complicated, once we define how
  768. things should work. We loop over each pair of characters in the
  769. @code{left} and @code{right} strings, comparing them one at a time.
  770. When comparing two characters, there are three cases, one of which has
  771. three subcases, as follows:
  772. @table @i
  773. @item Two letters
  774. @c nested table
  775. @table @i
  776. @item Same letter, but different case
  777. This is the complicated case. First, we want lowercase letters to be
  778. ordered before uppercase ones, even though this is the opposite of the
  779. natural ASCII ordering. To make this happen, we use a @samp{>}
  780. comparison instead of a @samp{<} comparison.
  781. Second, when two characters are equal, we have to look ahead at the next
  782. characters to decide whether to continue the loop or quit. As long as
  783. we are not at the end of the string, and at least one of the following
  784. characters in either string is a letter, we continue the loop.
  785. Otherwise we do the character comparison and return.
  786. @item Two different letters, but same case
  787. @itemx Two different letters, different case
  788. Use the comparison of the respective @code{Ordval} values.
  789. @end table
  790. @c end nested table
  791. @item A letter and something else
  792. @itemx Two nonletters
  793. Use the comparison of the respective @code{Ordval} values.
  794. @end table
  795. @noindent When the values are equal, continue around the loop. And, as
  796. usual, if one string is an initial substring of the other, that one is
  797. considered to be ``less than'' the other one.
  798. The rules just described produce @emph{better} results than did the C
  799. @command{texindex}. For example, @samp{beginfile()} sorts
  800. before @samp{BEGINFILE}, whereas with the C version they came out in the
  801. opposite order.
  802. @cindex @code{Ordval} array
  803. @cindex @code{char_split()} function
  804. @cindex @code{less_than()} function
  805. @cindex @code{isalpha()} function
  806. @<Work functions@>=
  807. function less_than(left, right, len_l, len_r, len, chars_l, chars_r)
  808. {
  809. len_l = length(left)
  810. len_r = length(right)
  811. len = (len_l < len_r ? len_l : len_r)
  812. char_split(left, chars_l)
  813. char_split(right, chars_r)
  814. for (i = 1; i <= len; i++) {
  815. if (isalpha(chars_l[i]) && isalpha(chars_r[i])) {
  816. # same char different case
  817. # upper case comes out last
  818. if (chars_l[i] != chars_r[i] &&
  819. tolower(chars_l[i]) == tolower(chars_r[i])) {
  820. if ( i != len \
  821. && (isalpha(chars_l[i+1]) \
  822. || isalpha(chars_r[i+1])))
  823. continue
  824. if (chars_l[i] > chars_r[i])
  825. return 1
  826. return 0
  827. }
  828. # same case, different char,
  829. # or different case, different char:
  830. # letter order wins
  831. if (Ordval[chars_l[i]] < Ordval[chars_r[i]])
  832. return 1
  833. if (Ordval[chars_l[i]] > Ordval[chars_r[i]])
  834. return 0
  835. # equal, keep going
  836. continue
  837. }
  838. # letter and something else, or two non-letters
  839. # letter order wins
  840. if (Ordval[chars_l[i]] < Ordval[chars_r[i]])
  841. return 1
  842. if (Ordval[chars_l[i]] > Ordval[chars_r[i]])
  843. return 0
  844. # equal, keep going
  845. }
  846. # equal so far, shorter one wins
  847. if (len_l < len_r)
  848. return 1
  849. return 0
  850. }
  851. @
  852. @node Necessary stuff
  853. @chapter Necessary stuff that isn't thrilling
  854. This chapter provides some necessary but unexciting elements.
  855. @menu
  856. * Copyright statement:: Copyright info.
  857. * Library functions:: From the @code{gawk} library: @file{ftrans.awk}, @code{join}.
  858. * Helper functions:: @code{del_array}, @code{check_split}, @code{fatal}, @dots{}
  859. * I18N:: Internationalization.
  860. @end menu
  861. @node Copyright statement
  862. @section Copyright statement
  863. @cindex copyright statement
  864. @cindex GNU General Public License
  865. @cindex License, GNU General Public
  866. @cindex GPL (GNU General Public License)
  867. Every program needs a copyright statement.
  868. @<GPL v3 copyright statement@>=
  869. #
  870. # Copyright 2014, 2015, 2016 Free Software Foundation, Inc.
  871. #
  872. # This file is part of GNU Texinfo.
  873. #
  874. # Texinfo is free software; you can redistribute it and/or modify
  875. # it under the terms of the GNU General Public License as published by
  876. # the Free Software Foundation; either version 3 of the License, or
  877. # (at your option) any later version.
  878. #
  879. # Texinfo is distributed in the hope that it will be useful,
  880. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  881. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  882. # GNU General Public License for more details.
  883. #
  884. # You should have received a copy of the GNU General Public License
  885. # along with this program; if not, see <http://www.gnu.org/licenses/>.
  886. @
  887. @node Library functions
  888. @section Library functions: @file{ftrans.awk}, @code{join}
  889. The program uses several library routines discussed in detail
  890. in the @command{gawk} documentation. The first sets up the
  891. infrastructure for the @code{beginfile()} and @code{endfile()} functions.
  892. @xref{Filetrans Function,,, gawk, GNU Awk User's Guide},
  893. for an explanation of how this function works.
  894. @cindex @file{ftrans.awk} library file
  895. @<Library functions@>=
  896. # ftrans.awk --- handle data file transitions
  897. #
  898. # user supplies beginfile() and endfile() functions
  899. #
  900. # Arnold Robbins, arnold@skeeve.com, Public Domain
  901. # November 1992
  902. FNR == 1 {
  903. if (_filename_ != "")
  904. endfile(_filename_)
  905. _filename_ = FILENAME
  906. beginfile(FILENAME)
  907. }
  908. END { endfile(_filename_) }
  909. @
  910. The next function is @code{join()}, which joins an array of characters
  911. back into a string. @xref{Join Function,,, gawk, GNU Awk User's Guide},
  912. for an explanation of how this function works.
  913. @cindex @file{join.awk} library file
  914. @cindex @code{join()} function
  915. @<Library functions@>=
  916. # join.awk --- join an array into a string
  917. #
  918. # Arnold Robbins, arnold@skeeve.com, Public Domain
  919. # May 1993
  920. function join(array, start, end, sep, result, i)
  921. {
  922. if (sep == "")
  923. sep = " "
  924. else if (sep == SUBSEP) # magic value
  925. sep = ""
  926. result = array[start]
  927. for (i = start + 1; i <= end; i++)
  928. result = result sep array[i]
  929. return result
  930. }
  931. @
  932. @node Helper functions
  933. @section Helper functions
  934. These helper functions make the main code easier to follow.
  935. @menu
  936. * @code{del_array}::
  937. * @code{check_split_null}::
  938. * @code{char_split}::
  939. * @code{fatal}::
  940. * @code{is@dots{}} functions::
  941. @end menu
  942. @node @code{del_array}
  943. @subsection @code{del_array}
  944. @code{del_array()} clears out an array.
  945. @cindex @code{del_array()} function
  946. @<Helper functions@>=
  947. function del_array(a)
  948. {
  949. # Portable and faster than
  950. # for (i in a)
  951. # delete a[i]
  952. split("", a)
  953. }
  954. @
  955. @node @code{check_split_null}
  956. @subsection @code{check_split_null}
  957. @code{check_split_null()} determines whether the @command{awk} running
  958. this program supports using the null string for the separator, splitting
  959. each character off into a separate element. If so, the return value
  960. will be the number of elements in the array, and it will be more than
  961. one. It is called at program startup.
  962. @cindex @code{check_split_null()} function
  963. @<Helper functions@>=
  964. function check_split_null( n, a)
  965. {
  966. n = split("abcde", a, "")
  967. return (n == 5)
  968. }
  969. @
  970. @node @code{char_split}
  971. @subsection @code{char_split}
  972. @code{char_split()} splits a string into separate characters, letting
  973. @command{awk} do the work if possible. If not, each character is
  974. extracted manually using a loop and @code{substr()}.
  975. @cindex @code{char_split()} function
  976. @cindex @code{Can_split_null} variable
  977. @cindex @code{del_array()} function
  978. @<Helper functions@>=
  979. function char_split(string, array, n, i)
  980. {
  981. if (Can_split_null)
  982. return split(string, array, "")
  983. # do it the hard way
  984. del_array(array)
  985. n = length(string)
  986. for (i = 1; i <= n; i++)
  987. array[i] = substr(string, i, 1)
  988. return n
  989. }
  990. @
  991. @node @code{fatal}
  992. @subsection @code{fatal}
  993. @cindex stderr
  994. The @code{fatal()} function prints a @code{printf}-formatted message to
  995. standard error and then exits badly.
  996. @cindex @code{fatal()} function
  997. @<Helper functions@>=
  998. function fatal(format, arg1, arg2, arg3, arg4, arg5,
  999. arg6, arg7, arg8, arg9, arg10)
  1000. {
  1001. printf(format, arg1, arg2, arg3, arg4, arg5,
  1002. arg6, arg7, arg8, arg9, arg10) > "/dev/stderr"
  1003. exit EXIT_FAILURE
  1004. }
  1005. @
  1006. @node @code{is@dots{}} functions
  1007. @subsection @code{is@dots{}} functions
  1008. @cindex @code{isupper()} function
  1009. @cindex @code{islower()} function
  1010. @cindex @code{isalpha()} function
  1011. @cindex @code{isdigit()} function
  1012. The following functions help identify what a character is; they are
  1013. similar in nature to the various macros in the C @code{<ctype.h>} header
  1014. file. Since each one returns a count, the return value could be used to
  1015. compute which character from the set was seen; this turned out not to be
  1016. necessary in this program but might be useful in some other context.
  1017. @<Helper functions@>=
  1018. function isupper(c)
  1019. {
  1020. return index("ABCDEFGHIJKLMNOPQRSTUVWXYZ", c)
  1021. }
  1022. function islower(c)
  1023. {
  1024. return index("abcdefghijklmnopqrstuvwxyz", c)
  1025. }
  1026. function isalpha(c)
  1027. {
  1028. return islower(c) || isupper(c)
  1029. }
  1030. function isdigit(c)
  1031. {
  1032. return index("0123456789", c)
  1033. }
  1034. @
  1035. @node I18N
  1036. @section Internationalization
  1037. For @command{gawk}, we can arrange for the various messages, e.g., in
  1038. the @code{usage()} and @code{version()} functions, to be translated. We
  1039. do this by setting the text domain at startup. For more information on
  1040. internationalization in @command{gawk},
  1041. @pxref{Internationalization.html,,, gawk, GNU Awk User's Guide}.
  1042. @<Initial setup@>=
  1043. TEXTDOMAIN = "texinfo"
  1044. @
  1045. @noindent On non-GNU versions of @command{awk}, this is a harmless
  1046. assignment, and the @code{_"..."} construct below is a harmless
  1047. concatenation of an unassigned variable @code{_}, i.e., the empty
  1048. string.
  1049. The @code{usage()} and @code{version()} functions print the necessary
  1050. information and then exit. The strings that can and should be
  1051. translated are prefixed with an underscore.
  1052. @cindex @code{Texindex_version} variable
  1053. @cindex @code{usage()} function
  1054. @cindex @code{version()} function
  1055. @tex
  1056. % avoid useless warnings/overfull boxes in these long strings
  1057. \global\hfuzz=\maxdimen
  1058. @end tex
  1059. @<Helper functions@>=
  1060. function usage(exit_val)
  1061. {
  1062. printf(_"Usage: %s [OPTION]... FILE...\n", Invocation_name)
  1063. print _"Generate a sorted index for each TeX output FILE."
  1064. print _"Usually FILE... is specified as `foo.??' for a document `foo.texi'."
  1065. print ""
  1066. print _"Options:"
  1067. print _" -h, --help display this help and exit"
  1068. print _" --version display version information and exit"
  1069. print _" -- end option processing"
  1070. print ""
  1071. print _"Email bug reports to bug-texinfo@gnu.org,\n\
  1072. general questions and discussion to help-texinfo@gnu.org.\n\
  1073. Texinfo home page: http://www.gnu.org/software/texinfo/";
  1074. exit exit_val
  1075. }
  1076. function version()
  1077. {
  1078. print "texindex (GNU texinfo)", Texindex_version
  1079. print ""
  1080. printf _"Copyright (C) %s Free Software Foundation, Inc.\n\
  1081. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\n\
  1082. This is free software: you are free to change and redistribute it.\n\
  1083. There is NO WARRANTY, to the extent permitted by law.\n", "2017";
  1084. exit EXIT_SUCCESS
  1085. }
  1086. @
  1087. @node Index
  1088. @unnumbered Index
  1089. @printindex cp
  1090. @bye