7.28 Extracting Goals to Separate Predicates

Sweep can help you extract a part of the body of a Prolog clause into a separate predicate, so you can reuse it in other places.

Command: sweeprolog-extract-region-to-predicate

Extract the goal between point and mark into a new predicate.

This command extracts the selected goal into a separate predicate. It prompts you for the name of the new predicate and inserts a definition for that predicate in the current buffer, while replacing the current region with a call to this new predicate. The body of the new predicate is the goal in the current region, and this command determines the arguments of the new predicate based on the variables that the goal to extract shares with the containing clause.

If the selected goal contains a cut whose scope would change as a result of being extracted from the current clause, sweeprolog-extract-region-to-predicate warns you about it and asks you to confirm before continuing.

If you call sweeprolog-extract-region-to-predicate when the region does not contain a valid Prolog term, this command complains and refuses to extract the invalid term.

By default, sweeprolog-extract-region-to-predicate is not bound directly to any key in Sweep Prolog mode; instead, you can invoke it by typing M-RET (sweeprolog-insert-term-dwim) when the region is active. See Context-Based Term Insertion.

If you invoke sweeprolog-extract-region-to-predicate with a prefix argument—either directly or via sweeprolog-insert-term-dwim by typing C-u M-RET with an active region—then after extracting the selected goal to a new predicate, this command searches the current buffer for other goals that the selected goal subsumes, and suggests replacing them with invocations of the newly defined predicate. See Query Replace Term.

With Context Menu mode enabled, you can also invoke this command by right-clicking on an active region and selecting ‘Extract to New Predicate’.