You can save the list of all explicitly installed packages to a file:
pacman -Qeq > pkglist.txt
You can also save the foreign packages with:
pacman -Qmq > pkgforeign.txt
Then you can install all repo packages from the list with:
sudo pacman -S --needed $(comm -12 <(pacman -Slq | sort) <(sort pkglist.txt))
This will make sure to exclude all foreign packages from pkglist.txt
You can then install the foreign packages manually, one by one. This is recommended, rather than doing it all together, as you might want to inspect each PKGBUILD file, and you will probably use yay
to install the packages from the AUR.
See also:
https://wiki.archlinux.org/index.php/Pacman/Tips_and_tricks