+ Moment result = *l - *e;
+ if (result < 0)
+ {
+ programming_error ("invalid measure position: "
+ + e->to_string () + " of " + l->to_string ());
+ return 0;
+ }
+ Moment const *unit = unsmob_moment (get_property ("completionUnit"));
+
+ if (unit)
+ {
+ Rational const now_unit = e->main_part_ / unit->main_part_;
+ if (now_unit.den () > 1)
+ {
+ /*
+ within a unit - go to the end of that
+ */
+ result = unit->main_part_
+ * (Rational (1) - (now_unit - now_unit.trunc_rat ()));
+ }
+ else
+ {
+ /*
+ at the beginning of a unit:
+ take a power-of-two number of units, but not more than required,
+ since then the Duration constructor destroys the unit structure
+ */
+ if (note_len < result.main_part_)
+ result.main_part_ = note_len;
+ Rational const step_unit = result.main_part_ / unit->main_part_;
+ if (step_unit.den () < step_unit.num ())
+ {
+ int const log2
+ = intlog2 (int (step_unit.num () / step_unit.den ()));
+ result.main_part_ = unit->main_part_ * Rational (1 << log2);
+ }
+ }
+ }
+
+ return result;