1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300
|
@c -*-texinfo-*-
@c This is part of the GNU Emacs Lisp Reference Manual.
@c Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1998, 1999
@c Free Software Foundation, Inc.
@c See the file elisp.texi for copying conditions.
@setfilename ../info/modes
@node Modes, Documentation, Keymaps, Top
@chapter Major and Minor Modes
@cindex mode
A @dfn{mode} is a set of definitions that customize Emacs and can be
turned on and off while you edit. There are two varieties of modes:
@dfn{major modes}, which are mutually exclusive and used for editing
particular kinds of text, and @dfn{minor modes}, which provide features
that users can enable individually.
This chapter describes how to write both major and minor modes, how to
indicate them in the mode line, and how they run hooks supplied by the
user. For related topics such as keymaps and syntax tables, see
@ref{Keymaps}, and @ref{Syntax Tables}.
@menu
* Major Modes:: Defining major modes.
* Minor Modes:: Defining minor modes.
* Mode Line Format:: Customizing the text that appears in the mode line.
* Imenu:: How a mode can provide a menu
of definitions in the buffer.
* Font Lock Mode:: How modes can highlight text according to syntax.
* Hooks:: How to use hooks; how to write code that provides hooks.
@end menu
@node Major Modes
@section Major Modes
@cindex major mode
@cindex Fundamental mode
Major modes specialize Emacs for editing particular kinds of text.
Each buffer has only one major mode at a time.
The least specialized major mode is called @dfn{Fundamental mode}.
This mode has no mode-specific definitions or variable settings, so each
Emacs command behaves in its default manner, and each option is in its
default state. All other major modes redefine various keys and options.
For example, Lisp Interaction mode provides special key bindings for
@kbd{C-j} (@code{eval-print-last-sexp}), @key{TAB}
(@code{lisp-indent-line}), and other keys.
When you need to write several editing commands to help you perform a
specialized editing task, creating a new major mode is usually a good
idea. In practice, writing a major mode is easy (in contrast to
writing a minor mode, which is often difficult).
If the new mode is similar to an old one, it is often unwise to modify
the old one to serve two purposes, since it may become harder to use and
maintain. Instead, copy and rename an existing major mode definition
and alter the copy---or define a @dfn{derived mode} (@pxref{Derived
Modes}). For example, Rmail Edit mode, which is in
@file{emacs/lisp/mail/rmailedit.el}, is a major mode that is very similar to
Text mode except that it provides two additional commands. Its
definition is distinct from that of Text mode, but uses that of Text mode.
Even if the new mode is not an obvious derivative of any other mode,
it can be convenient to define it as a derivative of
@code{fundamental-mode}, so that @code{define-derived-mode} can
automatically enforce the most important coding conventions for you.
Rmail Edit mode offers an example of changing the major mode
temporarily for a buffer, so it can be edited in a different way (with
ordinary Emacs commands rather than Rmail commands). In such cases, the
temporary major mode usually provides a command to switch back to the
buffer's usual mode (Rmail mode, in this case). You might be tempted to
present the temporary redefinitions inside a recursive edit and restore
the usual ones when the user exits; but this is a bad idea because it
constrains the user's options when it is done in more than one buffer:
recursive edits must be exited most-recently-entered first. Using an
alternative major mode avoids this limitation. @xref{Recursive
Editing}.
The standard GNU Emacs Lisp library directory tree contains the code
for several major modes, in files such as @file{text-mode.el},
@file{texinfo.el}, @file{lisp-mode.el}, @file{c-mode.el}, and
@file{rmail.el}. They are found in various subdirectories of the
@file{lisp} directory. You can study these libraries to see how modes
are written. Text mode is perhaps the simplest major mode aside from
Fundamental mode. Rmail mode is a complicated and specialized mode.
@menu
* Major Mode Conventions:: Coding conventions for keymaps, etc.
* Example Major Modes:: Text mode and Lisp modes.
* Auto Major Mode:: How Emacs chooses the major mode automatically.
* Mode Help:: Finding out how to use a mode.
* Derived Modes:: Defining a new major mode based on another major
mode.
@end menu
@node Major Mode Conventions
@subsection Major Mode Conventions
The code for existing major modes follows various coding conventions,
including conventions for local keymap and syntax table initialization,
global names, and hooks. Please follow these conventions when you
define a new major mode.
This list of conventions is only partial, because each major mode
should aim for consistency in general with other Emacs major modes.
This makes Emacs as a whole more coherent. It is impossible to list
here all the possible points where this issue might come up; if the
Emacs developers point out an area where your major mode deviates from
the usual conventions, please make it compatible.
@itemize @bullet
@item
Define a command whose name ends in @samp{-mode}, with no arguments,
that switches to the new mode in the current buffer. This command
should set up the keymap, syntax table, and buffer-local variables in an
existing buffer, without changing the buffer's contents.
@item
Write a documentation string for this command that describes the
special commands available in this mode. @kbd{C-h m}
(@code{describe-mode}) in your mode will display this string.
The documentation string may include the special documentation
substrings, @samp{\[@var{command}]}, @samp{\@{@var{keymap}@}}, and
@samp{\<@var{keymap}>}, which enable the documentation to adapt
automatically to the user's own key bindings. @xref{Keys in
Documentation}.
@item
The major mode command should start by calling
@code{kill-all-local-variables}. This is what gets rid of the
buffer-local variables of the major mode previously in effect.
@item
The major mode command should set the variable @code{major-mode} to the
major mode command symbol. This is how @code{describe-mode} discovers
which documentation to print.
@item
The major mode command should set the variable @code{mode-name} to the
``pretty'' name of the mode, as a string. This string appears in the
mode line.
@item
@cindex functions in modes
Since all global names are in the same name space, all the global
variables, constants, and functions that are part of the mode should
have names that start with the major mode name (or with an abbreviation
of it if the name is long). @xref{Coding Conventions}.
@item
In a major mode for editing some kind of structured text, such as a
programming language, indentation of text according to structure is
probably useful. So the mode should set @code{indent-line-function}
to a suitable function, and probably customize other variables
for indentation.
@item
@cindex keymaps in modes
The major mode should usually have its own keymap, which is used as the
local keymap in all buffers in that mode. The major mode command should
call @code{use-local-map} to install this local map. @xref{Active
Keymaps}, for more information.
This keymap should be stored permanently in a global variable named
@code{@var{modename}-mode-map}. Normally the library that defines the
mode sets this variable.
@xref{Tips for Defining}, for advice about how to write the code to set
up the mode's keymap variable.
@item
The key sequences bound in a major mode keymap should usually start with
@kbd{C-c}, followed by a control character, a digit, or @kbd{@{},
@kbd{@}}, @kbd{<}, @kbd{>}, @kbd{:} or @kbd{;}. The other punctuation
characters are reserved for minor modes, and ordinary letters are
reserved for users.
It is reasonable for a major mode to rebind a key sequence with a
standard meaning, if it implements a command that does ``the same job''
in a way that fits the major mode better. For example, a major mode for
editing a programming language might redefine @kbd{C-M-a} to ``move to
the beginning of a function'' in a way that works better for that
language.
Major modes such as Dired or Rmail that do not allow self-insertion of
text can reasonably redefine letters and other printing characters as
editing commands. Dired and Rmail both do this.
@item
Major modes must not define @key{RET} to do anything other than insert
a newline. The command to insert a newline and then indent is
@kbd{C-j}. Please keep this distinction uniform for all major modes.
@item
Major modes should not alter options that are primary a matter of user
preference, such as whether Auto-Fill mode is enabled. Leave this to
each user to decide. However, a major mode should customize other
variables so that Auto-Fill mode will work usefully @emph{if} the user
decides to use it.
@item
@cindex syntax tables in modes
The mode may have its own syntax table or may share one with other
related modes. If it has its own syntax table, it should store this in
a variable named @code{@var{modename}-mode-syntax-table}. @xref{Syntax
Tables}.
@item
If the mode handles a language that has a syntax for comments, it should
set the variables that define the comment syntax. @xref{Options for
Comments,, Options Controlling Comments, emacs, The GNU Emacs Manual}.
@item
@cindex abbrev tables in modes
The mode may have its own abbrev table or may share one with other
related modes. If it has its own abbrev table, it should store this in
a variable named @code{@var{modename}-mode-abbrev-table}. @xref{Abbrev
Tables}.
@item
The mode should specify how to do highlighting for Font Lock mode, by
setting up a buffer-local value for the variable
@code{font-lock-defaults} (@pxref{Font Lock Mode}).
@item
The mode should specify how Imenu should find the definitions or
sections of a buffer, by setting up a buffer-local value for the
variable @code{imenu-generic-expression} or
@code{imenu-create-index-function} (@pxref{Imenu}).
@item
Use @code{defvar} or @code{defcustom} to set mode-related variables, so
that they are not reinitialized if they already have a value. (Such
reinitialization could discard customizations made by the user.)
@item
@cindex buffer-local variables in modes
To make a buffer-local binding for an Emacs customization variable, use
@code{make-local-variable} in the major mode command, not
@code{make-variable-buffer-local}. The latter function would make the
variable local to every buffer in which it is subsequently set, which
would affect buffers that do not use this mode. It is undesirable for a
mode to have such global effects. @xref{Buffer-Local Variables}.
With rare exceptions, the only reasonable way to use
@code{make-variable-buffer-local} in a Lisp package is for a variable
which is used only within that package. Using it on a variable used by
other packages would interfere with them.
@item
@cindex mode hook
@cindex major mode hook
Each major mode should have a @dfn{mode hook} named
@code{@var{modename}-mode-hook}. The major mode command should run that
hook, with @code{run-hooks}, as the very last thing it
does. @xref{Hooks}.
@item
The major mode command may also run the hooks of some more basic modes.
For example, @code{indented-text-mode} runs @code{text-mode-hook} as
well as @code{indented-text-mode-hook}. It may run these other hooks
immediately before the mode's own hook (that is, after everything else),
or it may run them earlier.
@item
If something special should be done if the user switches a buffer from
this mode to any other major mode, this mode can set up a buffer-local
value for @code{change-major-mode-hook} (@pxref{Creating Buffer-Local}).
@item
If this mode is appropriate only for specially-prepared text, then the
major mode command symbol should have a property named @code{mode-class}
with value @code{special}, put on as follows:
@cindex @code{mode-class} property
@cindex @code{special}
@example
(put 'funny-mode 'mode-class 'special)
@end example
@noindent
This tells Emacs that new buffers created while the current buffer is in
Funny mode should not inherit Funny mode. Modes such as Dired, Rmail,
and Buffer List use this feature.
@item
If you want to make the new mode the default for files with certain
recognizable names, add an element to @code{auto-mode-alist} to select
the mode for those file names. If you define the mode command to
autoload, you should add this element in the same file that calls
@code{autoload}. Otherwise, it is sufficient to add the element in the
file that contains the mode definition. @xref{Auto Major Mode}.
@item
In the documentation, you should provide a sample @code{autoload} form
and an example of how to add to @code{auto-mode-alist}, that users can
include in their init files (@pxref{Init File}).
@item
@cindex mode loading
The top-level forms in the file defining the mode should be written so
that they may be evaluated more than once without adverse consequences.
Even if you never load the file more than once, someone else will.
@end itemize
@node Example Major Modes
@subsection Major Mode Examples
Text mode is perhaps the simplest mode besides Fundamental mode.
Here are excerpts from @file{text-mode.el} that illustrate many of
the conventions listed above:
@smallexample
@group
;; @r{Create mode-specific tables.}
(defvar text-mode-syntax-table nil
"Syntax table used while in text mode.")
@end group
@group
(if text-mode-syntax-table
() ; @r{Do not change the table if it is already set up.}
(setq text-mode-syntax-table (make-syntax-table))
(modify-syntax-entry ?\" ". " text-mode-syntax-table)
(modify-syntax-entry ?\\ ". " text-mode-syntax-table)
(modify-syntax-entry ?' "w " text-mode-syntax-table))
@end group
@group
(defvar text-mode-abbrev-table nil
"Abbrev table used while in text mode.")
(define-abbrev-table 'text-mode-abbrev-table ())
@end group
@group
(defvar text-mode-map nil ; @r{Create a mode-specific keymap.}
"Keymap for Text mode.
Many other modes, such as Mail mode, Outline mode and Indented Text mode,
inherit all the commands defined in this map.")
(if text-mode-map
() ; @r{Do not change the keymap if it is already set up.}
(setq text-mode-map (make-sparse-keymap))
(define-key text-mode-map "\e\t" 'ispell-complete-word)
(define-key text-mode-map "\t" 'indent-relative)
(define-key text-mode-map "\es" 'center-line)
(define-key text-mode-map "\eS" 'center-paragraph))
@end group
@end smallexample
Here is the complete major mode function definition for Text mode:
@smallexample
@group
(defun text-mode ()
"Major mode for editing text intended for humans to read...
Special commands: \\@{text-mode-map@}
@end group
@group
Turning on text-mode runs the hook `text-mode-hook'."
(interactive)
(kill-all-local-variables)
(use-local-map text-mode-map)
@end group
@group
(setq local-abbrev-table text-mode-abbrev-table)
(set-syntax-table text-mode-syntax-table)
@end group
@group
(make-local-variable 'paragraph-start)
(setq paragraph-start (concat "[ \t]*$\\|" page-delimiter))
(make-local-variable 'paragraph-separate)
(setq paragraph-separate paragraph-start)
(make-local-variable 'indent-line-function)
(setq indent-line-function 'indent-relative-maybe)
@end group
@group
(setq mode-name "Text")
(setq major-mode 'text-mode)
(run-hooks 'text-mode-hook)) ; @r{Finally, this permits the user to}
; @r{customize the mode with a hook.}
@end group
@end smallexample
@cindex @file{lisp-mode.el}
The three Lisp modes (Lisp mode, Emacs Lisp mode, and Lisp
Interaction mode) have more features than Text mode and the code is
correspondingly more complicated. Here are excerpts from
@file{lisp-mode.el} that illustrate how these modes are written.
@cindex syntax table example
@smallexample
@group
;; @r{Create mode-specific table variables.}
(defvar lisp-mode-syntax-table nil "")
(defvar emacs-lisp-mode-syntax-table nil "")
(defvar lisp-mode-abbrev-table nil "")
@end group
@group
(if (not emacs-lisp-mode-syntax-table) ; @r{Do not change the table}
; @r{if it is already set.}
(let ((i 0))
(setq emacs-lisp-mode-syntax-table (make-syntax-table))
@end group
@group
;; @r{Set syntax of chars up to 0 to class of chars that are}
;; @r{part of symbol names but not words.}
;; @r{(The number 0 is @code{48} in the @sc{ascii} character set.)}
(while (< i ?0)
(modify-syntax-entry i "_ " emacs-lisp-mode-syntax-table)
(setq i (1+ i)))
@dots{}
@end group
@group
;; @r{Set the syntax for other characters.}
(modify-syntax-entry ? " " emacs-lisp-mode-syntax-table)
(modify-syntax-entry ?\t " " emacs-lisp-mode-syntax-table)
@dots{}
@end group
@group
(modify-syntax-entry ?\( "() " emacs-lisp-mode-syntax-table)
(modify-syntax-entry ?\) ")( " emacs-lisp-mode-syntax-table)
@dots{}))
;; @r{Create an abbrev table for lisp-mode.}
(define-abbrev-table 'lisp-mode-abbrev-table ())
@end group
@end smallexample
Much code is shared among the three Lisp modes. The following
function sets various variables; it is called by each of the major Lisp
mode functions:
@smallexample
@group
(defun lisp-mode-variables (lisp-syntax)
(cond (lisp-syntax
(set-syntax-table lisp-mode-syntax-table)))
(setq local-abbrev-table lisp-mode-abbrev-table)
@dots{}
@end group
@end smallexample
Functions such as @code{forward-paragraph} use the value of the
@code{paragraph-start} variable. Since Lisp code is different from
ordinary text, the @code{paragraph-start} variable needs to be set
specially to handle Lisp. Also, comments are indented in a special
fashion in Lisp and the Lisp modes need their own mode-specific
@code{comment-indent-function}. The code to set these variables is the
rest of @code{lisp-mode-variables}.
@smallexample
@group
(make-local-variable 'paragraph-start)
(setq paragraph-start (concat page-delimiter "\\|$" ))
(make-local-variable 'paragraph-separate)
(setq paragraph-separate paragraph-start)
@dots{}
@end group
@group
(make-local-variable 'comment-indent-function)
(setq comment-indent-function 'lisp-comment-indent))
@dots{}
@end group
@end smallexample
Each of the different Lisp modes has a slightly different keymap. For
example, Lisp mode binds @kbd{C-c C-z} to @code{run-lisp}, but the other
Lisp modes do not. However, all Lisp modes have some commands in
common. The following code sets up the common commands:
@smallexample
@group
(defvar shared-lisp-mode-map ()
"Keymap for commands shared by all sorts of Lisp modes.")
(if shared-lisp-mode-map
()
(setq shared-lisp-mode-map (make-sparse-keymap))
(define-key shared-lisp-mode-map "\e\C-q" 'indent-sexp)
(define-key shared-lisp-mode-map "\177"
'backward-delete-char-untabify))
@end group
@end smallexample
@noindent
And here is the code to set up the keymap for Lisp mode:
@smallexample
@group
(defvar lisp-mode-map ()
"Keymap for ordinary Lisp mode...")
(if lisp-mode-map
()
(setq lisp-mode-map (make-sparse-keymap))
(set-keymap-parent lisp-mode-map shared-lisp-mode-map)
(define-key lisp-mode-map "\e\C-x" 'lisp-eval-defun)
(define-key lisp-mode-map "\C-c\C-z" 'run-lisp))
@end group
@end smallexample
Finally, here is the complete major mode function definition for
Lisp mode.
@smallexample
@group
(defun lisp-mode ()
"Major mode for editing Lisp code for Lisps other than GNU Emacs Lisp.
Commands:
Delete converts tabs to spaces as it moves back.
Blank lines separate paragraphs. Semicolons start comments.
\\@{lisp-mode-map@}
Note that `run-lisp' may be used either to start an inferior Lisp job
or to switch back to an existing one.
@end group
@group
Entry to this mode calls the value of `lisp-mode-hook'
if that value is non-nil."
(interactive)
(kill-all-local-variables)
@end group
@group
(use-local-map lisp-mode-map) ; @r{Select the mode's keymap.}
(setq major-mode 'lisp-mode) ; @r{This is how @code{describe-mode}}
; @r{finds out what to describe.}
(setq mode-name "Lisp") ; @r{This goes into the mode line.}
(lisp-mode-variables t) ; @r{This defines various variables.}
@end group
@group
(setq imenu-case-fold-search t)
(set-syntax-table lisp-mode-syntax-table)
(run-hooks 'lisp-mode-hook)) ; @r{This permits the user to use a}
; @r{hook to customize the mode.}
@end group
@end smallexample
@node Auto Major Mode
@subsection How Emacs Chooses a Major Mode
Based on information in the file name or in the file itself, Emacs
automatically selects a major mode for the new buffer when a file is
visited. It also processes local variables specified in the file text.
@deffn Command fundamental-mode
Fundamental mode is a major mode that is not specialized for anything
in particular. Other major modes are defined in effect by comparison
with this one---their definitions say what to change, starting from
Fundamental mode. The @code{fundamental-mode} function does @emph{not}
run any hooks; you're not supposed to customize it. (If you want Emacs
to behave differently in Fundamental mode, change the @emph{global}
state of Emacs.)
@end deffn
@deffn Command normal-mode &optional find-file
This function establishes the proper major mode and buffer-local variable
bindings for the current buffer. First it calls @code{set-auto-mode},
then it runs @code{hack-local-variables} to parse, and bind or
evaluate as appropriate, the file's local variables.
If the @var{find-file} argument to @code{normal-mode} is non-@code{nil},
@code{normal-mode} assumes that the @code{find-file} function is calling
it. In this case, it may process a local variables list at the end of
the file and in the @samp{-*-} line. The variable
@code{enable-local-variables} controls whether to do so. @xref{File
variables, , Local Variables in Files, emacs, The GNU Emacs Manual}, for
the syntax of the local variables section of a file.
If you run @code{normal-mode} interactively, the argument
@var{find-file} is normally @code{nil}. In this case,
@code{normal-mode} unconditionally processes any local variables list.
@cindex file mode specification error
@code{normal-mode} uses @code{condition-case} around the call to the
major mode function, so errors are caught and reported as a @samp{File
mode specification error}, followed by the original error message.
@end deffn
@defun set-auto-mode
@cindex visited file mode
This function selects the major mode that is appropriate for the
current buffer. It may base its decision on the value of the @w{@samp{-*-}}
line, on the visited file name (using @code{auto-mode-alist}), on the
@w{@samp{#!}} line (using @code{interpreter-mode-alist}), or on the
file's local variables list. However, this function does not look for
the @samp{mode:} local variable near the end of a file; the
@code{hack-local-variables} function does that. @xref{Choosing Modes, ,
How Major Modes are Chosen, emacs, The GNU Emacs Manual}.
@end defun
@defopt default-major-mode
This variable holds the default major mode for new buffers. The
standard value is @code{fundamental-mode}.
If the value of @code{default-major-mode} is @code{nil}, Emacs uses
the (previously) current buffer's major mode for the major mode of a new
buffer. However, if that major mode symbol has a @code{mode-class}
property with value @code{special}, then it is not used for new buffers;
Fundamental mode is used instead. The modes that have this property are
those such as Dired and Rmail that are useful only with text that has
been specially prepared.
@end defopt
@defun set-buffer-major-mode buffer
This function sets the major mode of @var{buffer} to the value of
@code{default-major-mode}. If that variable is @code{nil}, it uses
the current buffer's major mode (if that is suitable).
The low-level primitives for creating buffers do not use this function,
but medium-level commands such as @code{switch-to-buffer} and
@code{find-file-noselect} use it whenever they create buffers.
@end defun
@defvar initial-major-mode
@cindex @samp{*scratch*}
The value of this variable determines the major mode of the initial
@samp{*scratch*} buffer. The value should be a symbol that is a major
mode command. The default value is @code{lisp-interaction-mode}.
@end defvar
@defvar auto-mode-alist
This variable contains an association list of file name patterns
(regular expressions; @pxref{Regular Expressions}) and corresponding
major mode commands. Usually, the file name patterns test for suffixes,
such as @samp{.el} and @samp{.c}, but this need not be the case. An
ordinary element of the alist looks like @code{(@var{regexp} .
@var{mode-function})}.
For example,
@smallexample
@group
(("\\`/tmp/fol/" . text-mode)
("\\.texinfo\\'" . texinfo-mode)
("\\.texi\\'" . texinfo-mode)
@end group
@group
("\\.el\\'" . emacs-lisp-mode)
("\\.c\\'" . c-mode)
("\\.h\\'" . c-mode)
@dots{})
@end group
@end smallexample
When you visit a file whose expanded file name (@pxref{File Name
Expansion}) matches a @var{regexp}, @code{set-auto-mode} calls the
corresponding @var{mode-function}. This feature enables Emacs to select
the proper major mode for most files.
If an element of @code{auto-mode-alist} has the form @code{(@var{regexp}
@var{function} t)}, then after calling @var{function}, Emacs searches
@code{auto-mode-alist} again for a match against the portion of the file
name that did not match before. This feature is useful for
uncompression packages: an entry of the form @code{("\\.gz\\'"
@var{function} t)} can uncompress the file and then put the uncompressed
file in the proper mode according to the name sans @samp{.gz}.
Here is an example of how to prepend several pattern pairs to
@code{auto-mode-alist}. (You might use this sort of expression in your
init file.)
@smallexample
@group
(setq auto-mode-alist
(append
;; @r{File name (within directory) starts with a dot.}
'(("/\\.[^/]*\\'" . fundamental-mode)
;; @r{File name has no dot.}
("[^\\./]*\\'" . fundamental-mode)
;; @r{File name ends in @samp{.C}.}
("\\.C\\'" . c++-mode))
auto-mode-alist))
@end group
@end smallexample
@end defvar
@defvar interpreter-mode-alist
This variable specifies major modes to use for scripts that specify a
command interpreter in a @samp{#!} line. Its value is a list of
elements of the form @code{(@var{interpreter} . @var{mode})}; for
example, @code{("perl" . perl-mode)} is one element present by default.
The element says to use mode @var{mode} if the file specifies
an interpreter which matches @var{interpreter}. The value of
@var{interpreter} is actually a regular expression.
This variable is applicable only when the @code{auto-mode-alist} does
not indicate which major mode to use.
@end defvar
@node Mode Help
@subsection Getting Help about a Major Mode
@cindex mode help
@cindex help for major mode
@cindex documentation for major mode
The @code{describe-mode} function is used to provide information
about major modes. It is normally called with @kbd{C-h m}. The
@code{describe-mode} function uses the value of @code{major-mode},
which is why every major mode function needs to set the
@code{major-mode} variable.
@deffn Command describe-mode
This function displays the documentation of the current major mode.
The @code{describe-mode} function calls the @code{documentation}
function using the value of @code{major-mode} as an argument. Thus, it
displays the documentation string of the major mode function.
(@xref{Accessing Documentation}.)
@end deffn
@defvar major-mode
This variable holds the symbol for the current buffer's major mode.
This symbol should have a function definition that is the command to
switch to that major mode. The @code{describe-mode} function uses the
documentation string of the function as the documentation of the major
mode.
@end defvar
@node Derived Modes
@subsection Defining Derived Modes
It's often useful to define a new major mode in terms of an existing
one. An easy way to do this is to use @code{define-derived-mode}.
@defmac define-derived-mode variant parent name docstring body@dots{}
This construct defines @var{variant} as a major mode command, using
@var{name} as the string form of the mode name.
The new command @var{variant} is defined to call the function
@var{parent}, then override certain aspects of that parent mode:
@itemize @bullet
@item
The new mode has its own keymap, named @code{@var{variant}-map}.
@code{define-derived-mode} initializes this map to inherit from
@code{@var{parent}-map}, if it is not already set.
@item
The new mode has its own syntax table, kept in the variable
@code{@var{variant}-syntax-table}.
@code{define-derived-mode} initializes this variable by copying
@code{@var{parent}-syntax-table}, if it is not already set.
@item
The new mode has its own abbrev table, kept in the variable
@code{@var{variant}-abbrev-table}.
@code{define-derived-mode} initializes this variable by copying
@code{@var{parent}-abbrev-table}, if it is not already set.
@item
The new mode has its own mode hook, @code{@var{variant}-hook},
which it runs in standard fashion as the very last thing that it does.
(The new mode also runs the mode hook of @var{parent} as part
of calling @var{parent}.)
@end itemize
In addition, you can specify how to override other aspects of
@var{parent} with @var{body}. The command @var{variant}
evaluates the forms in @var{body} after setting up all its usual
overrides, just before running @code{@var{variant}-hook}.
The argument @var{docstring} specifies the documentation string for the
new mode. If you omit @var{docstring}, @code{define-derived-mode}
generates a documentation string.
Here is a hypothetical example:
@example
(define-derived-mode hypertext-mode
text-mode "Hypertext"
"Major mode for hypertext.
\\@{hypertext-mode-map@}"
(setq case-fold-search nil))
(define-key hypertext-mode-map
[down-mouse-3] 'do-hyper-link)
@end example
@end defmac
@node Minor Modes
@section Minor Modes
@cindex minor mode
A @dfn{minor mode} provides features that users may enable or disable
independently of the choice of major mode. Minor modes can be enabled
individually or in combination. Minor modes would be better named
``generally available, optional feature modes,'' except that such a name
would be unwieldy.
A minor mode is not usually meant as a variation of a single major mode.
Usually they are general and can apply to many major modes. For
example, Auto Fill mode works with any major mode that permits text
insertion. To be general, a minor mode must be effectively independent
of the things major modes do.
A minor mode is often much more difficult to implement than a major
mode. One reason is that you should be able to activate and deactivate
minor modes in any order. A minor mode should be able to have its
desired effect regardless of the major mode and regardless of the other
minor modes in effect.
Often the biggest problem in implementing a minor mode is finding a
way to insert the necessary hook into the rest of Emacs. Minor mode
keymaps make this easier than it used to be.
@menu
* Minor Mode Conventions:: Tips for writing a minor mode.
* Keymaps and Minor Modes:: How a minor mode can have its own keymap.
* Defining Minor Modes:: A convenient facility for defining minor modes.
@end menu
@node Minor Mode Conventions
@subsection Conventions for Writing Minor Modes
@cindex minor mode conventions
@cindex conventions for writing minor modes
There are conventions for writing minor modes just as there are for
major modes. Several of the major mode conventions apply to minor
modes as well: those regarding the name of the mode initialization
function, the names of global symbols, and the use of keymaps and
other tables.
In addition, there are several conventions that are specific to
minor modes.
@itemize @bullet
@item
@cindex mode variable
Make a variable whose name ends in @samp{-mode} to control the minor
mode. We call this the @dfn{mode variable}. The minor mode command
should set this variable (@code{nil} to disable; anything else to
enable).
If possible, implement the mode so that setting the variable
automatically enables or disables the mode. Then the minor mode command
does not need to do anything except set the variable.
This variable is used in conjunction with the @code{minor-mode-alist} to
display the minor mode name in the mode line. It can also enable
or disable a minor mode keymap. Individual commands or hooks can also
check the variable's value.
If you want the minor mode to be enabled separately in each buffer,
make the variable buffer-local.
@item
Define a command whose name is the same as the mode variable.
Its job is to enable and disable the mode by setting the variable.
The command should accept one optional argument. If the argument is
@code{nil}, it should toggle the mode (turn it on if it is off, and off
if it is on). Otherwise, it should turn the mode on if the argument is
a positive integer, a symbol other than @code{nil} or @code{-}, or a
list whose @sc{car} is such an integer or symbol; it should turn the
mode off otherwise.
Here is an example taken from the definition of @code{transient-mark-mode}.
It shows the use of @code{transient-mark-mode} as a variable that enables or
disables the mode's behavior, and also shows the proper way to toggle,
enable or disable the minor mode based on the raw prefix argument value.
@smallexample
@group
(setq transient-mark-mode
(if (null arg) (not transient-mark-mode)
(> (prefix-numeric-value arg) 0)))
@end group
@end smallexample
@item
Add an element to @code{minor-mode-alist} for each minor mode
(@pxref{Mode Line Variables}), if you want to indicate the minor mode in
the mode line. This element should be a list of the following form:
@smallexample
(@var{mode-variable} @var{string})
@end smallexample
Here @var{mode-variable} is the variable that controls enabling of the
minor mode, and @var{string} is a short string, starting with a space,
to represent the mode in the mode line. These strings must be short so
that there is room for several of them at once.
When you add an element to @code{minor-mode-alist}, use @code{assq} to
check for an existing element, to avoid duplication. For example:
@smallexample
@group
(unless (assq 'leif-mode minor-mode-alist)
(setq minor-mode-alist
(cons '(leif-mode " Leif") minor-mode-alist)))
@end group
@end smallexample
@noindent
or like this, using @code{add-to-list} (@pxref{Setting Variables}):
@smallexample
@group
(add-to-list 'minor-mode-alist '(leif-mode " Leif"))
@end group
@end smallexample
@end itemize
Global minor modes distributed with Emacs should if possible support
enabling and disabling via Custom (@pxref{Customization}). To do this,
the first step is to define the mode variable with @code{defcustom}, and
specify @code{:type boolean}.
If just setting the variable is not sufficient to enable the mode, you
should also specify a @code{:set} method which enables the mode by
invoke the mode command. Note in the variable's documentation string that
setting the variable other than via Custom may not take effect.
Also mark the definition with an autoload cookie (@pxref{Autoload}),
and specify a @code{:require} so that customizing the variable will load
the library that defines the mode. This will copy suitable definitions
into @file{loaddefs.el} so that users can use @code{customize-option} to
enable the mode. For example:
@smallexample
@group
;;;###autoload
(defcustom msb-mode nil
"Toggle msb-mode.
Setting this variable directly does not take effect;
use either \\[customize] or the function `msb-mode'."
:set (lambda (symbol value)
(msb-mode (or value 0)))
:initialize 'custom-initialize-default
:version "20.4"
:type 'boolean
:group 'msb
:require 'msb)
@end group
@end smallexample
@node Keymaps and Minor Modes
@subsection Keymaps and Minor Modes
Each minor mode can have its own keymap, which is active when the mode
is enabled. To set up a keymap for a minor mode, add an element to the
alist @code{minor-mode-map-alist}. @xref{Active Keymaps}.
@cindex @code{self-insert-command}, minor modes
One use of minor mode keymaps is to modify the behavior of certain
self-inserting characters so that they do something else as well as
self-insert. In general, this is the only way to do that, since the
facilities for customizing @code{self-insert-command} are limited to
special cases (designed for abbrevs and Auto Fill mode). (Do not try
substituting your own definition of @code{self-insert-command} for the
standard one. The editor command loop handles this function specially.)
The key sequences bound in a minor mode should consist of @kbd{C-c}
followed by a punctuation character @emph{other than} @kbd{@{},
@kbd{@}}, @kbd{<}, @kbd{>}, @kbd{:}, and @kbd{;}. (Those few punctuation
characters are reserved for major modes.)
@node Defining Minor Modes
@subsection Defining Minor Modes
The macro @code{define-minor-mode} offers a convenient way of
implementing a mode in one self-contained definition. It supports only
buffer-local minor modes, not global ones.
@defmac define-minor-mode mode doc &optional init-value mode-indicator keymap body...
@tindex define-minor-mode
This macro defines a new minor mode whose name is @var{mode} (a symbol).
It defines a command named @var{mode} to toggle the minor
mode, with @var{doc} as its documentation string. It also defines a
variable named @var{mode}, which is set to @code{t} or @code{nil} by
enabling or disabling the mode. The variable is initialized to
@var{init-value}.
The command named @var{mode} finishes by executing the @var{body} forms,
if any, after it has performed the standard actions such as setting
the variable named @var{mode}.
The string @var{mode-indicator} says what to display in the mode line
when the mode is enabled; if it is @code{nil}, the mode is not displayed
in the mode line.
The optional argument @var{keymap} specifies the keymap for the minor mode.
It can be a variable name, whose value is the keymap, or it can be an alist
specifying bindings in this form:
@example
(@var{key-sequence} . @var{definition})
@end example
@end defmac
Here is an example of using @code{define-minor-mode}:
@smallexample
(define-minor-mode hungry-mode
"Toggle Hungry mode.
With no argument, this command toggles the mode.
Non-null prefix argument turns on the mode.
Null prefix argument turns off the mode.
When Hungry mode is enabled, the control delete key
gobbles all preceding whitespace except the last.
See the command \\[hungry-electric-delete]."
;; The initial value.
nil
;; The indicator for the mode line.
" Hungry"
;; The minor mode bindings.
'(("\C-\^?" . hungry-electric-delete)
("\C-\M-\^?"
. (lambda ()
(interactive)
(hungry-electric-delete t)))))
@end smallexample
@noindent
This defines a minor mode named ``Hungry mode'', a command named
@code{hungry-mode} to toggle it, a variable named @code{hungry-mode}
which indicates whether the mode is enabled, and a variable named
@code{hungry-mode-map} which holds the keymap that is active when the
mode is enabled. It initializes the keymap with key bindings for
@kbd{C-@key{DEL}} and @kbd{C-M-@key{DEL}}.
@findex easy-mmode-define-minor-mode
The name @code{easy-mmode-define-minor-mode} is an alias
for this macro.
@node Mode Line Format
@section Mode Line Format
@cindex mode line
Each Emacs window (aside from minibuffer windows) typically has a mode
line at the bottom, which displays status information about the buffer
displayed in the window. The mode line contains information about the
buffer, such as its name, associated file, depth of recursive editing,
and major and minor modes. A window can also have a @dfn{header
line}, which is much like the mode line but appears at the top of the
window (starting in Emacs 21).
This section describes how to control the contents of the mode line
and header line. We include it in this chapter because much of the
information displayed in the mode line relates to the enabled major and
minor modes.
@code{mode-line-format} is a buffer-local variable that holds a
template used to display the mode line of the current buffer. All
windows for the same buffer use the same @code{mode-line-format}, so
their mode lines appear the same---except for scrolling percentages, and
line and column numbers, since those depend on point and on how the
window is scrolled. @code{header-line-format} is used likewise for
header lines.
The mode line and header line of a window are normally updated
whenever a different buffer is shown in the window, or when the buffer's
modified-status changes from @code{nil} to @code{t} or vice-versa. If
you modify any of the variables referenced by @code{mode-line-format}
(@pxref{Mode Line Variables}), or any other variables and data
structures that affect how text is displayed (@pxref{Display}), you may
want to force an update of the mode line so as to display the new
information or display it in the new way.
@c Emacs 19 feature
@defun force-mode-line-update
Force redisplay of the current buffer's mode line and header line.
@end defun
The mode line is usually displayed in inverse video; see
@code{mode-line-inverse-video} in @ref{Inverse Video}.
@menu
* Mode Line Data:: The data structure that controls the mode line.
* Mode Line Variables:: Variables used in that data structure.
* %-Constructs:: Putting information into a mode line.
* Properties in Mode:: Using text properties in the mode line.
* Header Lines:: Like a mode line, but at the top.
@end menu
@node Mode Line Data
@subsection The Data Structure of the Mode Line
@cindex mode line construct
The mode line contents are controlled by a data structure of lists,
strings, symbols, and numbers kept in buffer-local variables. The data
structure is called a @dfn{mode line construct}, and it is built in
recursive fashion out of simpler mode line constructs. The same data
structure is used for constructing frame titles (@pxref{Frame Titles})
and header lines (@pxref{Header Lines}).
@defvar mode-line-format
The value of this variable is a mode line construct with overall
responsibility for the mode line format. The value of this variable
controls which other variables are used to form the mode line text, and
where they appear.
If you set this variable to @code{nil} in a buffer, that buffer does not
have a mode line. (This feature was added in Emacs 21.)
@end defvar
A mode line construct may be as simple as a fixed string of text, but
it usually specifies how to use other variables to construct the text.
Many of these variables are themselves defined to have mode line
constructs as their values.
The default value of @code{mode-line-format} incorporates the values
of variables such as @code{mode-name} and @code{minor-mode-alist}.
Because of this, very few modes need to alter @code{mode-line-format}
itself. For most purposes, it is sufficient to alter some of the
variables that @code{mode-line-format} refers to.
A mode line construct may be a list, a symbol, or a string. If the
value is a list, each element may be a list, a symbol, or a string.
The mode line can display various faces, if the strings that control
it have the @code{face} property. @xref{Properties in Mode}. In
addition, the face @code{mode-line} is used as a default for the whole
mode line (@pxref{Standard Faces}).
@table @code
@cindex percent symbol in mode line
@item @var{string}
A string as a mode line construct is displayed verbatim in the mode line
except for @dfn{@code{%}-constructs}. Decimal digits after the @samp{%}
specify the field width for space filling on the right (i.e., the data
is left justified). @xref{%-Constructs}.
@item @var{symbol}
A symbol as a mode line construct stands for its value. The value of
@var{symbol} is used as a mode line construct, in place of @var{symbol}.
However, the symbols @code{t} and @code{nil} are ignored, as is any
symbol whose value is void.
There is one exception: if the value of @var{symbol} is a string, it is
displayed verbatim: the @code{%}-constructs are not recognized.
@item (@var{string} @var{rest}@dots{}) @r{or} (@var{list} @var{rest}@dots{})
A list whose first element is a string or list means to process all the
elements recursively and concatenate the results. This is the most
common form of mode line construct.
@item (:eval @var{form})
A list whose first element is the symbol @code{:eval} says to evaluate
@var{form}, and use the result as a string to display.
(This feature is new as of Emacs 21.)
@item (@var{symbol} @var{then} @var{else})
A list whose first element is a symbol that is not a keyword specifies a
conditional. Its meaning depends on the value of @var{symbol}. If the
value is non-@code{nil}, the second element, @var{then}, is processed
recursively as a mode line element. But if the value of @var{symbol} is
@code{nil}, the third element, @var{else}, is processed recursively.
You may omit @var{else}; then the mode line element displays nothing if
the value of @var{symbol} is @code{nil}.
@item (@var{width} @var{rest}@dots{})
A list whose first element is an integer specifies truncation or
padding of the results of @var{rest}. The remaining elements
@var{rest} are processed recursively as mode line constructs and
concatenated together. Then the result is space filled (if
@var{width} is positive) or truncated (to @minus{}@var{width} columns,
if @var{width} is negative) on the right.
For example, the usual way to show what percentage of a buffer is above
the top of the window is to use a list like this: @code{(-3 "%p")}.
@end table
If you do alter @code{mode-line-format} itself, the new value should
use the same variables that appear in the default value (@pxref{Mode
Line Variables}), rather than duplicating their contents or displaying
the information in another fashion. This way, customizations made by
the user or by Lisp programs (such as @code{display-time} and major
modes) via changes to those variables remain effective.
@cindex Shell mode @code{mode-line-format}
Here is an example of a @code{mode-line-format} that might be
useful for @code{shell-mode}, since it contains the host name and default
directory.
@example
@group
(setq mode-line-format
(list "-"
'mode-line-mule-info
'mode-line-modified
'mode-line-frame-identification
"%b--"
@end group
@group
;; @r{Note that this is evaluated while making the list.}
;; @r{It makes a mode line construct which is just a string.}
(getenv "HOST")
@end group
":"
'default-directory
" "
'global-mode-string
" %[("
'(:eval (mode-line-mode-name))
'mode-line-process
'minor-mode-alist
"%n"
")%]--"
@group
'(which-func-mode ("" which-func-format "--"))
'(line-number-mode "L%l--")
'(column-number-mode "C%c--")
'(-3 . "%p")
"-%-"))
@end group
@end example
@noindent
(The variables @code{line-number-mode}, @code{column-number-mode}
and @code{which-func-mode} enable particular minor modes; as usual,
these variable names are also the minor mode command names.)
@node Mode Line Variables
@subsection Variables Used in the Mode Line
This section describes variables incorporated by the
standard value of @code{mode-line-format} into the text of the mode
line. There is nothing inherently special about these variables; any
other variables could have the same effects on the mode line if
@code{mode-line-format} were changed to use them.
@defvar mode-line-mule-info
This variable holds the value of the mode-line construct that displays
information about the language environment, buffer coding system, and
current input method. @xref{Non-ASCII Characters}.
@end defvar
@defvar mode-line-modified
This variable holds the value of the mode-line construct that displays
whether the current buffer is modified.
The default value of @code{mode-line-modified} is @code{("%1*%1+")}.
This means that the mode line displays @samp{**} if the buffer is
modified, @samp{--} if the buffer is not modified, @samp{%%} if the
buffer is read only, and @samp{%*} if the buffer is read only and
modified.
Changing this variable does not force an update of the mode line.
@end defvar
@defvar mode-line-frame-identification
This variable identifies the current frame. The default value is
@code{" "} if you are using a window system which can show multiple
frames, or @code{"-%F "} on an ordinary terminal which shows only one
frame at a time.
@end defvar
@defvar mode-line-buffer-identification
This variable identifies the buffer being displayed in the window. Its
default value is @code{("%12b")}, which displays the buffer name, padded
with spaces to at least 12 columns.
@end defvar
@defvar global-mode-string
This variable holds a mode line spec that appears in the mode line by
default, just after the buffer name. The command @code{display-time}
sets @code{global-mode-string} to refer to the variable
@code{display-time-string}, which holds a string containing the time and
load information.
The @samp{%M} construct substitutes the value of
@code{global-mode-string}, but that is obsolete, since the variable is
included in the mode line from @code{mode-line-format}.
@end defvar
@defvar mode-name
This buffer-local variable holds the ``pretty'' name of the current
buffer's major mode. Each major mode should set this variable so that the
mode name will appear in the mode line.
@end defvar
@defvar minor-mode-alist
This variable holds an association list whose elements specify how the
mode line should indicate that a minor mode is active. Each element of
the @code{minor-mode-alist} should be a two-element list:
@example
(@var{minor-mode-variable} @var{mode-line-string})
@end example
More generally, @var{mode-line-string} can be any mode line spec. It
appears in the mode line when the value of @var{minor-mode-variable} is
non-@code{nil}, and not otherwise. These strings should begin with
spaces so that they don't run together. Conventionally, the
@var{minor-mode-variable} for a specific mode is set to a non-@code{nil}
value when that minor mode is activated.
The default value of @code{minor-mode-alist} is:
@example
@group
minor-mode-alist
@result{} ((vc-mode vc-mode)
(abbrev-mode " Abbrev")
(overwrite-mode overwrite-mode)
(auto-fill-function " Fill")
(defining-kbd-macro " Def")
(isearch-mode isearch-mode))
@end group
@end example
@code{minor-mode-alist} itself is not buffer-local. Each variable
mentioned in the alist should be buffer-local if its minor mode can be
enabled separately in each buffer.
@end defvar
@defvar mode-line-process
This buffer-local variable contains the mode line information on process
status in modes used for communicating with subprocesses. It is
displayed immediately following the major mode name, with no intervening
space. For example, its value in the @samp{*shell*} buffer is
@code{(":%s")}, which allows the shell to display its status along
with the major mode as: @samp{(Shell:run)}. Normally this variable
is @code{nil}.
@end defvar
Some variables are used by @code{minor-mode-alist} to display
a string for various minor modes when enabled. This is a typical
example:
@defvar vc-mode
The variable @code{vc-mode}, buffer-local in each buffer, records
whether the buffer's visited file is maintained with version control,
and, if so, which kind. Its value is a string that appears in the mode
line, or @code{nil} for no version control.
@end defvar
The variable @code{default-mode-line-format} is where
@code{mode-line-format} usually gets its value:
@defvar default-mode-line-format
This variable holds the default @code{mode-line-format} for buffers
that do not override it. This is the same as @code{(default-value
'mode-line-format)}.
The default value of @code{default-mode-line-format} is this list:
@example
@group
("-"
mode-line-mule-info
mode-line-modified
mode-line-frame-identification
mode-line-buffer-identification
@end group
" "
global-mode-string
@group
" %[("
;; @r{@code{mode-line-mode-name} is a function}
;; @r{that copies the mode name and adds text}
;; @r{properties to make it mouse-sensitive.}
(:eval (mode-line-mode-name))
mode-line-process
minor-mode-alist
"%n"
")%]--"
@end group
@group
(which-func-mode ("" which-func-format "--"))
(line-number-mode "L%l--")
(column-number-mode "C%c--")
(-3 . "%p")
"-%-")
@end group
@end example
@end defvar
@node %-Constructs
@subsection @code{%}-Constructs in the Mode Line
The following table lists the recognized @code{%}-constructs and what
they mean. In any construct except @samp{%%}, you can add a decimal
integer after the @samp{%} to specify how many characters to display.
@table @code
@item %b
The current buffer name, obtained with the @code{buffer-name} function.
@xref{Buffer Names}.
@item %c
The current column number of point.
@item %f
The visited file name, obtained with the @code{buffer-file-name}
function. @xref{Buffer File Name}.
@item %F
The title (only on a window system) or the name of the selected frame.
@xref{Window Frame Parameters}.
@item %l
The current line number of point, counting within the accessible portion
of the buffer.
@item %n
@samp{Narrow} when narrowing is in effect; nothing otherwise (see
@code{narrow-to-region} in @ref{Narrowing}).
@item %p
The percentage of the buffer text above the @strong{top} of window, or
@samp{Top}, @samp{Bottom} or @samp{All}. Note that the default
mode-line specification truncates this to three characters.
@item %P
The percentage of the buffer text that is above the @strong{bottom} of
the window (which includes the text visible in the window, as well as
the text above the top), plus @samp{Top} if the top of the buffer is
visible on screen; or @samp{Bottom} or @samp{All}.
@item %s
The status of the subprocess belonging to the current buffer, obtained with
@code{process-status}. @xref{Process Information}.
@item %t
Whether the visited file is a text file or a binary file. This is a
meaningful distinction only on certain operating systems (@pxref{MS-DOS
File Types}).
@item %*
@samp{%} if the buffer is read only (see @code{buffer-read-only}); @*
@samp{*} if the buffer is modified (see @code{buffer-modified-p}); @*
@samp{-} otherwise. @xref{Buffer Modification}.
@item %+
@samp{*} if the buffer is modified (see @code{buffer-modified-p}); @*
@samp{%} if the buffer is read only (see @code{buffer-read-only}); @*
@samp{-} otherwise. This differs from @samp{%*} only for a modified
read-only buffer. @xref{Buffer Modification}.
@item %&
@samp{*} if the buffer is modified, and @samp{-} otherwise.
@item %[
An indication of the depth of recursive editing levels (not counting
minibuffer levels): one @samp{[} for each editing level.
@xref{Recursive Editing}.
@item %]
One @samp{]} for each recursive editing level (not counting minibuffer
levels).
@item %-
Dashes sufficient to fill the remainder of the mode line.
@item %%
The character @samp{%}---this is how to include a literal @samp{%} in a
string in which @code{%}-constructs are allowed.
@end table
The following two @code{%}-constructs are still supported, but they are
obsolete, since you can get the same results with the variables
@code{mode-name} and @code{global-mode-string}.
@table @code
@item %m
The value of @code{mode-name}.
@item %M
The value of @code{global-mode-string}. Currently, only
@code{display-time} modifies the value of @code{global-mode-string}.
@end table
@node Properties in Mode
@subsection Properties in the Mode Line
Starting in Emacs 21, certain text properties are meaningful in the
mode line. The @code{face} property affects the appearance of text; the
@code{help-echo} property associate help strings with the text, and
@code{local-map} can make the text mouse-sensitive.
There are three ways to specify text properties for text in the mode
line:
@enumerate
@item
Put a string with the @code{local-map} property directly into the
mode-line data structure.
@item
Put a @code{local-map} property on a mode-line %-construct
such as @samp{%12b}; then the expansion of the %-construct
will have that same text property.
@item
Use a list containing @code{:eval @var{form}} in the mode-line data
structure, and make @var{form} evaluate to a string that has a
@code{local-map} property.
@end enumerate
You use the @code{local-map} property to specify a keymap. Like any
keymap, it can bind character keys and function keys; but that has no
effect, since it is impossible to move point into the mode line. This
keymap can only take real effect for mouse clicks.
@node Header Lines
@subsection Window Header Lines
@cindex header line (of a window)
@cindex window header line
Starting in Emacs 21, a window can have a @dfn{header line} at the
top, just as it can have a mode line at the bottom. The header line
feature works just like the mode line feature, except that it's
controlled by different variables.
@tindex header-line-format
@defvar header-line-format
This variable, local in every buffer, specifies how to display the
header line, for windows displaying the buffer. The format of the value
is the same as for @code{mode-line-format} (@pxref{Mode Line Data}).
@end defvar
@tindex default-header-line-format
@defvar default-header-line-format
This variable holds the default @code{header-line-format} for buffers
that do not override it. This is the same as @code{(default-value
'header-line-format)}.
It is normally @code{nil}, so that ordinary buffers have no header line.
@end defvar
@node Imenu
@section Imenu
@cindex Imenu
@dfn{Imenu} is a feature that lets users select a definition or
section in the buffer, from a menu which lists all of them, to go
directly to that location in the buffer. Imenu works by constructing a
buffer index which lists the names and buffer positions of the
definitions, or other named portions of the buffer; then the user can
choose one of them and move point to it. This section explains how to
customize how Imenu finds the definitions or buffer portions for a
particular major mode.
The usual and simplest way is to set the variable
@code{imenu-generic-expression}:
@defvar imenu-generic-expression
This variable, if non-@code{nil}, specifies regular expressions for
finding definitions for Imenu. In the simplest case, elements should
look like this:
@example
(@var{menu-title} @var{regexp} @var{subexp})
@end example
Here, if @var{menu-title} is non-@code{nil}, it says that the matches
for this element should go in a submenu of the buffer index;
@var{menu-title} itself specifies the name for the submenu. If
@var{menu-title} is @code{nil}, the matches for this element go directly
in the top level of the buffer index.
The second item in the list, @var{regexp}, is a regular expression
(@pxref{Regular Expressions}); anything in the buffer that it matches is
considered a definition, something to mention in the buffer index. The
third item, @var{subexp}, indicates which subexpression in @var{regexp}
matches the definition's name.
An element can also look like this:
@example
(@var{menu-title} @var{regexp} @var{index} @var{function} @var{arguments}@dots{})
@end example
Each match for this element creates a special index item which, if
selected by the user, calls @var{function} with arguments consisting of
the item name, the buffer position, and @var{arguments}.
For Emacs Lisp mode, @var{pattern} could look like this:
@c should probably use imenu-syntax-alist and \\sw rather than [-A-Za-z0-9+]
@example
@group
((nil "^\\s-*(def\\(un\\|subst\\|macro\\|advice\\)\
\\s-+\\([-A-Za-z0-9+]+\\)" 2)
@end group
@group
("*Vars*" "^\\s-*(def\\(var\\|const\\)\
\\s-+\\([-A-Za-z0-9+]+\\)" 2)
@end group
@group
("*Types*"
"^\\s-*\
(def\\(type\\|struct\\|class\\|ine-condition\\)\
\\s-+\\([-A-Za-z0-9+]+\\)" 2))
@end group
@end example
Setting this variable makes it buffer-local in the current buffer.
@end defvar
@defvar imenu-case-fold-search
This variable controls whether matching against
@var{imenu-generic-expression} is case-sensitive: @code{t}, the default,
means matching should ignore case.
Setting this variable makes it buffer-local in the current buffer.
@end defvar
@defvar imenu-syntax-alist
This variable is an alist of syntax table modifiers to use while
processing @code{imenu-generic-expression}, to override the syntax table
of the current buffer. Each element should have this form:
@example
(@var{characters} . @var{syntax-description})
@end example
The @sc{car}, @var{characters}, can be either a character or a string.
The element says to give that character or characters the syntax
specified by @var{syntax-description}, which is passed to
@code{modify-syntax-entry} (@pxref{Syntax Table Functions}).
This feature is typically used to give word syntax to characters which
normally have symbol syntax, and thus to simplify
@code{imenu-generic-expression} and speed up matching.
For example, Fortran mode uses it this way:
@example
(setq imenu-syntax-alist '(("_$" . "w")))
@end example
The @code{imenu-generic-expression} patterns can then use @samp{\\sw+}
instead of @samp{\\(\\sw\\|\\s_\\)+}. Note that this technique may be
inconvenient when the mode needs to limit the initial character
of a name to a smaller set of characters than are allowed in the rest
of a name.
Setting this variable makes it buffer-local in the current buffer.
@end defvar
Another way to customize Imenu for a major mode is to set the
variables @code{imenu-prev-index-position-function} and
@code{imenu-extract-index-name-function}:
@defvar imenu-prev-index-position-function
If this variable is non-@code{nil}, its value should be a function that
finds the next ``definition'' to put in the buffer index, scanning
backward in the buffer from point. It should return @code{nil} if it
doesn't find another ``definition'' before point. Otherwise it shuould
leave point at the place it finds a ``definition,'' and return any
non-@code{nil} value.
Setting this variable makes it buffer-local in the current buffer.
@end defvar
@defvar imenu-extract-index-name-function
If this variable is non-@code{nil}, its value should be a function to
return the name for a definition, assuming point is in that definition
as the @code{imenu-prev-index-position-function} function would leave
it.
Setting this variable makes it buffer-local in the current buffer.
@end defvar
The last way to customize Imenu for a major mode is to set the
variable @code{imenu-create-index-function}:
@defvar imenu-create-index-function
This variable specifies the function to use for creating a buffer index.
The function should take no arguments, and return an index for the
current buffer. It is called within @code{save-excursion}, so where it
leaves point makes no difference.
The default value is a function that uses
@code{imenu-generic-expression} to produce the index alist. If you
specify a different function, then @code{imenu-generic-expression} is
not used.
Setting this variable makes it buffer-local in the current buffer.
@end defvar
@defvar imenu-index-alist
This variable holds the index alist for the current buffer.
Setting it makes it buffer-local in the current buffer.
Simple elements in the alist look like @code{(@var{index-name}
. @var{index-position})}. Selecting a simple element has the effect of
moving to position @var{index-position} in the buffer.
Special elements look like @code{(@var{index-name} @var{position}
@var{function} @var{arguments}@dots{})}. Selecting a special element
performs
@example
(funcall @var{function} @var{index-name} @var{position} @var{arguments}@dots{})
@end example
A nested sub-alist element looks like @code{(@var{index-name}
@var{sub-alist})}.
@end defvar
@node Font Lock Mode
@section Font Lock Mode
@cindex Font Lock Mode
@dfn{Font Lock mode} is a feature that automatically attaches
@code{face} properties to certain parts of the buffer based on their
syntactic role. How it parses the buffer depends on the major mode;
most major modes define syntactic criteria for which faces to use in
which contexts. This section explains how to customize Font Lock for a
particular major mode.
Font Lock mode finds text to highlight in two ways: through syntactic
parsing based on the syntax table, and through searching (usually for
regular expressions). Syntactic fontification happens first; it finds
comments and string constants, and highlights them using
@code{font-lock-comment-face} and @code{font-lock-string-face}
(@pxref{Faces for Font Lock}). Search-based fontification follows.
@menu
* Font Lock Basics::
* Search-based Fontification::
* Other Font Lock Variables::
* Levels of Font Lock::
* Faces for Font Lock::
* Syntactic Font Lock::
@end menu
@node Font Lock Basics
@subsection Font Lock Basics
There are several variables that control how Font Lock mode highlights
text. But major modes should not set any of these variables directly.
Instead, they should set @code{font-lock-defaults} as a buffer-local
variable. The value assigned to this variable is used, if and when Font
Lock mode is enabled, to set all the other variables.
@defvar font-lock-defaults
This variable is set by major modes, as a buffer-local variable, to
specify how to fontify text in that mode. The value should look like
this:
@example
(@var{keywords} @var{keywords-only} @var{case-fold}
@var{syntax-alist} @var{syntax-begin} @var{other-vars}@dots{})
@end example
The first element, @var{keywords}, indirectly specifies the value of
@code{font-lock-keywords}. It can be a symbol, a variable whose value
is the list to use for @code{font-lock-keywords}. It can also be a list of
several such symbols, one for each possible level of fontification. The
first symbol specifies how to do level 1 fontification, the second
symbol how to do level 2, and so on.
The second element, @var{keywords-only}, specifies the value of the
variable @code{font-lock-keywords-only}. If this is non-@code{nil},
syntactic fontification (of strings and comments) is not performed.
The third element, @var{case-fold}, specifies the value of
@code{font-lock-case-fold-search}. If it is non-@code{nil}, Font Lock
mode ignores case when searching as directed by
@code{font-lock-keywords}.
If the fourth element, @var{syntax-alist}, is non-@code{nil}, it should be
a list of cons cells of the form @code{(@var{char-or-string}
. @var{string})}. These are used to set up a syntax table for
fontification (@pxref{Syntax Table Functions}). The resulting syntax
table is stored in @code{font-lock-syntax-table}.
The fifth element, @var{syntax-begin}, specifies the value of
@code{font-lock-beginning-of-syntax-function} (see below).
All the remaining elements (if any) are collectively called
@var{other-vars}. Each of these elements should have the form
@code{(@var{variable} . @var{value})}---which means, make @var{variable}
buffer-local and then set it to @var{value}. You can use these
@var{other-vars} to set other variables that affect fontification,
aside from those you can control with the first five elements.
@end defvar
@node Search-based Fontification
@subsection Search-based Fontification
The most important variable for customizing Font Lock mode is
@code{font-lock-keywords}. It specifies the search criteria for
search-based fontification.
@defvar font-lock-keywords
This variable's value is a list of the keywords to highlight. Be
careful when composing regular expressions for this list; a poorly
written pattern can dramatically slow things down!
@end defvar
Each element of @code{font-lock-keywords} specifies how to find
certain cases of text, and how to highlight those cases. Font Lock mode
processes the elements of @code{font-lock-keywords} one by one, and for
each element, it finds and handles all matches. Ordinarily, once
part of the text has been fontified already, this cannot be overridden
by a subsequent match in the same text; but you can specify different
behavior using the @var{override} element of a @var{highlighter}.
Each element of @code{font-lock-keywords} should have one of these
forms:
@table @code
@item @var{regexp}
Highlight all matches for @var{regexp} using
@code{font-lock-keyword-face}. For example,
@example
;; @r{Highlight discrete occurrences of @samp{foo}}
;; @r{using @code{font-lock-keyword-face}.}
"\\<foo\\>"
@end example
The function @code{regexp-opt} (@pxref{Syntax of Regexps}) is useful for
calculating optimal regular expressions to match a number of different
keywords.
@item @var{function}
Find text by calling @var{function}, and highlight the matches
it finds using @code{font-lock-keyword-face}.
When @var{function} is called, it receives one argument, the limit of
the search. It should return non-@code{nil} if it succeeds, and set the
match data to describe the match that was found.
@item (@var{matcher} . @var{match})
In this kind of element, @var{matcher} is either a regular
expression or a function, as described above. The @sc{cdr},
@var{match}, specifies which subexpression of @var{matcher} should be
highlighted (instead of the entire text that @var{matcher} matched).
@example
;; @r{Highlight the @samp{bar} in each occurrence of @samp{fubar},}
;; @r{using @code{font-lock-keyword-face}.}
("fu\\(bar\\)" . 1)
@end example
If you use @code{regexp-opt} to produce the regular expression
@var{matcher}, then you can use @code{regexp-opt-depth} (@pxref{Syntax
of Regexps}) to calculate the value for @var{match}.
@item (@var{matcher} . @var{facename})
In this kind of element, @var{facename} is an expression whose value
specifies the face name to use for highlighting.
@example
;; @r{Highlight occurrences of @samp{fubar},}
;; @r{using the face which is the value of @code{fubar-face}.}
("fubar" . fubar-face)
@end example
@item (@var{matcher} . @var{highlighter})
In this kind of element, @var{highlighter} is a list
which specifies how to highlight matches found by @var{matcher}.
It has the form
@example
(@var{subexp} @var{facename} @var{override} @var{laxmatch})
@end example
The @sc{car}, @var{subexp}, is an integer specifying which subexpression
of the match to fontify (0 means the entire matching text). The second
subelement, @var{facename}, specifies the face, as described above.
The last two values in @var{highlighter}, @var{override} and
@var{laxmatch}, are flags. If @var{override} is @code{t}, this element
can override existing fontification made by previous elements of
@code{font-lock-keywords}. If it is @code{keep}, then each character is
fontified if it has not been fontified already by some other element.
If it is @code{prepend}, the face @var{facename} is added to the
beginning of the @code{face} property. If it is @code{append}, the face
@var{facename} is added to the end of the @code{face} property.
If @var{laxmatch} is non-@code{nil}, it means there should be no error
if there is no subexpression numbered @var{subexp} in @var{matcher}.
Obviously, fontification of the subexpression numbered @var{subexp} will
not occur. However, fontification of other subexpressions (and other
regexps) will continue. If @var{laxmatch} is @code{nil}, and the
specified subexpression is missing, then an error is signalled which
terminates search-based fontification.
Here are some examples of elements of this kind, and what they do:
@smallexample
;; @r{Highlight occurrences of either @samp{foo} or @samp{bar},}
;; @r{using @code{foo-bar-face}, even if they have already been highlighted.}
;; @r{@code{foo-bar-face} should be a variable whose value is a face.}
("foo\\|bar" 0 foo-bar-face t)
;; @r{Highlight the first subexpression within each occurrence}
;; @r{that the function @code{fubar-match} finds,}
;; @r{using the face which is the value of @code{fubar-face}.}
(fubar-match 1 fubar-face)
@end smallexample
@item (@var{matcher} @var{highlighters}@dots{})
This sort of element specifies several @var{highlighter} lists for a
single @var{matcher}. In order for this to be useful, each
@var{highlighter} should have a different value of @var{subexp}; that is,
each one should apply to a different subexpression of @var{matcher}.
@ignore
@item (@var{matcher} . @var{anchored})
In this kind of element, @var{anchored} acts much like a
@var{highlighter}, but it is more complex and can specify multiple
successive searches.
For highlighting single items, typically only @var{highlighter} is
required. However, if an item or (typically) items are to be
highlighted following the instance of another item (the anchor) then
@var{anchored} may be required.
It has this format:
@example
(@var{submatcher} @var{pre-match-form} @var{post-match-form} @var{highlighters}@dots{})
@end example
@c I can't parse this text -- rms
where @var{submatcher} is much like @var{matcher}, with one
exception---see below. @var{pre-match-form} and @var{post-match-form}
are evaluated before the first, and after the last, instance
@var{anchored}'s @var{submatcher} is used. Therefore they can be used
to initialize before, and cleanup after, @var{submatcher} is used.
Typically, @var{pre-match-form} is used to move to some position
relative to the original @var{submatcher}, before starting with
@var{anchored}'s @var{submatcher}. @var{post-match-form} might be used
to move, before resuming with @var{anchored}'s parent's @var{matcher}.
For example, an element of the form highlights (if not already highlighted):
@example
("\\<anchor\\>" (0 anchor-face) ("\\<item\\>" nil nil (0 item-face)))
@end example
Discrete occurrences of @samp{anchor} in the value of
@code{anchor-face}, and subsequent discrete occurrences of @samp{item}
(on the same line) in the value of @code{item-face}. (Here
@var{pre-match-form} and @var{post-match-form} are @code{nil}.
Therefore @samp{item} is initially searched for starting from the end of
the match of @samp{anchor}, and searching for subsequent instance of
@samp{anchor} resumes from where searching for @samp{item} concluded.)
The above-mentioned exception is as follows. The limit of the
@var{submatcher} search defaults to the end of the line after
@var{pre-match-form} is evaluated. However, if @var{pre-match-form}
returns a position greater than the position after @var{pre-match-form}
is evaluated, that position is used as the limit of the search. It is
generally a bad idea to return a position greater than the end of the
line; in other words, the @var{submatcher} search should not span lines.
@item (@var{matcher} @var{highlighters-or-anchoreds} ...)
@end ignore
@item (eval . @var{form})
Here @var{form} is an expression to be evaluated the first time
this value of @code{font-lock-keywords} is used in a buffer.
Its value should have one of the forms described in this table.
@end table
@strong{Warning:} Do not design an element of @code{font-lock-keywords}
to match text which spans lines; this does not work reliably. While
@code{font-lock-fontify-buffer} handles multi-line patterns correctly,
updating when you edit the buffer does not, since it considers text one
line at a time.
@node Other Font Lock Variables
@subsection Other Font Lock Variables
This section describes additional variables that a major mode
can set by means of @code{font-lock-defaults}.
@defvar font-lock-keywords-only
Non-@code{nil} means Font Lock should not fontify comments or strings
syntactically; it should only fontify based on
@code{font-lock-keywords}.
@end defvar
@ignore
Other variables include those for buffer-specialized fontification functions,
`font-lock-fontify-buffer-function', `font-lock-unfontify-buffer-function',
`font-lock-fontify-region-function', `font-lock-unfontify-region-function',
`font-lock-inhibit-thing-lock' and `font-lock-maximum-size'.
@end ignore
@defvar font-lock-keywords-case-fold-search
Non-@code{nil} means that regular expression matching for the sake of
@code{font-lock-keywords} should be case-insensitive.
@end defvar
@defvar font-lock-syntax-table
This variable specifies the syntax table to use for fontification of
comments and strings.
@end defvar
@defvar font-lock-beginning-of-syntax-function
If this variable is non-@code{nil}, it should be a function to move
point back to a position that is syntactically at ``top level'' and
outside of strings or comments. Font Lock uses this when necessary
to get the right results for syntactic fontification.
This function is called with no arguments. It should leave point at the
beginning of any enclosing syntactic block. Typical values are
@code{beginning-of-line} (i.e., the start of the line is known to be
outside a syntactic block), or @code{beginning-of-defun} for programming
modes or @code{backward-paragraph} for textual modes (i.e., the
mode-dependent function is known to move outside a syntactic block).
If the value is @code{nil}, the beginning of the buffer is used as a
position outside of a syntactic block. This cannot be wrong, but it can
be slow.
@end defvar
@defvar font-lock-mark-block-function
If this variable is non-@code{nil}, it should be a function that is
called with no arguments, to choose an enclosing range of text for
refontification for the command @kbd{M-g M-g}
(@code{font-lock-fontify-block}).
The function should report its choice by placing the region around it.
A good choice is a range of text large enough to give proper results,
but not too large so that refontification becomes slow. Typical values
are @code{mark-defun} for programming modes or @code{mark-paragraph} for
textual modes.
@end defvar
@node Levels of Font Lock
@subsection Levels of Font Lock
Many major modes offer three different levels of fontification. You
can define multiple levels by using a list of symbols for @var{keywords}
in @code{font-lock-defaults}. Each symbol specifies one level of
fontification; it is up to the user to choose one of these levels. The
chosen level's symbol value is used to initialize
@code{font-lock-keywords}.
Here are the conventions for how to define the levels of
fontification:
@itemize @bullet
@item
Level 1: highlight function declarations, file directives (such as include or
import directives), strings and comments. The idea is speed, so only
the most important and top-level components are fontified.
@item
Level 2: in addition to level 1, highlight all language keywords,
including type names that act like keywords, as well as named constant
values. The idea is that all keywords (either syntactic or semantic)
should be fontified appropriately.
@item
Level 3: in addition to level 2, highlight the symbols being defined in
function and variable declarations, and all builtin function names,
wherever they appear.
@end itemize
@node Faces for Font Lock
@subsection Faces for Font Lock
You can make Font Lock mode use any face, but several faces are
defined specifically for Font Lock mode. Each of these symbols is both
a face name, and a variable whose default value is the symbol itself.
Thus, the default value of @code{font-lock-comment-face} is
@code{font-lock-comment-face}. This means you can write
@code{font-lock-comment-face} in a context such as
@code{font-lock-keywords} where a face-name-valued expression is used.
@table @code
@item font-lock-comment-face
@vindex font-lock-comment-face
Used (typically) for comments.
@item font-lock-string-face
@vindex font-lock-string-face
Used (typically) for string constants.
@item font-lock-keyword-face
@vindex font-lock-keyword-face
Used (typically) for keywords---names that have special syntactic
significance, like @code{for} and @code{if} in C.
@item font-lock-builtin-face
@vindex font-lock-builtin-face
Used (typically) for built-in function names.
@item font-lock-function-name-face
@vindex font-lock-function-name-face
Used (typically) for the name of a function being defined or declared,
in a function definition or declaration.
@item font-lock-variable-name-face
@vindex font-lock-variable-name-face
Used (typically) for the name of a variable being defined or declared,
in a variable definition or declaration.
@item font-lock-type-face
@vindex font-lock-type-face
Used (typically) for names of user-defined data types,
where they are defined and where they are used.
@item font-lock-constant-face
@vindex font-lock-constant-face
Used (typically) for constant names.
@item font-lock-warning-face
@vindex font-lock-warning-face
Used (typically) for constructs that are peculiar, or that greatly
change the meaning of other text. For example, this is used for
@samp{;;;###autoload} cookies in Emacs Lisp, and for @code{#error}
directives in C.
@end table
@node Syntactic Font Lock
@subsection Syntactic Font Lock
Font Lock mode can be used to update @code{syntax-table} properties
automatically. This is useful in languages for which a single syntax
table by itself is not sufficient.
@defvar font-lock-syntactic-keywords
This variable enables and controls syntactic Font Lock. Its value
should be a list of elements of this form:
@example
(@var{matcher} @var{subexp} @var{syntax} @var{override} @var{laxmatch})
@end example
The parts of this element have the same meanings as in the corresponding
sort of element of @code{font-lock-keywords},
@example
(@var{matcher} @var{subexp} @var{facename} @var{override} @var{laxmatch})
@end example
However, instead of specifying the value @var{facename} to use for the
@code{face} property, it specifies the value @var{syntax} to use for the
@code{syntax-table} property. Here, @var{syntax} can be a variable
whose value is a syntax table, a syntax entry of the form
@code{(@var{syntax-code} . @var{matching-char})}, or an expression whose
value is one of those two types.
@end defvar
@node Hooks
@section Hooks
@cindex hooks
A @dfn{hook} is a variable where you can store a function or functions
to be called on a particular occasion by an existing program. Emacs
provides hooks for the sake of customization. Most often, hooks are set
up in the init file (@pxref{Init File}), but Lisp programs can set them also.
@xref{Standard Hooks}, for a list of standard hook variables.
@cindex normal hook
Most of the hooks in Emacs are @dfn{normal hooks}. These variables
contain lists of functions to be called with no arguments. When the
hook name ends in @samp{-hook}, that tells you it is normal. We try to
make all hooks normal, as much as possible, so that you can use them in
a uniform way.
Every major mode function is supposed to run a normal hook called the
@dfn{mode hook} as the last step of initialization. This makes it easy
for a user to customize the behavior of the mode, by overriding the
buffer-local variable assignments already made by the mode. But hooks
are used in other contexts too. For example, the hook
@code{suspend-hook} runs just before Emacs suspends itself
(@pxref{Suspending Emacs}).
The recommended way to add a hook function to a normal hook is by
calling @code{add-hook} (see below). The hook functions may be any of
the valid kinds of functions that @code{funcall} accepts (@pxref{What Is
a Function}). Most normal hook variables are initially void;
@code{add-hook} knows how to deal with this.
@cindex abnormal hook
If the hook variable's name does not end with @samp{-hook}, that
indicates it is probably an @dfn{abnormal hook}. Then you should look at its
documentation to see how to use the hook properly.
If the variable's name ends in @samp{-functions} or @samp{-hooks},
then the value is a list of functions, but it is abnormal in that either
these functions are called with arguments or their values are used in
some way. You can use @code{add-hook} to add a function to the list,
but you must take care in writing the function. (A few of these
variables are actually normal hooks which were named before we
established the convention of using @samp{-hook} for them.)
If the variable's name ends in @samp{-function}, then its value
is just a single function, not a list of functions.
Here's an example that uses a mode hook to turn on Auto Fill mode when
in Lisp Interaction mode:
@example
(add-hook 'lisp-interaction-mode-hook 'turn-on-auto-fill)
@end example
At the appropriate time, Emacs uses the @code{run-hooks} function to
run particular hooks. This function calls the hook functions that have
been added with @code{add-hook}.
@defun run-hooks &rest hookvars
This function takes one or more hook variable names as arguments, and
runs each hook in turn. Each argument should be a symbol that is a hook
variable. These arguments are processed in the order specified.
If a hook variable has a non-@code{nil} value, that value may be a
function or a list of functions. If the value is a function (either a
lambda expression or a symbol with a function definition), it is called.
If it is a list, the elements are called, in order. The hook functions
are called with no arguments. Nowadays, storing a single function in
the hook variable is semi-obsolete; you should always use a list of
functions.
For example, here's how @code{emacs-lisp-mode} runs its mode hook:
@example
(run-hooks 'emacs-lisp-mode-hook)
@end example
@end defun
@defun run-hook-with-args hook &rest args
This function is the way to run an abnormal hook which passes arguments
to the hook functions. It calls each of the hook functions, passing
each of them the arguments @var{args}.
@end defun
@defun run-hook-with-args-until-failure hook &rest args
This function is the way to run an abnormal hook which passes arguments
to the hook functions, and stops as soon as any hook function fails. It
calls each of the hook functions, passing each of them the arguments
@var{args}, until some hook function returns @code{nil}. Then it stops,
and returns @code{nil} if some hook function returned @code{nil}.
Otherwise it returns a non-@code{nil} value.
@end defun
@defun run-hook-with-args-until-success hook &rest args
This function is the way to run an abnormal hook which passes arguments
to the hook functions, and stops as soon as any hook function succeeds.
It calls each of the hook functions, passing each of them the arguments
@var{args}, until some hook function returns non-@code{nil}. Then it
stops, and returns whatever was returned by the last hook function
that was called.
@end defun
@defun add-hook hook function &optional append local
This function is the handy way to add function @var{function} to hook
variable @var{hook}. The argument @var{function} may be any valid Lisp
function with the proper number of arguments. For example,
@example
(add-hook 'text-mode-hook 'my-text-hook-function)
@end example
@noindent
adds @code{my-text-hook-function} to the hook called @code{text-mode-hook}.
You can use @code{add-hook} for abnormal hooks as well as for normal
hooks.
It is best to design your hook functions so that the order in which they
are executed does not matter. Any dependence on the order is ``asking
for trouble.'' However, the order is predictable: normally,
@var{function} goes at the front of the hook list, so it will be
executed first (barring another @code{add-hook} call). If the optional
argument @var{append} is non-@code{nil}, the new hook function goes at
the end of the hook list and will be executed last.
If @var{local} is non-@code{nil}, that says to make the new hook
function buffer-local in the current buffer and automatically calls
@code{make-local-hook} to make the hook itself buffer-local.
@end defun
@defun remove-hook hook function &optional local
This function removes @var{function} from the hook variable @var{hook}.
If @var{local} is non-@code{nil}, that says to remove @var{function}
from the buffer-local hook list instead of from the global hook list.
If the hook variable itself is not buffer-local, then the value of
@var{local} makes no difference.
@end defun
@defun make-local-hook hook
This function makes the hook variable @code{hook} buffer-local in the
current buffer. When a hook variable is buffer-local, it can have
buffer-local and global hook functions, and @code{run-hooks} runs all of
them.
This function works by adding @code{t} as an element of the buffer-local
value. That serves as a flag to use the hook functions listed in the default
value of the hook variable, as well as those listed in the buffer-local value.
Since @code{run-hooks} understands this flag, @code{make-local-hook}
works with all normal hooks. It works for only some non-normal
hooks---those whose callers have been updated to understand this meaning
of @code{t}.
Do not use @code{make-local-variable} directly for hook variables; it is
not sufficient.
@end defun
|