late 14c., "Latin grammar, rules of Latin," from Old French gramaire "grammar; learning," especially Latin and philology, also "(magic) incantation, spells, mumbo-jumbo" (12c., Modern French grammaire), an "irregular semi-popular adoption" [OED] of Latin grammatica "grammar, philology," perhaps via an unrecorded Medieval Latin form *grammaria. The classical Latin word is from Greek grammatike (tekhnē) "(art) of letters," referring both to philology and to literature in the broadest sense, fem. of grammatikos (adj.) "pertaining to or versed in letters or learning," from gramma "letter" (see -gram). An Old English gloss of it was stæfcræft (see staff (n.)).
A much broader word in Latin and Greek; restriction of the meaning to "systematic account of the rules and usages of language" is a post-classical development. Until 16c. limited to Latin; in reference to English usage by late 16c., thence "rules of a language to which speakers and writers must conform" (1580s). Meaning "a treatise on grammar" is from 1520s. For the "magic" sense, compare gramary. The sense evolution is characteristic of the Dark Ages: "learning in general, knowledge peculiar to the learned classes," which included astrology and magic; hence the secondary meaning of "occult knowledge" (late 15c. in English), which evolved in Scottish into glamour (q.v.).
A grammar-school (late 14c.) originally was a school for learning Latin, which was begun by memorizing the grammar. In U.S. (1842) the term was put to use in the graded system for a school between primary and secondary where English grammar is one of the subjects taught. The word is attested earlier in surnames (late 12c.) such as Robertus Gramaticus, Richard le Gramarie, whence the modern surname Grammer.